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