diff --git a/app/tests/all.rs b/app/tests/all.rs index cf6cf88e..ac51c72b 100644 --- a/app/tests/all.rs +++ b/app/tests/all.rs @@ -23,6 +23,7 @@ mod auth; mod automatic_packs; mod baselines; mod billing; +mod billing_branches; mod branches; mod credit_overrides; mod credits; diff --git a/app/tests/billing_branches.rs b/app/tests/billing_branches.rs new file mode 100644 index 00000000..4b39b360 --- /dev/null +++ b/app/tests/billing_branches.rs @@ -0,0 +1,179 @@ +//! Billing branches the #199 review found untested: a reload whose pay call is cut off and Stripe then says the invoice +//! is still open (declined) or can't say (left alone, the claim kept); the unpaid subscription's notice; and Checkout +//! refusing a second subscription while one is unpaid. + +use app::events::CreditsRanOut; +use app::models::User; +use app::testing::fixtures; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::TestResponse; +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_STRIPE_WEBHOOK_SECRET", "whsec_test"), + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ]) + .create() +} + +/// A Team organization out of credits, with automatic packs on. +async fn team_out_of_credits(slug: &str) -> 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 = 2 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 for a reload whose pay call times out, and whose invoice then reads as `after` (an HTTP 500 when `None`). +fn pay_cut_off(after: Option<&'static str>) -> 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" => client::response().status(504).json(json!({ "error": { "message": "timeout" } })), + "invoices/in_1" if r.method() == "GET" => match after { + Some(status) => client::response().json(json!({ "id": "in_1", "status": status })), + None => client::response().status(500).json(json!({ "error": { "message": "down" } })), + }, + _ => client::response().json(json!({ "id": format!("x_{}", path.replace('/', "_")) })), + } + }) +} + +async fn org_row(org: i64) -> laravel::Result<(i64, bool, bool, Option)> { + let row = db::query!( + "SELECT credits_balance, reloads_paused_at IS NOT NULL AS paused, reload_started_at IS NOT NULL AS claimed, \ + billing_problem FROM organizations WHERE id = {org}" + ) + .select_one() + .await? + .expect("the organization"); + Ok(( + row.try_get("credits_balance")?, + row.try_get("paused")?, + row.try_get("claimed")?, + row.try_get("billing_problem")?, + )) +} + +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() +} + +/// The pay call timed out and Stripe then says the invoice is still open: the card didn't pay, so it's declined: the +/// invoice is voided, reloads pause and the problem shows. +#[laravel::test(app = with_stripe_key)] +async fn a_cut_off_pay_call_whose_invoice_is_still_open_is_declined(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme").await?; + let fake = pay_cut_off(Some("open")); + CreditsRanOut { organization_id: org }.dispatch().await?; + let (balance, paused, claimed, problem) = org_row(org).await?; + assert_eq!(balance, 0); + assert!(paused, "a declined pack pauses reloads"); + assert!(!claimed, "the claim is released"); + assert!(problem.is_some_and(|p| p.contains("declined"))); + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 1); + Ok(()) +} + +/// The pay call timed out and Stripe can't be asked: the charge may have gone through, so nothing is voided or paused, +/// and the claim stays until it's stale, so a second build doesn't buy another pack meanwhile (its `invoice.paid` +/// webhook credits it if it went through). +#[laravel::test(app = with_stripe_key)] +async fn a_cut_off_pay_call_stripe_cant_confirm_is_left_alone(_app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme").await?; + let fake = pay_cut_off(None); + CreditsRanOut { organization_id: org }.dispatch().await?; + let (balance, paused, claimed, problem) = org_row(org).await?; + assert_eq!((balance, paused, problem), (0, false, None)); + assert!(claimed, "the claim is kept until it's stale"); + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 0); + let invoices = posts_to(&fake, "invoices"); + CreditsRanOut { organization_id: org }.dispatch().await?; + assert_eq!(posts_to(&fake, "invoices"), invoices, "no second pack while the claim holds"); + Ok(()) +} + +async fn post_event(app: &Application, event: serde_json::Value) -> TestResponse { + use hmac::{Hmac, Mac}; + let body = event.to_string(); + let t = laravel::now().timestamp().as_second(); + let mut mac = Hmac::::new_from_slice(b"whsec_test").unwrap(); + mac.update(format!("{t}.{body}").as_bytes()); + let signature = format!("t={t},v1={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/stripe") + .header("stripe-signature", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// A subscription whose retries are over moves to Free and says why, with what to do to go back to Team. +#[laravel::test(app = with_stripe_key)] +async fn an_unpaid_subscription_says_so(app: Application) -> laravel::Result<()> { + let org = team_out_of_credits("acme").await?; + post_event( + &app, + json!({ "type": "customer.subscription.updated", "created": 100, "livemode": false, "data": { "object": { + "id": "sub_1", "customer": "cus_1", "status": "unpaid", "metadata": { "organization_id": org.to_string() } } } }), + ) + .await + .assert_ok(); + let (_, paused, _, problem) = org_row(org).await?; + let problem = problem.unwrap_or_default(); + assert!(problem.contains("on Free") && problem.contains("Pay the open invoice"), "{problem}"); + assert!(paused, "no automatic packs on an unpaid subscription"); + Ok(()) +} + +/// While its subscription is unpaid (on Free, the subscription kept), Checkout refuses a second one and points at the +/// open invoice. +#[laravel::test(app = with_stripe_key)] +async fn checkout_refuses_a_second_subscription_while_one_is_unpaid(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let id = org.id; + db::query!( + "UPDATE organizations SET plan = 'free', stripe_customer_id = 'cus_1', stripe_subscription_id = 'sub_1' \ + WHERE id = {id}" + ) + .update() + .await?; + let admin = + create!(User { pid: laravel::str::uuid7(), name: "Admin", email: "admin@example.com", staff: false }).await?; + fixtures::member(&org, &admin, "admin").await?; + let stripe = + client::fake().with("api.stripe.com/*", json!({ "id": "cs_1", "url": "https://checkout.stripe.test" })); + let refused = app + .post("/api/ui/orgs/acme/billing/checkout") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "plan": "team" })) + .await; + refused.assert_status(400); + assert!(refused.text().contains("unpaid invoice"), "{}", refused.text()); + assert!(stripe.sent().is_empty(), "no Checkout session"); + Ok(()) +}