28 Commits

Author SHA1 Message Date
ca60733ea0 Merge pull request 'feat: configurable plans, MP payment notifications and onboarding language selector' (#15) from development into main
Reviewed-on: #15
2026-11-11 10:55:18 +00:00
Jose Selesan
aac142d324 feat(billing): configurable plans from the backoffice and MP payment notifications
Plans:
- Plan limits and Pro prices per country live in the database
  (plan_configs, plan_prices, seeded with the previous constants) and are
  read through PlanCatalog (30 s cache, defaults as fallback).
- /admin/plans edits limits (with the count of accounts that would become
  read-only) and prices, optionally pushing the new price to live
  subscriptions from their next charge (MP preapproval amount, Stripe item
  without proration) via the ApplyPriceChanges job, with an email and a
  notice on /billing.
- GET /billing/plans feeds the onboarding and the billing screen.

Mercado Pago:
- The Pro checkout returns through GET /billing/return on API_PUBLIC_URL,
  since MP refuses a back_url on localhost.
- The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the
  session, requires the session to own the state, and redirects instead of
  answering JSON on unexpected errors.
- Checkout Pro links skip auto_return off public HTTPS and carry a
  notification_url to POST /payments/webhooks/mp/:paymentId, which confirms
  the payment with the owner's token (same rule as the polling job, which
  stays as fallback). The search now prefers the approved attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:50:14 -03:00
Jose Selesan
abb18f1815 Language selector on onboarding screen
Fixed docker-compose
2026-11-10 18:27:15 -03:00
Jose Selesan
4211d5cf39 Merge remote-tracking branch 'origin/development' 2026-11-10 16:51:24 -03:00
Jose Selesan
8cb5fe9b08 fix(deploy): allow dev and prod stacks on the same Dokploy server
Stop publishing web on host port 8080, which clashed between stacks; Traefik
reaches port 80 of the container through dokploy-network. Local testing now
uses docker-compose.local.yml to publish the port.

Proxy nginx to a `gruperly-api` alias that only exists on the stack's own
network: the `api` service name is also registered on dokploy-network, so
with two stacks nginx could reach the other environment's API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:36:25 -03:00
Jose Selesan
f4a6f2653f Update gitignore 2026-11-10 09:49:10 -03:00
bd7712b28e Merge pull request 'development' (#14) from development into main
Reviewed-on: #14
2026-11-07 13:21:41 +00:00
Jose Selesan
2d80af082f feat(web): redesign onboarding and home after design critique
Onboarding:
- Keep the current step in ?step= so the device back gesture moves one
  step back; effectiveStep guards skipping the plan and re-opening the
  group form after the group exists. Show Back on mobile.
- Format prices with the chosen country's currency (form prefix and
  confirmation).
- Welcome describes the real flow and previews the WhatsApp payment
  reminder; the last step shares the group's invite link instead of
  listing settings chores.
- Accessibility: named stepper steps with aria-current, focus moves to
  the new step heading, alerts on errors, reduced-motion and
  direction-aware step animation, 48px primary actions.
- Group form split into "classes" and "billing", due day hidden for
  per-class billing; Stripe skips the empty Pro confirmation; Free
  features read "in Pro" instead of struck through.

Home:
- Payments section follows the plan: Free gets a locked preview with
  an upgrade link and is never asked to link Mercado Pago.
- Secondary text meets 4.5:1 contrast; accent-fg for links in dark.
- Class times use a 24h clock in Spanish and Portuguese.
- Drop the summary tiles; one hero for the current or next class, the
  rest of the day as compact rows; two columns on desktop.
- "Para atender" reads the shared ['attention'] query, so resolved
  alerts match "Requiere atención", with WhatsApp shortcuts and a link
  to the full list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:58:08 -03:00
Jose Selesan
70ef049f34 docs: require English commit messages in AGENTS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:27:16 -03:00
Jose Selesan
f0bb02ab73 chore: ignorar .DS_Store y los intermedios de archify
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:24:32 -03:00
Jose Selesan
925f1a256d docs: AGENTS.md con el estado final del multi idioma
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:07:42 -03:00
Jose Selesan
70702ba852 feat(i18n): traducir el backoffice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:07:03 -03:00
Jose Selesan
4d50b46399 feat(i18n): traducir la app de alumnos (con selector de idioma en Perfil)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:05:21 -03:00
Jose Selesan
486fbaf2ca feat(i18n): traducir el acceso de alumnos (links, passkey, recuperación)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:02:56 -03:00
Jose Selesan
b615c17a16 feat(i18n): traducir inscripción por link y aviso de ausencia público
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:02:02 -03:00
Jose Selesan
243530fab2 feat(i18n): traducir perfil y seguridad
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:00:14 -03:00
Jose Selesan
dfb6951d7c feat(i18n): traducir el onboarding (nombres de país desde Intl)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:59:41 -03:00
Jose Selesan
e2d9ddf569 feat(i18n): traducir WhatsApp
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:57:44 -03:00
Jose Selesan
700b9fb91d feat(i18n): traducir Mercado Pago
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:56:08 -03:00
Jose Selesan
e3dca305a4 feat(i18n): traducir el plan (billing)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:55:20 -03:00
Jose Selesan
7db9414f12 feat(i18n): traducir Cobros
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:53:40 -03:00
Jose Selesan
13723d5bb9 feat(i18n): traducir la toma de asistencia
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:30:52 -03:00
Jose Selesan
8a5768e0c0 feat(i18n): traducir la ficha del alumno
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:30:11 -03:00
Jose Selesan
ecdbbbbca6 feat(i18n): traducir Requiere atención y redactar las alertas en cada idioma
Las alertas de shared suman razon + valores para que la web las redacte;
etiqueta/detalle se mantienen en español para el backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:27:17 -03:00
Jose Selesan
96661fb807 feat(i18n): traducir Grupos (lista, ficha, alta de miembros y estadísticas)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:25:21 -03:00
Jose Selesan
09647672b8 feat(i18n): traducir Inicio
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:16:16 -03:00
Jose Selesan
cb872eb8bc feat: soporte multi idioma en la web (infraestructura)
i18next + react-i18next con es-AR (fuente), es-419, pt-BR y en; el idioma
sale del dispositivo (fallback a inglés) y se puede cambiar en Ajustes.
La elección se guarda en localStorage y, para el profe, en users.locale.
Las validaciones de shared pasan a claves y los errores de la API se
traducen por code (con params para límites de plan y cupo).
Migrados: layout, Ajustes, auth, PWA y lib/format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:14:59 -03:00
Jose Selesan
ff885bddfc docs: diagramas de arquitectura y de personas/membresías
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:33:59 -03:00
440 changed files with 45617 additions and 2522 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,448 @@
{
"schema_version": 1,
"diagram_type": "architecture",
"meta": {
"title": "Arquitectura de Gruperly",
"locale": "es",
"output": ".archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.2pidev.com/jselesan/gruperly.git",
"link_mode": "local-only",
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
},
"views": [
{
"id": "request",
"label": "Pedido del profe",
"focus": [
"teacher",
"web",
"nginx",
"guards",
"api",
"db"
],
"note": "Mismo dominio: nginx sirve el bundle y hace proxy de /api al contenedor api."
},
{
"id": "students",
"label": "App de alumnos",
"focus": [
"student",
"web",
"guards",
"storage"
],
"note": "Sin Better Auth: cookie y middleware propios; comprobantes en S3 privado."
},
{
"id": "integrations",
"label": "Integraciones",
"focus": [
"api",
"mp",
"stripe",
"whatsapp",
"smtp",
"storage"
],
"note": "Cada proveedor detrás de un puerto; sin credenciales responde 503 y el resto sigue andando."
}
]
},
"components": [
{
"id": "teacher",
"type": "external",
"label": "Profesor",
"sublabel": "navegador / PWA",
"icon": "person",
"pos": [
40,
60
],
"size": [
120,
60
],
"sources": [
{
"path": "apps/web/src/routes/_authenticated.tsx",
"line": 1
}
]
},
{
"id": "web",
"type": "frontend",
"label": "Web PWA",
"sublabel": "React 19 · Vite",
"pos": [
230,
56
],
"size": [
140,
68
],
"sources": [
{
"path": "apps/web/vite.config.ts",
"line": 12,
"label": "VitePWA"
}
]
},
{
"id": "student",
"type": "external",
"label": "Alumno / tutor",
"sublabel": "/i/:token · /student",
"icon": "person",
"pos": [
230,
240
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/web/src/routes/i.$token.tsx",
"line": 1
},
{
"path": "apps/web/src/routes/_student.tsx",
"line": 1
}
]
},
{
"id": "nginx",
"type": "cloud",
"label": "nginx",
"sublabel": "bundle + proxy /api",
"pos": [
450,
60
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/web/nginx.conf",
"line": 14,
"end_line": 26
},
{
"path": "docker-compose.yml",
"line": 1,
"end_line": 8
}
]
},
{
"id": "guards",
"type": "security",
"label": "Guards de sesión",
"sublabel": "Better Auth · alumno",
"pos": [
680,
56
],
"size": [
150,
68
],
"sources": [
{
"path": "apps/backend/src/http/session-auth.ts",
"line": 23,
"end_line": 48
},
{
"path": "apps/backend/src/modules/student-portal/middleware.ts",
"line": 50
}
]
},
{
"id": "api",
"type": "backend",
"label": "API Hono + jobs",
"sublabel": "Bun.serve :4000 · cron",
"pos": [
880,
56
],
"size": [
150,
68
],
"sources": [
{
"path": "apps/backend/src/server.ts",
"line": 14,
"end_line": 23
},
{
"path": "apps/backend/src/app.ts",
"line": 44,
"end_line": 73
}
]
},
{
"id": "db",
"type": "database",
"label": "PostgreSQL",
"sublabel": "Prisma 7 · adapter-pg",
"pos": [
1090,
60
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/backend/src/lib/prisma.ts",
"line": 14,
"end_line": 18
}
]
},
{
"id": "mp",
"type": "external",
"label": "Mercado Pago",
"sublabel": "OAuth · Checkout Pro",
"pos": [
610,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/modules/mp/lib/mp-oauth.ts",
"line": 3,
"end_line": 4
},
{
"path": "apps/backend/src/modules/mp/lib/mp-http.ts",
"line": 4
}
]
},
{
"id": "stripe",
"type": "external",
"label": "Stripe",
"sublabel": "Pro fuera de AR",
"pos": [
760,
320
],
"size": [
110,
60
],
"sources": [
{
"path": "apps/backend/src/modules/billing/providers/index.ts",
"line": 24,
"end_line": 31
}
]
},
{
"id": "whatsapp",
"type": "external",
"label": "WhatsApp",
"sublabel": "OpenWA / Kapso",
"pos": [
890,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/modules/whatsapp/providers/index.ts",
"line": 26,
"end_line": 40
}
]
},
{
"id": "smtp",
"type": "external",
"label": "SMTP",
"sublabel": "mails",
"pos": [
1040,
320
],
"size": [
100,
60
],
"sources": [
{
"path": "apps/backend/src/lib/email.ts",
"line": 181,
"end_line": 187
}
]
},
{
"id": "storage",
"type": "cloud",
"label": "S3 (RustFS)",
"sublabel": "comprobantes",
"pos": [
1160,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/lib/storage.ts",
"line": 38,
"end_line": 54
}
]
}
],
"boundaries": [
{
"kind": "region",
"label": "Dokploy",
"wraps": [
"nginx",
"guards",
"api",
"db"
]
},
{
"kind": "security-group",
"label": "contenedor api",
"wraps": [
"guards",
"api"
]
}
],
"connections": [
{
"id": "teacher-web",
"from": "teacher",
"to": "web",
"label": "HTTPS",
"variant": "emphasis"
},
{
"id": "student-web",
"from": "student",
"to": "web",
"label": "link de WhatsApp"
},
{
"id": "web-nginx",
"from": "web",
"to": "nginx",
"label": "/api/v1",
"variant": "emphasis"
},
{
"id": "nginx-guards",
"from": "nginx",
"to": "guards",
"label": "proxy_pass",
"variant": "emphasis"
},
{
"id": "guards-api",
"from": "guards",
"to": "api",
"variant": "security"
},
{
"id": "api-db",
"from": "api",
"to": "db",
"label": "SQL"
},
{
"id": "api-mp",
"from": "api",
"to": "mp",
"label": "cobros"
},
{
"id": "api-stripe",
"from": "api",
"to": "stripe",
"label": "Pro"
},
{
"id": "api-whatsapp",
"from": "api",
"to": "whatsapp",
"label": "mensajes"
},
{
"id": "api-smtp",
"from": "api",
"to": "smtp",
"label": "mails"
},
{
"id": "api-storage",
"from": "api",
"to": "storage",
"label": "URLs firmadas"
}
],
"cards": [
{
"dot": "cyan",
"title": "Entrada",
"items": [
"Un solo dominio público en el contenedor web: nginx sirve la PWA y hace proxy de /api a api:4000, así la cookie de sesión es first-party.",
"Los alumnos entran por un link de invitación de un solo uso; no tienen contraseña."
]
},
{
"dot": "rose",
"title": "Seguridad",
"items": [
"sessionAuthMiddleware exige sesión de Better Auth salvo la whitelist pública (isPublicApiRequest).",
"/student-portal usa cookie y middleware propios (studentSession); una sesión de alumno no llega a rutas del profe.",
"Los webhooks de MP, Stripe y WhatsApp son públicos y se autentican por firma."
]
},
{
"dot": "emerald",
"title": "Jobs en el mismo proceso",
"items": [
"server.ts arranca los crons de MP, pagos, WhatsApp, billing y app de alumnos junto a Bun.serve.",
"La conciliación de pagos es por polling a Mercado Pago, sin webhook."
]
}
]
}

View File

