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

@@ -0,0 +1,26 @@
-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest).
-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids.
-- CreateEnum
CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE');
-- billing_subscriptions: provider + provider-neutral ids
ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO';
ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT;
ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id";
ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key";
CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref");
-- billing_charges: provider-neutral id and normalized status
ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id";
ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key";
UPDATE "billing_charges"
SET "status" = CASE
WHEN "status" = 'approved' THEN 'approved'
WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected'
ELSE 'pending'
END;
-- billing_webhook_events: dedupe per sending account (`mp:<CC>` or `stripe`)
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";

View File

@@ -1,7 +1,12 @@
// Gruperly's own billing: the professor pays a monthly Pro subscription through
// Mercado Pago Subscriptions (preapproval), collected by Gruperly's account in
// the professor's country. Not to be confused with `Payment`, which is what
// students pay the professor.
// Gruperly's own billing: the professor pays a monthly Pro subscription,
// collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe
// (every other country), see `modules/billing/providers/`. Not to be confused
// with `Payment`, which is what students pay the professor.
enum BillingProviderId {
MERCADO_PAGO
STRIPE
}
enum SubscriptionStatus {
PENDING
@@ -17,8 +22,14 @@ model BillingSubscription {
currency String
amount Decimal @db.Decimal(12, 2)
payerEmail String @map("payer_email")
// Null between creating the row and Mercado Pago answering.
mpPreapprovalId String? @unique(map: "billing_subscriptions_mpPreapprovalId_key") @map("mp_preapproval_id")
// Who collects it. Sync and cancel always follow this, never the current country.
provider BillingProviderId @default(MERCADO_PAGO)
// The provider's subscription id (MP preapproval, Stripe subscription). Null
// until the provider creates it: right after MP answers, or once the
// professor completes Stripe Checkout.
externalId String? @unique(map: "billing_subscriptions_externalId_key") @map("external_id")
// Stripe Checkout Session of the current attempt; null for Mercado Pago.
checkoutRef String? @unique(map: "billing_subscriptions_checkoutRef_key") @map("checkout_ref")
status SubscriptionStatus @default(PENDING)
// When the current attempt started: re-subscribing reuses the row.
requestedAt DateTime @default(now()) @map("requested_at")
@@ -39,18 +50,18 @@ model BillingSubscription {
@@map("billing_subscriptions")
}
// One Mercado Pago "authorized payment" (a monthly invoice) of a subscription.
// One monthly invoice of a subscription (MP authorized payment, Stripe invoice).
model BillingCharge {
id String @id @default(cuid())
subscriptionId String @map("subscription_id")
mpAuthorizedPaymentId String @unique(map: "billing_charges_mpAuthorizedPaymentId_key") @map("mp_authorized_payment_id")
amount Decimal @db.Decimal(12, 2)
currency String
// Mercado Pago's own status of the charge (e.g. approved, rejected).
status String
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(cuid())
subscriptionId String @map("subscription_id")
externalId String @unique(map: "billing_charges_externalId_key") @map("external_id")
amount Decimal @db.Decimal(12, 2)
currency String
// Normalized across providers: approved, pending or rejected.
status String
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey")
@@ -58,13 +69,14 @@ model BillingCharge {
@@map("billing_charges")
}
// Deduplication of Mercado Pago webhook deliveries, per country account.
// Deduplication of billing webhook deliveries, per sending account: `mp:<CC>`
// (one Mercado Pago account per country) or `stripe`.
model BillingWebhookEvent {
country String @map("country_code")
source String @map("source")
dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at")
@@id([country, dedupeKey], map: "billing_webhook_events_pkey")
@@id([source, dedupeKey], map: "billing_webhook_events_pkey")
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events")
}