Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 13 additions & 47 deletions app/src/billing/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
}

Expand All @@ -20,18 +20,19 @@ 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,
/// 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 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,
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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<bool> {
let added = laravel::db::transaction(async |tx| {
let balance: Option<i64> = 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<i64> = 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),
}
}
3 changes: 2 additions & 1 deletion app/src/billing/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
54 changes: 2 additions & 52 deletions app/src/domain/credits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -874,7 +874,7 @@ pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result<Build>
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 {
Expand Down
2 changes: 1 addition & 1 deletion app/src/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 })))
}

Expand Down
Loading