Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

48.7 KB
Raw Blame
//! Postgres adapter for the billing tables (`ai_billing_account`,
//! `ai_credit_ledger`, `ai_overage_charge`, `ai_credit_reload`,
//! `ai_billing_period_allowance`).
//!
//! Frozen allowances live in `ai_billing_period_allowance.included_cost_cents_by_user`
//! (cost cents). The legacy `included_cents_by_user` column predates the at-cost
//! model and is still written, with the same values, so a pre-cutover binary keeps
//! working during a deploy; it is never read here. A row whose cost column is
//! missing or does not match its roster was frozen by that older binary, and
//! every seat in it is priced at the configured allowance.

#[cfg(test)]
mod test;

use super::pg_funding_repo::{credit_commitments, lock_payer, postpaid_commitments};
use crate::domain::financial::legacy_cap_remaining;
use crate::domain::{
    AiPricing, AllowanceStore, AutoReloadThresholds, BillingError, BillingPeriod, BillingRepo,
    BillingSettings, CreditReloadKind, CreditReloadStatus, OpenPeriodStart, OverageChargeStatus,
    PendingCharge, PendingReload, PeriodAllowance, PeriodLedger, PurchaseReservation, ReloadState,
    ResolvedReload, Result, SeatAllowance, SeatGeneration, SettlementOutcome, SettlementPolicy,
    SettlementState, plan_reload, plan_settlement,
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use sqlx::PgPool;
use std::str::FromStr;

/// Postgres-backed [`BillingRepo`].
#[derive(Clone)]
pub struct PgBillingRepo {
    pool: PgPool,
    pricing: AiPricing,
}

impl PgBillingRepo {
    /// Create a repo over a connection pool. `pricing` prices frozen rosters
    /// that predate the per-seat cost column.
    pub fn new(pool: PgPool, pricing: AiPricing) -> Self {
        Self { pool, pricing }
    }
}

fn storage(e: sqlx::Error) -> BillingError {
    BillingError::Storage(e.into())
}

fn funding_storage(e: ai_usage::domain::financial::FinancialError) -> BillingError {
    BillingError::Storage(anyhow::anyhow!(e))
}

fn invalid_payer(e: impl std::fmt::Display) -> BillingError {
    BillingError::Storage(anyhow::anyhow!("invalid payer id: {e}"))
}

async fn reload_committed_cents(
    conn: &mut sqlx::PgConnection,
    payer: &str,
    month: BillingPeriod,
) -> Result<i64> {
    sqlx::query_scalar!(
        r#"
            SELECT COALESCE(SUM(amount_cents), 0)::bigint AS "spent!"
            FROM ai_credit_reload
            WHERE user_id = $1
              AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)
              -- A purchase whose collector died before Stripe saw it charged
              -- nothing; a paid webhook still books it by reload id.
              AND NOT (kind = 'purchase'
                       AND status = 'pending'
                       AND stripe_invoice_id IS NULL
                       AND updated_at < NOW() - INTERVAL '10 minutes')
              AND created_at >= $2
              AND created_at < $3
            "#,
        payer,
        month.start,
        month.end,
    )
    .fetch_one(conn)
    .await
    .map_err(storage)
}

async fn book_credit_reload(
    conn: &mut sqlx::PgConnection,
    payer: &MacroUserIdStr<'_>,
    amount_cents: i64,
    stripe_invoice_id: &str,
    kind: CreditReloadKind,
) -> Result<bool> {
    let id = macro_uuid::generate_uuid_v7();
    let note = match kind {
        CreditReloadKind::Automatic => "Automatic reload",
        CreditReloadKind::Purchase => "Credit purchase",
    };
    let result = sqlx::query!(
        r#"
        INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)
        VALUES ($1, $2, 'purchase', $3, $4, $5)
        ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING
        "#,
        id,
        payer.as_ref(),
        amount_cents,
        stripe_invoice_id,
        note,
    )
    .execute(conn)
    .await
    .map_err(storage)?;
    Ok(result.rows_affected() == 1)
}

impl BillingRepo for PgBillingRepo {
    async fn legacy_seats(
        &self,
        _payer: &MacroUserIdStr<'_>,
        period: crate::domain::BillingPeriod,
        mut seats: Vec<SeatAllowance>,
    ) -> Result<Vec<SeatAllowance>> {
        let users: Vec<_> = seats
            .iter()
            .map(|seat| seat.user.as_ref().to_owned())
            .collect();
        // Exclude even a historical binding to another payer: changing membership
        // must never route V1 analytics into a new owner's legacy settlement.
        let activated = sqlx::query_scalar!(
            "SELECT user_id FROM ai_billing_usage_period WHERE user_id = ANY($1)
             AND policy = 'public_allowance_v1' AND period_start < $3 AND period_end > $2
             AND NOT EXISTS (
                 SELECT 1 FROM ai_billing_plan_change AS change
                 WHERE change.user_id = ai_billing_usage_period.user_id
                   AND change.period_start = ai_billing_usage_period.period_start
                   AND change.changed_at < $3
                   AND (change.new_plan = 'max' OR change.previous_plan = 'max' AND change.changed_at > change.period_start)
             )",
            &users,
            period.start,
            period.end,
        )
        .fetch_all(&self.pool)
        .await
        .map_err(storage)?;
        seats.retain(|seat| !activated.iter().any(|user| user == seat.user.as_ref()));
        Ok(seats)
    }

