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.

25.9 KB
Raw Blame
//! HTTP API for AI billing: the payer's position, overage settings, credit
//! purchases, the plan catalog, and the internal settle and subscription-period
//! hooks.

use crate::domain::{
    AUTO_RELOAD_DEFAULT_MINIMUM_CENTS, AUTO_RELOAD_DEFAULT_TARGET_CENTS,
    AUTO_RELOAD_TARGET_MAX_CENTS, AiPricing, AutoReloadThresholds, BillingError, BillingService,
    CREDIT_PACKS_CENTS, CreditPurchaseStatus, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,
    PaymentGateway, PlanTier, SubscriptionScope, UsageSnapshot,
};
use axum::{
    Json, Router,
    extract::{FromRef, Query, State},
    http::{HeaderMap, StatusCode, Uri, header::ORIGIN},
    response::{IntoResponse, Response},
    routing::{get, patch, post},
};
use chrono::{DateTime, Utc};
use macro_authorization::{
    InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
    UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use teams::domain::model::SeatPlan;
use utoipa::{IntoParams, ToSchema};

/// Error response body.
#[derive(Debug, Serialize, ToSchema)]
pub struct AiBillingErrorBody {
    /// Human-readable error description.
    pub error: String,
}

/// One plan in the catalog.
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PlanCatalogEntry {
    /// The tier.
    pub tier: PlanTier,
    /// Monthly subscription price per seat, cents.
    pub monthly_price_cents: i64,
    /// Included AI per seat per period, in cents at provider cost. For the
    /// free plan this is its monthly hard cap.
    pub included_ai_cents_per_seat: i64,
    /// Whether a new purchase or plan move may pick this plan today.
    pub purchasable: bool,
    /// Monthly automatic reload limit a payer on this plan starts from,
    /// cents. Absent for plans that cannot reload.
    pub auto_reload_default_monthly_limit_cents: Option<i64>,
}

/// The plan catalog and the knobs the billing UI offers.
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PlanCatalogResponse {
    /// Every plan, cheapest first. Clients read allowances from here rather
    /// than hard-coding them; `purchasable` marks the plans a user can buy.
    pub plans: Vec<PlanCatalogEntry>,
    /// Credit packs a payer may buy, cents.
    pub credit_packs_cents: Vec<i64>,
    /// Smallest allowed overage cap, cents.
    pub overage_limit_min_cents: i64,
    /// Largest allowed overage cap, cents.
    pub overage_limit_max_cents: i64,
    /// Largest allowed automatic reload target, cents.
    pub auto_reload_target_max_cents: i64,
    /// Thresholds automatic reload starts from before the payer sets their own.
    pub auto_reload_defaults: AutoReloadDefaults,
}

/// The automatic reload thresholds a payer starts from.
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AutoReloadDefaults {
    /// Balance below which a reload fires, cents.
    pub minimum_balance_cents: i64,
    /// Balance a reload tops up to, cents.
    pub target_balance_cents: i64,
}

/// Request body for [`update_overage_handler`].
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateOverageRequest {
    /// Bill usage past allowance and credits.
    pub enabled: bool,
    /// Per-period cap on overage spend, cents. Required when enabling.
    #[serde(default)]
    pub limit_cents: i64,
}

/// Request body for [`update_auto_reload_handler`].
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAutoReloadRequest {
    /// Purchase prepaid credits automatically using the payer's card.
    pub enabled: bool,
    /// Reload once the balance drops below this, cents. Must be positive.
    pub minimum_balance_cents: i64,
    /// Reload the balance back up to this, cents. At least $0.50 above the
    /// minimum and no more than the catalog's `auto_reload_target_max_cents`.
    pub target_balance_cents: i64,
    /// Most to reload per calendar month, cents. Omit or `null` for no limit.
    /// Must be at least the catalog's `overage_limit_min_cents` (legacy name).
    #[serde(default)]
    pub monthly_spend_limit_cents: Option<i64>,
}

impl From<&UpdateAutoReloadRequest> for AutoReloadThresholds {
    fn from(req: &UpdateAutoReloadRequest) -> Self {
        Self {
            minimum_cents: req.minimum_balance_cents,
            target_cents: req.target_balance_cents,
            monthly_limit_cents: req.monthly_spend_limit_cents,
        }
    }
}

/// Request body for [`create_credit_checkout_handler`].
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreditCheckoutRequestBody {
    /// Pack size, cents; one of the catalog's `credit_packs_cents`.
    pub amount_cents: i64,
    /// Where Stripe returns the user after paying. Must be an `https` URL
    /// on the origin the request came from.
    pub success_url: String,
    /// Where Stripe returns the user on cancel. Same rules as `success_url`.
    pub cancel_url: String,
}

/// Why a Checkout return URL was refused.
#[derive(Debug, PartialEq, Eq)]
enum ReturnUrlError {
    Unparseable,
    Scheme,
    Credentials,
    Origin,
}

impl std::fmt::Display for ReturnUrlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ReturnUrlError::Unparseable => "is not an absolute URL",
            ReturnUrlError::Scheme => "must use https (http only for localhost)",
            ReturnUrlError::Credentials => "must not carry credentials",
            ReturnUrlError::Origin => "must be on the origin the request came from",
        })
    }
}

