development #14

Merged
jselesan merged 102 commits from development into main 2026-11-07 13:21:43 +00:00
606 changed files with 53402 additions and 1197 deletions
Showing only changes of commit f5e77c99f6 - Show all commits

View File

@@ -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.

View File

@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty.
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `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_<CC>` / `MP_PLATFORM_WEBHOOK_SECRET_<CC>`, `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 `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).

View File

@@ -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"

View File

@@ -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;

View File

@@ -8,6 +8,8 @@ model User {
image String?
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")
@@ -21,6 +23,7 @@ model User {
waitlist WaitlistEntry[]
mpAccount MpAccount?
whatsappAccount WhatsappAccount?
subscription BillingSubscription?
@@map("users")
}

View File

@@ -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")
}

View File

@@ -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);

View File

@@ -216,3 +216,88 @@ export function noAttendeesToBillProblem(): ProblemDetails {
code: 'no_attendees_to_bill',
});
}
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',
});
}

View File

@@ -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'

View File

@@ -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<PrismaClient, 'group' | 'attendee'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
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 });

View File

@@ -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<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
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,

View File

@@ -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;

View File

@@ -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<PrismaClient, 'billingSubscription'>;
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<Result<{ status: SubscriptionStatus }, ProblemDetails>> {
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' });
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'billingCharge'> };
/** The professor's own Pro charges, newest first. */
export class ListBillingCharges {
constructor(private readonly deps: ListBillingChargesDeps = {}) {}
async execute(
query: BillingChargesQuery,
userId: string,
): Promise<Result<BillingChargeList, ProblemDetails>> {
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),
});
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingSubscription'>;
guard?: PlanGuard;
sync?: Pick<SyncSubscription, 'execute'>;
credentials?: typeof getPlatformCredentials;
now?: () => Date;
};
export class GetBillingStatus {
constructor(private readonly deps: GetBillingStatusDeps = {}) {}
async execute(userId: string): Promise<Result<BillingStatusDto, ProblemDetails>> {
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,
});
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingSubscription'>;
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<Result<SubscribeResultDto, ProblemDetails>> {
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<ReturnType<PreapprovalClient['createPreapproval']>>;
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 });
}
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'billingWebhookEvent'>;
client?: PreapprovalClient;
credentials?: typeof getPlatformCredentials;
sync?: Pick<SyncSubscription, 'byPreapprovalId'>;
};
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<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
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 };
}
}

View File

@@ -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';

View File

@@ -0,0 +1,2 @@
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
export { startBillingJobs } from './schedule';

View File

@@ -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<PrismaClient, 'billingSubscription'>;
sync?: Pick<SyncSubscription, 'execute'>;
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<ReconcileTotals> {
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;
}
}

View File

@@ -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();
}

View File

@@ -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<string, string | undefined> = process.env,
): Result<PlatformCredentials, ProblemDetails> {
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<string, string | undefined> = 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<string, string | undefined> = process.env): number {
const value = Number(env.BILLING_GRACE_DAYS);
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
}

View File

@@ -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<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
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<Entitlements> {
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<Result<void, ProblemDetails>> {
if (!this.enforced) return ok(undefined);
const entitlements = await this.getEntitlements(ownerId);
return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
}
async canCreateGroup(ownerId: string): Promise<Result<void, ProblemDetails>> {
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<Result<void, ProblemDetails>> {
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<Result<void, ProblemDetails>> {
return (await this.hasFeature(ownerId, feature))
? ok(undefined)
: err(planFeatureRequiredProblem(feature));
}
async hasFeature(ownerId: string, feature: PlanFeature): Promise<boolean> {
if (!this.enforced) return true;
const { limits } = await this.getEntitlements(ownerId);
return limits[feature];
}
}

View File

@@ -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;

View File

@@ -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';

View File

@@ -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<Record<string, unknown>> {
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<string, unknown> | 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<string, unknown>;
}
function toPreapproval(payload: Record<string, unknown>): 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<MpPreapproval> {
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<MpPreapproval> {
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
}
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
return toPreapproval(
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
method: 'PUT',
body: { status: 'cancelled' },
}),
);
}
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
const payment = (payload.payment ?? null) as Record<string, unknown> | 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<MpAuthorizedPayment> {
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<MpAuthorizedPayment[]> {
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<string, unknown>[]) : [];
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,
};

View File

@@ -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<BackendEnv> {
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();
};
}

View File

@@ -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<string, SubscriptionStatus> = {
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<PrismaClient, 'billingSubscription' | 'billingCharge'>;
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<Result<SyncOutcome, ProblemDetails>> {
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<ReturnType<PreapprovalClient['searchAuthorizedPayments']>>;
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<Result<SyncOutcome, ProblemDetails>> {
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 });
}
}