@@ -0,0 +1,515 @@
{
"schema_version": 1,
"diagram_type": "erd",
"meta": {
"title": "Personas y membresías",
"locale": "es",
"output": ".archify/erd-personas-membresias-20261103-120000/personas-membresias.html",
"quality_profile": "standard",
"repository": {
"url": "https://git.2pidev.com/jselesan/gruperly.git",
"link_mode": "local-only",
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
},
"views": [
{
"id": "membership",
"label": "Persona y membresía",
"focus": [
"people",
"attendees",
"groups"
],
"note": "Una persona del profe, una fila de attendees por cada grupo en el que está."
},
{
"id": "owner",
"label": "Todo cuelga del profe",
"focus": [
"users",
"groups",
"people",
"student_accounts"
],
"note": "Grupos, personas y cuentas de alumno tienen created_by_id al profe."
},
{
"id": "student_app",
"label": "Una cuenta por persona",
"focus": [
"student_accounts",
"student_account_people",
"people"
],
"note": "La cuenta se vincula a la persona, así ve todos sus grupos."
}
]
},
"layout": {
"mode": "grid",
"gapX": 72,
"gapY": 40
},
"entities": [
{
"id": "groups",
"label": "groups",
"tag": "grupos",
"row": 0,
"col": 0,
"width": 256,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 3,
"end_line": 32
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "description",
"type": "text?"
},
{
"name": "days",
"type": "WeekDay[]"
},
{
"name": "time",
"type": "text?"
},
{
"name": "capacity",
"type": "int?"
},
{
"name": "price",
"type": "numeric(10,2)?"
},
{
"name": "billing_type",
"type": "BillingType?"
},
{
"name": "due_day",
"type": "int?"
},
{
"name": "auto_payment_reminders",
"type": "boolean"
},
{
"name": "auto_reengagement",
"type": "boolean"
},
{
"name": "invite_token",
"type": "text?",
"key": "uk"
},
{
"name": "created_by_id",
"type": "text",
"key": "fk",
"references": "users.id"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "attendees",
"label": "attendees",
"sublabel": "membresía",
"tag": "membresías",
"row": 0,
"col": 1,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 100,
"end_line": 125
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "group_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "groups.id"
},
{
"name": "person_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "people.id"
},
{
"name": "notify_token",
"type": "text?",
"key": "uk"
},
{
"name": "status",
"type": "AttendeeStatus"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "people",
"label": "people",
"sublabel": "persona del profe",
"tag": "personas",
"row": 0,
"col": 2,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 75,
"end_line": 98
},
{
"path": "apps/backend/prisma/migrations/20261102180000_add_people/migration.sql",
"line": 155,
"label": "índice parcial"
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "created_by_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "users.id"
},
{
"name": "full_name",
"type": "text"
},
{
"name": "email",
"type": "text?"
},
{
"name": "phone",
"type": "text?",
"key": "uk"
},
{
"name": "guardian_name",
"type": "text?"
},
{
"name": "guardian_phone",
"type": "text?"
},
{
"name": "notes",
"type": "text?"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "users",
"label": "users",
"sublabel": "profesor",
"tag": "profesor",
"row": 1,
"col": 2,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/auth.prisma",
"line": 3,
"end_line": 34
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "email",
"type": "text",
"key": "uk"
},
{
"name": "email_verified",
"type": "boolean"
},
{
"name": "image",
"type": "text?"
},
{
"name": "onboarding_completed",
"type": "boolean"
},
{
"name": "country_code",
"type": "text?"
},
{
"name": "plan_selected_at",
"type": "timestamp?"
},
{
"name": "transfer_alias",
"type": "text?"
},
{
"name": "transfer_holder",
"type": "text?"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "student_account_people",
"label": "student_account_people",
"tag": "app de alumnos",
"row": 0,
"col": 3,
"width": 300,
"sources": [
{
"path": "apps/backend/prisma/models/student-access.prisma",
"line": 40,
"end_line": 54
}
],
"attributes": [
{
"name": "account_id",
"type": "text",
"key": [
"pk",
"fk"
],
"references": "student_accounts.id"
},
{
"name": "person_id",
"type": "text",
"key": [
"pk",
"fk"
],
"references": "people.id"
},
{
"name": "created_at",
"type": "timestamp"
}
]
},
{
"id": "student_accounts",
"label": "student_accounts",
"tag": "app de alumnos",
"row": 1,
"col": 3,
"width": 300,
"sources": [
{
"path": "apps/backend/prisma/models/student-access.prisma",
"line": 10,
"end_line": 38
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "recovery_email",
"type": "text?"
},
{
"name": "recovery_email_verified_at",
"type": "timestamp?"
},
{
"name": "pending_recovery_email",
"type": "text?"
},
{
"name": "welcomed_at",
"type": "timestamp?"
},
{
"name": "created_by_id",
"type": "text",
"key": "fk",
"references": "users.id"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
}
],
"relationships": [
{
"id": "attendee_group",
"from": "attendees",
"to": "groups",
"label": "en el grupo",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "attendee_person",
"from": "attendees",
"to": "people",
"label": "membresía de",
"fromCardinality": "many",
"toCardinality": "one"
},
{
"id": "person_owner",
"from": "people",
"to": "users",
"label": "del profe",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "group_owner",
"from": "groups",
"to": "users",
"label": "dueño",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "link_person",
"from": "student_account_people",
"to": "people",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "link_account",
"from": "student_account_people",
"to": "student_accounts",
"fromCardinality": "many",
"toCardinality": "one"
},
{
"id": "account_owner",
"from": "student_accounts",
"to": "users",
"label": "creada por",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
}
],
"cards": [
{
"dot": "cyan",
"title": "Unicidad",
"items": [
"attendees: @@unique(group_id, person_id), una persona está una sola vez en cada grupo.",
"people_owner_phone_key: (created_by_id, phone) WHERE phone IS NOT NULL, índice parcial escrito a mano (Prisma no lo modela; el choque llega como P2002)."
]
},
{
"dot": "amber",
"title": "Qué es de quién",
"items": [
"people: contacto y notas; editarlos cambia en todos los grupos.",
"attendees: status y notify_token por grupo; asistencia, cuotas, alertas y mensajes cuelgan de esta fila (no dibujados).",
"El límite del plan cuenta personas con al menos una membresía ACTIVE."
]
},
{
"dot": "emerald",
"title": "Borrados",
"items": [
"Todas las FK son ON DELETE CASCADE.",
"Quitar la última membresía borra también la persona, y con ella el vínculo a la cuenta de alumno."
]
}
]
}

File diff suppressed because one or more lines are too long

View File

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

12
.gitignore vendored
View File

@@ -6,6 +6,7 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.impeccable
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
@@ -149,3 +150,14 @@ apps/backend/generated/
# env
apps/backend/.env
# macOS
.DS_Store
# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no
.archify/**/*.browser-check.json
.archify/**/*.delivery.json
.archify/**/*.finalize.json
.archify/**/*.finalize-summary.json
.archify/**/candidate.before-review.json
.archify/**/review-*/

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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty.
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; límites y precio de Pro por país se leen con `PlanCatalog`/`planCatalog`, nunca con `PLAN_LIMITS`/`PRO_PRICE_BY_COUNTRY` directo, que son solo defaults; guía en `docs/billing.md`). `admin` (backoffice de las cuentas de profesores, de solo lectura salvo **Planes** (`/admin/plans`: límites y precio de Pro, con opción de aplicar el precio a las suscripciones vivas desde el próximo cobro): acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*` y `/admin/plans*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
@@ -39,10 +39,10 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
## Gotchas operativos
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). Como la cookie de sesión es de `localhost:4000`, el callback que entra por el túnel rebota a `BETTER_AUTH_URL` con la misma query (`mpCallbackOriginMiddleware`, antes del middleware de sesión; no se dispara si ambos hosts coinciden, como en prod). El callback además exige que la sesión sea la del dueño del `state`. El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
@@ -61,7 +61,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp.
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde.
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
- **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).
@@ -84,11 +84,22 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto:
1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`.
2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`.
3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense).
4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma.
5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`).
6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `<FieldError message={errors.x?.message} />` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod.
7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción.
8. Lo que arma el backend en español y la UI muestra se redacta en la web a partir de datos estructurados: las alertas de `computeStudentAlerts` traen `razon` + `valores` (la web usa `alertLabel`/`alertDetail` de `features/attention/attention.ts`; `etiqueta`/`detalle` quedan para el backend), y los `message` de la API (importación masiva, preinscripción) se ignoran y se arman con los contadores. Nombres de país: `countryName` (`Intl.DisplayNames`), no `COUNTRY_LABELS`.
9. Pendiente: mails, WhatsApp y el manifest de la PWA (`vite.config.ts`) siguen solo en español (etapa 2: usar `users.locale`).
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
## Convenciones repo-específicas
- **Frontend en español**: copy de UI, comentarios y textos en español.
- **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están.
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español.
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.

View File

@@ -206,9 +206,11 @@ Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor** (nginx escucha `80` adentro). El compose no publica puertos en el host: Traefik llega por `dokploy-network`.
4. Deploy.
Se pueden tener varias apps Compose de este repo en el mismo server (p. ej. dev y prod): como no se publican puertos en el host no chocan, y nginx le pega a su propia API por el alias `gruperly-api`, que solo existe en la red de cada stack. Cada app necesita su dominio, su `WEB_URL`, su `DATABASE_URL` (otra base) y su `BETTER_AUTH_SECRET`.
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
@@ -226,7 +228,7 @@ Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la d
```bash
docker network create dokploy-network # una sola vez
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
docker compose up --build -d
docker compose -f docker-compose.yml -f docker-compose.local.yml up --build -d # publica web en :8080
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
curl http://localhost:8080/api/v1/health
```

View File

@@ -38,6 +38,11 @@ TOKEN_ENCRYPTION_KEY=""
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
MP_PLATFORM_ACCESS_TOKEN_AR=""
MP_PLATFORM_WEBHOOK_SECRET_AR=""
# Origen público de esta API, adonde MP y Stripe devuelven el navegador después
# del checkout de Pro (GET /api/v1/billing/return, que redirige a la web). MP
# rechaza localhost: en local poné el túnel (https://TU-DOMINIO.ngrok-free.app).
# Vacío = BETTER_AUTH_URL.
API_PUBLIC_URL=""
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.

View File

@@ -0,0 +1 @@
ALTER TABLE "users" ADD COLUMN "locale" TEXT;

View File

@@ -0,0 +1,67 @@
-- CreateEnum
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
-- AlterTable
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "price_change_error" TEXT,
ADD COLUMN "price_change_id" TEXT;
-- CreateTable
CREATE TABLE "plan_configs" (
"plan" "PlanId" NOT NULL,
"max_groups" INTEGER,
"max_attendees" INTEGER,
"whatsapp_automations" BOOLEAN NOT NULL,
"mp_charges" BOOLEAN NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
);
-- CreateTable
CREATE TABLE "plan_prices" (
"country_code" TEXT NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
);
-- CreateTable
CREATE TABLE "plan_price_changes" (
"id" TEXT NOT NULL,
"country_code" TEXT NOT NULL,
"previous_amount" DECIMAL(12,2),
"new_amount" DECIMAL(12,2) NOT NULL,
"currency" TEXT NOT NULL,
"apply_to_existing" BOOLEAN NOT NULL,
"queued" INTEGER NOT NULL DEFAULT 0,
"created_by_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
-- CreateIndex
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
-- in packages/shared), so nothing changes on deploy.
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
('AR', 15000, CURRENT_TIMESTAMP),
('BR', 49, CURRENT_TIMESTAMP),
('CL', 9900, CURRENT_TIMESTAMP),
('CO', 39900, CURRENT_TIMESTAMP),
('MX', 199, CURRENT_TIMESTAMP),
('PE', 39, CURRENT_TIMESTAMP),
('UY', 390, CURRENT_TIMESTAMP);

View File

@@ -8,6 +8,8 @@ model User {
image String?
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
country String? @map("country_code")
// UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
locale String? @map("locale")
// When the professor chose Free or Pro in the onboarding (mandatory step).
planSelectedAt DateTime? @map("plan_selected_at")
// Bank transfer details shown to students when they report a payment.

View File

@@ -39,6 +39,12 @@ model BillingSubscription {
// period, even after a cancellation or a failed renewal.
paidThrough DateTime? @map("paid_through")
lastSyncedAt DateTime? @map("last_synced_at")
// A new price queued by the backoffice for this live subscription: the job
// pushes it to the provider (from the next charge) and moves it to `amount`.
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
priceChangeId String? @map("price_change_id")
priceChangeAttempts Int @default(0) @map("price_change_attempts")
priceChangeError String? @map("price_change_error")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -47,6 +53,7 @@ model BillingSubscription {
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
@@map("billing_subscriptions")
}
@@ -80,3 +87,52 @@ model BillingWebhookEvent {
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events")
}
enum PlanId {
FREE
PRO
}
// What each plan allows, edited from the backoffice. Seeded with the defaults
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
model PlanConfig {
plan PlanId @id
// Null means no limit.
maxGroups Int? @map("max_groups")
maxAttendees Int? @map("max_attendees")
whatsappAutomations Boolean @map("whatsapp_automations")
mpCharges Boolean @map("mp_charges")
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_configs")
}
// Monthly price of Pro per country, in the country's currency. Seeded with
// `PRO_PRICE_BY_COUNTRY` (shared). New subscriptions take it; live ones keep
// their own `amount` unless a price change is applied to them.
model PlanPrice {
country String @id @map("country_code")
amount Decimal @db.Decimal(12, 2)
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_prices")
}
// Audit of every price edit from the backoffice.
model PlanPriceChange {
id String @id @default(cuid())
country String @map("country_code")
previousAmount Decimal? @db.Decimal(12, 2) @map("previous_amount")
newAmount Decimal @db.Decimal(12, 2) @map("new_amount")
currency String
applyToExisting Boolean @map("apply_to_existing")
// Live subscriptions queued to move to the new price.
queued Int @default(0)
createdById String? @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
@@index([country, createdAt], map: "plan_price_changes_country_created_at_idx")
@@map("plan_price_changes")
}

View File

@@ -25,6 +25,7 @@ import { healthCheckRoutes } from './modules/health-check';
import { homeRoutes } from './modules/home';
import { invitationsRoutes } from './modules/invitations';
import { mpRoutes } from './modules/mp';
import { mpCallbackOriginMiddleware } from './modules/mp/lib';
import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments';
import { peopleRoutes } from './modules/people';
@@ -43,6 +44,9 @@ app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }));
const api = app.basePath('/api/v1');
// Local development: the MP callback comes back through the tunnel, without the
// session cookie of localhost. Replay it there before asking for a session.
api.use('/mp/callback', mpCallbackOriginMiddleware);
api.use('*', sessionAuthMiddleware);
// Read-only accounts (Free over its limits) cannot write domain data. Billing,

View File

@@ -21,6 +21,7 @@ export function conflictProblem(params: {
detail: string;
code?: string;
instance?: string;
params?: ProblemDetails['params'];
}): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/conflict`,
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
detail: params.detail,
instance: params.instance,
code: params.code,
...(params.params ? { params: params.params } : {}),
};
}
@@ -186,6 +188,7 @@ export function capacityReachedProblem(capacity: number | null): ProblemDetails
? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
: 'El grupo alcanzó su cupo máximo de miembros.',
code: 'group_capacity_reached',
...(capacity ? { params: { capacity } } : {}),
});
}
@@ -216,13 +219,18 @@ export function noAttendeesToBillProblem(): ProblemDetails {
code: 'no_attendees_to_bill',
});
}
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails {
function paymentRequiredProblem(params: {
detail: string;
code: string;
params?: ProblemDetails['params'];
}): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/plan`,
title: 'Payment Required',
status: 402,
detail: params.detail,
code: params.code,
...(params.params ? { params: params.params } : {}),
};
}
@@ -236,6 +244,7 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
code: 'plan_limit_reached',
params: { limit, max },
});
}
@@ -247,6 +256,7 @@ export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutom
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
code: 'plan_feature_required',
params: { feature },
});
}

View File

@@ -47,6 +47,15 @@ export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
return true;
}
// Mercado Pago notifications about a Checkout Pro payment: no session; the
// owner's Mercado Pago account is asked before anything changes.
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/[A-Za-z0-9_-]+$/.test(normalizedPath)) {
return true;
}
// Back from the Pro checkout: only redirects to the web, which has the session.
if (method === 'GET' && normalizedPath === '/api/v1/billing/return') {
return true;
}
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;

View File

@@ -6,6 +6,15 @@ type PasswordResetEmailData = { email: string; url: string; name?: string }
type InvitationEmailData = { email: string; url: string; organizationName: string }
type StudentEmailConfirmationData = { email: string; url: string; name: string }
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
type ProPriceChangedData = {
email: string
name: string
/** Already formatted in the professor's currency. */
amount: string
/** Already formatted; `null` when the provider has not scheduled the next charge. */
nextPaymentDate: string | null
billingUrl: string
}
type StudentPaymentReviewedData = {
email: string
name: string
@@ -42,6 +51,7 @@ export interface EmailProvider {
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
sendProPriceChanged(data: ProPriceChangedData): Promise<void>
}
// Names come from what teachers and students type: never raw into the HTML.
@@ -176,6 +186,20 @@ class SMTPEmailProvider implements EmailProvider {
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
)
}
async sendProPriceChanged({ email, name, amount, nextPaymentDate, billingUrl }: ProPriceChangedData) {
const when = nextPaymentDate
? `desde tu próximo cobro, el ${escapeHtml(nextPaymentDate)}`
: 'desde tu próximo cobro'
await this.send(
email,
'Cambia el precio de Gruperly Pro',
this.layout(
'Nuevo precio de Gruperly Pro',
`Hola ${escapeHtml(name)}, te avisamos que el precio de tu suscripción a Gruperly Pro pasa a ser de ${escapeHtml(amount)} por mes ${when}. Lo que ya pagaste no cambia.<br/><br/>Si no querés seguir, podés cancelar la suscripción cuando quieras y vas a seguir con Pro hasta el final del período pago.<br/><br/>${button(billingUrl, 'Ver mi plan')}`,
),
)
}
}
// Future: transactional providers (Resend, SendGrid, Postmark).

View File

@@ -0,0 +1,17 @@
const DEFAULT_API_ORIGIN = 'http://localhost:4000';
/**
* Public origin of this API, as the billing providers reach it. Mercado Pago
* refuses a non-public `back_url` and `notification_url` (localhost), so in local development it is the
* ngrok tunnel. Falls back to `BETTER_AUTH_URL`, which is the API's base URL
* (in production the same origin as the web, since nginx proxies `/api`).
*/
export function getApiPublicOrigin(env: Record<string, string | undefined> = process.env): string {
const configured = env.API_PUBLIC_URL?.trim() || env.BETTER_AUTH_URL?.trim();
if (!configured) return DEFAULT_API_ORIGIN;
try {
return new URL(configured).origin;
} catch {
return DEFAULT_API_ORIGIN;
}
}

View File

@@ -1,9 +1,16 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib';
import {
exceedsLimits,
getGraceDays,
isBillingEnforced,
type PlanCatalogReader,
planCatalog,
toBillingChargeDto,
} from '@/modules/billing/lib';
import { accountPlan, toAccountListItem } from '../../lib';
const RECENT_CHARGES = 12;
@@ -13,6 +20,7 @@ type GetAccountDeps = {
enforced?: boolean;
graceDays?: number;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/** One professor's account: plan, links, groups and the latest Pro charges. */
@@ -65,18 +73,16 @@ export class GetAccount {
const { graceUntil } = accountPlan(user, context);
const enforced = this.deps.enforced ?? isBillingEnforced();
const subscription = user.subscription;
// Same rule as the PlanGuard: an account without a plan is held to Free.
const limits = await (this.deps.catalog ?? planCatalog).getLimits(summary.plan ?? 'FREE');
return ok({
...summary,
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
graceUntil: graceUntil?.toISOString() ?? null,
// Same rule as the PlanGuard: an account without a plan is held to Free.
readOnly:
enforced
&& exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], {
groups: usage.groupsCount,
attendees: usage.attendeesCount,
}),
enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }),
limits,
subscription:
summary.subscription && subscription
? {

View File

@@ -0,0 +1,12 @@
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { GetPlans } from './use-case';
const route = new Hono();
route.get('/plans', async (c) => {
const result = await new GetPlans().execute();
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,55 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminPlansDto, ProblemDetails, Result } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, countryCodeSchema, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { MAX_PRICE_CHANGE_ATTEMPTS } from '@/modules/billing/jobs';
import { type PlanCatalogReader, planCatalog } from '@/modules/billing/lib';
/** The subscriptions "apply to existing" moves: live, with a provider subscription. */
export const LIVE_SUBSCRIPTION_STATUSES = ['AUTHORIZED', 'PAUSED'] as const;
type GetPlansDeps = {
db?: Pick<PrismaClient, 'planPrice' | 'billingSubscription'>;
catalog?: PlanCatalogReader;
};
/** Limits of both plans and, per country, the price of Pro and how it reached live subscriptions. */
export class GetPlans {
constructor(private readonly deps: GetPlansDeps = {}) {}
async execute(): Promise<Result<AdminPlansDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const catalog = await (this.deps.catalog ?? planCatalog).snapshot();
const [priceRows, live] = await Promise.all([
db.planPrice.findMany({ select: { country: true, updatedAt: true } }),
db.billingSubscription.findMany({
where: { status: { in: [...LIVE_SUBSCRIPTION_STATUSES] }, externalId: { not: null } },
select: { country: true, amount: true, pendingAmount: true, priceChangeAttempts: true },
}),
]);
const updatedAt = new Map(priceRows.map((row) => [row.country, row.updatedAt]));
const prices = countryCodeSchema.options.map((country) => {
const amount = catalog.proPrices[country];
const rows = live.filter((row) => row.country === country);
const queued = rows.filter((row) => row.pendingAmount !== null);
const failed = queued.filter((row) => row.priceChangeAttempts >= MAX_PRICE_CHANGE_ATTEMPTS);
return {
country,
amount,
currency: COUNTRY_CURRENCY[country],
provider: billingProviderForCountry(country),
updatedAt: updatedAt.get(country)?.toISOString() ?? null,
liveSubscriptions: rows.length,
atOtherPrice: rows.filter(
(row) => Number((row.pendingAmount ?? row.amount).toString()) !== amount,
).length,
pendingChanges: queued.length - failed.length,
failedChanges: failed.length,
};
});
return ok({ limits: catalog.limits, prices });
}
}

View File

@@ -0,0 +1,23 @@
import type { PlanLimitsImpactQuery } from '@gruperly/shared';
import { PlanLimitsImpactQuerySchema, planSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import { resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { PlanLimitsImpact } from './use-case';
const route = new Hono();
route.get(
'/plans/:plan/impact',
validate.param(z.object({ plan: planSchema })),
validate.query(PlanLimitsImpactQuerySchema),
async (c) => {
const { plan } = c.req.valid('param');
const query = c.req.valid('query') as PlanLimitsImpactQuery;
const result = await new PlanLimitsImpact().execute(plan, query);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,52 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib';
type PlanLimitsImpactDeps = {
db?: Pick<PrismaClient, 'group' | 'person' | 'user'>;
graceDays?: number;
now?: () => Date;
};
/**
* How many accounts on a plan would exceed new limits, i.e. become read only
* as soon as they are saved (limits apply at once). Usage is the PlanGuard's:
* groups owned, and people with at least one ACTIVE membership.
*/
export class PlanLimitsImpact {
constructor(private readonly deps: PlanLimitsImpactDeps = {}) {}
async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise<Result<PlanLimitsImpactDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now?.() ?? new Date();
const graceDays = this.deps.graceDays ?? getGraceDays();
const [overGroups, overAttendees] = await Promise.all([
query.maxGroups === null
? []
: db.group.groupBy({
by: ['createdById'],
having: { id: { _count: { gt: query.maxGroups } } },
}),
query.maxAttendees === null
? []
: db.person.groupBy({
by: ['createdById'],
where: { attendees: { some: { status: 'ACTIVE' } } },
having: { id: { _count: { gt: query.maxAttendees } } },
}),
]);
const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))];
if (candidates.length === 0) return ok({ affectedAccounts: 0 });
// Same split as the PlanGuard: anyone without a live Pro is held to Free.
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
const affectedAccounts = await db.user.count({
where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) },
});
return ok({ affectedAccounts });
}
}

View File

@@ -0,0 +1,26 @@
import type { UpdatePlanLimitsInput } from '@gruperly/shared';
import { planSchema, UpdatePlanLimitsInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { UpdatePlanLimits } from './use-case';
const route = new Hono<BackendEnv>();
route.put(
'/plans/:plan/limits',
validate.param(z.object({ plan: planSchema })),
validate.json(UpdatePlanLimitsInputSchema),
async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { plan } = c.req.valid('param');
const input = c.req.valid('json') as UpdatePlanLimitsInput;
const result = await new UpdatePlanLimits().execute(plan, input, user.id);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,29 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { Plan, PlanLimits, ProblemDetails, Result, UpdatePlanLimitsInput } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
type UpdatePlanLimitsDeps = {
db?: Pick<PrismaClient, 'planConfig'>;
catalog?: Pick<PlanCatalog, 'invalidate'>;
};
/** New limits for a plan. They apply at once to every account on it. */
export class UpdatePlanLimits {
constructor(private readonly deps: UpdatePlanLimitsDeps = {}) {}
async execute(
plan: Plan,
input: UpdatePlanLimitsInput,
adminId: string,
): Promise<Result<PlanLimits, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const data = { ...input, updatedById: adminId };
await db.planConfig.upsert({ where: { plan }, create: { plan, ...data }, update: data });
(this.deps.catalog ?? planCatalog).invalidate();
logger.info({ plan, adminId, limits: input }, 'Plan limits updated');
return ok(input);
}
}

View File

@@ -0,0 +1,27 @@
import type { UpdatePlanPriceInput } from '@gruperly/shared';
import { countryCodeSchema, UpdatePlanPriceInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { z } from 'zod';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { runPriceChanges } from '@/modules/billing/jobs';
import { UpdatePlanPrice } from './use-case';
const route = new Hono<BackendEnv>();
route.put(
'/plans/prices/:country',
validate.param(z.object({ country: countryCodeSchema })),
validate.json(UpdatePlanPriceInputSchema),
async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { country } = c.req.valid('param');
const input = c.req.valid('json') as UpdatePlanPriceInput;
const result = await new UpdatePlanPrice({ applyQueued: runPriceChanges }).execute(country, input, user.id);
return resultJson(c, result);
},
);
export default route;

View File

@@ -0,0 +1,89 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, ProblemDetails, Result, UpdatePlanPriceInput, UpdatePlanPriceResultDto } from '@gruperly/shared';
import { COUNTRY_CURRENCY, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
import { LIVE_SUBSCRIPTION_STATUSES } from '../get-plans/use-case';
type UpdatePlanPriceDeps = {
db?: Pick<PrismaClient, '$transaction'>;
catalog?: Pick<PlanCatalog, 'invalidate' | 'getProPrice'>;
/** Kicks the job that pushes queued prices to the providers. */
applyQueued?: () => Promise<void>;
};
/**
* New monthly price of Pro in a country. New subscriptions take it right away.
* With `applyToExisting`, the country's live subscriptions are queued to move
* to it (`pending_amount`); the job tells each provider to charge it from the
* next charge on, and emails the professor.
*
* PENDING subscriptions are left alone: a checkout half done keeps its amount,
* and trying again starts a new one at the new price.
*/
export class UpdatePlanPrice {
constructor(private readonly deps: UpdatePlanPriceDeps = {}) {}
async execute(
country: CountryCode,
input: UpdatePlanPriceInput,
adminId: string,
): Promise<Result<UpdatePlanPriceResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const catalog = this.deps.catalog ?? planCatalog;
catalog.invalidate();
const previousAmount = await catalog.getProPrice(country);
const currency = COUNTRY_CURRENCY[country];
const queued = await db.$transaction(async (tx) => {
await tx.planPrice.upsert({
where: { country },
create: { country, amount: input.amount, updatedById: adminId },
update: { amount: input.amount, updatedById: adminId },
});
const change = await tx.planPriceChange.create({
data: {
country,
previousAmount,
newAmount: input.amount,
currency,
applyToExisting: input.applyToExisting,
createdById: adminId,
},
});
if (!input.applyToExisting) return 0;
// Rows already at the new price (or already moving to it) are not touched.
const moved = await tx.billingSubscription.updateMany({
where: {
country,
status: { in: [...LIVE_SUBSCRIPTION_STATUSES] },
externalId: { not: null },
OR: [
{ pendingAmount: null, amount: { not: input.amount } },
{ pendingAmount: { not: null, notIn: [input.amount] } },
],
},
data: {
pendingAmount: input.amount,
priceChangeId: change.id,
priceChangeAttempts: 0,
priceChangeError: null,
},
});
await tx.planPriceChange.update({ where: { id: change.id }, data: { queued: moved.count } });
return moved.count;
});
catalog.invalidate();
logger.info({ country, adminId, amount: input.amount, queued }, 'Pro price updated');
if (queued > 0 && this.deps.applyQueued) {
// In the background: the providers are slow, and the cron retries anyway.
void this.deps.applyQueued();
}
return ok({ country, amount: input.amount, queued });
}
}

View File

@@ -1,7 +1,11 @@
import { Hono } from 'hono';
import getAccountRoute from './features/get-account/route';
import getPlansRoute from './features/get-plans/route';
import listAccountsRoute from './features/list-accounts/route';
import meRoute from './features/me/route';
import planLimitsImpactRoute from './features/plan-limits-impact/route';
import updatePlanLimitsRoute from './features/update-plan-limits/route';
import updatePlanPriceRoute from './features/update-plan-price/route';
import { adminOnlyMiddleware } from './lib';
const routes = new Hono();
@@ -11,7 +15,13 @@ routes.route('/', meRoute);
// Everything below `/me` is the backoffice itself.
routes.use('/accounts', adminOnlyMiddleware());
routes.use('/accounts/*', adminOnlyMiddleware());
routes.use('/plans', adminOnlyMiddleware());
routes.use('/plans/*', adminOnlyMiddleware());
routes.route('/', listAccountsRoute);
routes.route('/', getAccountRoute);
routes.route('/', getPlansRoute);
routes.route('/', planLimitsImpactRoute);
routes.route('/', updatePlanLimitsRoute);
routes.route('/', updatePlanPriceRoute);
export default routes;

View File

@@ -1,4 +1,5 @@
import { passkey } from '@better-auth/passkey';
import { appLocaleSchema } from '@gruperly/shared';
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { organization } from 'better-auth/plugins/organization';
@@ -11,6 +12,18 @@ export const auth = betterAuth({
database: prismaAdapter(getPrismaClient(), {
provider: 'postgresql',
}),
user: {
additionalFields: {
// UI language chosen in Ajustes; null means "follow the device". The web
// saves it with updateUser and reads it back from the session.
locale: {
type: 'string',
required: false,
input: true,
validator: { input: appLocaleSchema.nullable() },
},
},
},
emailAndPassword: {
enabled: true,
minPasswordLength: 8,

View File

@@ -0,0 +1,16 @@
import { ok } from '@gruperly/shared';
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { planCatalog, toPlanCatalogDto } from '../../lib';
const route = new Hono();
/**
* What each plan allows and what Pro costs in every country. The onboarding
* asks before the professor's country is stored, so it gets all of them.
*/
route.get('/plans', async (c) => {
return resultJson(c, ok(toPlanCatalogDto(await planCatalog.snapshot())));
});
export default route;

View File

@@ -0,0 +1,19 @@
import { billingReturnToSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildSubscriptionReturnUrl } from '../../lib';
const route = new Hono();
/**
* The `back_url` of the Pro checkout (Mercado Pago and Stripe). Public: the
* browser comes from the provider, maybe through a tunnel without the session
* cookie. It only redirects to a fixed page of the web, so whatever the
* provider appends to the query is dropped and nothing can steer the redirect.
*/
route.get('/return', (c) => {
const parsed = billingReturnToSchema.safeParse(c.req.query('to'));
return c.redirect(buildSubscriptionReturnUrl(getWebOrigin(), parsed.success ? parsed.data : 'billing'));
});
export default route;

View File

@@ -1,17 +1,18 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
import { countryOf, type PlanCatalogReader, PlanGuard, planCatalog, SyncSubscription } from '../../lib';
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
type GetBillingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
db?: Pick<PrismaClient, 'user' | 'billingSubscription' | 'billingCharge'>;
guard?: PlanGuard;
catalog?: PlanCatalogReader;
sync?: Pick<SyncSubscription, 'execute'>;
providers?: BillingProviderResolver;
now?: () => Date;
@@ -54,6 +55,24 @@ export class GetBillingStatus {
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
);
const priceAmount = live
? Number(live.amount.toString())
: await (this.deps.catalog ?? planCatalog).getProPrice(country);
// A price change from the backoffice applies from the next charge: show it
// while it is queued, and after it reached the provider until it is charged.
let nextPriceAmount: number | null = null;
if (live?.pendingAmount) {
nextPriceAmount = Number(live.pendingAmount.toString());
} else if (live?.status === 'AUTHORIZED') {
const lastCharge = await db.billingCharge.findFirst({
where: { subscriptionId: live.id, status: 'approved' },
orderBy: { paidAt: 'desc' },
select: { amount: true },
});
if (lastCharge && Number(lastCharge.amount.toString()) !== priceAmount) nextPriceAmount = priceAmount;
}
return ok({
plan: entitlements.plan,
status: subscription?.status ?? null,
@@ -65,7 +84,8 @@ export class GetBillingStatus {
? (subscription.nextPaymentDate?.toISOString() ?? null)
: null,
payerEmail: subscription?.payerEmail ?? null,
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
priceAmount,
nextPriceAmount,
currency: live ? live.currency : COUNTRY_CURRENCY[country],
country,
provider: provider.id,

View File

@@ -1,6 +1,6 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
import {
billingNotAvailableProblem,
notFoundResourceProblem,
@@ -9,15 +9,20 @@ import {
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
import {
buildSubscriptionBackUrl,
countryOf,
getApiPublicOrigin,
type PlanCatalogReader, planCatalog, subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
providers?: BillingProviderResolver;
webOrigin?: string;
/** Public origin of the API, where the provider sends the browser back. */
apiOrigin?: string;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/**
@@ -60,7 +65,7 @@ export class Subscribe {
}
}
const amount = PRO_PRICE_BY_COUNTRY[country];
const amount = await (this.deps.catalog ?? planCatalog).getProPrice(country);
const currency = COUNTRY_CURRENCY[country];
const fields = {
country,
@@ -82,6 +87,10 @@ export class Subscribe {
checkoutRef: null,
authorizedAt: null,
nextPaymentDate: null,
pendingAmount: null,
priceChangeId: null,
priceChangeAttempts: 0,
priceChangeError: null,
},
});
@@ -97,7 +106,7 @@ export class Subscribe {
amount,
currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
backUrl: buildSubscriptionBackUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), input.returnTo),
startDate,
});
} catch (error) {

View File

@@ -0,0 +1,117 @@
import type { PrismaClient } from '@generated/prisma/client';
import { COUNTRY_TIME_ZONES } from '@gruperly/shared';
import type { EmailProvider } from '@/lib/email';
import { emailProvider } from '@/lib/email';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { formatAmount } from '@/modules/whatsapp/lib/format';
import { countryOf } from '../lib';
import {
BillingProviderNotConfigured,
type BillingProviderResolver,
getBillingProvider,
} from '../providers';
const BATCH_SIZE = 20;
/** After this many refusals the change stays visible as failed in the backoffice. */
export const MAX_PRICE_CHANGE_ATTEMPTS = 5;
type ApplyPriceChangesDeps = {
db?: Pick<PrismaClient, 'billingSubscription'>;
providers?: BillingProviderResolver;
email?: Pick<EmailProvider, 'sendProPriceChanged'>;
webOrigin?: string;
};
export type ApplyPriceChangesTotals = { applied: number; failed: number; dropped: number };
/**
* Pushes the prices the backoffice queued (`pending_amount`) to each live
* subscription's provider, from its next charge on, and tells the professor.
*
* The provider call is idempotent (it sets an amount), so two instances racing
* over a row are harmless: only the one whose conditional update moves
* `pending_amount` into `amount` sends the email.
*/
export class ApplyPriceChanges {
constructor(private readonly deps: ApplyPriceChangesDeps = {}) {}
async execute(): Promise<ApplyPriceChangesTotals> {
const db = this.deps.db ?? prisma;
const providers = this.deps.providers ?? getBillingProvider;
const totals: ApplyPriceChangesTotals = { applied: 0, failed: 0, dropped: 0 };
const rows = await db.billingSubscription.findMany({
where: { pendingAmount: { not: null }, priceChangeAttempts: { lt: MAX_PRICE_CHANGE_ATTEMPTS } },
include: { user: { select: { name: true, email: true, country: true } } },
orderBy: { updatedAt: 'asc' },
take: BATCH_SIZE,
});
for (const row of rows) {
const pendingAmount = row.pendingAmount;
if (!pendingAmount) continue;
const unchanged = { id: row.id, pendingAmount };
// Cancelled (or never completed) meanwhile: nothing left to reprice.
if (row.status === 'CANCELLED' || row.status === 'PENDING' || !row.externalId) {
await db.billingSubscription.updateMany({
where: unchanged,
data: { pendingAmount: null, priceChangeId: null, priceChangeAttempts: 0, priceChangeError: null },
});
totals.dropped += 1;
continue;
}
const amount = Number(pendingAmount.toString());
const country = countryOf({ country: row.country });
try {
await providers(row.provider).updateAmount(
{ country, externalId: row.externalId, checkoutRef: row.checkoutRef },
amount,
row.currency,
);
} catch (error) {
// Never the provider's message: it can echo what we sent.
const reason = error instanceof BillingProviderNotConfigured ? 'not_configured' : 'provider_error';
logger.warn({ subscriptionId: row.id, provider: row.provider, reason }, 'Could not apply a Pro price change');
await db.billingSubscription.updateMany({
where: unchanged,
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: reason },
});
totals.failed += 1;
continue;
}
const moved = await db.billingSubscription.updateMany({
where: unchanged,
data: { amount: pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
});
if (moved.count !== 1) continue;
totals.applied += 1;
try {
await (this.deps.email ?? emailProvider).sendProPriceChanged({
email: row.user.email,
name: row.user.name,
amount: formatAmount(amount, row.currency, country),
nextPaymentDate: row.nextPaymentDate
? new Intl.DateTimeFormat('es-AR', {
day: 'numeric',
month: 'long',
year: 'numeric',
timeZone: COUNTRY_TIME_ZONES[country],
}).format(row.nextPaymentDate)
: null,
billingUrl: `${this.deps.webOrigin ?? getWebOrigin()}/billing`,
});
} catch (error) {
// The price already changed; a lost email is not worth a retry loop.
logger.warn({ err: error, subscriptionId: row.id }, 'Could not email a Pro price change');
}
}
return totals;
}
}

View File

@@ -1,2 +1,3 @@
export { ApplyPriceChanges, type ApplyPriceChangesTotals, MAX_PRICE_CHANGE_ATTEMPTS } from './apply-price-changes';
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
export { startBillingJobs } from './schedule';
export { runPriceChanges, startBillingJobs } from './schedule';

View File

@@ -1,7 +1,9 @@
import { logger } from '@/logger';
import { ApplyPriceChanges } from './apply-price-changes';
import { ReconcileSubscriptions } from './reconcile-subscriptions';
const RECONCILE_CRON = '*/30 * * * *';
const PRICE_CHANGES_CRON = '*/5 * * * *';
/**
* Registers the billing background jobs. Called once from `server.ts`, with the
@@ -21,4 +23,27 @@ export function startBillingJobs(): void {
},
{ tz: 'UTC' },
).unref();
Bun.cron(
PRICE_CHANGES_CRON,
async () => {
await runPriceChanges();
},
{ tz: 'UTC' },
).unref();
}
/**
* Applies the Pro price changes queued by the backoffice. Also called right
* after a save, so the change does not wait for the next tick. Never throws.
*/
export async function runPriceChanges(): Promise<void> {
try {
const totals = await new ApplyPriceChanges().execute();
if (totals.applied + totals.failed + totals.dropped > 0) {
logger.info(totals, 'Pro price changes applied');
}
} catch (error) {
logger.error({ err: error }, 'Applying Pro price changes failed');
}
}

View File

@@ -0,0 +1,108 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, Plan, PlanCatalogDto, PlanLimits } from '@gruperly/shared';
import { COUNTRY_CURRENCY, countryCodeSchema, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
/** Limits and prices are read often (every plan guard) and edited rarely. */
const CACHE_TTL_MS = 30 * 1000;
export type PlanCatalogSnapshot = {
limits: Record<Plan, PlanLimits>;
/** Monthly price of Pro, in the currency of each country. */
proPrices: Record<CountryCode, number>;
};
export function defaultPlanCatalog(): PlanCatalogSnapshot {
return {
limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } },
proPrices: { ...PRO_PRICE_BY_COUNTRY },
};
}
type PlanCatalogDeps = {
db?: Pick<PrismaClient, 'planConfig' | 'planPrice'>;
ttlMs?: number;
now?: () => number;
};
/**
* What each plan allows and what Pro costs, as edited from the backoffice
* (`plan_configs`, `plan_prices`). A missing row falls back to the defaults in
* shared (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`), which also seed the tables.
*
* Cached in memory for a few seconds; the backoffice invalidates it on save, so
* the instance that saved sees the change at once and the others within the TTL.
*/
export class PlanCatalog {
private cached: { snapshot: PlanCatalogSnapshot; at: number } | null = null;
constructor(private readonly deps: PlanCatalogDeps = {}) {}
invalidate(): void {
this.cached = null;
}
async snapshot(): Promise<PlanCatalogSnapshot> {
const now = this.deps.now?.() ?? Date.now();
const ttl = this.deps.ttlMs ?? CACHE_TTL_MS;
if (this.cached && now - this.cached.at < ttl) return this.cached.snapshot;
const snapshot = defaultPlanCatalog();
try {
const db = this.deps.db ?? prisma;
const [configs, prices] = await Promise.all([db.planConfig.findMany(), db.planPrice.findMany()]);
for (const config of configs) {
snapshot.limits[config.plan] = {
maxGroups: config.maxGroups,
maxAttendees: config.maxAttendees,
whatsappAutomations: config.whatsappAutomations,
mpCharges: config.mpCharges,
};
}
for (const price of prices) {
const country = countryCodeSchema.safeParse(price.country);
if (country.success) snapshot.proPrices[country.data] = Number(price.amount.toString());
}
} catch (error) {
// The defaults keep the guards working; not cached, so the next call retries.
logger.warn({ err: error }, 'Could not read the plan catalog, using the defaults');
return snapshot;
}
this.cached = { snapshot, at: now };
return snapshot;
}
async getLimits(plan: Plan): Promise<PlanLimits> {
return (await this.snapshot()).limits[plan];
}
async getProPrice(country: CountryCode): Promise<number> {
return (await this.snapshot()).proPrices[country];
}
}
/** The catalog every use-case shares, so an invalidation reaches all of them. */
export const planCatalog = new PlanCatalog();
/** A fixed catalog, for tests and callers that already hold a snapshot. */
export function staticPlanCatalog(snapshot: PlanCatalogSnapshot = defaultPlanCatalog()): PlanCatalogReader {
return {
snapshot: async () => snapshot,
getLimits: async (plan) => snapshot.limits[plan],
getProPrice: async (country) => snapshot.proPrices[country],
};
}
export type PlanCatalogReader = Pick<PlanCatalog, 'snapshot' | 'getLimits' | 'getProPrice'>;
export function toPlanCatalogDto(snapshot: PlanCatalogSnapshot): PlanCatalogDto {
const proPrices = Object.fromEntries(
countryCodeSchema.options.map((country) => [
country,
{ amount: snapshot.proPrices[country], currency: COUNTRY_CURRENCY[country] },
]),
) as PlanCatalogDto['proPrices'];
return { limits: snapshot.limits, proPrices };
}

