import type { PrismaClient } from '@generated/prisma/client'; import type { CountryCode, CreatePaymentsBatch, CreatePaymentsBatchResult, PaymentBatchItem, ProblemDetails, Result, } from '@gruperly/shared'; import { currencyForCountry, err, ok } from '@gruperly/shared'; import { groupWithoutPriceProblem, noAttendeesToBillProblem, noGroupAccessProblem, notFoundResourceProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { getApiPublicOrigin } from '@/lib/public-origin'; import { logger } from '@/logger'; import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { getMpAccessToken } from '@/modules/mp'; import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib'; import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib'; type BatchDeps = { db?: Pick; createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; /** Public origin of the API, where Mercado Pago notifies the payment. */ apiOrigin?: string; planGuard?: Pick; }; /** * Creates one Checkout Pro payment link per active attendee of a group. * * The rows are created first (they are the single source of truth); a preference * that fails leaves its row PENDING without a link, and the professor retries * that one with `POST /payments/:id/renew` from the Cobros screen. A duplicate * batch call for the same period is up to the professor: each run creates new * links and creating a link never charges anyone. */ export class CreatePaymentBatch { constructor(private readonly deps: BatchDeps = {}) {} async execute( groupId: string, userId: string, input: CreatePaymentsBatch, ): Promise> { const db = this.deps.db ?? prisma; const group = await db.group.findUnique({ where: { id: groupId }, include: { members: { where: { userId } } }, }); if (!group) { return err(notFoundResourceProblem('Group', groupId)); } const isOwner = group.createdById === userId; const isMember = group.members.length > 0; if (!isOwner && !isMember) { return err(noGroupAccessProblem()); } const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature( group.createdById, 'mpCharges', ); if (!allowed.ok) { return allowed; } if (group.price == null) { return err(groupWithoutPriceProblem()); } const attendees = await db.attendee.findMany({ where: { groupId, status: 'ACTIVE', ...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}), }, include: { person: { select: { fullName: true } } }, }); if (attendees.length === 0) { return err(noAttendeesToBillProblem()); } const owner = await db.user.findUnique({ where: { id: group.createdById } }); const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null); const unitPrice = Number(group.price.toString()); const getToken = this.deps.getToken ?? getMpAccessToken; const token = await getToken(group.createdById); if (!token.ok) { return token; } const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`; const dueDate = new Date(input.dueDate); const title = input.description?.trim() || group.name; const createPreference = this.deps.createPreference ?? createCheckoutPreference; const items: PaymentBatchItem[] = []; let failed = 0; for (const attendee of attendees) { const payment = await db.payment.create({ data: { groupId, attendeeId: attendee.id, amount: group.price, currency, dueDate, description: input.description?.trim() || null, status: 'PENDING', }, }); let link: { initPoint: string; id: string } | null = null; let reason: string | null = null; try { const preference = await createPreference(token.value.accessToken, { title, unitPrice, currencyId: currency, externalReference: payment.id, backUrl, notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id), }); link = preference; } catch (error) { failed += 1; if (error instanceof MpApiError) { reason = 'mp_provider_error'; } else { // Never swallow a real bug: log it, but keep the rest of the batch going. reason = 'unknown_error'; logger.error({ err: error }, 'Unexpected Mercado Pago preference failure'); } } if (link) { await db.payment.update({ where: { id: payment.id }, data: { checkoutUrl: link.initPoint, mpPreferenceId: link.id }, }); } items.push({ paymentId: payment.id, attendeeId: attendee.id, attendeeName: attendee.person.fullName, amount: unitPrice, currency, checkoutUrl: link?.initPoint ?? null, outcome: link ? 'LINKED' : 'FAILED', reason, }); } return ok({ groupId, total: attendees.length, linked: attendees.length - failed, failed, items, }); } }