/// Stripe sends the payer wherever these URLs point after Checkout, so they
/// must not be an open redirect: absolute `https` (plain `http` only for a
/// local frontend), no embedded credentials, and, when the browser told us
/// where the request came from, that same origin.
fn validate_return_url(url: &str, request_origin: Option<&str>) -> Result<(), ReturnUrlError> {
    let uri: Uri = url.parse().map_err(|_| ReturnUrlError::Unparseable)?;
    let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else {
        return Err(ReturnUrlError::Unparseable);
    };
    if authority.as_str().contains('@') {
        return Err(ReturnUrlError::Credentials);
    }
    let host = authority.host();
    let local = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "[::1]";
    if !(scheme == "https" || (scheme == "http" && local)) {
        return Err(ReturnUrlError::Scheme);
    }
    if let Some(origin) = request_origin.filter(|o| *o != "null") {
        // Browsers omit the default port from `Origin`; match that.
        let default_port = if scheme == "https" { "443" } else { "80" };
        let expected = match authority.port_u16().map(|p| p.to_string()) {
            Some(port) if port != default_port => format!("{scheme}://{host}:{port}"),
            _ => format!("{scheme}://{host}"),
        };
        if !origin.eq_ignore_ascii_case(&expected) {
            return Err(ReturnUrlError::Origin);
        }
    }
    Ok(())
}

/// Validate both return URLs of a checkout request, naming the offending
/// field in the error so the client can surface it.
fn validate_return_urls(
    req: &CreditCheckoutRequestBody,
    headers: &HeaderMap,
) -> Result<(), AiBillingErrorBody> {
    let origin = headers.get(ORIGIN).and_then(|v| v.to_str().ok());
    for (name, url) in [
        ("successUrl", &req.success_url),
        ("cancelUrl", &req.cancel_url),
    ] {
        if let Err(e) = validate_return_url(url, origin) {
            return Err(AiBillingErrorBody {
                error: format!("{name} {e}"),
            });
        }
    }
    Ok(())
}

/// Response for [`create_credit_checkout_handler`].
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreditCheckoutResponse {
    /// The hosted Checkout URL to redirect to.
    pub url: String,
}

/// Request body for [`settle_handler`].
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SettleRequest {
    /// Any user billed to the payer to settle.
    pub user_id: String,
}

/// Query for [`subscription_period_handler`].
#[derive(Debug, Deserialize, IntoParams)]
#[into_params(parameter_in = Query)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionPeriodQuery {
    /// The payer's Stripe customer.
    pub customer_id: String,
    /// The team whose subscription to read. Absent for the personal subscription.
    pub team_id: Option<Uuid>,
}

/// Response for [`subscription_period_handler`].
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionPeriodResponse {
    /// First instant of the period.
    pub start: DateTime<Utc>,
    /// First instant after the period.
    pub end: DateTime<Utc>,
}

fn scope_from_query(team_id: Option<Uuid>) -> SubscriptionScope {
    match team_id {
        Some(team_id) => SubscriptionScope::Team { team_id },
        None => SubscriptionScope::Personal,
    }
}

/// Router state: the billing service, the payment gateway the internal
/// subscription-period read uses, the configured pricing the catalog
/// publishes, and the authorization state the extractors need.
pub struct AiBillingRouterState<B, P, Auth> {
    /// The billing service.
    pub service: Arc<B>,
    /// The payment gateway that answers subscription-period reads.
    pub payments: Arc<P>,
    /// The pricing the host composed the billing service with.
    pub pricing: AiPricing,
    /// Authorization state for the request extractors.
    pub authorization_state: MacroAuthorizationState<Auth>,
}