View File

@@ -14,3 +14,5 @@ export function getGraceDays(env: Record<string, string | undefined> = process.e
const value = Number(env.BILLING_GRACE_DAYS);
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
}
export { getApiPublicOrigin } from '@/lib/public-origin';

View File

@@ -1,12 +1,13 @@
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
planFeatureRequiredProblem,
planLimitReachedProblem,
planReadOnlyProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { type PlanCatalogReader, planCatalog } from './catalog';
import { getGraceDays, isBillingEnforced } from './config';
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -90,6 +91,7 @@ type PlanGuardDeps = {
enforced?: boolean;
graceDays?: number;
now?: () => Date;
catalog?: PlanCatalogReader;
};
/**
@@ -123,7 +125,7 @@ export class PlanGuard {
]);
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
const limits = PLAN_LIMITS[resolution.plan];
const limits = await (this.deps.catalog ?? planCatalog).getLimits(resolution.plan);
const usage = { groups, attendees };
const enforced = this.enforced;

View File

@@ -19,8 +19,18 @@ export function countryOf(user: { country: string | null } | null): CountryCode
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
}
/** Where the billing provider sends the professor after authorizing (or abandoning). */
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
/**
* Where the billing provider sends the professor after authorizing (or
* abandoning): a public API route that bounces to the web
* (`GET /billing/return`), because Mercado Pago refuses a `back_url` on
* localhost and the web is not tunneled in local development.
*/
export function buildSubscriptionBackUrl(apiOrigin: string, returnTo: BillingReturnTo): string {
return `${apiOrigin}/api/v1/billing/return?to=${returnTo}`;
}
/** The web page the professor lands on after the provider's checkout. */
export function buildSubscriptionReturnUrl(webOrigin: string, returnTo: BillingReturnTo): string {
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
}

