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,5 +1,5 @@
import { z } from 'zod';
import { BillingChargeDtoSchema, planSchema, subscriptionStatusSchema } from './billing.js';
import { BillingChargeDtoSchema, billingProviderIdSchema, planSchema, subscriptionStatusSchema } from './billing.js';
import { countryCodeSchema } from './country.js';
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
@@ -32,6 +32,7 @@ export type AdminAccountQuery = z.output<typeof AdminAccountQuerySchema>;
export type AdminAccountQueryInput = z.input<typeof AdminAccountQuerySchema>;
const AdminSubscriptionSummarySchema = z.object({
provider: billingProviderIdSchema,
status: subscriptionStatusSchema,
amount: z.number(),
currency: z.string(),

View File

@@ -25,9 +25,8 @@ export const PLAN_LIMITS: Record<Plan, PlanLimits> = {
PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true },
};
// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY).
// Mercado Pago does not charge across countries, so each one is collected by
// Gruperly's own account in that country.
// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY),
// whichever provider collects it.
export const PRO_PRICE_BY_COUNTRY: Record<CountryCode, number> = {
AR: 15000,
BR: 49,
@@ -38,7 +37,28 @@ export const PRO_PRICE_BY_COUNTRY: Record<CountryCode, number> = {
UY: 390,
};
// Mirror of the Mercado Pago preapproval status.
// Who collects Pro. Argentina stays on Mercado Pago (Gruperly's own account
// there); every other country is collected by Gruperly's single Stripe account,
// in the country's currency. Only decides *new* subscriptions: a live one keeps
// the provider it was created with.
export const billingProviderIdSchema = z.enum(['MERCADO_PAGO', 'STRIPE']);
export type BillingProviderId = z.output<typeof billingProviderIdSchema>;
export const BILLING_PROVIDER_BY_COUNTRY: Record<CountryCode, BillingProviderId> = {
AR: 'MERCADO_PAGO',
BR: 'STRIPE',
CL: 'STRIPE',
CO: 'STRIPE',
MX: 'STRIPE',
PE: 'STRIPE',
UY: 'STRIPE',
};
export function billingProviderForCountry(country: CountryCode): BillingProviderId {
return BILLING_PROVIDER_BY_COUNTRY[country];
}
// Subscription status, normalized across providers.
export const subscriptionStatusSchema = z.enum(['PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED']);
export type SubscriptionStatus = z.output<typeof subscriptionStatusSchema>;
@@ -67,7 +87,9 @@ export const BillingStatusDtoSchema = z.object({
priceAmount: z.number(),
currency: z.string(),
country: countryCodeSchema,
/** Gruperly has Mercado Pago credentials for the professor's country. */
/** Who collects (or would collect) the subscription. */
provider: billingProviderIdSchema,
/** That provider is configured for the professor's country. */
availableInCountry: z.boolean(),
/** `false` when the server runs with BILLING_ENFORCEMENT off. */
enforced: z.boolean(),
@@ -76,9 +98,12 @@ export const BillingStatusDtoSchema = z.object({
});
export type BillingStatusDto = z.output<typeof BillingStatusDtoSchema>;
// Mercado Pago requires the payer to log in with this exact email; Stripe asks
// for it in its own checkout, so it is only mandatory for Mercado Pago.
const payerEmailSchema = z.string().trim().email('Ingresá un email válido');
export const SubscribeInputSchema = z.strictObject({
// Mercado Pago requires the payer to log in with this exact email.
payerEmail: z.string().trim().email('Ingresá un email válido'),
payerEmail: payerEmailSchema.optional(),
returnTo: billingReturnToSchema.default('billing'),
});
export type SubscribeInput = z.output<typeof SubscribeInputSchema>;
@@ -92,6 +117,7 @@ export const BillingChargeDtoSchema = z.object({
id: z.string(),
amount: z.number(),
currency: z.string(),
/** Normalized across providers: `approved`, `pending` or `rejected`. */
status: z.string(),
paidAt: isoDateTimeSchema.nullable(),
createdAt: isoDateTimeSchema,
@@ -111,13 +137,13 @@ export const BillingChargeListSchema = z.object({
export type BillingChargeList = z.output<typeof BillingChargeListSchema>;
// Onboarding step "Plan": mandatory. The country comes along because it is not
// stored until then, and it decides the price and the Mercado Pago account.
// stored until then, and it decides the price and the billing provider.
export const SelectPlanInputSchema = z.discriminatedUnion('plan', [
z.strictObject({ plan: z.literal('FREE'), country: countryCodeSchema }),
z.strictObject({
plan: z.literal('PRO'),
country: countryCodeSchema,
payerEmail: z.string().trim().email('Ingresá un email válido'),
payerEmail: payerEmailSchema.optional(),
}),
]);
export type SelectPlanInput = z.output<typeof SelectPlanInputSchema>;