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
27 changes: 19 additions & 8 deletions app/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ axum = "0.8"
hex = "0.4"
oauth-provider = "0.1.3"
oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] }
hmac = "0.12"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
Expand Down
1 change: 1 addition & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ pub async fn whoami(principal: Principal) -> laravel::Result<axum::Json<serde_js
/// The sign-in routes, on the `web` group (they need the session).
pub fn routes(route: &mut laravel::prelude::Router) {
route.get("/login", sign_in::login_page);
crate::billing::routes::routes(route);
route.get("/auth/{forge}", sign_in::start);
route.post("/auth/{forge}/link", sign_in::link);
route.get("/auth/{forge}/callback", sign_in::callback);
Expand Down
113 changes: 113 additions & 0 deletions app/src/billing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,118 @@ pub struct CreditPack {
pub reload_below: i64,
}

/// Most automatic reloads an organization can allow in a month.
pub const MAX_AUTO_RELOAD_PACKS: i32 = 50;

/// One pack: 500,000 credits for $15, as today.
pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 };

pub mod routes;
pub mod stripe;
pub mod webhook;

/// A plan an organization can be on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
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.
pub credit_packs: bool,
/// No allowance or limit at all: builds never stop for credits.
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 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)
}

/// Stripe (`STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`). Production's keys come only from the cluster's
/// ExternalSecrets; tests fake Stripe.
#[derive(Clone, laravel::config::Section)]
pub struct Stripe {
#[env("STRIPE_SECRET_KEY")]
pub secret_key: Option<String>,
#[env("STRIPE_WEBHOOK_SECRET")]
pub webhook_secret: Option<String>,
}

impl Stripe {
/// Whether the secret key is a live one (`sk_live_`, `rk_live_`); `None` without a key.
#[must_use]
pub fn live(&self) -> Option<bool> {
let key = self.secret_key.as_deref().map(str::trim).filter(|k| !k.is_empty())?;
Some(key.starts_with("sk_live_") || key.starts_with("rk_live_"))
}
}

/// At boot: production never runs on a test key (`sk_test_`, `rk_test_`), which would take no real payments while
/// granting real plans and credits.
///
/// # Errors
/// In production, when the Stripe key isn't a live one.
pub fn check(stripe: &Stripe, production: bool) -> laravel::Result<()> {
if production && stripe.live() == Some(false) {
return Err(laravel::Error::msg(
"STRIPE_SECRET_KEY is a test key; production needs a live one (sk_live_ or rk_live_)",
));
}
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),
}
}
Loading
Loading