View File

@@ -1,4 +1,13 @@
export { getGraceDays, isBillingEnforced } from './config';
export {
defaultPlanCatalog,
PlanCatalog,
type PlanCatalogReader,
type PlanCatalogSnapshot,
planCatalog,
staticPlanCatalog,
toPlanCatalogDto,
} from './catalog';
export { getApiPublicOrigin, getGraceDays, isBillingEnforced } from './config';
export {
type Entitlements,
exceedsLimits,
@@ -9,5 +18,5 @@ export {
resolvePlan,
type SubscriptionSnapshot,
} from './entitlements';
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
export { buildSubscriptionBackUrl, buildSubscriptionReturnUrl, countryOf, toBillingChargeDto } from './helpers';
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';

View File

@@ -105,6 +105,8 @@ export interface BillingProvider {
/** `null` while the professor has not completed the checkout. */
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
/** New monthly amount from the next charge on; what was already charged stays. */
updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void>;
/** Stops the monthly charge, or voids a checkout never completed. */
cancel(ref: SubscriptionRef): Promise<void>;
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;

View File

@@ -137,6 +137,13 @@ export class MercadoPagoBillingProvider implements BillingProvider {
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
}
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
await this.client.updatePreapprovalAmount(this.tokenFor(ref.country), ref.externalId, {
amount,
currencyId: currency,
});
}
/**
* One URL per country, because each country is a different Gruperly account
* with its own secret. Mercado Pago signs a manifest of the notified id, the

View File

@@ -129,6 +129,23 @@ export async function cancelPreapproval(accessToken: string, id: string): Promis
);
}
/**
* Changes the monthly amount of a live preapproval. Mercado Pago applies it to
* the debits that follow; the ones already made are untouched.
*/
export async function updatePreapprovalAmount(
accessToken: string,
id: string,
input: { amount: number; currencyId: string },
): Promise<MpPreapproval> {
return toPreapproval(
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
method: 'PUT',
body: { auto_recurring: { transaction_amount: input.amount, currency_id: input.currencyId } },
}),
);
}
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
return {
@@ -181,6 +198,7 @@ export type PreapprovalClient = {
createPreapproval: typeof createPreapproval;
getPreapproval: typeof getPreapproval;
cancelPreapproval: typeof cancelPreapproval;
updatePreapprovalAmount: typeof updatePreapprovalAmount;
getAuthorizedPayment: typeof getAuthorizedPayment;
searchAuthorizedPayments: typeof searchAuthorizedPayments;
};
@@ -189,6 +207,7 @@ export const mpPreapprovalClient: PreapprovalClient = {
createPreapproval,
getPreapproval,
cancelPreapproval,
updatePreapprovalAmount,
getAuthorizedPayment,
searchAuthorizedPayments,
};

View File

@@ -214,6 +214,39 @@ export class StripeBillingProvider implements BillingProvider {
}
}
/**
* Moves the subscription to a new monthly amount from its next invoice on:
* the item gets a new inline price on the same product, without proration,
* so the period already paid is not touched.
*/
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
const request = this.request;
const path = `/subscriptions/${encodeURIComponent(ref.externalId)}`;
const subscription = await request(path);
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
const itemId = idOf(item?.id);
const product = idOf(objectOf(item?.price)?.product);
if (!itemId || !product) throw new Error('Stripe subscription came back without its item');
await request(path, {
method: 'POST',
form: {
proration_behavior: 'none',
items: [
{
id: itemId,
price_data: {
currency: currency.toLowerCase(),
unit_amount: toStripeUnitAmount(amount, currency),
recurring: { interval: 'month' },
product,
},
},
],
},
});
}
/** A single endpoint for the whole account; the event id is the dedupe key. */
async parseWebhook(
request: BillingWebhookRequest,

View File

@@ -1,6 +1,8 @@
import { Hono } from 'hono';
import cancelRoute from './features/cancel/route';
import chargesRoute from './features/charges/route';
import plansRoute from './features/plans/route';
import returnRoute from './features/return/route';
import statusRoute from './features/status/route';
import subscribeRoute from './features/subscribe/route';
import webhookRoute from './features/webhook/route';
@@ -11,6 +13,8 @@ routes.route('/', statusRoute);
routes.route('/', subscribeRoute);
routes.route('/', cancelRoute);
routes.route('/', chargesRoute);
routes.route('/', plansRoute);
routes.route('/', returnRoute);
routes.route('/', webhookRoute);
export default routes;

View File

@@ -25,8 +25,14 @@ route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
return c.redirect(new URL('/login', getWebOrigin()).toString());
}
const useCase = new CompleteMpAuthorization();
const result = await useCase.execute({ code, state, error });
let result: Awaited<ReturnType<CompleteMpAuthorization['execute']>>;
try {
result = await new CompleteMpAuthorization().execute({ code, state, error, userId: user.id });
} catch (unexpected) {
// A broken deployment (e.g. TOKEN_ENCRYPTION_KEY) still lands back in the app.
logger.error({ err: unexpected }, 'Mercado Pago callback crashed');
return c.redirect(buildMpReturnUrl(getWebOrigin(), 'settings', { kind: 'error', reason: 'mp_error' }));
}
if (!result.ok) {
logger.warn(

View File

@@ -39,6 +39,8 @@ export class CompleteMpAuthorization {
code?: string;
state?: string;
error?: string;
/** The signed-in teacher; has to be the one who started the flow. */
userId: string;
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
let config: ReturnType<typeof getMpOAuthConfig>;
try {
@@ -70,6 +72,14 @@ export class CompleteMpAuthorization {
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
// A state started by someone else (a link sent to this teacher) would attach
// this teacher's Mercado Pago account to the other account. Not burned: it
// is not this session's to spend.
if (stored.ownerId !== input.userId) {
logger.warn('Mercado Pago callback with a state from another account');
return failure('invalid_state', returnTo);
}
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
// means someone replayed a state we already consumed.
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });

View File

@@ -0,0 +1,39 @@
import type { MiddlewareHandler } from 'hono';
type Env = Record<string, string | undefined>;
function hostOf(value: string | undefined): string | null {
if (!value?.trim()) return null;
try {
return new URL(value.trim()).host;
} catch {
return null;
}
}
/**
* Where a callback that arrived through the public tunnel has to be replayed,
* or `null` when it is already on the origin that holds the session.
*
* In local development Mercado Pago only accepts an HTTPS Redirect URL, so it
* comes back through ngrok, while the session cookie belongs to the API on
* localhost (`BETTER_AUTH_URL`). In production both are the same host and this
* never fires, so it cannot loop behind the proxy.
*/
export function mpCallbackBounceUrl(requestUrl: string, requestHost: string | undefined, env: Env = process.env): string | null {
const tunnelHost = hostOf(env.MP_REDIRECT_URI);
const sessionOrigin = env.BETTER_AUTH_URL?.trim();
const sessionHost = hostOf(sessionOrigin);
if (!tunnelHost || !sessionOrigin || !sessionHost || tunnelHost === sessionHost) return null;
if (requestHost !== tunnelHost) return null;
const url = new URL(requestUrl);
return `${new URL(sessionOrigin).origin}${url.pathname}${url.search}`;
}
/** Runs before the session middleware, which would answer 401 on the tunnel. */
export const mpCallbackOriginMiddleware: MiddlewareHandler = async (c, next) => {
const target = mpCallbackBounceUrl(c.req.url, c.req.header('x-forwarded-host') ?? c.req.header('host'));
if (target) return c.redirect(target);
await next();
};

View File

@@ -1,3 +1,4 @@
export { mpCallbackBounceUrl, mpCallbackOriginMiddleware } from './callback-origin';
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
export {
codeChallengeFromVerifier,

View File

@@ -13,6 +13,8 @@ export type MpCreatePreferenceInput = {
externalReference: string;
/** Where the buyer lands after paying (pending/success/failure). */
backUrl: string;
/** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */
notificationUrl?: string;
};
export type MpPreference = {
@@ -21,6 +23,21 @@ export type MpPreference = {
sandboxInitPoint: string | null;
};
/**
* Mercado Pago refuses `auto_return` (`invalid_auto_return`) and notification
* URLs unless they are public HTTPS. In local development the web is on
* localhost: the buyer then gets MP's "back to the site" button instead of the
* automatic redirect, and without a tunnel only the polling confirms payments.
*/
export function isPublicHttpsUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
} catch {
return false;
}
}
/**
* Creates a Checkout Pro preference in the seller's account. This is a payment
* *link*: nothing is charged, and creating it again after a lost connection is
@@ -50,7 +67,10 @@ export async function createCheckoutPreference(
},
],
external_reference: input.externalReference,
auto_return: 'approved',
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
? { notification_url: input.notificationUrl }
: {}),
back_urls: {
success: input.backUrl,
pending: input.backUrl,
@@ -120,9 +140,10 @@ export async function searchMpPaymentByExternalReference(
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
const results = payload?.results ?? [];
const match = results.find(
(payment) => payment.external_reference === externalReference,
);
// A rejected attempt and a later approved one share the reference: the
// approved one wins, whatever order Mercado Pago lists them in.
const ours = results.filter((payment) => payment.external_reference === externalReference);
const match = ours.find((payment) => payment.status === 'approved') ?? ours[0];
if (!match) {
return null;
}

View File

@@ -15,17 +15,20 @@ import {
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getApiPublicOrigin } from '@/lib/public-origin';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH } from '../../lib';
import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib';
type BatchDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
/** Public origin of the API, where Mercado Pago notifies the payment. */
apiOrigin?: string;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
@@ -128,6 +131,7 @@ export class CreatePaymentBatch {
currencyId: currency,
externalReference: payment.id,
backUrl,
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
});
link = preference;
} catch (error) {

View File

@@ -8,17 +8,20 @@ import {
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getApiPublicOrigin } from '@/lib/public-origin';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, paymentNotificationUrl, toPaymentDto } from '../../lib';
type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
/** Public origin of the API, where Mercado Pago notifies the payment. */
apiOrigin?: string;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
@@ -94,6 +97,7 @@ export class RenewPaymentLink {
currencyId: currency,
externalReference: payment.id,
backUrl,
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
});
} catch (error) {
if (error instanceof Error) {

View File

@@ -0,0 +1,17 @@
import { Hono } from 'hono';
import { problemJson } from '@/http/problem-details';
import { HandleMpPaymentNotification } from './use-case';
const route = new Hono();
/**
* Public (`isPublicApiRequest`): Mercado Pago calls it with the URL each
* Checkout Pro link carries as `notification_url`.
*/
route.post('/webhooks/mp/:paymentId', async (c) => {
const result = await new HandleMpPaymentNotification().execute(c.req.param('paymentId'));
if (!result.ok) return problemJson(c, result.error);
return c.json({ received: true });
});
export default route;

View File

@@ -0,0 +1,45 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { mpProviderErrorProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { MpApiError } from '@/modules/mp/lib';
import { type ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment } from '../../lib';
type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & {
db?: Pick<PrismaClient, 'payment'>;
};
export type MpPaymentNotificationOutcome = ConfirmMpPaymentOutcome | 'ignored';
/**
* Mercado Pago says something happened to the payment of one of our links. The
* body is not read: the payment id in the URL picks the row, and the owner's
* account says whether it was approved (`confirmMpPayment`), so a forged or
* repeated notification costs one lookup and changes nothing.
*/
export class HandleMpPaymentNotification {
constructor(private readonly deps: HandleMpPaymentNotificationDeps = {}) {}
async execute(paymentId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
// OVERDUE too: a student can still pay a link after its due date.
const payment = await db.payment.findFirst({
where: { id: paymentId, status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
select: { id: true, group: { select: { createdById: true } } },
});
if (!payment) return ok({ outcome: 'ignored' });
try {
const outcome = await confirmMpPayment(db, { id: payment.id, ownerId: payment.group.createdById }, this.deps);
return ok({ outcome });
} catch (error) {
if (!(error instanceof MpApiError)) throw error;
// Not a 2xx, so Mercado Pago retries; the polling job is the fallback anyway.
logger.warn({ paymentId: payment.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
return err(mpProviderErrorProblem());
}
}
}

View File

@@ -3,15 +3,13 @@ import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
import { confirmMpPayment } from '../lib';
/**
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
* link is just a preference until someone pays it; this job asks the seller's
* account for our `external_reference` and marks approved payments as PAID.
*
* This is the stopgap and the source of truth: if a webhook is ever added it
* gives you the confirmation, but this job is what keeps the Cobros screen
* correct even when a notification is lost.
* Pulls payments from Mercado Pago. The notification
* (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the
* fallback for links created before it existed and for lost notifications.
* Both go through `confirmMpPayment`.
*/
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
const BATCH_LIMIT = 50;
@@ -51,34 +49,21 @@ export class ReconcilePayments {
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
for (const payment of awaiting) {
const token = await getToken(payment.group.createdById);
if (!token.ok) {
// No usable token (not linked, or needs re-auth). Not a payment problem:
// the row stays PENDING and the account notice tells the professor what to do.
totals.skipped += 1;
continue;
}
try {
const found = await search(token.value.accessToken, payment.id);
if (found && found.status === 'approved' && found.externalReference === payment.id) {
await db.payment.update({
where: { id: payment.id },
data: {
status: 'PAID',
mpPaymentId: found.id,
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
},
});
totals.paid += 1;
}
const outcome = await confirmMpPayment(
db,
{ id: payment.id, ownerId: payment.group.createdById },
{ getToken, search },
);
// No usable token is not a payment problem: the row stays PENDING and
// the account notice tells the professor what to do.
if (outcome === 'no_token') totals.skipped += 1;
if (outcome === 'paid') totals.paid += 1;
} catch (error) {
if (error instanceof MpApiError) {
totals.failed += 1;
} else {
if (!(error instanceof MpApiError)) {
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
totals.failed += 1;
}
totals.failed += 1;
}
}

View File

@@ -0,0 +1,45 @@
import type { PrismaClient } from '@generated/prisma/client';
import { getMpAccessToken } from '@/modules/mp';
import { searchMpPaymentByExternalReference } from '@/modules/mp/lib';
export type ConfirmMpPaymentDeps = {
getToken?: typeof getMpAccessToken;
search?: typeof searchMpPaymentByExternalReference;
};
/** `no_token`: the owner has no usable Mercado Pago link (not linked, or needs re-auth). */
export type ConfirmMpPaymentOutcome = 'paid' | 'unpaid' | 'no_token';
/**
* Asks the owner's Mercado Pago account whether this payment was approved and,
* if so, marks it PAID. The only rule for a Checkout Pro payment, shared by the
* polling job and the notification: whatever triggered it is never trusted, the
* owner's account is. Throws `MpApiError` when Mercado Pago cannot answer.
*/
export async function confirmMpPayment(
db: Pick<PrismaClient, 'payment'>,
payment: { id: string; ownerId: string },
deps: ConfirmMpPaymentDeps = {},
): Promise<ConfirmMpPaymentOutcome> {
const token = await (deps.getToken ?? getMpAccessToken)(payment.ownerId);
if (!token.ok) return 'no_token';
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, payment.id);
if (found?.status !== 'approved' || found.externalReference !== payment.id) return 'unpaid';
await db.payment.update({
where: { id: payment.id },
data: {
status: 'PAID',
mpPaymentId: found.id,
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
},
});
return 'paid';
}
/** Where Mercado Pago notifies a payment of this link (public: see `isPublicApiRequest`). */
export function paymentNotificationUrl(apiOrigin: string, paymentId: string): string {
// `source_news=webhooks`: only the webhook format, not the legacy IPN copy.
return `${apiOrigin}/api/v1/payments/webhooks/mp/${encodeURIComponent(paymentId)}?source_news=webhooks`;
}

View File

@@ -1 +1,7 @@
export {
type ConfirmMpPaymentDeps,
type ConfirmMpPaymentOutcome,
confirmMpPayment,
paymentNotificationUrl,
} from './confirm-mp-payment';
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -3,6 +3,7 @@ import getAllRoute from './features/get-all/route';
import renewRoute from './features/renew/route';
import reportedRoute from './features/reported/route';
import transferDetailsRoute from './features/transfer-details/route';
import webhookRoute from './features/webhook/route';
const routes = new Hono();
@@ -10,5 +11,6 @@ routes.route('/', getAllRoute);
routes.route('/', reportedRoute);
routes.route('/', transferDetailsRoute);
routes.route('/', renewRoute);
routes.route('/', webhookRoute);
export default routes;

View File

@@ -114,6 +114,25 @@ describe('admin access', () => {
expect(db.user.findUnique).not.toHaveBeenCalled();
});
it('forbids the plans to anyone outside the allowlist', async () => {
const app = makeApp('profe@gmail.com');
expect((await app.request('/admin/plans')).status).toBe(403);
expect((await app.request('/admin/plans/FREE/impact?maxGroups=1')).status).toBe(403);
const json = { 'Content-Type': 'application/json' };
const limits = await app.request('/admin/plans/FREE/limits', {
method: 'PUT',
headers: json,
body: JSON.stringify({ maxGroups: 1, maxAttendees: 1, whatsappAutomations: false, mpCharges: false }),
});
expect(limits.status).toBe(403);
const price = await app.request('/admin/plans/prices/AR', {
method: 'PUT',
headers: json,
body: JSON.stringify({ amount: 1, applyToExisting: true }),
});
expect(price.status).toBe(403);
});
it('asks for a session without a user', async () => {
const response = await makeApp(null).request('/admin/accounts');
expect(response.status).toBe(401);

View File

@@ -1,4 +1,5 @@
import { describe, expect, it, mock } from 'bun:test';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
const now = new Date('2026-10-22T12:00:00.000Z');
@@ -18,7 +19,7 @@ function makeDb(params: {
}
function makeGuard(db: ReturnType<typeof makeDb>, enforced = true) {
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now });
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now, catalog: staticPlanCatalog() });
}
describe('resolvePlan', () => {

View File

@@ -0,0 +1,266 @@
import { describe, expect, it, mock } from 'bun:test';
import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { UpdatePlanPrice } from '@/modules/admin/features/update-plan-price/use-case';
import { ApplyPriceChanges } from '@/modules/billing/jobs/apply-price-changes';
import { defaultPlanCatalog, PlanCatalog, PlanGuard, staticPlanCatalog } from '@/modules/billing/lib';
import { MercadoPagoBillingProvider } from '@/modules/billing/providers/mercado-pago';
import { StripeBillingProvider } from '@/modules/billing/providers/stripe';
const decimal = (value: number) => ({ toString: () => String(value) });
function catalogDb(configs: unknown[] = [], prices: unknown[] = []) {
return {
planConfig: { findMany: mock(async () => configs) },
planPrice: { findMany: mock(async () => prices) },
};
}
describe('PlanCatalog', () => {
it('falls back to the shared defaults when the tables are empty', async () => {
const catalog = new PlanCatalog({ db: catalogDb() as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
expect(await catalog.getProPrice('AR')).toBe(PRO_PRICE_BY_COUNTRY.AR);
});
it('reads the limits and prices edited from the backoffice', async () => {
const db = catalogDb(
[{ plan: 'FREE', maxGroups: 2, maxAttendees: 30, whatsappAutomations: true, mpCharges: false }],
[{ country: 'AR', amount: decimal(18000) }, { country: 'XX', amount: decimal(1) }],
);
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual({
maxGroups: 2,
maxAttendees: 30,
whatsappAutomations: true,
mpCharges: false,
});
expect(await catalog.getLimits('PRO')).toEqual(PLAN_LIMITS.PRO);
expect(await catalog.getProPrice('AR')).toBe(18000);
expect(await catalog.getProPrice('MX')).toBe(PRO_PRICE_BY_COUNTRY.MX);
});
it('caches within the TTL until invalidated', async () => {
let clock = 0;
const db = catalogDb();
const catalog = new PlanCatalog({ db: db as never, ttlMs: 1000, now: () => clock });
await catalog.snapshot();
clock = 500;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(1);
catalog.invalidate();
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
clock = 2000;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(3);
});
it('keeps working on the defaults if the database fails, without caching them', async () => {
const db = {
planConfig: { findMany: mock(async () => Promise.reject(new Error('down'))) },
planPrice: { findMany: mock(async () => []) },
};
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
});
it('feeds the PlanGuard', async () => {
const snapshot = defaultPlanCatalog();
snapshot.limits.FREE = { ...snapshot.limits.FREE, maxGroups: 3 };
const guard = new PlanGuard({
enforced: true,
catalog: staticPlanCatalog(snapshot),
db: {
billingSubscription: { findUnique: async () => null },
group: { count: async () => 2 },
person: { count: async () => 0 },
} as never,
});
expect((await guard.canCreateGroup('owner-1')).ok).toBe(true);
});
});
function priceTx(updated = 3) {
const tx = {
planPrice: { upsert: mock(async () => ({})) },
planPriceChange: { create: mock(async () => ({ id: 'change-1' })), update: mock(async () => ({})) },
billingSubscription: { updateMany: mock(async () => ({ count: updated })) },
};
const db = { $transaction: mock(async (run: (client: typeof tx) => unknown) => run(tx)) };
return { tx, db };
}
describe('UpdatePlanPrice', () => {
const catalog = { invalidate: mock(), getProPrice: mock(async () => 15000) };
it('queues the live subscriptions of the country and kicks the job', async () => {
const { tx, db } = priceTx(3);
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: true },
'staff-1',
);
expect(result).toEqual({ ok: true, value: { country: 'AR', amount: 18000, queued: 3 } });
expect(tx.planPrice.upsert).toHaveBeenCalled();
expect(tx.planPriceChange.create.mock.calls[0]?.[0]).toMatchObject({
data: { country: 'AR', previousAmount: 15000, newAmount: 18000, currency: 'ARS', applyToExisting: true },
});
expect(tx.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: {
country: 'AR',
status: { in: ['AUTHORIZED', 'PAUSED'] },
externalId: { not: null },
},
});
expect(tx.planPriceChange.update).toHaveBeenCalledWith({ where: { id: 'change-1' }, data: { queued: 3 } });
expect(catalog.invalidate).toHaveBeenCalled();
expect(applyQueued).toHaveBeenCalledTimes(1);
});
it('only changes the price for new subscriptions when not applied to existing ones', async () => {
const { tx, db } = priceTx();
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: false },
'staff-1',
);
expect(result.ok && result.value.queued).toBe(0);
expect(tx.billingSubscription.updateMany).not.toHaveBeenCalled();
expect(applyQueued).not.toHaveBeenCalled();
});
});
function row(overrides: Record<string, unknown> = {}) {
return {
id: 'sub-1',
country: 'AR',
currency: 'ARS',
provider: 'MERCADO_PAGO',
status: 'AUTHORIZED',
externalId: 'pre-1',
checkoutRef: null,
amount: decimal(15000),
pendingAmount: decimal(18000),
nextPaymentDate: new Date('2026-12-05T12:00:00.000Z'),
user: { name: 'Ana', email: 'ana@gruperly.test', country: 'AR' },
...overrides,
};
}
function applyHarness(rows: unknown[], { fail = false, moved = 1 } = {}) {
const db = {
billingSubscription: {
findMany: mock(async () => rows),
updateMany: mock(async () => ({ count: moved })),
},
};
const provider = {
updateAmount: mock(async () => {
if (fail) throw new Error('boom');
}),
};
const email = { sendProPriceChanged: mock(async () => {}) };
const job = new ApplyPriceChanges({
db: db as never,
providers: () => provider as never,
email,
webOrigin: 'http://web',
});
return { db, provider, email, job };
}
describe('ApplyPriceChanges', () => {
it('pushes the price to the provider, moves it to amount and emails the professor', async () => {
const pending = row();
const { db, provider, email, job } = applyHarness([pending]);
expect(await job.execute()).toEqual({ applied: 1, failed: 0, dropped: 0 });
expect(provider.updateAmount).toHaveBeenCalledWith(
{ country: 'AR', externalId: 'pre-1', checkoutRef: null },
18000,
'ARS',
);
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
where: { id: 'sub-1', pendingAmount: pending.pendingAmount },
data: { amount: pending.pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
});
expect(email.sendProPriceChanged).toHaveBeenCalledTimes(1);
const sent = (email.sendProPriceChanged.mock.calls[0] as unknown[])[0] as Record<string, string>;
expect(sent).toMatchObject({ email: 'ana@gruperly.test', name: 'Ana', billingUrl: 'http://web/billing' });
expect(sent.amount).toContain('18.000');
});
it('counts a refusal as an attempt and keeps the change queued', async () => {
const { db, email, job } = applyHarness([row()], { fail: true });
expect(await job.execute()).toEqual({ applied: 0, failed: 1, dropped: 0 });
expect(db.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: 'provider_error' },
});
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
it('drops the change of a subscription cancelled meanwhile', async () => {
const { provider, job } = applyHarness([row({ status: 'CANCELLED' })]);
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 1 });
expect(provider.updateAmount).not.toHaveBeenCalled();
});
it('does not email twice when another instance already applied it', async () => {
const { email, job } = applyHarness([row()], { moved: 0 });
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 0 });
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
});
describe('updateAmount', () => {
it('Mercado Pago changes the preapproval amount', async () => {
const client = { updatePreapprovalAmount: mock(async () => ({})) };
const provider = new MercadoPagoBillingProvider({
client: client as never,
credentials: () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }),
});
await provider.updateAmount({ country: 'AR', externalId: 'pre-1', checkoutRef: null }, 18000, 'ARS');
expect(client.updatePreapprovalAmount).toHaveBeenCalledWith('platform-token', 'pre-1', {
amount: 18000,
currencyId: 'ARS',
});
});
it('Stripe reprices the item on its product without proration', async () => {
const calls: { method: string; path: string; body: URLSearchParams | null }[] = [];
const fetch = mock(async (input: string, init: RequestInit) => {
const method = init.method ?? 'GET';
calls.push({
method,
path: new URL(input).pathname,
body: init.body ? new URLSearchParams(String(init.body)) : null,
});
return new Response(
JSON.stringify({ id: 'sub_1', items: { data: [{ id: 'si_1', price: { product: 'prod_1' } }] } }),
);
});
const provider = new StripeBillingProvider({
config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }),
fetch: fetch as never,
});
await provider.updateAmount({ country: 'MX', externalId: 'sub_1', checkoutRef: null }, 249, 'MXN');
expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([
'GET /v1/subscriptions/sub_1',
'POST /v1/subscriptions/sub_1',
]);
const body = calls[1]?.body;
expect(body?.get('proration_behavior')).toBe('none');
expect(body?.get('items[0][id]')).toBe('si_1');
expect(body?.get('items[0][price_data][product]')).toBe('prod_1');
expect(body?.get('items[0][price_data][unit_amount]')).toBe('24900');
expect(body?.get('items[0][price_data][currency]')).toBe('mxn');
expect(body?.get('items[0][price_data][recurring][interval]')).toBe('month');
});
});

