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>
This commit is contained in:
Jose Selesan
2026-11-11 07:50:14 -03:00
parent abb18f1815
commit aac142d324
90 changed files with 2642 additions and 104 deletions

View File

@@ -0,0 +1,67 @@
-- CreateEnum
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
-- AlterTable
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "price_change_error" TEXT,
ADD COLUMN "price_change_id" TEXT;
-- CreateTable
CREATE TABLE "plan_configs" (
"plan" "PlanId" NOT NULL,
"max_groups" INTEGER,
"max_attendees" INTEGER,
"whatsapp_automations" BOOLEAN NOT NULL,
"mp_charges" BOOLEAN NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
);
-- CreateTable
CREATE TABLE "plan_prices" (
"country_code" TEXT NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"updated_by_id" TEXT,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
);
-- CreateTable
CREATE TABLE "plan_price_changes" (
"id" TEXT NOT NULL,
"country_code" TEXT NOT NULL,
"previous_amount" DECIMAL(12,2),
"new_amount" DECIMAL(12,2) NOT NULL,
"currency" TEXT NOT NULL,
"apply_to_existing" BOOLEAN NOT NULL,
"queued" INTEGER NOT NULL DEFAULT 0,
"created_by_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
-- CreateIndex
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
-- in packages/shared), so nothing changes on deploy.
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
('AR', 15000, CURRENT_TIMESTAMP),
('BR', 49, CURRENT_TIMESTAMP),
('CL', 9900, CURRENT_TIMESTAMP),
('CO', 39900, CURRENT_TIMESTAMP),
('MX', 199, CURRENT_TIMESTAMP),
('PE', 39, CURRENT_TIMESTAMP),
('UY', 390, CURRENT_TIMESTAMP);

View File

@@ -39,6 +39,12 @@ model BillingSubscription {
// 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")
@@ -47,6 +53,7 @@ model BillingSubscription {
// 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")
}
@@ -80,3 +87,52 @@ model BillingWebhookEvent {
@@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")
}