feat(billing): planes Free/Pro con Suscripciones de Mercado Pago

- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales
  de plataforma por país, webhook firmado y reconciliación por polling.
- PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o
  activan automatizaciones (402 plan_limit_reached / plan_feature_required /
  plan_read_only), detrás de BILLING_ENFORCEMENT.
- Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se
  saltean Cobros y WhatsApp.
- Web: pantalla /billing, aviso de Pro desde el MutationCache.
- Migración billing_subscriptions y docs/billing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-23 15:49:27 -03:00
parent f4d2c26e29
commit f5e77c99f6
93 changed files with 4402 additions and 117 deletions

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

@@ -215,4 +215,89 @@ export function noAttendeesToBillProblem(): ProblemDetails {
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
code: 'no_attendees_to_bill',
});
}
}
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);