View File

@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { Hono } from 'hono';
import { isPublicApiRequest } from '@/http/session-auth';
import returnRoute from '@/modules/billing/features/return/route';
import { getApiPublicOrigin } from '@/modules/billing/lib';
const previousWebUrl = process.env.WEB_URL;
function makeApp() {
return new Hono().basePath('/api/v1').route('/billing', returnRoute);
}
describe('GET /billing/return', () => {
afterEach(() => {
process.env.WEB_URL = previousWebUrl;
});
it('bounces the browser to the billing screen of the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=billing&preapproval_id=pre-1');
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('goes back to the onboarding step when it started there', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=onboarding');
expect(res.headers.get('location')).toBe('https://app.example.com/onboarding?sub=return');
});
it('never redirects anywhere but the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=https://evil.example');
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('is reachable without a session', () => {
expect(isPublicApiRequest('GET', '/api/v1/billing/return')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/billing/return')).toBe(false);
});
});
describe('getApiPublicOrigin', () => {
it('prefers API_PUBLIC_URL, then BETTER_AUTH_URL, then localhost', () => {
expect(
getApiPublicOrigin({ API_PUBLIC_URL: 'https://x.ngrok-free.app/', BETTER_AUTH_URL: 'http://localhost:4000' }),
).toBe('https://x.ngrok-free.app');
expect(getApiPublicOrigin({ BETTER_AUTH_URL: 'https://app.example.com' })).toBe('https://app.example.com');
expect(getApiPublicOrigin({})).toBe('http://localhost:4000');
expect(getApiPublicOrigin({ API_PUBLIC_URL: 'not a url' })).toBe('http://localhost:4000');
});
});

View File

@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import type { BillingProvider } from '@/modules/billing/providers';
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
@@ -53,7 +54,7 @@ function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
return {
client,
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute(
new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider, apiOrigin: 'https://api', now: () => now }).execute(
userId,
{ payerEmail: 'profe@mail.com', returnTo },
),
@@ -79,7 +80,7 @@ describe('Subscribe', () => {
payerEmail: 'profe@mail.com',
amount: 15000,
currencyId: 'ARS',
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect(db.billingSubscription.update).toHaveBeenCalledWith({
@@ -93,7 +94,7 @@ describe('Subscribe', () => {
await run('onboarding');
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
backUrl: 'http://web/onboarding?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=onboarding',
});
});
@@ -131,7 +132,7 @@ describe('Subscribe', () => {
const db = makeDb(null, 'AR');
const client = makeClient();
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
payerEmail: 'profe@mail.com',
returnTo: 'billing',
});
@@ -224,13 +225,13 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const stripe = fakeStripe();
const resolved: string[] = [];
const result = await new Subscribe({
const result = await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => {
resolved.push(id);
return stripe;
},
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -242,7 +243,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
amount: 199,
currency: 'MXN',
payerEmail: null,
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
@@ -261,10 +262,10 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const mp = mpProvider(client);
const stripe = fakeStripe();
await new Subscribe({
await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -275,7 +276,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'CL');
const stripe = fakeStripe({ isAvailable: () => false });
const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => stripe }).execute(userId, {
returnTo: 'billing',
});
@@ -288,7 +289,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'AR');
const provider = mpProvider(makeClient());
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
returnTo: 'billing',
});