View File

@@ -0,0 +1,40 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/**
* Checks Mercado Pago's `x-signature` header (`ts=<ts>,v1=<hex>`).
*
* 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);
}

View File

@@ -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;

View File

@@ -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<PrismaClient, 'group' | 'groupPreRegistration'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
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(

View File

@@ -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<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
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(

View File

@@ -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<PlanGuard, 'canCreateGroup'>;
};
export class CreateGroup {
@@ -23,6 +25,11 @@ export class CreateGroup {
): Promise<Result<CreateGroupResult, ProblemDetails>> {
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({

View File

@@ -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<PrismaClient, 'user'>;
unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
};
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) => {

View File

@@ -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;

View File

@@ -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<PrismaClient, 'user' | 'billingSubscription'>;
subscribe?: Pick<Subscribe, 'execute'>;
cancel?: Pick<CancelSubscription, 'execute'>;
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<Result<SelectPlanResultDto, ProblemDetails>> {
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 });
}
}

View File

@@ -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<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount'>;
db?: Pick<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount' | 'billingSubscription'>;
};
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,
});
}
}

View File

@@ -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;

View File

@@ -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<PlanGuard, 'requireFeature'>;
};
/**
@@ -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());
}

View File

@@ -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<PlanGuard, 'requireFeature'>;
};
/**
@@ -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());
}

View File

@@ -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<PrismaClient, 'group'> };
type UpdateGroupAutomationsDeps = {
db?: Pick<PrismaClient, 'group'>;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
/**
* 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: {

View File

@@ -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<PrismaClient, 'group'>,
provider: MessagingProvider,
flag: AutomationFlag,
kind: WhatsappMessageKind,
planGuard: Pick<PlanGuard, 'hasFeature'> = new PlanGuard(),
): Promise<EligibleAccount[]> {
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;

View File

@@ -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<void> {
server.stop(true);

View File

@@ -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<string, unknown> | 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<typeof makeDb>, 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);
});
});

View File

@@ -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();
});
});

View File

@@ -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<string, unknown> | null, country: string | null = 'MX') {
return {
user: { findUnique: mock(async () => ({ id: userId, country })) },
billingSubscription: {
findUnique: mock(async () => existing),
upsert: mock(async (args: { create: Record<string, unknown> }) => {
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<typeof makeDb>, 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<typeof mock>).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<typeof mock>).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');
});
});

View File

@@ -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<string, unknown> = {}) {
return {
id: 'sub-1',
userId,
country: 'AR',
currency: 'ARS',
status: 'PENDING',
mpPreapprovalId: 'pre-1',
authorizedAt: null,
paidThrough: null,
...overrides,
};
}
function invoice(overrides: Partial<MpAuthorizedPayment> = {}): 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<string, unknown> | 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<typeof makeDb>, 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<string, unknown> }])[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<string, unknown> }])[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();
});
});

View File

@@ -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<typeof makeDeps>) {
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);
});
});

View File

@@ -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<string, unknown> | null, user: Record<string, unknown> = {}) {
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<typeof makeDb>) {
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');
});
});

View File

@@ -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 });

View File

@@ -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 <main> para que fluya con el contenido y no tape la barra
immersive ni el bottom nav; se oculta solo en Ajustes. */}
<MpReauthNotice />
{/* Solo lectura o Pro en período de gracia, con la misma lógica. */}
<PlanNotice />
{children}
</main>
</ImmersiveBarProvider>
</div>
<BottomNav />
{/* "Disponible en Pro": lo abre cualquier 402 de plan (MutationCache). */}
<PlanUpgradePrompt />
</div>
)
}

View File

@@ -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<BillingStatusDto>
chargesQuery: UseQueryResult<BillingChargeList>
chargesPage: number
setChargesPage: (page: number) => void
isSubscribeOpen: boolean
openSubscribe: () => void
closeSubscribe: () => void
cancel: () => void
isCancelling: boolean
}
const BillingContext = createContext<BillingContextValue | null>(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 (
<BillingContext.Provider
value={{
statusQuery,
chargesQuery,
chargesPage,
setChargesPage,
isSubscribeOpen,
openSubscribe: () => setIsSubscribeOpen(true),
closeSubscribe: () => setIsSubscribeOpen(false),
cancel: () => cancelMutation.mutate(),
isCancelling: cancelMutation.isPending,
}}
>
{children}
</BillingContext.Provider>
)
}
export function useBilling() {
const context = useContext(BillingContext)
if (!context) {
throw new Error('useBilling debe usarse dentro de <BillingProvider>')
}
return context
}

View File

