Skip to main content

fauna_api/
billing.rs

1use serde::de::DeserializeOwned;
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::error::{Error, Result};
6use crate::http::{client, encode, ok};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub struct PaymentMethod {
11    pub brand: String,
12    pub last4: String,
13    pub exp_month: u32,
14    pub exp_year: u32,
15}
16
17#[derive(Debug, Clone, Serialize)]
18#[serde(rename_all = "camelCase")]
19pub struct AutoReload {
20    pub enabled: bool,
21    pub threshold: f64,
22    pub target: f64,
23    pub monthly_cap: f64,
24    pub monthly_spent: f64,
25    pub status: String,
26    pub available: bool,
27}
28
29#[derive(Debug, Clone, Serialize)]
30#[serde(rename_all = "camelCase")]
31pub struct AutoReloadUpdate {
32    pub enabled: bool,
33    pub threshold: f64,
34    pub target: f64,
35    pub monthly_cap: f64,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "lowercase")]
40pub enum TransactionKind {
41    Manual,
42    Automatic,
43    Subscription,
44    Grant,
45}
46
47#[derive(Debug, Clone, Serialize)]
48#[serde(rename_all = "camelCase")]
49pub struct Transaction {
50    pub id: String,
51    pub kind: TransactionKind,
52    pub amount: f64,
53    pub status: String,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub failure_message: Option<String>,
56    pub created_at: String,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub completed_at: Option<String>,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "lowercase")]
63pub enum Plan {
64    Free,
65    Premium,
66    Enterprise,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(rename_all = "camelCase")]
71pub struct Subscription {
72    pub plan: Plan,
73    pub status: String,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub period_end: Option<String>,
76    pub cancel_at_period_end: bool,
77}
78
79/// The free plan: `credit` is the dollars of credit it gives each month.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct FreePlan {
82    pub credit: f64,
83}
84
85/// Premium: `price` in `currency` each `interval`, and `credit`, the dollars of
86/// credit each paid invoice gives.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct PremiumPlan {
89    pub price: f64,
90    pub currency: String,
91    pub interval: String,
92    pub credit: f64,
93}
94
95/// What each plan gives and what Premium costs.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct Plans {
98    pub free: FreePlan,
99    pub premium: PremiumPlan,
100}
101
102#[derive(Debug, Clone, Serialize)]
103#[serde(rename_all = "camelCase")]
104pub struct Summary {
105    pub balance: f64,
106    pub currency: String,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub payment_method: Option<PaymentMethod>,
109    pub auto_reload: AutoReload,
110    pub subscription: Subscription,
111    pub recent_transactions: Vec<Transaction>,
112}
113
114#[derive(Deserialize)]
115#[serde(rename_all = "camelCase")]
116struct WireSummary {
117    balance_micros: f64,
118    currency: String,
119    #[serde(default)]
120    payment_method: Option<PaymentMethod>,
121    auto_reload: Value,
122    subscription: Subscription,
123    recent_transactions: Vec<Value>,
124}
125
126impl AutoReload {
127    pub fn from_json(json: &Value) -> AutoReload {
128        let number = |key: &str| json[key].as_f64().unwrap_or(0.0);
129        AutoReload {
130            enabled: json["enabled"].as_bool().unwrap_or(false),
131            threshold: number("thresholdMicros") / 1_000_000.0,
132            target: number("targetMicros") / 1_000_000.0,
133            monthly_cap: number("monthlyCapCents") / 100.0,
134            monthly_spent: number("monthlySpentCents") / 100.0,
135            status: json["status"].as_str().unwrap_or_default().to_string(),
136            available: json["available"] == Value::Bool(true),
137        }
138    }
139}
140
141impl Transaction {
142    pub fn from_json(json: &Value) -> Transaction {
143        let text = |key: &str| json[key].as_str().map(str::to_string);
144        Transaction {
145            id: text("id").unwrap_or_default(),
146            kind: serde_json::from_value(json["kind"].clone()).unwrap_or(TransactionKind::Manual),
147            amount: json["amountCents"].as_f64().unwrap_or(0.0) / 100.0,
148            status: text("status").unwrap_or_default(),
149            failure_message: text("failureMessage"),
150            created_at: text("createdAt").unwrap_or_default(),
151            completed_at: text("completedAt"),
152        }
153    }
154}
155
156/// The `{ cursor, max }` query of paged lists: `cursor` items skipped from the
157/// newest, `max` the page size.
158#[derive(Debug, Clone, Copy)]
159pub struct PageQuery {
160    pub cursor: u32,
161    pub max: u32,
162}
163
164/// The `{ url }` checkout, setup, portal and subscribe calls resolve to.
165#[derive(Debug, Clone, Deserialize)]
166pub struct RedirectUrl {
167    pub url: String,
168}
169
170/// The `options` argument of checkout, setup, portal and subscribe. Stripe
171/// returns to `return_url` when it is a trusted app origin, else the Fauna app.
172#[derive(Debug, Clone, Default)]
173pub struct ReturnOptions {
174    pub return_url: Option<String>,
175}
176
177async fn request<T: DeserializeOwned>(token: &str, request: reqwest::RequestBuilder) -> Result<T> {
178    let response = request
179        .header("Authorization", format!("Token {token}"))
180        .send()
181        .await?;
182    Ok(ok(response).await?.json().await?)
183}
184
185pub async fn get(token: &str) -> Result<Summary> {
186    let value: WireSummary =
187        request(token, client().get(format!("{}/billing", crate::get_url()))).await?;
188    Ok(Summary {
189        balance: value.balance_micros / 1_000_000.0,
190        currency: value.currency,
191        payment_method: value.payment_method,
192        auto_reload: AutoReload::from_json(&value.auto_reload),
193        subscription: value.subscription,
194        recent_transactions: value
195            .recent_transactions
196            .iter()
197            .map(Transaction::from_json)
198            .collect(),
199    })
200}
201
202/// What each plan gives and what Premium costs. Anyone may ask; it takes no authorization.
203pub async fn plans() -> Result<Plans> {
204    let response = client()
205        .get(format!("{}/billing/plans", crate::get_url()))
206        .send()
207        .await?;
208    Ok(ok(response).await?.json().await?)
209}
210
211/// Start a Stripe Checkout top-up for the caller's personal wallet.
212pub async fn checkout(token: &str, amount: f64, options: &ReturnOptions) -> Result<RedirectUrl> {
213    let amount_cents = (amount * 100.0).round();
214    if !amount_cents.is_finite() || amount_cents.abs() > 9_007_199_254_740_991.0 {
215        return Err(Error::Message("Invalid top-up amount.".to_string()));
216    }
217    request(
218        token,
219        client()
220            .post(format!("{}/billing/checkout", crate::get_url()))
221            .json(&json!({ "amountCents": amount_cents as i64, "returnUrl": options.return_url })),
222    )
223    .await
224}
225
226pub async fn setup_payment_method(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
227    request(
228        token,
229        client()
230            .post(format!("{}/billing/payment-method/setup", crate::get_url()))
231            .json(&json!({ "returnUrl": options.return_url })),
232    )
233    .await
234}
235
236pub async fn update_auto_reload(token: &str, update: &AutoReloadUpdate) -> Result<AutoReload> {
237    let value: Value = request(
238        token,
239        client()
240            .patch(format!("{}/billing/auto-reload", crate::get_url()))
241            .json(&json!({
242                "enabled": update.enabled,
243                "thresholdCents": (update.threshold * 100.0).round() as i64,
244                "targetCents": (update.target * 100.0).round() as i64,
245                "monthlyCapCents": (update.monthly_cap * 100.0).round() as i64,
246            })),
247    )
248    .await?;
249    Ok(AutoReload::from_json(&value))
250}
251
252pub async fn open_portal(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
253    request(
254        token,
255        client()
256            .post(format!(
257                "{}/billing/payment-method/portal",
258                crate::get_url()
259            ))
260            .json(&json!({ "returnUrl": options.return_url })),
261    )
262    .await
263}
264
265/// Start Premium's Stripe Checkout. Open the returned URL; Stripe returns to
266/// `return_url` when it is a trusted app origin, else the Fauna app.
267pub async fn subscribe(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
268    request(
269        token,
270        client()
271            .post(format!(
272                "{}/billing/subscription/checkout",
273                crate::get_url()
274            ))
275            .json(&json!({ "returnUrl": options.return_url })),
276    )
277    .await
278}
279
280/// End Premium at the close of the period already paid for.
281pub async fn cancel_subscription(token: &str) -> Result<Subscription> {
282    request(
283        token,
284        client().post(format!("{}/billing/subscription/cancel", crate::get_url())),
285    )
286    .await
287}
288
289pub async fn transactions(token: &str, query: PageQuery) -> Result<Vec<Transaction>> {
290    let rows: Vec<Value> = request(
291        token,
292        client().get(format!(
293            "{}/billing/transactions?cursor={}&max={}",
294            crate::get_url(),
295            query.cursor,
296            query.max
297        )),
298    )
299    .await?;
300    Ok(rows.iter().map(Transaction::from_json).collect())
301}
302
303/// What one service charged on one UTC day, in dollars.
304#[derive(Debug, Clone, Serialize)]
305pub struct UsagePoint {
306    pub day: String,
307    pub service: String,
308    pub amount: f64,
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(rename_all = "lowercase")]
313pub enum PrincipalKind {
314    User,
315    Group,
316}
317
318#[derive(Debug, Clone, Serialize)]
319#[serde(rename_all = "camelCase")]
320pub struct Usage {
321    pub principal_kind: PrincipalKind,
322    pub since: String,
323    pub usage: Vec<UsagePoint>,
324}
325
326#[derive(Deserialize)]
327#[serde(rename_all = "camelCase")]
328struct WireUsagePoint {
329    day: String,
330    service: String,
331    amount_micros: f64,
332}
333
334#[derive(Deserialize)]
335#[serde(rename_all = "camelCase")]
336struct WireUsage {
337    principal_kind: PrincipalKind,
338    since: String,
339    usage: Vec<WireUsagePoint>,
340}
341
342/// What the caller's wallet, or a group's (member-only), was charged each day by each service.
343/// `days` bounds the window server-side (default 30, max 180).
344pub async fn usage(token: &str, group_id: Option<&str>, days: Option<u32>) -> Result<Usage> {
345    let mut query = format!("days={}", days.unwrap_or(30));
346    if let Some(group_id) = group_id {
347        query.push_str(&format!("&groupId={}", encode(group_id)));
348    }
349    let value: WireUsage = request(
350        token,
351        client().get(format!("{}/billing/usage?{query}", crate::get_url())),
352    )
353    .await?;
354    Ok(Usage {
355        principal_kind: value.principal_kind,
356        since: value.since,
357        usage: value
358            .usage
359            .into_iter()
360            .map(|point| UsagePoint {
361                day: point.day,
362                service: point.service,
363                amount: point.amount_micros / 1_000_000.0,
364            })
365            .collect(),
366    })
367}
368
369/// What a rate is counted in.
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase")]
372pub enum Unit {
373    Token,
374    Character,
375    Image,
376    Second,
377    Minute,
378    Hour,
379    Query,
380    Read,
381    Call,
382    Tile,
383    Search,
384    Gb,
385    GbMonth,
386}
387
388/// One price as callers are charged: `dollars` for every `per` `unit`s, the way a price is said
389/// ("2.5 dollars per 1,000,000 tokens"). Every service's pricing (`GET /{service}/pricing`)
390/// lists its prices as rates.
391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392pub struct Rate {
393    /// What it prices, stable across releases: `input`, `search`, `storage`.
394    pub key: String,
395    /// What it prices, as a person reads it: `Input`, `Web search`, `Saved files`.
396    pub name: String,
397    pub dollars: f64,
398    pub per: f64,
399    pub unit: Unit,
400}
401
402impl Rate {
403    pub fn from_json(json: &Value) -> Result<Rate> {
404        Ok(serde_json::from_value(json.clone())?)
405    }
406
407    /// What `count` units cost at this rate.
408    pub fn cost(&self, count: f64) -> f64 {
409        self.dollars / self.per * count
410    }
411}
412
413/// US dollars, the way `Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })` prints them.
414pub fn format(amount: f64) -> String {
415    let cents = (amount.abs() * 100.0).round() as u64;
416    let dollars = (cents / 100).to_string();
417    let mut grouped = String::new();
418    for (index, digit) in dollars.chars().enumerate() {
419        if index > 0 && (dollars.len() - index).is_multiple_of(3) {
420            grouped.push(',');
421        }
422        grouped.push(digit);
423    }
424    let sign = if amount < 0.0 && cents > 0 { "-" } else { "" };
425    format!("{sign}${grouped}.{:02}", cents % 100)
426}