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>
This commit is contained in:
Jose Selesan
2026-10-26 17:01:07 -03:00
parent cd82a1e549
commit 9617447e05
42 changed files with 1938 additions and 457 deletions

View File

@@ -1,75 +1,75 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import {
billingProviderErrorProblem,
billingNotAvailableProblem,
notFoundResourceProblem,
payerEmailRequiredProblem,
subscriptionAlreadyActiveProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import {
buildSubscriptionBackUrl,
countryOf,
getPlatformCredentials,
mpPreapprovalClient,
type PreapprovalClient,
} from '../../lib';
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
client?: PreapprovalClient;
credentials?: typeof getPlatformCredentials;
providers?: BillingProviderResolver;
webOrigin?: string;
now?: () => Date;
};
const SUBSCRIPTION_REASON = 'Gruperly Pro';
/**
* Starts a monthly Pro subscription in Gruperly's Mercado Pago account of the
* Starts a monthly Pro subscription with the billing provider of the
* professor's country and returns where the browser goes to authorize it.
*
* The row is written PENDING before calling Mercado Pago (it is the source of
* The row is written PENDING before calling the provider (it is the source of
* truth, like `Payment` rows in the batch). A previous subscription that was
* never authorized is cancelled first, so the professor can fix the payer
* email by simply trying again.
* never authorized is voided first, with whichever provider it was created, so
* the professor can fix the payer email (or switch country) by trying again.
*/
export class Subscribe {
constructor(private readonly deps: SubscribeDeps = {}) {}
async execute(userId: string, input: SubscribeInput): Promise<Result<SubscribeResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const client = this.deps.client ?? mpPreapprovalClient;
const providers = this.deps.providers ?? getBillingProvider;
const now = this.deps.now?.() ?? new Date();
const user = await db.user.findUnique({ where: { id: userId } });
if (!user) return err(notFoundResourceProblem('User', userId));
const country = countryOf(user);
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
if (!credentials.ok) return credentials;
const token = credentials.value.accessToken;
const provider = providers(billingProviderForCountry(country));
if (!provider.isAvailable(country)) return err(billingNotAvailableProblem());
if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem());
const existing = await db.billingSubscription.findUnique({ where: { userId } });
if (existing?.status === 'AUTHORIZED') {
return err(subscriptionAlreadyActiveProblem());
}
if (existing?.mpPreapprovalId && existing.status !== 'CANCELLED') {
if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') {
try {
await client.cancelPreapproval(token, existing.mpPreapprovalId);
await providers(existing.provider).cancel(subscriptionRefOf(existing));
} catch {
// A stale PENDING preapproval that cannot be cancelled is harmless: it
// was never authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not cancel the previous Mercado Pago preapproval');
// A stale attempt that cannot be voided is harmless: it was never
// authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not void the previous Pro subscription attempt');
}
}
const amount = PRO_PRICE_BY_COUNTRY[country];
const currency = COUNTRY_CURRENCY[country];
const fields = { country, currency, amount, payerEmail: input.payerEmail };
const fields = {
country,
currency,
amount,
provider: provider.id,
// Stripe asks for the email in its checkout; the sync stores the real one.
payerEmail: input.payerEmail ?? user.email,
};
const row = await db.billingSubscription.upsert({
where: { userId },
@@ -78,7 +78,8 @@ export class Subscribe {
...fields,
status: 'PENDING',
requestedAt: now,
mpPreapprovalId: null,
externalId: null,
checkoutRef: null,
authorizedAt: null,
nextPaymentDate: null,
},
@@ -88,31 +89,27 @@ export class Subscribe {
// so nobody pays twice for the same month.
const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined;
let preapproval: Awaited<ReturnType<PreapprovalClient['createPreapproval']>>;
let started: Awaited<ReturnType<typeof provider.start>>;
try {
preapproval = await client.createPreapproval(token, {
reason: SUBSCRIPTION_REASON,
externalReference: userId,
payerEmail: input.payerEmail,
started = await provider.start({
userId,
country,
amount,
currencyId: currency,
currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
startDate,
});
} catch {
return err(billingProviderErrorProblem());
}
if (!preapproval.initPoint) {
logger.error({ userId }, 'Mercado Pago preapproval came back without init_point');
return err(billingProviderErrorProblem());
} catch (error) {
logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription');
return err(toBillingProblem(error));
}
await db.billingSubscription.update({
where: { id: row.id },
data: { mpPreapprovalId: preapproval.id, lastSyncedAt: now },
data: { externalId: started.externalId, checkoutRef: started.checkoutRef, lastSyncedAt: now },
});
return ok({ checkoutUrl: preapproval.initPoint });
return ok({ checkoutUrl: started.checkoutUrl });
}
}