@@ -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 (
<section className="space-y-6">
<div>
<Link
to="/settings"
className="mb-2 hidden items-center gap-1 text-sm text-foreground/60 hover:text-primary lg:inline-flex"
>
<ChevronLeft className="size-4" />
Ajustes
</Link>
<h1 className="text-2xl font-bold text-primary">Tu plan</h1>
<p className="mt-1 text-sm text-foreground/60">Elegí cómo usar Gruperly.</p>
</div>
<PlanSummaryCard />
{status ? (
<div className="grid gap-4 sm:grid-cols-2">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE} current={status.plan === 'FREE'} />
<PlanOptionCard
plan="PRO"
limits={PLAN_LIMITS.PRO}
price={proPrice}
current={status.plan === 'PRO'}
highlighted={status.plan === 'FREE'}
>
{subscribed ? (
<Button variant="outline" className="w-full" onClick={() => setIsConfirmingCancel(true)}>
Cancelar suscripción
</Button>
) : status.availableInCountry ? (
<Button variant="primary" className="w-full" onClick={openSubscribe}>
<Sparkles className="size-4" />
{pending ? 'Reintentar el pago' : 'Pasar a Pro'}
</Button>
) : (
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
)}
</PlanOptionCard>
</div>
) : null}
<ChargesList />
<SubscribeModal />
<CancelSubscriptionModal
isOpen={isConfirmingCancel}
isPending={isCancelling}
paidThrough={status?.paidThrough ?? null}
onClose={() => setIsConfirmingCancel(false)}
onConfirm={() => {
setIsConfirmingCancel(false)
cancel()
}}
/>
</section>
)
}

View File

@@ -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 (
<Modal
isOpen={isOpen}
onClose={onClose}
title="Cancelar Pro"
description={
until
? `No te vamos a cobrar más. Seguís con Pro hasta el ${until}; después tu cuenta pasa a Free.`
: 'No te vamos a cobrar más y tu cuenta pasa a Free.'
}
maxWidth="sm"
>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={onClose}>
Volver
</Button>
<Button variant="primary" disabled={isPending} onClick={onConfirm}>
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
Cancelar suscripción
</Button>
</div>
</Modal>
)
}

View File

@@ -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<string, string> = {
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 (
<section className="space-y-2">
<h2 className="text-sm font-semibold text-primary">Historial de pagos</h2>
<ul className="divide-y divide-border rounded-xl border border-border bg-surface">
{charges.map((charge) => (
<li key={charge.id} className="flex items-center justify-between gap-3 px-4 py-3">
<div className="min-w-0">
<p className="text-sm text-primary">{formatPrice(charge.amount, charge.currency)}</p>
<p className="text-xs text-foreground/50">
{formatBillingDate(charge.paidAt ?? charge.createdAt)}
</p>
</div>
<span className="text-xs text-foreground/60">
{CHARGE_STATUS_LABELS[charge.status] ?? charge.status}
</span>
</li>
))}
</ul>
{totalPages > 1 ? (
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
disabled={chargesPage <= 1}
onClick={() => setChargesPage(chargesPage - 1)}
>
Anteriores
</Button>
<Button
variant="ghost"
size="sm"
disabled={chargesPage >= totalPages}
onClick={() => setChargesPage(chargesPage + 1)}
>
Siguientes
</Button>
</div>
) : null}
</section>
)
}

View File

@@ -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 <main> 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 (
<div
className={cn(
'mb-4 flex items-start gap-3 rounded-xl border px-4 py-3',
danger ? 'border-danger/30 bg-danger-soft' : 'border-warning/30 bg-warning-soft',
)}
>
<TriangleAlert className={cn('mt-0.5 size-4 shrink-0', danger ? 'text-danger' : 'text-warning')} />
<p className={cn('min-w-0 flex-1 text-xs', danger ? 'text-danger' : 'text-warning')}>{notice.text}</p>
<Link
to="/billing"
className={cn(
'shrink-0 self-center text-sm font-medium underline',
danger ? 'text-danger' : 'text-warning',
)}
>
Ver plan
</Link>
</div>
)
}

View File

@@ -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 (
<div
className={cn(
'flex flex-col rounded-xl border bg-surface p-4',
highlighted ? 'border-accent ring-2 ring-accent/20' : 'border-border',
)}
>
<div className="flex items-center justify-between gap-3">
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
{current ? <Badge variant="info">Tu plan</Badge> : null}
</div>
<p className="mt-1 text-sm text-foreground/60">{price ?? 'Gratis'}</p>
<ul className="mt-3 flex-1 space-y-1.5">
{planFeatureList(limits).map((feature) => (
<li key={feature.label} className="flex items-start gap-2 text-sm">
<Check
className={cn('mt-0.5 size-4 shrink-0', feature.included ? 'text-success' : 'text-foreground/20')}
/>
<span className={feature.included ? 'text-primary' : 'text-foreground/40 line-through'}>
{feature.label}
</span>
</li>
))}
</ul>
{children ? <div className="mt-4">{children}</div> : null}
</div>
)
}

