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