Files
gruperly/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts
Jose Selesan 9617447e05 feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:01:07 -03:00

72 lines
2.4 KiB
TypeScript

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: {
AND: [
{ OR: [{ externalId: { not: null } }, { checkoutRef: { 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;
}
}