View File

@@ -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 (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<Link to="/billing" className="flex items-center gap-3 px-4 py-3 hover:bg-primary-soft">
<span className="rounded-lg bg-accent-soft p-2">
<Sparkles className="size-4 text-accent-fg" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">Plan</p>
<p className="text-xs text-foreground/50">Tu plan de Gruperly y tus pagos</p>
</div>
{status ? (
<Badge variant={planBadgeVariant(status)}>
{status.readOnly ? 'Solo lectura' : PLAN_NAMES[status.plan]}
</Badge>
) : null}
<ChevronRight className="size-4 text-foreground/40" />
</Link>
</div>
)
}

View File

@@ -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 (
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
<Loader2 className="size-4 animate-spin text-foreground/40" />
<p className="text-sm text-foreground/50">Consultando tu plan…</p>
</div>
)
}
const notice = planNoticeMessage(status)
const nextPayment = formatBillingDate(status.nextPaymentDate)
const paidThrough = formatBillingDate(status.paidThrough)
return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<div className="px-4 py-3">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-primary">Plan {PLAN_NAMES[status.plan]}</p>
<Badge variant={planBadgeVariant(status)}>
{status.readOnly ? 'Solo lectura' : subscriptionStatusLabel(status.status)}
</Badge>
</div>
{status.status === 'AUTHORIZED' && nextPayment ? (
<p className="mt-0.5 text-xs text-foreground/50">
Próximo cobro: {formatPrice(status.priceAmount, status.currency)} el {nextPayment}
</p>
) : null}
{status.status === 'PENDING' ? (
<p className="mt-0.5 text-xs text-foreground/50">
Estamos esperando que Mercado Pago confirme tu suscripción.
</p>
) : null}
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (
<p className="mt-0.5 text-xs text-foreground/50">Pagado hasta el {paidThrough}.</p>
) : null}
{!status.enforced ? (
<p className="mt-0.5 text-xs text-foreground/50">
Por ahora todas las funciones están habilitadas para todas las cuentas.
</p>
) : null}
</div>
{notice ? (
<p
className={
notice.tone === 'danger'
? 'bg-danger-soft px-4 py-3 text-xs text-danger'
: 'bg-warning-soft px-4 py-3 text-xs text-warning'
}
>
{notice.text}
</p>
) : null}
<dl className="grid grid-cols-2 gap-3 px-4 py-3">
<div>
<dt className="text-xs text-foreground/50">Grupos</dt>
<dd className="text-sm font-medium text-primary">
{formatUsage(status.usage.groups, status.limits.maxGroups)}
</dd>
</div>
<div>
<dt className="text-xs text-foreground/50">Alumnos activos</dt>
<dd className="text-sm font-medium text-primary">
{formatUsage(status.usage.attendees, status.limits.maxAttendees)}
</dd>
</div>
</dl>
</div>
)
}

View File

@@ -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 (
<Modal
isOpen={detail !== null}
onClose={dismissPlanPrompt}
title="Disponible en Pro"
description={detail ?? undefined}
maxWidth="sm"
>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={dismissPlanPrompt}>
Ahora no
</Button>
<Button
variant="primary"
onClick={() => {
dismissPlanPrompt()
void navigate({ to: '/billing' })
}}
>
<Sparkles className="size-4" />
Ver planes
</Button>
</div>
</Modal>
)
}

View File

@@ -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 (
<form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-1.5">
<Label htmlFor="payer-email">Email de tu cuenta de Mercado Pago</Label>
<Input
id="payer-email"
type="email"
required
autoFocus
autoComplete="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<p className="text-xs text-foreground/50">
Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual.
</p>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex justify-end gap-3">
{onCancel ? (
<Button type="button" variant="outline" onClick={onCancel}>
Cancelar
</Button>
) : null}
<Button type="submit" variant="primary" disabled={isPending || !email.trim()}>
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
{isPending ? 'Abriendo…' : submitLabel}
</Button>
</div>
</form>
)
}

View File

@@ -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 (
<Modal
isOpen={isSubscribeOpen}
onClose={closeSubscribe}
title="Pasate a Pro"
description="Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras."
maxWidth="sm"
>
{/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */}
{isSubscribeOpen ? (
<SubscribeForm
defaultEmail={statusQuery.data?.payerEmail ?? user?.email ?? ''}
isPending={subscription.isStarting}
error={subscription.error}
onSubmit={(email) => void subscription.start(email, 'billing')}
onCancel={closeSubscribe}
/>
) : null}
</Modal>
)
}

