Files
gruperly/apps/backend/src/modules/payments/features/create-batch/use-case.ts
Jose Selesan aac142d324 feat(billing): configurable plans from the backoffice and MP payment notifications
Plans:
- Plan limits and Pro prices per country live in the database
  (plan_configs, plan_prices, seeded with the previous constants) and are
  read through PlanCatalog (30 s cache, defaults as fallback).
- /admin/plans edits limits (with the count of accounts that would become
  read-only) and prices, optionally pushing the new price to live
  subscriptions from their next charge (MP preapproval amount, Stripe item
  without proration) via the ApplyPriceChanges job, with an email and a
  notice on /billing.
- GET /billing/plans feeds the onboarding and the billing screen.

Mercado Pago:
- The Pro checkout returns through GET /billing/return on API_PUBLIC_URL,
  since MP refuses a back_url on localhost.
- The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the
  session, requires the session to own the state, and redirects instead of
  answering JSON on unexpected errors.
- Checkout Pro links skip auto_return off public HTTPS and carry a
  notification_url to POST /payments/webhooks/mp/:paymentId, which confirms
  the payment with the owner's token (same rule as the polling job, which
  stays as fallback). The search now prefers the approved attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:50:14 -03:00

175 lines
5.3 KiB
TypeScript

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<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
/** Public origin of the API, where Mercado Pago notifies the payment. */
apiOrigin?: string;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
/**
* 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<Result<CreatePaymentsBatchResult, ProblemDetails>> {
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,
});
}
}