Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(ai): billing should find correct default payment method (#7138)
Will Hutchinsona4ffbb28b89e
diff --git a/Cargo.lock b/Cargo.lockindex 5156e6c63d..21c9ab6339 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -748,6 +748,7 @@ dependencies = ["tokio","tracing","utoipa",+ "wiremock","workspace-hack",]diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.tomlindex 3805548d60..7c3308a3b0 100644--- a/crates/ai_billing/Cargo.toml+++ b/crates/ai_billing/Cargo.toml@@ -38,3 +38,4 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }+wiremock = { workspace = true }diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex 0d670ffed1..59562f9580 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -12,8 +12,8 @@ pub use models::{CREDIT_PACKS_CENTS, DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS,OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,OpenPeriodStart, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, PlanTier,- Result, SeatAllowance, SeatGeneration, SeatUsage, TARGET_GROSS_MARGIN_BPS, UsageSnapshot,- list_rate_cents,+ Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope, TARGET_GROSS_MARGIN_BPS,+ UsageSnapshot, list_rate_cents,};pub use ports::{BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex 7bf80f4b53..a9b76f8919 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -242,6 +242,32 @@ pub enum AllowanceStore {Conflict,}+/// Which of the payer's subscriptions funds an overage charge.+///+/// A payer may hold a personal subscription and a team subscription at the+/// same time. Team owners and team members both use the team subscription.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SubscriptionScope {+ /// The subscription that is not tied to a team.+ Personal,+ /// The subscription for this team.+ Team {+ /// The team.+ team_id: Uuid,+ },+}++impl From<&PayerScope> for SubscriptionScope {+ fn from(scope: &PayerScope) -> Self {+ match scope {+ PayerScope::Personal => Self::Personal,+ PayerScope::TeamOwner { team_id } | PayerScope::TeamMember { team_id } => {+ Self::Team { team_id: *team_id }+ }+ }+ }+}+/// Who pays for a user's AI, and through what.#[derive(Debug, Clone, PartialEq, Eq)]pub enum PayerScope {diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex aa6e02305c..2a94421f90 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -5,7 +5,7 @@ use super::ledger::SettlementPolicy;use super::models::{AllowanceDecision, AllowanceStore, BillingPeriod, BillingSettings, Entitlement,OpenPeriodStart, OverageChargeStatus, PeriodAllowance, PeriodLedger, Result, SeatAllowance,- SeatGeneration, SeatUsage, UsageSnapshot,+ SeatGeneration, SeatUsage, SubscriptionScope, UsageSnapshot,};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -242,6 +242,8 @@ pub struct OverageChargeRequest {pub amount_cents: i64,/// Line description shown on the invoice.pub description: String,+ /// Which subscription pays this charge.+ pub scope: SubscriptionScope,}/// The payment provider.@@ -253,21 +255,35 @@ pub trait PaymentGateway: Send + Sync + 'static {) -> impl Future<Output = Result<String>> + Send;/// Open a finalized invoice for exactly this overage chunk (and nothing- /// else pending on the customer). Returns the invoice id. Idempotent on- /// `charge_id`.+ /// else pending on the customer). [`OverageChargeRequest::scope`] selects+ /// the active or trialing subscription. Another scope is ignored. No+ /// matching subscription fails unless an idempotent retry finds an invoice+ /// that already stores its payment method. Distinct effective methods in+ /// the selected scope fail with+ /// [`BillingError::Payment`](super::BillingError::Payment).+ /// Returns the invoice id. Idempotent on `charge_id`.fn open_overage_invoice(&self,request: OverageChargeRequest,) -> impl Future<Output = Result<String>> + Send;- /// Attempt to collect an open overage invoice now. `Ok(true)` when it is- /// paid, `Ok(false)` when the card was declined and the invoice stays- /// open for Stripe's own retries (the webhook reports the outcome), `Err`- /// when the provider could not be reached or rejected the request.+ /// Attempt to collect an open overage invoice now. `scope` is the payer's+ /// current subscription scope. A scope stamped on the invoice overrides+ /// it. Invoices without that stamp use `scope`. Distinct effective methods+ /// in the chosen scope fail with+ /// [`BillingError::Payment`](super::BillingError::Payment).+ /// If no active or trialing subscription matches, an invoice-stored+ /// payment method may still collect the existing debt.+ ///+ /// `Ok(true)` when it is paid, `Ok(false)` when the card was declined and+ /// the invoice stays open for the provider's own retries (the webhook+ /// reports the outcome), `Err` when the provider could not be reached or+ /// rejected the request.fn pay_overage_invoice(&self,charge_id: Uuid,invoice_id: &str,+ scope: SubscriptionScope,) -> impl Future<Output = Result<bool>> + Send;}diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 48186e0e93..8c40607fe6 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -9,7 +9,7 @@ use super::models::{AllowanceDecision, AllowanceStore, BillingError, BillingPeriod, BillingSettings,CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS,OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PlanTier, Result,- SeatAllowance, SeatUsage, UsageSnapshot,+ SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,};use super::ports::{BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,@@ -299,6 +299,7 @@ wherecharge: PendingCharge,) -> Result<()> {let payer = &entitlement.payer;+ let scope = SubscriptionScope::from(&entitlement.scope);let customer_id = match self.entitlements.stripe_customer_id(payer).await {Ok(Some(customer_id)) => customer_id,Ok(None) => {@@ -329,6 +330,7 @@ wherecharge_id: charge.id,amount_cents: charge.amount_cents,description,+ scope,}).await{@@ -353,7 +355,7 @@ wherematch self.payments- .pay_overage_invoice(charge.id, &invoice_id)+ .pay_overage_invoice(charge.id, &invoice_id, scope).await{Ok(true) => {diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex a0abbcd520..65c86648c8 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -470,7 +470,12 @@ impl PaymentGateway for FakePayments {self.opened.lock().unwrap().push(request);Ok(invoice)}- async fn pay_overage_invoice(&self, charge_id: Uuid, invoice_id: &str) -> Result<bool> {+ async fn pay_overage_invoice(+ &self,+ charge_id: Uuid,+ invoice_id: &str,+ _scope: SubscriptionScope,+ ) -> Result<bool> {self.payments.lock().unwrap()@@ -690,6 +695,7 @@ async fn overage_is_charged_in_chunks_and_respects_the_cap() {assert_eq!(opened.len(), 1);assert_eq!(opened[0].amount_cents, 1_200);assert_eq!(opened[0].customer_id, "cus_123");+ assert_eq!(opened[0].scope, SubscriptionScope::Personal);let charges = repo.charges();let charge = &charges[0];assert_eq!(charge.status, OverageChargeStatus::Paid);@@ -1257,6 +1263,7 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {// The owner's unused allowance does not offset it. Member B's usage is// ignored because they were not a billed user in that period.assert_eq!(opened[0].amount_cents, 5_200);+ assert_eq!(opened[0].scope, SubscriptionScope::Team { team_id });}#[tokio::test]diff --git a/crates/ai_billing/src/outbound/stripe_gateway.rs b/crates/ai_billing/src/outbound/stripe_gateway.rsindex aaac1adfb9..ad74a16533 100644--- a/crates/ai_billing/src/outbound/stripe_gateway.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway.rs@@ -1,19 +1,26 @@//! Stripe adapter: one-off Checkout for credit packs, and immediate invoices//! for overage chunks.+#[cfg(test)]+mod test;+use crate::domain::{BillingError, CreditCheckoutRequest, OverageChargeRequest, PaymentGateway, Result,+ SubscriptionScope,};use chrono::Utc;use macro_uuid::Uuid;+use serde::Serialize;use std::collections::HashMap;use std::sync::Arc;use stripe::{CheckoutSession, CheckoutSessionMode, CollectionMethod, CreateCheckoutSession,CreateCheckoutSessionLineItems, CreateCheckoutSessionLineItemsPriceData,CreateCheckoutSessionLineItemsPriceDataProductData, CreateCheckoutSessionPaymentIntentData,- CreateInvoice, CreateInvoiceItem, Currency, CustomerId, FinalizeInvoiceParams, Invoice,- InvoiceId, InvoiceItem, InvoicePendingInvoiceItemsBehavior, InvoiceStatus, RequestStrategy,+ CreateInvoice, CreateInvoiceItem, Currency, Customer, CustomerId, Expandable,+ FinalizeInvoiceParams, Invoice, InvoiceId, InvoiceItem, InvoicePendingInvoiceItemsBehavior,+ InvoiceStatus, ListSubscriptions, PaymentMethodId, RequestStrategy, Subscription,+ SubscriptionStatus,};/// Metadata key stamped on every Stripe object this crate creates.@@ -26,6 +33,9 @@ pub const PURPOSE_AI_OVERAGE: &str = "ai_overage";pub const PAYER_METADATA_KEY: &str = "macro_user_id";/// Metadata key carrying the `ai_overage_charge` id on overage invoices.pub const CHARGE_METADATA_KEY: &str = "macro_charge_id";+const BILLING_SCOPE_METADATA_KEY: &str = "macro_billing_scope";+const PERSONAL_SCOPE_STAMP: &str = "personal";+const TEAM_ID_METADATA_KEY: &str = "team_id";/// [`PaymentGateway`] backed by Stripe.#[derive(Clone)]@@ -46,12 +56,66 @@ impl StripePaymentGateway {.clone().with_strategy(RequestStrategy::Idempotent(key))}++ async fn resolve_charge_method(+ &self,+ customer_id: &CustomerId,+ scope: SubscriptionScope,+ ) -> Result<ChargeMethod> {+ let customer = Customer::retrieve(&self.client, customer_id, &[])+ .await+ .map_err(payment)?;+ let subscriptions = self.non_canceled_subscriptions(customer_id).await?;+ charge_method(customer_fallback(&customer), &subscriptions, scope)+ }++ /// Stripe omits `status` to mean every subscription that is not canceled.+ async fn non_canceled_subscriptions(+ &self,+ customer_id: &CustomerId,+ ) -> Result<Vec<Subscription>> {+ let mut params = ListSubscriptions::new();+ params.customer = Some(customer_id.clone());+ params.limit = Some(100);+ let mut subscriptions = Vec::new();+ let mut starting_after = None;+ loop {+ params.starting_after = starting_after.clone();+ let page = Subscription::list(&self.client, ¶ms)+ .await+ .map_err(payment)?;+ let has_more = page.has_more;+ let next = page.data.last().map(|subscription| subscription.id.clone());+ subscriptions.extend(page.data);+ if !has_more {+ break;+ }+ let next = next.ok_or_else(|| {+ BillingError::Payment(anyhow::anyhow!(+ "stripe returned an empty subscription page with more results"+ ))+ })?;+ if starting_after.as_ref() == Some(&next) {+ return Err(BillingError::Payment(anyhow::anyhow!(+ "stripe repeated a subscription page"+ )));+ }+ starting_after = Some(next);+ }+ Ok(subscriptions)+ }}fn payment(e: stripe::StripeError) -> BillingError {BillingError::Payment(e.into())}+fn no_matching_subscription() -> BillingError {+ BillingError::Payment(anyhow::anyhow!(+ "no active or trialing subscription matches the billing scope"+ ))+}+fn parse_customer(id: &str) -> Result<CustomerId> {id.parse::<CustomerId>().map_err(|e| BillingError::Payment(anyhow::anyhow!("invalid stripe customer id: {e}")))@@ -61,6 +125,132 @@ fn dollars(cents: i64) -> String {format!("${}.{:02}", cents / 100, cents % 100)}+#[derive(PartialEq, Eq)]+enum ChargeMethod {+ NoMatchingSubscription,+ StripeFallback,+ PaymentMethod(PaymentMethodId),+}++impl ChargeMethod {+ fn select_payment_method(+ &self,+ stored_method: Option<&PaymentMethodId>,+ ) -> Result<Option<PaymentMethodId>> {+ match self {+ Self::NoMatchingSubscription => match stored_method {+ Some(method) => Ok(Some(method.clone())),+ None => Err(no_matching_subscription()),+ },+ Self::StripeFallback => Ok(stored_method.cloned()),+ Self::PaymentMethod(method) => Ok(Some(method.clone())),+ }+ }++ fn has_matching_subscription(&self) -> bool {+ !matches!(self, Self::NoMatchingSubscription)+ }+}++fn customer_fallback(customer: &Customer) -> Option<PaymentMethodId> {+ customer+ .invoice_settings+ .as_ref()+ .and_then(|settings| payment_method_id(&settings.default_payment_method))+}++fn payment_method_id(+ method: &Option<Expandable<stripe::PaymentMethod>>,+) -> Option<PaymentMethodId> {+ method.as_ref().map(Expandable::id)+}++fn in_scope(subscription: &Subscription, scope: SubscriptionScope) -> bool {+ let team_id = subscription.metadata.get(TEAM_ID_METADATA_KEY);+ match scope {+ SubscriptionScope::Personal => team_id.is_none(),+ SubscriptionScope::Team { team_id: expected } => team_id+ .and_then(|raw| macro_uuid::string_to_uuid(raw).ok())+ .is_some_and(|parsed| parsed == expected),+ }+}++fn charge_method(+ fallback: Option<PaymentMethodId>,+ subscriptions: &[Subscription],+ scope: SubscriptionScope,+) -> Result<ChargeMethod> {+ let mut selected = ChargeMethod::NoMatchingSubscription;+ for subscription in subscriptions {+ if !matches!(+ subscription.status,+ SubscriptionStatus::Active | SubscriptionStatus::Trialing+ ) || !in_scope(subscription, scope)+ {+ continue;+ }+ let candidate = payment_method_id(&subscription.default_payment_method)+ .or_else(|| fallback.clone())+ .map_or(ChargeMethod::StripeFallback, ChargeMethod::PaymentMethod);+ if !selected.has_matching_subscription() {+ selected = candidate;+ } else if selected != candidate {+ return Err(BillingError::Payment(anyhow::anyhow!(+ "active subscriptions do not share a payment method"+ )));+ }+ }+ Ok(selected)+}++fn scope_stamp(scope: SubscriptionScope) -> String {+ match scope {+ SubscriptionScope::Personal => PERSONAL_SCOPE_STAMP.to_string(),+ SubscriptionScope::Team { team_id } => team_id.to_string(),+ }+}++fn stamped_scope(invoice: &Invoice) -> Result<Option<SubscriptionScope>> {+ let Some(raw) = invoice+ .metadata+ .as_ref()+ .and_then(|metadata| metadata.get(BILLING_SCOPE_METADATA_KEY))+ else {+ return Ok(None);+ };+ if raw == PERSONAL_SCOPE_STAMP {+ return Ok(Some(SubscriptionScope::Personal));+ }+ match macro_uuid::string_to_uuid(raw) {+ Ok(team_id) => Ok(Some(SubscriptionScope::Team { team_id })),+ Err(_) => Err(BillingError::Payment(anyhow::anyhow!(+ "overage invoice has a malformed billing scope"+ ))),+ }+}++#[derive(Serialize)]+struct UpdateInvoice<'a> {+ #[serde(skip_serializing_if = "Option::is_none")]+ default_payment_method: Option<&'a PaymentMethodId>,+ metadata: HashMap<String, String>,+}++impl<'a> UpdateInvoice<'a> {+ fn new(scope: SubscriptionScope, default_payment_method: Option<&'a PaymentMethodId>) -> Self {+ Self {+ default_payment_method,+ metadata: HashMap::from([(BILLING_SCOPE_METADATA_KEY.to_string(), scope_stamp(scope))]),+ }+ }+}++#[derive(Serialize)]+struct PayInvoice<'a> {+ #[serde(skip_serializing_if = "Option::is_none")]+ payment_method: Option<&'a PaymentMethodId>,+}+impl PaymentGateway for StripePaymentGateway {#[tracing::instrument(skip(self, request), fields(payer = %request.payer, cents = request.amount_cents), err)]async fn create_credit_checkout(&self, request: CreditCheckoutRequest) -> Result<String> {@@ -116,6 +306,7 @@ impl PaymentGateway for StripePaymentGateway {#[tracing::instrument(skip(self, request), fields(charge = %request.charge_id, cents = request.amount_cents), err)]async fn open_overage_invoice(&self, request: OverageChargeRequest) -> Result<String> {let customer = parse_customer(&request.customer_id)?;+ let live_method = self.resolve_charge_method(&customer, request.scope).await?;let key = format!("ai_overage:{}", request.charge_id);let metadata: HashMap<String, String> = HashMap::from([(@@ -130,11 +321,10 @@ impl PaymentGateway for StripePaymentGateway {// 1. An empty draft invoice that takes nothing else pending on the// customer, so it can never bill more than this one charge.- // `auto_advance` keeps Stripe's retry schedule on a declined card;- // the outcome arrives via webhook.+ // It cannot auto-finalize until routing and its line item are present.let mut invoice = CreateInvoice::new();invoice.customer = Some(customer.clone());- invoice.auto_advance = Some(true);+ invoice.auto_advance = Some(false);invoice.collection_method = Some(CollectionMethod::ChargeAutomatically);invoice.pending_invoice_items_behavior = Some(InvoicePendingInvoiceItemsBehavior::Exclude);invoice.description = Some("Macro AI usage beyond plan");@@ -142,6 +332,32 @@ impl PaymentGateway for StripePaymentGateway {let invoice = Invoice::create(&self.idempotent(format!("{key}:invoice")), invoice).await.map_err(payment)?;+ // Stripe replays the original create response. Read the invoice again+ // to observe routing written by an earlier attempt.+ let invoice = Invoice::retrieve(&self.client, &invoice.id, &[])+ .await+ .map_err(payment)?;+ // Finalization can collect before the caller persists this id. A retry+ // must recover the paid invoice instead of attempting a forbidden update.+ if invoice.status == Some(InvoiceStatus::Paid) {+ return Ok(invoice.id.to_string());+ }+ let invoice_scope = stamped_scope(&invoice)?;+ let scope = invoice_scope.unwrap_or(request.scope);+ let charge_method = if invoice_scope.is_some_and(|scope| scope != request.scope) {+ self.resolve_charge_method(&customer, scope).await?+ } else {+ live_method+ };+ let stored_method = payment_method_id(&invoice.default_payment_method);+ let method = charge_method.select_payment_method(stored_method.as_ref())?;+ self.client+ .post_form::<Invoice, _>(+ &format!("/invoices/{}", invoice.id),+ &UpdateInvoice::new(scope, method.as_ref()),+ )+ .await+ .map_err(payment)?;// 2. The line item, attached to that invoice rather than left pending// on the customer where another invoice could sweep it up.@@ -151,19 +367,9 @@ impl PaymentGateway for StripePaymentGateway {item.currency = Some(Currency::USD);item.description = Some(request.description.as_str());item.metadata = Some(metadata);- if let Err(e) = InvoiceItem::create(&self.idempotent(format!("{key}:item")), item).await {- // Nothing is owed on a draft with no lines; drop it so nothing else- // can finalize it. Best effort: a retry replays the same keys and- // lands on the same draft either way.- if let Err(delete_err) = Invoice::delete(&self.client, &invoice.id).await {- tracing::warn!(- error = ?delete_err,- invoice = %invoice.id,- "could not delete an empty overage draft invoice"- );- }- return Err(payment(e));- }+ InvoiceItem::create(&self.idempotent(format!("{key}:item")), item)+ .await+ .map_err(payment)?;// 3. Finalize so it is collectable now rather than in an hour.Invoice::finalize(@@ -180,17 +386,61 @@ impl PaymentGateway for StripePaymentGateway {}#[tracing::instrument(skip(self), fields(charge = %charge_id, invoice = %invoice_id), err)]- async fn pay_overage_invoice(&self, charge_id: Uuid, invoice_id: &str) -> Result<bool> {+ async fn pay_overage_invoice(+ &self,+ charge_id: Uuid,+ invoice_id: &str,+ scope: SubscriptionScope,+ ) -> Result<bool> {let invoice_id: InvoiceId = invoice_id.parse().map_err(|e| {BillingError::Payment(anyhow::anyhow!("invalid stripe invoice id: {e}"))})?;+ let invoice = Invoice::retrieve(&self.client, &invoice_id, &[])+ .await+ .map_err(payment)?;+ if invoice.status == Some(InvoiceStatus::Paid) {+ return Ok(true);+ }+ let invoice_scope = stamped_scope(&invoice)?;+ let scope = invoice_scope.unwrap_or(scope);+ let customer_id = invoice+ .customer+ .as_ref()+ .map(Expandable::id)+ .ok_or_else(|| {+ BillingError::Payment(anyhow::anyhow!("overage invoice has no customer"))+ })?;+ let charge_method = self.resolve_charge_method(&customer_id, scope).await?;+ let stored_method = payment_method_id(&invoice.default_payment_method);+ let method = charge_method.select_payment_method(stored_method.as_ref())?;+ if invoice.status == Some(InvoiceStatus::Open)+ && charge_method.has_matching_subscription()+ && (invoice_scope.is_none() || method.as_ref() != stored_method.as_ref())+ {+ // A repeated set converges. An idempotency key would replay the+ // previous card after the payer switches away and back.+ self.client+ .post_form::<Invoice, _>(+ &format!("/invoices/{invoice_id}"),+ &UpdateInvoice::new(scope, method.as_ref()),+ )+ .await+ .map_err(payment)?;+ }// Every attempt is its own request: replaying the first attempt's key// would replay its decline instead of trying the payer's (new) card.let key = format!("ai_overage:{charge_id}:pay:{}",Utc::now().timestamp_millis());- match Invoice::pay(&self.idempotent(key), &invoice_id).await {+ let pay = PayInvoice {+ payment_method: method.as_ref(),+ };+ match self+ .idempotent(key)+ .post_form::<Invoice, _>(&format!("/invoices/{invoice_id}/pay"), &pay)+ .await+ {Ok(invoice) => Ok(invoice.status == Some(InvoiceStatus::Paid)),Err(e) => {// A decline is a failed collection, not a failed request: the@@ -241,7 +491,12 @@ impl PaymentGateway for NoOpPaymentGateway {)))}- async fn pay_overage_invoice(&self, _charge_id: Uuid, _invoice_id: &str) -> Result<bool> {+ async fn pay_overage_invoice(+ &self,+ _charge_id: Uuid,+ _invoice_id: &str,+ _scope: SubscriptionScope,+ ) -> Result<bool> {Err(BillingError::Payment(anyhow::anyhow!("payments are not configured in this service")))diff --git a/crates/ai_billing/src/outbound/stripe_gateway/test.rs b/crates/ai_billing/src/outbound/stripe_gateway/test.rsnew file mode 100644index 0000000000..6d7f002255--- /dev/null+++ b/crates/ai_billing/src/outbound/stripe_gateway/test.rs@@ -0,0 +1,1006 @@+use super::*;+use serde::Serialize;+use serde::de::DeserializeOwned;+use serde_json::{Value, json};+use std::collections::HashMap;+use wiremock::matchers::{method, path, query_param, query_param_is_missing};+use wiremock::{Mock, MockServer, ResponseTemplate};++const CUSTOMER_ID: &str = "cus_test";+const STALE_PAYMENT_METHOD: &str = "pm_stale";+const CURRENT_PAYMENT_METHOD: &str = "pm_current";+const PERSONAL_PAYMENT_METHOD: &str = "pm_personal";+const TEAM_PAYMENT_METHOD: &str = "pm_team";+const INVOICE_ID: &str = "in_overage";+const TEAM_ID: Uuid = Uuid::from_u128(7);++#[tokio::test]+async fn open_overage_invoice_keeps_create_stable_and_updates_current_routing() {+ let invoice = stripe_response(&draft_invoice());+ let invoice_item = stripe_response(&draft_invoice_item());+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(+ &server,+ subscription_page(+ vec![stripe_response(&subscription(+ "sub_active",+ stripe::SubscriptionStatus::Active,+ Some(CURRENT_PAYMENT_METHOD),+ None,+ ))],+ false,+ ),+ )+ .await;+ Mock::given(method("POST"))+ .and(path("/v1/invoices"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/v1/invoiceitems"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice_item))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/finalize")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;++ gateway(&server)+ .open_overage_invoice(OverageChargeRequest {+ customer_id: CUSTOMER_ID.to_string(),+ charge_id: Uuid::from_u128(1),+ amount_cents: 2_500,+ description: "Macro AI usage beyond plan".to_string(),+ scope: SubscriptionScope::Personal,+ })+ .await+ .expect("open overage invoice");++ let requests = server.received_requests().await.expect("recorded requests");++ let create = post_request(&requests, "/v1/invoices");+ let create_body = body_str(create);+ assert_eq!(form_value(create_body, "default_payment_method"), None);+ assert_eq!(form_value(create_body, "subscription"), None);+ assert_eq!(form_value(create_body, "auto_advance"), Some("false"));+ assert_eq!(+ form_value(+ create_body,+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ None+ );+ assert_eq!(+ form_value(create_body, &format!("metadata[{PURPOSE_METADATA_KEY}]")),+ Some(PURPOSE_AI_OVERAGE)+ );+ assert_eq!(+ form_value(create_body, &format!("metadata[{CHARGE_METADATA_KEY}]")),+ Some("00000000-0000-0000-0000-000000000001")+ );+ assert_eq!(+ idempotency_key(create),+ Some("ai_overage:00000000-0000-0000-0000-000000000001:invoice")+ );++ let update = post_request(&requests, &format!("/v1/invoices/{INVOICE_ID}"));+ let update_body = body_str(update);+ assert_eq!(+ form_value(update_body, "default_payment_method"),+ Some(CURRENT_PAYMENT_METHOD)+ );+ assert_eq!(+ form_value(+ update_body,+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ Some(PERSONAL_SCOPE_STAMP)+ );+ assert_eq!(idempotency_key(update), None);++ let item = post_request(&requests, "/v1/invoiceitems");+ let item_body = body_str(item);+ assert_eq!(+ form_value(+ item_body,+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ None+ );+ assert_eq!(form_value(item_body, "default_payment_method"), None);+ assert_eq!(form_value(item_body, "subscription"), None);+ assert_eq!(+ form_value(item_body, &format!("metadata[{PURPOSE_METADATA_KEY}]")),+ Some(PURPOSE_AI_OVERAGE)+ );+ assert_eq!(+ form_value(item_body, &format!("metadata[{CHARGE_METADATA_KEY}]")),+ Some("00000000-0000-0000-0000-000000000001")+ );+ assert_eq!(+ idempotency_key(item),+ Some("ai_overage:00000000-0000-0000-0000-000000000001:item")+ );++ let create_at = request_position(&requests, "POST", "/v1/invoices");+ let retrieve_at = request_position(&requests, "GET", &format!("/v1/invoices/{INVOICE_ID}"));+ let update_at = request_position(&requests, "POST", &format!("/v1/invoices/{INVOICE_ID}"));+ let item_at = request_position(&requests, "POST", "/v1/invoiceitems");+ let finalize_at = request_position(+ &requests,+ "POST",+ &format!("/v1/invoices/{INVOICE_ID}/finalize"),+ );+ assert!(create_at < retrieve_at, "{requests:?}");+ assert!(retrieve_at < update_at, "{requests:?}");+ assert!(update_at < item_at, "{requests:?}");+ assert!(item_at < finalize_at, "{requests:?}");+}++#[tokio::test]+async fn pay_overage_invoice_updates_a_stale_open_invoice_before_paying() {+ let invoice = stripe_response(&open_invoice(Some(STALE_PAYMENT_METHOD), None));+ let paid = stripe_response(&paid_invoice(TEAM_PAYMENT_METHOD, None));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, both_subscriptions()).await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/pay")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;++ let paid_now = gateway(&server)+ .pay_overage_invoice(+ Uuid::from_u128(1),+ INVOICE_ID,+ SubscriptionScope::Team { team_id: TEAM_ID },+ )+ .await+ .expect("pay overage invoice");+ assert!(paid_now);++ let requests = server.received_requests().await.expect("recorded requests");+ let update_at = request_position(&requests, "POST", &format!("/v1/invoices/{INVOICE_ID}"));+ let pay_at = request_position(&requests, "POST", &format!("/v1/invoices/{INVOICE_ID}/pay"));+ assert!(update_at < pay_at);+ let update = &requests[update_at];+ let pay = &requests[pay_at];+ assert_eq!(idempotency_key(update), None);+ assert_eq!(+ form_value(body_str(update), "default_payment_method"),+ Some(TEAM_PAYMENT_METHOD)+ );+ assert_eq!(+ form_value(+ body_str(update),+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ Some("00000000-0000-0000-0000-000000000007")+ );+ assert!(idempotency_key(pay).is_some_and(|key| key.starts_with("ai_overage:")));+ assert_eq!(+ form_value(body_str(pay), "payment_method"),+ Some(TEAM_PAYMENT_METHOD)+ );+}++#[tokio::test]+async fn open_overage_invoice_rejects_distinct_subscription_methods_without_posting() {+ let server = MockServer::start().await;+ mount_customer(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions"))+ .and(query_param("customer", CUSTOMER_ID))+ .and(query_param_is_missing("starting_after"))+ .respond_with(ResponseTemplate::new(200).set_body_json(subscription_page(+ vec![stripe_response(&subscription(+ "sub_first",+ stripe::SubscriptionStatus::Active,+ Some(PERSONAL_PAYMENT_METHOD),+ None,+ ))],+ true,+ )))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions"))+ .and(query_param("customer", CUSTOMER_ID))+ .and(query_param("starting_after", "sub_first"))+ .respond_with(ResponseTemplate::new(200).set_body_json(subscription_page(+ vec![stripe_response(&subscription(+ "sub_second",+ stripe::SubscriptionStatus::Trialing,+ Some("pm_other"),+ None,+ ))],+ false,+ )))+ .mount(&server)+ .await;++ let error = gateway(&server)+ .open_overage_invoice(OverageChargeRequest {+ customer_id: CUSTOMER_ID.to_string(),+ charge_id: Uuid::from_u128(2),+ amount_cents: 2_500,+ description: "Macro AI usage beyond plan".to_string(),+ scope: SubscriptionScope::Personal,+ })+ .await+ .expect_err("distinct subscription methods");+ assert!(matches!(error, BillingError::Payment(_)));++ let requests = server.received_requests().await.expect("recorded requests");+ assert!(+ requests.iter().any(|request| request+ .url+ .query_pairs()+ .any(|(key, value)| { key == "starting_after" && value == "sub_first" })),+ "{requests:?}"+ );+ assert!(+ requests+ .iter()+ .all(|request| request.method.as_str() != "POST"),+ "{requests:?}"+ );+}++#[tokio::test]+async fn pay_overage_invoice_skips_the_update_when_the_open_invoice_already_matches() {+ let invoice = stripe_response(&open_invoice(+ Some(CURRENT_PAYMENT_METHOD),+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let paid = stripe_response(&paid_invoice(CURRENT_PAYMENT_METHOD, None));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(+ &server,+ subscription_page(+ vec![stripe_response(&subscription(+ "sub_active",+ stripe::SubscriptionStatus::Active,+ Some(CURRENT_PAYMENT_METHOD),+ None,+ ))],+ false,+ ),+ )+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/pay")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;++ let paid_now = gateway(&server)+ .pay_overage_invoice(Uuid::from_u128(3), INVOICE_ID, SubscriptionScope::Personal)+ .await+ .expect("pay overage invoice");+ assert!(paid_now);++ let requests = server.received_requests().await.expect("recorded requests");+ assert!(requests.iter().all(|request| {+ !(request.method.as_str() == "POST"+ && request.url.path() == format!("/v1/invoices/{INVOICE_ID}"))+ }));+ assert_eq!(+ form_value(+ post_body(&requests, &format!("/v1/invoices/{INVOICE_ID}/pay")),+ "payment_method"+ ),+ Some(CURRENT_PAYMENT_METHOD)+ );+}++#[tokio::test]+async fn open_overage_invoice_selects_the_subscription_for_the_requested_scope() {+ let invoice = stripe_response(&draft_invoice());+ let invoice_item = stripe_response(&draft_invoice_item());+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, both_subscriptions()).await;+ Mock::given(method("POST"))+ .and(path("/v1/invoices"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/v1/invoiceitems"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice_item))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/finalize")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;++ let gateway = gateway(&server);+ gateway+ .open_overage_invoice(charge(SubscriptionScope::Personal, 4))+ .await+ .expect("personal overage invoice");+ gateway+ .open_overage_invoice(charge(SubscriptionScope::Team { team_id: TEAM_ID }, 5))+ .await+ .expect("team overage invoice");++ let requests = server.received_requests().await.expect("recorded requests");+ let creates: Vec<_> = requests+ .iter()+ .filter(|request| request.method.as_str() == "POST" && request.url.path() == "/v1/invoices")+ .collect();+ assert_eq!(creates.len(), 2);+ for create in creates {+ let body = body_str(create);+ assert_eq!(form_value(body, "default_payment_method"), None, "{body}");+ assert_eq!(form_value(body, "subscription"), None, "{body}");+ assert_eq!(+ form_value(body, &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")),+ None,+ "{body}"+ );+ }++ let updates: Vec<_> = requests+ .iter()+ .filter(|request| {+ request.method.as_str() == "POST"+ && request.url.path() == format!("/v1/invoices/{INVOICE_ID}")+ })+ .collect();+ assert_eq!(updates.len(), 2);+ let personal = body_str(updates[0]);+ let team = body_str(updates[1]);+ assert_eq!(+ form_value(personal, "default_payment_method"),+ Some(PERSONAL_PAYMENT_METHOD),+ "{personal}"+ );+ assert_eq!(+ form_value(personal, &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")),+ Some(PERSONAL_SCOPE_STAMP),+ "{personal}"+ );+ assert_eq!(+ form_value(team, "default_payment_method"),+ Some(TEAM_PAYMENT_METHOD),+ "{team}"+ );+ assert_eq!(+ form_value(team, &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")),+ Some("00000000-0000-0000-0000-000000000007"),+ "{team}"+ );+}++#[tokio::test]+async fn open_overage_invoice_replay_uses_the_retrieved_scope_and_stored_method() {+ let cached_invoice = stripe_response(&draft_invoice());+ let mut current_invoice = draft_invoice();+ current_invoice.default_payment_method = Some(stripe::Expandable::Id(+ PERSONAL_PAYMENT_METHOD+ .parse()+ .expect("personal payment method"),+ ));+ current_invoice.metadata = Some(HashMap::from([(+ BILLING_SCOPE_METADATA_KEY.to_string(),+ PERSONAL_SCOPE_STAMP.to_string(),+ )]));+ let current_invoice = stripe_response(¤t_invoice);+ let invoice_item = stripe_response(&draft_invoice_item());+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, subscription_page(Vec::new(), false)).await;+ Mock::given(method("POST"))+ .and(path("/v1/invoices"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&cached_invoice))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(¤t_invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(¤t_invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/v1/invoiceitems"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice_item))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/finalize")))+ .respond_with(ResponseTemplate::new(200).set_body_json(¤t_invoice))+ .mount(&server)+ .await;++ gateway(&server)+ .open_overage_invoice(charge(SubscriptionScope::Team { team_id: TEAM_ID }, 7))+ .await+ .expect("replay overage invoice");++ let requests = server.received_requests().await.expect("recorded requests");+ let update_at = request_position(&requests, "POST", &format!("/v1/invoices/{INVOICE_ID}"));+ let item_at = request_position(&requests, "POST", "/v1/invoiceitems");+ let finalize_at = request_position(+ &requests,+ "POST",+ &format!("/v1/invoices/{INVOICE_ID}/finalize"),+ );+ assert!(update_at < item_at, "{requests:?}");+ assert!(item_at < finalize_at, "{requests:?}");+ let update = post_request(&requests, &format!("/v1/invoices/{INVOICE_ID}"));+ assert_eq!(+ form_value(body_str(update), "default_payment_method"),+ Some(PERSONAL_PAYMENT_METHOD)+ );+ assert_eq!(+ form_value(+ body_str(update),+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ Some(PERSONAL_SCOPE_STAMP)+ );+ assert_eq!(idempotency_key(update), None);+}++#[tokio::test]+async fn open_overage_invoice_replay_returns_an_already_paid_invoice() {+ let cached_invoice = stripe_response(&draft_invoice());+ let paid_invoice = stripe_response(&paid_invoice(+ CURRENT_PAYMENT_METHOD,+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(+ &server,+ subscription_page(+ vec![stripe_response(&subscription(+ "sub_active",+ stripe::SubscriptionStatus::Active,+ Some(CURRENT_PAYMENT_METHOD),+ None,+ ))],+ false,+ ),+ )+ .await;+ Mock::given(method("POST"))+ .and(path("/v1/invoices"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&cached_invoice))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid_invoice))+ .mount(&server)+ .await;++ let invoice_id = gateway(&server)+ .open_overage_invoice(charge(SubscriptionScope::Personal, 12))+ .await+ .expect("already paid invoice");+ assert_eq!(invoice_id, INVOICE_ID);++ let requests = server.received_requests().await.expect("recorded requests");+ assert_eq!(+ requests+ .iter()+ .filter(|request| request.method.as_str() == "POST")+ .map(|request| request.url.path())+ .collect::<Vec<_>>(),+ vec!["/v1/invoices"],+ "{requests:?}"+ );+ assert!(requests.iter().any(|request| {+ request.method.as_str() == "GET"+ && request.url.path() == format!("/v1/invoices/{INVOICE_ID}")+ }));+}++#[tokio::test]+async fn open_overage_invoice_leaves_a_safe_draft_when_scope_has_no_match() {+ let invoice = stripe_response(&draft_invoice());+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, team_subscription()).await;+ Mock::given(method("POST"))+ .and(path("/v1/invoices"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;++ let error = gateway(&server)+ .open_overage_invoice(charge(SubscriptionScope::Personal, 9))+ .await+ .expect_err("missing personal subscription");+ assert!(matches!(error, BillingError::Payment(_)));++ let requests = server.received_requests().await.expect("recorded requests");+ let create = post_request(&requests, "/v1/invoices");+ let body = body_str(create);+ assert_eq!(form_value(body, "default_payment_method"), None, "{body}");+ assert_eq!(form_value(body, "subscription"), None, "{body}");+ assert_eq!(form_value(body, "auto_advance"), Some("false"), "{body}");+ assert_eq!(+ form_value(body, &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")),+ None,+ "{body}"+ );+ assert_eq!(+ idempotency_key(create),+ Some("ai_overage:00000000-0000-0000-0000-000000000009:invoice")+ );+ assert_eq!(+ requests+ .iter()+ .filter(|request| request.method.as_str() == "POST")+ .count(),+ 1,+ "{requests:?}"+ );+ assert_eq!(+ requests+ .iter()+ .filter(|request| {+ request.method.as_str() == "GET"+ && request.url.path() == format!("/v1/invoices/{INVOICE_ID}")+ })+ .count(),+ 1,+ "{requests:?}"+ );+ let create_at = request_position(&requests, "POST", "/v1/invoices");+ let retrieve_at = request_position(&requests, "GET", &format!("/v1/invoices/{INVOICE_ID}"));+ assert!(create_at < retrieve_at, "{requests:?}");+}++#[tokio::test]+async fn pay_overage_invoice_keeps_a_stamped_scope_when_the_live_scope_differs() {+ let invoice = stripe_response(&open_invoice(+ Some(STALE_PAYMENT_METHOD),+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let paid = stripe_response(&paid_invoice(+ PERSONAL_PAYMENT_METHOD,+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, both_subscriptions()).await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/pay")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;++ let paid_now = gateway(&server)+ .pay_overage_invoice(+ Uuid::from_u128(6),+ INVOICE_ID,+ SubscriptionScope::Team { team_id: TEAM_ID },+ )+ .await+ .expect("pay stamped invoice");+ assert!(paid_now);++ let requests = server.received_requests().await.expect("recorded requests");+ let update = post_request(&requests, &format!("/v1/invoices/{INVOICE_ID}"));+ assert_eq!(+ form_value(body_str(update), "default_payment_method"),+ Some(PERSONAL_PAYMENT_METHOD)+ );+ assert_eq!(+ form_value(+ body_str(update),+ &format!("metadata[{BILLING_SCOPE_METADATA_KEY}]")+ ),+ Some(PERSONAL_SCOPE_STAMP)+ );+ assert_eq!(+ form_value(+ post_body(&requests, &format!("/v1/invoices/{INVOICE_ID}/pay")),+ "payment_method"+ ),+ Some(PERSONAL_PAYMENT_METHOD)+ );+}++#[tokio::test]+async fn pay_overage_invoice_preserves_a_stamped_personal_method_after_team_conversion() {+ let invoice = stripe_response(&open_invoice(+ Some(PERSONAL_PAYMENT_METHOD),+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let paid = stripe_response(&paid_invoice(+ PERSONAL_PAYMENT_METHOD,+ Some(PERSONAL_SCOPE_STAMP),+ ));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, team_subscription()).await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/pay")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;++ let paid_now = gateway(&server)+ .pay_overage_invoice(+ Uuid::from_u128(10),+ INVOICE_ID,+ SubscriptionScope::Team { team_id: TEAM_ID },+ )+ .await+ .expect("pay converted personal invoice");+ assert!(paid_now);++ let requests = server.received_requests().await.expect("recorded requests");+ assert!(requests.iter().all(|request| {+ !(request.method.as_str() == "POST"+ && request.url.path() == format!("/v1/invoices/{INVOICE_ID}"))+ }));+ let pay_body = post_body(&requests, &format!("/v1/invoices/{INVOICE_ID}/pay"));+ assert_eq!(+ form_value(pay_body, "payment_method"),+ Some(PERSONAL_PAYMENT_METHOD)+ );+ assert!(!pay_body.contains(STALE_PAYMENT_METHOD), "{pay_body}");+}++#[tokio::test]+async fn pay_overage_invoice_rejects_no_match_without_a_stored_method() {+ let invoice = stripe_response(&open_invoice(None, None));+ let server = MockServer::start().await;+ mount_customer_and_subscriptions(&server, team_subscription()).await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&invoice))+ .mount(&server)+ .await;++ let error = gateway(&server)+ .pay_overage_invoice(Uuid::from_u128(11), INVOICE_ID, SubscriptionScope::Personal)+ .await+ .expect_err("missing personal subscription and stored method");+ assert!(matches!(error, BillingError::Payment(_)));++ let requests = server.received_requests().await.expect("recorded requests");+ assert!(+ requests+ .iter()+ .all(|request| request.method.as_str() != "POST"),+ "{requests:?}"+ );+}++#[tokio::test]+async fn pay_overage_invoice_returns_when_the_invoice_is_already_paid() {+ let paid = stripe_response(&paid_invoice(STALE_PAYMENT_METHOD, None));+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;++ let paid_now = gateway(&server)+ .pay_overage_invoice(Uuid::from_u128(8), INVOICE_ID, SubscriptionScope::Personal)+ .await+ .expect("already paid invoice");+ assert!(paid_now);++ let requests = server.received_requests().await.expect("recorded requests");+ assert!(requests.iter().all(|request| {+ request.url.path() != format!("/v1/customers/{CUSTOMER_ID}")+ && request.url.path() != "/v1/subscriptions"+ && request.method.as_str() != "POST"+ }));+}++fn customer_with_stale_fallback() -> stripe::Customer {+ let stale: stripe::PaymentMethodId =+ STALE_PAYMENT_METHOD.parse().expect("stale payment method");+ stripe::Customer {+ id: CUSTOMER_ID.parse().expect("customer id"),+ invoice_settings: Some(stripe::InvoiceSettingCustomerSetting {+ default_payment_method: Some(stripe::Expandable::Id(stale)),+ ..Default::default()+ }),+ ..Default::default()+ }+}++fn subscription(+ id: &str,+ status: stripe::SubscriptionStatus,+ default_payment_method: Option<&str>,+ team_id: Option<&str>,+) -> stripe::Subscription {+ let mut metadata = HashMap::new();+ if let Some(team_id) = team_id {+ metadata.insert(TEAM_ID_METADATA_KEY.to_string(), team_id.to_string());+ }+ stripe::Subscription {+ id: id.parse().expect("subscription id"),+ customer: stripe::Expandable::Id(CUSTOMER_ID.parse().expect("customer id")),+ default_payment_method: default_payment_method+ .map(|method| stripe::Expandable::Id(method.parse().expect("payment method"))),+ status,+ currency: stripe::Currency::USD,+ metadata,+ items: stripe::List {+ data: vec![stripe::SubscriptionItem {+ id: format!("si_{id}").parse().expect("subscription item id"),+ ..Default::default()+ }],+ has_more: false,+ total_count: Some(1),+ url: "/v1/subscription_items".into(),+ },+ ..Default::default()+ }+}++fn open_invoice(default_payment_method: Option<&str>, scope: Option<&str>) -> stripe::Invoice {+ let method = default_payment_method+ .map(|method| stripe::Expandable::Id(method.parse().expect("invoice payment method")));+ let metadata = scope.map(|scope| {+ let mut metadata = HashMap::new();+ metadata.insert(BILLING_SCOPE_METADATA_KEY.to_string(), scope.to_string());+ metadata+ });+ stripe::Invoice {+ id: INVOICE_ID.parse().expect("invoice id"),+ customer: Some(stripe::Expandable::Id(+ CUSTOMER_ID.parse().expect("customer id"),+ )),+ default_payment_method: method,+ status: Some(stripe::InvoiceStatus::Open),+ metadata,+ ..Default::default()+ }+}++fn paid_invoice(default_payment_method: &str, scope: Option<&str>) -> stripe::Invoice {+ let mut invoice = open_invoice(Some(default_payment_method), scope);+ invoice.status = Some(stripe::InvoiceStatus::Paid);+ invoice+}++fn draft_invoice() -> stripe::Invoice {+ stripe::Invoice {+ id: INVOICE_ID.parse().expect("invoice id"),+ ..Default::default()+ }+}++fn draft_invoice_item() -> stripe::InvoiceItem {+ stripe::InvoiceItem {+ id: "ii_overage".parse().expect("invoice item id"),+ ..Default::default()+ }+}++fn gateway(server: &MockServer) -> StripePaymentGateway {+ let api_base = server.uri();+ StripePaymentGateway::new(Arc::new(stripe::Client::from_url(+ api_base.as_str(),+ "sk_test",+ )))+}++async fn mount_customer(server: &MockServer) {+ Mock::given(method("GET"))+ .and(path(format!("/v1/customers/{CUSTOMER_ID}")))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(stripe_response(&customer_with_stale_fallback())),+ )+ .mount(server)+ .await;+}++async fn mount_customer_and_subscriptions(server: &MockServer, subscriptions: Value) {+ mount_customer(server).await;+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions"))+ .and(query_param("customer", CUSTOMER_ID))+ .respond_with(ResponseTemplate::new(200).set_body_json(subscriptions))+ .mount(server)+ .await;+}++fn subscription_page(data: Vec<Value>, has_more: bool) -> Value {+ let total_count = data.len();+ json!({+ "data": data,+ "has_more": has_more,+ "total_count": total_count,+ "url": "/v1/subscriptions",+ })+}++fn both_subscriptions() -> Value {+ let team_id = TEAM_ID.to_string();+ subscription_page(+ vec![+ stripe_response(&subscription(+ "sub_personal",+ stripe::SubscriptionStatus::Active,+ Some(PERSONAL_PAYMENT_METHOD),+ None,+ )),+ stripe_response(&subscription(+ "sub_team",+ stripe::SubscriptionStatus::Active,+ Some(TEAM_PAYMENT_METHOD),+ Some(&team_id),+ )),+ ],+ false,+ )+}++fn team_subscription() -> Value {+ let team_id = TEAM_ID.to_string();+ subscription_page(+ vec![stripe_response(&subscription(+ "sub_team",+ stripe::SubscriptionStatus::Active,+ Some(TEAM_PAYMENT_METHOD),+ Some(&team_id),+ ))],+ false,+ )+}++fn charge(scope: SubscriptionScope, charge_id: u128) -> OverageChargeRequest {+ OverageChargeRequest {+ customer_id: CUSTOMER_ID.to_string(),+ charge_id: Uuid::from_u128(charge_id),+ amount_cents: 2_500,+ description: "Macro AI usage beyond plan".to_string(),+ scope,+ }+}++fn post_request<'a>(requests: &'a [wiremock::Request], path: &str) -> &'a wiremock::Request {+ requests+ .iter()+ .find(|request| request.method.as_str() == "POST" && request.url.path() == path)+ .unwrap_or_else(|| panic!("POST {path}"))+}++fn post_body<'a>(requests: &'a [wiremock::Request], path: &str) -> &'a str {+ body_str(post_request(requests, path))+}++fn request_position(requests: &[wiremock::Request], method: &str, path: &str) -> usize {+ requests+ .iter()+ .position(|request| request.method.as_str() == method && request.url.path() == path)+ .unwrap_or_else(|| panic!("{method} {path}"))+}++fn idempotency_key(request: &wiremock::Request) -> Option<&str> {+ request+ .headers+ .get("idempotency-key")+ .and_then(|value| value.to_str().ok())+}++fn body_str(request: &wiremock::Request) -> &str {+ std::str::from_utf8(&request.body).expect("utf-8 body")+}++fn form_value<'a>(body: &'a str, key: &str) -> Option<&'a str> {+ body.split('&').find_map(|pair| {+ let (name, value) = pair.split_once('=')?;+ (name == key).then_some(value)+ })+}++/// async-stripe omits `None` when serializing and then rejects that omission when reading a response.+fn stripe_response<T>(value: &T) -> Value+where+ T: Serialize + DeserializeOwned,+{+ let mut json = serde_json::to_value(value).expect("serialize stripe fixture");+ for _ in 0..256 {+ match serde_json::from_value::<T>(json.clone()) {+ Ok(_) => return json,+ Err(error) => {+ let message = error.to_string();+ let Some(field) = missing_field_name(&message) else {+ panic!("stripe fixture does not deserialize: {message}\n{json}");+ };+ fill_missing_field(&mut json, field);+ }+ }+ }+ panic!("stripe fixture still missing fields:\n{json}");+}++fn missing_field_name(message: &str) -> Option<&str> {+ let rest = message.strip_prefix("missing field `")?;+ rest.split_once('`').map(|(name, _)| name)+}++fn fill_missing_field(value: &mut Value, field: &str) {+ match value {+ Value::Object(map) => {+ if !map.contains_key(field) {+ map.insert(field.to_string(), Value::Null);+ }+ for child in map.values_mut() {+ fill_missing_field(child, field);+ }+ }+ Value::Array(items) => {+ for item in items {+ fill_missing_field(item, field);+ }+ }+ Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}+ }+}