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

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