View File

@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { createCheckoutPreference, isPublicHttpsUrl, searchMpPaymentByExternalReference } from '@/modules/mp/lib/mp-http';
describe('isPublicHttpsUrl', () => {
it('only asks Mercado Pago for the automatic return on public HTTPS', () => {
expect(isPublicHttpsUrl('https://app.gruperly.com/student/payments')).toBe(true);
expect(isPublicHttpsUrl('http://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('https://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('http://app.gruperly.com/student/payments')).toBe(false);
expect(isPublicHttpsUrl('not a url')).toBe(false);
});
});
describe('createCheckoutPreference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
async function sentBody(input: { backUrl: string; notificationUrl?: string }) {
let body: Record<string, unknown> = {};
globalThis.fetch = (async (_url: string, init: RequestInit) => {
body = JSON.parse(String(init.body));
return new Response(JSON.stringify({ id: 'pref-1', init_point: 'https://mp/pay' }), { status: 201 });
}) as unknown as typeof fetch;
await createCheckoutPreference('token', {
title: 'Octubre',
unitPrice: 100,
currencyId: 'ARS',
externalReference: 'pay-1',
...input,
});
return body;
}
it('asks for the automatic return and the notification on public HTTPS', async () => {
const body = await sentBody({
backUrl: 'https://app.gruperly.com/student/payments',
notificationUrl: 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(body.auto_return).toBe('approved');
expect(body.notification_url).toBe(
'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
);
});
it('leaves both out on localhost, which Mercado Pago refuses', async () => {
const body = await sentBody({
backUrl: 'http://localhost:6173/student/payments',
notificationUrl: 'http://localhost:4000/api/v1/payments/webhooks/mp/pay-1',
});
expect(body).not.toHaveProperty('auto_return');
expect(body).not.toHaveProperty('notification_url');
});
});
describe('searchMpPaymentByExternalReference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
it('prefers the approved attempt over an earlier rejected one', async () => {
globalThis.fetch = (async () =>
new Response(
JSON.stringify({
results: [
{ id: 1, status: 'rejected', external_reference: 'pay-1' },
{ id: 2, status: 'approved', external_reference: 'pay-1', date_approved: '2026-11-11T03:00:00.000Z' },
],
}),
{ status: 200 },
)) as unknown as typeof fetch;
const found = await searchMpPaymentByExternalReference('token', 'pay-1');
expect(found).toMatchObject({ id: '2', status: 'approved' });
});
});

View File

@@ -27,6 +27,7 @@ import prisma from '@/lib/prisma';
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account';
import { mpCallbackBounceUrl } from '@/modules/mp/lib/callback-origin';
import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
@@ -579,6 +580,17 @@ describe('modules/mp', () => {
expect(location.href).not.toContain(storedState.codeVerifier);
});
it('refuses a state started by another teacher, without spending it', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue({ ...storedState, ownerId: otherOwnerId });
const res = await makeApp({ id: ownerId }).request(callbackUrl('?code=auth-code-123&state=state-abc'));
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(prisma.mpOAuthState.deleteMany).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('sends a teacher without a session to the login screen', async () => {
const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc'));
@@ -1040,3 +1052,30 @@ describe('modules/mp RefreshExpiringMpTokens', () => {
expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 });
});
});
describe('mpCallbackBounceUrl', () => {
const env = {
MP_REDIRECT_URI: 'https://tunnel.ngrok-free.app/api/v1/mp/callback',
BETTER_AUTH_URL: 'http://localhost:4000',
};
const url = 'https://tunnel.ngrok-free.app/api/v1/mp/callback?code=c&state=s';
it('replays a callback that came through the tunnel on the origin with the session', () => {
expect(mpCallbackBounceUrl(url, 'tunnel.ngrok-free.app', env)).toBe(
'http://localhost:4000/api/v1/mp/callback?code=c&state=s',
);
});
it('leaves it alone once it is on the session origin', () => {
expect(mpCallbackBounceUrl('http://localhost:4000/api/v1/mp/callback?code=c', 'localhost:4000', env)).toBeNull();
});
it('never fires when the redirect and the session share a host (production)', () => {
const prod = {
MP_REDIRECT_URI: 'https://app.gruperly.com/api/v1/mp/callback',
BETTER_AUTH_URL: 'https://app.gruperly.com',
};
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'app.gruperly.com', prod)).toBeNull();
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'api:4000', prod)).toBeNull();
});
});

View File

@@ -69,7 +69,7 @@ function batchUseCase() {
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
}));
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' });
}
describe('create payments batch', () => {
@@ -143,6 +143,7 @@ describe('create payments batch', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
});
@@ -191,7 +192,7 @@ describe('create payments batch', () => {
throw new Error('should not be called');
});
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute(
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'group-1',
userId,
{ dueDate: '2026-10-05T12:00:00.000Z' },

View File

@@ -83,7 +83,7 @@ describe('renew payment link', () => {
sandboxInitPoint: null,
}));
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'pay-1',
userId,
);
@@ -102,6 +102,7 @@ describe('renew payment link', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },

View File

@@ -0,0 +1,103 @@
import { describe, expect, it, mock } from 'bun:test';
import { isPublicApiRequest } from '@/http/session-auth';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
import { HandleMpPaymentNotification } from '@/modules/payments/features/webhook/use-case';
import { paymentNotificationUrl } from '@/modules/payments/lib';
const ownerId = 'user-1';
const tokenOk = () =>
mock(async () => ({ ok: true, value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() } }));
function makeDb(row: unknown) {
return {
payment: {
findFirst: mock(async () => row),
update: mock(async () => ({})),
},
};
}
const linked = { id: 'pay-1', group: { createdById: ownerId } };
describe('HandleMpPaymentNotification', () => {
it('marks the payment PAID once the owner account confirms it was approved', async () => {
const db = makeDb(linked);
const getToken = tokenOk();
const search = mock(async () => ({
id: '999',
status: 'approved',
externalReference: 'pay-1',
liveMode: true,
dateApproved: '2026-11-11T03:00:00.000Z',
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken, search }).execute('pay-1');
expect(result).toEqual({ ok: true, value: { outcome: 'paid' } });
expect(getToken).toHaveBeenCalledWith(ownerId);
expect(search).toHaveBeenCalledWith('token-1', 'pay-1');
expect(db.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { status: 'PAID', mpPaymentId: '999', paidAt: new Date('2026-11-11T03:00:00.000Z') },
});
expect(db.payment.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 'pay-1', status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
}),
);
});
it('changes nothing while the payment is not approved', async () => {
const db = makeDb(linked);
const search = mock(async () => ({
id: '999',
status: 'rejected',
externalReference: 'pay-1',
liveMode: true,
dateApproved: null,
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result).toEqual({ ok: true, value: { outcome: 'unpaid' } });
expect(db.payment.update).not.toHaveBeenCalled();
});
it('ignores an unknown, already paid or link-less payment without asking Mercado Pago', async () => {
const db = makeDb(null);
const search = mock(async () => null);
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-x',
);
expect(result).toEqual({ ok: true, value: { outcome: 'ignored' } });
expect(search).not.toHaveBeenCalled();
});
it('answers an error when Mercado Pago cannot be asked, so it retries', async () => {
const db = makeDb(linked);
const search = mock(async () => {
throw new MpApiError(503, null);
});
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result.ok).toBe(false);
expect(db.payment.update).not.toHaveBeenCalled();
});
});
describe('payment notification URL', () => {
it('points at the public payment webhook, which needs no session', () => {
const url = paymentNotificationUrl('https://x.ngrok-free.app', 'cmabc123');
expect(url).toBe('https://x.ngrok-free.app/api/v1/payments/webhooks/mp/cmabc123?source_news=webhooks');
expect(isPublicApiRequest('POST', new URL(url).pathname)).toBe(true);
expect(isPublicApiRequest('GET', new URL(url).pathname)).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/a/b')).toBe(false);
});
});

View File