View File

@@ -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<Plan, string> = { 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<PlanFeature, string> = {
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<PlanProblemError>
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
}

View File

@@ -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'

View File

@@ -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,
)
}

View File

@@ -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,
})
}

View File

@@ -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<string | null>(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 }
}

View File

@@ -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<number | null>(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 }
}

View File

@@ -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 (
<section className="rounded-xl border border-border bg-surface">
@@ -44,8 +47,22 @@ export function GroupAutomationsCard() {
<MessageCircle className="size-4 text-success" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
<p className="text-xs text-foreground/50">{WEEKLY_SEND_LABEL}</p>
{includedInPlan ? null : <Badge variant="info">Pro</Badge>}
</div>
<p className="text-xs text-foreground/50">
{WEEKLY_SEND_LABEL}
{includedInPlan ? null : (
<>
{' '}
Disponible en el plan Pro.{' '}
<Link to="/billing" className="font-medium text-accent-fg underline">
Ver planes
</Link>
</>
)}
</p>
</div>
</header>
@@ -75,7 +92,9 @@ export function GroupAutomationsCard() {
</div>
<Switch
checked={checked}
disabled={isUpdatingAutomations || (!checked && blocked !== null)}
disabled={
isUpdatingAutomations || (!checked && (blocked !== null || !includedInPlan))
}
aria-label={automation.title}
aria-describedby={hintId}
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}

View File

@@ -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 (
<section className="animate-fade-in space-y-5 sm:space-y-6">
{/* The large title always renders, even while loading: it is what gives
the immersive bar its height and stops the layout from jumping when
the data arrives. */}
<GroupHeader onCharge={() => setIsChargeModalOpen(true)} />
<GroupHeader onCharge={handleCharge} />
{groupQueryPending ? (
<div className="flex items-center justify-center py-20">

View File

@@ -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,6 +73,21 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
</dl>
</div>
{selectedPlan ? (
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<Sparkles className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
Estás en el plan <span className="font-semibold">{PLAN_NAMES[selectedPlan]}</span>.
{selectedPlan === 'FREE'
? ' Cuando quieras cobrar con Mercado Pago o automatizar WhatsApp, pasate a Pro desde Ajustes.'
: ''}
</p>
</div>
) : null}
{/* Con Free no se cobra ni se automatiza: esos avisos son solo de Pro. */}
{selectedPlan === 'FREE' ? null : (
<>
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<CreditCard className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
@@ -105,6 +123,8 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
)}
</p>
</div>
</>
)}
<Button variant="primary" className="w-full" onClick={goToDashboard}>
Ir a mi Panel

View File

@@ -1,9 +1,9 @@
import type { CountryCode } from '@gruperly/shared'
import { COUNTRY_CURRENCY, COUNTRY_LABELS, DEFAULT_COUNTRY } from '@gruperly/shared'
import { COUNTRY_CURRENCY, COUNTRY_LABELS } from '@gruperly/shared'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { useOnboarding } from './OnboardingProvider'
export const COUNTRY_OPTIONS: readonly CountryCode[] = [
'AR',
@@ -24,11 +24,12 @@ type CountryStepProps = {
* Paso "País" del onboarding.
*
* El país del profesor define la moneda con la que se generan los links de
* cobro, así que se pregunta al empezar. Por default Argentina (la moneda por
* default es ARS); se cambia después desde Ajustes.
* cobro y el precio de Pro, así que se pregunta al empezar. Por default
* Argentina (la moneda por default es ARS). Vive en el provider: el paso Plan y
* el del primer grupo lo usan, y se guarda junto con el plan.
*/
export function CountryStep({ onNext, onBack }: CountryStepProps) {
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
const { country, setCountry } = useOnboarding()
return (
<section className="space-y-5">

View File

@@ -1,4 +1,4 @@
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto, Plan } from '@gruperly/shared'
import { DEFAULT_COUNTRY } from '@gruperly/shared'
import type { UseQueryResult } from '@tanstack/react-query'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -7,26 +7,31 @@ import type { ReactNode } from 'react'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { useAuth } from '../../context/AuthProvider'
import { getOnboardingStatus } from '../../lib/api'
import { billingStatusQueryKey } from '../billing'
import type { MpCallbackFeedback } from '../mp'
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
import type { WhatsappCallbackFeedback } from '../whatsapp'
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
const WELCOME_STEP = 0
const PAYMENT_STEP = 2
const WHATSAPP_STEP = 3
const FIRST_GROUP_STEP = 4
import { type OnboardingStepId, resumeStep, visibleSteps } from './steps'
type OnboardingContextValue = {
step: number
setStep: (step: number) => void
/** El país del profesor; define la moneda de los links de cobro. */
step: OnboardingStepId
steps: OnboardingStepId[]
goTo: (step: OnboardingStepId) => void
goNext: () => void
goBack: () => void
/** El país del profesor; define la moneda de los links de cobro y el precio de Pro. */
country: CountryCode
setCountry: (country: CountryCode) => void
/** El plan elegido en el paso "Plan"; decide qué pasos siguen. */
selectedPlan: Plan | null
setSelectedPlan: (plan: Plan) => void
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
mpFeedback: MpCallbackFeedback | null
/** Lo que volvió de una vinculación de WhatsApp por redirect en `?wa=`. */
waFeedback: WhatsappCallbackFeedback | null
/** Volvió de autorizar (o abandonar) la suscripción a Pro (`?sub=return`). */
returnedFromSubscription: boolean
createdGroup: OnboardingGroupDto | null
setCreatedGroup: (group: OnboardingGroupDto) => void
statusQuery: UseQueryResult<OnboardingStatusDto>
@@ -39,10 +44,12 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const search = useSearch({ from: '/onboarding' })
const [step, setStep] = useState(WELCOME_STEP)
const [step, setStep] = useState<OnboardingStepId>('welcome')
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null)
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
const [returnedFromSubscription, setReturnedFromSubscription] = useState(false)
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
const statusQuery = useQuery({
@@ -51,6 +58,16 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
enabled: !!user,
})
const steps = useMemo(() => visibleSteps(selectedPlan), [selectedPlan])
const goNext = () => {
const next = steps[steps.indexOf(step) + 1]
if (next) setStep(next)
}
const goBack = () => {
const previous = steps[steps.indexOf(step) - 1]
if (previous) setStep(previous)
}
const callbackFeedback = useMemo(
() => readMpCallbackFeedback(search.mp, search.reason),
[search.mp, search.reason],
@@ -67,7 +84,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
// Vuelve al paso de Cobros, que es de donde salió el flujo. Setearlo siempre
// (y no solo desde el primer paso) evita que un `?mp=` que llega con el
// proveedor recién montado salte al resumen sin mostrar la confirmación.
setStep(PAYMENT_STEP)
setStep('payment')
// Se limpian los parámetros de la URL: si no, recargar la página volvería a
// mostrar el aviso de la vinculación vieja.
@@ -87,32 +104,51 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
setWaFeedback(whatsappCallbackFeedback)
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
setStep(WHATSAPP_STEP)
setStep('whatsapp')
void navigate({ to: '/onboarding', search: {}, replace: true })
}, [whatsappCallbackFeedback, navigate, queryClient])
// Vuelta de Mercado Pago tras la suscripción a Pro: el paso Plan muestra si
// quedó activa o se sigue procesando (y deja seguir igual).
useEffect(() => {
if (search.sub !== 'return') return
setReturnedFromSubscription(true)
setSelectedPlan('PRO')
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
setStep('plan')
void navigate({ to: '/onboarding', search: {}, replace: true })
}, [search.sub, navigate, queryClient])
useEffect(() => {
const status = statusQuery.data
if (!status) return
// Si dejó el onboarding después de vincular los cobros, se retoma en
// WhatsApp (o en el grupo, si también lo vinculó). Con la cuenta ya activa
// el paso de Cobros muestra "Cambiar de cuenta", así que solo se salta
// desde la bienvenida.
if (status.step === 'PAYMENT_CONNECTED') {
const resumeAt = status.whatsappConnected ? FIRST_GROUP_STEP : WHATSAPP_STEP
setStep((current) => (current === WELCOME_STEP ? resumeAt : current))
}
// El estado local se pierde con cada redirect (Mercado Pago, WhatsApp): el
// país y el plan elegidos se recuperan del servidor.
if (status.country) setCountry(status.country)
if (status.selectedPlan) setSelectedPlan((current) => current ?? status.selectedPlan)
// Retomar donde quedó, solo si recién arranca (desde la bienvenida).
const resumeAt = resumeStep(status)
if (resumeAt) setStep((current) => (current === 'welcome' ? resumeAt : current))
}, [statusQuery.data])
return (
<OnboardingContext.Provider
value={{
step,
setStep,
steps,
goTo: setStep,
goNext,
goBack,
country,
setCountry,
selectedPlan,
setSelectedPlan,
mpFeedback,
waFeedback,
returnedFromSubscription,
createdGroup,
setCreatedGroup,
statusQuery,

View File

@@ -9,24 +9,27 @@ import { CountryStep } from './CountryStep'
import { FirstGroupStep } from './FirstGroupStep'
import { useOnboarding } from './OnboardingProvider'
import { PaymentStep } from './PaymentStep'
import { PlanStep } from './PlanStep'
import { STEP_LABELS } from './steps'
import { Stepper } from './Stepper'
import { WelcomeStep } from './WelcomeStep'
import { WhatsappStep } from './WhatsappStep'
const STEPS = [
{ label: 'Bienvenida' },
{ label: 'País' },
{ label: 'Cobros' },
{ label: 'WhatsApp' },
{ label: 'Tu grupo' },
{ label: 'Listo' },
]
export function OnboardingView() {
const { user, isPending: authPending } = useAuth()
const navigate = useNavigate()
const { step, setStep, mpFeedback, waFeedback, createdGroup, setCreatedGroup, statusQuery } =
useOnboarding()
const {
step,
steps,
goTo,
goNext,
goBack,
mpFeedback,
waFeedback,
createdGroup,
setCreatedGroup,
statusQuery,
} = useOnboarding()
useEffect(() => {
if (statusQuery.data?.completed) {
@@ -81,29 +84,33 @@ export function OnboardingView() {
<Logo className="h-6" />
</header>
<Stepper steps={STEPS} current={step} />
{/* Con Free no se muestran Cobros ni WhatsApp: el stepper refleja solo
los pasos que se van a recorrer. */}
<Stepper
steps={steps.map((id) => ({ label: STEP_LABELS[id] }))}
current={steps.indexOf(step)}
/>
<div key={step} className="mt-8 animate-step-enter">
{step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null}
{step === 1 ? (
<CountryStep onNext={() => setStep(2)} onBack={() => setStep(0)} />
{step === 'welcome' ? <WelcomeStep name={firstName} onNext={goNext} /> : null}
{step === 'country' ? <CountryStep onNext={goNext} onBack={goBack} /> : null}
{step === 'plan' ? <PlanStep /> : null}
{step === 'payment' ? (
<PaymentStep feedback={mpFeedback} onNext={goNext} onBack={goBack} />
) : null}
{step === 2 ? (
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
{step === 'whatsapp' ? (
<WhatsappStep feedback={waFeedback} onNext={goNext} onBack={goBack} />
) : null}
{step === 3 ? (
<WhatsappStep feedback={waFeedback} onNext={() => setStep(4)} onBack={() => setStep(2)} />
) : null}
{step === 4 ? (
{step === 'group' ? (
<FirstGroupStep
onBack={() => setStep(3)}
onBack={goBack}
onCompleted={(group) => {
setCreatedGroup(group)
setStep(5)
goTo('done')
}}
/>
) : null}
{step === 5 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
{step === 'done' && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
</div>
</main>
)

View File

@@ -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<string | null>(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 (
<StepShell>
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
¡Listo! Tu suscripción a Pro quedó activa.
</p>
<Button variant="primary" className="w-full" onClick={() => goTo('payment')}>
Continuar
<ArrowRight className="size-4" />
</Button>
</StepShell>
)
}
if (subscriptionStatus === 'PENDING' && (returnedFromSubscription || choseProBefore) && !isEnteringEmail) {
const stillChecking = returnedFromSubscription && billingQuery.isFetching
return (
<StepShell>
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface px-4 py-3">
{stillChecking ? (
<Loader2 className="mt-0.5 size-4 shrink-0 animate-spin text-accent" />
) : (
<Clock className="mt-0.5 size-4 shrink-0 text-warning" />
)}
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">
{returnedFromSubscription ? 'Procesando tu pago…' : 'Tu suscripción a Pro quedó pendiente'}
</p>
<p className="text-xs text-foreground/50">
{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.'}
</p>
</div>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex flex-col gap-3 sm:flex-row">
{returnedFromSubscription ? (
<Button variant="primary" className="flex-1" onClick={() => goTo('payment')}>
Continuar
<ArrowRight className="size-4" />
</Button>
) : (
<>
<Button variant="primary" className="flex-1" onClick={() => setIsEnteringEmail(true)}>
<Sparkles className="size-4" />
Reintentar el pago
</Button>
<Button variant="outline" className="flex-1" disabled={mutation.isPending} onClick={chooseFree}>
Seguir con Free
</Button>
</>
)}
</div>
</StepShell>
)
}
return (
<StepShell>
<div className="grid gap-3">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE}>
<Button variant="outline" className="w-full" disabled={isLeavingToMp} onClick={chooseFree}>
{mutation.isPending && mutation.variables?.plan === 'FREE' ? (
<Loader2 className="size-4 animate-spin" />
) : null}
Empezar gratis
</Button>
</PlanOptionCard>
<PlanOptionCard plan="PRO" limits={PLAN_LIMITS.PRO} price={proPrice} highlighted>
{proUnavailable ? (
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
) : isEnteringEmail ? (
<SubscribeForm
defaultEmail={user?.email ?? ''}
isPending={isLeavingToMp}
error={null}
onSubmit={choosePro}
onCancel={() => setIsEnteringEmail(false)}
/>
) : (
<Button variant="primary" className="w-full" onClick={() => setIsEnteringEmail(true)}>
<Sparkles className="size-4" />
Elegir Pro
</Button>
)}
</PlanOptionCard>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex items-center gap-3">
<Button variant="outline" onClick={goBack} className="hidden lg:inline-flex">
<ArrowLeft className="size-4" />
Volver
</Button>
</div>
</StepShell>
)
}
/** Encabezado común a los tres estados del paso. */
function StepShell({ children }: { children: ReactNode }) {
return (
<section className="space-y-5">
<header className="space-y-1">
<h2 className="text-2xl font-bold text-primary">Elegí tu plan</h2>
<p className="text-sm text-foreground/60">
Empezá gratis o pasate a Pro para cobrar con Mercado Pago y automatizar WhatsApp.
</p>
</header>
{children}
</section>
)
}

View File

@@ -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<OnboardingStepId, string> = {
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'
}

View File

@@ -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() {
</Link>
</div>
<PlanSettingsCard />
<MpStatusCard />
<WhatsappStatusCard />

View File

@@ -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<SelectPlanResultDto>('/api/v1/onboarding/plan', {
method: 'POST',
body: JSON.stringify(payload),
})
export const createGroup = (payload: CreateFirstGroup) =>
apiFetch<CreateGroupResult>('/api/v1/groups', {
method: 'POST',
@@ -131,6 +145,24 @@ export const getMpStatus = () => apiFetch<MpStatusDto>('/api/v1/mp/status')
export const disconnectMp = () =>
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
// — Plan de Gruperly (suscripción a Pro con Mercado Pago) —
export const getBillingStatus = () => apiFetch<BillingStatusDto>('/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<SubscribeResultDto>('/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<BillingChargeList>(`/api/v1/billing/charges?page=${page}&pageSize=10`)
// --- WhatsApp (recordatorios y reenganche automáticos) ---
export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>

View File

@@ -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 },
},

View File

@@ -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,

View File

@@ -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<string, unknown>): { sub?: string } => ({
sub: typeof search.sub === 'string' ? search.sub : undefined,
}),
component: () => (
<BillingProvider>
<BillingView />
</BillingProvider>
),
})

View File

@@ -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<string, unknown>,
): { 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: () => (
<OnboardingProvider>

View File

@@ -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> = {}): 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)
})
})

View File

@@ -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> = {}): 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')
})
})

View File

@@ -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

49
docs/billing.md Normal file
View File

@@ -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_<CC>`, donde `CC` es `AR`, `BR`, `CL`, `CO`, `MX`, `PE` o `UY`.
3. En **Webhooks**, configurar la URL `https://<API>/api/v1/billing/webhooks/mp/<cc>` (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_<CC>`.
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:<data.id>;request-id:<x-request-id>;ts:<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.

View File

@@ -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';

View File

@@ -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<typeof planSchema>;
export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges']);
export type PlanFeature = z.output<typeof planFeatureSchema>;
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<Plan, PlanLimits> = {
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<CountryCode, number> = {
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<typeof subscriptionStatusSchema>;
// Where the professor started the subscription, so Mercado Pago sends them back.
export const billingReturnToSchema = z.enum(['onboarding', 'billing']);
export type BillingReturnTo = z.output<typeof billingReturnToSchema>;
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<typeof BillingStatusDtoSchema>;
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<typeof SubscribeInputSchema>;
export const SubscribeResultDtoSchema = z.object({
checkoutUrl: z.string(),
});
export type SubscribeResultDto = z.output<typeof SubscribeResultDtoSchema>;
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<typeof BillingChargeDtoSchema>;
export const BillingChargesQuerySchema = z.object({
page: createPageSchema(),
pageSize: createPageSizeSchema(10),
});
export type BillingChargesQuery = z.output<typeof BillingChargesQuerySchema>;
export const BillingChargeListSchema = z.object({
data: z.array(BillingChargeDtoSchema),
pagination: createPaginationSchema(),
});
export type BillingChargeList = z.output<typeof BillingChargeListSchema>;
// 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<typeof SelectPlanInputSchema>;
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<typeof SelectPlanResultDtoSchema>;

View File

@@ -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<typeof OnboardingStatusDtoSchema>;