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:
118
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal file
118
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user