diff --git a/app/database/migrations/2026_12_08_000000_opt_in_automatic_packs.rs b/app/database/migrations/2026_12_08_000000_opt_in_automatic_packs.rs new file mode 100644 index 00000000..8e1892e6 --- /dev/null +++ b/app/database/migrations/2026_12_08_000000_opt_in_automatic_packs.rs @@ -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; +"; diff --git a/app/database/migrations/2026_12_08_000001_work_made_by_a_build.rs b/app/database/migrations/2026_12_08_000001_work_made_by_a_build.rs new file mode 100644 index 00000000..6149f2c1 --- /dev/null +++ b/app/database/migrations/2026_12_08_000001_work_made_by_a_build.rs @@ -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; +"; diff --git a/app/src/billing/listeners.rs b/app/src/billing/listeners.rs new file mode 100644 index 00000000..1ce1c9cd --- /dev/null +++ b/app/src/billing/listeners.rs @@ -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 { + 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, stripe: Section) -> 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, stripe: Section) -> 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) -> 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(()) +} diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs index a80653db..eec523b5 100644 --- a/app/src/billing/mod.rs +++ b/app/src/billing/mod.rs @@ -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; diff --git a/app/src/billing/reload.rs b/app/src/billing/reload.rs new file mode 100644 index 00000000..4ec56b25 --- /dev/null +++ b/app/src/billing/reload.rs @@ -0,0 +1,238 @@ +//! Automatic credit packs (sc-9146: ported from the Loco server, which #132 removed without a replacement). An +//! organization on a plan with packs (Team) that has turned them on, with a card on file, buys one pack when its credits +//! left fall below `CREDIT_PACK.reload_below`, up to the monthly limit its admins chose. Off by default: nothing extra +//! is charged until an admin turns them on (Nathan, 4 Dec 2026). +//! +//! A pack is an invoice charged to the card on file off-session, with Stripe Tax. A declined card voids the invoice (so +//! nothing retries it behind the organization's back), records the problem and pauses reloads until an admin fixes +//! the card and saves the limit again. The pack is credited once, by whichever of this code and the `invoice.paid` +//! webhook gets there first (`credits::add_purchased_credits`, keyed by the invoice). + +use laravel::db; +use serde_json::Value; + +use super::stripe::{self, Method}; +use super::{CREDIT_PACK, plan_by_id}; +use crate::domain::credits; +use crate::models::Organization; +use crate::notify::{self, Kind, Paused, To}; + +/// What an automatic reload did. +#[derive(Debug, PartialEq, Eq)] +pub enum Reload { + Bought, + NotNeeded, + /// Payments aren't set up, the plan has no packs (Free), or there's no customer or card on file. + Unavailable, + /// Turned off (a limit of 0), or this month's limit is used up. + LimitReached, + /// A payment failed, and reloads wait until an admin fixes the card and turns them back on. + Paused, + /// Another reload is under way. + InProgress, + Declined(String), +} + +/// Buy one pack if the organization needs one and may: see the module's doc. +/// +/// # Errors +/// On a database error, or when Stripe can't be reached. +pub async fn auto_reload(key: &str, organization_id: i64) -> laravel::Result { + let org = Organization::find_or_fail(organization_id).await?; + if !plan_by_id(&org.plan).credit_packs || org.stripe_customer_id.is_none() { + return Ok(Reload::Unavailable); + } + if org.reloads_paused_at.is_some() { + return Ok(Reload::Paused); + } + if credits::credits_left(&org).await? >= CREDIT_PACK.reload_below { + return Ok(Reload::NotNeeded); + } + if org.auto_reload_packs <= 0 { + return Ok(Reload::LimitReached); + } + if credits::reloads_this_month(org.id).await? >= i64::from(org.auto_reload_packs) { + // Once a month: the limit they chose is used up. + let kind = Kind::AutoBuyPaused(Paused::LimitReached(org.auto_reload_packs)); + let dedupe = format!("auto_buy_limit:{}:{}", org.id, month_key()); + if let Err(e) = notify::queue(&kind, To::Billing(org.id), None, &dedupe).await { + tracing::warn!(org_id = org.id, error = %e, "automatic pack limit email"); + } + return Ok(Reload::LimitReached); + } + // Claim the reload, so two builds finishing together buy one pack. A claim older than five minutes is stale. The + // claim's time names this attempt in Stripe's idempotency keys. + let claimed: Option = db::query!( + "UPDATE organizations SET reload_started_at = now() WHERE id = {organization_id} \ + AND (reload_started_at IS NULL OR reload_started_at < now() - interval '5 minutes') \ + RETURNING (extract(epoch FROM reload_started_at) * 1000000)::BIGINT" + ) + .scalar() + .await?; + let Some(claimed) = claimed else { return Ok(Reload::InProgress) }; + // Read again under the claim: a reload that finished between the checks above and the claim already bought the + // pack this one would. + // An error keeps the claim until it's stale: a pay call whose outcome is unknown may have charged the card, and + // its `invoice.paid` webhook credits the pack in the meantime, so a second build doesn't buy another. + let org = Organization::find_or_fail(organization_id).await?; + let still_needed = plan_by_id(&org.plan).credit_packs + && org.reloads_paused_at.is_none() + && credits::credits_left(&org).await? < CREDIT_PACK.reload_below + && credits::reloads_this_month(org.id).await? < i64::from(org.auto_reload_packs); + let reload = if still_needed { + charge_pack(key, &org, &format!("visualci-reload-{organization_id}-{claimed}")).await? + } else { + Reload::NotNeeded + }; + db::query!("UPDATE organizations SET reload_started_at = NULL WHERE id = {organization_id}").update().await?; + tracing::info!(organization_id, ?reload, "automatic reload"); + Ok(reload) +} + +/// The card a reload charges: the subscription's (where Checkout saves it), or else the customer's default. +async fn reload_card(key: &str, org: &Organization) -> laravel::Result> { + let id = |v: &Value| v.as_str().or_else(|| v["id"].as_str()).map(str::to_string); + if let Some(sub) = &org.stripe_subscription_id { + let s = stripe::get(key, &format!("subscriptions/{sub}"), &[]).await?; + if let Some(card) = id(&s["default_payment_method"]) { + return Ok(Some(card)); + } + } + let Some(customer) = &org.stripe_customer_id else { return Ok(None) }; + let c = stripe::get(key, &format!("customers/{customer}"), &[]).await?; + Ok(id(&c["invoice_settings"]["default_payment_method"])) +} + +async fn charge_pack(key: &str, org: &Organization, idempotency: &str) -> laravel::Result { + let catalog = stripe::catalog(key).await?; + let Some(card) = reload_card(key, org).await? else { return Ok(Reload::Unavailable) }; + let customer = org.stripe_customer_id.clone().unwrap_or_default(); + let invoice = stripe::request( + key, + Method::Post, + "invoices", + &[ + ("customer", customer.clone()), + ("collection_method", "charge_automatically".to_string()), + ("default_payment_method", card), + ("auto_advance", "false".to_string()), + ("automatic_tax[enabled]", "true".to_string()), + ("pending_invoice_items_behavior", "exclude".to_string()), + ("description", "Automatic reload: one credit pack".to_string()), + ("metadata[organization_id]", org.id.to_string()), + ("metadata[kind]", "auto_reload".to_string()), + ], + Some(&format!("{idempotency}-invoice")), + ) + .await?; + let invoice_id = invoice["id"].as_str().unwrap_or_default().to_string(); + stripe::request( + key, + Method::Post, + "invoiceitems", + &[ + ("customer", customer), + ("invoice", invoice_id.clone()), + ("pricing[price]", catalog.pack_price.clone()), + ("quantity", "1".to_string()), + ], + Some(&format!("{idempotency}-item")), + ) + .await?; + let finalized = stripe::request( + key, + Method::Post, + &format!("invoices/{invoice_id}/finalize"), + &[("auto_advance", "false".to_string())], + Some(&format!("{idempotency}-finalize")), + ) + .await?; + if finalized["status"] == "paid" { + // A zero total (a credit balance covered it) is paid on finalizing. + return credit_reload(org, &invoice_id, finalized["hosted_invoice_url"].as_str()).await; + } + let paid = stripe::request( + key, + Method::Post, + &format!("invoices/{invoice_id}/pay"), + &[("off_session", "true".to_string())], + Some(&format!("{idempotency}-pay")), + ) + .await; + // A pay call cut off in transit may have charged the card: ask Stripe before calling it declined. + let paid = match paid { + Err(e) if !e.to_string().contains("HTTP 402") => { + match stripe::get(key, &format!("invoices/{invoice_id}"), &[]).await { + Ok(invoice) if invoice["status"] == "paid" => Ok(invoice), + Ok(invoice) if invoice["status"] == "open" => Err(e), + // Neither paid nor clearly declined (or Stripe can't be reached): leave the invoice and the packs + // alone; its `invoice.paid` webhook credits the pack if it went through. + _ => return Err(e), + } + } + other => other, + }; + match paid { + Ok(invoice) if invoice["status"] == "paid" => { + credit_reload(org, &invoice_id, invoice["hosted_invoice_url"].as_str()).await + } + // A declined card comes back as an HTTP error; anything short of paid is a failure too. + other => { + let reason = match other { + Ok(invoice) => format!("the invoice is {}", invoice["status"]), + Err(e) => e.to_string(), + }; + if let Err(e) = stripe::post(key, &format!("invoices/{invoice_id}/void"), &[]).await { + tracing::warn!(org_id = org.id, invoice_id, error = %e, "couldn't void a failed reload invoice"); + } + super::webhook::record_payment_problem( + org.id, + "An automatic credit pack was declined. Update the card in Manage billing, then turn automatic packs \ + back on.", + ) + .await?; + let kind = Kind::AutoBuyPaused(Paused::Declined(decline_reason(&reason))); + let dedupe = format!("auto_buy_declined:{}:{invoice_id}", org.id); + if let Err(e) = notify::queue(&kind, To::Billing(org.id), None, &dedupe).await { + tracing::warn!(org_id = org.id, error = %e, "declined pack email"); + } + Ok(Reload::Declined(reason)) + } + } +} + +async fn credit_reload(org: &Organization, invoice_id: &str, invoice_url: Option<&str>) -> laravel::Result { + credits::add_purchased_credits(org.id, CREDIT_PACK.credits, &format!("auto-reload: {invoice_id}")).await?; + let kind = Kind::PackBought { + packs_this_month: credits::reloads_this_month(org.id).await?, + limit: org.auto_reload_packs, + invoice_url: invoice_url.map(str::to_string), + }; + let dedupe = format!("pack_bought:{}:{invoice_id}", org.id); + if let Err(e) = notify::queue(&kind, To::Billing(org.id), None, &dedupe).await { + tracing::warn!(org_id = org.id, error = %e, "pack bought email"); + } + Ok(Reload::Bought) +} + +/// Stripe's decline message from a failed payment's error, for the email. +#[must_use] +pub fn decline_reason(error: &str) -> String { + let reason = error.rsplit(": ").next().unwrap_or(error).trim().trim_matches('"').trim_end_matches('.'); + if reason.is_empty() { "no reason given".to_string() } else { reason.to_lowercase() } +} + +/// "2026-12": once-a-month emails are keyed by it. +#[must_use] +pub fn month_key() -> String { + credits::month_start().in_tz("UTC").map(|z| z.strftime("%Y-%m").to_string()).unwrap_or_default() +} + +/// "1 January 2027": when this month's allowance renews. +#[must_use] +pub fn renews_on() -> String { + credits::renews_at() + .and_then(|t| t.in_tz("UTC").ok()) + .map(|z| z.strftime("%-d %B %Y").to_string()) + .unwrap_or_default() +} diff --git a/app/src/billing/routes.rs b/app/src/billing/routes.rs index 20e395b3..bdb2f32d 100644 --- a/app/src/billing/routes.rs +++ b/app/src/billing/routes.rs @@ -108,9 +108,15 @@ pub async fn checkout( return Err(laravel::abort_with(400, "the only plan to subscribe to is team")); } let org = billing_org(&user, &org).await?; - if org.plan == TEAM.id || org.subscription.is_some() { + if org.plan == TEAM.id { return Err(laravel::abort_with(400, "this organization already has a Team subscription")); } + if org.subscription.is_some() { + return Err(laravel::abort_with( + 400, + "this organization's Team subscription has an unpaid invoice: pay it in Manage billing to go back to Team", + )); + } if org.plan == STAFF.id { return Err(laravel::abort_with(400, "this organization is on the Staff plan, which has no limits")); } diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs index 7dfa1ff9..ea770296 100644 --- a/app/src/billing/webhook.rs +++ b/app/src/billing/webhook.rs @@ -85,12 +85,25 @@ pub async fn handle( customer: text(&object["customer"]), subscription: text(&object["id"]), }, - "past_due" | "unpaid" => Change::Problem(PAYMENT_FAILED), + // Stripe is still retrying the payment: Team stays, with a notice. + "past_due" => Change::Problem(PAYMENT_FAILED), + // Retries are over: Free until it's paid. The subscription stays on the organization, so paying the open + // invoice (Manage billing, which the plan page offers) brings Team back ("active" again). + "unpaid" => Change::Plan { + plan: FREE.id, + customer: text(&object["customer"]), + subscription: text(&object["id"]), + }, + // Over for good (`incomplete_expired`'s invoice can't be paid): Free, and a new Checkout can start Team. + "canceled" | "incomplete_expired" => Change::Plan { plan: FREE.id, customer: None, subscription: None }, _ => Change::Nothing, }; if !subscription_event(org_id, created, change).await? { return Ok(Json(json!({ "ignored": "an older event" }))); } + if object["status"] == "unpaid" { + record_payment_problem(org_id, UNPAID).await?; + } } "customer.subscription.deleted" => { let change = Change::Plan { plan: FREE.id, customer: None, subscription: None }; @@ -139,6 +152,8 @@ async fn org_for(object: &Value) -> laravel::Result> { const TWO_SUBSCRIPTIONS: &str = "This organization has two Team subscriptions. Cancel one in Manage billing."; const PAYMENT_FAILED: &str = "The Team subscription's last payment failed. Update the card in Manage billing."; +const UNPAID: &str = "The Team subscription's payment failed and Stripe has stopped trying, so this organization is on \ + Free. Pay the open invoice in Manage billing to go back to Team."; /// What a subscription event does. enum Change { diff --git a/app/src/domain/compare.rs b/app/src/domain/compare.rs index 9d5bc6d7..989a6021 100644 --- a/app/src/domain/compare.rs +++ b/app/src/domain/compare.rs @@ -290,7 +290,8 @@ async fn page_state( let other = (env != snapshot.environment).then_some(env); return Ok(("variant", None, other)); } - let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options, mask).await?; + let diff = + super::diffs::find_or_compute(store, &base.image, &head.image, options, mask, Some(snapshot.build_id)).await?; if !super::diffs::is_change(&diff) { return Ok((super::diffs::unchanged_state(&diff), Some(diff.id), None)); } diff --git a/app/src/domain/credits.rs b/app/src/domain/credits.rs index 74674e81..fa94854e 100644 --- a/app/src/domain/credits.rs +++ b/app/src/domain/credits.rs @@ -335,10 +335,12 @@ pub async fn spend_gallery(project: &crate::models::Project, credits: i64, daily /// source project), then this month's allowance, then pack credits. Returns the pack balance after and how many came /// from the pool. async fn take(organization_id: i64, credits: i64, spender: Option) -> laravel::Result<(i64, i64)> { - let plan: String = db::query!("SELECT plan FROM organizations WHERE id = {organization_id} FOR UPDATE") - .scalar() + let row = db::query!("SELECT plan, credits_balance FROM organizations WHERE id = {organization_id} FOR UPDATE") + .select_one() .await? .ok_or_else(|| laravel::Error::msg(format!("no organization {organization_id}")))?; + let plan: String = row.try_get("plan")?; + let balance_before: i64 = row.try_get("credits_balance")?; let allowance = credit_overrides::allowance_of(organization_id, &plan).await?; let plan = plan_by_id(&plan); let from_pool = match spender { @@ -353,7 +355,11 @@ async fn take(organization_id: i64, credits: i64, spender: Option) -> l 0 } else { let allowance_left = (allowance - used_this_month(organization_id).await?).max(0); - (for_plan - allowance_left).clamp(0, for_plan.max(0)) + let over = (for_plan - allowance_left).clamp(0, for_plan.max(0)); + // A plan without packs (Free) never owes credits (sc-9146, Nathan, 4 Dec 2026): what a build uses past the + // allowance comes out of pack credits left from an earlier plan, and the rest is forgiven, never carried into + // the first pack bought after upgrading. On Team the next pack pays it. + if plan.credit_packs { over } else { over.min(balance_before.max(0)) } }; let balance: i64 = db::query!( "UPDATE organizations SET credits_balance = credits_balance - {from_packs}, updated_at = now() \ diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index 4d80e429..57ae4391 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -489,7 +489,7 @@ impl Seeder<'_> { let blob = super::blobs::put(self.store, source.into_bytes(), "application/pdf").await?; let renderer_key = super::projects::renderer_key(&project.renderer, project.dpi, self.renderer_version); let render = - super::renders::find_or_queue(project.id, &fingerprint, &renderer_key, &blob.sha256).await?; + super::renders::find_or_queue(project.id, &fingerprint, &renderer_key, &blob.sha256, None).await?; if render.state != "done" { super::renders::complete(render, &rendered, None).await?; } diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs index 38c69cf5..0bdb122d 100644 --- a/app/src/domain/detail.rs +++ b/app/src/domain/detail.rs @@ -162,7 +162,7 @@ pub async fn review_detail_against( let (bp, hp) = (&old[b], &new[h]); match (&bp.head_image, &hp.head_image) { (Some(bi), Some(hi)) => { - let diff = super::diffs::find_or_compute(store, bi, hi, options, mask).await?; + let diff = super::diffs::find_or_compute(store, bi, hi, options, mask, None).await?; let state = if super::diffs::is_change(&diff) { "changed" } else { diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs index 21bed2ff..b0522f29 100644 --- a/app/src/domain/diffs.rs +++ b/app/src/domain/diffs.rs @@ -72,6 +72,7 @@ pub async fn find_or_compute( head_image: &str, options: DiffOptions, mask: &ImageMask, + made_by: Option, ) -> laravel::Result { let key = options_key(&options, mask); let stale = match find(base_image, head_image, &key).await? { @@ -115,9 +116,9 @@ pub async fn find_or_compute( let json = serde_json::to_value(&outcome).unwrap_or_default(); db::query!( "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ - fingerprint, result, overlay_blob) \ + fingerprint, result, overlay_blob, made_by_build_id) \ VALUES ({base_image}, {head_image}, {key}, {changed_pixels}, {fraction}, {size_changed}, {fingerprint}, \ - {json}, {overlay_blob}) \ + {json}, {overlay_blob}, {made_by}) \ ON CONFLICT (base_image, head_image, options_key) DO NOTHING" ) .insert() diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 8cec66d1..0da68449 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -243,6 +243,27 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la Ok(()) } +/// How many snapshots a run compares between credit checks: a build that runs out part-way overruns by at most this +/// many comparisons (and the builds of the organization running at the same moment). +pub const CREDIT_CHECK_EVERY: usize = 200; + +/// Charge what the build has used so far and, when its organization is now out of credits, stop it as `run` does +/// (billing's listeners get their chance to reload first). `true` when it stopped. Outside any transaction. +async fn stop_part_way(build: &Build) -> laravel::Result { + charge(build).await?; + let project = Project::find_or_fail(build.project_id).await?; + let org = Organization::find_or_fail(project.organization_id).await?; + if !credits::out_of_credits_for(&org, Spender::of(&project)).await? { + return Ok(false); + } + let build = stop_if_out_of_credits(Build::find_or_fail(build.id).await?).await?; + if build.state != "failed" { + return Ok(false); + } + drop_unneeded_renders(build.id).await?; + Ok(true) +} + /// Fail a processing build whose stored `visualci.yml` no longer validates, rather than compare it with settings it /// wasn't sent: its `error` names the field and the problem (shown by get_build, its page and its check's title), and /// its queued renders that nothing else waits on are dropped. @@ -267,10 +288,12 @@ async fn fail_for_config(mut build: Build, invalid: &ConfigInvalid) -> laravel:: /// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { + // The build's check and live pages first: billing's listeners (an automatic pack, the low-credit emails) call + // Stripe and the outbox, and mustn't hold them up. + crate::events::BuildChanged { build_id }.dispatch().await?; if let Some(project) = Project::find(project_id).await? { crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await?; } - crate::events::BuildChanged { build_id }.dispatch().await?; Ok(()) } @@ -301,7 +324,14 @@ async fn redraw_base( if base_key.as_deref() == Some(head_key.as_str()) { return Ok(Redraw::Ready(Box::new(base.clone()))); } - let render = super::renders::find_or_queue(settings.project.id, &base.source_fingerprint, &head_key, &blob).await?; + let render = super::renders::find_or_queue( + settings.project.id, + &base.source_fingerprint, + &head_key, + &blob, + Some(head.build_id), + ) + .await?; Ok(match render.state.as_str() { "done" => { let mut redrawn = base.clone(); @@ -420,7 +450,7 @@ async fn queue_render(project_id: i64, renderer: &str, snapshot: &mut Snapshot) update!(snapshot { source_fingerprint }).await?; } let key = if snapshot.source_fingerprint.is_empty() { blob.clone() } else { snapshot.source_fingerprint.clone() }; - super::renders::find_or_queue(project_id, &key, renderer, &blob).await + super::renders::find_or_queue(project_id, &key, renderer, &blob, Some(snapshot.build_id)).await } /// Once a document's render is done: a PDF sent without a fingerprint takes the one the renderer reported for its @@ -546,11 +576,18 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> let compare_started = std::time::Instant::now(); let mut seen = HashSet::new(); + let mut compared = 0usize; for mut snapshot in snapshots { seen.insert((snapshot.name.clone(), snapshot.platform.clone())); if snapshot.state == "failed" { continue; } + // Out of credits part-way through a large build: stop between batches rather than compare the rest + // (sc-9146). Document builds already stop between render waits, in `run`. + compared += 1; + if compared.is_multiple_of(CREDIT_CHECK_EVERY) && Box::pin(stop_part_way(&build)).await? { + return Ok(true); + } let key = (snapshot.name.clone(), snapshot.platform.clone()); match Box::pin(compare(&mut snapshot, store, &settings, base_snapshots.get(&key))).await { Ok(()) => set_baseline_id(&mut snapshot, baseline_rows.get(&key).copied()).await?, @@ -882,15 +919,15 @@ async fn charge_locked(build: &Build) -> laravel::Result<()> { let project = Project::find_or_fail(build.project_id).await?; let mut fresh = Build::find_or_fail(build.id).await?; let charged: Usage = serde_json::from_value(fresh.charged.clone()).unwrap_or_default(); - let (id, since) = (build.id, build.created_at); + let id = build.id; let row = db::query!( "SELECT \ (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed')::BIGINT AS checks, \ (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND kind = 'text' AND state = 'changed')::BIGINT AS text_diffs, \ (SELECT COALESCE(SUM(jsonb_array_length(r.pages)), 0) FROM renders r \ - WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.created_at >= {since})::BIGINT AS pages, \ + WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.made_by_build_id = {id})::BIGINT AS pages, \ (SELECT COUNT(DISTINCT d.id) FROM diffs d JOIN snapshot_pages p ON p.diff_id = d.id \ - JOIN snapshots s ON s.id = p.snapshot_id WHERE s.build_id = {id} AND d.created_at >= {since})::BIGINT AS image_diffs" + JOIN snapshots s ON s.id = p.snapshot_id WHERE s.build_id = {id} AND d.made_by_build_id = {id})::BIGINT AS image_diffs" ) .select_one() .await?; @@ -972,7 +1009,8 @@ pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result Ok(build) } -/// A build stopped: its queued renders that no other receiving or processing build waits on aren't drawn. +/// A build stopped: its queued renders that no other receiving or processing build waits on aren't drawn, and the +/// ones another build waits on are charged to that build. /// /// # Errors /// On a database error. @@ -986,6 +1024,15 @@ pub async fn drop_unneeded_renders(build_id: i64) -> laravel::Result<()> { ) .update() .await?; + // A render another build still waits for stays queued, and that build pays for its pages: this one is charged now, + // without them. + db::query!( + "UPDATE renders SET made_by_build_id = (SELECT MIN(s.build_id) FROM snapshots s JOIN builds b ON b.id = s.build_id \ + WHERE s.render_id = renders.id AND s.build_id <> {id} AND b.state IN ('receiving', 'processing')) \ + WHERE state = 'queued' AND made_by_build_id = {id}" + ) + .update() + .await?; Ok(()) } diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs index efad61c7..a8950033 100644 --- a/app/src/domain/renders.rs +++ b/app/src/domain/renders.rs @@ -53,7 +53,8 @@ pub async fn with_text(mut pages: Vec) -> laravel::Result, ) -> laravel::Result { db::query!( - "INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob) \ - VALUES ({project_id}, {fingerprint}, {renderer}, {source_blob}) \ + "INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob, made_by_build_id) \ + VALUES ({project_id}, {fingerprint}, {renderer}, {source_blob}, {made_by}) \ ON CONFLICT (project_id, source_fingerprint, renderer) DO UPDATE SET used_at = now() \ WHERE renders.used_at IS NULL OR renders.used_at < now() - interval '1 hour'" ) @@ -83,6 +85,9 @@ pub async fn find_or_queue( if render.state == "failed" && render.attempts < MAX_ATTEMPTS { let source_blob = source_blob.to_string(); update!(render { state: "queued", source_blob }).await?; + // The build that queues it again pays for its pages: the one whose attempt failed was charged without them. + let id = render.id; + db::query!("UPDATE renders SET made_by_build_id = {made_by} WHERE id = {id}").update().await?; } Ok(render) } diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs index db25cc07..961ffce1 100644 --- a/app/src/notify/render.rs +++ b/app/src/notify/render.rs @@ -274,12 +274,22 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { fail with an \"out of credits\" error instead of being compared, until the credits renew on {renews}." ), if *packs { - "Buy a credit pack, or turn on automatic packs, on the billing page.".to_string() + format!( + "A pack of {} credits costs {} and doesn't expire. Automatic packs, on the billing page, buy \ + one when credits run low, up to a monthly limit you choose.", + n(CREDIT_PACK.credits), + money(CREDIT_PACK.price_cents) + ) } else { "Team includes 1,000,000 credits a month. Upgrade on the billing page.".to_string() }, ], - ("Open billing".into(), billing), + // One click from the email to Stripe's checkout for a pack (the billing page starts it for an admin). + if *packs { + ("Buy a credit pack".into(), format!("{billing}?buy=pack")) + } else { + ("Upgrade to Team".into(), billing) + }, ), Kind::PackBought { packs_this_month, limit, invoice_url } => ( format!("VisualCI bought a credit pack for {org}"), diff --git a/app/tests/all.rs b/app/tests/all.rs index 36540273..254fc442 100644 --- a/app/tests/all.rs +++ b/app/tests/all.rs @@ -20,6 +20,7 @@ mod abuse; mod api_builds; mod app_shell; mod auth; +mod automatic_packs; mod baselines; mod billing; mod branches; diff --git a/app/tests/automatic_packs.rs b/app/tests/automatic_packs.rs new file mode 100644 index 00000000..626f8c1d --- /dev/null +++ b/app/tests/automatic_packs.rs @@ -0,0 +1,277 @@ +//! Billing audit (sc-9146): automatic credit packs are off until an admin turns them on; when on, running low buys one +//! pack (charged once, credited once, emailed), a declined card pauses them, and the monthly limit holds. The credit +//! emails go out: 80% and 95% used, and out of credits (once a month, with a link that buys a pack). Free never owes +//! credits. + +use app::events::{BuildStoppedForCredits, CreditsRanOut, CreditsSpent}; +use app::testing::fixtures; +use laravel::db; +use laravel::http::client; +use laravel::testing::prelude::*; +use serde_json::json; + +fn with_stripe_key() -> Application { + app::testing::configure() + .with_envs([("VISUALCI_STRIPE_SECRET_KEY", "sk_test_x"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) + .create() +} + +/// A Team organization with a Stripe customer and subscription, a billing email, its allowance used up, no pack +/// credits, and automatic packs set to `packs` a month. +async fn team_out_of_credits(slug: &str, packs: i32) -> laravel::Result { + let org = fixtures::organization(slug).await?; + let id = org.id; + db::query!( + "UPDATE organizations SET plan = 'team', stripe_customer_id = 'cus_1', stripe_subscription_id = 'sub_1', \ + billing_email = 'billing@example.com', auto_reload_packs = {packs} WHERE id = {id}" + ) + .update() + .await?; + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind) VALUES ({id}, -1000000, 0, 'build')" + ) + .insert() + .await?; + Ok(id) +} + +/// Stripe, as the reload sees it: the catalog, the subscription's card, and an invoice the card pays (or declines). +fn stripe(pays: bool) -> client::HttpFake { + client::fake().with("api.stripe.com/*", move |r: &client::Request| -> client::FakeResponse { + let path = r.url().split_once("/v1/").map_or("", |(_, p)| p).split('?').next().unwrap_or("").to_string(); + match path.as_str() { + "prices" | "billing_portal/configurations" if r.method() == "GET" => { + client::response().json(json!({ "data": [] })) + } + "subscriptions/sub_1" => { + client::response().json(json!({ "id": "sub_1", "default_payment_method": "pm_1" })) + } + "invoices" => client::response().json(json!({ "id": "in_1", "status": "draft" })), + "invoices/in_1/finalize" => client::response().json(json!({ "id": "in_1", "status": "open" })), + "invoices/in_1/pay" if pays => client::response().json( + json!({ "id": "in_1", "status": "paid", "hosted_invoice_url": "https://invoice.stripe.test/in_1" }), + ), + "invoices/in_1/pay" => { + client::response().status(402).json(json!({ "error": { "message": "Your card was declined." } })) + } + _ => client::response().json(json!({ "id": format!("x_{}", path.replace('/', "_")) })), + } + }) +} + +/// A build of a new project in `org`, created over the API and moved on to processing (as finalizing does). +async fn processing_build(app: &Application, org: i64) -> laravel::Result { + let organization = app::models::Organization::find_or_fail(org).await?; + let project = fixtures::project(&organization, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + let created = app + .post("/api/v1/builds") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "commit": "c1", "branch": "main", "parent_commits": [] })) + .await; + created.assert_ok(); + db::query!("UPDATE builds SET state = 'processing' WHERE project_id = {project_id}").update().await?; + Ok(app::models::Build::query() + .filter(app::models::Build::project_id.eq(project_id)) + .first() + .await? + .expect("the build")) +} + +fn posts_to(fake: &client::HttpFake, path: &str) -> usize { + fake.sent().iter().filter(|r| r.method() == "POST" && r.url().ends_with(&format!("/v1/{path}"))).count() +} + +async fn balance(org: i64) -> laravel::Result { + Ok(db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar().await?.unwrap_or(0)) +} + +async fn emails(org: i64, kind: &str) -> laravel::Result { + Ok(db::query!("SELECT COUNT(*) FROM emails WHERE organization_id = {org} AND kind = {kind}") + .scalar() + .await? + .unwrap_or(0)) +} + +#[laravel::test] +async fn automatic_packs_are_off_until_an_admin_turns_them_on(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + assert_eq!(org.auto_reload_packs, 0); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn running_out_buys_one_pack_charged_once_and_emailed(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 2).await?; + let fake = stripe(true); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(balance(org).await?, 500_000, "one pack credited"); + assert_eq!(posts_to(&fake, "invoices/in_1/pay"), 1); + assert_eq!(emails(org, "pack_bought").await?, 1); + // Credits are no longer low: nothing more is bought, and the invoice's own webhook adds nothing. + CreditsSpent { organization_id: org }.dispatch().await?; + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(posts_to(&fake, "invoices/in_1/pay"), 1, "a second pack was charged"); + assert!(!app::domain::credits::add_purchased_credits(org, 500_000, "auto-reload: in_1").await?); + assert_eq!(balance(org).await?, 500_000); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn off_by_default_nothing_is_charged(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 0).await?; + let fake = stripe(true); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(posts_to(&fake, "invoices"), 0, "an invoice was made with automatic packs off"); + assert_eq!(balance(org).await?, 0); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn a_declined_card_pauses_automatic_packs_and_says_so(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 2).await?; + let fake = stripe(false); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(balance(org).await?, 0); + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 1, "the failed invoice is voided, so Stripe doesn't retry it"); + let paused: Option = + db::query!("SELECT reloads_paused_at IS NOT NULL FROM organizations WHERE id = {org}").scalar().await?; + assert_eq!(paused, Some(true)); + assert_eq!(emails(org, "auto_buy_paused").await?, 1); + // Paused: no new attempt until an admin turns them back on. + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(posts_to(&fake, "invoices/in_1/pay"), 1); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn the_monthly_limit_holds(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 1).await?; + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference) \ + VALUES ({org}, 500000, 500000, 'purchase', 'auto-reload: in_0'), ({org}, -500000, 0, 'build', NULL)" + ) + .insert() + .await?; + let fake = stripe(true); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(posts_to(&fake, "invoices"), 0, "a pack past the limit"); + assert_eq!(emails(org, "auto_buy_paused").await?, 1, "the limit email"); + Ok(()) +} + +#[laravel::test] +async fn a_stopped_build_emails_once_a_month_with_a_link_that_buys_a_pack(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 0).await?; + for build_id in [1, 2] { + BuildStoppedForCredits { build_id, organization_id: org }.dispatch().await?; + } + assert_eq!(emails(org, "out_of_credits").await?, 1); + let data: serde_json::Value = + db::query!("SELECT data FROM emails WHERE organization_id = {org} AND kind = 'out_of_credits'") + .scalar() + .await? + .unwrap_or_default(); + let kind: app::notify::Kind = serde_json::from_value(data).expect("the email's kind"); + let about = app::notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + let rendered = app::notify::render(&kind, &about); + assert!(rendered.text.contains("https://app.visualci.test/acme/billing?buy=pack"), "{}", rendered.text); + Ok(()) +} + +#[laravel::test] +async fn low_credit_emails_go_out_at_80_and_95_percent_once_each(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let id = org.id; + db::query!("UPDATE organizations SET billing_email = 'billing@example.com' WHERE id = {id}").update().await?; + app::domain::credits::spend(id, 20_000, "build", None, None, None).await?; + CreditsSpent { organization_id: id }.dispatch().await?; + CreditsSpent { organization_id: id }.dispatch().await?; + assert_eq!(emails(id, "credits_low").await?, 1, "80% of Free's 25,000"); + app::domain::credits::spend(id, 4_000, "build", None, None, None).await?; + CreditsSpent { organization_id: id }.dispatch().await?; + assert_eq!(emails(id, "credits_low").await?, 2, "and 95%"); + Ok(()) +} + +#[laravel::test] +async fn free_never_owes_credits(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let id = org.id; + // 100 pack credits left from an earlier Team plan. + app::domain::credits::add_credits(id, 100, "purchase", Some("packs: cs_old")).await?; + app::domain::credits::spend(id, 30_000, "build", None, None, None).await?; + assert_eq!(balance(id).await?, 0, "5,000 past the allowance: the 100 pack credits go, the rest is forgiven"); + // Upgrading and buying a pack gives the whole pack. + db::query!("UPDATE organizations SET plan = 'team' WHERE id = {id}").update().await?; + app::domain::credits::add_purchased_credits(id, 500_000, "packs: cs_new").await?; + assert_eq!(balance(id).await?, 500_000); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn an_automatic_pack_lets_a_build_that_ran_out_go_on(app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 1).await?; + let _stripe = stripe(true); + let build = processing_build(&app, org).await?; + let build = app::domain::processing::stop_if_out_of_credits(build).await?; + assert_eq!(build.state, "processing", "the pack was bought before the build was stopped"); + assert_eq!(balance(org).await?, 500_000); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn stripe_failing_never_fails_more_than_the_credits_do(app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 1).await?; + let stripe = client::fake() + .with("api.stripe.com/*", client::response().status(500).json(json!({ "error": { "message": "down" } }))); + CreditsSpent { organization_id: org }.dispatch().await?; + let tried = stripe.sent().len(); + assert!(tried > 0, "the reload tried Stripe"); + let build = processing_build(&app, org).await?; + let build = app::domain::processing::stop_if_out_of_credits(build).await?; + assert_eq!(build.state, "failed", "out of credits, as without automatic packs"); + assert_eq!(build.error_code.as_deref(), Some("out_of_credits")); + // The claim stays until it's stale (five minutes): a charge whose outcome is unknown isn't tried again meanwhile. + let released: Option = + db::query!("SELECT reload_started_at IS NULL FROM organizations WHERE id = {org}").scalar().await?; + assert_eq!(released, Some(false), "the reload's claim is kept after an error"); + assert_eq!(stripe.sent().len(), tried, "running out again doesn't call Stripe while the claim holds"); + Ok(()) +} + +#[laravel::test(app = with_stripe_key)] +async fn a_pay_call_cut_off_after_the_charge_credits_the_pack(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme", 1).await?; + let fake = client::fake().with("api.stripe.com/*", move |r: &client::Request| -> client::FakeResponse { + let path = r.url().split_once("/v1/").map_or("", |(_, p)| p).split('?').next().unwrap_or("").to_string(); + match path.as_str() { + "prices" | "billing_portal/configurations" if r.method() == "GET" => { + client::response().json(json!({ "data": [] })) + } + "subscriptions/sub_1" => { + client::response().json(json!({ "id": "sub_1", "default_payment_method": "pm_1" })) + } + "invoices" => client::response().json(json!({ "id": "in_1", "status": "draft" })), + "invoices/in_1/finalize" => client::response().json(json!({ "id": "in_1", "status": "open" })), + // Stripe charged the card, but the answer never arrived. + "invoices/in_1/pay" => client::response().status(504).json(json!({ "error": { "message": "timeout" } })), + "invoices/in_1" => client::response().json(json!({ "id": "in_1", "status": "paid" })), + _ => client::response().json(json!({ "id": format!("x_{}", path.replace('/', "_")) })), + } + }); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(balance(org).await?, 500_000, "the pack it paid for"); + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 0, "a paid invoice isn't voided"); + let paused: Option = + db::query!("SELECT reloads_paused_at IS NOT NULL FROM organizations WHERE id = {org}").scalar().await?; + assert_eq!(paused, Some(false), "a timeout isn't a declined card"); + Ok(()) +} diff --git a/app/tests/billing.rs b/app/tests/billing.rs index 5cac8161..6eddbe43 100644 --- a/app/tests/billing.rs +++ b/app/tests/billing.rs @@ -209,3 +209,42 @@ async fn a_paid_invoice_keeps_the_two_subscriptions_notice(app: Application) -> assert_eq!(problem, None); Ok(()) } + +#[laravel::test(app = stripe)] +async fn a_subscription_that_stops_paying_moves_to_free_and_paying_brings_team_back( + app: Application, +) -> laravel::Result<()> { + let org = org().await?; + let meta = json!({ "organization_id": org.to_string() }); + let event = |created: i64, status: &str| { + json!({ "type": "customer.subscription.updated", "created": created, "data": { "object": { + "id": "sub_1", "customer": "cus_1", "status": status, "metadata": meta } } }) + }; + let plan = || async { db::query!("SELECT plan FROM organizations WHERE id = {org}").scalar::().await }; + post(&app, event(100, "active")).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("team")); + // Stripe still retrying: Team stays, with a notice. + post(&app, event(200, "past_due")).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("team")); + // Retries over: Free, with the subscription kept so paying the invoice brings Team back. + post(&app, event(300, "unpaid")).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("free")); + let subscription = || async { + db::query!("SELECT stripe_subscription_id FROM organizations WHERE id = {org}").scalar::>().await + }; + assert_eq!( + subscription().await?.flatten().as_deref(), + Some("sub_1"), + "kept, so paying its invoice brings Team back" + ); + post(&app, event(400, "active")).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("team")); + for (created, status) in [(500, "canceled"), (600, "incomplete_expired")] { + post(&app, event(created - 50, "active")).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("team")); + post(&app, event(created, status)).await.assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("free"), "{status}"); + assert_eq!(subscription().await?.flatten(), None, "{status}: a new Checkout can start Team"); + } + Ok(()) +} diff --git a/app/tests/fingerprints.rs b/app/tests/fingerprints.rs index e13cac9d..17761410 100644 --- a/app/tests/fingerprints.rs +++ b/app/tests/fingerprints.rs @@ -612,8 +612,9 @@ async fn a_finished_render_wakes_only_the_processing_builds_that_wait_on_it(_app for blob in ["blob-invoice", "blob-other", "blob-receipt-2", "blob-home"] { app::domain::blobs::register(blob, 1, "application/pdf").await?; } - let render = app::domain::renders::find_or_queue(project.id, "fp-invoice", "pdfium/150/1", "blob-invoice").await?; - let other = app::domain::renders::find_or_queue(project.id, "fp-other", "pdfium/150/1", "blob-other").await?; + let render = + app::domain::renders::find_or_queue(project.id, "fp-invoice", "pdfium/150/1", "blob-invoice", None).await?; + let other = app::domain::renders::find_or_queue(project.id, "fp-other", "pdfium/150/1", "blob-other", None).await?; let mut number = 0; let mut build = async |state: &str| -> laravel::Result { number += 1; diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json index 9f990d26..baeaabf0 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -70,7 +70,7 @@ }, "slug": "", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json index ca990893..0a6e0894 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -52,7 +52,7 @@ }, "slug": "", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/list_organizations.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/list_organizations.json index 4aa54217..d59f8904 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/list_organizations.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/list_organizations.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\"],\"role\":\"project\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", + "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\"],\"role\":\"project\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", "type": "text" } ], @@ -18,7 +18,7 @@ "role": "project", "slug": "", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json index 7e9b5af2..4c57361d 100644 --- a/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json +++ b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\",\"shots\"],\"role\":\"admin\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", + "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\",\"shots\"],\"role\":\"admin\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", "type": "text" } ], @@ -19,7 +19,7 @@ "role": "admin", "slug": "", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json index b0959df4..89e27610 100644 --- a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json +++ b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", "type": "text" } ], @@ -104,7 +104,7 @@ }, "slug": "", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_org.json b/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_org.json index 4c7cb5c5..456a7a07 100644 --- a/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_org.json +++ b/app/tests/golden/mcp_admin/staff_read_and_write_with_a_reason_and_every_call_is_audited/get_org.json @@ -5,14 +5,14 @@ "result": { "content": [ { - "text": "{\"billing\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credits_balance\":0,\"reloads_paused_at\":null,\"stripe_customer_id\":null,\"stripe_subscription_id\":null},\"created_at\":\"\",\"members\":[{\"person\":{\"untrusted_customer_data\":{\"email\":\"ada@acme.test\",\"identities\":[{\"forge\":\"github\",\"login\":\"ada-gh\"}],\"name\":\"Ada\"}},\"role\":\"admin\",\"source\":\"created\",\"synced_at\":null}],\"name\":{\"untrusted_customer_data\":\"Acme Ltd\"},\"plan\":\"free\",\"projects\":[{\"deleted_at\":null,\"forge\":null,\"forge_app_installed\":false,\"latest_build\":{\"branch\":\"fix\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"default\",\"number\":2,\"state\":\"failed\"},\"project\":\"acme/invoices\",\"repository_url\":null}],\"slug\":\"acme\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}", + "text": "{\"billing\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credits_balance\":0,\"reloads_paused_at\":null,\"stripe_customer_id\":null,\"stripe_subscription_id\":null},\"created_at\":\"\",\"members\":[{\"person\":{\"untrusted_customer_data\":{\"email\":\"ada@acme.test\",\"identities\":[{\"forge\":\"github\",\"login\":\"ada-gh\"}],\"name\":\"Ada\"}},\"role\":\"admin\",\"source\":\"created\",\"synced_at\":null}],\"name\":{\"untrusted_customer_data\":\"Acme Ltd\"},\"plan\":\"free\",\"projects\":[{\"deleted_at\":null,\"forge\":null,\"forge_app_installed\":false,\"latest_build\":{\"branch\":\"fix\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"default\",\"number\":2,\"state\":\"failed\"},\"project\":\"acme/invoices\",\"repository_url\":null}],\"slug\":\"acme\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}", "type": "text" } ], "isError": false, "structuredContent": { "billing": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credits_balance": 0, "reloads_paused_at": null, @@ -62,7 +62,7 @@ ], "slug": "acme", "usage": { - "auto_reload_packs": 4, + "auto_reload_packs": 0, "billing_problem": null, "credit_pack": { "credits": 500000, diff --git a/app/tests/processing.rs b/app/tests/processing.rs index 3109e873..37bba405 100644 --- a/app/tests/processing.rs +++ b/app/tests/processing.rs @@ -203,6 +203,92 @@ async fn an_organization_out_of_credits_gets_a_failed_build_that_says_why(app: A Ok(()) } +/// What a build was charged for: its charges' references, in order. +async fn charged_for(token_org: i64, number: i32) -> laravel::Result> { + let rows = db::query!( + "SELECT t.reference FROM credit_transactions t JOIN builds b ON b.id = t.build_id \ + JOIN projects p ON p.id = b.project_id WHERE p.organization_id = {token_org} AND b.number = {number} ORDER BY t.id" + ) + .select() + .await?; + Ok(rows.iter().map(|r| r.try_get::>("reference").unwrap().unwrap_or_default()).collect()) +} + +#[laravel::test] +async fn a_build_pays_for_the_image_diffs_it_makes_and_another_project_reusing_one_does_not( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let mut orgs = Vec::new(); + for _ in 0..2 { + let token = project_token().await?; + run(&app, &token, "c1", "c0", &[("home/desktop.png", [255, 0, 0])]).await; + run(&app, &token, "c2", "c1", &[("home/desktop.png", [0, 0, 255])]).await; + let org: i64 = db::query!( + "SELECT p.organization_id FROM project_tokens t JOIN projects p ON p.id = t.project_id \ + ORDER BY t.id DESC LIMIT 1" + ) + .scalar() + .await? + .unwrap(); + orgs.push(org); + } + let first = charged_for(orgs[0], 2).await?.join("; "); + assert!(first.contains("1 image diff"), "the build that made the diff pays for it: {first}"); + let second = charged_for(orgs[1], 2).await?.join("; "); + assert!( + second.contains("snapshot checked") && !second.contains("image diff"), + "the same two images again: {second}" + ); + Ok(()) +} + +fn refs(v: &[(String, [u8; 3])]) -> Vec<(&str, [u8; 3])> { + v.iter().map(|(n, c)| (n.as_str(), *c)).collect() +} + +#[laravel::test] +async fn a_build_that_runs_out_part_way_stops_between_batches_and_free_owes_nothing( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let org: i64 = db::query!("SELECT organization_id FROM projects LIMIT 1").scalar().await?.unwrap(); + let shots = |blue: u8| -> Vec<(String, [u8; 3])> { + (0..205u32) + .map(|i| (format!("page-{i:03}/desktop.png"), [(i % 250) as u8, (i / 250 * 40) as u8, blue])) + .collect() + }; + let base = shots(0); + run(&app, &token, "c1", "c0", &refs(&base)).await; + // Enough for the next build's checks and about 50 image diffs, not for 205. + let used: i64 = + db::query!("SELECT COALESCE(-SUM(amount), 0)::BIGINT FROM credit_transactions WHERE organization_id = {org}") + .scalar() + .await? + .unwrap_or(0); + let spend = -(25_000 - used - (205 + 10 + 50 * 10)); + db::query!("INSERT INTO credit_transactions (organization_id, amount, balance_after, kind) VALUES ({org}, {spend}, 0, 'build')") + .insert() + .await?; + let head = shots(200); + let done = run(&app, &token, "c2", "c1", &refs(&head)).await; + assert_eq!(done["state"], "failed", "{done}"); + assert!(done["error"].as_str().unwrap_or_default().contains("has used this month's"), "{done}"); + let two = build_number(2).await?; + let id = two.id; + let changed: i64 = db::query!("SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND state = 'changed'") + .scalar() + .await? + .unwrap_or(0); + let checked_at = i64::try_from(app::domain::processing::CREDIT_CHECK_EVERY).unwrap() - 1; + assert_eq!(changed, checked_at, "it stops at the first credit check, having compared {changed} of 205"); + let balance: i64 = + db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar().await?.unwrap_or(0); + assert_eq!(balance, 0, "Free owes nothing for the overrun"); + Ok(()) +} + #[laravel::test] async fn a_build_whose_manifest_matches_writes_no_snapshots_and_is_charged_one_group_check( app: Application, diff --git a/app/tests/renderer.rs b/app/tests/renderer.rs index df7d1883..4a34b640 100644 --- a/app/tests/renderer.rs +++ b/app/tests/renderer.rs @@ -75,6 +75,12 @@ async fn every_renderer_route_needs_its_token_whatever_the_host(app: Application /// A build on main with one PDF, waiting for its render. Returns the build's id. async fn waiting_build(app: &Application, token: &str, commit: &str) -> String { + waiting_build_of(app, token, commit, None).await +} + +/// A build waiting on its PDF's render; `pdf` names the PDF's text (two builds sending the same one share its render), +/// else it's the build's own. +async fn waiting_build_of(app: &Application, token: &str, commit: &str, pdf: Option<&str>) -> String { let auth = format!("Bearer {token}"); let build = app .post("/api/v1/builds") @@ -84,7 +90,7 @@ async fn waiting_build(app: &Application, token: &str, commit: &str) -> String { .json() .clone(); let id = build["id"].as_str().unwrap().to_string(); - let pdf = format!("%PDF-1.4 renderer test {id}").into_bytes(); + let pdf = format!("%PDF-1.4 renderer test {}", pdf.unwrap_or(&id)).into_bytes(); let sha = visualci_core::sha256_hex(&pdf); let registered = app .post(format!("/api/v1/builds/{id}/snapshots")) @@ -96,7 +102,10 @@ async fn waiting_build(app: &Application, token: &str, commit: &str) -> String { .await .json() .clone(); - put(registered["snapshots"][0]["upload_url"].as_str().unwrap(), pdf, "application/pdf").await; + // A PDF another build already sent needs no upload. + if let Some(url) = registered["snapshots"][0]["upload_url"].as_str() { + put(url, pdf, "application/pdf").await; + } let waiting = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await.json().clone(); assert_eq!(waiting["state"], "processing", "waiting for its render"); id @@ -198,6 +207,78 @@ async fn claimed_drawn_completed(app: Application) -> laravel::Result<()> { Ok(()) } +#[laravel::test] +async fn the_build_that_queued_a_render_pays_for_its_pages_once_even_when_another_build_shares_it( + app: Application, +) -> laravel::Result<()> { + Box::pin(pays_for_pages_once(app)).await +} + +async fn pays_for_pages_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + // Two builds of one project send the same PDF before it's drawn: one render, waited on by both. + waiting_build_of(&app, &token, "c1", Some("shared")).await; + waiting_build_of(&app, &token, "c2", Some("shared")).await; + let (render_id, claim) = claim(&app).await; + let pages = [png(), png_of([200, 20, 30, 255])]; + let shas: Vec = pages.iter().map(|p| visualci_core::sha256_hex(p)).collect(); + let urls = uploads(&app, render_id, &claim, &[&pages[0], &pages[1]]).await; + for (sha, bytes) in shas.iter().zip(pages.iter()) { + put(urls[sha].as_str().unwrap(), bytes.clone(), "image/png").await; + } + complete(&app, render_id, &claim, json!([page(&pages[0], "One"), page(&pages[1], "Two")])).await.assert_ok(); + let mut drawn = Vec::new(); + for number in [1, 2] { + let build = Build::query().filter(Build::number.eq(number)).first().await?.unwrap(); + assert_eq!(build.state, "completed", "build {number}"); + let id = build.id; + let references: Vec = db::query!("SELECT reference FROM credit_transactions WHERE build_id = {id}") + .select() + .await? + .iter() + .map(|r| r.try_get::>("reference").unwrap().unwrap_or_default()) + .collect(); + drawn.push(references.join("; ")); + } + assert!(drawn[0].contains("2 pages drawn"), "the build that queued the render pays for its pages: {}", drawn[0]); + assert!(!drawn[1].contains("drawn"), "the build sharing it doesn't pay again: {}", drawn[1]); + Ok(()) +} + +/// A render that failed (its build ran out of credits and stopped) and that a later build queues again is paid for by +/// the later build: the first was charged when it stopped, without the pages. +#[laravel::test] +async fn a_render_queued_again_by_another_build_is_paid_for_by_that_build(app: Application) -> laravel::Result<()> { + Box::pin(queued_again(app)).await +} + +async fn queued_again(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + waiting_build_of(&app, &token, "c1", Some("retried")).await; + db::query!("UPDATE renders SET state = 'failed', error = 'its build ran out of credits'").update().await?; + db::query!("UPDATE builds SET state = 'failed' WHERE number = 1").update().await?; + waiting_build_of(&app, &token, "c2", Some("retried")).await; + let (render_id, claim) = claim(&app).await; + let pages = [png()]; + let sha = visualci_core::sha256_hex(&pages[0]); + let urls = uploads(&app, render_id, &claim, &[&pages[0]]).await; + put(urls[&sha].as_str().unwrap(), pages[0].clone(), "image/png").await; + complete(&app, render_id, &claim, json!([page(&pages[0], "One")])).await.assert_ok(); + let build = Build::query().filter(Build::number.eq(2)).first().await?.unwrap(); + assert_eq!(build.state, "completed"); + let id = build.id; + let references: Vec = db::query!("SELECT reference FROM credit_transactions WHERE build_id = {id}") + .select() + .await? + .iter() + .map(|r| r.try_get::>("reference").unwrap().unwrap_or_default()) + .collect(); + assert!(references.join("; ").contains("1 page drawn"), "the build that queued it again pays: {references:?}"); + Ok(()) +} + /// A render whose claims all expired would stay `rendering` forever: the next claim fails it, and its build goes on. #[laravel::test] async fn a_render_out_of_attempts_fails_and_its_build_finishes(app: Application) -> laravel::Result<()> { diff --git a/docs/design.md b/docs/design.md index 2d4ceae9..2fcb662a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -695,6 +695,17 @@ DocSpring's own ops agents (triage, support) work on customers' issues through a it's newer than the last one applied (`organizations.stripe_event_at`) and about its own subscription; a second Team subscription (two checkout tabs) becomes a billing problem, not the plan. A purchase's credits are added once per reference (a unique index), even when a reload and its `invoice.paid` race. +- Running low and out (`app/src/billing/listeners.rs`, `reload.rs`; sc-9146). Billing listens to the domain's credit + events: after a build spends (`CreditsSpent`), the 80% and 95% emails (once each a month) and an automatic pack if + the credits left are under the line; before a build is stopped (`CreditsRanOut`), an automatic pack; after + (`BuildStoppedForCredits`), the out-of-credits email (once a month, with a link that starts a pack's Checkout). + Automatic packs are off until an admin turns them on and picks a monthly limit: nothing is charged without that + choice. A reload is claimed on the organization's row (`reload_started_at`), so two builds buy one pack. A build + that runs out part-way stops between batches of snapshots (`processing::CREDIT_CHECK_EVERY`) or render waits, + having charged what it did. On Free, what a build uses past the allowance is forgiven (never a negative balance + taken out of a later pack); on Team the next pack pays it. A subscription Stripe gives up on (`unpaid`, + `incomplete_expired`, `canceled`) moves the organization to Free; `unpaid` keeps the subscription, so paying the + invoice brings Team back. - Credit overrides (`app/src/domain/credit_overrides.rs`): staff raise an organization's monthly credits until a date, such as a big open source project that needs more than the 1,000,000 open source pool. The override replaces the plan's monthly allowance (never lowering it) and nothing else: the open source pool still comes first and pack diff --git a/frontend/content/docs/reference/credits.md b/frontend/content/docs/reference/credits.md index 043f2d46..2594b577 100644 --- a/frontend/content/docs/reference/credits.md +++ b/frontend/content/docs/reference/credits.md @@ -63,8 +63,10 @@ the organization's admins get an email a week before. After that date it's back On Team, a pack is 500,000 credits for $15, paid up front. Pack credits don't expire. Builds use the month's allowance first, then pack credits. - **Buy packs** on the organization's billing page, 1 to 20 at a time. -- **Automatic reloads** buy a pack with the default card (the billing page's Payment methods tab) when fewer than 100,000 credits are left. Each organization sets how many packs reloads may buy in a month: 4 by default, 0 to 50. +- **Automatic reloads** are off until an admin turns them on. Then they buy a pack with the default card (the billing page's Payment methods tab) when fewer than 100,000 credits are left, up to the number of packs a month the admin chose (1 to 50). A declined card pauses them until the card is updated and the limit saved again. -An organization that has used its allowance and has no pack credits gets a failed build that says so, instead of a comparison. A build that runs out part-way (a large build's PDF pages) stops there the same way: what it already did is charged, and the rest isn't done. +An organization that has used its allowance and has no pack credits gets a failed build that says so, instead of a comparison, and its billing contact gets an email once a month with a link to buy a pack (or, on Free, to upgrade). A build that runs out part-way stops there the same way, between batches of snapshots or PDF pages: what it already did is charged, and the rest isn't done. On Free, what a build used past the allowance is never owed. On Team, the next pack pays for it. + +The billing contact also gets an email when 80% and 95% of the month's credits are used, once each a month (Account > Notifications turns these off). `get_organization` over MCP shows the plan, the credits used this month, pack credits and what each thing costs. Choosing a plan and paying stay with a person, in the web app. diff --git a/frontend/src/pages/BillingPage.tsx b/frontend/src/pages/BillingPage.tsx index 82154a4f..a68d9264 100644 --- a/frontend/src/pages/BillingPage.tsx +++ b/frontend/src/pages/BillingPage.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Link, useParams } from '@tanstack/react-router' import { useAddPaymentMethod, @@ -188,7 +188,18 @@ export function BillingPage({ tab }: { tab: BillingTab }) { Manage )} - {!current && p.id !== 'free' && ( + {!current && p.id !== 'free' && o.subscribed && ( + + )} + {!current && p.id !== 'free' && !o.subscribed && (