From 343193469431ee2c7336964cfa53c6b5aeb2cd2b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 01:32:31 +1300 Subject: [PATCH] app/: one plan catalogue in billing, one credit ledger in domain::credits Plan, CreditPack, the plans, CREDIT_PACK and MAX_AUTO_RELOAD_PACKS were defined in both modules, and add_purchased_credits had two implementations, left over from the port. billing now holds the catalogue (with PLANS) and Stripe; domain::credits holds the ledger, spending and usage, and the one add_purchased_credits, which the webhook calls. No behaviour changes. --- app/src/billing/mod.rs | 60 ++++++++---------------------------- app/src/billing/webhook.rs | 3 +- app/src/domain/credits.rs | 54 ++------------------------------ app/src/domain/processing.rs | 2 +- app/src/mcp/mod.rs | 2 +- 5 files changed, 19 insertions(+), 102 deletions(-) diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs index 66a7eded..edadcbf7 100644 --- a/app/src/billing/mod.rs +++ b/app/src/billing/mod.rs @@ -1,12 +1,12 @@ -//! Billing (sc-8900, the billing side; ported from today's server as it moves over). For now, the credit pack the -//! emails quote. +//! Billing: the plans and the credit pack (the catalogue), Stripe's settings, and its routes and webhook. The credit +//! ledger (balances, spending, usage) is `domain::credits`. -/// A pack of credits bought on top of a plan. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// A prepaid credit pack, used after the month's allowance. Pack credits don't expire. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] pub struct CreditPack { pub credits: i64, pub price_cents: i64, - /// Automatic packs buy one when the balance falls below this. + /// An automatic reload buys a pack when the credits left (allowance and packs) fall below this. pub reload_below: i64, } @@ -20,8 +20,8 @@ pub mod routes; pub mod stripe; pub mod webhook; -/// A plan an organization can be on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// A plan. Builds use credits: 1 per snapshot checked, 5 per text diff, 10 per image diff and 20 per PDF page drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] pub struct Plan { pub id: &'static str, pub name: &'static str, @@ -29,9 +29,10 @@ pub struct Plan { pub price_cents: i64, /// Credits included each calendar month (UTC). pub included_credits: i64, - /// Whether the organization can buy credit packs past the allowance. + /// Whether the organization can buy credit packs for builds past the allowance. Without them, builds stop until + /// the month renews. pub credit_packs: bool, - /// No allowance or limit at all: builds never stop for credits. + /// No allowance or limit at all: builds never stop for credits. Usage is still recorded. pub unlimited: bool, } @@ -49,6 +50,9 @@ pub const TEAM: Plan = Plan { pub const STAFF: Plan = Plan { id: "staff", name: "Staff", price_cents: 0, included_credits: 0, credit_packs: false, unlimited: true }; +/// The plans anyone can choose (Staff isn't one of them). +pub const PLANS: &[Plan] = &[FREE, TEAM]; + /// The plan with this id (an organization's `plan` column). Anything unknown is Free. #[must_use] pub fn plan_by_id(id: &str) -> Plan { @@ -104,41 +108,3 @@ pub fn check(stripe: &Stripe, production: bool) -> laravel::Result<()> { } Ok(()) } - -/// Add purchased credits once per `reference` (a Checkout session or an invoice): `true` when added, `false` when -/// that reference was already credited. Two callers that both get here (an automatic reload and its `invoice.paid` -/// webhook) are kept apart by the `credit_transactions_purchase_once` index. -/// -/// # Errors -/// On a database error. -pub async fn add_purchased_credits(org_id: i64, credits: i64, reference: &str) -> laravel::Result { - let added = laravel::db::transaction(async |tx| { - let balance: Option = laravel::db::query!( - tx, - "UPDATE organizations SET credits_balance = credits_balance + {credits}, updated_at = now() \ - WHERE id = {org_id} RETURNING credits_balance" - ) - .scalar() - .await?; - let Some(balance) = balance else { return Ok(false) }; - let inserted: Option = laravel::db::query!( - tx, - "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference) \ - VALUES ({org_id}, {credits}, {balance}, 'purchase', {reference}) \ - ON CONFLICT (organization_id, reference) WHERE kind = 'purchase' DO NOTHING RETURNING id" - ) - .scalar() - .await?; - if inserted.is_none() { - // Already credited: undo this transaction's balance change - return Err(laravel::Error::msg("already credited")); - } - Ok(true) - }) - .await; - match added { - Ok(added) => Ok(added), - Err(e) if e.to_string().contains("already credited") => Ok(false), - Err(e) => Err(e), - } -} diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs index 93fa2ef5..de0deb86 100644 --- a/app/src/billing/webhook.rs +++ b/app/src/billing/webhook.rs @@ -16,7 +16,8 @@ use laravel::prelude::*; use serde_json::{Value, json}; use sha2::Sha256; -use super::{CREDIT_PACK, FREE, Stripe, TEAM, add_purchased_credits, plan_by_id}; +use super::{CREDIT_PACK, FREE, Stripe, TEAM, plan_by_id}; +use crate::domain::credits::add_purchased_credits; use crate::notify::{self, Kind, To}; /// `POST /webhooks/stripe`. diff --git a/app/src/domain/credits.rs b/app/src/domain/credits.rs index d3d217c7..233fc52f 100644 --- a/app/src/domain/credits.rs +++ b/app/src/domain/credits.rs @@ -2,6 +2,8 @@ use laravel::db; +use crate::billing::{CREDIT_PACK, plan_by_id}; + /// Add (or, with a negative amount, take away) pack credits, recording the transaction. Returns the new balance. /// /// # Errors @@ -55,62 +57,10 @@ pub async fn add_purchased_credits(organization_id: i64, credits: i64, reference } } -/// A plan. Builds use credits: 1 per snapshot checked, 5 per text diff, 10 per image diff and 20 per PDF page drawn. -#[derive(Debug, Clone, Copy, serde::Serialize)] -pub struct Plan { - pub id: &'static str, - pub name: &'static str, - /// US cents per month. - pub price_cents: i64, - /// Credits included each calendar month (UTC). - pub included_credits: i64, - /// Whether the organization can buy credit packs for builds past the allowance. Without them, builds stop until - /// the month renews. - pub credit_packs: bool, - /// No allowance or limit at all: builds never stop for credits. Usage is still recorded. - pub unlimited: bool, -} - -pub const FREE: Plan = - Plan { id: "free", name: "Free", price_cents: 0, included_credits: 25_000, credit_packs: false, unlimited: false }; -pub const TEAM: Plan = Plan { - id: "team", - name: "Team", - price_cents: 2_900, - included_credits: 1_000_000, - credit_packs: true, - unlimited: false, -}; -/// DocSpring's own organizations: unlimited, free, and never offered. -pub const STAFF: Plan = - Plan { id: "staff", name: "Staff", price_cents: 0, included_credits: 0, credit_packs: false, unlimited: true }; - -/// The plans anyone can choose (Staff isn't one of them). -pub const PLANS: &[Plan] = &[FREE, TEAM]; - -/// The plan with this id (an organization's `plan` column). Anything unknown is Free. -#[must_use] -pub fn plan_by_id(id: &str) -> Plan { - [TEAM, STAFF].into_iter().find(|p| p.id == id).unwrap_or(FREE) -} - /// Credits a month each organization gets for its open source projects, on any plan: their builds use this pool /// first, then the plan's allowance and packs like any other project. pub const OPEN_SOURCE_POOL: i64 = 1_000_000; -/// A prepaid credit pack, used after the month's allowance. Pack credits don't expire. -#[derive(Debug, Clone, Copy, serde::Serialize)] -pub struct CreditPack { - pub credits: i64, - pub price_cents: i64, - /// An automatic reload buys a pack when the credits left (allowance and packs) fall below this. - pub reload_below: i64, -} - -pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 }; -/// Most automatic reloads an organization can allow in a month. -pub const MAX_AUTO_RELOAD_PACKS: i32 = 50; - /// What each thing costs in credits, for the billing page and the MCP server. #[must_use] pub fn credit_rates() -> serde_json::Value { diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index ad29135c..3819b911 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -874,7 +874,7 @@ pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result if !credits::out_of_credits_for(&org, spender).await? { return Ok(build); } - let plan = credits::plan_by_id(&org.plan); + let plan = crate::billing::plan_by_id(&org.plan); let what_now = if plan.credit_packs { "Buy a credit pack on the billing page, or raise the limit on automatic reloads." } else { diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 5e7206ce..a17de5c5 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -848,7 +848,7 @@ impl VisualCi { .await .map_err(internal)? .ok_or_else(|| internal("the new organization wasn't saved"))?; - let plan = domain::credits::plan_by_id(&org.plan); + let plan = crate::billing::plan_by_id(&org.plan); Ok(structured(json!({ "slug": org.slug, "name": org.name, "plan": plan.name }))) }