Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions app/database/migrations/2026_12_09_000000_credit_reversals.rs
Original file line number Diff line number Diff line change
@@ -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);
";
1 change: 1 addition & 0 deletions app/src/billing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
20 changes: 14 additions & 6 deletions app/src/billing/reload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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<Reload> {
let org = Organization::find_or_fail(organization_id).await?;
if !plan_by_id(&org.plan).credit_packs || org.stripe_customer_id.is_none() {
Expand Down Expand Up @@ -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 {
Expand Down
178 changes: 178 additions & 0 deletions app/src/billing/reversals.rs
Original file line number Diff line number Diff line change
@@ -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<Option<Purchase>> {
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<i64> {
let (reference, credits) = (purchase.reference.as_str(), purchase.credits);
db::transaction(async |tx| {
let balance: Option<i64> =
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<i64> = 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<Option<Purchase>> {
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)
}
28 changes: 25 additions & 3 deletions app/src/billing/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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?;
Expand Down
Loading
Loading