|
| 1 | +//! Billing branches the #199 review found untested: a reload whose pay call is cut off and Stripe then says the invoice |
| 2 | +//! is still open (declined) or can't say (left alone, the claim kept); the unpaid subscription's notice; and Checkout |
| 3 | +//! refusing a second subscription while one is unpaid. |
| 4 | +
|
| 5 | +use app::events::CreditsRanOut; |
| 6 | +use app::models::User; |
| 7 | +use app::testing::fixtures; |
| 8 | +use laravel::db; |
| 9 | +use laravel::http::client; |
| 10 | +use laravel::model::create; |
| 11 | +use laravel::testing::TestResponse; |
| 12 | +use laravel::testing::prelude::*; |
| 13 | +use serde_json::json; |
| 14 | + |
| 15 | +fn with_stripe_key() -> Application { |
| 16 | + app::testing::configure() |
| 17 | + .with_envs([ |
| 18 | + ("VISUALCI_STRIPE_SECRET_KEY", "sk_test_x"), |
| 19 | + ("VISUALCI_STRIPE_WEBHOOK_SECRET", "whsec_test"), |
| 20 | + ("VISUALCI_APP_URL", "https://app.visualci.test"), |
| 21 | + ]) |
| 22 | + .create() |
| 23 | +} |
| 24 | + |
| 25 | +/// A Team organization out of credits, with automatic packs on. |
| 26 | +async fn team_out_of_credits(slug: &str) -> laravel::Result<i64> { |
| 27 | + let org = fixtures::organization(slug).await?; |
| 28 | + let id = org.id; |
| 29 | + db::query!( |
| 30 | + "UPDATE organizations SET plan = 'team', stripe_customer_id = 'cus_1', stripe_subscription_id = 'sub_1', \ |
| 31 | + billing_email = 'billing@example.com', auto_reload_packs = 2 WHERE id = {id}" |
| 32 | + ) |
| 33 | + .update() |
| 34 | + .await?; |
| 35 | + db::query!( |
| 36 | + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind) VALUES ({id}, -1000000, 0, 'build')" |
| 37 | + ) |
| 38 | + .insert() |
| 39 | + .await?; |
| 40 | + Ok(id) |
| 41 | +} |
| 42 | + |
| 43 | +/// Stripe for a reload whose pay call times out, and whose invoice then reads as `after` (an HTTP 500 when `None`). |
| 44 | +fn pay_cut_off(after: Option<&'static str>) -> client::HttpFake { |
| 45 | + client::fake().with("api.stripe.com/*", move |r: &client::Request| -> client::FakeResponse { |
| 46 | + let path = r.url().split_once("/v1/").map_or("", |(_, p)| p).split('?').next().unwrap_or("").to_string(); |
| 47 | + match path.as_str() { |
| 48 | + "prices" | "billing_portal/configurations" if r.method() == "GET" => { |
| 49 | + client::response().json(json!({ "data": [] })) |
| 50 | + } |
| 51 | + "subscriptions/sub_1" => { |
| 52 | + client::response().json(json!({ "id": "sub_1", "default_payment_method": "pm_1" })) |
| 53 | + } |
| 54 | + "invoices" => client::response().json(json!({ "id": "in_1", "status": "draft" })), |
| 55 | + "invoices/in_1/finalize" => client::response().json(json!({ "id": "in_1", "status": "open" })), |
| 56 | + "invoices/in_1/pay" => client::response().status(504).json(json!({ "error": { "message": "timeout" } })), |
| 57 | + "invoices/in_1" if r.method() == "GET" => match after { |
| 58 | + Some(status) => client::response().json(json!({ "id": "in_1", "status": status })), |
| 59 | + None => client::response().status(500).json(json!({ "error": { "message": "down" } })), |
| 60 | + }, |
| 61 | + _ => client::response().json(json!({ "id": format!("x_{}", path.replace('/', "_")) })), |
| 62 | + } |
| 63 | + }) |
| 64 | +} |
| 65 | + |
| 66 | +async fn org_row(org: i64) -> laravel::Result<(i64, bool, bool, Option<String>)> { |
| 67 | + let row = db::query!( |
| 68 | + "SELECT credits_balance, reloads_paused_at IS NOT NULL AS paused, reload_started_at IS NOT NULL AS claimed, \ |
| 69 | + billing_problem FROM organizations WHERE id = {org}" |
| 70 | + ) |
| 71 | + .select_one() |
| 72 | + .await? |
| 73 | + .expect("the organization"); |
| 74 | + Ok(( |
| 75 | + row.try_get("credits_balance")?, |
| 76 | + row.try_get("paused")?, |
| 77 | + row.try_get("claimed")?, |
| 78 | + row.try_get("billing_problem")?, |
| 79 | + )) |
| 80 | +} |
| 81 | + |
| 82 | +fn posts_to(fake: &client::HttpFake, path: &str) -> usize { |
| 83 | + fake.sent().iter().filter(|r| r.method() == "POST" && r.url().ends_with(&format!("/v1/{path}"))).count() |
| 84 | +} |
| 85 | + |
| 86 | +/// The pay call timed out and Stripe then says the invoice is still open: the card didn't pay, so it's declined: the |
| 87 | +/// invoice is voided, reloads pause and the problem shows. |
| 88 | +#[laravel::test(app = with_stripe_key)] |
| 89 | +async fn a_cut_off_pay_call_whose_invoice_is_still_open_is_declined(_app: Application) -> laravel::Result<()> { |
| 90 | + let org = team_out_of_credits("acme").await?; |
| 91 | + let fake = pay_cut_off(Some("open")); |
| 92 | + CreditsRanOut { organization_id: org }.dispatch().await?; |
| 93 | + let (balance, paused, claimed, problem) = org_row(org).await?; |
| 94 | + assert_eq!(balance, 0); |
| 95 | + assert!(paused, "a declined pack pauses reloads"); |
| 96 | + assert!(!claimed, "the claim is released"); |
| 97 | + assert!(problem.is_some_and(|p| p.contains("declined"))); |
| 98 | + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 1); |
| 99 | + Ok(()) |
| 100 | +} |
| 101 | + |
| 102 | +/// The pay call timed out and Stripe can't be asked: the charge may have gone through, so nothing is voided or paused, |
| 103 | +/// and the claim stays until it's stale, so a second build doesn't buy another pack meanwhile (its `invoice.paid` |
| 104 | +/// webhook credits it if it went through). |
| 105 | +#[laravel::test(app = with_stripe_key)] |
| 106 | +async fn a_cut_off_pay_call_stripe_cant_confirm_is_left_alone(_app: Application) -> laravel::Result<()> { |
| 107 | + let org = team_out_of_credits("acme").await?; |
| 108 | + let fake = pay_cut_off(None); |
| 109 | + CreditsRanOut { organization_id: org }.dispatch().await?; |
| 110 | + let (balance, paused, claimed, problem) = org_row(org).await?; |
| 111 | + assert_eq!((balance, paused, problem), (0, false, None)); |
| 112 | + assert!(claimed, "the claim is kept until it's stale"); |
| 113 | + assert_eq!(posts_to(&fake, "invoices/in_1/void"), 0); |
| 114 | + let invoices = posts_to(&fake, "invoices"); |
| 115 | + CreditsRanOut { organization_id: org }.dispatch().await?; |
| 116 | + assert_eq!(posts_to(&fake, "invoices"), invoices, "no second pack while the claim holds"); |
| 117 | + Ok(()) |
| 118 | +} |
| 119 | + |
| 120 | +async fn post_event(app: &Application, event: serde_json::Value) -> TestResponse { |
| 121 | + use hmac::{Hmac, Mac}; |
| 122 | + let body = event.to_string(); |
| 123 | + let t = laravel::now().timestamp().as_second(); |
| 124 | + let mut mac = Hmac::<sha2::Sha256>::new_from_slice(b"whsec_test").unwrap(); |
| 125 | + mac.update(format!("{t}.{body}").as_bytes()); |
| 126 | + let signature = format!("t={t},v1={}", hex::encode(mac.finalize().into_bytes())); |
| 127 | + app.post("/webhooks/stripe") |
| 128 | + .header("stripe-signature", signature) |
| 129 | + .header("content-type", "application/json") |
| 130 | + .body(body) |
| 131 | + .await |
| 132 | +} |
| 133 | + |
| 134 | +/// A subscription whose retries are over moves to Free and says why, with what to do to go back to Team. |
| 135 | +#[laravel::test(app = with_stripe_key)] |
| 136 | +async fn an_unpaid_subscription_says_so(app: Application) -> laravel::Result<()> { |
| 137 | + let org = team_out_of_credits("acme").await?; |
| 138 | + post_event( |
| 139 | + &app, |
| 140 | + json!({ "type": "customer.subscription.updated", "created": 100, "livemode": false, "data": { "object": { |
| 141 | + "id": "sub_1", "customer": "cus_1", "status": "unpaid", "metadata": { "organization_id": org.to_string() } } } }), |
| 142 | + ) |
| 143 | + .await |
| 144 | + .assert_ok(); |
| 145 | + let (_, paused, _, problem) = org_row(org).await?; |
| 146 | + let problem = problem.unwrap_or_default(); |
| 147 | + assert!(problem.contains("on Free") && problem.contains("Pay the open invoice"), "{problem}"); |
| 148 | + assert!(paused, "no automatic packs on an unpaid subscription"); |
| 149 | + Ok(()) |
| 150 | +} |
| 151 | + |
| 152 | +/// While its subscription is unpaid (on Free, the subscription kept), Checkout refuses a second one and points at the |
| 153 | +/// open invoice. |
| 154 | +#[laravel::test(app = with_stripe_key)] |
| 155 | +async fn checkout_refuses_a_second_subscription_while_one_is_unpaid(app: Application) -> laravel::Result<()> { |
| 156 | + let org = fixtures::organization("acme").await?; |
| 157 | + let id = org.id; |
| 158 | + db::query!( |
| 159 | + "UPDATE organizations SET plan = 'free', stripe_customer_id = 'cus_1', stripe_subscription_id = 'sub_1' \ |
| 160 | + WHERE id = {id}" |
| 161 | + ) |
| 162 | + .update() |
| 163 | + .await?; |
| 164 | + let admin = |
| 165 | + create!(User { pid: laravel::str::uuid7(), name: "Admin", email: "admin@example.com", staff: false }).await?; |
| 166 | + fixtures::member(&org, &admin, "admin").await?; |
| 167 | + let stripe = |
| 168 | + client::fake().with("api.stripe.com/*", json!({ "id": "cs_1", "url": "https://checkout.stripe.test" })); |
| 169 | + let refused = app |
| 170 | + .post("/api/ui/orgs/acme/billing/checkout") |
| 171 | + .acting_as(&admin) |
| 172 | + .header("sec-fetch-site", "same-origin") |
| 173 | + .json(json!({ "plan": "team" })) |
| 174 | + .await; |
| 175 | + refused.assert_status(400); |
| 176 | + assert!(refused.text().contains("unpaid invoice"), "{}", refused.text()); |
| 177 | + assert!(stripe.sent().is_empty(), "no Checkout session"); |
| 178 | + Ok(()) |
| 179 | +} |
0 commit comments