diff --git a/.env.example b/.env.example index 6e23709..867841c 100644 --- a/.env.example +++ b/.env.example @@ -46,6 +46,17 @@ 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. +# MP_PLATFORM_ACCESS_TOKEN_AR="" +# MP_PLATFORM_WEBHOOK_SECRET_AR="" +# 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" + # 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. diff --git a/AGENTS.md b/AGENTS.md index d18dae6..c973d2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`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: "/"`), `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`). + - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `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`). - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). @@ -54,6 +54,13 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web 9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`. 10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos. 11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`. +- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual vía `/preapproval`), no lo que pagan los alumnos. Ojo con esto: + 1. Usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_` / `MP_PLATFORM_WEBHOOK_SECRET_`, `getPlatformCredentials`), nunca `getMpAccessToken`. Un país sin credenciales da `503 billing_not_available`. + 2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard. + 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. El webhook `POST /billing/webhooks/mp/:country` es público (`isPublicApiRequest`), verifica `x-signature` y vuelve a pedirle todo a MP; 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. - **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 `` 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). diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 1464c3f..54eff8d 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -32,6 +32,17 @@ MP_REDIRECT_URI="" # Generar con: openssl rand -base64 32 TOKEN_ENCRYPTION_KEY="" +# 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. +MP_PLATFORM_ACCESS_TOKEN_AR="" +MP_PLATFORM_WEBHOOK_SECRET_AR="" +# 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" + # WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md). # Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta). WHATSAPP_PROVIDER="openwa" diff --git a/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql new file mode 100644 index 0000000..826d695 --- /dev/null +++ b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql @@ -0,0 +1,74 @@ +-- CreateEnum +CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED'); + +-- AlterTable +ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3); + +-- CreateTable +CREATE TABLE "billing_subscriptions" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "country_code" TEXT NOT NULL, + "currency" TEXT NOT NULL, + "amount" DECIMAL(12,2) NOT NULL, + "payer_email" TEXT NOT NULL, + "mp_preapproval_id" TEXT, + "status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING', + "requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "authorized_at" TIMESTAMP(3), + "next_payment_date" TIMESTAMP(3), + "paid_through" TIMESTAMP(3), + "last_synced_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "billing_charges" ( + "id" TEXT NOT NULL, + "subscription_id" TEXT NOT NULL, + "mp_authorized_payment_id" TEXT NOT NULL, + "amount" DECIMAL(12,2) NOT NULL, + "currency" TEXT NOT NULL, + "status" TEXT NOT NULL, + "paid_at" TIMESTAMP(3), + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "billing_webhook_events" ( + "country_code" TEXT NOT NULL, + "dedupe_key" TEXT NOT NULL, + "received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key") +); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id"); + +-- CreateIndex +CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id"); + +-- CreateIndex +CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at"); + +-- CreateIndex +CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at"); + +-- AddForeignKey +ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma index b038c60..1c96664 100644 --- a/apps/backend/prisma/models/auth.prisma +++ b/apps/backend/prisma/models/auth.prisma @@ -1,26 +1,29 @@ // Auth (Better Auth) - required tables model User { - id String @id @default(cuid()) + id String @id @default(cuid()) name String - email String @unique - emailVerified Boolean @default(false) @map("email_verified") + email String @unique + emailVerified Boolean @default(false) @map("email_verified") image String? - onboardingCompleted Boolean @default(false) @map("onboarding_completed") - country String? @map("country_code") - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @updatedAt @map("updated_at") + onboardingCompleted Boolean @default(false) @map("onboarding_completed") + country String? @map("country_code") + // When the professor chose Free or Pro in the onboarding (mandatory step). + planSelectedAt DateTime? @map("plan_selected_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") accounts Account[] sessions Session[] passkeys Passkey[] groupsMember GroupMember[] - groupsOwner Group[] @relation("OwnerGroups") + groupsOwner Group[] @relation("OwnerGroups") orgMemberships Member[] - orgInvitations Invitation[] @relation("InvitedBy") + orgInvitations Invitation[] @relation("InvitedBy") waitlist WaitlistEntry[] mpAccount MpAccount? whatsappAccount WhatsappAccount? + subscription BillingSubscription? @@map("users") } diff --git a/apps/backend/prisma/models/billing.prisma b/apps/backend/prisma/models/billing.prisma new file mode 100644 index 0000000..65cf3df --- /dev/null +++ b/apps/backend/prisma/models/billing.prisma @@ -0,0 +1,70 @@ +// Gruperly's own billing: the professor pays a monthly Pro subscription through +// Mercado Pago Subscriptions (preapproval), collected by Gruperly's account in +// the professor's country. Not to be confused with `Payment`, which is what +// students pay the professor. + +enum SubscriptionStatus { + PENDING + AUTHORIZED + PAUSED + CANCELLED +} + +model BillingSubscription { + id String @id @default(cuid()) + userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id") + country String @map("country_code") + currency String + amount Decimal @db.Decimal(12, 2) + payerEmail String @map("payer_email") + // Null between creating the row and Mercado Pago answering. + mpPreapprovalId String? @unique(map: "billing_subscriptions_mpPreapprovalId_key") @map("mp_preapproval_id") + status SubscriptionStatus @default(PENDING) + // When the current attempt started: re-subscribing reuses the row. + requestedAt DateTime @default(now()) @map("requested_at") + authorizedAt DateTime? @map("authorized_at") + nextPaymentDate DateTime? @map("next_payment_date") + // Last day covered by an approved charge. Pro lasts until then plus the grace + // period, even after a cancellation or a failed renewal. + paidThrough DateTime? @map("paid_through") + lastSyncedAt DateTime? @map("last_synced_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey") + charges BillingCharge[] + + // The reconciliation job walks PENDING and stale AUTHORIZED rows. + @@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx") + @@map("billing_subscriptions") +} + +// One Mercado Pago "authorized payment" (a monthly invoice) of a subscription. +model BillingCharge { + id String @id @default(cuid()) + subscriptionId String @map("subscription_id") + mpAuthorizedPaymentId String @unique(map: "billing_charges_mpAuthorizedPaymentId_key") @map("mp_authorized_payment_id") + amount Decimal @db.Decimal(12, 2) + currency String + // Mercado Pago's own status of the charge (e.g. approved, rejected). + status String + paidAt DateTime? @map("paid_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey") + + @@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx") + @@map("billing_charges") +} + +// Deduplication of Mercado Pago webhook deliveries, per country account. +model BillingWebhookEvent { + country String @map("country_code") + dedupeKey String @map("dedupe_key") + receivedAt DateTime @default(now()) @map("received_at") + + @@id([country, dedupeKey], map: "billing_webhook_events_pkey") + @@index([receivedAt], map: "billing_webhook_events_receivedAt_idx") + @@map("billing_webhook_events") +} diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index f39043f..1adc52c 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -16,6 +16,7 @@ import { } from './modules/analytics'; import { attendeesRoutes } from './modules/attendees'; import { authRoutes } from './modules/auth'; +import { billingRoutes, planReadOnlyMiddleware } from './modules/billing'; import { classesRoutes } from './modules/classes'; import { groupsRoutes } from './modules/groups'; import { healthCheckRoutes } from './modules/health-check'; @@ -40,6 +41,13 @@ const api = app.basePath('/api/v1'); api.use('*', sessionAuthMiddleware); +// Read-only accounts (Free over its limits) cannot write domain data. Billing, +// onboarding and the MP/WhatsApp links stay open: that is how they get out of it. +const planReadOnly = planReadOnlyMiddleware(); +for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/students', '/waitlist']) { + api.use(`${prefix}/*`, planReadOnly); +} + api.route('/auth', authRoutes); api.route('/health', healthCheckRoutes); api.route('/invitations', invitationsRoutes); @@ -50,6 +58,7 @@ api.route('/mp', mpRoutes); api.route('/whatsapp', whatsappRoutes); api.route('/attendees', attendeesRoutes); api.route('/payments', paymentsRoutes); +api.route('/billing', billingRoutes); api.route('/waitlist', waitlistRoutes); api.route('/classes', classesRoutes); api.route('/students', studentStatusRoutes); diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts index cdf8ae3..1615c03 100644 --- a/apps/backend/src/http/problem-builders.ts +++ b/apps/backend/src/http/problem-builders.ts @@ -215,4 +215,89 @@ export function noAttendeesToBillProblem(): ProblemDetails { detail: 'No hay miembros activos con un cobro pendiente para este grupo.', code: 'no_attendees_to_bill', }); -} \ No newline at end of file +} +function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/plan`, + title: 'Payment Required', + status: 402, + detail: params.detail, + code: params.code, + }; +} + +export type PlanLimitKind = 'groups' | 'attendees'; + +/** The Free plan does not allow one more group or attendee. */ +export function planLimitReachedProblem(limit: PlanLimitKind, max: number): ProblemDetails { + return paymentRequiredProblem({ + detail: + limit === 'groups' + ? `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', + }); +} + +/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */ +export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails { + return paymentRequiredProblem({ + detail: + feature === 'mpCharges' + ? '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', + }); +} + +/** Free plan with more usage than its limits: only reads and deletes. */ +export function planReadOnlyProblem(): ProblemDetails { + return paymentRequiredProblem({ + detail: + 'Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.', + code: 'plan_read_only', + }); +} + +/** Gruperly has no Mercado Pago account configured for the professor's country. */ +export function billingNotAvailableProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/billing-not-available`, + title: 'Service Unavailable', + status: 503, + detail: 'La suscripción a Pro todavía no está disponible en tu país.', + code: 'billing_not_available', + }; +} + +/** Mercado Pago refused the subscription request, or could not be reached. */ +export function billingProviderErrorProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`, + title: 'Bad Gateway', + status: 502, + detail: 'No pudimos comunicarnos con Mercado Pago. Intentá de nuevo en unos minutos.', + code: 'billing_provider_error', + }; +} + +export function subscriptionAlreadyActiveProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Ya tenés una suscripción a Pro activa.', + code: 'subscription_already_active', + }); +} + +export function noActiveSubscriptionProblem(): ProblemDetails { + return conflictProblem({ + detail: 'No tenés una suscripción para cancelar.', + code: 'no_active_subscription', + }); +} + +export function planNotSelectedProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Elegí un plan antes de crear tu primer grupo.', + code: 'plan_not_selected', + }); +} diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index 5ea490e..6001e0c 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -42,6 +42,11 @@ export function isPublicApiRequest(method: string, path: string): boolean { ) { return true; } + // Mercado Pago notifications about Pro subscriptions, one URL per country: + // no session, authenticated by Mercado Pago's `x-signature`. + if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) { + return true; + } return ( normalizedPath === '/api/v1/health' diff --git a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts index b457784..2a5f1f8 100644 --- a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts @@ -8,10 +8,12 @@ import type { import { err, ok } from '@gruperly/shared'; import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; type BulkCreateAttendeesDeps = { db?: Pick; + planGuard?: Pick; }; export class BulkCreateAttendeesUseCase { @@ -88,6 +90,16 @@ export class BulkCreateAttendeesUseCase { }); } + // All or nothing: a partial import that stops at the limit is harder to + // reason about than a clear "your plan allows N". + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees( + group.createdById, + toCreateData.length, + ); + if (!allowed.ok) { + return allowed; + } + const createdRecords: AttendeeRecord[] = []; for (const data of toCreateData) { const record = await db.attendee.create({ data }); diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts index cf8a656..9ee24bd 100644 --- a/apps/backend/src/modules/attendees/features/create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/create/use-case.ts @@ -9,10 +9,12 @@ import { notFoundResourceProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; type CreateAttendeeDeps = { db?: Pick; + planGuard?: Pick; }; type CreateAttendeeOptions = { @@ -106,6 +108,12 @@ export class CreateAttendeeUseCase { } } + // The owner's plan pays for the attendee, whoever adds it. + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById); + if (!allowed.ok) { + return allowed; + } + const attendee = await db.attendee.create({ data: { groupId, diff --git a/apps/backend/src/modules/billing/features/cancel/route.ts b/apps/backend/src/modules/billing/features/cancel/route.ts new file mode 100644 index 0000000..ec19a5f --- /dev/null +++ b/apps/backend/src/modules/billing/features/cancel/route.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { CancelSubscription } from './use-case'; + +const route = new Hono(); + +route.post('/cancel', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const result = await new CancelSubscription().execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/cancel/use-case.ts b/apps/backend/src/modules/billing/features/cancel/use-case.ts new file mode 100644 index 0000000..9985cc2 --- /dev/null +++ b/apps/backend/src/modules/billing/features/cancel/use-case.ts @@ -0,0 +1,50 @@ +import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { billingProviderErrorProblem, noActiveSubscriptionProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { getPlatformCredentials, mpPreapprovalClient, type PreapprovalClient } from '../../lib'; + +type CancelSubscriptionDeps = { + db?: Pick; + client?: PreapprovalClient; + credentials?: typeof getPlatformCredentials; +}; + +/** + * Stops the monthly charge. `paidThrough` stays: the professor keeps Pro until + * the end of what they already paid (plus the grace period). + */ +export class CancelSubscription { + constructor(private readonly deps: CancelSubscriptionDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + if (!subscription?.mpPreapprovalId || subscription.status === 'CANCELLED') { + return err(noActiveSubscriptionProblem()); + } + + const credentials = (this.deps.credentials ?? getPlatformCredentials)( + subscription.country as CountryCode, + ); + if (!credentials.ok) return credentials; + + try { + await (this.deps.client ?? mpPreapprovalClient).cancelPreapproval( + credentials.value.accessToken, + subscription.mpPreapprovalId, + ); + } catch { + return err(billingProviderErrorProblem()); + } + + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + + return ok({ status: 'CANCELLED' }); + } +} diff --git a/apps/backend/src/modules/billing/features/charges/route.ts b/apps/backend/src/modules/billing/features/charges/route.ts new file mode 100644 index 0000000..5cc6c0f --- /dev/null +++ b/apps/backend/src/modules/billing/features/charges/route.ts @@ -0,0 +1,19 @@ +import type { BillingChargesQuery } from '@gruperly/shared'; +import { BillingChargesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListBillingCharges } from './use-case'; + +const route = new Hono(); + +route.get('/charges', validate.query(BillingChargesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const query = c.req.valid('query') as BillingChargesQuery; + const result = await new ListBillingCharges().execute(query, user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/charges/use-case.ts b/apps/backend/src/modules/billing/features/charges/use-case.ts new file mode 100644 index 0000000..8873b6e --- /dev/null +++ b/apps/backend/src/modules/billing/features/charges/use-case.ts @@ -0,0 +1,36 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { BillingChargeList, BillingChargesQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { toBillingChargeDto } from '../../lib'; + +type ListBillingChargesDeps = { db?: Pick }; + +/** The professor's own Pro charges, newest first. */ +export class ListBillingCharges { + constructor(private readonly deps: ListBillingChargesDeps = {}) {} + + async execute( + query: BillingChargesQuery, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const where = { subscription: { userId } }; + + const [charges, total] = await Promise.all([ + db.billingCharge.findMany({ + where, + orderBy: { createdAt: 'desc' }, + skip: getPaginationOffset(query), + take: query.pageSize, + }), + db.billingCharge.count({ where }), + ]); + + return ok({ + data: charges.map(toBillingChargeDto), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/billing/features/status/route.ts b/apps/backend/src/modules/billing/features/status/route.ts new file mode 100644 index 0000000..b79fe1c --- /dev/null +++ b/apps/backend/src/modules/billing/features/status/route.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetBillingStatus } from './use-case'; + +const route = new Hono(); + +route.get('/status', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const result = await new GetBillingStatus().execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/status/use-case.ts b/apps/backend/src/modules/billing/features/status/use-case.ts new file mode 100644 index 0000000..e384f23 --- /dev/null +++ b/apps/backend/src/modules/billing/features/status/use-case.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; +import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { countryOf, getPlatformCredentials, PlanGuard, SyncSubscription } from '../../lib'; + +/** A PENDING subscription is re-read from Mercado Pago at most this often. */ +const PENDING_SYNC_INTERVAL_MS = 30 * 1000; + +type GetBillingStatusDeps = { + db?: Pick; + guard?: PlanGuard; + sync?: Pick; + credentials?: typeof getPlatformCredentials; + now?: () => Date; +}; + +export class GetBillingStatus { + constructor(private readonly deps: GetBillingStatusDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + const country = countryOf(user); + + let subscription = await db.billingSubscription.findUnique({ where: { userId } }); + + // Coming back from Mercado Pago, the webhook may not have arrived yet (or + // may never arrive in local dev): ask Mercado Pago directly, throttled. + if ( + subscription?.status === 'PENDING' + && subscription.mpPreapprovalId + && (!subscription.lastSyncedAt + || now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS) + ) { + const synced = await (this.deps.sync ?? new SyncSubscription()).execute(subscription.id); + if (synced.ok && synced.value.synced) { + subscription = await db.billingSubscription.findUnique({ where: { userId } }); + } + } + + const entitlements = await (this.deps.guard ?? new PlanGuard()).getEntitlements(userId); + // A live subscription keeps the price it was created with; otherwise the + // current price of the country is what subscribing would cost. + const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null; + + return ok({ + plan: entitlements.plan, + status: subscription?.status ?? null, + readOnly: entitlements.readOnly, + graceUntil: entitlements.graceUntil?.toISOString() ?? null, + paidThrough: subscription?.paidThrough?.toISOString() ?? null, + nextPaymentDate: + subscription?.status === 'AUTHORIZED' + ? (subscription.nextPaymentDate?.toISOString() ?? null) + : null, + payerEmail: subscription?.payerEmail ?? null, + priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country], + currency: live ? live.currency : COUNTRY_CURRENCY[country], + country, + availableInCountry: (this.deps.credentials ?? getPlatformCredentials)(country).ok, + enforced: entitlements.enforced, + usage: entitlements.usage, + limits: entitlements.limits, + }); + } +} diff --git a/apps/backend/src/modules/billing/features/subscribe/route.ts b/apps/backend/src/modules/billing/features/subscribe/route.ts new file mode 100644 index 0000000..4013de7 --- /dev/null +++ b/apps/backend/src/modules/billing/features/subscribe/route.ts @@ -0,0 +1,21 @@ +import type { SubscribeInput } from '@gruperly/shared'; +import { SubscribeInputSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { Subscribe } from './use-case'; + +const route = new Hono(); + +// Returns `{ checkoutUrl }`: the browser navigates there to authorize the +// subscription in Mercado Pago, the same way `/mp/connect` works. +route.post('/subscribe', validate.json(SubscribeInputSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const input = c.req.valid('json') as SubscribeInput; + const result = await new Subscribe().execute(user.id, input); + return resultJson(c, result, { status: 201 }); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/subscribe/use-case.ts b/apps/backend/src/modules/billing/features/subscribe/use-case.ts new file mode 100644 index 0000000..564fd6f --- /dev/null +++ b/apps/backend/src/modules/billing/features/subscribe/use-case.ts @@ -0,0 +1,118 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared'; +import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { + billingProviderErrorProblem, + notFoundResourceProblem, + subscriptionAlreadyActiveProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { getWebOrigin } from '@/modules/mp/lib'; +import { + buildSubscriptionBackUrl, + countryOf, + getPlatformCredentials, + mpPreapprovalClient, + type PreapprovalClient, +} from '../../lib'; + +type SubscribeDeps = { + db?: Pick; + client?: PreapprovalClient; + credentials?: typeof getPlatformCredentials; + webOrigin?: string; + now?: () => Date; +}; + +const SUBSCRIPTION_REASON = 'Gruperly Pro'; + +/** + * Starts a monthly Pro subscription in Gruperly's Mercado Pago account of the + * professor's country and returns where the browser goes to authorize it. + * + * The row is written PENDING before calling Mercado Pago (it is the source of + * truth, like `Payment` rows in the batch). A previous subscription that was + * never authorized is cancelled first, so the professor can fix the payer + * email by simply trying again. + */ +export class Subscribe { + constructor(private readonly deps: SubscribeDeps = {}) {} + + async execute(userId: string, input: SubscribeInput): Promise> { + const db = this.deps.db ?? prisma; + const client = this.deps.client ?? mpPreapprovalClient; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + + const country = countryOf(user); + const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); + if (!credentials.ok) return credentials; + const token = credentials.value.accessToken; + + const existing = await db.billingSubscription.findUnique({ where: { userId } }); + if (existing?.status === 'AUTHORIZED') { + return err(subscriptionAlreadyActiveProblem()); + } + + if (existing?.mpPreapprovalId && existing.status !== 'CANCELLED') { + try { + await client.cancelPreapproval(token, existing.mpPreapprovalId); + } catch { + // A stale PENDING preapproval that cannot be cancelled is harmless: it + // was never authorized, and its notifications no longer match our row. + logger.warn({ userId }, 'Could not cancel the previous Mercado Pago preapproval'); + } + } + + const amount = PRO_PRICE_BY_COUNTRY[country]; + const currency = COUNTRY_CURRENCY[country]; + const fields = { country, currency, amount, payerEmail: input.payerEmail }; + + const row = await db.billingSubscription.upsert({ + where: { userId }, + create: { userId, ...fields, status: 'PENDING', requestedAt: now }, + update: { + ...fields, + status: 'PENDING', + requestedAt: now, + mpPreapprovalId: null, + authorizedAt: null, + nextPaymentDate: null, + }, + }); + + // Re-subscribing before the paid period ends: the first charge waits for it, + // so nobody pays twice for the same month. + const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined; + + let preapproval: Awaited>; + try { + preapproval = await client.createPreapproval(token, { + reason: SUBSCRIPTION_REASON, + externalReference: userId, + payerEmail: input.payerEmail, + amount, + currencyId: currency, + backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo), + startDate, + }); + } catch { + return err(billingProviderErrorProblem()); + } + + if (!preapproval.initPoint) { + logger.error({ userId }, 'Mercado Pago preapproval came back without init_point'); + return err(billingProviderErrorProblem()); + } + + await db.billingSubscription.update({ + where: { id: row.id }, + data: { mpPreapprovalId: preapproval.id, lastSyncedAt: now }, + }); + + return ok({ checkoutUrl: preapproval.initPoint }); + } +} diff --git a/apps/backend/src/modules/billing/features/webhook/route.ts b/apps/backend/src/modules/billing/features/webhook/route.ts new file mode 100644 index 0000000..752c5c3 --- /dev/null +++ b/apps/backend/src/modules/billing/features/webhook/route.ts @@ -0,0 +1,36 @@ +import { Hono } from 'hono'; +import { logger } from '@/logger'; +import { HandleBillingWebhook } from './use-case'; + +/** + * Public endpoint (see `isPublicApiRequest`): Mercado Pago calls it, not the + * browser, so there is no session. One URL per country, because each country + * is a different Gruperly account with its own webhook secret. + */ +const route = new Hono(); + +route.post('/webhooks/mp/:country', async (c) => { + const result = await new HandleBillingWebhook().execute({ + country: c.req.param('country'), + rawBody: await c.req.text(), + headers: c.req.raw.headers, + query: new URL(c.req.url).searchParams, + }); + + if (!result.ok) { + logger.warn({ reason: result.error }, 'Mercado Pago billing webhook rejected'); + const status = + result.error === 'invalid_signature' + ? 401 + : result.error === 'unknown_country' + ? 404 + : result.error === 'not_configured' + ? 503 + : 500; + return c.body(null, status); + } + + return c.json({ received: true, duplicate: result.value.duplicate }); +}); + +export default route; diff --git a/apps/backend/src/modules/billing/features/webhook/use-case.ts b/apps/backend/src/modules/billing/features/webhook/use-case.ts new file mode 100644 index 0000000..7ae403d --- /dev/null +++ b/apps/backend/src/modules/billing/features/webhook/use-case.ts @@ -0,0 +1,136 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { CountryCode, Result } from '@gruperly/shared'; +import { countryCodeSchema, err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { + getPlatformCredentials, + mpPreapprovalClient, + type PreapprovalClient, + SyncSubscription, + verifyMpSignature, +} from '../../lib'; + +type HandleBillingWebhookDeps = { + db?: Pick; + client?: PreapprovalClient; + credentials?: typeof getPlatformCredentials; + sync?: Pick; +}; + +export type BillingWebhookFailure = + | 'unknown_country' + | 'not_configured' + | 'invalid_signature' + | 'sync_failed'; + +/** Prisma's unique-constraint violation: this delivery was already processed. */ +const UNIQUE_VIOLATION = 'P2002'; + +export type BillingWebhookRequest = { + country: string; + rawBody: string; + headers: Headers; + query: URLSearchParams; +}; + +/** + * Applies one Mercado Pago notification about a Pro subscription. + * + * The notification is only a hint: after checking its signature, the resource + * is fetched again from Mercado Pago and synced (`SyncSubscription`). The body + * is never trusted for a status. If syncing fails the dedupe key is removed, so + * Mercado Pago's retry gets another chance (same rule as the WhatsApp webhook). + */ +export class HandleBillingWebhook { + constructor(private readonly deps: HandleBillingWebhookDeps = {}) {} + + async execute( + request: BillingWebhookRequest, + ): Promise> { + const parsedCountry = countryCodeSchema.safeParse(request.country.toUpperCase()); + if (!parsedCountry.success) return err('unknown_country'); + const country: CountryCode = parsedCountry.data; + + const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); + if (!credentials.ok) return err('not_configured'); + + const body = parseBody(request.rawBody); + const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId; + const type = request.query.get('type') ?? request.query.get('topic') ?? body.type; + const requestId = request.headers.get('x-request-id'); + + const valid = verifyMpSignature({ + signature: request.headers.get('x-signature'), + requestId, + dataId, + secret: credentials.value.webhookSecret, + }); + if (!valid) return err('invalid_signature'); + + if (!dataId || !isSubscriptionTopic(type)) { + return ok({ duplicate: false, applied: false }); + } + + const db = this.deps.db ?? prisma; + const dedupe = requestId ? { country, dedupeKey: requestId } : null; + if (dedupe) { + try { + await db.billingWebhookEvent.create({ data: dedupe }); + } catch (error) { + if ((error as { code?: string }).code === UNIQUE_VIOLATION) { + return ok({ duplicate: true, applied: false }); + } + throw error; + } + } + + const unburn = async () => { + if (!dedupe) return; + await db.billingWebhookEvent + .delete({ where: { country_dedupeKey: dedupe } }) + .catch(() => undefined); + }; + + try { + let preapprovalId = dataId; + if (type === 'subscription_authorized_payment') { + const invoice = await (this.deps.client ?? mpPreapprovalClient).getAuthorizedPayment( + credentials.value.accessToken, + dataId, + ); + preapprovalId = invoice.preapprovalId; + } + + const synced = await (this.deps.sync ?? new SyncSubscription()).byPreapprovalId( + country, + preapprovalId, + ); + if (!synced.ok) { + await unburn(); + return err('sync_failed'); + } + return ok({ duplicate: false, applied: synced.value.synced }); + } catch { + await unburn(); + return err('sync_failed'); + } + } +} + +function isSubscriptionTopic( + type: string | null, +): type is 'subscription_preapproval' | 'subscription_authorized_payment' { + return type === 'subscription_preapproval' || type === 'subscription_authorized_payment'; +} + +function parseBody(rawBody: string): { dataId: string | null; type: string | null } { + try { + const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null; + return { + dataId: payload?.data?.id == null ? null : String(payload.data.id), + type: typeof payload?.type === 'string' ? payload.type : null, + }; + } catch { + return { dataId: null, type: null }; + } +} diff --git a/apps/backend/src/modules/billing/index.ts b/apps/backend/src/modules/billing/index.ts new file mode 100644 index 0000000..c664a9e --- /dev/null +++ b/apps/backend/src/modules/billing/index.ts @@ -0,0 +1,4 @@ +export { startBillingJobs } from './jobs'; +export { PlanGuard } from './lib/entitlements'; +export { planReadOnlyMiddleware } from './lib/read-only-middleware'; +export { default as billingRoutes } from './routes'; diff --git a/apps/backend/src/modules/billing/jobs/index.ts b/apps/backend/src/modules/billing/jobs/index.ts new file mode 100644 index 0000000..01574f3 --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/index.ts @@ -0,0 +1,2 @@ +export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions'; +export { startBillingJobs } from './schedule'; diff --git a/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts new file mode 100644 index 0000000..a6ede73 --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts @@ -0,0 +1,67 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { SyncSubscription } from '../lib'; + +const BATCH_SIZE = 50; +const DAY_MS = 24 * 60 * 60 * 1000; +/** A subscription nobody authorized within this window is given up. */ +const PENDING_TTL_MS = 7 * DAY_MS; +/** Authorized subscriptions are re-checked at least daily (renewals, cancellations in MP). */ +const AUTHORIZED_STALE_MS = DAY_MS; + +type ReconcileSubscriptionsDeps = { + db?: Pick; + sync?: Pick; + now?: () => Date; +}; + +export type ReconcileTotals = { checked: number; synced: number; failed: number; expired: number }; + +/** + * Polling fallback for the billing webhook: the webhook can be lost, and in + * local dev it usually never arrives. Every sync is idempotent, so the webhook + * and this job racing over the same row is harmless. + */ +export class ReconcileSubscriptions { + constructor(private readonly deps: ReconcileSubscriptionsDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const sync = this.deps.sync ?? new SyncSubscription(); + const now = this.deps.now?.() ?? new Date(); + const totals: ReconcileTotals = { checked: 0, synced: 0, failed: 0, expired: 0 }; + + const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS); + const expired = await db.billingSubscription.updateMany({ + where: { status: 'PENDING', requestedAt: { lt: pendingCutoff } }, + data: { status: 'CANCELLED' }, + }); + totals.expired = expired.count; + + const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS); + const rows = await db.billingSubscription.findMany({ + where: { + mpPreapprovalId: { not: null }, + OR: [ + { status: 'PENDING' }, + { + status: { in: ['AUTHORIZED', 'PAUSED'] }, + OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }], + }, + ], + }, + select: { id: true }, + orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } }, + take: BATCH_SIZE, + }); + + for (const row of rows) { + totals.checked += 1; + const result = await sync.execute(row.id); + if (result.ok && result.value.synced) totals.synced += 1; + else if (!result.ok) totals.failed += 1; + } + + return totals; + } +} diff --git a/apps/backend/src/modules/billing/jobs/schedule.ts b/apps/backend/src/modules/billing/jobs/schedule.ts new file mode 100644 index 0000000..5e9b60f --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/schedule.ts @@ -0,0 +1,24 @@ +import { logger } from '@/logger'; +import { ReconcileSubscriptions } from './reconcile-subscriptions'; + +const RECONCILE_CRON = '*/30 * * * *'; + +/** + * Registers the billing background jobs. Called once from `server.ts`, with the + * same guards as `startPaymentJobs`: a rejected promise inside Bun's cron would + * crash the process, and `unref` keeps the job from holding it alive. + */ +export function startBillingJobs(): void { + Bun.cron( + RECONCILE_CRON, + async () => { + try { + const totals = await new ReconcileSubscriptions().execute(); + logger.info(totals, 'Pro subscriptions reconciliation finished'); + } catch (error) { + logger.error({ err: error }, 'Pro subscriptions reconciliation failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} diff --git a/apps/backend/src/modules/billing/lib/config.ts b/apps/backend/src/modules/billing/lib/config.ts new file mode 100644 index 0000000..ae33f74 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/config.ts @@ -0,0 +1,47 @@ +import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { billingNotAvailableProblem } from '@/http/problem-builders'; + +export type PlatformCredentials = { + /** Access token of Gruperly's own Mercado Pago account in that country. */ + accessToken: string; + /** Secret of the webhook configured in that account's panel. */ + webhookSecret: string; +}; + +const DEFAULT_GRACE_DAYS = 7; + +/** + * Gruperly's Mercado Pago credentials for one country. Mercado Pago does not + * charge across countries, so each country has its own account; a country + * without both variables cannot subscribe to Pro (503, not a deployment crash: + * rolling out country by country is expected). + * + * These are platform credentials, never the professor's OAuth token. + */ +export function getPlatformCredentials( + country: CountryCode, + env: Record = process.env, +): Result { + const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim(); + const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim(); + if (!accessToken || !webhookSecret) { + return err(billingNotAvailableProblem()); + } + return ok({ accessToken, webhookSecret }); +} + +/** + * Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset + * included) treats everyone as Pro, so the module can ship before the existing + * professors are moved to a plan. + */ +export function isBillingEnforced(env: Record = process.env): boolean { + return env.BILLING_ENFORCEMENT?.trim().toLowerCase() === 'on'; +} + +/** Days a lapsed Pro keeps working after its last paid period. */ +export function getGraceDays(env: Record = process.env): number { + const value = Number(env.BILLING_GRACE_DAYS); + return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS; +} diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts new file mode 100644 index 0000000..dad8d30 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/entitlements.ts @@ -0,0 +1,158 @@ +import type { 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 { + planFeatureRequiredProblem, + planLimitReachedProblem, + planReadOnlyProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { getGraceDays, isBillingEnforced } from './config'; + +const DAY_MS = 24 * 60 * 60 * 1000; + +export type SubscriptionSnapshot = { + status: SubscriptionStatus; + authorizedAt: Date | null; + paidThrough: Date | null; +}; + +export type PlanResolution = { + plan: Plan; + /** Set while Pro survives a lapse (failed renewal or cancellation) on grace. */ + graceUntil: Date | null; +}; + +/** + * Pro lasts while a charge covers today, plus the grace period after the last + * paid day. That one rule covers a cancelled subscription (Pro until the end of + * what was paid) and a failed renewal (Mercado Pago keeps retrying meanwhile). + * + * An AUTHORIZED subscription with no approved charge yet is Pro too, for the + * grace period after the authorization: the first charge is in flight. + */ +export function resolvePlan( + subscription: SubscriptionSnapshot | null, + now: Date, + graceDays: number, +): PlanResolution { + if (!subscription) return { plan: 'FREE', graceUntil: null }; + const graceMs = graceDays * DAY_MS; + + if (subscription.paidThrough) { + if (subscription.paidThrough > now) return { plan: 'PRO', graceUntil: null }; + const graceUntil = new Date(subscription.paidThrough.getTime() + graceMs); + return graceUntil > now ? { plan: 'PRO', graceUntil } : { plan: 'FREE', graceUntil: null }; + } + + if (subscription.status === 'AUTHORIZED' && subscription.authorizedAt) { + const graceUntil = new Date(subscription.authorizedAt.getTime() + graceMs); + if (graceUntil > now) return { plan: 'PRO', graceUntil: null }; + } + + return { plan: 'FREE', graceUntil: null }; +} + +export type PlanUsage = { groups: number; attendees: number }; + +export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean { + return ( + (limits.maxGroups !== null && usage.groups > limits.maxGroups) + || (limits.maxAttendees !== null && usage.attendees > limits.maxAttendees) + ); +} + +export type Entitlements = PlanResolution & { + limits: PlanLimits; + usage: PlanUsage; + /** Free with more usage than its limits. Always false when not enforced. */ + readOnly: boolean; + enforced: boolean; +}; + +type PlanGuardDeps = { + db?: Pick; + enforced?: boolean; + graceDays?: number; + now?: () => Date; +}; + +/** + * What a professor's plan allows. Every check is about the **owner** of the + * group (`group.createdById`): an ADMIN acting on someone else's group spends + * the owner's plan, not their own. + * + * With enforcement off the checks pass without touching the database. + */ +export class PlanGuard { + constructor(private readonly deps: PlanGuardDeps = {}) {} + + private get enforced(): boolean { + return this.deps.enforced ?? isBillingEnforced(); + } + + async getEntitlements(ownerId: string): Promise { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const [subscription, groups, attendees] = await Promise.all([ + db.billingSubscription.findUnique({ + where: { userId: ownerId }, + select: { status: true, authorizedAt: true, paidThrough: true }, + }), + db.group.count({ where: { createdById: ownerId } }), + db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }), + ]); + + const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays()); + const limits = PLAN_LIMITS[resolution.plan]; + const usage = { groups, attendees }; + const enforced = this.enforced; + + return { + ...resolution, + limits, + usage, + readOnly: enforced && exceedsLimits(limits, usage), + enforced, + }; + } + + async requireWritable(ownerId: string): Promise> { + if (!this.enforced) return ok(undefined); + const entitlements = await this.getEntitlements(ownerId); + return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined); + } + + async canCreateGroup(ownerId: string): Promise> { + if (!this.enforced) return ok(undefined); + const { readOnly, limits, usage } = await this.getEntitlements(ownerId); + if (readOnly) return err(planReadOnlyProblem()); + if (limits.maxGroups !== null && usage.groups + 1 > limits.maxGroups) { + return err(planLimitReachedProblem('groups', limits.maxGroups)); + } + return ok(undefined); + } + + async canAddAttendees(ownerId: string, count = 1): Promise> { + if (!this.enforced || count <= 0) return ok(undefined); + const { readOnly, limits, usage } = await this.getEntitlements(ownerId); + if (readOnly) return err(planReadOnlyProblem()); + if (limits.maxAttendees !== null && usage.attendees + count > limits.maxAttendees) { + return err(planLimitReachedProblem('attendees', limits.maxAttendees)); + } + return ok(undefined); + } + + async requireFeature(ownerId: string, feature: PlanFeature): Promise> { + return (await this.hasFeature(ownerId, feature)) + ? ok(undefined) + : err(planFeatureRequiredProblem(feature)); + } + + async hasFeature(ownerId: string, feature: PlanFeature): Promise { + if (!this.enforced) return true; + const { limits } = await this.getEntitlements(ownerId); + return limits[feature]; + } +} diff --git a/apps/backend/src/modules/billing/lib/helpers.ts b/apps/backend/src/modules/billing/lib/helpers.ts new file mode 100644 index 0000000..f0740fc --- /dev/null +++ b/apps/backend/src/modules/billing/lib/helpers.ts @@ -0,0 +1,27 @@ +import type { BillingCharge, BillingSubscription } from '@generated/prisma/client'; +import type { BillingChargeDto, BillingReturnTo, CountryCode } from '@gruperly/shared'; +import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared'; + +export function toBillingChargeDto(charge: BillingCharge): BillingChargeDto { + return { + id: charge.id, + amount: Number(charge.amount.toString()), + currency: charge.currency, + status: charge.status, + paidAt: charge.paidAt?.toISOString() ?? null, + createdAt: charge.createdAt.toISOString(), + }; +} + +/** The professor's country as stored on the user; Argentina until they pick one. */ +export function countryOf(user: { country: string | null } | null): CountryCode { + const parsed = countryCodeSchema.safeParse(user?.country); + return parsed.success ? parsed.data : DEFAULT_COUNTRY; +} + +/** Where Mercado Pago sends the professor after authorizing (or abandoning). */ +export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string { + return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`; +} + +export type SubscriptionRecord = BillingSubscription; diff --git a/apps/backend/src/modules/billing/lib/index.ts b/apps/backend/src/modules/billing/lib/index.ts new file mode 100644 index 0000000..2db0fa8 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/index.ts @@ -0,0 +1,19 @@ +export { getGraceDays, getPlatformCredentials, isBillingEnforced, type PlatformCredentials } from './config'; +export { + type Entitlements, + exceedsLimits, + PlanGuard, + type PlanResolution, + type PlanUsage, + resolvePlan, + type SubscriptionSnapshot, +} from './entitlements'; +export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers'; +export { + type MpAuthorizedPayment, + type MpPreapproval, + mpPreapprovalClient, + type PreapprovalClient, +} from './mp-preapproval'; +export { coveredUntil, SyncSubscription, type SyncSubscriptionDeps } from './sync'; +export { verifyMpSignature } from './webhook-signature'; diff --git a/apps/backend/src/modules/billing/lib/mp-preapproval.ts b/apps/backend/src/modules/billing/lib/mp-preapproval.ts new file mode 100644 index 0000000..1f82a85 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/mp-preapproval.ts @@ -0,0 +1,180 @@ +import { logger } from '@/logger'; +import { MP_API_URL, MpApiError } from '@/modules/mp/lib'; + +// Mercado Pago Subscriptions (preapproval), called with Gruperly's own +// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`. + +export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled'; + +export type CreatePreapprovalInput = { + reason: string; + /** Our user id: the only thing that ties the subscription back to a professor. */ + externalReference: string; + /** Mercado Pago requires the payer to log in with this exact email. */ + payerEmail: string; + amount: number; + currencyId: string; + backUrl: string; + /** First charge date; omitted means right after the professor authorizes. */ + startDate?: Date; +}; + +export type MpPreapproval = { + id: string; + status: MpPreapprovalStatus | string; + externalReference: string | null; + initPoint: string | null; + nextPaymentDate: string | null; +}; + +export type MpAuthorizedPayment = { + id: string; + preapprovalId: string; + /** Status of the invoice itself: scheduled, processed, recycling, cancelled. */ + status: string; + /** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */ + paymentStatus: string | null; + amount: number; + currencyId: string; + /** When the charge was debited (or attempted), ISO. */ + debitDate: string | null; + createdAt: string | null; +}; + +async function request( + accessToken: string, + path: string, + init: { method?: string; body?: unknown } = {}, +): Promise> { + let response: Response; + try { + response = await fetch(`${MP_API_URL}${path}`, { + method: init.method ?? 'GET', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + Authorization: `Bearer ${accessToken}`, + }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }); + } catch (error) { + logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable'); + throw new MpApiError(0, null); + } + + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as Record | null; + const reason = typeof payload?.message === 'string' ? payload.message : null; + // The path carries ids, never tokens or emails; the body is not logged. + logger.error( + { status: response.status, reason, path: path.split('?')[0] }, + 'Mercado Pago subscriptions request failed', + ); + throw new MpApiError(response.status, reason); + } + + return (await response.json()) as Record; +} + +function toPreapproval(payload: Record): MpPreapproval { + return { + id: String(payload.id), + status: String(payload.status), + externalReference: + typeof payload.external_reference === 'string' ? payload.external_reference : null, + initPoint: typeof payload.init_point === 'string' ? payload.init_point : null, + nextPaymentDate: + typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null, + }; +} + +/** + * Creates a monthly subscription waiting for the professor's authorization. + * Nothing is charged until they log in to Mercado Pago through `initPoint`. + */ +export async function createPreapproval( + accessToken: string, + input: CreatePreapprovalInput, +): Promise { + const payload = await request(accessToken, '/preapproval', { + method: 'POST', + body: { + reason: input.reason, + external_reference: input.externalReference, + payer_email: input.payerEmail, + back_url: input.backUrl, + status: 'pending', + auto_recurring: { + frequency: 1, + frequency_type: 'months', + transaction_amount: input.amount, + currency_id: input.currencyId, + ...(input.startDate ? { start_date: input.startDate.toISOString() } : {}), + }, + }, + }); + return toPreapproval(payload); +} + +export async function getPreapproval(accessToken: string, id: string): Promise { + return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`)); +} + +export async function cancelPreapproval(accessToken: string, id: string): Promise { + return toPreapproval( + await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, { + method: 'PUT', + body: { status: 'cancelled' }, + }), + ); +} + +function toAuthorizedPayment(payload: Record): MpAuthorizedPayment { + const payment = (payload.payment ?? null) as Record | null; + return { + id: String(payload.id), + preapprovalId: String(payload.preapproval_id), + status: String(payload.status), + paymentStatus: typeof payment?.status === 'string' ? payment.status : null, + amount: Number(payload.transaction_amount ?? 0), + currencyId: String(payload.currency_id ?? ''), + debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null, + createdAt: typeof payload.date_created === 'string' ? payload.date_created : null, + }; +} + +export async function getAuthorizedPayment( + accessToken: string, + id: string, +): Promise { + return toAuthorizedPayment( + await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`), + ); +} + +/** The invoices of one subscription, newest first as Mercado Pago returns them. */ +export async function searchAuthorizedPayments( + accessToken: string, + preapprovalId: string, +): Promise { + const query = new URLSearchParams({ preapproval_id: preapprovalId, limit: '50' }); + const payload = await request(accessToken, `/authorized_payments/search?${query}`); + const results = Array.isArray(payload.results) ? (payload.results as Record[]) : []; + return results.map(toAuthorizedPayment); +} + +export type PreapprovalClient = { + createPreapproval: typeof createPreapproval; + getPreapproval: typeof getPreapproval; + cancelPreapproval: typeof cancelPreapproval; + getAuthorizedPayment: typeof getAuthorizedPayment; + searchAuthorizedPayments: typeof searchAuthorizedPayments; +}; + +export const mpPreapprovalClient: PreapprovalClient = { + createPreapproval, + getPreapproval, + cancelPreapproval, + getAuthorizedPayment, + searchAuthorizedPayments, +}; diff --git a/apps/backend/src/modules/billing/lib/read-only-middleware.ts b/apps/backend/src/modules/billing/lib/read-only-middleware.ts new file mode 100644 index 0000000..ddb84c0 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/read-only-middleware.ts @@ -0,0 +1,29 @@ +import type { MiddlewareHandler } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { problemJson } from '@/http/problem-details'; +import { PlanGuard } from './entitlements'; + +const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); + +/** + * Blocks writes while the professor's account is read-only (Free with more + * usage than its limits). DELETE stays open: removing attendees is how they get + * back under the limits without paying. + * + * It checks the signed-in user. The create paths (groups, attendees) check the + * group **owner** on their own, so an ADMIN cannot add to a read-only owner's group. + */ +export function planReadOnlyMiddleware(guard: PlanGuard = new PlanGuard()): MiddlewareHandler { + return async (c, next) => { + const user = c.get('user'); + if (!user || SAFE_METHODS.has(c.req.method) || c.req.method === 'DELETE') { + await next(); + return; + } + + const writable = await guard.requireWritable(user.id); + if (!writable.ok) return problemJson(c, writable.error); + + await next(); + }; +} diff --git a/apps/backend/src/modules/billing/lib/sync.ts b/apps/backend/src/modules/billing/lib/sync.ts new file mode 100644 index 0000000..a67a5ff --- /dev/null +++ b/apps/backend/src/modules/billing/lib/sync.ts @@ -0,0 +1,157 @@ +import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { billingProviderErrorProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { getPlatformCredentials } from './config'; +import { type MpPreapproval, mpPreapprovalClient, type PreapprovalClient } from './mp-preapproval'; + +const MP_STATUS: Record = { + pending: 'PENDING', + authorized: 'AUTHORIZED', + paused: 'PAUSED', + cancelled: 'CANCELLED', +}; + +/** One approved monthly charge covers one month from the day it was debited. */ +export function coveredUntil(paidAt: Date): Date { + const until = new Date(paidAt); + until.setUTCMonth(until.getUTCMonth() + 1); + return until; +} + +export type SyncSubscriptionDeps = { + db?: Pick; + client?: PreapprovalClient; + credentials?: typeof getPlatformCredentials; + now?: () => Date; +}; + +export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null }; + +/** + * Brings one subscription row in line with Mercado Pago. Shared by the webhook, + * the reconciliation job and the status endpoint (on read, while PENDING). + * + * Never trusts what a notification says: it asks Mercado Pago for the + * preapproval and its invoices, checks that the preapproval is ours + * (`external_reference` is the user id) and only then writes. Re-running it is + * harmless; every write is an upsert or a monotonic `paidThrough`. + */ +export class SyncSubscription { + constructor(private readonly deps: SyncSubscriptionDeps = {}) {} + + async execute(subscriptionId: string): Promise> { + const db = this.deps.db ?? prisma; + const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } }); + if (!subscription?.mpPreapprovalId) { + return ok({ synced: false, status: subscription?.status ?? null }); + } + + const credentials = (this.deps.credentials ?? getPlatformCredentials)( + subscription.country as CountryCode, + ); + if (!credentials.ok) return credentials; + + const client = this.deps.client ?? mpPreapprovalClient; + const token = credentials.value.accessToken; + + let preapproval: MpPreapproval; + let invoices: Awaited>; + try { + preapproval = await client.getPreapproval(token, subscription.mpPreapprovalId); + invoices = await client.searchAuthorizedPayments(token, subscription.mpPreapprovalId); + } catch { + return err(billingProviderErrorProblem()); + } + + if (preapproval.externalReference !== subscription.userId) { + logger.warn({ subscriptionId }, 'Mercado Pago preapproval does not belong to this subscription'); + return ok({ synced: false, status: subscription.status }); + } + + const now = this.deps.now?.() ?? new Date(); + let paidThrough = subscription.paidThrough; + + for (const invoice of invoices) { + if (invoice.preapprovalId !== subscription.mpPreapprovalId) continue; + const approved = invoice.paymentStatus === 'approved'; + const debitedAt = invoice.debitDate ?? invoice.createdAt; + const paidAt = approved && debitedAt ? new Date(debitedAt) : null; + + await db.billingCharge.upsert({ + where: { mpAuthorizedPaymentId: invoice.id }, + create: { + subscriptionId: subscription.id, + mpAuthorizedPaymentId: invoice.id, + amount: invoice.amount, + currency: invoice.currencyId || subscription.currency, + status: invoice.paymentStatus ?? invoice.status, + paidAt, + }, + update: { status: invoice.paymentStatus ?? invoice.status, paidAt }, + }); + + if (paidAt) { + const until = coveredUntil(paidAt); + if (!paidThrough || until > paidThrough) paidThrough = until; + } + } + + const status = MP_STATUS[preapproval.status] ?? subscription.status; + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { + status, + authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined, + nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null, + paidThrough, + lastSyncedAt: now, + }, + }); + + return ok({ synced: true, status }); + } + + /** + * Same as `execute`, starting from a Mercado Pago preapproval id (webhooks). + * A notification can beat our own write of `mpPreapprovalId` (the professor + * authorizes faster than our request returns), so an unknown id falls back to + * the `external_reference` once Mercado Pago confirms it. + */ + async byPreapprovalId( + country: CountryCode, + preapprovalId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const known = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } }); + if (known) return this.execute(known.id); + + const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); + if (!credentials.ok) return credentials; + + let preapproval: MpPreapproval; + try { + preapproval = await (this.deps.client ?? mpPreapprovalClient).getPreapproval( + credentials.value.accessToken, + preapprovalId, + ); + } catch { + return err(billingProviderErrorProblem()); + } + // A cancelled one is a previous attempt being replaced, never the new one. + if (!preapproval.externalReference || preapproval.status === 'cancelled') { + return ok({ synced: false, status: null }); + } + + const claimed = await db.billingSubscription.updateMany({ + where: { userId: preapproval.externalReference, country, mpPreapprovalId: null }, + data: { mpPreapprovalId: preapprovalId }, + }); + if (claimed.count === 0) return ok({ synced: false, status: null }); + + const row = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } }); + return row ? this.execute(row.id) : ok({ synced: false, status: null }); + } +} diff --git a/apps/backend/src/modules/billing/lib/webhook-signature.ts b/apps/backend/src/modules/billing/lib/webhook-signature.ts new file mode 100644 index 0000000..289a803 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/webhook-signature.ts @@ -0,0 +1,40 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +/** + * Checks Mercado Pago's `x-signature` header (`ts=,v1=`). + * + * Mercado Pago does not sign the body: it signs a manifest built from the + * notified resource id (the `data.id` query parameter, lower-cased when it is + * alphanumeric), the `x-request-id` header and the timestamp. Parts that did + * not come in the request are left out of the manifest. + */ +export function verifyMpSignature(params: { + signature: string | null; + requestId: string | null; + dataId: string | null; + secret: string; +}): boolean { + if (!params.signature) return false; + + let ts: string | null = null; + let v1: string | null = null; + for (const part of params.signature.split(',')) { + const [key, value] = part.split('=', 2).map((piece) => piece.trim()); + if (key === 'ts') ts = value ?? null; + if (key === 'v1') v1 = value ?? null; + } + if (!ts || !v1) return false; + + const dataId = params.dataId && /^[a-z0-9]+$/i.test(params.dataId) + ? params.dataId.toLowerCase() + : params.dataId; + + let manifest = ''; + if (dataId) manifest += `id:${dataId};`; + if (params.requestId) manifest += `request-id:${params.requestId};`; + manifest += `ts:${ts};`; + + const expected = Buffer.from(createHmac('sha256', params.secret).update(manifest).digest('hex')); + const received = Buffer.from(v1); + return received.length === expected.length && timingSafeEqual(received, expected); +} diff --git a/apps/backend/src/modules/billing/routes.ts b/apps/backend/src/modules/billing/routes.ts new file mode 100644 index 0000000..7d8b587 --- /dev/null +++ b/apps/backend/src/modules/billing/routes.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import cancelRoute from './features/cancel/route'; +import chargesRoute from './features/charges/route'; +import statusRoute from './features/status/route'; +import subscribeRoute from './features/subscribe/route'; +import webhookRoute from './features/webhook/route'; + +const routes = new Hono(); + +routes.route('/', statusRoute); +routes.route('/', subscribeRoute); +routes.route('/', cancelRoute); +routes.route('/', chargesRoute); +routes.route('/', webhookRoute); + +export default routes; diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts index 00acb92..e4166b6 100644 --- a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts +++ b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts @@ -7,6 +7,7 @@ import type { import { err, ok } from '@gruperly/shared'; import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { findGroupOwnedByUser, type GroupWaitlistEntryRecord, @@ -18,6 +19,7 @@ import { type GroupPreRegistrationRecord } from '../../lib/helpers'; type ApproveGroupPreRegistrationDeps = { db?: Pick; unitOfWork?: UnitOfWork; + planGuard?: Pick; }; export class ApproveGroupPreRegistration { @@ -51,6 +53,11 @@ export class ApproveGroupPreRegistration { ); } + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId); + if (!allowed.ok) { + return allowed; + } + const record = entry as unknown as GroupPreRegistrationRecord; return unitOfWork.executeResult( diff --git a/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts index 3e5fc09..ff24cba 100644 --- a/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts +++ b/apps/backend/src/modules/group-waitlist/features/promote/use-case.ts @@ -3,6 +3,7 @@ import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@g import { err, ok } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { findGroupOwnedByUser, type GroupWaitlistEntryRecord, @@ -12,6 +13,7 @@ import { promoteWaitlistEntryRecord } from '../../lib/promote'; type PromoteGroupWaitlistEntryDeps = { db?: Pick; unitOfWork?: UnitOfWork; + planGuard?: Pick; }; export class PromoteGroupWaitlistEntry { @@ -37,6 +39,11 @@ export class PromoteGroupWaitlistEntry { return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); } + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId); + if (!allowed.ok) { + return allowed; + } + return unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { const promoteResult = await promoteWaitlistEntryRecord( diff --git a/apps/backend/src/modules/groups/features/create/use-case.ts b/apps/backend/src/modules/groups/features/create/use-case.ts index e423644..4e1eb8d 100644 --- a/apps/backend/src/modules/groups/features/create/use-case.ts +++ b/apps/backend/src/modules/groups/features/create/use-case.ts @@ -8,10 +8,12 @@ import type { } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { type GroupRecord, toGroupDto } from '../../lib'; type CreateGroupDeps = { unitOfWork?: UnitOfWork; + planGuard?: Pick; }; export class CreateGroup { @@ -23,6 +25,11 @@ export class CreateGroup { ): Promise> { const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + if (!allowed.ok) { + return allowed; + } + const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { const created = await tx.group.create({ diff --git a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts index e12fddd..1714e08 100644 --- a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts +++ b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts @@ -7,14 +7,16 @@ import type { Result, } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; -import { onboardingAlreadyCompletedProblem } from '@/http/problem-builders'; +import { onboardingAlreadyCompletedProblem, planNotSelectedProblem } from '@/http/problem-builders'; import { problemDetails } from '@/http/problem-details'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { toOnboardingGroupDto } from '../../lib'; type CreateFirstGroupDeps = { db?: Pick; unitOfWork?: UnitOfWork; + planGuard?: Pick; }; export class CreateFirstGroup { @@ -34,6 +36,15 @@ export class CreateFirstGroup { if (user.onboardingCompleted) { return err(onboardingAlreadyCompletedProblem()); } + // The "Plan" step is mandatory; this is its server-side half. + if (!user.planSelectedAt) { + return err(planNotSelectedProblem()); + } + + const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + if (!allowed.ok) { + return allowed; + } const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { diff --git a/apps/backend/src/modules/onboarding/features/select-plan/route.ts b/apps/backend/src/modules/onboarding/features/select-plan/route.ts new file mode 100644 index 0000000..ebf2288 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/select-plan/route.ts @@ -0,0 +1,19 @@ +import type { SelectPlanInput } from '@gruperly/shared'; +import { SelectPlanInputSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { SelectPlan } from './use-case'; + +const route = new Hono(); + +route.post('/', validate.json(SelectPlanInputSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const input = c.req.valid('json') as SelectPlanInput; + const result = await new SelectPlan().execute(user.id, input); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts b/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts new file mode 100644 index 0000000..b6dac10 --- /dev/null +++ b/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts @@ -0,0 +1,78 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result, SelectPlanInput, SelectPlanResultDto } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + notFoundResourceProblem, + onboardingAlreadyCompletedProblem, + subscriptionAlreadyActiveProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; +import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; + +type SelectPlanDeps = { + db?: Pick; + subscribe?: Pick; + cancel?: Pick; + now?: () => Date; +}; + +/** + * The mandatory "Plan" step of the onboarding. + * + * It stores the country first: until now it was only saved with the first + * group, and Pro needs it to pick the price and Gruperly's Mercado Pago account. + * Free is immediate; Pro starts the subscription and returns where the browser + * goes to authorize it, coming back to `/onboarding?sub=return`. + */ +export class SelectPlan { + constructor(private readonly deps: SelectPlanDeps = {}) {} + + async execute( + userId: string, + input: SelectPlanInput, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now?.() ?? new Date(); + + const user = await db.user.findUnique({ where: { id: userId } }); + if (!user) return err(notFoundResourceProblem('User', userId)); + if (user.onboardingCompleted) return err(onboardingAlreadyCompletedProblem()); + + await db.user.update({ where: { id: userId }, data: { country: input.country } }); + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + + if (input.plan === 'FREE') { + // A paid subscription is never dropped from here; that is "Cancelar" in /billing. + if (subscription?.status === 'AUTHORIZED') return err(subscriptionAlreadyActiveProblem()); + + // Going back to Free after abandoning Mercado Pago: the attempt is void. + if (subscription && subscription.status !== 'CANCELLED') { + const cancelled = await (this.deps.cancel ?? new CancelSubscription()).execute(userId); + if (!cancelled.ok) { + await db.billingSubscription.update({ + where: { id: subscription.id }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + } + } + + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'FREE', checkoutUrl: null }); + } + + if (subscription?.status === 'AUTHORIZED') { + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'PRO', checkoutUrl: null }); + } + + const started = await (this.deps.subscribe ?? new Subscribe()).execute(userId, { + payerEmail: input.payerEmail, + returnTo: 'onboarding', + }); + if (!started.ok) return started; + + await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); + return ok({ plan: 'PRO', checkoutUrl: started.value.checkoutUrl }); + } +} diff --git a/apps/backend/src/modules/onboarding/features/status/use-case.ts b/apps/backend/src/modules/onboarding/features/status/use-case.ts index 5e92e91..68bfc77 100644 --- a/apps/backend/src/modules/onboarding/features/status/use-case.ts +++ b/apps/backend/src/modules/onboarding/features/status/use-case.ts @@ -1,12 +1,12 @@ import type { PrismaClient } from '@generated/prisma/client'; -import type { OnboardingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; -import { err, ok } from '@gruperly/shared'; +import type { OnboardingStatusDto, Plan, ProblemDetails, Result } from '@gruperly/shared'; +import { countryCodeSchema, err, ok } from '@gruperly/shared'; import { problemDetails } from '@/http/problem-details'; import prisma from '@/lib/prisma'; import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account'; type GetOnboardingStatusDeps = { - db?: Pick; + db?: Pick; }; export class GetOnboardingStatus { @@ -30,8 +30,23 @@ export class GetOnboardingStatus { const whatsappAccount = await db.whatsappAccount.findUnique({ where: { ownerId: userId } }); const whatsappConnected = isWhatsappAccountUsable(whatsappAccount); + // The "Plan" step: PRO as soon as the professor chose it (a subscription + // that is not cancelled, even if Mercado Pago has not authorized it yet). + const subscription = await db.billingSubscription.findUnique({ where: { userId } }); + const planSelected = user.planSelectedAt != null; + const selectedPlan: Plan | null = planSelected + ? subscription && subscription.status !== 'CANCELLED' ? 'PRO' : 'FREE' + : null; + const country = countryCodeSchema.safeParse(user.country); + const plan = { + planSelected, + selectedPlan, + subscriptionStatus: subscription?.status ?? null, + country: country.success ? country.data : null, + }; + if (user.onboardingCompleted) { - return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true }); + return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true, ...plan }); } // Linking Mercado Pago is optional, so `paymentConnected` here only resumes @@ -44,9 +59,16 @@ export class GetOnboardingStatus { paymentConnected: true, whatsappConnected, completed: false, + ...plan, }); } - return ok({ step: 'NOT_STARTED', paymentConnected: false, whatsappConnected, completed: false }); + return ok({ + step: 'NOT_STARTED', + paymentConnected: false, + whatsappConnected, + completed: false, + ...plan, + }); } -} \ No newline at end of file +} diff --git a/apps/backend/src/modules/onboarding/routes.ts b/apps/backend/src/modules/onboarding/routes.ts index 225f20b..5b79eca 100644 --- a/apps/backend/src/modules/onboarding/routes.ts +++ b/apps/backend/src/modules/onboarding/routes.ts @@ -1,10 +1,12 @@ import { Hono } from 'hono'; import firstGroupRoute from './features/first-group/route'; +import selectPlanRoute from './features/select-plan/route'; import statusRoute from './features/status/route'; const routes = new Hono(); routes.route('/status', statusRoute); routes.route('/first-group', firstGroupRoute); +routes.route('/plan', selectPlanRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/create-batch/use-case.ts b/apps/backend/src/modules/payments/features/create-batch/use-case.ts index a6ef183..6fbc283 100644 --- a/apps/backend/src/modules/payments/features/create-batch/use-case.ts +++ b/apps/backend/src/modules/payments/features/create-batch/use-case.ts @@ -16,6 +16,7 @@ import { } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { getMpAccessToken } from '@/modules/mp'; import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib'; @@ -24,6 +25,7 @@ type BatchDeps = { createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; + planGuard?: Pick; }; /** @@ -60,6 +62,14 @@ export class CreatePaymentBatch { return err(noGroupAccessProblem()); } + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + group.createdById, + 'mpCharges', + ); + if (!allowed.ok) { + return allowed; + } + if (group.price == null) { return err(groupWithoutPriceProblem()); } diff --git a/apps/backend/src/modules/payments/features/renew/use-case.ts b/apps/backend/src/modules/payments/features/renew/use-case.ts index 2cde419..7374c1b 100644 --- a/apps/backend/src/modules/payments/features/renew/use-case.ts +++ b/apps/backend/src/modules/payments/features/renew/use-case.ts @@ -9,6 +9,7 @@ import { } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { getMpAccessToken } from '@/modules/mp'; import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib'; import { type PaymentRecord, toPaymentDto } from '../../lib'; @@ -18,6 +19,7 @@ type RenewDeps = { createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; + planGuard?: Pick; }; /** @@ -59,6 +61,14 @@ export class RenewPaymentLink { return ok(toPaymentDto(payment as unknown as PaymentRecord)); } + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + payment.group.createdById, + 'mpCharges', + ); + if (!allowed.ok) { + return allowed; + } + if (payment.group.price == null) { return err(groupWithoutPriceProblem()); } diff --git a/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts index cd5a18a..cf9ae38 100644 --- a/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts +++ b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts @@ -8,8 +8,12 @@ import type { import { err, ok } from '@gruperly/shared'; import { forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; -type UpdateGroupAutomationsDeps = { db?: Pick }; +type UpdateGroupAutomationsDeps = { + db?: Pick; + planGuard?: Pick; +}; /** * Turns the group's weekly WhatsApp automations on or off. Only the owner can: @@ -42,6 +46,15 @@ export class UpdateGroupAutomationsUseCase { ); } + // Turning them off always works, so a Free professor can clean up. + if (input.autoPaymentReminders === true || input.autoReengagement === true) { + const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( + userId, + 'whatsappAutomations', + ); + if (!allowed.ok) return allowed; + } + const updated = await db.group.update({ where: { id: groupId }, data: { diff --git a/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts index acf7634..9d6467d 100644 --- a/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts +++ b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts @@ -1,6 +1,7 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared'; import { countryCodeSchema } from '@gruperly/shared'; +import { PlanGuard } from '@/modules/billing/lib/entitlements'; import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider'; export type EligibleGroup = { id: string; name: string }; @@ -16,13 +17,15 @@ type AutomationFlag = 'autoPaymentReminders' | 'autoReengagement'; /** * Groups with the automation on, bundled by owner, keeping only owners whose * WhatsApp is linked with the active provider and ready to send this kind of - * message (for Kapso: the template is approved). + * message (for Kapso: the template is approved) and whose plan includes the + * automations (Pro). A Free owner keeps the flag on but nothing goes out. */ export async function findEligibleAccounts( db: Pick, provider: MessagingProvider, flag: AutomationFlag, kind: WhatsappMessageKind, + planGuard: Pick = new PlanGuard(), ): Promise { const groups = await db.group.findMany({ where: { @@ -52,7 +55,8 @@ export async function findEligibleAccounts( } const eligible: EligibleAccount[] = []; - for (const entry of byOwner.values()) { + for (const [ownerId, entry] of byOwner) { + if (!(await planGuard.hasFeature(ownerId, 'whatsappAutomations'))) continue; if ((await provider.readiness(entry.account, kind)) === 'ready') eligible.push(entry); } return eligible; diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index 8e0a7ae..15de3dc 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -1,6 +1,7 @@ import app from '@/app'; import { getPrismaClient } from '@/lib/prisma'; import { logger } from '@/logger'; +import { startBillingJobs } from '@/modules/billing'; import { startMpJobs } from '@/modules/mp'; import { startPaymentJobs } from '@/modules/payments'; import { startWhatsappJobs } from '@/modules/whatsapp'; @@ -17,6 +18,7 @@ const server = Bun.serve({ startMpJobs(); startPaymentJobs(); startWhatsappJobs(); +startBillingJobs(); async function shutdown(): Promise { server.stop(true); diff --git a/apps/backend/test/billing-entitlements.test.ts b/apps/backend/test/billing-entitlements.test.ts new file mode 100644 index 0000000..e81366b --- /dev/null +++ b/apps/backend/test/billing-entitlements.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements'; + +const now = new Date('2026-10-22T12:00:00.000Z'); +const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000); + +function makeDb(params: { + subscription?: Record | null; + groups?: number; + attendees?: number; +}) { + return { + billingSubscription: { findUnique: mock(async () => params.subscription ?? null) }, + group: { count: mock(async () => params.groups ?? 0) }, + attendee: { count: mock(async () => params.attendees ?? 0) }, + }; +} + +function makeGuard(db: ReturnType, enforced = true) { + return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now }); +} + +describe('resolvePlan', () => { + it('is Free without a subscription', () => { + expect(resolvePlan(null, now, 7)).toEqual({ plan: 'FREE', graceUntil: null }); + }); + + it('is Pro while a charge covers today', () => { + const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7); + expect(plan).toEqual({ plan: 'PRO', graceUntil: null }); + }); + + it('keeps Pro on grace after the paid period, then drops to Free', () => { + const onGrace = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-2) }, now, 7); + expect(onGrace).toEqual({ plan: 'PRO', graceUntil: days(5) }); + + const lapsed = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-8) }, now, 7); + expect(lapsed).toEqual({ plan: 'FREE', graceUntil: null }); + }); + + it('keeps Pro until the end of what was paid after a cancellation', () => { + const plan = resolvePlan({ status: 'CANCELLED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7); + expect(plan.plan).toBe('PRO'); + }); + + it('is Pro right after authorizing, while the first charge is in flight', () => { + const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-1), paidThrough: null }, now, 7); + expect(plan.plan).toBe('PRO'); + }); + + it('is Free for a subscription that was never authorized', () => { + const plan = resolvePlan({ status: 'PENDING', authorizedAt: null, paidThrough: null }, now, 7); + expect(plan.plan).toBe('FREE'); + }); +}); + +describe('PlanGuard', () => { + it('lets everything through without touching the database when not enforced', async () => { + const db = makeDb({ groups: 50, attendees: 500 }); + const guard = makeGuard(db, false); + + expect((await guard.canCreateGroup('user-1')).ok).toBe(true); + expect((await guard.canAddAttendees('user-1', 10)).ok).toBe(true); + expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true); + expect((await guard.requireWritable('user-1')).ok).toBe(true); + expect(db.group.count).not.toHaveBeenCalled(); + }); + + it('stops a Free professor at the group limit', async () => { + const result = await makeGuard(makeDb({ groups: 1 })).canCreateGroup('user-1'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' }); + }); + + it('counts a whole import against the attendee limit', async () => { + const guard = makeGuard(makeDb({ groups: 1, attendees: 10 })); + + expect((await guard.canAddAttendees('user-1', 5)).ok).toBe(true); + const tooMany = await guard.canAddAttendees('user-1', 6); + expect(tooMany.ok).toBe(false); + if (!tooMany.ok) expect(tooMany.error.code).toBe('plan_limit_reached'); + }); + + it('keeps Pro-only features off for Free', async () => { + const result = await makeGuard(makeDb({})).requireFeature('user-1', 'whatsappAutomations'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' }); + }); + + it('puts a Free account over its limits in read-only', async () => { + const guard = makeGuard(makeDb({ groups: 3, attendees: 40 })); + + const entitlements = await guard.getEntitlements('user-1'); + expect(entitlements.readOnly).toBe(true); + const writable = await guard.requireWritable('user-1'); + expect(writable.ok).toBe(false); + if (!writable.ok) expect(writable.error.code).toBe('plan_read_only'); + }); + + it('gives Pro no limits', async () => { + const guard = makeGuard( + makeDb({ + subscription: { status: 'AUTHORIZED', authorizedAt: days(-5), paidThrough: days(25) }, + groups: 12, + attendees: 300, + }), + ); + + expect((await guard.canCreateGroup('user-1')).ok).toBe(true); + expect((await guard.canAddAttendees('user-1', 100)).ok).toBe(true); + expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true); + expect((await guard.getEntitlements('user-1')).readOnly).toBe(false); + }); +}); diff --git a/apps/backend/test/billing-plan-guards.test.ts b/apps/backend/test/billing-plan-guards.test.ts new file mode 100644 index 0000000..ba118ce --- /dev/null +++ b/apps/backend/test/billing-plan-guards.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { err } from '@gruperly/shared'; +import { + planFeatureRequiredProblem, + planLimitReachedProblem, +} from '@/http/problem-builders'; +import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case'; +import { CreateGroup } from '@/modules/groups/features/create/use-case'; +import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case'; +import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case'; + +const ownerId = 'owner-1'; + +describe('plan guards in the use cases', () => { + it('does not create a group past the Free limit', async () => { + const unitOfWork = { executeResult: mock() }; + const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) }; + + const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute( + {} as never, + ownerId, + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' }); + expect(unitOfWork.executeResult).not.toHaveBeenCalled(); + }); + + it('checks a bulk import against the group owner, with the number of new attendees', async () => { + const db = { + group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) }, + attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() }, + }; + const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) }; + + const result = await new BulkCreateAttendeesUseCase({ db: db as never, planGuard }).execute('g1', 'admin-1', { + attendees: [ + { fullName: 'Ana', phone: '2222' }, + { fullName: 'Beto', phone: '3333' }, + { fullName: 'Repetido', phone: '1111' }, + ], + } as never); + + expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2); + expect(result.ok).toBe(false); + expect(db.attendee.create).not.toHaveBeenCalled(); + }); + + it('keeps charging with Mercado Pago for Pro', async () => { + const db = { + group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, price: 100, members: [] })) }, + attendee: { findMany: mock() }, + payment: { create: mock() }, + user: { findUnique: mock() }, + }; + const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('mpCharges'))) }; + + const result = await new CreatePaymentBatch({ db: db as never, planGuard }).execute('g1', ownerId, { + dueDate: '2026-11-05T12:00:00.000Z', + }); + + expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'mpCharges'); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' }); + expect(db.attendee.findMany).not.toHaveBeenCalled(); + }); + + it('blocks turning automations on for Free, but lets them be turned off', async () => { + const db = { + group: { + findUnique: mock(async () => ({ id: 'g1', createdById: ownerId })), + update: mock(async () => ({ autoPaymentReminders: false, autoReengagement: false })), + }, + }; + const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('whatsappAutomations'))) }; + const useCase = new UpdateGroupAutomationsUseCase({ db: db as never, planGuard }); + + const on = await useCase.execute('g1', ownerId, { autoPaymentReminders: true }); + expect(on.ok).toBe(false); + expect(db.group.update).not.toHaveBeenCalled(); + + const off = await useCase.execute('g1', ownerId, { autoPaymentReminders: false }); + expect(off.ok).toBe(true); + expect(db.group.update).toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/billing-subscribe.test.ts b/apps/backend/test/billing-subscribe.test.ts new file mode 100644 index 0000000..89bd3d3 --- /dev/null +++ b/apps/backend/test/billing-subscribe.test.ts @@ -0,0 +1,182 @@ +import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { ok } from '@gruperly/shared'; +import { billingNotAvailableProblem } from '@/http/problem-builders'; +import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; +import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; +import type { PreapprovalClient } from '@/modules/billing/lib'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); +const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' }); + +let calls: string[] = []; + +function makeDb(existing: Record | null, country: string | null = 'MX') { + return { + user: { findUnique: mock(async () => ({ id: userId, country })) }, + billingSubscription: { + findUnique: mock(async () => existing), + upsert: mock(async (args: { create: Record }) => { + calls.push('upsert'); + return { id: 'sub-1', paidThrough: existing?.paidThrough ?? null, ...args.create }; + }), + update: mock(async () => { + calls.push('update'); + return {}; + }), + }, + }; +} + +function makeClient(): PreapprovalClient { + return { + createPreapproval: mock(async () => { + calls.push('createPreapproval'); + return { id: 'pre-1', status: 'pending', externalReference: userId, initPoint: 'https://mp/checkout', nextPaymentDate: null }; + }), + cancelPreapproval: mock(async () => { + calls.push('cancelPreapproval'); + return { id: 'old', status: 'cancelled', externalReference: userId, initPoint: null, nextPaymentDate: null }; + }), + getPreapproval: mock(), + getAuthorizedPayment: mock(), + searchAuthorizedPayments: mock(), + } as unknown as PreapprovalClient; +} + +function subscribe(db: ReturnType, client = makeClient()) { + return { + client, + run: (returnTo: 'billing' | 'onboarding' = 'billing') => + new Subscribe({ db: db as never, client, credentials, webOrigin: 'http://web', now: () => now }).execute( + userId, + { payerEmail: 'profe@mail.com', returnTo }, + ), + }; +} + +describe('Subscribe', () => { + beforeEach(() => { + calls = []; + }); + + it('writes the PENDING row before asking Mercado Pago, in the country currency', async () => { + const db = makeDb(null); + const { client, run } = subscribe(db); + + const result = await run(); + + expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://mp/checkout' } }); + expect(calls).toEqual(['upsert', 'createPreapproval', 'update']); + expect(client.createPreapproval).toHaveBeenCalledWith('platform-token', { + reason: 'Gruperly Pro', + externalReference: userId, + payerEmail: 'profe@mail.com', + amount: 199, + currencyId: 'MXN', + backUrl: 'http://web/billing?sub=return', + startDate: undefined, + }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { mpPreapprovalId: 'pre-1', lastSyncedAt: now }, + }); + }); + + it('sends the onboarding back to its own step', async () => { + const { client, run } = subscribe(makeDb(null)); + await run('onboarding'); + + expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ + backUrl: 'http://web/onboarding?sub=return', + }); + }); + + it('refuses a second subscription while one is authorized', async () => { + const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', mpPreapprovalId: 'pre-0' })); + + const result = await run(); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 409, code: 'subscription_already_active' }); + expect(client.createPreapproval).not.toHaveBeenCalled(); + }); + + it('cancels an abandoned attempt before starting a new one', async () => { + const { run } = subscribe(makeDb({ status: 'PENDING', mpPreapprovalId: 'old' })); + + await run(); + + expect(calls).toEqual(['cancelPreapproval', 'upsert', 'createPreapproval', 'update']); + }); + + it('delays the first charge to the end of a period already paid', async () => { + const paidThrough = new Date('2026-11-10T00:00:00.000Z'); + const { client, run } = subscribe(makeDb({ status: 'CANCELLED', mpPreapprovalId: 'old', paidThrough })); + + await run(); + + expect(client.cancelPreapproval).not.toHaveBeenCalled(); + expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ + startDate: paidThrough, + }); + }); + + it('answers 503 when Gruperly has no account in that country', async () => { + const db = makeDb(null, 'PE'); + const client = makeClient(); + const result = await new Subscribe({ + db: db as never, + client, + credentials: () => ({ ok: false, error: billingNotAvailableProblem() }), + }).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing' }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' }); + expect(db.billingSubscription.upsert).not.toHaveBeenCalled(); + }); + + it('reports a Mercado Pago failure as 502 and keeps the row', async () => { + const client = makeClient(); + client.createPreapproval = mock(async () => { + throw new Error('down'); + }) as never; + const db = makeDb(null); + + const result = await subscribe(db, client).run(); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(502); + expect(db.billingSubscription.upsert).toHaveBeenCalled(); + }); +}); + +describe('CancelSubscription', () => { + it('cancels in Mercado Pago and keeps what was paid', async () => { + const db = { + billingSubscription: { + findUnique: mock(async () => ({ id: 'sub-1', status: 'AUTHORIZED', mpPreapprovalId: 'pre-1', country: 'AR' })), + update: mock(async () => ({})), + }, + }; + const client = makeClient(); + + const result = await new CancelSubscription({ db: db as never, client, credentials }).execute(userId); + + expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } }); + expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1'); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + }); + + it('has nothing to cancel without a live subscription', async () => { + const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } }; + + const result = await new CancelSubscription({ db: db as never, client: makeClient(), credentials }).execute(userId); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('no_active_subscription'); + }); +}); diff --git a/apps/backend/test/billing-sync.test.ts b/apps/backend/test/billing-sync.test.ts new file mode 100644 index 0000000..df2f7d2 --- /dev/null +++ b/apps/backend/test/billing-sync.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { ok } from '@gruperly/shared'; +import type { MpAuthorizedPayment, PreapprovalClient } from '@/modules/billing/lib'; +import { SyncSubscription } from '@/modules/billing/lib/sync'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); +const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' }); + +function subscription(overrides: Record = {}) { + return { + id: 'sub-1', + userId, + country: 'AR', + currency: 'ARS', + status: 'PENDING', + mpPreapprovalId: 'pre-1', + authorizedAt: null, + paidThrough: null, + ...overrides, + }; +} + +function invoice(overrides: Partial = {}): MpAuthorizedPayment { + return { + id: 'inv-1', + preapprovalId: 'pre-1', + status: 'processed', + paymentStatus: 'approved', + amount: 15000, + currencyId: 'ARS', + debitDate: '2026-10-20T10:00:00.000Z', + createdAt: '2026-10-20T09:00:00.000Z', + ...overrides, + }; +} + +function makeDb(row: Record | null) { + return { + billingSubscription: { + findUnique: mock(async () => row), + update: mock(async () => ({})), + updateMany: mock(async () => ({ count: 0 })), + }, + billingCharge: { upsert: mock(async () => ({})) }, + }; +} + +function makeClient(params: { status?: string; externalReference?: string | null; invoices?: MpAuthorizedPayment[] }) { + return { + getPreapproval: mock(async (_token: string, id: string) => ({ + id, + status: params.status ?? 'authorized', + externalReference: params.externalReference === undefined ? userId : params.externalReference, + initPoint: null, + nextPaymentDate: '2026-11-20T10:00:00.000Z', + })), + searchAuthorizedPayments: mock(async () => params.invoices ?? []), + createPreapproval: mock(), + cancelPreapproval: mock(), + getAuthorizedPayment: mock(), + } as unknown as PreapprovalClient; +} + +function sync(db: ReturnType, client: PreapprovalClient) { + return new SyncSubscription({ db: db as never, client, credentials, now: () => now }); +} + +describe('SyncSubscription', () => { + it('marks the subscription authorized and extends paidThrough one month from the debit', async () => { + const db = makeDb(subscription()); + + const result = await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1'); + + expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } }); + expect(db.billingCharge.upsert).toHaveBeenCalledWith({ + where: { mpAuthorizedPaymentId: 'inv-1' }, + create: { + subscriptionId: 'sub-1', + mpAuthorizedPaymentId: 'inv-1', + amount: 15000, + currency: 'ARS', + status: 'approved', + paidAt: new Date('2026-10-20T10:00:00.000Z'), + }, + update: { status: 'approved', paidAt: new Date('2026-10-20T10:00:00.000Z') }, + }); + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { + status: 'AUTHORIZED', + authorizedAt: now, + nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'), + paidThrough: new Date('2026-11-20T10:00:00.000Z'), + lastSyncedAt: now, + }, + }); + }); + + it('records a rejected charge without extending what was paid', async () => { + const paidThrough = new Date('2026-10-25T00:00:00.000Z'); + const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough })); + + await sync(db, makeClient({ invoices: [invoice({ paymentStatus: 'rejected' })] })).execute('sub-1'); + + const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[0].data; + expect(data.paidThrough).toEqual(paidThrough); + expect(data.authorizedAt).toBeUndefined(); + }); + + it('never moves paidThrough back', async () => { + const paidThrough = new Date('2027-01-01T00:00:00.000Z'); + const db = makeDb(subscription({ status: 'AUTHORIZED', paidThrough })); + + await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1'); + + const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[0].data; + expect(data.paidThrough).toEqual(paidThrough); + }); + + it('mirrors a cancellation done in Mercado Pago', async () => { + const db = makeDb(subscription({ status: 'AUTHORIZED' })); + + const result = await sync(db, makeClient({ status: 'cancelled' })).execute('sub-1'); + + expect(result.ok && result.value.status).toBe('CANCELLED'); + }); + + it('ignores a preapproval whose external_reference is not this user', async () => { + const db = makeDb(subscription()); + + const result = await sync(db, makeClient({ externalReference: 'someone-else' })).execute('sub-1'); + + expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } }); + expect(db.billingSubscription.update).not.toHaveBeenCalled(); + expect(db.billingCharge.upsert).not.toHaveBeenCalled(); + }); + + it('claims a preapproval that beat our own write of its id', async () => { + const db = makeDb(null); + let lookups = 0; + db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never; + db.billingSubscription.updateMany = mock(async () => ({ count: 1 })); + + const result = await sync(db, makeClient({})).byPreapprovalId('AR', 'pre-1'); + + expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({ + where: { userId, country: 'AR', mpPreapprovalId: null }, + data: { mpPreapprovalId: 'pre-1' }, + }); + expect(result.ok && result.value.synced).toBe(true); + }); + + it('does not claim a cancelled preapproval (a replaced attempt)', async () => { + const db = makeDb(null); + + const result = await sync(db, makeClient({ status: 'cancelled' })).byPreapprovalId('AR', 'old'); + + expect(result).toEqual({ ok: true, value: { synced: false, status: null } }); + expect(db.billingSubscription.updateMany).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/test/billing-webhook.test.ts b/apps/backend/test/billing-webhook.test.ts new file mode 100644 index 0000000..81439fc --- /dev/null +++ b/apps/backend/test/billing-webhook.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { createHmac } from 'node:crypto'; +import { err, ok } from '@gruperly/shared'; +import { billingProviderErrorProblem } from '@/http/problem-builders'; +import { isPublicApiRequest } from '@/http/session-auth'; +import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case'; +import type { PreapprovalClient } from '@/modules/billing/lib'; +import { verifyMpSignature } from '@/modules/billing/lib/webhook-signature'; + +const secret = 'webhook-secret'; +const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: secret }); + +function sign(dataId: string, requestId: string, ts = '1729600000') { + const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex'); + return `ts=${ts},v1=${v1}`; +} + +function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) { + const requestId = params.requestId ?? 'req-1'; + return { + country: 'ar', + rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }), + headers: new Headers({ + 'x-request-id': requestId, + 'x-signature': params.signature ?? sign(params.dataId, requestId), + }), + query: new URLSearchParams({ 'data.id': params.dataId, type: params.type }), + }; +} + +function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const })) { + const db = { + billingWebhookEvent: { + create: mock(async () => ({})), + delete: mock(async () => ({})), + }, + }; + const sync = { byPreapprovalId: mock(async () => syncResult) }; + const client = { + getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })), + } as unknown as PreapprovalClient; + return { db, sync, client }; +} + +function handler(deps: ReturnType) { + return new HandleBillingWebhook({ + db: deps.db as never, + sync: deps.sync as never, + client: deps.client, + credentials, + }); +} + +describe('verifyMpSignature', () => { + it('accepts Mercado Pago signatures and lower-cases alphanumeric ids', () => { + const signature = sign('abc123', 'req-1'); + expect(verifyMpSignature({ signature, requestId: 'req-1', dataId: 'ABC123', secret })).toBe(true); + }); + + it('rejects a tampered or missing signature', () => { + expect(verifyMpSignature({ signature: sign('1', 'req-1'), requestId: 'req-1', dataId: '2', secret })).toBe(false); + expect(verifyMpSignature({ signature: 'ts=1,v1=short', requestId: 'req-1', dataId: '1', secret })).toBe(false); + expect(verifyMpSignature({ signature: null, requestId: 'req-1', dataId: '1', secret })).toBe(false); + }); +}); + +describe('HandleBillingWebhook', () => { + it('rejects a bad signature before touching anything', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute( + request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }), + ); + + expect(result).toEqual(err('invalid_signature')); + expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); + expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); + }); + + it('re-fetches the preapproval instead of trusting the body', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(ok({ duplicate: false, applied: true })); + expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-1'); + expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { country: 'AR', dedupeKey: 'req-1' } }); + }); + + it('resolves an invoice notification to its subscription', async () => { + const deps = makeDeps(); + + await handler(deps).execute(request({ type: 'subscription_authorized_payment', dataId: 'inv-1' })); + + expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1'); + expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-9'); + }); + + it('answers a repeated delivery as a duplicate', async () => { + const deps = makeDeps(); + deps.db.billingWebhookEvent.create = mock(async () => { + throw Object.assign(new Error('unique'), { code: 'P2002' }); + }); + + const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(ok({ duplicate: true, applied: false })); + expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); + }); + + it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => { + const deps = makeDeps(err(billingProviderErrorProblem()) as never); + + const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); + + expect(result).toEqual(err('sync_failed')); + expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({ + where: { country_dedupeKey: { country: 'AR', dedupeKey: 'req-1' } }, + }); + }); + + it('acknowledges topics it does not handle', async () => { + const deps = makeDeps(); + + const result = await handler(deps).execute(request({ type: 'payment', dataId: '123' })); + + expect(result).toEqual(ok({ duplicate: false, applied: false })); + expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); + }); + + it('is reachable without a session, and only that path', () => { + expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true); + expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false); + }); +}); diff --git a/apps/backend/test/onboarding-select-plan.test.ts b/apps/backend/test/onboarding-select-plan.test.ts new file mode 100644 index 0000000..7c6dcd9 --- /dev/null +++ b/apps/backend/test/onboarding-select-plan.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { err, ok } from '@gruperly/shared'; +import { noActiveSubscriptionProblem } from '@/http/problem-builders'; +import { SelectPlan } from '@/modules/onboarding/features/select-plan/use-case'; + +const userId = 'user-1'; +const now = new Date('2026-10-22T12:00:00.000Z'); + +function makeDb(subscription: Record | null, user: Record = {}) { + return { + user: { + findUnique: mock(async () => ({ id: userId, onboardingCompleted: false, ...user })), + update: mock(async () => ({})), + }, + billingSubscription: { + findUnique: mock(async () => subscription), + update: mock(async () => ({})), + }, + }; +} + +function makeDeps(db: ReturnType) { + return { + db: db as never, + subscribe: { execute: mock(async () => ok({ checkoutUrl: 'https://mp/checkout' })) }, + cancel: { execute: mock(async () => ok({ status: 'CANCELLED' as const })) }, + now: () => now, + }; +} + +describe('SelectPlan (onboarding)', () => { + it('stores the country first and marks Free as chosen', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + + const result = await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'CL' }); + + expect(result).toEqual(ok({ plan: 'FREE', checkoutUrl: null })); + expect(db.user.update).toHaveBeenNthCalledWith(1, { where: { id: userId }, data: { country: 'CL' } }); + expect(db.user.update).toHaveBeenNthCalledWith(2, { where: { id: userId }, data: { planSelectedAt: now } }); + expect(deps.subscribe.execute).not.toHaveBeenCalled(); + }); + + it('voids an abandoned Pro attempt when switching to Free', async () => { + const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: 'pre-1' }); + const deps = makeDeps(db); + + await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(deps.cancel.execute).toHaveBeenCalledWith(userId); + }); + + it('voids it locally when Mercado Pago never got the attempt', async () => { + const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: null }); + const deps = makeDeps(db); + deps.cancel.execute = mock(async () => err(noActiveSubscriptionProblem())) as never; + + await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(db.billingSubscription.update).toHaveBeenCalledWith({ + where: { id: 'sub-1' }, + data: { status: 'CANCELLED', nextPaymentDate: null }, + }); + }); + + it('starts the subscription for Pro and comes back to the onboarding', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + + const result = await new SelectPlan(deps).execute(userId, { + plan: 'PRO', + country: 'AR', + payerEmail: 'profe@mail.com', + }); + + expect(result).toEqual(ok({ plan: 'PRO', checkoutUrl: 'https://mp/checkout' })); + expect(deps.subscribe.execute).toHaveBeenCalledWith(userId, { + payerEmail: 'profe@mail.com', + returnTo: 'onboarding', + }); + expect(db.user.update).toHaveBeenLastCalledWith({ where: { id: userId }, data: { planSelectedAt: now } }); + }); + + it('does not mark a plan when the subscription could not start', async () => { + const db = makeDb(null); + const deps = makeDeps(db); + deps.subscribe.execute = mock(async () => err({ title: 'x', status: 503, code: 'billing_not_available' })) as never; + + const result = await new SelectPlan(deps).execute(userId, { + plan: 'PRO', + country: 'PE', + payerEmail: 'profe@mail.com', + }); + + expect(result.ok).toBe(false); + expect(db.user.update).toHaveBeenCalledTimes(1); + }); + + it('never drops an authorized subscription from the onboarding', async () => { + const db = makeDb({ id: 'sub-1', status: 'AUTHORIZED' }); + + const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('subscription_already_active'); + }); + + it('refuses once the onboarding is completed', async () => { + const db = makeDb(null, { onboardingCompleted: true }); + + const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('onboarding_already_completed'); + }); +}); diff --git a/apps/backend/test/onboarding.test.ts b/apps/backend/test/onboarding.test.ts index a103418..80f5684 100644 --- a/apps/backend/test/onboarding.test.ts +++ b/apps/backend/test/onboarding.test.ts @@ -12,6 +12,9 @@ const db = { whatsappAccount: { findUnique: mock(async () => null), }, + billingSubscription: { + findUnique: mock(async () => null), + }, group: { create: mock(), }, @@ -72,6 +75,9 @@ const firstGroupPayload = { country: 'AR', }; +const noPlan = { planSelected: false, selectedPlan: null, subscriptionStatus: null, country: null }; +const planSelectedAt = new Date('2026-08-01T09:00:00.000Z'); + describe('onboarding routes', () => { beforeEach(() => { vi.clearAllMocks(); @@ -90,6 +96,7 @@ describe('onboarding routes', () => { paymentConnected: false, whatsappConnected: false, completed: false, + ...noPlan, }); }); @@ -105,6 +112,7 @@ describe('onboarding routes', () => { paymentConnected: true, whatsappConnected: false, completed: false, + ...noPlan, }); }); @@ -124,6 +132,7 @@ describe('onboarding routes', () => { paymentConnected: false, whatsappConnected: false, completed: false, + ...noPlan, }); }); @@ -138,6 +147,27 @@ describe('onboarding routes', () => { paymentConnected: true, whatsappConnected: false, completed: true, + ...noPlan, + }); + }); + + it('reports a chosen Pro plan while its subscription is still pending', async () => { + prisma.user.findUnique.mockResolvedValue({ + id: userId, + onboardingCompleted: false, + planSelectedAt, + country: 'MX', + }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.billingSubscription.findUnique.mockResolvedValueOnce({ status: 'PENDING' }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(await res.json()).toMatchObject({ + planSelected: true, + selectedPlan: 'PRO', + subscriptionStatus: 'PENDING', + country: 'MX', }); }); @@ -151,7 +181,7 @@ describe('onboarding routes', () => { describe('POST /onboarding/first-group', () => { it('creates the first group and completes onboarding', async () => { - prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt }); prisma.group.create.mockResolvedValue(group); const res = await makeApp({ id: userId }).request('/onboarding/first-group', { @@ -202,7 +232,7 @@ describe('onboarding routes', () => { }); it('creates the group without Mercado Pago linked, since that step is skippable', async () => { - prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt }); prisma.mpAccount.findUnique.mockResolvedValue(null); prisma.group.create.mockResolvedValue(group); @@ -216,6 +246,20 @@ describe('onboarding routes', () => { expect(prisma.group.create).toHaveBeenCalled(); }); + it('rejects until a plan was chosen, since the Plan step is mandatory', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt: null }); + + const res = await makeApp({ id: userId }).request('/onboarding/first-group', { + method: 'POST', + body: JSON.stringify(firstGroupPayload), + headers: { 'Content-Type': 'application/json' }, + }); + + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: 'plan_not_selected' }); + expect(prisma.group.create).not.toHaveBeenCalled(); + }); + it('rejects when onboarding is already completed', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true }); diff --git a/apps/web/src/components/layout/RootLayout.tsx b/apps/web/src/components/layout/RootLayout.tsx index 2a9d538..5ada8ad 100644 --- a/apps/web/src/components/layout/RootLayout.tsx +++ b/apps/web/src/components/layout/RootLayout.tsx @@ -1,6 +1,7 @@ import { useLocation } from '@tanstack/react-router' import type { ReactNode } from 'react' import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider' +import { PlanNotice, PlanUpgradePrompt } from '../../features/billing' import { MpReauthNotice } from '../../features/mp' import { isImmersiveRoute } from '../../lib/immersive-routes' import { cn } from '../../lib/utils' @@ -36,12 +37,16 @@ export function RootLayout({ children }: { children: ReactNode }) { de
para que fluya con el contenido y no tape la barra immersive ni el bottom nav; se oculta solo en Ajustes. */} + {/* Solo lectura o Pro en período de gracia, con la misma lógica. */} + {children}
+ {/* "Disponible en Pro": lo abre cualquier 402 de plan (MutationCache). */} + ) } diff --git a/apps/web/src/features/billing/BillingProvider.tsx b/apps/web/src/features/billing/BillingProvider.tsx new file mode 100644 index 0000000..c842482 --- /dev/null +++ b/apps/web/src/features/billing/BillingProvider.tsx @@ -0,0 +1,99 @@ +import type { BillingChargeList, BillingStatusDto } from '@gruperly/shared' +import type { UseQueryResult } from '@tanstack/react-query' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useNavigate, useSearch } from '@tanstack/react-router' +import type { ReactNode } from 'react' +import { createContext, useContext, useEffect, useRef, useState } from 'react' +import { useToast } from '../../components/ui' +import { ApiError, cancelSubscription, getBillingCharges } from '../../lib/api' +import { billingStatusQueryKey, useBillingStatus } from './useBillingStatus' +import { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling' + +type BillingContextValue = { + statusQuery: UseQueryResult + chargesQuery: UseQueryResult + chargesPage: number + setChargesPage: (page: number) => void + isSubscribeOpen: boolean + openSubscribe: () => void + closeSubscribe: () => void + cancel: () => void + isCancelling: boolean +} + +const BillingContext = createContext(null) + +export function BillingProvider({ children }: { children: ReactNode }) { + const search = useSearch({ from: '/_authenticated/billing' }) + const navigate = useNavigate() + const queryClient = useQueryClient() + const toast = useToast() + const [isSubscribeOpen, setIsSubscribeOpen] = useState(false) + const [chargesPage, setChargesPage] = useState(1) + const polling = useSubscriptionReturnPolling() + + const statusQuery = useBillingStatus({ refetchInterval: polling.refetchInterval }) + const chargesQuery = useQuery({ + queryKey: ['billing', 'charges', chargesPage], + queryFn: () => getBillingCharges(chargesPage), + }) + + // Vuelta de Mercado Pago (`?sub=return`): se reconsulta hasta que la + // suscripción deje de estar PENDING y se limpia la URL para que recargar no + // repita el aviso. + useEffect(() => { + if (search.sub !== 'return') return + polling.startPolling() + void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey }) + void navigate({ to: '/billing', search: {}, replace: true }) + }, [search.sub, navigate, queryClient, polling.startPolling]) + + // Avisar una sola vez cuando la suscripción queda activa tras volver. + const announced = useRef(false) + useEffect(() => { + if (!polling.isPolling || announced.current) return + if (statusQuery.data?.status === 'AUTHORIZED') { + announced.current = true + toast.success('¡Listo! Ya tenés Gruperly Pro.') + void queryClient.invalidateQueries({ queryKey: ['billing', 'charges'] }) + } + // `toast` cambia en cada aviso: el efecto depende solo del estado. + }, [polling.isPolling, statusQuery.data?.status, queryClient]) + + const cancelMutation = useMutation({ + mutationFn: cancelSubscription, + onSuccess: () => { + toast.success('Cancelaste tu suscripción. Seguís con Pro hasta el fin del período pago.') + void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey }) + }, + onError: (error: Error) => { + toast.error(error instanceof ApiError ? error.message : 'No pudimos cancelar la suscripción.') + }, + }) + + return ( + setIsSubscribeOpen(true), + closeSubscribe: () => setIsSubscribeOpen(false), + cancel: () => cancelMutation.mutate(), + isCancelling: cancelMutation.isPending, + }} + > + {children} + + ) +} + +export function useBilling() { + const context = useContext(BillingContext) + if (!context) { + throw new Error('useBilling debe usarse dentro de ') + } + return context +} diff --git a/apps/web/src/features/billing/BillingView.tsx b/apps/web/src/features/billing/BillingView.tsx new file mode 100644 index 0000000..f08808b --- /dev/null +++ b/apps/web/src/features/billing/BillingView.tsx @@ -0,0 +1,80 @@ +import { PLAN_LIMITS } from '@gruperly/shared' +import { Link } from '@tanstack/react-router' +import { ChevronLeft, Sparkles } from 'lucide-react' +import { useState } from 'react' +import { Button } from '../../components/ui' +import { formatPrice } from '../../lib/format' +import { useBilling } from './BillingProvider' +import { CancelSubscriptionModal } from './CancelSubscriptionModal' +import { ChargesList } from './ChargesList' +import { PlanOptionCard } from './PlanOptionCard' +import { PlanSummaryCard } from './PlanSummaryCard' +import { SubscribeModal } from './SubscribeModal' + +export function BillingView() { + const { statusQuery, openSubscribe, cancel, isCancelling } = useBilling() + const [isConfirmingCancel, setIsConfirmingCancel] = useState(false) + const status = statusQuery.data + + const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED' + const pending = status?.status === 'PENDING' + const proPrice = status ? `${formatPrice(status.priceAmount, status.currency)} / mes` : undefined + + return ( +
+
+ + + Ajustes + +

Tu plan

+

Elegí cómo usar Gruperly.

+
+ + + + {status ? ( +
+ + + {subscribed ? ( + + ) : status.availableInCountry ? ( + + ) : ( +

Todavía no está disponible en tu país.

+ )} +
+
+ ) : null} + + + + + setIsConfirmingCancel(false)} + onConfirm={() => { + setIsConfirmingCancel(false) + cancel() + }} + /> +
+ ) +} diff --git a/apps/web/src/features/billing/CancelSubscriptionModal.tsx b/apps/web/src/features/billing/CancelSubscriptionModal.tsx new file mode 100644 index 0000000..d124742 --- /dev/null +++ b/apps/web/src/features/billing/CancelSubscriptionModal.tsx @@ -0,0 +1,45 @@ +import { Loader2 } from 'lucide-react' +import { Button, Modal } from '../../components/ui' +import { formatBillingDate } from './copy' + +type CancelSubscriptionModalProps = { + isOpen: boolean + isPending: boolean + paidThrough: string | null + onClose: () => void + onConfirm: () => void +} + +/** Cancelar se confirma: deja de debitarse, pero el período pago se mantiene. */ +export function CancelSubscriptionModal({ + isOpen, + isPending, + paidThrough, + onClose, + onConfirm, +}: CancelSubscriptionModalProps) { + const until = formatBillingDate(paidThrough) + return ( + +
+ + +
+
+ ) +} diff --git a/apps/web/src/features/billing/ChargesList.tsx b/apps/web/src/features/billing/ChargesList.tsx new file mode 100644 index 0000000..2cd0a4f --- /dev/null +++ b/apps/web/src/features/billing/ChargesList.tsx @@ -0,0 +1,63 @@ +import { Button } from '../../components/ui' +import { formatPrice } from '../../lib/format' +import { useBilling } from './BillingProvider' +import { formatBillingDate } from './copy' + +const CHARGE_STATUS_LABELS: Record = { + approved: 'Pagado', + rejected: 'Rechazado', + pending: 'Pendiente', + in_process: 'En proceso', + cancelled: 'Cancelado', + refunded: 'Devuelto', +} + +/** Historial de cobros de la suscripción a Pro. */ +export function ChargesList() { + const { chargesQuery, chargesPage, setChargesPage } = useBilling() + const charges = chargesQuery.data?.data ?? [] + const totalPages = chargesQuery.data?.pagination.totalPages ?? 0 + + if (charges.length === 0) return null + + return ( +
+

Historial de pagos

+
    + {charges.map((charge) => ( +
  • +
    +

    {formatPrice(charge.amount, charge.currency)}

    +

    + {formatBillingDate(charge.paidAt ?? charge.createdAt)} +

    +
    + + {CHARGE_STATUS_LABELS[charge.status] ?? charge.status} + +
  • + ))} +
+ {totalPages > 1 ? ( +
+ + +
+ ) : null} +
+ ) +} diff --git a/apps/web/src/features/billing/PlanNotice.tsx b/apps/web/src/features/billing/PlanNotice.tsx new file mode 100644 index 0000000..a20245e --- /dev/null +++ b/apps/web/src/features/billing/PlanNotice.tsx @@ -0,0 +1,43 @@ +import { Link, useLocation } from '@tanstack/react-router' +import { TriangleAlert } from 'lucide-react' +import { useAuth } from '../../context/AuthProvider' +import { cn } from '../../lib/utils' +import { planNoticeMessage } from './copy' +import { useBillingStatus } from './useBillingStatus' + +/** + * Aviso global del plan: cuenta en solo lectura o Pro en período de gracia. + * Como `MpReauthNotice`, va dentro de
y solo con sesión iniciada. En la + * pantalla del plan no se muestra porque ahí está la acción, con más contexto. + */ +export function PlanNotice() { + const { user } = useAuth() + const statusQuery = useBillingStatus({ enabled: !!user }) + const pathname = useLocation({ select: (location) => location.pathname }) + + if (!user || pathname === '/billing' || !statusQuery.data) return null + const notice = planNoticeMessage(statusQuery.data) + if (!notice) return null + + const danger = notice.tone === 'danger' + return ( +
+ +

{notice.text}

+ + Ver plan + +
+ ) +} diff --git a/apps/web/src/features/billing/PlanOptionCard.tsx b/apps/web/src/features/billing/PlanOptionCard.tsx new file mode 100644 index 0000000..940d046 --- /dev/null +++ b/apps/web/src/features/billing/PlanOptionCard.tsx @@ -0,0 +1,50 @@ +import type { Plan, PlanLimits } from '@gruperly/shared' +import { Check } from 'lucide-react' +import type { ReactNode } from 'react' +import { Badge } from '../../components/ui' +import { cn } from '../../lib/utils' +import { PLAN_NAMES, planFeatureList } from './copy' + +type PlanOptionCardProps = { + plan: Plan + limits: PlanLimits + /** Precio ya formateado ("$15.000 / mes"); Free no lleva. */ + price?: string + current?: boolean + highlighted?: boolean + /** La acción de la tarjeta (elegir, suscribirse); queda abajo de todo. */ + children?: ReactNode +} + +/** Una tarjeta de plan, igual en la pantalla del plan y en el onboarding. */ +export function PlanOptionCard({ plan, limits, price, current, highlighted, children }: PlanOptionCardProps) { + return ( +
+
+

{PLAN_NAMES[plan]}

+ {current ? Tu plan : null} +
+

{price ?? 'Gratis'}

+ +
    + {planFeatureList(limits).map((feature) => ( +
  • + + + {feature.label} + +
  • + ))} +
+ + {children ?
{children}
: null} +
+ ) +} diff --git a/apps/web/src/features/billing/PlanSettingsCard.tsx b/apps/web/src/features/billing/PlanSettingsCard.tsx new file mode 100644 index 0000000..c5658a7 --- /dev/null +++ b/apps/web/src/features/billing/PlanSettingsCard.tsx @@ -0,0 +1,31 @@ +import { Link } from '@tanstack/react-router' +import { ChevronRight, Sparkles } from 'lucide-react' +import { Badge } from '../../components/ui' +import { PLAN_NAMES, planBadgeVariant } from './copy' +import { useBillingStatus } from './useBillingStatus' + +/** Entrada a la pantalla del plan desde Ajustes. */ +export function PlanSettingsCard() { + const statusQuery = useBillingStatus() + const status = statusQuery.data + + return ( +
+ + + + +
+

Plan

+

Tu plan de Gruperly y tus pagos

+
+ {status ? ( + + {status.readOnly ? 'Solo lectura' : PLAN_NAMES[status.plan]} + + ) : null} + + +
+ ) +} diff --git a/apps/web/src/features/billing/PlanSummaryCard.tsx b/apps/web/src/features/billing/PlanSummaryCard.tsx new file mode 100644 index 0000000..47dc901 --- /dev/null +++ b/apps/web/src/features/billing/PlanSummaryCard.tsx @@ -0,0 +1,89 @@ +import { Loader2 } from 'lucide-react' +import { Badge } from '../../components/ui' +import { formatPrice } from '../../lib/format' +import { useBilling } from './BillingProvider' +import { + formatBillingDate, + formatUsage, + PLAN_NAMES, + planBadgeVariant, + planNoticeMessage, + subscriptionStatusLabel, +} from './copy' + +/** El plan actual: estado de la suscripción, próximo cobro y uso contra los límites. */ +export function PlanSummaryCard() { + const { statusQuery } = useBilling() + const status = statusQuery.data + + if (!status) { + return ( +
+ +

Consultando tu plan…

+
+ ) + } + + const notice = planNoticeMessage(status) + const nextPayment = formatBillingDate(status.nextPaymentDate) + const paidThrough = formatBillingDate(status.paidThrough) + + return ( +
+
+
+

Plan {PLAN_NAMES[status.plan]}

+ + {status.readOnly ? 'Solo lectura' : subscriptionStatusLabel(status.status)} + +
+ {status.status === 'AUTHORIZED' && nextPayment ? ( +

+ Próximo cobro: {formatPrice(status.priceAmount, status.currency)} el {nextPayment} +

+ ) : null} + {status.status === 'PENDING' ? ( +

+ Estamos esperando que Mercado Pago confirme tu suscripción. +

+ ) : null} + {status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? ( +

Pagado hasta el {paidThrough}.

+ ) : null} + {!status.enforced ? ( +

+ Por ahora todas las funciones están habilitadas para todas las cuentas. +

+ ) : null} +
+ + {notice ? ( +

+ {notice.text} +

+ ) : null} + +
+
+
Grupos
+
+ {formatUsage(status.usage.groups, status.limits.maxGroups)} +
+
+
+
Alumnos activos
+
+ {formatUsage(status.usage.attendees, status.limits.maxAttendees)} +
+
+
+
+ ) +} diff --git a/apps/web/src/features/billing/PlanUpgradePrompt.tsx b/apps/web/src/features/billing/PlanUpgradePrompt.tsx new file mode 100644 index 0000000..8d8eb52 --- /dev/null +++ b/apps/web/src/features/billing/PlanUpgradePrompt.tsx @@ -0,0 +1,40 @@ +import { useNavigate } from '@tanstack/react-router' +import { Sparkles } from 'lucide-react' +import { Button, Modal } from '../../components/ui' +import { dismissPlanPrompt, usePlanPrompt } from './plan-prompt' + +/** + * Aviso de "esto es de Pro". Lo dispara cualquier 402 de plan (ver el + * MutationCache de main.tsx) o un botón que ya sabe que el plan no alcanza. + * El motivo es el `detail` del backend, que ya explica qué límite se alcanzó. + */ +export function PlanUpgradePrompt() { + const detail = usePlanPrompt() + const navigate = useNavigate() + + return ( + +
+ + +
+
+ ) +} diff --git a/apps/web/src/features/billing/SubscribeForm.tsx b/apps/web/src/features/billing/SubscribeForm.tsx new file mode 100644 index 0000000..0de85bf --- /dev/null +++ b/apps/web/src/features/billing/SubscribeForm.tsx @@ -0,0 +1,67 @@ +import { Loader2 } from 'lucide-react' +import { type FormEvent, useState } from 'react' +import { Button, Input, Label } from '../../components/ui' + +type SubscribeFormProps = { + defaultEmail: string + isPending: boolean + error: string | null + submitLabel?: string + onSubmit: (payerEmail: string) => void + onCancel?: () => void +} + +/** + * El email de la cuenta de Mercado Pago que paga. Mercado Pago exige que el + * profesor inicie sesión con ese mismo email, por eso se pide en vez de asumir + * el de Gruperly (que viene precargado). + */ +export function SubscribeForm({ + defaultEmail, + isPending, + error, + submitLabel = 'Ir a Mercado Pago', + onSubmit, + onCancel, +}: SubscribeFormProps) { + const [email, setEmail] = useState(defaultEmail) + + const handleSubmit = (event: FormEvent) => { + event.preventDefault() + onSubmit(email.trim()) + } + + return ( +
+
+ + setEmail(event.target.value)} + /> +

+ Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual. +

+
+ + {error ?

{error}

: null} + +
+ {onCancel ? ( + + ) : null} + +
+
+ ) +} diff --git a/apps/web/src/features/billing/SubscribeModal.tsx b/apps/web/src/features/billing/SubscribeModal.tsx new file mode 100644 index 0000000..409de00 --- /dev/null +++ b/apps/web/src/features/billing/SubscribeModal.tsx @@ -0,0 +1,32 @@ +import { Modal } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { useBilling } from './BillingProvider' +import { SubscribeForm } from './SubscribeForm' +import { useStartSubscription } from './useStartSubscription' + +export function SubscribeModal() { + const { user } = useAuth() + const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling() + const subscription = useStartSubscription() + + return ( + + {/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */} + {isSubscribeOpen ? ( + void subscription.start(email, 'billing')} + onCancel={closeSubscribe} + /> + ) : null} + + ) +} diff --git a/apps/web/src/features/billing/copy.ts b/apps/web/src/features/billing/copy.ts new file mode 100644 index 0000000..4927346 --- /dev/null +++ b/apps/web/src/features/billing/copy.ts @@ -0,0 +1,120 @@ +import type { BillingStatusDto, Plan, PlanFeature, PlanLimits, SubscriptionStatus } from '@gruperly/shared' +import type { BadgeVariant } from '../../components/ui' + +/* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el + paso del onboarding y los avisos tienen que decir lo mismo. Funciones puras, + cubiertas con tests sin renderizar. */ + +export const PLAN_NAMES: Record = { FREE: 'Free', PRO: 'Pro' } + +export const SUBSCRIBE_ERROR_MESSAGE = + 'No pudimos abrir Mercado Pago. Revisá tu conexión e intentá de nuevo.' + +/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */ +export function planFeatureList(limits: PlanLimits): { label: string; included: boolean }[] { + return [ + { + label: + limits.maxGroups === null + ? 'Grupos ilimitados' + : `${limits.maxGroups} ${limits.maxGroups === 1 ? 'grupo' : 'grupos'}`, + included: true, + }, + { + label: + limits.maxAttendees === null + ? 'Alumnos ilimitados' + : `Hasta ${limits.maxAttendees} alumnos activos`, + included: true, + }, + { label: 'Cobros con Mercado Pago', included: limits.mpCharges }, + { label: 'Mensajes automáticos por WhatsApp', included: limits.whatsappAutomations }, + ] +} + +export const PLAN_FEATURE_REQUIRED_MESSAGES: Record = { + mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.', + whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.', +} + +/** + * Si el plan del profesor incluye la función. Sin datos todavía, o con los + * límites apagados en el servidor, se deja pasar: el backend decide igual. + */ +export function hasPlanFeature(status: BillingStatusDto | undefined, feature: PlanFeature): boolean { + return !status || !status.enforced || status.limits[feature] +} + +export function subscriptionStatusLabel(status: SubscriptionStatus | null): string { + switch (status) { + case 'AUTHORIZED': + return 'Activa' + case 'PENDING': + return 'Pendiente de pago' + case 'PAUSED': + return 'Pausada' + case 'CANCELLED': + return 'Cancelada' + default: + return 'Sin suscripción' + } +} + +export function planBadgeVariant(status: BillingStatusDto): BadgeVariant { + if (status.readOnly) return 'danger' + if (status.graceUntil) return 'warning' + return status.plan === 'PRO' ? 'success' : 'neutral' +} + +export function formatBillingDate(iso: string | null): string | null { + if (!iso) return null + const date = new Date(iso) + if (Number.isNaN(date.getTime())) return null + return new Intl.DateTimeFormat('es', { day: 'numeric', month: 'short', year: 'numeric' }).format( + date, + ) +} + +/** "3 de 15": el uso contra el límite, o solo el uso cuando no hay límite. */ +export function formatUsage(used: number, limit: number | null): string { + return limit === null ? `${used}` : `${used} de ${limit}` +} + +const PLAN_PROBLEM_CODES = ['plan_limit_reached', 'plan_feature_required', 'plan_read_only'] + +type PlanProblemError = { status: number; problem: { code?: string; detail?: string } | null } + +/** + * Un 402 del backend porque el plan no alcanza: se ofrece pasar a Pro. Mira la + * forma de `ApiError` en vez de importarlo, así el copy no arrastra el cliente. + */ +export function isPlanProblem(error: unknown): error is PlanProblemError { + if (typeof error !== 'object' || error === null) return false + const candidate = error as Partial + return candidate.status === 402 && PLAN_PROBLEM_CODES.includes(candidate.problem?.code ?? '') +} + +/** + * Qué decir arriba de la app cuando el plan limita. `null` si no hay nada que + * avisar. El período de gracia se avisa aunque la cuenta siga funcionando: si + * no paga, en unos días puede quedar en solo lectura. + */ +export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' | 'warning'; text: string } | null { + if (status.readOnly) { + return { + tone: 'danger', + text: 'Tu cuenta está en solo lectura: superás los límites del plan Free. Pasate a Pro o reducí tus alumnos para volver a editar.', + } + } + const graceUntil = formatBillingDate(status.graceUntil) + if (graceUntil) { + return { + tone: 'warning', + text: + status.status === 'CANCELLED' + ? `Cancelaste Pro: lo seguís teniendo hasta el ${graceUntil}.` + : `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en Mercado Pago antes del ${graceUntil}.`, + } + } + return null +} diff --git a/apps/web/src/features/billing/index.ts b/apps/web/src/features/billing/index.ts new file mode 100644 index 0000000..0fe0bd0 --- /dev/null +++ b/apps/web/src/features/billing/index.ts @@ -0,0 +1,18 @@ +export { + formatBillingDate, + hasPlanFeature, + isPlanProblem, + PLAN_FEATURE_REQUIRED_MESSAGES, + PLAN_NAMES, + planFeatureList, + planNoticeMessage, + subscriptionStatusLabel, +} from './copy' +export { dismissPlanPrompt, showPlanPrompt, usePlanPrompt } from './plan-prompt' +export { PlanNotice } from './PlanNotice' +export { PlanOptionCard } from './PlanOptionCard' +export { PlanSettingsCard } from './PlanSettingsCard' +export { PlanUpgradePrompt } from './PlanUpgradePrompt' +export { SubscribeForm } from './SubscribeForm' +export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus' +export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling' diff --git a/apps/web/src/features/billing/plan-prompt.ts b/apps/web/src/features/billing/plan-prompt.ts new file mode 100644 index 0000000..30672ed --- /dev/null +++ b/apps/web/src/features/billing/plan-prompt.ts @@ -0,0 +1,34 @@ +import { useSyncExternalStore } from 'react' + +/* El aviso de "pasate a Pro" se dispara desde cualquier mutación (el + MutationCache de main.tsx) y se muestra en un solo lugar (RootLayout). Este + store mínimo los conecta sin un provider más en el árbol. */ + +let current: string | null = null +const listeners = new Set<() => void>() + +function emit() { + for (const listener of listeners) listener() +} + +/** Muestra el aviso con el motivo que mandó el backend (o uno propio). */ +export function showPlanPrompt(detail: string) { + current = detail + emit() +} + +export function dismissPlanPrompt() { + current = null + emit() +} + +export function usePlanPrompt(): string | null { + return useSyncExternalStore( + (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + () => current, + () => null, + ) +} diff --git a/apps/web/src/features/billing/useBillingStatus.ts b/apps/web/src/features/billing/useBillingStatus.ts new file mode 100644 index 0000000..8189cfc --- /dev/null +++ b/apps/web/src/features/billing/useBillingStatus.ts @@ -0,0 +1,22 @@ +import type { BillingStatusDto } from '@gruperly/shared' +import { useQuery } from '@tanstack/react-query' +import { getBillingStatus } from '../../lib/api' + +/** La misma clave en toda la app: Ajustes, /billing, el onboarding y los avisos. */ +export const billingStatusQueryKey = ['billing', 'status'] as const + +type UseBillingStatusOptions = { + /** `RootLayout` se renderiza sin sesión, así que la consulta se puede apagar. */ + enabled?: boolean + /** Al volver de Mercado Pago: cada cuánto reconsultar, según el último estado. */ + refetchInterval?: (data: BillingStatusDto | undefined) => number | false +} + +export function useBillingStatus({ enabled = true, refetchInterval }: UseBillingStatusOptions = {}) { + return useQuery({ + queryKey: billingStatusQueryKey, + queryFn: getBillingStatus, + enabled, + refetchInterval: refetchInterval ? (query) => refetchInterval(query.state.data) : false, + }) +} diff --git a/apps/web/src/features/billing/useStartSubscription.ts b/apps/web/src/features/billing/useStartSubscription.ts new file mode 100644 index 0000000..441405f --- /dev/null +++ b/apps/web/src/features/billing/useStartSubscription.ts @@ -0,0 +1,28 @@ +import type { BillingReturnTo } from '@gruperly/shared' +import { useState } from 'react' +import { ApiError, subscribeToPro } from '../../lib/api' +import { SUBSCRIBE_ERROR_MESSAGE } from './copy' + +/** + * Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se + * resuelve con `fetch`: el navegador navega a Mercado Pago para que el profesor + * autorice el débito, y Mercado Pago lo devuelve con `?sub=return`. + */ +export function useStartSubscription() { + const [error, setError] = useState(null) + const [isStarting, setIsStarting] = useState(false) + + const start = async (payerEmail: string, returnTo: BillingReturnTo = 'billing') => { + setError(null) + setIsStarting(true) + try { + const { checkoutUrl } = await subscribeToPro({ payerEmail, returnTo }) + window.location.assign(checkoutUrl) + } catch (caught) { + setError(caught instanceof ApiError && caught.problem?.detail ? caught.problem.detail : SUBSCRIBE_ERROR_MESSAGE) + setIsStarting(false) + } + } + + return { start, isStarting, error } +} diff --git a/apps/web/src/features/billing/useSubscriptionReturnPolling.ts b/apps/web/src/features/billing/useSubscriptionReturnPolling.ts new file mode 100644 index 0000000..b76a562 --- /dev/null +++ b/apps/web/src/features/billing/useSubscriptionReturnPolling.ts @@ -0,0 +1,24 @@ +import type { BillingStatusDto } from '@gruperly/shared' +import { useCallback, useState } from 'react' + +const POLL_EVERY_MS = 5_000 +const POLL_FOR_MS = 60_000 + +/** + * Al volver de Mercado Pago la suscripción suele seguir PENDING unos segundos: + * el webhook todavía no llegó (en local, nunca llega). El backend la reconsulta + * a Mercado Pago en cada status, así que alcanza con reconsultar un rato. + */ +export function useSubscriptionReturnPolling() { + const [pollUntil, setPollUntil] = useState(null) + + const startPolling = useCallback(() => setPollUntil(Date.now() + POLL_FOR_MS), []) + + const refetchInterval = useCallback( + (data: BillingStatusDto | undefined) => + pollUntil !== null && Date.now() < pollUntil && data?.status === 'PENDING' ? POLL_EVERY_MS : false, + [pollUntil], + ) + + return { isPolling: pollUntil !== null, startPolling, refetchInterval } +} diff --git a/apps/web/src/features/groups/detail/GroupAutomationsCard.tsx b/apps/web/src/features/groups/detail/GroupAutomationsCard.tsx index 75b133a..775650d 100644 --- a/apps/web/src/features/groups/detail/GroupAutomationsCard.tsx +++ b/apps/web/src/features/groups/detail/GroupAutomationsCard.tsx @@ -1,7 +1,8 @@ import type { GroupAutomationsDto } from '@gruperly/shared' import { Link } from '@tanstack/react-router' import { MessageCircle } from 'lucide-react' -import { Switch } from '../../../components/ui' +import { Badge, Switch } from '../../../components/ui' +import { hasPlanFeature, useBillingStatus } from '../../billing' import { automationBlockedReason, useWhatsappStatus, WEEKLY_SEND_LABEL } from '../../whatsapp' import { useGroupDetail } from './GroupDetailProvider' @@ -35,7 +36,9 @@ const AUTOMATIONS: readonly Automation[] = [ export function GroupAutomationsCard() { const { group, updateAutomations, isUpdatingAutomations, isGroupOwner } = useGroupDetail() const whatsappQuery = useWhatsappStatus({ enabled: isGroupOwner }) + const billingQuery = useBillingStatus({ enabled: isGroupOwner }) if (!group || !isGroupOwner) return null + const includedInPlan = hasPlanFeature(billingQuery.data, 'whatsappAutomations') return (
@@ -44,8 +47,22 @@ export function GroupAutomationsCard() {
-

Mensajes automáticos por WhatsApp

-

{WEEKLY_SEND_LABEL}

+
+

Mensajes automáticos por WhatsApp

+ {includedInPlan ? null : Pro} +
+

+ {WEEKLY_SEND_LABEL} + {includedInPlan ? null : ( + <> + {' '} + Disponible en el plan Pro.{' '} + + Ver planes + + + )} +

@@ -75,7 +92,9 @@ export function GroupAutomationsCard() { updateAutomations({ [automation.key]: next })} diff --git a/apps/web/src/features/groups/detail/GroupDetailView.tsx b/apps/web/src/features/groups/detail/GroupDetailView.tsx index 4dee958..4e94028 100644 --- a/apps/web/src/features/groups/detail/GroupDetailView.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailView.tsx @@ -2,6 +2,12 @@ import { useNavigate } from '@tanstack/react-router' import { Loader2 } from 'lucide-react' import { useState } from 'react' import { Button } from '../../../components/ui' +import { + hasPlanFeature, + PLAN_FEATURE_REQUIRED_MESSAGES, + showPlanPrompt, + useBillingStatus, +} from '../../billing' import { ChargeMembersModal } from './ChargeMembersModal' import { GroupAutomationsCard } from './GroupAutomationsCard' import { GroupHeader } from './GroupHeader' @@ -23,16 +29,27 @@ export function GroupDetailView() { firstWaitlistEntry, waitlistTotal, isSubmittingRemoval, + isGroupOwner, } = useGroupDetail() const navigate = useNavigate() const [isChargeModalOpen, setIsChargeModalOpen] = useState(false) + // El plan que cuenta es el del dueño: para un ADMIN no sabemos el suyo y + // decide el backend (un 402 abre el mismo aviso). + const billingQuery = useBillingStatus({ enabled: isGroupOwner }) + const handleCharge = () => { + if (isGroupOwner && !hasPlanFeature(billingQuery.data, 'mpCharges')) { + showPlanPrompt(PLAN_FEATURE_REQUIRED_MESSAGES.mpCharges) + return + } + setIsChargeModalOpen(true) + } return (
{/* The large title always renders, even while loading: it is what gives the immersive bar its height and stops the layout from jumping when the data arrives. */} - setIsChargeModalOpen(true)} /> + {groupQueryPending ? (
diff --git a/apps/web/src/features/onboarding/ConfirmationStep.tsx b/apps/web/src/features/onboarding/ConfirmationStep.tsx index 84216a1..bd8a363 100644 --- a/apps/web/src/features/onboarding/ConfirmationStep.tsx +++ b/apps/web/src/features/onboarding/ConfirmationStep.tsx @@ -1,12 +1,14 @@ import type { OnboardingGroupDto } from '@gruperly/shared' import { useQueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import { ArrowRight, CheckCircle2, CreditCard, MessageCircle } from 'lucide-react' +import { ArrowRight, CheckCircle2, CreditCard, MessageCircle, Sparkles } from 'lucide-react' import { Badge, Button } from '../../components/ui' import { useAuth } from '../../context/AuthProvider' +import { PLAN_NAMES } from '../billing' import { MP_PROVIDER_NAME, useMpStatus } from '../mp' import { useWhatsappStatus } from '../whatsapp' import { BILLING_LABELS, formatPrice, formatSchedule } from './constants' +import { useOnboarding } from './OnboardingProvider' type ConfirmationStepProps = { group: OnboardingGroupDto @@ -20,6 +22,7 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) { const isMpConnected = statusQuery.data?.status === 'active' const whatsappQuery = useWhatsappStatus() const isWhatsappConnected = whatsappQuery.data?.status === 'active' + const { selectedPlan } = useOnboarding() const goToDashboard = () => { // Revalidates the cache (onboarding state, session, groups) before redirecting. @@ -70,41 +73,58 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
-
- -

- {isMpConnected ? ( - <> - Vas a cobrar con {MP_PROVIDER_NAME}. Los - pagos entran directo en tu cuenta. - - ) : ( - <> - Cuando quieras cobrar, vinculá - {MP_PROVIDER_NAME} - {' '} - desde Ajustes. Tu grupo ya quedó creado. - - )} -

-
+ {selectedPlan ? ( +
+ +

+ Estás en el plan {PLAN_NAMES[selectedPlan]}. + {selectedPlan === 'FREE' + ? ' Cuando quieras cobrar con Mercado Pago o automatizar WhatsApp, pasate a Pro desde Ajustes.' + : ''} +

+
+ ) : null} -
- -

- {isWhatsappConnected ? ( - <> - Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la - ficha del grupo. - - ) : ( - <> - Para enviar recordatorios automáticos, vinculá{' '} - WhatsApp desde Ajustes. - - )} -

-
+ {/* Con Free no se cobra ni se automatiza: esos avisos son solo de Pro. */} + {selectedPlan === 'FREE' ? null : ( + <> +
+ +

+ {isMpConnected ? ( + <> + Vas a cobrar con {MP_PROVIDER_NAME}. Los + pagos entran directo en tu cuenta. + + ) : ( + <> + Cuando quieras cobrar, vinculá + {MP_PROVIDER_NAME} + {' '} + desde Ajustes. Tu grupo ya quedó creado. + + )} +

+
+ +
+ +

+ {isWhatsappConnected ? ( + <> + Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la + ficha del grupo. + + ) : ( + <> + Para enviar recordatorios automáticos, vinculá{' '} + WhatsApp desde Ajustes. + + )} +

+
+ + )}
) diff --git a/apps/web/src/features/onboarding/PlanStep.tsx b/apps/web/src/features/onboarding/PlanStep.tsx new file mode 100644 index 0000000..3a50fa4 --- /dev/null +++ b/apps/web/src/features/onboarding/PlanStep.tsx @@ -0,0 +1,199 @@ +import type { SelectPlanInput } from '@gruperly/shared' +import { COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react' +import { type ReactNode, useEffect, useState } from 'react' +import { Button } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { ApiError, selectPlan } from '../../lib/api' +import { formatPrice } from '../../lib/format' +import { + PlanOptionCard, + SubscribeForm, + useBillingStatus, + useSubscriptionReturnPolling, +} from '../billing' +import { useOnboarding } from './OnboardingProvider' + +const SELECT_PLAN_ERROR_MESSAGE = 'No pudimos guardar tu plan. Revisá tu conexión e intentá de nuevo.' + +/** + * Paso "Plan" del onboarding (obligatorio). Free sigue directo al primer grupo + * (sin Cobros ni WhatsApp, que son de Pro). Pro lleva a Mercado Pago a + * autorizar el débito y vuelve acá con `?sub=return`; mientras Mercado Pago + * confirma se puede seguir igual. + */ +export function PlanStep() { + const { user } = useAuth() + const queryClient = useQueryClient() + const { country, selectedPlan, setSelectedPlan, returnedFromSubscription, goTo, goBack, statusQuery } = + useOnboarding() + const [isEnteringEmail, setIsEnteringEmail] = useState(false) + const [error, setError] = useState(null) + const [proUnavailable, setProUnavailable] = useState(false) + + const polling = useSubscriptionReturnPolling() + const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null + const billingQuery = useBillingStatus({ + enabled: returnedFromSubscription || choseProBefore, + refetchInterval: polling.refetchInterval, + }) + useEffect(() => { + if (returnedFromSubscription) polling.startPolling() + }, [returnedFromSubscription, polling.startPolling]) + + const subscriptionStatus = billingQuery.data?.status ?? statusQuery.data?.subscriptionStatus ?? null + + const mutation = useMutation({ + mutationFn: (input: SelectPlanInput) => selectPlan(input), + onSuccess: (result) => { + void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] }) + if (result.checkoutUrl) { + window.location.assign(result.checkoutUrl) + return + } + setSelectedPlan(result.plan) + // `goTo` y no `goNext`: el plan recién elegido cambia la lista de pasos. + goTo(result.plan === 'FREE' ? 'group' : 'payment') + }, + onError: (caught: Error) => { + if (caught instanceof ApiError && caught.problem?.code === 'billing_not_available') { + setProUnavailable(true) + setIsEnteringEmail(false) + } + setError(caught instanceof ApiError && caught.problem?.detail ? caught.problem.detail : SELECT_PLAN_ERROR_MESSAGE) + }, + }) + + // Pending de `selectPlan` con Pro incluye el redirect: el botón queda cargando. + const isLeavingToMp = mutation.isPending || (mutation.isSuccess && !!mutation.data?.checkoutUrl) + const chooseFree = () => { + setError(null) + mutation.mutate({ plan: 'FREE', country }) + } + const choosePro = (payerEmail: string) => { + setError(null) + mutation.mutate({ plan: 'PRO', country, payerEmail }) + } + + const proPrice = `${formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country])} / mes` + + if (subscriptionStatus === 'AUTHORIZED') { + return ( + +

+ + ¡Listo! Tu suscripción a Pro quedó activa. +

+ +
+ ) + } + + if (subscriptionStatus === 'PENDING' && (returnedFromSubscription || choseProBefore) && !isEnteringEmail) { + const stillChecking = returnedFromSubscription && billingQuery.isFetching + return ( + +
+ {stillChecking ? ( + + ) : ( + + )} +
+

+ {returnedFromSubscription ? 'Procesando tu pago…' : 'Tu suscripción a Pro quedó pendiente'} +

+

+ {returnedFromSubscription + ? 'Mercado Pago puede tardar unos minutos en confirmarlo. Podés seguir mientras tanto: te avisamos cuando quede activa.' + : 'No terminaste de autorizar el débito en Mercado Pago. Podés reintentarlo o seguir con Free.'} +

+
+
+ + {error ?

{error}

: null} + +
+ {returnedFromSubscription ? ( + + ) : ( + <> + + + + )} +
+
+ ) + } + + return ( + +
+ + + + + + {proUnavailable ? ( +

Todavía no está disponible en tu país.

+ ) : isEnteringEmail ? ( + setIsEnteringEmail(false)} + /> + ) : ( + + )} +
+
+ + {error ?

{error}

: null} + +
+ +
+
+ ) +} + +/** Encabezado común a los tres estados del paso. */ +function StepShell({ children }: { children: ReactNode }) { + return ( +
+
+

Elegí tu plan

+

+ Empezá gratis o pasate a Pro para cobrar con Mercado Pago y automatizar WhatsApp. +

+
+ {children} +
+ ) +} diff --git a/apps/web/src/features/onboarding/steps.ts b/apps/web/src/features/onboarding/steps.ts new file mode 100644 index 0000000..52a748f --- /dev/null +++ b/apps/web/src/features/onboarding/steps.ts @@ -0,0 +1,55 @@ +import type { OnboardingStatusDto, Plan } from '@gruperly/shared' + +/* Los pasos del onboarding y cómo se retoma, como funciones puras: el provider + las usa y los tests las cubren sin montar nada. */ + +export type OnboardingStepId = + | 'welcome' + | 'country' + | 'plan' + | 'payment' + | 'whatsapp' + | 'group' + | 'done' + +export const STEP_LABELS: Record = { + welcome: 'Bienvenida', + country: 'País', + plan: 'Plan', + payment: 'Cobros', + whatsapp: 'WhatsApp', + group: 'Tu grupo', + done: 'Listo', +} + +const ALL_STEPS: readonly OnboardingStepId[] = [ + 'welcome', + 'country', + 'plan', + 'payment', + 'whatsapp', + 'group', + 'done', +] + +/** Pasos que solo sirven con Pro: con Free no se puede cobrar ni automatizar. */ +const PRO_ONLY_STEPS: readonly OnboardingStepId[] = ['payment', 'whatsapp'] + +/** Los pasos que se recorren con el plan elegido (sin elegir, se muestran todos). */ +export function visibleSteps(plan: Plan | null): OnboardingStepId[] { + return plan === 'FREE' ? ALL_STEPS.filter((id) => !PRO_ONLY_STEPS.includes(id)) : [...ALL_STEPS] +} + +/** + * Dónde retomar un onboarding interrumpido. Sin plan elegido arranca de cero + * (el país se guarda junto con el plan). Con Free va directo al grupo. Con Pro, + * una suscripción abandonada vuelve a Plan (para reintentar o pasar a Free) y si + * no, se sigue como antes: Cobros, WhatsApp o el grupo según lo ya vinculado. + */ +export function resumeStep(status: OnboardingStatusDto): OnboardingStepId | null { + if (!status.planSelected) return null + if (status.selectedPlan === 'FREE') return 'group' + if (status.subscriptionStatus === 'PENDING') return 'plan' + if (status.step === 'PAYMENT_CONNECTED') return status.whatsappConnected ? 'group' : 'whatsapp' + return 'payment' +} diff --git a/apps/web/src/features/settings/SettingsView.tsx b/apps/web/src/features/settings/SettingsView.tsx index 07e21af..897a588 100644 --- a/apps/web/src/features/settings/SettingsView.tsx +++ b/apps/web/src/features/settings/SettingsView.tsx @@ -2,6 +2,7 @@ import { Link } from '@tanstack/react-router' import { Fingerprint } from 'lucide-react' import { Button } from '../../components/ui' import { signOut } from '../../lib/auth-client' +import { PlanSettingsCard } from '../billing' import { MpStatusCard } from '../mp' import { WhatsappStatusCard } from '../whatsapp' import { AppearanceCard } from './AppearanceCard' @@ -36,6 +37,8 @@ export function SettingsView() { + + diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 739fd05..2e467b9 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -7,6 +7,8 @@ import type { AttendeeList, AttendeeStats, AttendeeStatus, + BillingChargeList, + BillingStatusDto, BulkCreateAttendees, BulkCreateAttendeesResult, ClassTodayList, @@ -49,8 +51,12 @@ import type { RejectGroupPreRegistrationResult, RemoveAttendeeResult, RemoveGroupWaitlistEntryResult, + SelectPlanInput, + SelectPlanResultDto, SessionStudents, StudentsAtRisk, + SubscribeInput, + SubscribeResultDto, UpdateAttendee, UpdateStudentStatusResult, GroupAutomationsDto, @@ -112,6 +118,14 @@ export const createFirstGroup = (payload: CreateFirstGroup) => body: JSON.stringify(payload), }) +/* Paso obligatorio "Plan" del onboarding. Con Pro devuelve `checkoutUrl`: el + navegador navega a Mercado Pago y vuelve a `/onboarding?sub=return`. */ +export const selectPlan = (payload: SelectPlanInput) => + apiFetch('/api/v1/onboarding/plan', { + method: 'POST', + body: JSON.stringify(payload), + }) + export const createGroup = (payload: CreateFirstGroup) => apiFetch('/api/v1/groups', { method: 'POST', @@ -131,6 +145,24 @@ export const getMpStatus = () => apiFetch('/api/v1/mp/status') export const disconnectMp = () => apiFetch('/api/v1/mp/connect', { method: 'DELETE' }) +// — Plan de Gruperly (suscripción a Pro con Mercado Pago) — + +export const getBillingStatus = () => apiFetch('/api/v1/billing/status') + +/* Igual que la vinculación de MP: el backend devuelve a dónde navegar y Mercado + Pago devuelve el control a `/billing?sub=return`. */ +export const subscribeToPro = (payload: SubscribeInput) => + apiFetch('/api/v1/billing/subscribe', { + method: 'POST', + body: JSON.stringify(payload), + }) + +export const cancelSubscription = () => + apiFetch<{ status: string }>('/api/v1/billing/cancel', { method: 'POST' }) + +export const getBillingCharges = (page = 1) => + apiFetch(`/api/v1/billing/charges?page=${page}&pageSize=10`) + // --- WhatsApp (recordatorios y reenganche automáticos) --- export const startWhatsappConnection = (returnTo: WhatsappReturnTo) => diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 6aa2b29..309f430 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,15 +1,26 @@ import React from 'react' import ReactDOM from 'react-dom/client' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { MutationCache, QueryClient, QueryClientProvider } from '@tanstack/react-query' import { RouterProvider } from '@tanstack/react-router' import { router } from './router' import { AuthProvider } from './context/AuthProvider' import { ThemeProvider } from './context/ThemeProvider' import { ToastProvider } from './components/ui' +import { isPlanProblem, showPlanPrompt } from './features/billing' import { PwaProvider } from './features/pwa' import './index.css' const queryClient = new QueryClient({ + // Un 402 de plan (límite de Free, función de Pro, solo lectura) en cualquier + // mutación abre el aviso para pasar a Pro. Cada pantalla sigue mostrando su + // propio error; esto solo suma la salida. + mutationCache: new MutationCache({ + onError: (error) => { + if (isPlanProblem(error)) { + showPlanPrompt(error.problem?.detail ?? 'Esta función está disponible en el plan Pro.') + } + }, + }), defaultOptions: { queries: { staleTime: 30_000, retry: 1 }, }, diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 76923a5..d28ec83 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -15,6 +15,7 @@ import { Route as OnboardingRouteImport } from './routes/onboarding' import { Route as SignupRouteImport } from './routes/signup' import { Route as VerifyEmailRouteImport } from './routes/verify-email' import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index' +import { Route as AuthenticatedBillingRouteImport } from './routes/_authenticated/billing' import { Route as AuthenticatedPaymentsRouteImport } from './routes/_authenticated/payments' import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile' import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticated/security' @@ -58,6 +59,11 @@ const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({ path: '/', getParentRoute: () => AuthenticatedRoute, } as any) +const AuthenticatedBillingRoute = AuthenticatedBillingRouteImport.update({ + id: '/billing', + path: '/billing', + getParentRoute: () => AuthenticatedRoute, +} as any) const AuthenticatedPaymentsRoute = AuthenticatedPaymentsRouteImport.update({ id: '/payments', path: '/payments', @@ -136,6 +142,7 @@ export interface FileRoutesByFullPath { '/onboarding': typeof OnboardingRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute + '/billing': typeof AuthenticatedBillingRoute '/payments': typeof AuthenticatedPaymentsRoute '/profile': typeof AuthenticatedProfileRoute '/security': typeof AuthenticatedSecurityRoute @@ -155,6 +162,7 @@ export interface FileRoutesByTo { '/onboarding': typeof OnboardingRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute + '/billing': typeof AuthenticatedBillingRoute '/payments': typeof AuthenticatedPaymentsRoute '/profile': typeof AuthenticatedProfileRoute '/security': typeof AuthenticatedSecurityRoute @@ -177,6 +185,7 @@ export interface FileRoutesById { '/onboarding': typeof OnboardingRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute + '/_authenticated/billing': typeof AuthenticatedBillingRoute '/_authenticated/payments': typeof AuthenticatedPaymentsRoute '/_authenticated/profile': typeof AuthenticatedProfileRoute '/_authenticated/security': typeof AuthenticatedSecurityRoute @@ -200,6 +209,7 @@ export interface FileRouteTypes { | '/onboarding' | '/signup' | '/verify-email' + | '/billing' | '/payments' | '/profile' | '/security' @@ -219,6 +229,7 @@ export interface FileRouteTypes { | '/onboarding' | '/signup' | '/verify-email' + | '/billing' | '/payments' | '/profile' | '/security' @@ -240,6 +251,7 @@ export interface FileRouteTypes { | '/onboarding' | '/signup' | '/verify-email' + | '/_authenticated/billing' | '/_authenticated/payments' | '/_authenticated/profile' | '/_authenticated/security' @@ -310,6 +322,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedIndexRouteImport parentRoute: typeof AuthenticatedRoute } + '/_authenticated/billing': { + id: '/_authenticated/billing' + path: '/billing' + fullPath: '/billing' + preLoaderRoute: typeof AuthenticatedBillingRouteImport + parentRoute: typeof AuthenticatedRoute + } '/_authenticated/payments': { id: '/_authenticated/payments' path: '/payments' @@ -405,6 +424,7 @@ declare module '@tanstack/react-router' { } interface AuthenticatedRouteChildren { + AuthenticatedBillingRoute: typeof AuthenticatedBillingRoute AuthenticatedPaymentsRoute: typeof AuthenticatedPaymentsRoute AuthenticatedProfileRoute: typeof AuthenticatedProfileRoute AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute @@ -420,6 +440,7 @@ interface AuthenticatedRouteChildren { } const AuthenticatedRouteChildren: AuthenticatedRouteChildren = { + AuthenticatedBillingRoute: AuthenticatedBillingRoute, AuthenticatedPaymentsRoute: AuthenticatedPaymentsRoute, AuthenticatedProfileRoute: AuthenticatedProfileRoute, AuthenticatedSecurityRoute: AuthenticatedSecurityRoute, diff --git a/apps/web/src/routes/_authenticated/billing.tsx b/apps/web/src/routes/_authenticated/billing.tsx new file mode 100644 index 0000000..9c3b242 --- /dev/null +++ b/apps/web/src/routes/_authenticated/billing.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { BillingProvider } from '../../features/billing/BillingProvider' +import { BillingView } from '../../features/billing/BillingView' + +export const Route = createFileRoute('/_authenticated/billing')({ + /* Mercado Pago devuelve el control acá con `?sub=return` después de autorizar + (o abandonar) la suscripción a Pro empezada desde esta pantalla. */ + validateSearch: (search: Record): { sub?: string } => ({ + sub: typeof search.sub === 'string' ? search.sub : undefined, + }), + component: () => ( + + + + ), +}) diff --git a/apps/web/src/routes/onboarding.tsx b/apps/web/src/routes/onboarding.tsx index 50dae5b..0cda82b 100644 --- a/apps/web/src/routes/onboarding.tsx +++ b/apps/web/src/routes/onboarding.tsx @@ -4,15 +4,17 @@ import { OnboardingView } from '../features/onboarding/OnboardingView' export const Route = createFileRoute('/onboarding')({ /* Los callbacks de Mercado Pago (`?mp=`) y de WhatsApp por redirect (`?wa=`) - devuelven el control acá con `success` o `error&reason=…`. Se validan como + devuelven el control acá con `success` o `error&reason=…`; la suscripción a + Pro vuelve con `?sub=return`. Se validan como search params para que el provider tenga los valores ya tipados y no tenga que leer el `location` crudo. */ validateSearch: ( search: Record, - ): { mp?: string; wa?: string; reason?: string } => ({ + ): { mp?: string; wa?: string; reason?: string; sub?: string } => ({ mp: typeof search.mp === 'string' ? search.mp : undefined, wa: typeof search.wa === 'string' ? search.wa : undefined, reason: typeof search.reason === 'string' ? search.reason : undefined, + sub: typeof search.sub === 'string' ? search.sub : undefined, }), component: () => ( diff --git a/apps/web/test/billing-copy.test.ts b/apps/web/test/billing-copy.test.ts new file mode 100644 index 0000000..24d1e45 --- /dev/null +++ b/apps/web/test/billing-copy.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from 'bun:test' +import type { BillingStatusDto } from '@gruperly/shared' +import { PLAN_LIMITS } from '@gruperly/shared' +import { + formatUsage, + hasPlanFeature, + isPlanProblem, + planBadgeVariant, + planFeatureList, + planNoticeMessage, + subscriptionStatusLabel, +} from '../src/features/billing/copy' + +function status(overrides: Partial = {}): BillingStatusDto { + return { + plan: 'FREE', + status: null, + readOnly: false, + graceUntil: null, + paidThrough: null, + nextPaymentDate: null, + payerEmail: null, + priceAmount: 15000, + currency: 'ARS', + country: 'AR', + availableInCountry: true, + enforced: true, + usage: { groups: 1, attendees: 3 }, + limits: PLAN_LIMITS.FREE, + ...overrides, + } +} + +/* El copy del plan lo comparten Ajustes, /billing, el onboarding y los avisos. */ +describe('copy del plan', () => { + test('lista lo que incluye cada plan', () => { + expect(planFeatureList(PLAN_LIMITS.FREE)).toEqual([ + { label: '1 grupo', included: true }, + { label: 'Hasta 15 alumnos activos', included: true }, + { label: 'Cobros con Mercado Pago', included: false }, + { label: 'Mensajes automáticos por WhatsApp', included: false }, + ]) + expect(planFeatureList(PLAN_LIMITS.PRO).every((feature) => feature.included)).toBe(true) + }) + + test('muestra el uso contra el límite', () => { + expect(formatUsage(3, 15)).toBe('3 de 15') + expect(formatUsage(42, null)).toBe('42') + }) + + test('nombra cada estado de la suscripción', () => { + expect(subscriptionStatusLabel('AUTHORIZED')).toBe('Activa') + expect(subscriptionStatusLabel('PENDING')).toBe('Pendiente de pago') + expect(subscriptionStatusLabel(null)).toBe('Sin suscripción') + }) + + test('avisa solo lectura antes que gracia', () => { + expect(planNoticeMessage(status())).toBeNull() + expect(planNoticeMessage(status({ readOnly: true }))?.tone).toBe('danger') + expect(planNoticeMessage(status({ plan: 'PRO', status: 'AUTHORIZED', graceUntil: '2026-11-01T00:00:00.000Z' }))?.tone).toBe('warning') + expect(planBadgeVariant(status({ readOnly: true }))).toBe('danger') + expect(planBadgeVariant(status({ plan: 'PRO', limits: PLAN_LIMITS.PRO }))).toBe('success') + }) + + test('el aviso de gracia distingue la cancelación de un cobro rechazado', () => { + const graceUntil = '2026-11-01T12:00:00.000Z' + expect(planNoticeMessage(status({ plan: 'PRO', status: 'CANCELLED', graceUntil }))?.text).toContain('Cancelaste Pro') + expect(planNoticeMessage(status({ plan: 'PRO', status: 'AUTHORIZED', graceUntil }))?.text).toContain('No pudimos cobrar') + }) + + test('deja pasar las funciones sin datos o sin límites aplicados', () => { + expect(hasPlanFeature(undefined, 'mpCharges')).toBe(true) + expect(hasPlanFeature(status({ enforced: false }), 'mpCharges')).toBe(true) + expect(hasPlanFeature(status(), 'mpCharges')).toBe(false) + expect(hasPlanFeature(status({ limits: PLAN_LIMITS.PRO }), 'whatsappAutomations')).toBe(true) + }) + + test('reconoce un 402 de plan y nada más', () => { + expect(isPlanProblem({ status: 402, problem: { code: 'plan_limit_reached' } })).toBe(true) + expect(isPlanProblem({ status: 402, problem: { code: 'otra_cosa' } })).toBe(false) + expect(isPlanProblem({ status: 409, problem: { code: 'plan_limit_reached' } })).toBe(false) + expect(isPlanProblem(new Error('x'))).toBe(false) + expect(isPlanProblem(null)).toBe(false) + }) +}) diff --git a/apps/web/test/onboarding-steps.test.ts b/apps/web/test/onboarding-steps.test.ts new file mode 100644 index 0000000..bb2c3f1 --- /dev/null +++ b/apps/web/test/onboarding-steps.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, test } from 'bun:test' +import type { OnboardingStatusDto } from '@gruperly/shared' +import { resumeStep, visibleSteps } from '../src/features/onboarding/steps' + +function status(overrides: Partial = {}): OnboardingStatusDto { + return { + step: 'NOT_STARTED', + paymentConnected: false, + whatsappConnected: false, + completed: false, + planSelected: false, + selectedPlan: null, + subscriptionStatus: null, + country: null, + ...overrides, + } +} + +describe('pasos del onboarding', () => { + test('con Free no se recorren Cobros ni WhatsApp', () => { + expect(visibleSteps('FREE')).toEqual(['welcome', 'country', 'plan', 'group', 'done']) + expect(visibleSteps('PRO')).toEqual(['welcome', 'country', 'plan', 'payment', 'whatsapp', 'group', 'done']) + expect(visibleSteps(null)).toEqual(visibleSteps('PRO')) + }) + + test('sin plan elegido arranca de cero', () => { + expect(resumeStep(status())).toBeNull() + }) + + test('con Free retoma en el primer grupo', () => { + expect(resumeStep(status({ planSelected: true, selectedPlan: 'FREE' }))).toBe('group') + }) + + test('una suscripción a Pro abandonada vuelve al paso Plan', () => { + expect( + resumeStep(status({ planSelected: true, selectedPlan: 'PRO', subscriptionStatus: 'PENDING' })), + ).toBe('plan') + }) + + test('con Pro activo sigue por Cobros, WhatsApp o el grupo', () => { + const pro = { planSelected: true, selectedPlan: 'PRO' as const, subscriptionStatus: 'AUTHORIZED' as const } + expect(resumeStep(status(pro))).toBe('payment') + expect(resumeStep(status({ ...pro, step: 'PAYMENT_CONNECTED', paymentConnected: true }))).toBe('whatsapp') + expect( + resumeStep(status({ ...pro, step: 'PAYMENT_CONNECTED', paymentConnected: true, whatsappConnected: true })), + ).toBe('group') + }) +}) diff --git a/docker-compose.yml b/docker-compose.yml index df62133..bb26b2a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,6 +32,25 @@ x-backend-env: &backend-env # Clave de 32 bytes en base64 (openssl rand -base64 32) para cifrar los tokens # en reposo. Sin ella, mp/callback falla al guardar la cuenta. TOKEN_ENCRYPTION_KEY: ${TOKEN_ENCRYPTION_KEY:-} + # Suscripcion a Gruperly Pro (docs/billing.md): credenciales de las cuentas de MP + # de Gruperly, una por pais. Un pais sin las dos variables no ofrece Pro (503). + MP_PLATFORM_ACCESS_TOKEN_AR: ${MP_PLATFORM_ACCESS_TOKEN_AR:-} + MP_PLATFORM_WEBHOOK_SECRET_AR: ${MP_PLATFORM_WEBHOOK_SECRET_AR:-} + MP_PLATFORM_ACCESS_TOKEN_BR: ${MP_PLATFORM_ACCESS_TOKEN_BR:-} + MP_PLATFORM_WEBHOOK_SECRET_BR: ${MP_PLATFORM_WEBHOOK_SECRET_BR:-} + MP_PLATFORM_ACCESS_TOKEN_CL: ${MP_PLATFORM_ACCESS_TOKEN_CL:-} + MP_PLATFORM_WEBHOOK_SECRET_CL: ${MP_PLATFORM_WEBHOOK_SECRET_CL:-} + MP_PLATFORM_ACCESS_TOKEN_CO: ${MP_PLATFORM_ACCESS_TOKEN_CO:-} + MP_PLATFORM_WEBHOOK_SECRET_CO: ${MP_PLATFORM_WEBHOOK_SECRET_CO:-} + MP_PLATFORM_ACCESS_TOKEN_MX: ${MP_PLATFORM_ACCESS_TOKEN_MX:-} + MP_PLATFORM_WEBHOOK_SECRET_MX: ${MP_PLATFORM_WEBHOOK_SECRET_MX:-} + MP_PLATFORM_ACCESS_TOKEN_PE: ${MP_PLATFORM_ACCESS_TOKEN_PE:-} + MP_PLATFORM_WEBHOOK_SECRET_PE: ${MP_PLATFORM_WEBHOOK_SECRET_PE:-} + MP_PLATFORM_ACCESS_TOKEN_UY: ${MP_PLATFORM_ACCESS_TOKEN_UY:-} + MP_PLATFORM_WEBHOOK_SECRET_UY: ${MP_PLATFORM_WEBHOOK_SECRET_UY:-} + # `on` aplica los limites del plan Free; cualquier otro valor deja a todos en Pro. + BILLING_ENFORCEMENT: ${BILLING_ENFORCEMENT:-off} + BILLING_GRACE_DAYS: ${BILLING_GRACE_DAYS:-7} # WhatsApp (recordatorios de pago y reenganche semanales). Ver docs/whatsapp.md. # `openwa` (MVP, gateway instalado aparte) o `kapso` (API oficial de Meta). Sin las # variables del proveedor elegido, /whatsapp/* responde 503 y el paso del diff --git a/docs/billing.md b/docs/billing.md new file mode 100644 index 0000000..acc8aea --- /dev/null +++ b/docs/billing.md @@ -0,0 +1,49 @@ +# Plan de Gruperly: Free y Pro con Suscripciones de Mercado Pago + +Gruperly le cobra **al profesor** una suscripción mensual a **Pro** con débito automático (Suscripciones de Mercado Pago, `/preapproval`). No tiene nada que ver con `payments`, que es lo que los **alumnos** le pagan al profesor con su propia cuenta de MP vinculada por OAuth. + +| | **Free** | **Pro** | +| --- | --- | --- | +| Grupos | 1 | Ilimitados | +| Alumnos activos (sumando todos los grupos del profesor) | 15 | Ilimitados | +| Cobros a alumnos con Mercado Pago | No | Sí | +| Mensajes automáticos por WhatsApp | No | Sí | + +Los límites y los precios por país viven en `packages/shared/src/schemas/billing.ts` (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`). No hay trial. + +## Reglas + +- **Los límites son del dueño del grupo** (`group.createdById`). Un ADMIN que agrega alumnos a un grupo ajeno consume el plan del dueño. +- **Pro dura mientras haya un cobro que cubra hoy**, más `BILLING_GRACE_DAYS` (7) de gracia después del último día pago. Esa regla cubre las dos situaciones: al **cancelar**, el profesor sigue con Pro hasta el fin de lo que pagó, y con un **cobro rechazado** también sigue mientras MP reintenta. Una suscripción recién autorizada y sin cobro todavía también es Pro, durante la gracia. +- **Solo lectura**: una cuenta Free que supera los límites (por ejemplo, un Pro que dejó de pagar y tiene 3 grupos) no puede escribir en grupos, alumnos, cobros, asistencias ni lista de espera. Responde `402 plan_read_only`. `DELETE` sigue abierto, así puede bajar el uso sin pagar. Billing, onboarding y las vinculaciones de MP y WhatsApp tampoco se bloquean. +- Errores de plan, todos `402` en Problem Details: `plan_limit_reached`, `plan_feature_required` y `plan_read_only`. En la web, el `MutationCache` de `main.tsx` abre el aviso "Disponible en Pro" ante cualquiera de esos errores. +- `BILLING_ENFORCEMENT=on` aplica los límites. Con cualquier otro valor, o sin la variable, todos funcionan como Pro y los guards no tocan la base. Sirve para desplegar sin pasar a solo lectura de golpe a los profesores actuales. +- **Onboarding**: el paso **Plan** (después de País) es obligatorio. `POST /onboarding/first-group` responde `409 plan_not_selected` si falta `users.plan_selected_at`. Con Free se saltean los pasos Cobros y WhatsApp. + +## Cuentas de Mercado Pago (una por país) + +MP no cobra entre países, así que Gruperly necesita **su propia cuenta en cada país** donde vende Pro. Por cada país: + +1. Crear la cuenta de MP de Gruperly y una aplicación en el [panel de desarrolladores](https://www.mercadopago.com/developers/panel/app). +2. Copiar el **Access Token de producción** en `MP_PLATFORM_ACCESS_TOKEN_`, donde `CC` es `AR`, `BR`, `CL`, `CO`, `MX`, `PE` o `UY`. +3. En **Webhooks**, configurar la URL `https:///api/v1/billing/webhooks/mp/` (país en minúscula) con los eventos **Planes y suscripciones** (`subscription_preapproval` y `subscription_authorized_payment`). Copiar la **clave secreta** en `MP_PLATFORM_WEBHOOK_SECRET_`. + +Un país sin las dos variables ofrece Pro como "no disponible" (`503 billing_not_available`). Free funciona igual. Estas son credenciales de **Gruperly**, no las del OAuth del profesor (`getMpAccessToken`). Nunca se loguean. + +## Flujo + +1. `POST /billing/subscribe` (o `POST /onboarding/plan` con `PRO`) crea la fila `billing_subscriptions` en `PENDING` **antes** de llamar a MP. Después crea el preapproval (`external_reference` = id del usuario, `payer_email` el que puso el profesor) y devuelve `{ checkoutUrl }`. El navegador navega ahí. +2. El profesor inicia sesión en MP **con ese mismo email** (MP lo exige) y autoriza. MP lo devuelve a `/billing?sub=return` o a `/onboarding?sub=return`. +3. El estado se sincroniza por tres caminos, todos con `SyncSubscription`, que es idempotente: + - el **webhook** verifica `x-signature` (HMAC-SHA256 de `id:;request-id:;ts:;`), deduplica en `billing_webhook_events` y **no confía en el body**: vuelve a pedirle a MP el preapproval y sus `authorized_payments`; + - `GET /billing/status` reconsulta a MP si la suscripción sigue `PENDING`, como mucho cada 30 s. Es lo que actualiza la pantalla al volver de MP; + - el job `ReconcileSubscriptions` (`*/30 * * * *` UTC) procesa las `PENDING` y las `AUTHORIZED` que llevan más de 24 h sin sincronizar, y da por `CANCELLED` las `PENDING` con más de 7 días. +4. Cada `authorized_payment` aprobado queda en `billing_charges` y extiende `paid_through` un mes desde el débito. `paid_through` nunca retrocede. + +Volver a suscribirse cancela en MP el intento `PENDING` anterior, así se puede corregir el email. Si todavía hay un período pago, el primer débito se agenda para cuando termine (`start_date`). + +## Desarrollo local + +- El webhook necesita una URL pública: el mismo túnel de ngrok de `MP_REDIRECT_URI` sirve (`https://TU-DOMINIO.ngrok-free.app/api/v1/billing/webhooks/mp/ar`). Sin webhook todo funciona igual, porque el status sincroniza al leer. +- Para probar sin plata real, usar **usuarios de prueba** de MP del mismo país (un vendedor de test cuyo token va en `MP_PLATFORM_ACCESS_TOKEN_AR` y un comprador de test para pagar). +- Para simular un vencimiento, poner `paid_through` en el pasado en `billing_subscriptions`. Con `BILLING_ENFORCEMENT=on` y más uso que el permitido por Free, aparece el aviso de solo lectura. diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 4dd6202..621c1f9 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -5,6 +5,7 @@ export * from './lib/result.js'; export * from './schemas/analytics.js'; export * from './schemas/attendance.js'; export * from './schemas/attendees.js'; +export * from './schemas/billing.js'; export * from './schemas/country.js'; export * from './schemas/enums.js'; export * from './schemas/groups.js'; diff --git a/packages/shared/src/schemas/billing.ts b/packages/shared/src/schemas/billing.ts new file mode 100644 index 0000000..a64148b --- /dev/null +++ b/packages/shared/src/schemas/billing.ts @@ -0,0 +1,130 @@ +import { z } from 'zod'; +import { type CountryCode, countryCodeSchema } from './country.js'; +import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; + +const isoDateTimeSchema = z.string().datetime(); + +// Gruperly's own plans: what the professor pays us, not what students pay them. +export const planSchema = z.enum(['FREE', 'PRO']); +export type Plan = z.output; + +export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges']); +export type PlanFeature = z.output; + +export type PlanLimits = { + /** Groups the professor owns. `null` means no limit. */ + maxGroups: number | null; + /** ACTIVE attendees across all the groups the professor owns. */ + maxAttendees: number | null; + whatsappAutomations: boolean; + mpCharges: boolean; +}; + +export const PLAN_LIMITS: Record = { + FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false }, + PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true }, +}; + +// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY). +// Mercado Pago does not charge across countries, so each one is collected by +// Gruperly's own account in that country. +export const PRO_PRICE_BY_COUNTRY: Record = { + AR: 15000, + BR: 49, + CL: 9900, + CO: 39900, + MX: 199, + PE: 39, + UY: 390, +}; + +// Mirror of the Mercado Pago preapproval status. +export const subscriptionStatusSchema = z.enum(['PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED']); +export type SubscriptionStatus = z.output; + +// Where the professor started the subscription, so Mercado Pago sends them back. +export const billingReturnToSchema = z.enum(['onboarding', 'billing']); +export type BillingReturnTo = z.output; + +const PlanLimitsSchema = z.object({ + maxGroups: z.number().int().nullable(), + maxAttendees: z.number().int().nullable(), + whatsappAutomations: z.boolean(), + mpCharges: z.boolean(), +}); + +export const BillingStatusDtoSchema = z.object({ + plan: planSchema, + /** `null` when the professor never started a subscription. */ + status: subscriptionStatusSchema.nullable(), + /** Free plan with more usage than its limits: only reads and deletes work. */ + readOnly: z.boolean(), + /** Set while a lapsed Pro still works: payment failed or cancelled, not yet expired. */ + graceUntil: isoDateTimeSchema.nullable(), + paidThrough: isoDateTimeSchema.nullable(), + nextPaymentDate: isoDateTimeSchema.nullable(), + payerEmail: z.string().nullable(), + priceAmount: z.number(), + currency: z.string(), + country: countryCodeSchema, + /** Gruperly has Mercado Pago credentials for the professor's country. */ + availableInCountry: z.boolean(), + /** `false` when the server runs with BILLING_ENFORCEMENT off. */ + enforced: z.boolean(), + usage: z.object({ groups: z.number().int(), attendees: z.number().int() }), + limits: PlanLimitsSchema, +}); +export type BillingStatusDto = z.output; + +export const SubscribeInputSchema = z.strictObject({ + // Mercado Pago requires the payer to log in with this exact email. + payerEmail: z.string().trim().email('Ingresá un email válido'), + returnTo: billingReturnToSchema.default('billing'), +}); +export type SubscribeInput = z.output; + +export const SubscribeResultDtoSchema = z.object({ + checkoutUrl: z.string(), +}); +export type SubscribeResultDto = z.output; + +export const BillingChargeDtoSchema = z.object({ + id: z.string(), + amount: z.number(), + currency: z.string(), + status: z.string(), + paidAt: isoDateTimeSchema.nullable(), + createdAt: isoDateTimeSchema, +}); +export type BillingChargeDto = z.output; + +export const BillingChargesQuerySchema = z.object({ + page: createPageSchema(), + pageSize: createPageSizeSchema(10), +}); +export type BillingChargesQuery = z.output; + +export const BillingChargeListSchema = z.object({ + data: z.array(BillingChargeDtoSchema), + pagination: createPaginationSchema(), +}); +export type BillingChargeList = z.output; + +// Onboarding step "Plan": mandatory. The country comes along because it is not +// stored until then, and it decides the price and the Mercado Pago account. +export const SelectPlanInputSchema = z.discriminatedUnion('plan', [ + z.strictObject({ plan: z.literal('FREE'), country: countryCodeSchema }), + z.strictObject({ + plan: z.literal('PRO'), + country: countryCodeSchema, + payerEmail: z.string().trim().email('Ingresá un email válido'), + }), +]); +export type SelectPlanInput = z.output; + +export const SelectPlanResultDtoSchema = z.object({ + plan: planSchema, + /** Only for PRO: where the browser goes to authorize the subscription. */ + checkoutUrl: z.string().nullable(), +}); +export type SelectPlanResultDto = z.output; diff --git a/packages/shared/src/schemas/onboarding.ts b/packages/shared/src/schemas/onboarding.ts index 2d2824a..c80dba1 100644 --- a/packages/shared/src/schemas/onboarding.ts +++ b/packages/shared/src/schemas/onboarding.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { planSchema, subscriptionStatusSchema } from './billing.js'; import { countryCodeSchema, DEFAULT_COUNTRY } from './country.js'; import { billingTypeSchema, weekdaySchema } from './enums.js'; import { GroupDtoSchema } from './groups.js'; @@ -65,5 +66,12 @@ export const OnboardingStatusDtoSchema = z.object({ // WhatsApp is its own skippable step and does not move `step`. whatsappConnected: z.boolean(), completed: z.boolean(), + // The "Plan" step is mandatory: these survive the round trip to Mercado Pago + // and a reload, so the flow resumes where it was. + planSelected: z.boolean(), + // PRO as soon as the professor chose it, even while the subscription is PENDING. + selectedPlan: planSchema.nullable(), + subscriptionStatus: subscriptionStatusSchema.nullable(), + country: countryCodeSchema.nullable(), }); export type OnboardingStatusDto = z.output; \ No newline at end of file