Skip to main content

atp_client/
model.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
4/// Current balances for a user, including an optional team contribution.
5pub struct Balance {
6    /// ATP tenant/application identifier.
7    pub app_id: String,
8    /// Tenant-scoped external user identifier.
9    pub user_id: String,
10    /// Credits granted by the current subscription period.
11    pub subscription: u32,
12    /// Non-expiring credits purchased separately.
13    pub purchased: u32,
14    /// Active team whose shared pool is available to the user.
15    pub team_id: Option<String>,
16    #[serde(default)]
17    /// Credits currently available from the active team pool.
18    pub team_pool: u32,
19    /// Optimistic-concurrency version of the balance snapshot.
20    pub version: u64,
21}
22
23impl Balance {
24    /// Returns all immediately spendable credit buckets as a widened integer.
25    pub fn total(&self) -> u64 {
26        self.subscription as u64 + self.purchased as u64 + self.team_pool as u64
27    }
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31/// Entitlement and balance facts returned by the consolidated status endpoint.
32pub struct BillingStatus {
33    /// ATP tenant/application identifier.
34    pub app_id: String,
35    /// Tenant-scoped external user identifier.
36    pub user_id: String,
37    /// Product tier configured by the ATP tenant.
38    pub tier: String,
39    /// Subscription lifecycle state, such as `active` or `canceled`.
40    pub subscription_status: String,
41    /// Current credit-bucket snapshot.
42    pub balance: Balance,
43}
44
45impl BillingStatus {
46    /// Builds a zero-credit Free status for an explicitly configured login fallback.
47    pub fn free_fallback(user_id: impl Into<String>) -> Self {
48        let user_id = user_id.into();
49        Self {
50            app_id: String::new(),
51            user_id: user_id.clone(),
52            tier: "free".into(),
53            subscription_status: "degraded".into(),
54            balance: Balance {
55                user_id,
56                ..Balance::default()
57            },
58        }
59    }
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
63/// Immutable ledger fact describing one balance change.
64pub struct LedgerEntry {
65    /// Stable ATP transaction identifier.
66    pub tx_id: String,
67    /// ATP tenant/application identifier.
68    pub app_id: String,
69    /// User or team whose ledger owns this entry.
70    pub owner_id: String,
71    /// Transaction kind, such as debit, refund, grant, or adjustment.
72    pub tx_type: String,
73    /// Signed total change represented by this entry.
74    pub amount: i32,
75    /// Signed portion applied to subscription credits.
76    pub from_subscription: i32,
77    /// Signed portion applied to purchased credits.
78    pub from_purchased: i32,
79    /// Signed portion applied to the team pool.
80    pub from_team_pool: i32,
81    /// Tenant-supplied business operation identifier, when present.
82    pub related_id: Option<String>,
83    /// Human-readable audit description.
84    pub description: String,
85    /// RFC 3339 creation timestamp.
86    pub created_at: String,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
90/// Request to atomically consume credits for a business operation.
91pub struct DebitRequest {
92    /// Tenant-scoped user that owns or can access the credit buckets.
93    pub user_id: String,
94    /// Positive integer number of credits to consume.
95    pub amount: u32,
96    /// Stable business identifier used for tracing the charged work.
97    pub related_id: String,
98    /// Optional audit-safe description; do not include sensitive payloads.
99    pub description: Option<String>,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
103/// Result of a debit or refund, broken down by original credit source.
104pub struct DebitResult {
105    /// Stable ATP transaction identifier.
106    pub tx_id: String,
107    /// Total number of credits affected.
108    pub amount: u32,
109    /// Portion taken from or restored to subscription credits.
110    pub from_subscription: u32,
111    /// Portion taken from or restored to purchased credits.
112    pub from_purchased: u32,
113    /// Portion taken from or restored to the team pool.
114    pub from_team_pool: u32,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118/// Request to reverse one previously completed debit.
119pub struct RefundRequest {
120    /// Tenant-scoped user associated with the original debit.
121    pub user_id: String,
122    /// ATP transaction identifier returned by the original debit.
123    pub debit_tx_id: String,
124    /// Audit reason for the compensation.
125    pub reason: String,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129#[serde(tag = "kind", rename_all = "snake_case")]
130/// Product a user intends to buy through Stripe Checkout.
131pub enum Purchase {
132    /// Recurring subscription for a configured tier.
133    Subscription {
134        /// Tenant-defined tier identifier.
135        tier: String,
136    },
137    /// One-time purchase of a configured credit pack.
138    CreditPack {
139        /// Tenant-defined credit-pack identifier.
140        pack_id: String,
141    },
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145/// Server-to-server Checkout request including authenticated user identity.
146pub struct CheckoutRequest {
147    /// Tenant-scoped user purchasing the product.
148    pub user_id: String,
149    /// Customer email used for Stripe customer lookup or creation.
150    pub email: String,
151    /// Subscription tier or credit pack to purchase.
152    pub purchase: Purchase,
153    /// Allowlisted URL used after successful Checkout.
154    pub success_url: String,
155    /// Allowlisted URL used when Checkout is canceled.
156    pub cancel_url: String,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
160/// Browser-safe Checkout input for [`crate::BillingRouter`].
161///
162/// Identity is intentionally absent and is derived from the authenticated Principal.
163pub struct CheckoutInput {
164    /// Subscription tier or credit pack to purchase.
165    pub purchase: Purchase,
166    /// Allowlisted URL used after successful Checkout.
167    pub success_url: String,
168    /// Allowlisted URL used when Checkout is canceled.
169    pub cancel_url: String,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
173/// Newly created Stripe Checkout session.
174pub struct CheckoutResponse {
175    /// Stripe Checkout Session identifier.
176    pub session_id: String,
177    /// Short-lived URL to which the browser should be redirected.
178    pub checkout_url: String,
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
182/// Browser-safe Customer Portal input for [`crate::BillingRouter`].
183pub struct PortalInput {
184    /// Allowlisted URL to which Stripe returns the customer.
185    pub return_url: String,
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize)]
189/// Newly created Stripe Customer Portal session.
190pub struct PortalResponse {
191    /// Short-lived URL to which the browser should be redirected.
192    pub portal_url: String,
193}
194
195#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
196#[serde(rename_all = "snake_case")]
197/// Provenance of the status held by a [`BillingSnapshot`].
198pub enum SnapshotSource {
199    /// Loaded from ATP during this request.
200    Fresh,
201    /// Served within the configured fresh TTL.
202    Cache,
203    /// Served after fresh expiry because ATP was unavailable.
204    Stale,
205    /// Synthetic zero-credit Free state used for login continuity.
206    FreeFallback,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210/// Billing status plus cache/fallback provenance needed for safe decisions.
211pub struct BillingSnapshot {
212    /// Entitlement and credit facts.
213    pub status: BillingStatus,
214    /// Where this snapshot came from.
215    pub source: SnapshotSource,
216    /// True when the snapshot was returned under an outage fallback policy.
217    pub degraded: bool,
218}
219
220#[derive(Debug, Clone)]
221/// Ordered tier hierarchy used by Axum's minimum-tier guard.
222pub struct TierPolicy {
223    order: Vec<String>,
224}
225
226impl TierPolicy {
227    /// Creates a policy ordered from least to most privileged.
228    pub fn new(order: impl IntoIterator<Item = impl Into<String>>) -> Self {
229        Self {
230            order: order.into_iter().map(Into::into).collect(),
231        }
232    }
233
234    /// Returns whether `actual` is at least as privileged as `required`.
235    ///
236    /// Unknown tiers fail closed.
237    pub fn allows(&self, actual: &str, required: &str) -> bool {
238        let rank = |tier: &str| self.order.iter().position(|value| value == tier);
239        matches!((rank(actual), rank(required)), (Some(actual), Some(required)) if actual >= required)
240    }
241}
242
243impl Default for TierPolicy {
244    fn default() -> Self {
245        Self::new(["free", "pro", "team"])
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn default_tier_policy_is_monotonic() {
255        let policy = TierPolicy::default();
256        assert!(policy.allows("team", "pro"));
257        assert!(policy.allows("pro", "pro"));
258        assert!(!policy.allows("free", "pro"));
259        assert!(!policy.allows("unknown", "free"));
260    }
261
262    #[test]
263    fn cross_language_status_fixture_is_forward_compatible() {
264        let status: BillingStatus =
265            serde_json::from_str(include_str!("../../../sdk-conformance/billing-status.json"))
266                .unwrap();
267        assert_eq!(status.tier, "pro");
268        assert_eq!(status.balance.total(), 160);
269    }
270}