    async fn record_plan_change(
        &self,
        user: &MacroUserIdStr<'_>,
        record: crate::domain::plan_change::RecordedPlanChange,
    ) -> Result<()> {
        let previous_plan = plan_name(record.change.from);
        let new_plan = plan_name(record.change.to);
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_plan_change
                (user_id, period_start, changed_at, previous_plan, new_plan,
                 previous_included_cost_cents, new_included_cost_cents)
            VALUES ($1, $2, $3, $4, $5, $6, $7)
            ON CONFLICT (user_id, period_start, changed_at, previous_plan, new_plan) DO NOTHING
            "#,
            user.as_ref(),
            record.change.period.start,
            record.change.at,
            previous_plan,
            new_plan,
            record.previous_included_cents,
            record.new_included_cents,
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn settings(&self, payer: &MacroUserIdStr<'_>) -> Result<BillingSettings> {
        let row = sqlx::query!(
            r#"
            SELECT overage_enabled, overage_limit_cents, overage_suspended_at,
                   auto_reload_minimum_cents, auto_reload_target_cents,
                   auto_reload_monthly_limit_cents, auto_reload_suspended_at,
                   period_start, period_end, seat_generation
            FROM ai_billing_account
            WHERE user_id = $1
            "#,
            payer.as_ref(),
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(storage)?;

        Ok(row
            .map(|r| BillingSettings {
                overage_enabled: r.overage_enabled,
                overage_limit_cents: r.overage_limit_cents,
                overage_suspended_at: r.overage_suspended_at,
                auto_reload: AutoReloadThresholds {
                    minimum_cents: r.auto_reload_minimum_cents,
                    target_cents: r.auto_reload_target_cents,
                    monthly_limit_cents: r.auto_reload_monthly_limit_cents,
                },
                auto_reload_suspended_at: r.auto_reload_suspended_at,
                period_anchor: r.period_start.zip(r.period_end),
                seat_generation: SeatGeneration::from_raw(r.seat_generation),
            })
            .unwrap_or_default())
    }

    async fn credit_reload_committed_cents(
        &self,
        payer: &MacroUserIdStr<'_>,
        month: BillingPeriod,
    ) -> Result<i64> {
        let mut conn = self.pool.acquire().await.map_err(storage)?;
        reload_committed_cents(&mut conn, payer.as_ref(), month).await
    }

    async fn update_overage(
        &self,
        payer: &MacroUserIdStr<'_>,
        enabled: bool,
        limit_cents: i64,
    ) -> Result<()> {
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id, overage_enabled, overage_limit_cents)
            VALUES ($1, $2, $3)
            ON CONFLICT (user_id) DO UPDATE
            SET overage_enabled = EXCLUDED.overage_enabled,
                overage_limit_cents = EXCLUDED.overage_limit_cents,
                overage_suspended_at = NULL,
                updated_at = NOW()
            "#,
            payer.as_ref(),
            enabled,
            limit_cents,
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn set_period(
        &self,
        payer: &MacroUserIdStr<'_>,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    ) -> Result<()> {
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id, period_start, period_end)
            VALUES ($1, $2, $3)
            ON CONFLICT (user_id) DO UPDATE
            SET period_start = EXCLUDED.period_start,
                period_end = EXCLUDED.period_end,
                updated_at = NOW()
            WHERE ai_billing_account.period_start IS NULL
               OR (EXCLUDED.period_start > ai_billing_account.period_start
                   AND EXCLUDED.period_start >= ai_billing_account.period_end)
               OR (EXCLUDED.period_start = ai_billing_account.period_start
                   AND EXCLUDED.period_end > EXCLUDED.period_start)
            "#,
            payer.as_ref(),
            start,
            end,
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn suspend_overage(&self, payer: &MacroUserIdStr<'_>) -> Result<()> {
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id, overage_suspended_at)
            VALUES ($1, NOW())
            ON CONFLICT (user_id) DO UPDATE
            SET overage_suspended_at = COALESCE(ai_billing_account.overage_suspended_at, NOW()),
                updated_at = NOW()
            "#,
            payer.as_ref(),
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn clear_overage_suspension(&self, payer: &MacroUserIdStr<'_>) -> Result<()> {
        sqlx::query!(
            r#"
            UPDATE ai_billing_account
            SET overage_suspended_at = NULL, updated_at = NOW()
            WHERE user_id = $1
            "#,
            payer.as_ref(),
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn free_allowance_bonus_cents(&self, user: &MacroUserIdStr<'_>) -> Result<i64> {
        sqlx::query_scalar!(
            r#"
            SELECT COALESCE(SUM(cost_cents), 0)::bigint AS "bonus!"
            FROM ai_free_allowance_bonus
            WHERE user_id = $1
            "#,
            user.as_ref(),
        )
        .fetch_one(&self.pool)
        .await
        .map_err(storage)
    }

    async fn credit_balance_cents(&self, payer: &MacroUserIdStr<'_>) -> Result<i64> {
        let balance = sqlx::query_scalar!(
            r#"
            SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
            FROM ai_credit_ledger
            WHERE user_id = $1
            "#,
            payer.as_ref(),
        )
        .fetch_one(&self.pool)
        .await
        .map_err(storage)?;
        Ok(balance)
    }

    async fn period_ledger(
        &self,
        payer: &MacroUserIdStr<'_>,
        period_start: DateTime<Utc>,
    ) -> Result<PeriodLedger> {
        let mut conn = self.pool.acquire().await.map_err(storage)?;
        read_period_ledger(&mut conn, payer.as_ref(), period_start).await
    }

    async fn period_allowance(
        &self,
        payer: &MacroUserIdStr<'_>,
        period_start: DateTime<Utc>,
    ) -> Result<Option<PeriodAllowance>> {
        let row = sqlx::query!(
            r#"
            SELECT billed_users as "billed_users!",
                   included_cost_cents_by_user
            FROM ai_billing_period_allowance
            WHERE user_id = $1 AND period_start = $2
            "#,
            payer.as_ref(),
            period_start,
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(storage)?;
        row.map(|r| {
            Ok(PeriodAllowance {
                seats: parse_seat_allowances(
                    r.billed_users,
                    r.included_cost_cents_by_user,
                    self.pricing,
                )?,
            })
        })
        .transpose()
    }

    async fn frozen_period_starts(
        &self,
        payer: &MacroUserIdStr<'_>,
        since: DateTime<Utc>,
        before: DateTime<Utc>,
    ) -> Result<Vec<DateTime<Utc>>> {
        sqlx::query_scalar!(
            r#"
            SELECT period_start
            FROM ai_billing_period_allowance
            WHERE user_id = $1
              AND period_start >= $2
              AND period_start < $3
            ORDER BY period_start
            "#,
            payer.as_ref(),
            since,
            before,
        )
        .fetch_all(&self.pool)
        .await
        .map_err(storage)
    }

    async fn store_open_allowance(
        &self,
        payer: &MacroUserIdStr<'_>,
        period: OpenPeriodStart,
        seats: &[SeatAllowance],
        observed: SeatGeneration,
    ) -> Result<AllowanceStore> {
        let billed_users: Vec<String> = seats
            .iter()
            .map(|seat| seat.user.as_ref().to_string())
            .collect();
        let included_cents_by_user: Vec<i64> =
            seats.iter().map(|seat| seat.included_cents).collect();
        let payer = payer.as_ref();
        let mut tx = self.pool.begin().await.map_err(storage)?;

        // Lock the payer account before the allowance row, same order as release.
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id) VALUES ($1)
            ON CONFLICT (user_id) DO NOTHING
            "#,
            payer,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        let generation = sqlx::query!(
            r#"
            SELECT seat_generation
            FROM ai_billing_account
            WHERE user_id = $1
            FOR UPDATE
            "#,
            payer,
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(storage)?
        .seat_generation;
        if SeatGeneration::from_raw(generation) != observed {
            tx.rollback().await.map_err(storage)?;
            return Ok(AllowanceStore::Conflict);
        }

        // The legacy column receives the same values so an older binary can
        // still read the row during a deploy; see the module docs.
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_period_allowance (
                user_id, period_start, billed_users, included_cents_by_user,
                included_cost_cents_by_user
            )
            VALUES ($1, $2, $3, $4, $4)
            ON CONFLICT (user_id, period_start) DO UPDATE
            SET billed_users = EXCLUDED.billed_users,
                included_cents_by_user = EXCLUDED.included_cents_by_user,
                included_cost_cents_by_user = EXCLUDED.included_cost_cents_by_user,
                updated_at = NOW()
            WHERE ai_billing_period_allowance.billed_users
                  IS DISTINCT FROM EXCLUDED.billed_users
               OR ai_billing_period_allowance.included_cost_cents_by_user
                  IS DISTINCT FROM EXCLUDED.included_cost_cents_by_user
            "#,
            payer,
            period.start(),
            &billed_users,
            &included_cents_by_user,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        tx.commit().await.map_err(storage)?;
        Ok(AllowanceStore::Stored)
    }

    async fn release_open_seat(
        &self,
        payer: &MacroUserIdStr<'_>,
        period: OpenPeriodStart,
        member: &MacroUserIdStr<'_>,
    ) -> Result<()> {
        let payer = payer.as_ref();
        let mut tx = self.pool.begin().await.map_err(storage)?;

        // Lock and bump the payer account before the allowance row, same order as store.
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id, seat_generation)
            VALUES ($1, 1)
            ON CONFLICT (user_id) DO UPDATE
            SET seat_generation = ai_billing_account.seat_generation + 1,
                updated_at = NOW()
            "#,
            payer,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;

        // A cost array that is missing or out of step with the roster (an older
        // binary refreshed the row) is dropped rather than excised positionally.
        sqlx::query!(
            r#"
            UPDATE ai_billing_period_allowance AS allowance
            SET billed_users = excised.users,
                included_cents_by_user = excised.cents,
                included_cost_cents_by_user = CASE
                    WHEN cardinality(allowance.included_cost_cents_by_user)
                         = cardinality(allowance.billed_users)
                    THEN excised.cost_cents
                END,
                updated_at = NOW()
            FROM (
                SELECT
                    COALESCE(
                        array_agg(seat.billed_user ORDER BY seat.ordinality)
                            FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),
                        ARRAY[]::text[]
                    )::text[] AS users,
                    COALESCE(
                        array_agg(seat.included_cents ORDER BY seat.ordinality)
                            FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),
                        ARRAY[]::bigint[]
                    )::bigint[] AS cents,
                    COALESCE(
                        array_agg(seat.cost_cents ORDER BY seat.ordinality)
                            FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),
                        ARRAY[]::bigint[]
                    )::bigint[] AS cost_cents
                FROM ai_billing_period_allowance AS src
                CROSS JOIN LATERAL unnest(
                    src.billed_users, src.included_cents_by_user, src.included_cost_cents_by_user
                ) WITH ORDINALITY AS seat(billed_user, included_cents, cost_cents, ordinality)
                WHERE src.user_id = $1
                  AND src.period_start = $2
            ) AS excised
            WHERE allowance.user_id = $1
              AND allowance.period_start = $2
              AND $3 = ANY (allowance.billed_users)
            "#,
            payer,
            period.start(),
            member.as_ref(),
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        tx.commit().await.map_err(storage)?;
        Ok(())
    }

    async fn record_credit_purchase(
        &self,
        payer: &MacroUserIdStr<'_>,
        amount_cents: i64,
        stripe_reference: &str,
    ) -> Result<bool> {
        let id = macro_uuid::generate_uuid_v7();
        let mut tx = self.pool.begin().await.map_err(storage)?;
        lock_payer(&mut tx, payer.as_ref())
            .await
            .map_err(funding_storage)?;
        let result = sqlx::query!(
            r#"
            INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)
            VALUES ($1, $2, 'purchase', $3, $4, 'Credit pack purchase')
            ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING
            "#,
            id,
            payer.as_ref(),
            amount_cents,
            stripe_reference,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        tx.commit().await.map_err(storage)?;
        Ok(result.rows_affected() == 1)
    }

    async fn apply_settlement(
        &self,
        payer: &MacroUserIdStr<'_>,
        period_start: DateTime<Utc>,
        chargeable_customer_cents: i64,
        policy: SettlementPolicy,
    ) -> Result<SettlementOutcome> {
        let payer = payer.as_ref();
        let mut tx = self.pool.begin().await.map_err(storage)?;

        // Serialize settlements per payer on the account row.
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id) VALUES ($1)
            ON CONFLICT (user_id) DO NOTHING
            "#,
            payer,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        let account = sqlx::query!(
            r#"
            SELECT overage_enabled, overage_limit_cents, overage_suspended_at
            FROM ai_billing_account
            WHERE user_id = $1
            FOR UPDATE
            "#,
            payer,
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(storage)?;

        let balance = sqlx::query_scalar!(
            r#"
            SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
            FROM ai_credit_ledger
            WHERE user_id = $1
            "#,
            payer,
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(storage)?;
        let commitments = credit_commitments(&mut tx, payer)
            .await
            .map_err(funding_storage)?;
        let balance = commitments
            .legacy_available_cents(balance)
            .map_err(funding_storage)?;
        let committed_postpaid = postpaid_commitments(&mut tx, payer, period_start)
            .await
            .map_err(funding_storage)?;
        let legacy_limit = legacy_cap_remaining(account.overage_limit_cents, committed_postpaid);
        let ledger = read_period_ledger(&mut tx, payer, period_start).await?;
        let overage_active = policy.overage_active
            && account.overage_enabled
            && account.overage_suspended_at.is_none()
            && account.overage_limit_cents > 0;

        let plan = plan_settlement(
            SettlementState {
                chargeable_customer_cents,
                credits_consumed_cents: ledger.credits_consumed_cents,
                overage_charged_cents: ledger.overage_charged_cents,
                credit_balance_cents: balance,
            },
            SettlementPolicy {
                overage_active,
                overage_limit_cents: legacy_limit,
                charge_threshold_cents: policy.charge_threshold_cents,
                period_ended: policy.period_ended,
            },
        );

        if plan.consume_credits_cents > 0 {
            sqlx::query!(
                r#"
                INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, period_start, note)
                VALUES ($1, $2, 'consumption', $3, $4, 'AI usage beyond plan allowance')
                "#,
                macro_uuid::generate_uuid_v7(),
                payer,
                -plan.consume_credits_cents,
                period_start,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
        }

        // A charge still owed from an earlier pass comes first, so a retry
        // reuses its id (and with it its Stripe idempotency keys and invoice)
        // instead of reserving a second charge for the same usage. A failed
        // charge with an invoice remains in the ledger because Stripe may
        // still collect it, and is retried whenever overage is active. A
        // failed charge without an invoice is excluded from the ledger and is
        // retried only when the new plan still covers its full amount.
        let owed = sqlx::query!(
            r#"
            SELECT id, amount_cents, stripe_invoice_id, status::text AS "status!"
            FROM ai_overage_charge
            WHERE user_id = $1
              AND period_start = $2
              AND accounting_policy = 'legacy'
              AND (
                status = 'failed'
                OR (
                  status = 'pending'
                  AND stripe_invoice_id IS NULL
                  AND updated_at < NOW() - INTERVAL '10 minutes'
                )
              )
            ORDER BY created_at
            FOR UPDATE
            "#,
            payer,
            period_start,
        )
        .fetch_all(&mut *tx)
        .await
        .map_err(storage)?;
        let orphaned = owed
            .iter()
            .find(|row| policy.overage_active && row.status == "pending");
        let retryable = owed.iter().find(|row| {
            row.status == "failed"
                && overage_active
                && (row.stripe_invoice_id.is_some()
                    || row.amount_cents <= plan.charge_overage_cents)
        });

        let pending_charge = if let Some(row) = orphaned {
            // Reserved but never collected (the collector died before it
            // opened an invoice). It already counts as covered; collect it.
            Some(PendingCharge {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id.clone(),
            })
        } else if let Some(row) = retryable {
            sqlx::query!(
                r#"
                UPDATE ai_overage_charge
                SET status = 'pending', updated_at = NOW()
                WHERE id = $1
                "#,
                row.id,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
            Some(PendingCharge {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id.clone(),
            })
        } else if plan.charge_overage_cents > 0 {
            let id = macro_uuid::generate_uuid_v7();
            sqlx::query!(
                r#"
                INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status)
                VALUES ($1, $2, $3, $4, 'pending')
                "#,
                id,
                payer,
                period_start,
                plan.charge_overage_cents,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
            Some(PendingCharge {
                id,
                amount_cents: plan.charge_overage_cents,
                stripe_invoice_id: None,
            })
        } else {
            None
        };

        tx.commit().await.map_err(storage)?;
        Ok(SettlementOutcome {
            consumed_credits_cents: plan.consume_credits_cents,
            pending_charge,
        })
    }

    async fn finish_overage_charge(
        &self,
        charge_id: Uuid,
        stripe_invoice_id: Option<&str>,
        status: OverageChargeStatus,
    ) -> Result<()> {
        sqlx::query!(
            r#"
            UPDATE ai_overage_charge
            SET stripe_invoice_id = COALESCE($2, stripe_invoice_id),
                status = ($3::text)::ai_overage_charge_status,
                updated_at = NOW()
            WHERE id = $1
            "#,
            charge_id,
            stripe_invoice_id,
            status.to_string(),
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn resolve_overage_invoice(
        &self,
        stripe_invoice_id: &str,
        status: OverageChargeStatus,
    ) -> Result<Option<MacroUserIdStr<'static>>> {
        // `paid` is terminal and re-reporting the current status changes
        // nothing, so a late or duplicate webhook cannot un-pay a charge or
        // count twice.
        let row = sqlx::query!(
            r#"
            UPDATE ai_overage_charge
            SET status = ($2::text)::ai_overage_charge_status, updated_at = NOW()
            WHERE stripe_invoice_id = $1
              AND status <> 'paid'
              AND status <> ($2::text)::ai_overage_charge_status
            RETURNING user_id
            "#,
            stripe_invoice_id,
            status.to_string(),
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(storage)?;
        row.map(|r| MacroUserIdStr::try_from(r.user_id).map_err(invalid_payer))
            .transpose()
    }

    async fn latest_charge_status(
        &self,
        payer: &MacroUserIdStr<'_>,
    ) -> Result<Option<OverageChargeStatus>> {
        let status = sqlx::query_scalar!(
            r#"
            SELECT status::text AS "status!"
            FROM ai_overage_charge
            WHERE user_id = $1
            ORDER BY created_at DESC, id DESC
            LIMIT 1
            "#,
            payer.as_ref(),
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(storage)?;
        status
            .map(|s| {
                OverageChargeStatus::from_str(&s).map_err(|e| {
                    BillingError::Storage(anyhow::anyhow!("unknown overage charge status {s}: {e}"))
                })
            })
            .transpose()
    }

    async fn update_auto_reload(
        &self,
        payer: &MacroUserIdStr<'_>,
        enabled: bool,
        overage_limit_cents: i64,
        thresholds: Option<&AutoReloadThresholds>,
    ) -> Result<()> {
        // A new row takes the defaults when no thresholds are given; an
        // existing row keeps what it has.
        let replace_thresholds = thresholds.is_some();
        let thresholds = thresholds.copied().unwrap_or_default();
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (
                user_id, overage_enabled, overage_limit_cents,
                auto_reload_minimum_cents, auto_reload_target_cents,
                auto_reload_monthly_limit_cents
            )
            VALUES ($1, $2, $3, $4, $5, $6)
            ON CONFLICT (user_id) DO UPDATE
            SET overage_enabled = EXCLUDED.overage_enabled,
                overage_limit_cents = EXCLUDED.overage_limit_cents,
                auto_reload_minimum_cents = CASE
                    WHEN $7 THEN EXCLUDED.auto_reload_minimum_cents
                    ELSE ai_billing_account.auto_reload_minimum_cents
                END,
                auto_reload_target_cents = CASE
                    WHEN $7 THEN EXCLUDED.auto_reload_target_cents
                    ELSE ai_billing_account.auto_reload_target_cents
                END,
                auto_reload_monthly_limit_cents = CASE
                    WHEN $7 THEN EXCLUDED.auto_reload_monthly_limit_cents
                    ELSE ai_billing_account.auto_reload_monthly_limit_cents
                END,
                overage_suspended_at = NULL,
                auto_reload_suspended_at = NULL,
                updated_at = NOW()
            "#,
            payer.as_ref(),
            enabled,
            overage_limit_cents,
            thresholds.minimum_cents,
            thresholds.target_cents,
            thresholds.monthly_limit_cents,
            replace_thresholds,
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn reserve_credit_reload(
        &self,
        payer: &MacroUserIdStr<'_>,
        period_start: DateTime<Utc>,
        chargeable_customer_cents: i64,
        now: DateTime<Utc>,
    ) -> Result<Option<PendingReload>> {
        let payer = payer.as_ref();
        let mut tx = self.pool.begin().await.map_err(storage)?;

        // Serialize reloads with settlements and purchases on the account row.
        lock_payer(&mut tx, payer).await.map_err(funding_storage)?;
        let account = sqlx::query!(
            r#"
            SELECT overage_enabled, overage_limit_cents, overage_suspended_at,
                   auto_reload_minimum_cents, auto_reload_target_cents,
                   auto_reload_monthly_limit_cents, auto_reload_suspended_at
            FROM ai_billing_account
            WHERE user_id = $1
            "#,
            payer,
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(storage)?;
        let settings = BillingSettings {
            overage_enabled: account.overage_enabled,
            overage_limit_cents: account.overage_limit_cents,
            overage_suspended_at: account.overage_suspended_at,
            auto_reload: AutoReloadThresholds {
                minimum_cents: account.auto_reload_minimum_cents,
                target_cents: account.auto_reload_target_cents,
                monthly_limit_cents: account.auto_reload_monthly_limit_cents,
            },
            auto_reload_suspended_at: account.auto_reload_suspended_at,
            ..Default::default()
        };
        if !settings.auto_reload_active() {
            tx.rollback().await.map_err(storage)?;
            return Ok(None);
        }

        // A reload still owed from an earlier pass comes first, so the retry
        // reuses its id (and with it its Stripe idempotency keys and invoice)
        // instead of reserving a second reload while the first can still
        // collect. A pending reload whose collector died before opening an
        // invoice is handed back as is. A failed reload that reached Stripe
        // keeps its invoice open (`auto_advance`) and is retried on that same
        // invoice now that the payer has re-enabled reloads. Any other
        // pending reload is still with Stripe and blocks a new one until the
        // webhook resolves it.
        let open = sqlx::query!(
            r#"
            SELECT id, amount_cents, stripe_invoice_id, status::text AS "status!",
                   (status = 'pending'
                    AND stripe_invoice_id IS NULL
                    AND updated_at < NOW() - INTERVAL '10 minutes') AS "orphaned!"
            FROM ai_credit_reload
            WHERE user_id = $1
              AND kind = 'automatic'
              AND (status = 'pending'
                   OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))
            ORDER BY created_at
            FOR UPDATE
            "#,
            payer,
        )
        .fetch_all(&mut *tx)
        .await
        .map_err(storage)?;
        if let Some(row) = open.iter().find(|row| row.orphaned) {
            tx.commit().await.map_err(storage)?;
            return Ok(Some(PendingReload {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id.clone(),
            }));
        }
        if let Some(row) = open.iter().find(|row| row.status == "failed") {
            sqlx::query!(
                r#"
                UPDATE ai_credit_reload
                SET status = 'pending', updated_at = NOW()
                WHERE id = $1
                "#,
                row.id,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
            tx.commit().await.map_err(storage)?;
            return Ok(Some(PendingReload {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id.clone(),
            }));
        }
        if !open.is_empty() {
            tx.rollback().await.map_err(storage)?;
            return Ok(None);
        }

        // Same balance as settlement: ledger sum less V1 funding commitments.
        let balance = sqlx::query_scalar!(
            r#"
            SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
            FROM ai_credit_ledger
            WHERE user_id = $1
            "#,
            payer,
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(storage)?;
        let commitments = credit_commitments(&mut tx, payer)
            .await
            .map_err(funding_storage)?;
        let balance = commitments
            .legacy_available_cents(balance)
            .map_err(funding_storage)?;
        let ledger = read_period_ledger(&mut tx, payer, period_start).await?;
        let covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;
        let uncovered_cents = (chargeable_customer_cents - covered).max(0);
        // A failed reload that reached Stripe may still be collected by its
        // retries, so it counts against the limit like a pending one.
        let month = BillingPeriod::calendar_month(now);
        let spent_this_month_cents = reload_committed_cents(&mut tx, payer, month).await?;

        let amount_cents = plan_reload(
            ReloadState {
                credit_balance_cents: balance,
                uncovered_cents,
                spent_this_month_cents,
            },
            &settings.auto_reload,
        );
        let Some(amount_cents) = amount_cents else {
            tx.rollback().await.map_err(storage)?;
            return Ok(None);
        };

        let id = macro_uuid::generate_uuid_v7();
        sqlx::query!(
            r#"
            INSERT INTO ai_credit_reload (id, user_id, amount_cents, status)
            VALUES ($1, $2, $3, 'pending')
            "#,
            id,
            payer,
            amount_cents,
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        tx.commit().await.map_err(storage)?;
        Ok(Some(PendingReload {
            id,
            amount_cents,
            stripe_invoice_id: None,
        }))
    }

    #[tracing::instrument(skip(self), err)]
    async fn reserve_credit_purchase(
        &self,
        payer: &MacroUserIdStr<'_>,
        purchased_by: &MacroUserIdStr<'_>,
        amount_cents: i64,
        monthly_limit_cents: Option<i64>,
        now: DateTime<Utc>,
    ) -> Result<PurchaseReservation> {
        let payer = payer.as_ref();
        let mut tx = self.pool.begin().await.map_err(storage)?;
        // Serialize purchases with reloads and settlements on the account row.
        lock_payer(&mut tx, payer).await.map_err(funding_storage)?;
        let open = sqlx::query!(
            r#"
            SELECT id, amount_cents, stripe_invoice_id, status::text AS "status!",
                   (status = 'pending'
                    AND stripe_invoice_id IS NULL
                    AND updated_at < NOW() - INTERVAL '10 minutes') AS "orphaned!"
            FROM ai_credit_reload
            WHERE user_id = $1
              AND kind = 'purchase'
              AND (status = 'pending'
                   OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))
            ORDER BY created_at
            FOR UPDATE
            "#,
            payer,
        )
        .fetch_all(&mut *tx)
        .await
        .map_err(storage)?;
        // A purchase whose collector died before Stripe saw it charged nothing.
        for row in open.iter().filter(|row| row.orphaned) {
            sqlx::query!(
                r#"
                UPDATE ai_credit_reload
                SET status = 'failed', updated_at = NOW()
                WHERE id = $1
                "#,
                row.id,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
        }
        if let Some(row) = open.iter().find(|row| row.status == "failed") {
            sqlx::query!(
                r#"
                UPDATE ai_credit_reload
                SET status = 'pending', updated_at = NOW()
                WHERE id = $1
                "#,
                row.id,
            )
            .execute(&mut *tx)
            .await
            .map_err(storage)?;
            tx.commit().await.map_err(storage)?;
            return Ok(PurchaseReservation::Retry(PendingReload {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id.clone(),
            }));
        }
        if open.iter().any(|row| !row.orphaned) {
            tx.commit().await.map_err(storage)?;
            return Ok(PurchaseReservation::InProgress);
        }

        if let Some(limit) = monthly_limit_cents {
            let month = BillingPeriod::calendar_month(now);
            let committed = reload_committed_cents(&mut tx, payer, month).await?;
            let remaining_cents = (limit - committed).max(0);
            if amount_cents > remaining_cents {
                tx.commit().await.map_err(storage)?;
                return Ok(PurchaseReservation::OverLimit { remaining_cents });
            }
        }

        let id = macro_uuid::generate_uuid_v7();
        sqlx::query!(
            r#"
            INSERT INTO ai_credit_reload (id, user_id, amount_cents, status, kind, purchased_by)
            VALUES ($1, $2, $3, 'pending', 'purchase', $4)
            "#,
            id,
            payer,
            amount_cents,
            purchased_by.as_ref(),
        )
        .execute(&mut *tx)
        .await
        .map_err(storage)?;
        tx.commit().await.map_err(storage)?;
        Ok(PurchaseReservation::New(PendingReload {
            id,
            amount_cents,
            stripe_invoice_id: None,
        }))
    }

    async fn declined_credit_purchases(
        &self,
        payer: &MacroUserIdStr<'_>,
    ) -> Result<Vec<PendingReload>> {
        let rows = sqlx::query!(
            r#"
            SELECT id, amount_cents, stripe_invoice_id
            FROM ai_credit_reload
            WHERE user_id = $1
              AND kind = 'purchase'
              AND status = 'failed'
              AND stripe_invoice_id IS NOT NULL
            ORDER BY created_at
            "#,
            payer.as_ref(),
        )
        .fetch_all(&self.pool)
        .await
        .map_err(storage)?;
        Ok(rows
            .into_iter()
            .map(|row| PendingReload {
                id: row.id,
                amount_cents: row.amount_cents,
                stripe_invoice_id: row.stripe_invoice_id,
            })
            .collect())
    }

    async fn void_credit_purchase(&self, reload_id: Uuid) -> Result<()> {
        sqlx::query!(
            r#"
            UPDATE ai_credit_reload
            SET status = 'failed', stripe_invoice_id = NULL, updated_at = NOW()
            WHERE id = $1 AND kind = 'purchase' AND status <> 'paid'
            "#,
            reload_id,
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn finish_credit_reload(
        &self,
        reload_id: Uuid,
        stripe_invoice_id: Option<&str>,
        status: CreditReloadStatus,
    ) -> Result<()> {
        sqlx::query!(
            r#"
            UPDATE ai_credit_reload
            SET stripe_invoice_id = COALESCE($2, stripe_invoice_id),
                status = ($3::text)::ai_credit_reload_status,
                updated_at = NOW()
            WHERE id = $1
            "#,
            reload_id,
            stripe_invoice_id,
            status.to_string(),
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }

    async fn record_credit_reload(
        &self,
        payer: &MacroUserIdStr<'_>,
        amount_cents: i64,
        stripe_invoice_id: &str,
        kind: CreditReloadKind,
    ) -> Result<bool> {
        let mut tx = self.pool.begin().await.map_err(storage)?;
        lock_payer(&mut tx, payer.as_ref())
            .await
            .map_err(funding_storage)?;
        let booked =
            book_credit_reload(&mut tx, payer, amount_cents, stripe_invoice_id, kind).await?;
        tx.commit().await.map_err(storage)?;
        Ok(booked)
    }

    async fn resolve_credit_reload_invoice(
        &self,
        stripe_invoice_id: &str,
        reload_id: Option<Uuid>,
        status: CreditReloadStatus,
    ) -> Result<Option<ResolvedReload>> {
        // A paid invoice whose id never reached its row (the collector died
        // between Stripe finalizing it and recording it) is matched by the
        // reload id stamped on the invoice, so the charge is still booked.
        let adopt = status == CreditReloadStatus::Paid;
        let mut tx = self.pool.begin().await.map_err(storage)?;
        let Some(payer) = sqlx::query_scalar!(
            r#"
            SELECT user_id FROM ai_credit_reload
            WHERE stripe_invoice_id = $1
               OR ($3 AND id = $2 AND stripe_invoice_id IS NULL)
            ORDER BY (stripe_invoice_id = $1) DESC NULLS LAST
            LIMIT 1
            "#,
            stripe_invoice_id,
            reload_id,
            adopt,
        )
        .fetch_optional(&mut *tx)
        .await
        .map_err(storage)?
        else {
            return Ok(None);
        };
        let payer = MacroUserIdStr::try_from(payer).map_err(invalid_payer)?;
        // Match the account-before-reload lock order used by reload reservation.
        lock_payer(&mut tx, payer.as_ref())
            .await
            .map_err(funding_storage)?;
        // `paid` is terminal and re-reporting the current status changes
        // nothing, so a late or duplicate webhook cannot un-pay a reload or
        // book its credits twice.
        let Some(row) = sqlx::query!(
            r#"
            UPDATE ai_credit_reload
            SET status = ($2::text)::ai_credit_reload_status,
                stripe_invoice_id = $1,
                updated_at = NOW()
            WHERE (stripe_invoice_id = $1
                   OR ($4 AND id = $3 AND stripe_invoice_id IS NULL))
              AND status <> 'paid'
              AND status <> ($2::text)::ai_credit_reload_status
            RETURNING user_id, amount_cents, kind::text AS "kind!"
            "#,
            stripe_invoice_id,
            status.to_string(),
            reload_id,
            adopt,
        )
        .fetch_optional(&mut *tx)
        .await
        .map_err(storage)?
        else {
            return Ok(None);
        };
        let resolved = ResolvedReload {
            payer: MacroUserIdStr::try_from(row.user_id).map_err(invalid_payer)?,
            amount_cents: row.amount_cents,
            kind: CreditReloadKind::from_str(&row.kind).map_err(|e| {
                BillingError::Storage(anyhow::anyhow!(
                    "unknown credit reload kind {}: {e}",
                    row.kind
                ))
            })?,
        };
        if status == CreditReloadStatus::Paid {
            book_credit_reload(
                &mut tx,
                &resolved.payer,
                resolved.amount_cents,
                stripe_invoice_id,
                resolved.kind,
            )
            .await?;
        }
        tx.commit().await.map_err(storage)?;
        Ok(Some(resolved))
    }

    async fn suspend_auto_reload(&self, payer: &MacroUserIdStr<'_>) -> Result<()> {
        sqlx::query!(
            r#"
            INSERT INTO ai_billing_account (user_id, auto_reload_suspended_at)
            VALUES ($1, NOW())
            ON CONFLICT (user_id) DO UPDATE
            SET auto_reload_suspended_at
                    = COALESCE(ai_billing_account.auto_reload_suspended_at, NOW()),
                updated_at = NOW()
            "#,
            payer.as_ref(),
        )
        .execute(&self.pool)
        .await
        .map_err(storage)?;
        Ok(())
    }
}

/// Sum consumption and charges that can still collect for a period, on any
/// connection so the settlement transaction can reuse it under its lock.
async fn read_period_ledger(
    conn: &mut sqlx::PgConnection,
    payer: &str,
    period_start: DateTime<Utc>,
) -> Result<PeriodLedger> {
    let consumed = sqlx::query_scalar!(
        r#"
        SELECT COALESCE(-SUM(delta_cents), 0)::bigint AS "consumed!"
        FROM ai_credit_ledger
        WHERE user_id = $1 AND kind = 'consumption' AND period_start = $2
          AND funding_invocation_id IS NULL
        "#,
        payer,
        period_start,
    )
    .fetch_one(&mut *conn)
    .await
    .map_err(storage)?;
    let charged = sqlx::query_scalar!(
        r#"
        SELECT COALESCE(SUM(amount_cents), 0)::bigint AS "charged!"
        FROM ai_overage_charge
        WHERE user_id = $1
          AND period_start = $2
          AND accounting_policy = 'legacy'
          AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)
        "#,
        payer,
        period_start,
    )
    .fetch_one(&mut *conn)
    .await
    .map_err(storage)?;
    Ok(PeriodLedger {
        credits_consumed_cents: consumed,
        overage_charged_cents: charged,
    })
}

/// Pair a frozen roster with its cost-cent allowances. A missing or mismatched
/// cost array means an older binary wrote the row; every seat then gets the
/// configured Premium allowance, which is what that binary's seats were all
/// entitled to (it predates per-plan allowances).
fn parse_seat_allowances(
    billed_users: Vec<String>,
    included_cost_cents_by_user: Option<Vec<i64>>,
    pricing: AiPricing,
) -> Result<Vec<SeatAllowance>> {
    let included_cents_by_user = match included_cost_cents_by_user {
        Some(cents) if cents.len() == billed_users.len() => cents,
        _ => vec![pricing.included_allowance_cents(); billed_users.len()],
    };
    billed_users
        .into_iter()
        .zip(included_cents_by_user)
        .map(|(id, included_cents)| {
            let user = MacroUserIdStr::try_from(id).map_err(|e| {
                BillingError::Storage(anyhow::anyhow!("invalid billed user id: {e}"))
            })?;
            Ok(SeatAllowance {
                user,
                included_cents,
            })
        })
        .collect()
}

fn plan_name(plan: crate::domain::PlanTier) -> &'static str {
    match plan {
        crate::domain::PlanTier::Free => "free",
        crate::domain::PlanTier::Premium => "premium",
        crate::domain::PlanTier::Max => "max",
    }
}