@@ -95,6 +95,8 @@ describe('computeStudentAlerts: pagos', () => {
gravedad: 'vigilar',
etiqueta: 'Cuota vencida',
detalle: 'La cuota de octubre venció el 10/10.',
razon: 'cuota',
valores: { cuotas: 1, vencimientos: ['2026-10-10T12:00:00.000Z'] },
firma: 'pay_1',
peso: 1,
},

3
apps/web/bunfig.toml Normal file
View File

@@ -0,0 +1,3 @@
[test]
# Inicializa i18n en es-AR: los tests asertan el copy en español.
preload = ["./test/setup.ts"]

View File

@@ -3,8 +3,10 @@
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
# es first-party y el CORS del backend queda como red de seguridad.
# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive
# a un recreate del contenedor (que cambia la IP).
# DNS interno de Docker: resuelve `gruperly-api` en cada request, así el proxy
# sobrevive a un recreate del contenedor (que cambia la IP). Es un alias que el
# compose define solo en la red propia del stack; `api` también existe en
# dokploy-network y con dev y prod en el mismo server resolvería a cualquiera.
resolver 127.0.0.11 valid=10s ipv6=off;
server {
@@ -18,7 +20,7 @@ server {
# ── API ────────────────────────────────────────────────────────────────────
location /api/ {
set $api http://api:4000;
set $api http://gruperly-api:4000;
proxy_pass $api$request_uri;
proxy_http_version 1.1;

View File

@@ -21,10 +21,12 @@
"@tanstack/react-router": "^1.170.38",
"better-auth": "1.7.2",
"clsx": "^2.1.1",
"i18next": "^26.5.11",
"lucide-react": "^1.34.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.54.0",
"react-i18next": "^17.1.9",
"tailwind-merge": "^3.6.0",
"zod": "3.24.2"
},

View File

@@ -1,15 +1,17 @@
import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
import { NavBadge } from './NavBadge'
import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function BottomNav() {
const location = useLocation()
const { t } = useTranslation('layout')
return (
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
<div className="mx-auto grid max-w-md grid-cols-4">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
{NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to)
return (
<Link
@@ -32,7 +34,7 @@ export function BottomNav() {
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
</span>
<span className="leading-none">{label}</span>
<span className="leading-none">{t(labelKey)}</span>
</Link>
)
})}

View File

@@ -1,52 +1,55 @@
import { Link, useLocation } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react'
import { useTranslation } from 'react-i18next'
type Crumb = { label: string; to?: string }
type CrumbKey = 'home' | 'groups' | 'payments' | 'settings' | 'security' | 'profile'
type Crumb = { label: CrumbKey; to?: string }
const BREADCRUMBS: Record<string, Crumb[]> = {
'/': [{ label: 'Inicio' }],
'/': [{ label: 'home' }],
'/groups': [
{ label: 'Inicio', to: '/' },
{ label: 'Grupos' },
{ label: 'home', to: '/' },
{ label: 'groups' },
],
'/payments': [
{ label: 'Inicio', to: '/' },
{ label: 'Cobros' },
{ label: 'home', to: '/' },
{ label: 'payments' },
],
'/settings': [
{ label: 'Inicio', to: '/' },
{ label: 'Ajustes' },
{ label: 'home', to: '/' },
{ label: 'settings' },
],
'/security': [
{ label: 'Inicio', to: '/' },
{ label: 'Ajustes', to: '/settings' },
{ label: 'Seguridad' },
{ label: 'home', to: '/' },
{ label: 'settings', to: '/settings' },
{ label: 'security' },
],
'/profile': [
{ label: 'Inicio', to: '/' },
{ label: 'Mi perfil' },
{ label: 'home', to: '/' },
{ label: 'profile' },
],
}
export function Breadcrumb() {
const location = useLocation()
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'Inicio' }]
const { t } = useTranslation('layout')
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'home' }]
return (
<nav aria-label="Breadcrumb" className="hidden items-center gap-1.5 text-sm lg:flex">
<nav aria-label={t('breadcrumb')} className="hidden items-center gap-1.5 text-sm lg:flex">
{crumbs.map((crumb, i) => {
const isLast = i === crumbs.length - 1
return (
<span key={crumb.label} className="flex items-center gap-1.5">
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
{isLast ? (
<span className="font-medium text-primary">{crumb.label}</span>
<span className="font-medium text-primary">{t(`nav.${crumb.label}`)}</span>
) : (
<Link
to={crumb.to!}
className="text-foreground/50 transition-colors hover:text-primary"
>
{crumb.label}
{t(`nav.${crumb.label}`)}
</Link>
)}
</span>

View File

@@ -1,10 +1,12 @@
import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { Logo } from '../brand'
import { Breadcrumb } from './Breadcrumb'
import { ThemeToggle } from './ThemeToggle'
import { UserMenu } from './UserMenu'
export function Header() {
const { t } = useTranslation('layout')
return (
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
@@ -12,7 +14,7 @@ export function Header() {
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
home screen and an anchor would reload the whole document, losing
the in-memory state (React Query cache, install event). */}
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
<Link to="/" className="flex items-center lg:hidden" aria-label={t('homeLink')}>
<Logo className="h-8" />
</Link>
<Breadcrumb />

View File

@@ -1,10 +1,12 @@
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
number is in the accessible name too (sr-only), not only in the dot. */
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
const count = useReportedPaymentsCount()
const { t } = useTranslation('layout')
if (kind !== 'reported-payments' || count === 0) return null
return (
<span
@@ -13,8 +15,8 @@ export function NavBadge({ kind, className }: { kind: 'reported-payments'; class
className,
)}
>
{count > 99 ? '99+' : count}
<span className="sr-only"> pagos para verificar</span>
<span aria-hidden="true">{count > 99 ? '99+' : count}</span>
<span className="sr-only">{t('reportedPayments', { count })}</span>
</span>
)
}

View File

@@ -1,7 +1,10 @@
import { useTranslation } from 'react-i18next'
export function PublicFooter() {
const { t } = useTranslation('layout')
return (
<footer className="border-t border-border px-4 py-4 text-center text-xs text-foreground/40">
Gruperly — Gestión sencilla de cobros y grupos
{t('publicFooter')}
</footer>
)
}

View File

@@ -1,4 +1,5 @@
import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
import { Logo } from '../brand'
import { NavBadge } from './NavBadge'
@@ -6,6 +7,7 @@ import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
const location = useLocation()
const { t } = useTranslation('layout')
return (
// Without the global header there's nothing to clear above: the sidebar
@@ -19,12 +21,12 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
>
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
in-memory state (React Query cache, install event). */}
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
<Link to="/" className="mb-8 flex items-center px-1" aria-label={t('homeLink')}>
<Logo className="h-10" />
</Link>
<nav className="flex flex-col gap-1">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
{NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to)
return (
<Link
@@ -39,7 +41,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
)}
>
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
{label}
{t(labelKey)}
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
</Link>
)

View File

@@ -1,14 +1,16 @@
import { Moon, Sun } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useTheme } from '../../context/ThemeProvider'
export function ThemeToggle() {
const { isDark, setTheme } = useTheme()
const { t } = useTranslation('layout')
return (
<button
type="button"
onClick={() => setTheme(isDark ? 'light' : 'dark')}
aria-label={isDark ? 'Cambiar a tema claro' : 'Cambiar a tema oscuro'}
aria-label={isDark ? t('theme.toLight') : t('theme.toDark')}
className="flex size-9 items-center justify-center rounded-full border border-border text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary"
>
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Link, useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { ChevronDown, LogOut, Settings, ShieldCheck, UserRound, X } from 'lucide-react'
import { cn } from '../../lib/utils'
import { signOut } from '../../lib/auth-client'
@@ -18,6 +19,7 @@ export function UserMenu() {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
const navigate = useNavigate()
const { t } = useTranslation(['layout', 'common'])
// Solo el equipo de Gruperly ve el acceso al backoffice.
const isAdmin = useAdminAccess(!!user).data?.isAdmin ?? false
@@ -65,7 +67,7 @@ export function UserMenu() {
>
<Avatar name={user?.name} src={user?.image ?? undefined} className="size-8 lg:size-9" />
<span className="hidden max-w-40 flex-col items-start leading-tight lg:flex">
<span className="truncate text-sm font-medium text-primary">{user?.name ?? 'Usuario'}</span>
<span className="truncate text-sm font-medium text-primary">{user?.name ?? t('common:user.fallbackName')}</span>
</span>
<ChevronDown
className={cn(
@@ -88,7 +90,7 @@ export function UserMenu() {
<button
type="button"
onClick={() => setOpen(false)}
aria-label="Cerrar menú"
aria-label={t('userMenu.close')}
className="absolute right-4 top-4 z-20 rounded-full bg-surface/90 p-2 text-foreground/70 shadow-md backdrop-blur transition-colors hover:bg-surface"
>
<X className="size-5" />
@@ -102,7 +104,7 @@ export function UserMenu() {
/>
<div>
<p className="text-base font-semibold text-primary">
{user?.name ?? 'Usuario'}
{user?.name ?? t('common:user.fallbackName')}
</p>
<p className="text-sm text-foreground/50">{user?.email}</p>
</div>
@@ -116,7 +118,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<UserRound className="size-5 text-foreground/60" />
Mi perfil
{t('userMenu.profile')}
</Link>
<Link
role="menuitem"
@@ -125,7 +127,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<Settings className="size-5 text-foreground/60" />
Ajustes
{t('userMenu.settings')}
</Link>
{isAdmin ? (
<Link
@@ -135,7 +137,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<ShieldCheck className="size-5 text-foreground/60" />
Backoffice
{t('userMenu.admin')}
</Link>
) : null}
</div>
@@ -150,7 +152,7 @@ export function UserMenu() {
)}
>
<LogOut className="size-5 text-foreground/60" />
Cerrar sesión
{t('userMenu.signOut')}
</button>
</div>
</div>
@@ -164,28 +166,28 @@ export function UserMenu() {
className="absolute right-0 top-full z-50 mt-2 w-60 rounded-xl border border-border bg-surface p-1.5 shadow-lg"
>
<div className="px-3 py-2">
<p className="truncate text-sm font-semibold text-primary">{user?.name ?? 'Usuario'}</p>
<p className="truncate text-sm font-semibold text-primary">{user?.name ?? t('common:user.fallbackName')}</p>
<p className="truncate text-xs text-foreground/50">{user?.email}</p>
</div>
<div className="mx-3 my-1 h-px bg-border" />
<Link role="menuitem" to="/profile" onClick={() => setOpen(false)} className={itemClass}>
<UserRound className="size-4 text-foreground/60" />
Mi perfil
{t('userMenu.profile')}
</Link>
<Link role="menuitem" to="/settings" onClick={() => setOpen(false)} className={itemClass}>
<Settings className="size-4 text-foreground/60" />
Ajustes
{t('userMenu.settings')}
</Link>
{isAdmin ? (
<Link role="menuitem" to="/admin" onClick={() => setOpen(false)} className={itemClass}>
<ShieldCheck className="size-4 text-foreground/60" />
Backoffice
{t('userMenu.admin')}
</Link>
) : null}
<div className="mx-3 my-1 h-px bg-border" />
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
<LogOut className="size-4 text-foreground/60" />
Cerrar sesión
{t('userMenu.signOut')}
</button>
</div>
) : null}

View File

@@ -1,7 +1,8 @@
import { Home, Users, Wallet, Settings, type LucideIcon } from 'lucide-react'
export type NavItem = {
label: string
/** Clave en el namespace `layout` (`nav.*`). */
labelKey: 'nav.home' | 'nav.groups' | 'nav.payments' | 'nav.settings'
to: string
icon: LucideIcon
/** Counter shown on the item (see NavBadge). */
@@ -9,10 +10,10 @@ export type NavItem = {
}
export const NAV_ITEMS: NavItem[] = [
{ label: 'Inicio', to: '/', icon: Home },
{ label: 'Grupos', to: '/groups', icon: Users },
{ label: 'Cobros', to: '/payments', icon: Wallet, badge: 'reported-payments' },
{ label: 'Ajustes', to: '/settings', icon: Settings },
{ labelKey: 'nav.home', to: '/', icon: Home },
{ labelKey: 'nav.groups', to: '/groups', icon: Users },
{ labelKey: 'nav.payments', to: '/payments', icon: Wallet, badge: 'reported-payments' },
{ labelKey: 'nav.settings', to: '/settings', icon: Settings },
]
/** A section stays active within its subroutes: on `/groups/abc` the active

View File

@@ -2,7 +2,7 @@ import { forwardRef, type ButtonHTMLAttributes } from 'react'
import { cn } from '../../lib/utils'
export type ButtonVariant = 'primary' | 'ghost' | 'outline'
export type ButtonSize = 'sm' | 'md' | 'icon'
export type ButtonSize = 'sm' | 'md' | 'lg' | 'icon'
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: ButtonVariant
@@ -18,6 +18,8 @@ const variants: Record<ButtonVariant, string> = {
const sizes: Record<ButtonSize, string> = {
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
// Acciones principales de un flujo en mobile: 48px, cómodo para el pulgar.
lg: 'h-12 px-5 text-sm',
icon: 'size-9',
}

View File

@@ -0,0 +1,19 @@
import { useTranslation } from 'react-i18next'
import { validationMessage } from '../../i18n'
import { cn } from '../../lib/utils'
type FieldErrorProps = {
/** El `message` del error del form: una clave de validación o un texto. */
message?: string
className?: string
}
/** Error de un campo, traducido. Los esquemas llevan claves (`email.invalid`)
* y acá se pasan al idioma de la UI. */
export function FieldError({ message, className }: FieldErrorProps) {
// Suscribe el componente al cambio de idioma.
useTranslation('validation')
const text = validationMessage(message)
if (!text) return null
return <p className={cn('mt-1 text-sm text-danger', className)}>{text}</p>
}

View File

@@ -9,3 +9,4 @@ export { Tooltip, type TooltipProps } from './tooltip'
export { Switch, type SwitchProps } from './switch'
export { Sheet, type SheetProps } from './sheet'
export { FieldError } from './field-error'

View File

@@ -1,6 +1,7 @@
import { useEffect, type ReactNode } from 'react';
import { X } from 'lucide-react';
import { cn } from '../../lib/utils';
import { i18n } from '../../i18n/instance';
export type ModalProps = {
isOpen: boolean;
@@ -78,7 +79,7 @@ export function Modal({
type="button"
onClick={onClose}
className="shrink-0 -mr-2 -mt-2 p-2 rounded-xl text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
aria-label="Cerrar modal"
aria-label={i18n.t('actions.close')}
>
<X className="size-5" />
</button>

View File

@@ -1,6 +1,7 @@
import { useEffect, useId, useRef, type ReactNode } from 'react'
import { X } from 'lucide-react'
import { cn } from '../../lib/utils'
import { i18n } from '../../i18n/instance'
export type SheetProps = {
isOpen: boolean
@@ -72,7 +73,7 @@ export function Sheet({ isOpen, onClose, title, description, children, className
type="button"
onClick={onClose}
className="-mr-2 -mt-2 flex size-11 shrink-0 items-center justify-center rounded-xl text-foreground hover:bg-primary-soft hover:text-primary"
aria-label="Cerrar"
aria-label={i18n.t('actions.close')}
>
<X className="size-5" />
</button>

View File

@@ -8,6 +8,7 @@ import {
} from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import { cn } from '../../lib/utils';
import { i18n } from '../../i18n/instance';
export type ToastType = 'success' | 'error' | 'info';
@@ -126,7 +127,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
type="button"
onClick={() => removeToast(toast.id)}
className="shrink-0 -mr-1 -mt-1 p-1 rounded-lg text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
aria-label="Cerrar notificación"
aria-label={i18n.t('toast.close')}
>
<X className="size-4" />
</button>

View File

@@ -4,6 +4,8 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import type { AbsenceDetails } from '@gruperly/shared'
import { useToast } from '../../components/ui'
import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api'
import { errorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
type AbsenceNotifyContextValue = {
token: string
@@ -32,14 +34,14 @@ export function AbsenceNotifyProvider({ token, children }: { token: string; chil
mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }),
onSuccess: (_data, sessionId) => {
setLocallyNotified((prev) => [...prev, sessionId])
toast.success('Tu profesor ya tiene registrado el aviso. Gracias por avisar.', 'Ausencia avisada')
toast.success(i18n.t('public:absence.done'), i18n.t('public:absence.doneTitle'))
},
onError: (error: unknown) => {
if (error instanceof ApiError && error.problem?.status === 404) {
toast.error('Este enlace ya no es válido. Consultá a tu profesor.')
toast.error(i18n.t('public:absence.invalidLink'))
return
}
toast.error(error instanceof Error ? error.message : 'No pudimos registrar el aviso.')
toast.error(errorMessage(error, i18n.t('public:absence.error')))
},
})

View File

@@ -3,9 +3,11 @@ import { PublicFooter, PublicHeader } from '../../components/layout'
import { Badge } from '../../components/ui'
import { AbsenceSessionRow } from './AbsenceSessionRow'
import { useAbsenceNotify } from './AbsenceNotifyProvider'
import { Trans, useTranslation } from 'react-i18next'
export function AbsenceNotifyView() {
const { details, detailsPending, detailsFailed } = useAbsenceNotify()
const { t } = useTranslation('public')
return (
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
@@ -16,15 +18,15 @@ export function AbsenceNotifyView() {
{detailsPending ? (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<Loader2 className="size-8 animate-spin text-accent" />
<p className="text-sm text-foreground/60">Cargando tus clases...</p>
<p className="text-sm text-foreground/60">{t('absence.loading')}</p>
</div>
) : null}
{detailsFailed || (!details && !detailsPending) ? (
<div className="space-y-3 rounded-2xl border border-danger/20 bg-danger-soft p-6 text-center sm:p-8">
<h2 className="text-xl font-bold text-danger">Enlace no válido</h2>
<h2 className="text-xl font-bold text-danger">{t('absence.invalidTitle')}</h2>
<p className="mx-auto max-w-sm text-sm leading-relaxed text-foreground/70">
No pudimos identificarte con este enlace. Consultá con tu profesor para solicitar uno nuevo.
{t('absence.invalidDescription')}
</p>
</div>
) : null}
@@ -36,18 +38,22 @@ export function AbsenceNotifyView() {
<CalendarX2 className="size-7" />
</div>
<Badge variant="neutral" className="mb-2">
Aviso de ausencia
{t('absence.badge')}
</Badge>
<h1 className="text-2xl font-bold text-primary">Hola, {details.fullName}</h1>
<h1 className="text-2xl font-bold text-primary">{t('absence.greeting', { name: details.fullName })}</h1>
<p className="mt-1 text-sm font-medium text-foreground/80">
Grupo: <span className="text-primary">{details.groupName}</span>
<Trans
t={t}
i18nKey="absence.group"
values={{ group: details.groupName }}
components={{ strong: <span className="text-primary" /> }}
/>
</p>
</div>
{details.sessions.length === 0 ? (
<p className="rounded-xl border border-dashed border-border bg-primary-soft/40 px-4 py-8 text-center text-sm text-foreground/60">
No tenés clases programadas para hoy. Si necesitás avisar de todas formas, contactá a tu
profesor.
{t('absence.noClasses')}
</p>
) : (
<ul className="space-y-3">
@@ -58,7 +64,7 @@ export function AbsenceNotifyView() {
)}
<p className="text-center text-xs leading-relaxed text-foreground/50">
Si avisás con anticipación, tu cupo se libera para una clase de recuperación.
{t('absence.hint')}
</p>
</div>
) : null}

View File

@@ -1,6 +1,8 @@
import { CheckCircle2, Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { useAbsenceNotify } from './AbsenceNotifyProvider'
import { useTranslation } from 'react-i18next'
import { useIntlLocale } from '../../i18n'
type AbsenceSession = {
sessionId: string
@@ -11,22 +13,20 @@ type AbsenceSession = {
export function AbsenceSessionRow({ session }: { session: AbsenceSession }) {
const { isNotified, isNotifying, notify } = useAbsenceNotify()
const time = new Date(session.startsAt).toLocaleTimeString('es-MX', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
const { t } = useTranslation('public')
const locale = useIntlLocale()
const time = new Date(session.startsAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
return (
<li className="flex items-center justify-between gap-3 rounded-xl border border-border bg-primary-soft/30 px-4 py-3">
<div className="min-w-0">
<p className="text-sm font-semibold text-primary">Hoy · {time} hs</p>
<p className="text-sm font-semibold text-primary">{t('absence.today', { time })}</p>
<p className="truncate text-xs text-foreground/60">{session.groupName}</p>
</div>
{isNotified(session) ? (
<span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-success-soft px-2.5 py-1 text-xs font-medium text-success">
<CheckCircle2 className="size-3.5" />
Ya avisaste
{t('absence.notified')}
</span>
) : (
<Button
@@ -36,7 +36,7 @@ export function AbsenceSessionRow({ session }: { session: AbsenceSession }) {
onClick={() => notify(session.sessionId)}
>
{isNotifying(session.sessionId) ? <Loader2 className="size-4 animate-spin" /> : null}
Avisar ausencia
{t('absence.notify')}
</Button>
)}
</li>

View File

@@ -3,6 +3,8 @@ import { useQuery } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext } from 'react'
import { ApiError, getAdminAccount } from '../../lib/api'
import { errorMessage as apiErrorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
type AdminAccountDetailContextValue = {
account: AdminAccountDetail | null
@@ -30,9 +32,7 @@ export function AdminAccountDetailProvider({
const error = accountQuery.error
const isNotFound = error instanceof ApiError && error.status === 404
const errorMessage = accountQuery.isError
? error instanceof ApiError
? (error.problem?.detail ?? 'No pudimos cargar la cuenta.')
: 'No pudimos cargar la cuenta.'
? apiErrorMessage(error, i18n.t('admin:detail.loadError'))
: null
return (

View File

@@ -1,5 +1,4 @@
import type { AdminAccountDetail } from '@gruperly/shared'
import { PLAN_LIMITS } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { ArrowLeft, Loader2 } from 'lucide-react'
import type { ReactNode } from 'react'
@@ -9,15 +8,17 @@ import { BILLING_PROVIDER_NAMES, formatBillingDate, formatUsage, subscriptionSta
import { useAdminAccountDetail } from './AdminAccountDetailProvider'
import {
countryLabel,
MP_STATUS_LABELS,
mpStatusLabel,
planLabel,
planVariant,
subscriptionVariant,
WHATSAPP_STATUS_LABELS,
whatsappStatusLabel,
} from './copy'
import { useTranslation } from 'react-i18next'
export function AdminAccountDetailView() {
const { account, isPending, isError, isNotFound, errorMessage, retry } = useAdminAccountDetail()
const { t } = useTranslation(['admin', 'common', 'billing'])
return (
<section>
@@ -26,26 +27,26 @@ export function AdminAccountDetailView() {
className="hidden items-center gap-1.5 text-sm font-medium text-foreground/60 hover:text-primary lg:inline-flex"
>
<ArrowLeft className="size-4" aria-hidden="true" />
Cuentas
{t('accounts')}
</Link>
{/* El h1 va siempre, también cargando, para que el layout no salte. */}
<h1 className="mt-2 truncate text-2xl font-bold text-primary">{account?.name ?? 'Cuenta'}</h1>
<h1 className="mt-2 truncate text-2xl font-bold text-primary">{account?.name ?? t('detail.fallback')}</h1>
{account ? <p className="mt-0.5 truncate text-sm text-foreground/60">{account.email}</p> : null}
{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 cuenta</span>
<span className="sr-only">{t('detail.loading')}</span>
</div>
) : null}
{isError ? (
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>{isNotFound ? 'Esta cuenta no existe.' : errorMessage}</p>
<p>{isNotFound ? t('detail.notFound') : errorMessage}</p>
{isNotFound ? null : (
<Button variant="outline" size="sm" onClick={retry}>
Reintentar
{t('common:actions.retry')}
</Button>
)}
</div>
@@ -58,66 +59,70 @@ export function AdminAccountDetailView() {
function AccountDetail({ account }: { account: AdminAccountDetail }) {
const subscription = account.subscription
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
const limits = account.limits
const { t } = useTranslation(['admin', 'common', 'billing'])
return (
<div className="mt-6 grid gap-4 lg:grid-cols-2">
<Card title="Cuenta">
<Field label="País">{countryLabel(account.country)}</Field>
<Field label="Alta">{formatBillingDate(account.createdAt)}</Field>
<Field label="Onboarding">{account.onboardingCompleted ? 'Completo' : 'Sin terminar'}</Field>
<Field label="Mercado Pago">{MP_STATUS_LABELS[account.mpStatus ?? 'NONE']}</Field>
<Field label="WhatsApp">{WHATSAPP_STATUS_LABELS[account.whatsappStatus ?? 'NONE']}</Field>
<Card title={t('detail.account')}>
<Field label={t('detail.country')}>{countryLabel(account.country)}</Field>
<Field label={t('detail.createdAt')}>{formatBillingDate(account.createdAt)}</Field>
<Field label={t('detail.onboarding')}>
{account.onboardingCompleted ? t('detail.onboardingDone') : t('detail.onboardingPending')}
</Field>
<Field label="Mercado Pago">{mpStatusLabel(account.mpStatus)}</Field>
<Field label="WhatsApp">{whatsappStatusLabel(account.whatsappStatus)}</Field>
</Card>
<Card title="Plan">
<Field label="Plan">
<Card title={t('detail.plan')}>
<Field label={t('detail.plan')}>
<span className="inline-flex flex-wrap items-center gap-1.5">
<Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
{account.readOnly ? <Badge variant="danger">Solo lectura</Badge> : null}
{account.readOnly ? <Badge variant="danger">{t('detail.readOnly')}</Badge> : null}
</span>
</Field>
<Field label="Elegido el">{formatBillingDate(account.planSelectedAt) ?? '—'}</Field>
<Field label="Suscripción">
<Field label={t('detail.chosenOn')}>{formatBillingDate(account.planSelectedAt) ?? '—'}</Field>
<Field label={t('detail.subscription')}>
<Badge variant={subscriptionVariant(subscription?.status ?? null)}>
{subscriptionStatusLabel(subscription?.status ?? null)}
</Badge>
</Field>
{subscription ? (
<>
<Field label="Cobra">{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
<Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field>
<Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
<Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
<Field label="Email de pago">{subscription.payerEmail}</Field>
<Field label={t('detail.provider')}>{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
<Field label={t('detail.price')}>
{t('detail.perMonth', { price: formatPrice(subscription.amount, subscription.currency) })}
</Field>
<Field label={t('detail.paidThrough')}>{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
<Field label={t('detail.nextPayment')}>{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
<Field label={t('detail.payerEmail')}>{subscription.payerEmail}</Field>
</>
) : null}
{account.graceUntil ? (
<Field label="En gracia hasta">{formatBillingDate(account.graceUntil)}</Field>
<Field label={t('detail.graceUntil')}>{formatBillingDate(account.graceUntil)}</Field>
) : null}
</Card>
<Card title="Uso">
<Field label="Grupos">{formatUsage(account.groupsCount, limits.maxGroups)}</Field>
<Field label="Alumnos activos">{formatUsage(account.attendeesCount, limits.maxAttendees)}</Field>
<Card title={t('detail.usage')}>
<Field label={t('detail.groups')}>{formatUsage(account.groupsCount, limits.maxGroups)}</Field>
<Field label={t('detail.students')}>{formatUsage(account.attendeesCount, limits.maxAttendees)}</Field>
{account.groups.length > 0 ? (
<ul className="mt-2 divide-y divide-border border-t border-border">
{account.groups.map((group) => (
<li key={group.id} className="flex items-center justify-between gap-3 py-2 text-sm">
<span className="min-w-0 truncate text-primary">{group.name}</span>
<span className="shrink-0 text-xs text-foreground/60">
{group.attendeesCount} {group.attendeesCount === 1 ? 'alumno' : 'alumnos'} · desde{' '}
{formatBillingDate(group.createdAt)}
{t('detail.groupLine', { count: group.attendeesCount, date: formatBillingDate(group.createdAt) })}
</span>
</li>
))}
</ul>
) : (
<p className="mt-2 text-sm text-foreground/60">Todavía no creó grupos.</p>
<p className="mt-2 text-sm text-foreground/60">{t('detail.noGroups')}</p>
)}
</Card>
<Card title="Cobros de Gruperly">
<Card title={t('detail.charges')}>
{account.charges.length > 0 ? (
<ul className="divide-y divide-border">
{account.charges.map((charge) => (
@@ -135,7 +140,7 @@ function AccountDetail({ account }: { account: AdminAccountDetail }) {
))}
</ul>
) : (
<p className="text-sm text-foreground/60">Sin cobros registrados.</p>
<p className="text-sm text-foreground/60">{t('detail.noCharges')}</p>
)}
</Card>
</div>

View File

@@ -5,6 +5,7 @@ import { Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { formatBillingDate, subscriptionStatusLabel } from '../billing'
import { countryLabel, planLabel, planVariant, subscriptionVariant } from './copy'
import { useTranslation } from 'react-i18next'
/** Columnas de la grilla en `lg+`; el encabezado de `AdminAccountsView` usa las mismas. */
export const ACCOUNT_GRID_COLUMNS =
@@ -13,6 +14,7 @@ export const ACCOUNT_GRID_COLUMNS =
/* Una cuenta de la lista: tarjeta en móvil, fila de la grilla en escritorio. */
export function AdminAccountRow({ account }: { account: AdminAccountListItem }) {
const subscription = account.subscription
const { t } = useTranslation(['admin', 'common', 'billing'])
const status = subscription?.status ?? null
const paidThrough = formatBillingDate(subscription?.paidThrough ?? null)
const planBadge = <Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
@@ -39,9 +41,8 @@ export function AdminAccountRow({ account }: { account: AdminAccountListItem })
{statusBadge}
</div>
<p className="mt-2 text-xs text-foreground/60">
{countryLabel(account.country)} · {account.groupsCount}{' '}
{account.groupsCount === 1 ? 'grupo' : 'grupos'} · {account.attendeesCount}{' '}
{account.attendeesCount === 1 ? 'alumno' : 'alumnos'}
{countryLabel(account.country)} · {t('row.groups', { count: account.groupsCount })} ·{' '}
{t('row.students', { count: account.attendeesCount })}
</p>
</div>
@@ -58,7 +59,7 @@ export function AdminAccountRow({ account }: { account: AdminAccountListItem })
{subscription ? (
<p className="mt-1 truncate text-xs text-foreground/50">
{formatPrice(subscription.amount, subscription.currency)}
{paidThrough ? ` · hasta ${paidThrough}` : ''}
{paidThrough ? t('row.until', { date: paidThrough }) : ''}
</p>
) : null}
</div>

View File

@@ -9,6 +9,8 @@ import { useQuery } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { ApiError, getAdminAccounts } from '../../lib/api'
import { errorMessage as apiErrorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
const PAGE_SIZE = 20
const SEARCH_DEBOUNCE_MS = 300
@@ -73,9 +75,7 @@ export function AdminAccountsProvider({ children }: { children: ReactNode }) {
const data = accountsQuery.data
const errorMessage = accountsQuery.isError
? accountsQuery.error instanceof ApiError
? (accountsQuery.error.problem?.detail ?? 'No pudimos cargar las cuentas.')
: 'No pudimos cargar las cuentas.'
? apiErrorMessage(accountsQuery.error, i18n.t('admin:loadError'))
: null
// Cambiar un filtro vuelve a la primera página.

View File

@@ -4,7 +4,8 @@ import { Button, Input } from '../../components/ui'
import { cn } from '../../lib/utils'
import { ACCOUNT_GRID_COLUMNS, AdminAccountRow } from './AdminAccountRow'
import { useAdminAccounts } from './AdminAccountsProvider'
import { COUNTRY_OPTIONS, PLAN_FILTER_OPTIONS, SUBSCRIPTION_FILTER_OPTIONS } from './copy'
import { countryOptions, planFilterOptions, subscriptionFilterOptions } from './copy'
import { useTranslation } from 'react-i18next'
const selectClass =
'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'
@@ -30,21 +31,22 @@ export function AdminAccountsView() {
setPage,
retry,
} = useAdminAccounts()
const { t } = useTranslation(['admin', 'common', 'billing'])
const hasFilters = !!search.trim() || !!country || !!plan || !!subscriptionStatus
return (
<section>
<div>
<h1 className="text-2xl font-bold text-primary">Cuentas</h1>
<h1 className="text-2xl font-bold text-primary">{t('accounts')}</h1>
<p className="mt-1 text-sm text-foreground/60">
Profesores que usan Gruperly, con su plan y su uso.
{t('subtitle')}
</p>
</div>
<div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(0,2fr)_repeat(3,minmax(0,1fr))]">
<label className="block sm:col-span-2 lg:col-span-1">
<span className="mb-1.5 block text-sm font-medium text-primary">Buscar</span>
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.search')}</span>
<div className="relative">
<Search
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/40"
@@ -55,21 +57,21 @@ export function AdminAccountsView() {
autoFocus
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Nombre o email"
placeholder={t('filters.searchPlaceholder')}
className="pl-9"
/>
</div>
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">País</span>
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.country')}</span>
<select
value={country ?? ''}
onChange={(event) => setCountry((event.target.value || null) as CountryCode | null)}
className={selectClass}
>
<option value="">Todos</option>
{COUNTRY_OPTIONS.map((option) => (
<option value="">{t('filters.all')}</option>
{countryOptions().map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
@@ -78,14 +80,14 @@ export function AdminAccountsView() {
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Plan</span>
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.plan')}</span>
<select
value={plan ?? ''}
onChange={(event) => setPlan((event.target.value || null) as AdminPlanFilter | null)}
className={selectClass}
>
<option value="">Todos</option>
{PLAN_FILTER_OPTIONS.map((option) => (
<option value="">{t('filters.all')}</option>
{planFilterOptions().map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
@@ -94,7 +96,7 @@ export function AdminAccountsView() {
</label>
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Suscripción</span>
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.subscription')}</span>
<select
value={subscriptionStatus ?? ''}
onChange={(event) =>
@@ -102,8 +104,8 @@ export function AdminAccountsView() {
}
className={selectClass}
>
<option value="">Todas</option>
{SUBSCRIPTION_FILTER_OPTIONS.map((option) => (
<option value="">{t('filters.allFem')}</option>
{subscriptionFilterOptions().map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
@@ -115,7 +117,7 @@ export function AdminAccountsView() {
{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 cuentas</span>
<span className="sr-only">{t('loading')}</span>
</div>
) : null}
@@ -123,7 +125,7 @@ export function AdminAccountsView() {
<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
{t('common:actions.retry')}
</Button>
</div>
) : null}
@@ -134,11 +136,11 @@ export function AdminAccountsView() {
<Users className="size-7" aria-hidden="true" />
</span>
<p className="mt-4 text-base font-semibold text-primary">
{hasFilters ? 'Ninguna cuenta coincide' : 'Todavía no hay cuentas'}
{hasFilters ? t('noMatch') : t('empty')}
</p>
{hasFilters ? (
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
Probá con otra búsqueda o sacá algún filtro.
{t('noMatchHint')}
</p>
) : null}
</div>
@@ -158,12 +160,12 @@ export function AdminAccountsView() {
ACCOUNT_GRID_COLUMNS,
)}
>
<span>Cuenta</span>
<span>País</span>
<span>Plan</span>
<span>Suscripción</span>
<span className="text-right">Grupos</span>
<span className="text-right">Alumnos</span>
<span>{t('columns.account')}</span>
<span>{t('columns.country')}</span>
<span>{t('columns.plan')}</span>
<span>{t('columns.subscription')}</span>
<span className="text-right">{t('columns.groups')}</span>
<span className="text-right">{t('columns.students')}</span>
<span />
</div>
<ul className="space-y-3 lg:space-y-0">
@@ -176,10 +178,10 @@ export function AdminAccountsView() {
<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
{t('prev')}
</Button>
<p className="text-xs text-foreground/50">
Página {page} de {totalPages} · {total} {total === 1 ? 'cuenta' : 'cuentas'}
{t('pageInfo', { page, pages: totalPages, count: total })}
</p>
<Button
variant="outline"
@@ -187,7 +189,7 @@ export function AdminAccountsView() {
disabled={page >= totalPages}
onClick={() => setPage(page + 1)}
>
Siguientes
{t('next')}
<ChevronRight className="size-4" />
</Button>
</div>

View File

@@ -6,6 +6,7 @@ import { Button } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { AdminLayout } from './AdminLayout'
import { useAdminAccess } from './useAdminAccess'
import { useTranslation } from 'react-i18next'
/* El backoffice cuelga de la raíz y no de `_authenticated`: un admin no tiene
por qué completar el onboarding de profesor. La sesión y el permiso se
@@ -13,6 +14,7 @@ import { useAdminAccess } from './useAdminAccess'
export function AdminGuard({ children }: { children: ReactNode }) {
const { user, isPending } = useAuth()
const navigate = useNavigate()
const { t } = useTranslation(['admin', 'common', 'billing'])
const access = useAdminAccess(!!user)
useEffect(() => {
@@ -30,9 +32,9 @@ export function AdminGuard({ children }: { children: ReactNode }) {
if (access.isError) {
return (
<div className="flex min-h-dvh flex-col items-center justify-center gap-3 px-4 text-center">
<p className="text-sm text-danger">No pudimos verificar tu acceso al backoffice.</p>
<p className="text-sm text-danger">{t('guard.error')}</p>
<Button variant="outline" size="sm" onClick={() => void access.refetch()}>
Reintentar
{t('common:actions.retry')}
</Button>
</div>
)
@@ -45,13 +47,13 @@ export function AdminGuard({ children }: { children: ReactNode }) {
<ShieldOff className="size-7" aria-hidden="true" />
</span>
<div>
<h1 className="text-lg font-semibold text-primary">No tenés acceso</h1>
<h1 className="text-lg font-semibold text-primary">{t('guard.noAccess')}</h1>
<p className="mt-1 max-w-[36ch] text-sm text-secondary">
El backoffice es solo para el equipo de Gruperly.
{t('guard.noAccessHint')}
</p>
</div>
<Link to="/" className="text-sm font-medium text-accent-fg hover:underline">
Ir a la app
{t('guard.goToApp')}
</Link>
</div>
)

View File

@@ -2,17 +2,38 @@ import type { ReactNode } from 'react'
import { Link } from '@tanstack/react-router'
import { ArrowLeft } from 'lucide-react'
import { ThemeToggle } from '../../components/layout/ThemeToggle'
import { useTranslation } from 'react-i18next'
const navLinkClass = 'rounded-xl px-2.5 py-1.5 font-medium text-foreground/60 transition-colors hover:bg-primary-soft hover:text-primary'
const activeNavLinkClass = 'bg-primary-soft text-primary'
/* Layout propio del backoffice: sin la navegación del profesor y pensado para
escritorio, aunque en móvil se lee igual (columna única). */
export function AdminLayout({ children }: { children: ReactNode }) {
const { t } = useTranslation(['admin', 'common', 'billing'])
return (
<div className="min-h-dvh bg-background">
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
<Link to="/admin" className="text-base font-bold text-primary">
Gruperly <span className="font-medium text-foreground/50">· Backoffice</span>
</Link>
<div className="flex min-w-0 items-center gap-4">
<Link to="/admin" className="shrink-0 text-base font-bold text-primary">
Gruperly <span className="hidden font-medium text-foreground/50 sm:inline">· {t('brand')}</span>
</Link>
<nav className="flex items-center gap-1 text-sm">
{/* exact: /admin no queda activo dentro de /admin/plans */}
<Link
to="/admin"
activeOptions={{ exact: true }}
className={navLinkClass}
activeProps={{ className: activeNavLinkClass }}
>
{t('accounts')}
</Link>
<Link to="/admin/plans" className={navLinkClass} activeProps={{ className: activeNavLinkClass }}>
{t('plans.title')}
</Link>
</nav>
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
<Link
@@ -20,7 +41,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
className="hidden items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm font-medium text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary lg:inline-flex"
>
<ArrowLeft className="size-4" aria-hidden="true" />
Volver a la app
{t('backToApp')}
</Link>
</div>
</div>

View File

@@ -0,0 +1,95 @@
import type { AdminPlansDto, CountryCode, Plan, UpdatePlanLimitsInput, UpdatePlanPriceInput } from '@gruperly/shared'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext } from 'react'
import { useToast } from '../../components/ui'
import { getAdminPlans, updatePlanLimits, updatePlanPrice } from '../../lib/api'
import { errorMessage as apiErrorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
const adminPlansQueryKey = ['admin', 'plans'] as const
type AdminPlansContextValue = {
plans: AdminPlansDto | null
isPending: boolean
isError: boolean
errorMessage: string | null
retry: () => void
saveLimits: (plan: Plan, input: UpdatePlanLimitsInput) => Promise<boolean>
isSavingLimits: boolean
savePrice: (country: CountryCode, input: UpdatePlanPriceInput) => Promise<boolean>
isSavingPrice: boolean
}
const AdminPlansContext = createContext<AdminPlansContextValue | null>(null)
export function AdminPlansProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
const toast = useToast()
const plansQuery = useQuery({ queryKey: adminPlansQueryKey, queryFn: getAdminPlans })
// Lo que ve el profe (catálogo y su estado) también cambia.
const refresh = () => {
void queryClient.invalidateQueries({ queryKey: adminPlansQueryKey })
void queryClient.invalidateQueries({ queryKey: ['billing'] })
void queryClient.invalidateQueries({ queryKey: ['admin', 'accounts'] })
}
const limitsMutation = useMutation({
mutationFn: ({ plan, input }: { plan: Plan; input: UpdatePlanLimitsInput }) => updatePlanLimits(plan, input),
onSuccess: () => {
toast.success(i18n.t('admin:plans.limits.saved'))
refresh()
},
onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))),
})
const priceMutation = useMutation({
mutationFn: ({ country, input }: { country: CountryCode; input: UpdatePlanPriceInput }) =>
updatePlanPrice(country, input),
onSuccess: (result) => {
toast.success(
result.queued > 0
? i18n.t('admin:plans.prices.savedQueued', { count: result.queued })
: i18n.t('admin:plans.prices.saved'),
)
refresh()
},
onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))),
})
const run = async (mutation: () => Promise<unknown>) => {
try {
await mutation()
return true
} catch {
return false
}
}
return (
<AdminPlansContext.Provider
value={{
plans: plansQuery.data ?? null,
isPending: plansQuery.isPending,
isError: plansQuery.isError,
errorMessage: plansQuery.isError
? apiErrorMessage(plansQuery.error, i18n.t('admin:plans.loadError'))
: null,
retry: () => void plansQuery.refetch(),
saveLimits: (plan, input) => run(() => limitsMutation.mutateAsync({ plan, input })),
isSavingLimits: limitsMutation.isPending,
savePrice: (country, input) => run(() => priceMutation.mutateAsync({ country, input })),
isSavingPrice: priceMutation.isPending,
}}
>
{children}
</AdminPlansContext.Provider>
)
}
export function useAdminPlans(): AdminPlansContextValue {
const context = useContext(AdminPlansContext)
if (!context) throw new Error('useAdminPlans must be used inside AdminPlansProvider')
return context
}

View File

@@ -0,0 +1,61 @@
import { Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { useAdminPlans } from './AdminPlansProvider'
import { PlanLimitsCard } from './PlanLimitsCard'
import { PlanPriceRow } from './PlanPriceRow'
import { useTranslation } from 'react-i18next'
export function AdminPlansView() {
const { plans, isPending, isError, errorMessage, retry } = useAdminPlans()
const { t } = useTranslation(['admin', 'common'])
return (
<section>
<h1 className="text-2xl font-bold text-primary">{t('plans.title')}</h1>
<p className="mt-1 text-sm text-foreground/60">{t('plans.subtitle')}</p>
{isPending ? (
<div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">{t('plans.loading')}</span>
</div>
) : null}
{isError ? (
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>{errorMessage}</p>
<Button variant="outline" size="sm" onClick={retry}>
{t('common:actions.retry')}
</Button>
</div>
) : null}
{plans ? (
<div className="mt-6 space-y-8">
<div>
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
{t('plans.limits.title')}
</h2>
<p className="mt-1 text-xs text-foreground/50">{t('plans.limits.hint')}</p>
<div className="mt-3 grid gap-4 sm:grid-cols-2">
<PlanLimitsCard plan="FREE" limits={plans.limits.FREE} />
<PlanLimitsCard plan="PRO" limits={plans.limits.PRO} />
</div>
</div>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
{t('plans.prices.title')}
</h2>
<p className="mt-1 text-xs text-foreground/50">{t('plans.prices.hint')}</p>
<ul className="mt-3 divide-y divide-border rounded-xl border border-border bg-surface">
{plans.prices.map((price) => (
<PlanPriceRow key={price.country} price={price} />
))}
</ul>
</div>
</div>
) : null}
</section>
)
}

Some files were not shown because too many files have changed in this diff Show More