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:
@@ -0,0 +1,67 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { SyncSubscription } from '../lib';
|
||||
|
||||
const BATCH_SIZE = 50;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
/** A subscription nobody authorized within this window is given up. */
|
||||
const PENDING_TTL_MS = 7 * DAY_MS;
|
||||
/** Authorized subscriptions are re-checked at least daily (renewals, cancellations in MP). */
|
||||
const AUTHORIZED_STALE_MS = DAY_MS;
|
||||
|
||||
type ReconcileSubscriptionsDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||
sync?: Pick<SyncSubscription, 'execute'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export type ReconcileTotals = { checked: number; synced: number; failed: number; expired: number };
|
||||
|
||||
/**
|
||||
* Polling fallback for the billing webhook: the webhook can be lost, and in
|
||||
* local dev it usually never arrives. Every sync is idempotent, so the webhook
|
||||
* and this job racing over the same row is harmless.
|
||||
*/
|
||||
export class ReconcileSubscriptions {
|
||||
constructor(private readonly deps: ReconcileSubscriptionsDeps = {}) {}
|
||||
|
||||
async execute(): Promise<ReconcileTotals> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const sync = this.deps.sync ?? new SyncSubscription();
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
const totals: ReconcileTotals = { checked: 0, synced: 0, failed: 0, expired: 0 };
|
||||
|
||||
const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS);
|
||||
const expired = await db.billingSubscription.updateMany({
|
||||
where: { status: 'PENDING', requestedAt: { lt: pendingCutoff } },
|
||||
data: { status: 'CANCELLED' },
|
||||
});
|
||||
totals.expired = expired.count;
|
||||
|
||||
const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS);
|
||||
const rows = await db.billingSubscription.findMany({
|
||||
where: {
|
||||
mpPreapprovalId: { not: null },
|
||||
OR: [
|
||||
{ status: 'PENDING' },
|
||||
{
|
||||
status: { in: ['AUTHORIZED', 'PAUSED'] },
|
||||
OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } },
|
||||
take: BATCH_SIZE,
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
totals.checked += 1;
|
||||
const result = await sync.execute(row.id);
|
||||
if (result.ok && result.value.synced) totals.synced += 1;
|
||||
else if (!result.ok) totals.failed += 1;
|
||||
}
|
||||
|
||||
return totals;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user