Files
gruperly/apps/backend/src/modules/onboarding/features/select-plan/use-case.ts
Jose Selesan f5e77c99f6 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>
2026-10-23 15:49:27 -03:00

79 lines
3.1 KiB
TypeScript

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