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; sync?: Pick; 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 { 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; } }