impl<B, P, Auth> Clone for AiBillingRouterState<B, P, Auth> {
    fn clone(&self) -> Self {
        Self {
            service: self.service.clone(),
            payments: self.payments.clone(),
            pricing: self.pricing,
            authorization_state: self.authorization_state.clone(),
        }
    }
}

impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for AiPricing {
    fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {
        state.pricing
    }
}

impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for Arc<B> {
    fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {
        state.service.clone()
    }
}

impl<B, P, Auth> FromRef<AiBillingRouterState<B, P, Auth>> for MacroAuthorizationState<Auth> {
    fn from_ref(state: &AiBillingRouterState<B, P, Auth>) -> Self {
        state.authorization_state.clone()
    }
}

/// Build the AI billing router.
pub fn ai_billing_router<B, P, Auth, S>(state: AiBillingRouterState<B, P, Auth>) -> Router<S>
where
    B: BillingService,
    P: PaymentGateway,
    Auth: MacroAuthorizationService,
    S: Send + Sync + Clone + 'static,
{
    Router::new()
        .route("/ai-billing/summary", get(get_summary_handler::<B, Auth>))
        .route("/ai-billing/plans", get(get_plans_handler))
        .route(
            "/ai-billing/overage",
            patch(update_overage_handler::<B, Auth>),
        )
        .route(
            "/ai-billing/auto-reload",
            patch(update_auto_reload_handler::<B, Auth>),
        )
        .route(
            "/ai-billing/credits/checkout",
            post(create_credit_checkout_handler::<B, Auth>),
        )
        .route(
            "/ai-billing/credits/purchase",
            post(purchase_credits_handler::<B, Auth>),
        )
        .route(
            "/internal/ai-billing/settle",
            post(settle_handler::<B, Auth>),
        )
        .route(
            "/internal/ai-billing/subscription-period",
            get(subscription_period_handler::<B, P, Auth>),
        )
        .with_state(state)
}

fn error_response(e: BillingError) -> Response {
    let status = match &e {
        BillingError::NotPayer => StatusCode::FORBIDDEN,
        BillingError::FreePlan => StatusCode::PAYMENT_REQUIRED,
        BillingError::InvalidCreditAmount
        | BillingError::InvalidOverageLimit
        | BillingError::DirectUsageBillingDisabled
        | BillingError::InvalidAutoReload(_)
        | BillingError::NoStripeCustomer => StatusCode::BAD_REQUEST,
        BillingError::CreditLimitExceeded { .. } | BillingError::PurchaseInProgress => {
            StatusCode::CONFLICT
        }
        BillingError::Payment(_) | BillingError::Storage(_) | BillingError::Entitlement(_) => {
            tracing::error!(error = ?e, "ai billing request failed");
            StatusCode::INTERNAL_SERVER_ERROR
        }
    };
    let error = if status == StatusCode::INTERNAL_SERVER_ERROR {
        "internal error".to_string()
    } else {
        e.to_string()
    };
    (status, Json(AiBillingErrorBody { error })).into_response()
}

/// The caller's current-period AI usage, credits, and overage settings.
///
/// Runs a settlement first so the position reflects any credits or overage
/// that were waiting to be booked.
#[utoipa::path(
    get,
    path = "/ai-billing/summary",
    operation_id = "get_ai_billing_summary",
    responses(
        (status = 200, description = "Current-period position", body = UsageSnapshot),
        (status = 401, description = "Unauthorized"),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn get_summary_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Response {
    let user_id = &user.authorization.user.macro_user_id;
    if let Err(e) = service.settle(user_id).await {
        // Collection problems show up in the snapshot; don't fail the read.
        tracing::warn!(error = ?e, "settlement before summary failed");
    }
    match service.snapshot(user_id).await {
        Ok(snapshot) => Json(snapshot).into_response(),
        Err(e) => error_response(e),
    }
}

/// The plan catalog, credit packs, overage cap bounds, and automatic reload
/// defaults and bounds.
#[utoipa::path(
    get,
    path = "/ai-billing/plans",
    operation_id = "get_ai_billing_plans",
    responses(
        (status = 200, description = "Plan catalog", body = PlanCatalogResponse),
    ),
    tag = "ai_billing"
)]
pub async fn get_plans_handler(State(pricing): State<AiPricing>) -> Json<PlanCatalogResponse> {
    Json(PlanCatalogResponse {
        plans: [PlanTier::Free, PlanTier::Premium, PlanTier::Max]
            .into_iter()
            .map(|tier| PlanCatalogEntry {
                tier,
                monthly_price_cents: tier.monthly_price_cents(),
                included_ai_cents_per_seat: tier.included_ai_cents_per_seat(pricing),
                purchasable: SeatPlan::PURCHASABLE
                    .into_iter()
                    .any(|plan| PlanTier::from(plan) == tier),
                auto_reload_default_monthly_limit_cents: tier
                    .default_auto_reload_monthly_limit_cents(),
            })
            .collect(),
        credit_packs_cents: CREDIT_PACKS_CENTS.to_vec(),
        overage_limit_min_cents: OVERAGE_LIMIT_MIN_CENTS,
        overage_limit_max_cents: OVERAGE_LIMIT_MAX_CENTS,
        auto_reload_target_max_cents: AUTO_RELOAD_TARGET_MAX_CENTS,
        auto_reload_defaults: AutoReloadDefaults {
            minimum_balance_cents: AUTO_RELOAD_DEFAULT_MINIMUM_CENTS,
            target_balance_cents: AUTO_RELOAD_DEFAULT_TARGET_CENTS,
        },
    })
}

/// Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.
#[utoipa::path(
    patch,
    path = "/ai-billing/overage",
    operation_id = "update_ai_billing_overage",
    request_body = UpdateOverageRequest,
    responses(
        (status = 200, description = "Updated position", body = UsageSnapshot),
        (status = 400, description = "Invalid limit", body = AiBillingErrorBody),
        (status = 401, description = "Unauthorized"),
        (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
        (status = 403, description = "Only the payer may change billing", body = AiBillingErrorBody),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn update_overage_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(req): Json<UpdateOverageRequest>,
) -> Response {
    match service
        .update_overage(
            &user.authorization.user.macro_user_id,
            req.enabled,
            req.limit_cents,
        )
        .await
    {
        Ok(snapshot) => Json(snapshot).into_response(),
        Err(e) => error_response(e),
    }
}

/// Turn automatic credit reloads on with the given
/// thresholds, or off. Payer only. Enabling settles right away, so a balance
/// already under the minimum reloads immediately.
#[utoipa::path(
    patch,
    path = "/ai-billing/auto-reload",
    operation_id = "update_ai_billing_auto_reload",
    request_body = UpdateAutoReloadRequest,
    responses(
        (status = 200, description = "Updated position", body = UsageSnapshot),
        (status = 400, description = "Invalid thresholds", body = AiBillingErrorBody),
        (status = 401, description = "Unauthorized"),
        (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
        (status = 403, description = "Only the payer may change billing", body = AiBillingErrorBody),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id))]
pub async fn update_auto_reload_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(req): Json<UpdateAutoReloadRequest>,
) -> Response {
    match service
        .update_auto_reload(
            &user.authorization.user.macro_user_id,
            req.enabled,
            AutoReloadThresholds::from(&req),
        )
        .await
    {
        Ok(snapshot) => Json(snapshot).into_response(),
        Err(e) => error_response(e),
    }
}

/// Request body for [`purchase_credits_handler`].
#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreditPurchaseRequestBody {
    /// One of the catalog's credit packs, cents.
    pub amount_cents: i64,
}

/// Response for [`purchase_credits_handler`].
#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreditPurchaseResponse {
    /// Whether the card on file paid.
    pub status: CreditPurchaseStatus,
    /// Amount charged, cents: the requested pack, unless an earlier declined
    /// purchase that Stripe collected in the meantime was booked instead.
    pub amount_cents: i64,
    /// The caller's position after the purchase. Absent when it could not be
    /// read; the purchase still happened, so refetch the summary instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot: Option<UsageSnapshot>,
}

/// Buy a credit pack now, charged to the payer's card on file. Any paid team
/// member may buy, within the team's monthly credit limit.
#[utoipa::path(
    post,
    path = "/ai-billing/credits/purchase",
    operation_id = "purchase_ai_credits",
    request_body = CreditPurchaseRequestBody,
    responses(
        (status = 200, description = "Purchase outcome and updated position", body = CreditPurchaseResponse),
        (status = 400, description = "Invalid pack or no payment account", body = AiBillingErrorBody),
        (status = 401, description = "Unauthorized"),
        (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
        (status = 409, description = "Over the monthly credit limit, or an earlier purchase is still processing", body = AiBillingErrorBody),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id, cents = req.amount_cents))]
