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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! Billing audit (sc-9146, Nathan, 4 Dec 2026):
//!
//! - Automatic credit packs are opt-in: nothing extra is charged until an admin turns them on and picks a monthly
//! limit. The default was 4 packs a month, and every organization had it without choosing it; none had a Stripe
//! customer, so none was ever charged. All go back to off.
//! - Overrun on a plan without packs (Free) is forgiven rather than carried as a negative pack balance, which would be
//! taken out of the first pack bought after upgrading.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r"
SET LOCAL lock_timeout = '5s';
ALTER TABLE organizations ALTER COLUMN auto_reload_packs SET DEFAULT 0;
UPDATE organizations SET auto_reload_packs = 0 WHERE auto_reload_packs <> 0;
INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference)
SELECT id, -credits_balance, 0, 'adjustment', 'Overrun on Free forgiven (sc-9146)'
FROM organizations WHERE plan = 'free' AND credits_balance < 0;
UPDATE organizations SET credits_balance = 0 WHERE plan = 'free' AND credits_balance < 0;
";
17 changes: 17 additions & 0 deletions app/database/migrations/2026_12_08_000001_work_made_by_a_build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! A render or diff records the build that made it, and that build alone pays for it (sc-9146). Charges used to
//! count the renders and diffs created after the build was, comparing the app's clock with the database's: two builds
//! of one project running at once both paid for one shared render, and in tests (one transaction, so every row is
//! stamped with its start) nothing was ever charged for one. Rows from before stay NULL: work already charged.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r"
SET LOCAL lock_timeout = '5s';
ALTER TABLE renders ADD COLUMN made_by_build_id BIGINT;
ALTER TABLE diffs ADD COLUMN made_by_build_id BIGINT;
";
132 changes: 132 additions & 0 deletions app/src/billing/listeners.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//! Billing's side of a build's credits (sc-9146: the Loco server did this, and #132 removed it without a replacement):
//! warnings at 80% and 95% of the month's credits, automatic packs, and the out-of-credits email. A failure here is
//! logged and never fails the build: dispatching awaits these listeners and returns their first error.

use laravel::config::Section;
use laravel::event::{Event, listener};

use super::reload::{self, Reload};
use super::{CREDIT_PACK, plan_by_id};
use crate::config::Stripe;
use crate::domain::{credit_overrides, credits};
use crate::events::{BuildStoppedForCredits, CreditsRanOut, CreditsSpent};
use crate::models::Organization;
use crate::notify::{self, Kind, To};

/// Stripe's secret key, when payments are set up.
fn key(stripe: &Stripe) -> Option<&str> {
stripe.secret_key.as_deref().map(str::trim).filter(|k| !k.is_empty())
}

async fn reload_quietly(stripe: &Stripe, organization_id: i64) -> Option<Reload> {
let key = key(stripe)?;
match reload::auto_reload(key, organization_id).await {
Ok(r) => Some(r),
Err(e) => {
tracing::warn!(organization_id, error = %e, "automatic reload failed");
None
}
}
}

/// A build spent credits: the low-credit warnings, then an automatic pack if the credits left are below the line.
#[listener]
pub async fn after_credits_spent(event: Event<CreditsSpent>, stripe: Section<Stripe>) -> laravel::Result<()> {
if let Err(e) = credits_low(event.organization_id).await {
tracing::warn!(org_id = event.organization_id, error = %e, "low-credit email");
}
reload_quietly(&stripe, event.organization_id).await;
Ok(())
}

/// About to stop a build for credits: an automatic pack first, if the organization has them on. The domain checks the
/// credits again afterwards.
#[listener]
pub async fn when_credits_run_out(event: Event<CreditsRanOut>, stripe: Section<Stripe>) -> laravel::Result<()> {
reload_quietly(&stripe, event.organization_id).await;
Ok(())
}

/// A build was stopped for credits: the billing contact hears once a month, with a link that buys a pack (Team) or
/// upgrades (Free).
#[listener]
pub async fn when_a_build_stops_for_credits(event: Event<BuildStoppedForCredits>) -> laravel::Result<()> {
let org_id = event.organization_id;
let send = async {
let org = Organization::find_or_fail(org_id).await?;
let plan = plan_by_id(&org.plan);
let kind =
Kind::OutOfCredits { plan: plan.name.to_string(), renews: reload::renews_on(), packs: plan.credit_packs };
notify::queue(&kind, To::Billing(org_id), None, &format!("out_of_credits:{org_id}:{}", reload::month_key()))
.await
};
if let Err(e) = send.await {
tracing::warn!(org_id, error = %e, "out-of-credits email");
}
Ok(())
}

/// Warn at 80% and 95% of the plan's credits and of the open source pool, once each a month.
async fn credits_low(org_id: i64) -> laravel::Result<()> {
let org = Organization::find_or_fail(org_id).await?;
let plan = plan_by_id(&org.plan);
let renews = reload::renews_on();
let month = reload::month_key();
if !plan.unlimited {
let total = credit_overrides::allowance_of(org.id, &org.plan).await?;
let used = credits::used_this_month(org.id).await?;
let next = if plan.credit_packs && org.auto_reload_packs > 0 && org.reloads_paused_at.is_none() {
format!(
"When they run out, VisualCI buys a pack of {} credits for ${} with the default card, up to {} packs \
this month.",
credits::thousands(CREDIT_PACK.credits),
CREDIT_PACK.price_cents / 100,
org.auto_reload_packs
)
} else if plan.credit_packs {
"When they and any pack credits run out, builds stop being compared. Buy a pack, or turn on automatic \
packs, on the billing page."
.to_string()
} else {
format!(
"When they run out, builds aren't compared until the credits renew. Team includes {} credits a month.",
credits::thousands(super::TEAM.included_credits)
)
};
threshold(org.id, false, used, total, &renews, &next, &month).await?;
}
let pool_used = credits::pool_used_this_month(org.id).await?;
if pool_used > 0 {
let next = "When they run out, open source projects use the plan's credits.".to_string();
threshold(org.id, true, pool_used, credits::OPEN_SOURCE_POOL, &renews, &next, &month).await?;
}
Ok(())
}

async fn threshold(
org_id: i64,
pool: bool,
used: i64,
total: i64,
renews: &str,
next: &str,
month: &str,
) -> laravel::Result<()> {
// Out of credits has its own email.
if total <= 0 || used >= total {
return Ok(());
}
// The highest threshold passed: 95 before 80, so a jump past both sends one email.
let Some(percent) = [95u8, 80].into_iter().find(|p| used * 100 >= total * i64::from(*p)) else { return Ok(()) };
let kind = Kind::CreditsLow {
pool,
percent,
left: total - used,
total,
renews: renews.to_string(),
next: next.to_string(),
};
let key = format!("credits_low:{org_id}:{}:{month}:{percent}", if pool { "pool" } else { "plan" });
notify::queue(&kind, To::Billing(org_id), None, &key).await?;
Ok(())
}
2 changes: 2 additions & 0 deletions app/src/billing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ 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 listeners;
pub mod reload;
pub mod routes;
pub mod stripe;
pub mod webhook;
Expand Down
Loading
Loading