Files
gruperly/apps/backend/prisma/models/billing.prisma
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

139 lines
6.0 KiB
Plaintext

// 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
AUTHORIZED
PAUSED
CANCELLED
}
model BillingSubscription {
id String @id @default(cuid())
userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id")
country String @map("country_code")
currency String
amount Decimal @db.Decimal(12, 2)
payerEmail String @map("payer_email")
// 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")
authorizedAt DateTime? @map("authorized_at")
nextPaymentDate DateTime? @map("next_payment_date")
// Last day covered by an approved charge. Pro lasts until then plus the grace
// period, even after a cancellation or a failed renewal.
paidThrough DateTime? @map("paid_through")
lastSyncedAt DateTime? @map("last_synced_at")
// A new price queued by the backoffice for this live subscription: the job
// pushes it to the provider (from the next charge) and moves it to `amount`.
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
priceChangeId String? @map("price_change_id")
priceChangeAttempts Int @default(0) @map("price_change_attempts")
priceChangeError String? @map("price_change_error")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey")
charges BillingCharge[]
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
@@map("billing_subscriptions")
}
// One monthly invoice of a subscription (MP authorized payment, Stripe invoice).
model BillingCharge {
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")
@@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx")
@@map("billing_charges")
}
// Deduplication of billing webhook deliveries, per sending account: `mp:<CC>`
// (one Mercado Pago account per country) or `stripe`.
model BillingWebhookEvent {
source String @map("source")
dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at")
@@id([source, dedupeKey], map: "billing_webhook_events_pkey")
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events")
}
enum PlanId {
FREE
PRO
}
// What each plan allows, edited from the backoffice. Seeded with the defaults
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
model PlanConfig {
plan PlanId @id
// Null means no limit.
maxGroups Int? @map("max_groups")
maxAttendees Int? @map("max_attendees")
whatsappAutomations Boolean @map("whatsapp_automations")
mpCharges Boolean @map("mp_charges")
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_configs")
}
// Monthly price of Pro per country, in the country's currency. Seeded with
// `PRO_PRICE_BY_COUNTRY` (shared). New subscriptions take it; live ones keep
// their own `amount` unless a price change is applied to them.
model PlanPrice {
country String @id @map("country_code")
amount Decimal @db.Decimal(12, 2)
updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("plan_prices")
}
// Audit of every price edit from the backoffice.
model PlanPriceChange {
id String @id @default(cuid())
country String @map("country_code")
previousAmount Decimal? @db.Decimal(12, 2) @map("previous_amount")
newAmount Decimal @db.Decimal(12, 2) @map("new_amount")
currency String
applyToExisting Boolean @map("apply_to_existing")
// Live subscriptions queued to move to the new price.
queued Int @default(0)
createdById String? @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
@@index([country, createdAt], map: "plan_price_changes_country_created_at_idx")
@@map("plan_price_changes")
}