pub async fn purchase_credits_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(req): Json<CreditPurchaseRequestBody>,
) -> Response {
    let user_id = &user.authorization.user.macro_user_id;
    let purchase = match service.purchase_credits(user_id, req.amount_cents).await {
        Ok(purchase) => purchase,
        Err(e) => return error_response(e),
    };
    // A failed read must not hide a completed purchase: reporting an error
    // here would invite the buyer to pay again.
    let snapshot = service
        .snapshot(user_id)
        .await
        .inspect_err(|e| tracing::warn!(error = ?e, "snapshot after credit purchase failed"))
        .ok();
    Json(CreditPurchaseResponse {
        status: purchase.status,
        amount_cents: purchase.amount_cents,
        snapshot,
    })
    .into_response()
}

/// Start a Stripe Checkout for a credit pack. Payer only.
#[utoipa::path(
    post,
    path = "/ai-billing/credits/checkout",
    operation_id = "create_ai_credit_checkout",
    request_body = CreditCheckoutRequestBody,
    responses(
        (status = 200, description = "Checkout URL", body = CreditCheckoutResponse),
        (status = 400, description = "Invalid pack, untrusted return URL, or no payment account", body = AiBillingErrorBody),
        (status = 401, description = "Unauthorized"),
        (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),
        (status = 403, description = "Only the payer may buy credits", body = AiBillingErrorBody),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, user, req), fields(user_id = %user.authorization.user.macro_user_id, cents = req.amount_cents))]
pub async fn create_credit_checkout_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    headers: HeaderMap,
    Json(req): Json<CreditCheckoutRequestBody>,
) -> Response {
    if let Err(body) = validate_return_urls(&req, &headers) {
        return (StatusCode::BAD_REQUEST, Json(body)).into_response();
    }
    match service
        .create_credit_checkout(
            &user.authorization.user.macro_user_id,
            req.amount_cents,
            req.success_url,
            req.cancel_url,
        )
        .await
    {
        Ok(url) => Json(CreditCheckoutResponse { url }).into_response(),
        Err(e) => error_response(e),
    }
}

/// Settle a payer's AI billing. Internal services only; called by the usage
/// recorder in other services when a payer has usage past their allowance.
#[utoipa::path(
    post,
    path = "/internal/ai-billing/settle",
    operation_id = "settle_ai_billing",
    request_body = SettleRequest,
    responses(
        (status = 204, description = "Settled"),
        (status = 400, description = "Invalid user id", body = AiBillingErrorBody),
        (status = 401, description = "Unauthorized"),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(service, _internal), fields(user_id = %req.user_id))]
pub async fn settle_handler<B: BillingService, Auth: MacroAuthorizationService>(
    State(service): State<Arc<B>>,
    _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
    Json(req): Json<SettleRequest>,
) -> Response {
    let user_id = match MacroUserIdStr::try_from(req.user_id) {
        Ok(id) => id,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(AiBillingErrorBody {
                    error: format!("invalid user id: {e}"),
                }),
            )
                .into_response();
        }
    };
    match service.settle(&user_id).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        // A declined card is reported through the payer's snapshot, not to
        // the internal caller.
        Err(BillingError::Payment(_) | BillingError::NoStripeCustomer) => {
            StatusCode::NO_CONTENT.into_response()
        }
        Err(e) => error_response(e),
    }
}

/// The current period of a Stripe customer's non-canceled subscription in the
/// personal or team scope, preferring an active or trialing one. Internal
/// services only; the document cognition service reads it when a payer's stored
/// period is missing or ended.
#[utoipa::path(
    get,
    path = "/internal/ai-billing/subscription-period",
    operation_id = "get_ai_billing_subscription_period",
    params(SubscriptionPeriodQuery),
    responses(
        (status = 200, description = "Current subscription period", body = SubscriptionPeriodResponse),
        (status = 204, description = "No non-canceled subscription in scope"),
        (status = 401, description = "Unauthorized"),
        (status = 500, description = "Internal server error", body = AiBillingErrorBody),
    ),
    tag = "ai_billing"
)]
#[tracing::instrument(skip(state, _internal))]
pub async fn subscription_period_handler<B, P, Auth>(
    State(state): State<AiBillingRouterState<B, P, Auth>>,
    _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
    Query(query): Query<SubscriptionPeriodQuery>,
) -> Response
where
    B: BillingService,
    P: PaymentGateway,
    Auth: MacroAuthorizationService,
{
    match state
        .payments
        .subscription_period(&query.customer_id, scope_from_query(query.team_id))
        .await
    {
        Ok(Some(period)) => Json(SubscriptionPeriodResponse {
            start: period.start,
            end: period.end,
        })
        .into_response(),
        Ok(None) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => error_response(e),
    }
}

#[cfg(test)]
mod test;