diff --git a/app/database/migrations/2026_12_09_000000_credit_reversals.rs b/app/database/migrations/2026_12_09_000000_credit_reversals.rs new file mode 100644 index 00000000..46261a34 --- /dev/null +++ b/app/database/migrations/2026_12_09_000000_credit_reversals.rs @@ -0,0 +1,24 @@ +//! What a refunded or disputed charge has settled (sc-9146): the share of its purchase's credits refunded so far, and +//! whether a dispute is open. Each event moves these and takes back only the difference, so a retry takes nothing, +//! and credits that were already spent when a refund came are forgiven once rather than taken from a later pack. + +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'; +CREATE TABLE credit_reversals ( + charge_id TEXT PRIMARY KEY, + organization_id BIGINT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE, + purchase_reference TEXT NOT NULL, + refunded_credits BIGINT NOT NULL DEFAULT 0, + disputed BOOLEAN NOT NULL DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX credit_reversals_org ON credit_reversals (organization_id); +"; diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs index eec523b5..ed627100 100644 --- a/app/src/billing/mod.rs +++ b/app/src/billing/mod.rs @@ -18,6 +18,7 @@ pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: pub mod listeners; pub mod reload; +pub mod reversals; pub mod routes; pub mod stripe; pub mod webhook; diff --git a/app/src/billing/reload.rs b/app/src/billing/reload.rs index 4ec56b25..b56c3fa6 100644 --- a/app/src/billing/reload.rs +++ b/app/src/billing/reload.rs @@ -37,6 +37,19 @@ pub enum Reload { /// /// # Errors /// On a database error, or when Stripe can't be reached. +/// Whether an automatic pack could still be bought for `org` this month: Team with a Stripe customer, packs on and +/// not paused, and the month's limit not reached. Says nothing of whether one is needed. +/// +/// # Errors +/// On a database error. +pub async fn may_reload(org: &Organization) -> laravel::Result { + Ok(plan_by_id(&org.plan).credit_packs + && org.stripe_customer_id.is_some() + && org.reloads_paused_at.is_none() + && org.auto_reload_packs > 0 + && credits::reloads_this_month(org.id).await? < i64::from(org.auto_reload_packs)) +} + 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() { @@ -185,12 +198,7 @@ async fn charge_pack(key: &str, org: &Organization, idempotency: &str) -> larave 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?; + super::webhook::record_payment_problem(org.id, super::webhook::AUTO_PACK_DECLINED).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 { diff --git a/app/src/billing/reversals.rs b/app/src/billing/reversals.rs new file mode 100644 index 00000000..d610d26f --- /dev/null +++ b/app/src/billing/reversals.rs @@ -0,0 +1,178 @@ +//! Refunds and disputes take back the credits the payment bought (terms.md: "If a payment is refunded or disputed, +//! the credits it bought are removed"; sc-9146). +//! +//! A charge is traced to its purchase through Stripe: a pack bought through Checkout by its session (`packs: cs_…`), an +//! automatic pack by its invoice (`auto-reload: in_…`). Each charge's settled state (`credit_reversals`: the share +//! refunded so far, a dispute open) moves with each event, and only the difference is taken back (`refund: ch_…`, +//! `dispute: ch_…` in the ledger), so a retry takes nothing, a partial refund takes its share and a later refund or a +//! dispute the rest. A dispute the organization wins gives back what it took, once (`dispute won: ch_…`). Credits +//! already spent can't be taken back: the balance never goes below zero, and the forgiven part counts as settled, so +//! a pack bought later isn't charged for an old refund. + +use laravel::db; +use serde_json::{Value, json}; + +use super::stripe; + +/// What a charge's purchase was: its ledger reference and the credits it added. +pub struct Purchase { + pub reference: String, + pub credits: i64, +} + +/// The purchase a charge paid for, `None` when it bought no credits (a subscription invoice) or was never credited. +/// +/// # Errors +/// When Stripe can't be reached, or on a database error. +pub async fn purchase_of(key: &str, org_id: i64, charge: &Value) -> laravel::Result> { + let mut references = Vec::new(); + if let Some(intent) = charge["payment_intent"].as_str() { + let sessions = stripe::get(key, "checkout/sessions", &[("payment_intent", intent.to_string())]).await?; + if let Some(id) = sessions["data"][0]["id"].as_str() { + references.push(format!("packs: {id}")); + } + // Older API versions name the invoice on the charge; newer ones list it among the invoice's payments. + let invoice = match charge["invoice"].as_str() { + Some(id) => Some(id.to_string()), + None => { + let query = + [("payment[type]", "payment_intent".to_string()), ("payment[payment_intent]", intent.to_string())]; + let payments = stripe::get(key, "invoice_payments", &query).await?; + payments["data"][0]["invoice"].as_str().map(str::to_string) + } + }; + if let Some(id) = invoice { + references.push(format!("auto-reload: {id}")); + } + } + if references.is_empty() { + return Ok(None); + } + let references = json!(references); + let row = db::query!( + "SELECT reference, amount FROM credit_transactions WHERE organization_id = {org_id} AND kind = 'purchase' \ + AND reference IN (SELECT jsonb_array_elements_text({references}::jsonb)) ORDER BY id LIMIT 1" + ) + .select_one() + .await?; + let Some(row) = row else { return Ok(None) }; + Ok(Some(Purchase { reference: row.try_get("reference")?, credits: row.try_get("amount")? })) +} + +/// What happened to a charge, as one event says. +#[derive(Clone, Copy, Debug)] +pub enum Reversal { + /// Refunded so far: this many of its purchase's credits (Stripe sends the running total). + Refunded(i64), + /// A dispute opened: all its credits. + Disputed, + /// The organization won the dispute (or the inquiry closed without a chargeback): what the dispute took comes back. + DisputeWon, +} + +/// Apply `reversal` to charge `charge_id` of `purchase`: the charge's settled state moves (`credit_reversals`) and the +/// difference in credits owed is taken back or given back. What's taken back stops at the balance: credits already +/// spent are forgiven, and the forgiven part counts as settled, so a pack bought later keeps its credits. Returns the +/// change to the balance. +/// +/// # Errors +/// On a database error. +pub async fn apply(org_id: i64, charge_id: &str, purchase: &Purchase, reversal: Reversal) -> laravel::Result { + let (reference, credits) = (purchase.reference.as_str(), purchase.credits); + db::transaction(async |tx| { + let balance: Option = + db::query!(tx, "SELECT credits_balance FROM organizations WHERE id = {org_id} FOR UPDATE").scalar().await?; + let Some(balance) = balance else { return Ok(0) }; + db::query!( + tx, + "INSERT INTO credit_reversals (charge_id, organization_id, purchase_reference) \ + VALUES ({charge_id}, {org_id}, {reference}) ON CONFLICT (charge_id) DO NOTHING" + ) + .insert() + .await?; + let row = db::query!(tx, "SELECT refunded_credits, disputed FROM credit_reversals WHERE charge_id = {charge_id}") + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("the reversal row is gone"))?; + let (refunded, disputed): (i64, bool) = (row.try_get("refunded_credits")?, row.try_get("disputed")?); + let owed = |refunded: i64, disputed: bool| if disputed { credits } else { refunded.clamp(0, credits) }; + let (now_refunded, now_disputed) = match reversal { + Reversal::Refunded(share) => (refunded.max(share.clamp(0, credits)), disputed), + Reversal::Disputed => (refunded, true), + Reversal::DisputeWon => (refunded, false), + }; + let change = if matches!(reversal, Reversal::DisputeWon) { + // Back to what the refunds alone owe: give back whatever was taken for this charge beyond that. Only + // once, since the dispute is then closed. + if disputed { + let refs = json!([format!("refund: {charge_id}"), format!("dispute: {charge_id}"), format!("dispute won: {charge_id}")]); + let taken: Option = db::query!( + tx, + "SELECT COALESCE(-SUM(amount), 0)::BIGINT FROM credit_transactions \ + WHERE organization_id = {org_id} AND reference IN (SELECT jsonb_array_elements_text({refs}::jsonb))" + ) + .scalar() + .await?; + (taken.unwrap_or(0) - owed(now_refunded, false)).max(0) + } else { + 0 + } + } else { + -(owed(now_refunded, now_disputed) - owed(refunded, disputed)).clamp(0, balance.max(0)) + }; + db::query!( + tx, + "UPDATE credit_reversals SET refunded_credits = {now_refunded}, disputed = {now_disputed}, \ + updated_at = now() WHERE charge_id = {charge_id}" + ) + .update() + .await?; + if change != 0 { + let (kind, why) = match reversal { + Reversal::Refunded(_) => ("refund", format!("refund: {charge_id}")), + Reversal::Disputed => ("refund", format!("dispute: {charge_id}")), + Reversal::DisputeWon => ("adjustment", format!("dispute won: {charge_id}")), + }; + let after = balance + change; + db::query!(tx, "UPDATE organizations SET credits_balance = {after}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + db::query!( + tx, + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference) \ + VALUES ({org_id}, {change}, {after}, {kind}, {why})" + ) + .insert() + .await?; + tracing::info!(org_id, charge_id, purchase = reference, change, ?reversal, "credits reversed"); + } + Ok(change) + }) + .await +} + +/// The purchase a charge already reversed belongs to, so a closed dispute needs no Stripe lookup. +/// +/// # Errors +/// On a database error. +pub async fn reversed_purchase(org_id: i64, charge_id: &str) -> laravel::Result> { + let row = db::query!( + "SELECT r.purchase_reference, t.amount FROM credit_reversals r \ + JOIN credit_transactions t ON t.organization_id = r.organization_id AND t.kind = 'purchase' \ + AND t.reference = r.purchase_reference \ + WHERE r.charge_id = {charge_id} AND r.organization_id = {org_id}" + ) + .select_one() + .await?; + let Some(row) = row else { return Ok(None) }; + Ok(Some(Purchase { reference: row.try_get("purchase_reference")?, credits: row.try_get("amount")? })) +} + +/// The refunded share of a purchase's credits: `credits × refunded ÷ amount`, rounded down. +#[must_use] +pub fn refunded_share(credits: i64, amount: i64, refunded: i64) -> i64 { + if amount <= 0 { + return 0; + } + i64::try_from(i128::from(credits) * i128::from(refunded.clamp(0, amount)) / i128::from(amount)).unwrap_or(credits) +} diff --git a/app/src/billing/routes.rs b/app/src/billing/routes.rs index bdb2f32d..6df4741a 100644 --- a/app/src/billing/routes.rs +++ b/app/src/billing/routes.rs @@ -136,10 +136,26 @@ pub async fn checkout( ("subscription_data[billing_mode][type]", "flexible".to_string()), ]; form.extend(checkout_tax_fields()); - let body = stripe::post(key, "checkout/sessions", &form).await?; + // Two tabs (or a double click) within the same half hour get the same Checkout session, so they can't start two + // subscriptions (sc-9146; the webhook still keeps the first if two finish). The session expires at the end of the + // next half hour, so the request is the same in every call of the window, as an idempotency key needs. + let (idempotency, expires_at) = checkout_window(org.id, laravel::now().timestamp().as_second()); + form.push(("expires_at", expires_at.to_string())); + let body = stripe::request(key, Method::Post, "checkout/sessions", &form, Some(&idempotency)).await?; Ok(Json(json!({ "url": body["url"] }))) } +/// Checkout windows are half an hour. +const CHECKOUT_WINDOW_SECONDS: i64 = 30 * 60; + +/// The Team Checkout's idempotency key for `org` at `now` (Unix seconds), and when its session expires: the end of the +/// next window, 30 to 60 minutes away (Stripe allows 30 minutes to a day). +#[must_use] +pub fn checkout_window(org: i64, now: i64) -> (String, i64) { + let window = now.div_euclid(CHECKOUT_WINDOW_SECONDS); + (format!("visualci-team-checkout-{org}-{window}"), (window + 2) * CHECKOUT_WINDOW_SECONDS) +} + #[laravel::input] #[validate(authenticated)] pub struct PackParams { @@ -206,9 +222,15 @@ pub async fn set_auto_reload( } let org = billing_org(&user, &org).await?; let (id, packs) = (org.id, p.packs); + // Turning automatic packs back on clears the problems that asked for it (a declined pack, a failed invoice), not + // a second subscription, an unpaid one or a project that left the open source pool (sc-9146). + let (declined, advice) = + (super::webhook::AUTO_PACK_DECLINED, format!("%{}", super::webhook::INVOICE_FAILED_ADVICE)); db::query!( - "UPDATE organizations SET auto_reload_packs = {packs}, reloads_paused_at = NULL, billing_problem = NULL, \ - updated_at = now() WHERE id = {id}" + "UPDATE organizations SET auto_reload_packs = {packs}, reloads_paused_at = NULL, \ + billing_problem = CASE WHEN billing_problem = {declined} OR billing_problem LIKE {advice} THEN NULL \ + ELSE billing_problem END, \ + updated_at = now() WHERE id = {id}" ) .update() .await?; diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs index ea770296..14fe0292 100644 --- a/app/src/billing/webhook.rs +++ b/app/src/billing/webhook.rs @@ -1,11 +1,15 @@ //! Stripe's webhook (`POST /webhooks/stripe`), ported from today's server. Every event is safe to receive twice. //! //! - `checkout.session.completed`: a subscription moves the organization to Team; a paid pack adds its credits. +//! - `checkout.session.async_payment_succeeded`: a pack paid by a method that settles later (a bank debit) adds its +//! credits then. //! - `customer.subscription.updated`: active keeps it on Team; past due or unpaid shows a billing problem. //! - `customer.subscription.deleted`: back to Free. -//! - `invoice.paid`: an automatic reload's credits (if the reload itself didn't record them), and any billing problem -//! is over. +//! - `invoice.paid`: an automatic reload's credits (if the reload itself didn't record them), and the billing problem +//! that invoice caused is over (another problem stays). //! - `invoice.payment_failed`: shows the problem and pauses automatic reloads. +//! - `charge.refunded`, `charge.dispute.created`: the payment's credits are taken back (its refunded share, or all of +//! them for a dispute); `charge.dispute.closed` as won gives a dispute's credits back ([`super::reversals`]). //! //! Subscription events apply only to the organization's own subscription, and only when newer than the last one //! applied: Stripe sends events in any order and retries them for days. @@ -44,7 +48,13 @@ pub async fn handle( let object = &event["data"]["object"]; let text = |v: &Value| v.as_str().map(str::to_string); let kind = event["type"].as_str().unwrap_or_default(); - let Some(org_id) = org_for(object).await? else { + let key = stripe.secret_key.as_deref().filter(|k| !k.is_empty()); + // A dispute names its charge but not the customer: the charge says whose it is. + let disputed = match (kind.starts_with("charge.dispute."), key, object["charge"].as_str()) { + (true, Some(key), Some(charge)) => Some(super::stripe::get(key, &format!("charges/{charge}"), &[]).await?), + _ => None, + }; + let Some(org_id) = org_for(disputed.as_ref().unwrap_or(object)).await? else { return Ok(Json(json!({ "ignored": "not a VisualCI organization's" }))); }; let created = event["created"].as_i64().unwrap_or_default(); @@ -62,7 +72,9 @@ pub async fn handle( } } } - "checkout.session.completed" if object["mode"] == "payment" && object["metadata"]["kind"] == "credit_pack" => { + "checkout.session.completed" | "checkout.session.async_payment_succeeded" + if object["mode"] == "payment" && object["metadata"]["kind"] == "credit_pack" => + { let packs: i64 = object["metadata"]["packs"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0); if packs == 0 { return Err(laravel::abort_with(400, "session without VisualCI metadata")); @@ -117,22 +129,51 @@ pub async fn handle( { add_purchased_credits(org_id, CREDIT_PACK.credits, &format!("auto-reload: {invoice}")).await?; } - // A paid invoice settles a payment problem, not a second subscription. + // A paid invoice settles the problem it caused: its own failed payment, and a subscription's failed or + // unpaid renewal when it's the subscription's invoice. A second subscription, a declined automatic pack or + // a project that left the open source pool stays. + let settled = json!(settled_by(object)); db::query!( "UPDATE organizations SET billing_problem = NULL, updated_at = now() \ - WHERE id = {org_id} AND billing_problem IS DISTINCT FROM {TWO_SUBSCRIPTIONS}" + WHERE id = {org_id} AND billing_problem IN (SELECT jsonb_array_elements_text({settled}::jsonb))" ) .update() .await?; } "invoice.payment_failed" => { - let number = object["number"].as_str().unwrap_or("an invoice"); // Stripe emails the failed payment itself; a declined automatic pack has its own email (the reload) - record_payment_problem( - org_id, - &format!("Payment for {number} failed. Update the card in Manage billing, then turn reloads back on."), - ) - .await?; + record_payment_problem(org_id, &invoice_failed(object)).await?; + } + "charge.refunded" | "charge.dispute.created" | "charge.dispute.closed" => { + let charge = disputed.as_ref().unwrap_or(object); + let (Some(key), Some(charge_id)) = (key, charge["id"].as_str()) else { + return Ok(Json(json!({ "ignored": "no Stripe key to trace the charge with" }))); + }; + use super::reversals::{self, Reversal}; + let reversal = match kind { + // The amount refunded so far, in the charge's currency: turned into credits once the purchase is known. + "charge.refunded" => Reversal::Refunded(charge["amount_refunded"].as_i64().unwrap_or(0)), + "charge.dispute.created" => Reversal::Disputed, + // Won, or an inquiry closed without a chargeback: the credits come back. Lost: they stay taken. + _ if matches!(object["status"].as_str(), Some("won" | "warning_closed")) => Reversal::DisputeWon, + _ => return Ok(Json(json!({ "ignored": "a lost dispute keeps the credits taken" }))), + }; + let purchase = match reversals::reversed_purchase(org_id, charge_id).await? { + Some(p) => Some(p), + None => reversals::purchase_of(key, org_id, charge).await?, + }; + let Some(purchase) = purchase else { + return Ok(Json(json!({ "ignored": "the charge bought no credits" }))); + }; + let reversal = match reversal { + Reversal::Refunded(refunded) => Reversal::Refunded(reversals::refunded_share( + purchase.credits, + charge["amount"].as_i64().unwrap_or(0), + refunded, + )), + other => other, + }; + reversals::apply(org_id, charge_id, &purchase, reversal).await?; } _ => return Ok(Json(json!({ "ignored": true }))), } @@ -150,6 +191,31 @@ async fn org_for(object: &Value) -> laravel::Result> { db::query!("SELECT id FROM organizations WHERE stripe_customer_id = {customer}").scalar().await } +/// The problem a failed invoice shows ("Payment for VCI-0012 failed. …"). +fn invoice_failed(invoice: &Value) -> String { + let number = invoice["number"].as_str().unwrap_or("an invoice"); + format!("Payment for {number} failed. {INVOICE_FAILED_ADVICE}") +} + +/// The end of every failed invoice's problem ([`invoice_failed`]): turning automatic packs back on clears it. +pub const INVOICE_FAILED_ADVICE: &str = "Update the card in Manage billing, then turn reloads back on."; + +/// A declined automatic pack ([`super::reload`]): turning automatic packs back on clears it. +pub const AUTO_PACK_DECLINED: &str = + "An automatic credit pack was declined. Update the card in Manage billing, then turn automatic packs back on."; + +/// The problems a paid invoice settles: its own failed payment, and for a subscription's invoice, the subscription's +/// failed or unpaid renewal. +fn settled_by(invoice: &Value) -> Vec { + let mut settled = vec![invoice_failed(invoice)]; + let subscription = + invoice["subscription"].as_str().or_else(|| invoice["parent"]["subscription_details"]["subscription"].as_str()); + if subscription.is_some() || invoice["billing_reason"].as_str().is_some_and(|r| r.starts_with("subscription")) { + settled.extend([PAYMENT_FAILED.to_string(), UNPAID.to_string()]); + } + settled +} + 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 \ @@ -215,21 +281,30 @@ async fn subscription_event(org_id: i64, created: i64, change: Change) -> larave } Change::Nothing => {} } - Ok(Some(before)) + // The email is recorded with the change, so a change that commits always has it: queued after the commit, a + // failure to queue lost it for good, since Stripe's retry finds the plan already changed (sc-9146). + let mut emailed = 0; + if let Change::Plan { plan, .. } = &change + && before != *plan + { + let kind = + Kind::PlanChanged { from: plan_by_id(&before).name.to_string(), to: plan_by_id(plan).name.to_string() }; + let dedupe = format!("plan_changed:{org_id}:{plan}:{created}"); + emailed = notify::queue_in(tx, &kind, To::Billing(org_id), None, &dedupe).await?; + } + Ok(Some(emailed)) }) .await?; - let Some(before) = changed else { return Ok(false) }; + let Some(emailed) = changed else { return Ok(false) }; + if emailed > 0 + && let Err(e) = notify::DeliverEmails.dispatch().await + { + // Recorded: the five-minute run sends it. + tracing::warn!(org_id, error = %e, "couldn't queue the plan change email's delivery"); + } match change { Change::Plan { plan, .. } => { tracing::info!(org_id, plan, "plan changed"); - if before != plan { - let kind = Kind::PlanChanged { - from: plan_by_id(&before).name.to_string(), - to: plan_by_id(plan).name.to_string(), - }; - notify::queue(&kind, To::Billing(org_id), None, &format!("plan_changed:{org_id}:{plan}:{created}")) - .await?; - } } Change::Problem(message) => tracing::warn!(org_id, message, "billing problem"), Change::Nothing => {} diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 1d3e02c8..e1589480 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -990,6 +990,26 @@ async fn charge_locked(build: &Build) -> laravel::Result<()> { Ok(()) } +/// [`stop_if_out_of_credits`] for a request (finalizing a build through the API or MCP): it fails the build at once +/// only when no automatic pack could help. When one could, the build stays processing and its job, which runs this +/// check again before comparing anything, buys the pack: a request never waits on Stripe's calls (sc-9146). +/// +/// # Errors +/// On a database error. +pub async fn stop_if_out_of_credits_without_reloading(build: Build) -> laravel::Result { + if build.state != "processing" { + return Ok(build); + } + 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? + && crate::billing::reload::may_reload(&org).await? + { + return Ok(build); + } + stop_if_out_of_credits(build).await +} + /// Fail a build that's processing when its organization is out of credits, after billing's chance to reload (the /// `CreditsRanOut` event's listeners run first). Billing's listeners hear `BuildStoppedForCredits` (the monthly email). /// diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 8fe86bca..508865ed 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -268,8 +268,11 @@ pub async fn finalize( let was_receiving = build.state == "receiving"; let allow_empty = params.allow_empty || params.empty_reason.is_some(); let build = domain::finalize_shard(build, params.shard, allow_empty).await.map_err(ApiError::from)?; - let build = - if was_receiving { crate::domain::processing::stop_if_out_of_credits(build).await? } else { build }; + let build = if was_receiving { + crate::domain::processing::stop_if_out_of_credits_without_reloading(build).await? + } else { + build + }; if was_receiving && build.state == "processing" { crate::live::tell(project.id, Some(build.id)).await; crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await?; diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index ae8ddfaa..d7015ef5 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -2040,7 +2040,7 @@ impl VisualCi { Err(refused) => return Ok(refused), }; let build = if was_receiving { - domain::processing::stop_if_out_of_credits(build).await.map_err(internal)? + domain::processing::stop_if_out_of_credits_without_reloading(build).await.map_err(internal)? } else { build }; diff --git a/app/src/notify/mod.rs b/app/src/notify/mod.rs index 2f29169e..a6e26fbb 100644 --- a/app/src/notify/mod.rs +++ b/app/src/notify/mod.rs @@ -10,7 +10,7 @@ pub mod outbox; pub mod postmark; pub mod render; -pub use outbox::{DeliverEmails, To, queue}; +pub use outbox::{DeliverEmails, To, queue, queue_in}; pub use render::{About, Kind, Paused, Preference, Rendered, render}; use laravel::event::{Event, listener}; diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs index 968c44be..50b9e92f 100644 --- a/app/src/notify/outbox.rs +++ b/app/src/notify/outbox.rs @@ -58,6 +58,65 @@ async fn admins(org_id: i64, preference: Option) -> laravel::Result< /// # Errors /// On a database error. pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result { + let mut queued = 0; + for e in outgoing(kind, to, org_id, dedupe_key).await? { + let inserted: Option = db::query!( + "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ + VALUES ({e.name}, {e.key}, {e.org_id}, {e.user_id}, {e.address}, {e.data}) \ + ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + queued += usize::from(inserted.is_some()); + } + if queued > 0 { + DeliverEmails.dispatch().await?; + } + Ok(queued) +} + +/// [`queue`] inside the caller's transaction: the email is recorded only if the change it tells of commits, and a +/// change that commits always has its email (a plan change whose email was queued after the commit was lost when +/// queueing failed, and Stripe's retry then saw no change to tell of; sc-9146). Its recipients are read outside the +/// transaction. Delivery isn't queued: the caller dispatches [`DeliverEmails`] after the commit when this returned +/// more than 0, and the five-minute run sends it anyway. +/// +/// # Errors +/// On a database error. +pub async fn queue_in( + tx: &mut db::AnyTransaction<'_>, + kind: &Kind, + to: To, + org_id: Option, + dedupe_key: &str, +) -> laravel::Result { + let mut queued = 0; + for e in outgoing(kind, to, org_id, dedupe_key).await? { + let inserted: Option = db::query!( + tx, + "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ + VALUES ({e.name}, {e.key}, {e.org_id}, {e.user_id}, {e.address}, {e.data}) \ + ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + queued += usize::from(inserted.is_some()); + } + Ok(queued) +} + +/// One outbox row to record. +struct Outgoing { + name: &'static str, + key: String, + org_id: Option, + user_id: Option, + address: String, + data: serde_json::Value, +} + +/// The rows an email is recorded as: one per recipient, each with its own dedupe key. +async fn outgoing(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result> { let org_id = match to { To::Billing(o) | To::Admins(o) => Some(o), To::User(_) | To::Address(_) => org_id, @@ -84,22 +143,17 @@ pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) - }; let data = serde_json::to_value(kind).map_err(|e| laravel::Error::msg(e.to_string()))?; let name = kind.name(); - let mut queued = 0; - for (address, user_id) in recipients { - let key = format!("{dedupe_key}:{address}"); - let inserted: Option = db::query!( - "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ - VALUES ({name}, {key}, {org_id}, {user_id}, {address}, {data}) \ - ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" - ) - .scalar() - .await?; - queued += usize::from(inserted.is_some()); - } - if queued > 0 { - DeliverEmails.dispatch().await?; - } - Ok(queued) + Ok(recipients + .into_iter() + .map(|(address, user_id)| Outgoing { + name, + key: format!("{dedupe_key}:{address}"), + org_id, + user_id, + address, + data: data.clone(), + }) + .collect()) } /// Send pending emails, up to 50 a run. Each is claimed just before it's sent, so two runs never send one twice; a diff --git a/app/tests/automatic_packs.rs b/app/tests/automatic_packs.rs index 626f8c1d..2e3e1c9e 100644 --- a/app/tests/automatic_packs.rs +++ b/app/tests/automatic_packs.rs @@ -275,3 +275,64 @@ async fn a_pay_call_cut_off_after_the_charge_credits_the_pack(_app: Application) assert_eq!(paused, Some(false), "a timeout isn't a declined card"); Ok(()) } + +/// A receiving build of `org`'s new project, with its project token. +async fn receiving_build(app: &Application, org: i64) -> laravel::Result<(String, String)> { + 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(); + let pid = created.json()["id"].as_str().expect("the build's id").to_string(); + Ok((token, pid)) +} + +/// Finalizing a build of an organization out of credits never waits on Stripe: with an automatic pack possible the +/// build stays processing and its job buys the pack; without one it fails at once, as before (sc-9146). +#[laravel::test(app = with_stripe_key)] +async fn finalizing_leaves_the_automatic_pack_to_the_job(app: Application) -> laravel::Result<()> { + let jobs = laravel::queue::fake(); + let fake = stripe(true); + let org = team_out_of_credits("acme", 2).await?; + let (token, pid) = receiving_build(&app, org).await?; + let finalized = app + .post(format!("/api/v1/builds/{pid}/finalize")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "allow_empty": true })) + .await; + finalized.assert_ok().assert_json_path("state", "processing"); + assert!( + fake.sent().is_empty(), + "the request called Stripe: {:?}", + fake.sent().iter().map(|r| r.url().to_string()).collect::>() + ); + assert_eq!(jobs.pushed::().len(), 1, "the job buys the pack"); + + db::query!("UPDATE organizations SET auto_reload_packs = 0 WHERE id = {org}").update().await?; + let created = app + .post("/api/v1/builds") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "commit": "c2", "branch": "main", "parent_commits": [] })) + .await; + let pid = created.json()["id"].as_str().expect("the build's id").to_string(); + let finalized = app + .post(format!("/api/v1/builds/{pid}/finalize")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "allow_empty": true })) + .await; + finalized.assert_ok().assert_json_path("state", "failed"); + let error = finalized.json()["error"].as_str().unwrap_or_default().to_string(); + assert!(error.contains("no pack credits left"), "{error}"); + Ok(()) +} diff --git a/app/tests/billing.rs b/app/tests/billing.rs index 6eddbe43..c3c52c76 100644 --- a/app/tests/billing.rs +++ b/app/tests/billing.rs @@ -199,8 +199,10 @@ async fn a_paid_invoice_keeps_the_two_subscriptions_notice(app: Application) -> .await? .flatten(); assert_eq!(problem.as_deref(), Some(notice)); - let failed = "Payment for INV-1 failed."; + let failed = format!("Payment for INV-1 failed. {}", app::billing::webhook::INVOICE_FAILED_ADVICE); db::query!("UPDATE organizations SET billing_problem = {failed} WHERE id = {org}").update().await?; + let mut paid = paid; + paid["data"]["object"]["number"] = json!("INV-1"); post(&app, paid).await.assert_ok(); let problem: Option = db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") .scalar::>() @@ -248,3 +250,288 @@ async fn a_subscription_that_stops_paying_moves_to_free_and_paying_brings_team_b } Ok(()) } + +async fn problem(org: i64) -> laravel::Result> { + Ok(db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten()) +} + +/// A pack paid by a method that settles later (a bank debit) completes Checkout unpaid and is credited when +/// `async_payment_succeeded` comes, once however often Stripe sends it (sc-9146). +#[laravel::test(app = stripe)] +async fn a_pack_paid_later_is_credited_when_the_payment_succeeds(app: Application) -> laravel::Result<()> { + let org = org().await?; + let session = |kind: &str, status: &str| { + json!({ "type": kind, "created": 100, "data": { "object": { + "id": "cs_2", "mode": "payment", "payment_status": status, + "metadata": { "organization_id": org.to_string(), "kind": "credit_pack", "packs": "1" } } } }) + }; + post(&app, session("checkout.session.completed", "unpaid")) + .await + .assert_ok() + .assert_json_path("ignored", "not paid"); + let balance = + || async { db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar::().await }; + assert_eq!(balance().await?, Some(0)); + for _ in 0..2 { + post(&app, session("checkout.session.async_payment_succeeded", "paid")).await.assert_ok(); + } + assert_eq!(balance().await?, Some(app::billing::CREDIT_PACK.credits)); + Ok(()) +} + +/// A paid invoice settles the problem it caused and no other: an automatic pack's invoice leaves the subscription's +/// failed renewal, the subscription's invoice clears it, and a project that left the open source pool stays (sc-9146). +#[laravel::test(app = stripe)] +async fn a_paid_invoice_settles_only_its_own_problem(app: Application) -> laravel::Result<()> { + let org = org().await?; + let renewal_failed = "The Team subscription's last payment failed. Update the card in Manage billing."; + db::query!("UPDATE organizations SET billing_problem = {renewal_failed} WHERE id = {org}").update().await?; + let invoice = |object: serde_json::Value| { + let mut object = object; + object["metadata"]["organization_id"] = json!(org.to_string()); + json!({ "type": "invoice.paid", "created": 1_800_000_000, "data": { "object": object } }) + }; + post(&app, invoice(json!({ "id": "in_pack", "number": "INV-7", "metadata": { "kind": "auto_reload" } }))) + .await + .assert_ok(); + assert_eq!(problem(org).await?.as_deref(), Some(renewal_failed), "a pack's invoice isn't the renewal"); + post(&app, invoice(json!({ "id": "in_sub", "number": "INV-8", "subscription": "sub_1", "metadata": {} }))) + .await + .assert_ok(); + assert_eq!(problem(org).await?, None, "the subscription's invoice settles its renewal"); + let left_pool = "acme/web is no longer an open source project: its repository is private."; + db::query!("UPDATE organizations SET billing_problem = {left_pool} WHERE id = {org}").update().await?; + post(&app, invoice(json!({ "id": "in_sub2", "number": "INV-9", "subscription": "sub_1", "metadata": {} }))) + .await + .assert_ok(); + assert_eq!(problem(org).await?.as_deref(), Some(left_pool)); + Ok(()) +} + +/// Turning automatic packs back on clears the declined pack it was asked for, and leaves any other problem (sc-9146). +#[laravel::test(app = with_stripe_key)] +async fn turning_automatic_packs_on_clears_only_their_own_problem(app: Application) -> laravel::Result<()> { + let org = org().await?; + db::query!("UPDATE organizations SET plan = 'team' WHERE id = {org}").update().await?; + let admin = member(org, "admin@example.com", "admin").await?; + let turn_on = || { + app.put("/api/ui/orgs/acme/billing/auto-reload") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "packs": 2 })) + }; + let declined = app::billing::webhook::AUTO_PACK_DECLINED; + db::query!("UPDATE organizations SET billing_problem = {declined} WHERE id = {org}").update().await?; + turn_on().await.assert_ok(); + assert_eq!(problem(org).await?, None); + let two = "This organization has two Team subscriptions. Cancel one in Manage billing."; + db::query!("UPDATE organizations SET billing_problem = {two} WHERE id = {org}").update().await?; + turn_on().await.assert_ok(); + assert_eq!(problem(org).await?.as_deref(), Some(two)); + Ok(()) +} + +/// The plan change email is recorded in the same transaction as the plan, so a plan that changed always has its +/// email, and Stripe's retry of the event records no second one (sc-9146). +#[laravel::test(app = stripe)] +async fn a_plan_change_records_its_email_with_the_change(app: Application) -> laravel::Result<()> { + let org = org().await?; + db::query!("UPDATE organizations SET billing_email = 'billing@example.com' WHERE id = {org}").update().await?; + let event = json!({ "type": "checkout.session.completed", "created": 100, "data": { "object": { + "mode": "subscription", "subscription": "sub_1", "customer": "cus_1", + "metadata": { "organization_id": org.to_string() } } } }); + post(&app, event.clone()).await.assert_ok(); + post(&app, event).await.assert_ok(); + let emails: Option = db::query!( + "SELECT COUNT(*) FROM emails WHERE organization_id = {org} AND kind = 'plan_changed' \ + AND recipient = 'billing@example.com'" + ) + .scalar() + .await?; + assert_eq!(emails, Some(1)); + Ok(()) +} + +/// Two Team checkouts in the same half hour (two tabs, a double click) send Stripe the same idempotency key and the +/// same session expiry, so Stripe returns one session and they can't start two subscriptions (sc-9146). +#[laravel::test(app = with_stripe_key)] +async fn checkouts_in_the_same_half_hour_share_one_stripe_session(app: Application) -> laravel::Result<()> { + let org = org().await?; + let admin = member(org, "admin@example.com", "admin").await?; + let stripe = client::fake() + .with("api.stripe.com/*", json!({ "id": "cs_1", "url": "https://checkout.stripe.test/cs_1", "data": [] })); + for _ in 0..2 { + app.post("/api/ui/orgs/acme/billing/checkout") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "plan": "team" })) + .await + .assert_ok(); + } + let sessions: Vec<_> = stripe.sent().into_iter().filter(|r| r.url().ends_with("/v1/checkout/sessions")).collect(); + assert_eq!(sessions.len(), 2); + let key = |i: usize| sessions[i].header("idempotency-key").map(str::to_string); + assert!(key(0).is_some_and(|k| k.starts_with(&format!("visualci-team-checkout-{org}-"))), "{:?}", key(0)); + assert_eq!(key(0), key(1)); + assert_eq!(sessions[0].body(), sessions[1].body(), "Stripe refuses a reused key with other parameters"); + Ok(()) +} + +#[test] +fn a_checkout_window_is_half_an_hour_and_its_session_outlives_it() { + use app::billing::routes::checkout_window; + let (key, expires) = checkout_window(7, 1_800_000_000); + assert_eq!(key, "visualci-team-checkout-7-1000000"); + assert_eq!(expires - 1_800_000_000, 3600, "the start of a window: an hour"); + assert_eq!(checkout_window(7, 1_800_001_799).0, key, "the same window"); + assert_eq!(expires - 1_800_001_799, 1801, "its end: just over 30 minutes, Stripe's minimum"); + assert_ne!(checkout_window(7, 1_800_001_800).0, key); + assert_ne!(checkout_window(8, 1_800_000_000).0, key); +} + +fn stripe_with_key() -> Application { + app::testing::configure() + .with_envs([("VISUALCI_STRIPE_WEBHOOK_SECRET", SECRET), ("VISUALCI_STRIPE_SECRET_KEY", "sk_test_x")]) + .create() +} + +/// Stripe as the refunds see it: payment intent `pi_pack` paid Checkout session `cs_9`, `pi_reload` paid automatic +/// pack invoice `in_9`, and charge `ch_1` (customer `cus_1`) is the one disputed. +fn stripe_charges() -> client::HttpFake { + client::fake().with("api.stripe.com/*", |r: &client::Request| -> client::FakeResponse { + let url = r.url().to_string(); + let path = url.split_once("/v1/").map_or("", |(_, p)| p).split('?').next().unwrap_or("").to_string(); + let empty = client::response().json(json!({ "data": [] })); + match path.as_str() { + "checkout/sessions" if url.contains("pi_pack") => { + client::response().json(json!({ "data": [{ "id": "cs_9" }] })) + } + "invoice_payments" if url.contains("pi_reload") => { + client::response().json(json!({ "data": [{ "invoice": "in_9" }] })) + } + "charges/ch_1" => { + client::response().json(json!({ + "id": "ch_1", "customer": "cus_1", "payment_intent": "pi_pack", "amount": 2000, "amount_refunded": 0 })) + } + _ => empty, + } + }) +} + +/// An organization with Stripe customer `cus_1` that bought 2 packs through Checkout `cs_9`. +async fn org_with_packs() -> laravel::Result { + let org = org().await?; + db::query!("UPDATE organizations SET stripe_customer_id = 'cus_1' WHERE id = {org}").update().await?; + app::domain::credits::add_purchased_credits(org, 2 * app::billing::CREDIT_PACK.credits, "packs: cs_9").await?; + Ok(org) +} + +async fn balance(org: i64) -> laravel::Result { + Ok(db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar::().await?.unwrap_or(-1)) +} + +fn refunded(charge: &str, intent: &str, refunded: i64) -> serde_json::Value { + json!({ "type": "charge.refunded", "created": 100, "livemode": false, "data": { "object": { + "id": charge, "customer": "cus_1", "payment_intent": intent, "amount": 2000, "amount_refunded": refunded } } }) +} + +/// A refund takes back its share of the pack's credits, once however often Stripe sends it, and a second refund the +/// rest (terms.md: "If a payment is refunded or disputed, the credits it bought are removed"; sc-9146). +#[laravel::test(app = stripe_with_key)] +async fn a_refund_takes_back_its_share_of_the_credits_once(app: Application) -> laravel::Result<()> { + let _stripe = stripe_charges(); + let org = org_with_packs().await?; + let pack = app::billing::CREDIT_PACK.credits; + for _ in 0..2 { + post(&app, refunded("ch_2", "pi_pack", 1000)).await.assert_ok(); + assert_eq!(balance(org).await?, pack, "half refunded: one pack's credits back, once"); + } + post(&app, refunded("ch_2", "pi_pack", 2000)).await.assert_ok(); + assert_eq!(balance(org).await?, 0); + Ok(()) +} + +/// Credits already spent can't be taken back: the balance stops at zero, and a pack bought afterwards keeps its credits. +#[laravel::test(app = stripe_with_key)] +async fn a_refund_never_takes_more_than_is_left(app: Application) -> laravel::Result<()> { + let _stripe = stripe_charges(); + let org = org_with_packs().await?; + let pack = app::billing::CREDIT_PACK.credits; + app::domain::credits::add_credits(org, -(2 * pack - 10), "build", None).await?; + post(&app, refunded("ch_2", "pi_pack", 2000)).await.assert_ok(); + assert_eq!(balance(org).await?, 0); + app::domain::credits::add_purchased_credits(org, pack, "packs: cs_10").await?; + post(&app, refunded("ch_2", "pi_pack", 2000)).await.assert_ok(); + assert_eq!(balance(org).await?, pack, "the new pack isn't charged for the old refund"); + Ok(()) +} + +/// An automatic pack's charge is traced through its invoice; a subscription's charge bought no credits. +#[laravel::test(app = stripe_with_key)] +async fn refunds_are_traced_to_automatic_packs_and_skip_subscriptions(app: Application) -> laravel::Result<()> { + let _stripe = stripe_charges(); + let org = org_with_packs().await?; + let pack = app::billing::CREDIT_PACK.credits; + app::domain::credits::add_purchased_credits(org, pack, "auto-reload: in_9").await?; + post(&app, refunded("ch_3", "pi_subscription", 2000)) + .await + .assert_ok() + .assert_json_path("ignored", "the charge bought no credits"); + assert_eq!(balance(org).await?, 3 * pack); + post(&app, refunded("ch_4", "pi_reload", 2000)).await.assert_ok(); + assert_eq!(balance(org).await?, 2 * pack); + Ok(()) +} + +/// A dispute takes back all the pack's credits; won, it gives them back once; lost, they stay removed. +#[laravel::test(app = stripe_with_key)] +async fn a_dispute_takes_the_credits_and_a_won_one_gives_them_back(app: Application) -> laravel::Result<()> { + let _stripe = stripe_charges(); + let org = org_with_packs().await?; + let pack = app::billing::CREDIT_PACK.credits; + let dispute = |kind: &str, status: &str| { + json!({ "type": kind, "created": 100, "livemode": false, "data": { "object": { + "id": "dp_1", "charge": "ch_1", "payment_intent": "pi_pack", "status": status } } }) + }; + post(&app, dispute("charge.dispute.created", "needs_response")).await.assert_ok(); + assert_eq!(balance(org).await?, 0); + for _ in 0..2 { + post(&app, dispute("charge.dispute.closed", "won")).await.assert_ok(); + assert_eq!(balance(org).await?, 2 * pack, "given back once"); + } + post(&app, dispute("charge.dispute.closed", "lost")).await.assert_ok(); + assert_eq!(balance(org).await?, 2 * pack, "a late 'lost' after 'won' changes nothing"); + Ok(()) +} + +#[test] +fn a_refunded_share_rounds_down() { + use app::billing::reversals::refunded_share; + assert_eq!(refunded_share(500_000, 2000, 1000), 250_000); + assert_eq!(refunded_share(500_000, 3000, 1000), 166_666); + assert_eq!(refunded_share(500_000, 2000, 5000), 500_000, "never more than the purchase"); + assert_eq!(refunded_share(500_000, 0, 0), 0); +} + +/// A refund while a dispute is open takes nothing more (the dispute took it all); won, the dispute gives back only +/// what the refund doesn't keep. +#[laravel::test(app = stripe_with_key)] +async fn a_won_dispute_keeps_a_refunds_share(app: Application) -> laravel::Result<()> { + let _stripe = stripe_charges(); + let org = org_with_packs().await?; + let pack = app::billing::CREDIT_PACK.credits; + let dispute = |kind: &str, status: &str| { + json!({ "type": kind, "created": 100, "livemode": false, "data": { "object": { + "id": "dp_1", "charge": "ch_1", "payment_intent": "pi_pack", "status": status } } }) + }; + post(&app, dispute("charge.dispute.created", "needs_response")).await.assert_ok(); + assert_eq!(balance(org).await?, 0); + post(&app, refunded("ch_1", "pi_pack", 1000)).await.assert_ok(); + assert_eq!(balance(org).await?, 0); + post(&app, dispute("charge.dispute.closed", "won")).await.assert_ok(); + assert_eq!(balance(org).await?, pack, "half was refunded: that half stays taken"); + Ok(()) +} diff --git a/docs/deploy.md b/docs/deploy.md index b8a2916c..1d3696d0 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -59,7 +59,7 @@ app reads is in `app/src/config.rs`, and the generated reference is | `VISUALCI_S3_BUCKET` | `visualci` | | `VISUALCI_S3_ACCESS_KEY_ID`, `VISUALCI_S3_SECRET_ACCESS_KEY` | an R2 token scoped to that bucket | | `VISUALCI_GITHUB_APP_ID`, `VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `VISUALCI_GITHUB_WEBHOOK_SECRET` | the VisualCI GitHub App (production refuses to boot without them) | -| `VISUALCI_STRIPE_SECRET_KEY`, `VISUALCI_STRIPE_WEBHOOK_SECRET` | payments; production refuses to boot without them or on a test key. The webhook endpoint is `https://api.visualci.com/webhooks/stripe` with `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed` | +| `VISUALCI_STRIPE_SECRET_KEY`, `VISUALCI_STRIPE_WEBHOOK_SECRET` | payments; production refuses to boot without them or on a test key. The webhook endpoint is `https://api.visualci.com/webhooks/stripe` with `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid`, `invoice.payment_failed`, `charge.refunded`, `charge.dispute.created` and `charge.dispute.closed`; the key needs read access to Charges, Checkout Sessions and Invoices (refunds trace a charge to the pack it bought) | | `VISUALCI_POSTMARK_SERVER_TOKEN` | transactional email through the "VisualCI" Postmark server (1Password `talira-cluster/visualci-postmark`); production refuses to boot without it. `VISUALCI_MAIL_FROM`, `VISUALCI_MAIL_REPLY_TO` and `VISUALCI_TEAM_EMAIL` (support@visualci.com, which forwards to DocSpring's Intercom: new feedback and sign-ups go there) | | `VISUALCI_WAITLIST` | `true`: sign-ups join the waitlist | | `VISUALCI_*_HEARTBEAT_URL`, `_TOKEN` | the Gatus external endpoints the scheduled jobs push to (Monitoring, below) |