import type { PrismaClient } from '@generated/prisma/client'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { getMpAccessToken } from '@/modules/mp'; import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib'; import { confirmMpPayment } from '../lib'; /** * Pulls payments from Mercado Pago. The notification * (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the * fallback for links created before it existed and for lost notifications. * Both go through `confirmMpPayment`. */ const RECONCILE_AFTER_MS = 5 * 60 * 1000; const BATCH_LIMIT = 50; export type ReconcilePaymentsResult = { paid: number; skipped: number; failed: number; }; type ReconcilePaymentsDeps = { db?: PrismaClient; getToken?: typeof getMpAccessToken; search?: typeof searchMpPaymentByExternalReference; now?: Date; }; export class ReconcilePayments { constructor(private readonly deps: ReconcilePaymentsDeps = {}) {} async execute(): Promise { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const getToken = this.deps.getToken ?? getMpAccessToken; const search = this.deps.search ?? searchMpPaymentByExternalReference; const awaiting = await db.payment.findMany({ where: { status: 'PENDING', checkoutUrl: { not: null }, createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) }, }, include: { group: { select: { createdById: true } } }, take: BATCH_LIMIT, }); const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 }; for (const payment of awaiting) { try { const outcome = await confirmMpPayment( db, { id: payment.id, ownerId: payment.group.createdById }, { getToken, search }, ); // No usable token is not a payment problem: the row stays PENDING and // the account notice tells the professor what to do. if (outcome === 'no_token') totals.skipped += 1; if (outcome === 'paid') totals.paid += 1; } catch (error) { if (!(error instanceof MpApiError)) { logger.error({ err: error }, 'Unexpected payment reconciliation failure'); } totals.failed += 1; } } return totals; } }