fauna-api 1.0.807

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::error::{Error, Result};
use crate::http::{client, encode, ok};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethod {
    pub brand: String,
    pub last4: String,
    pub exp_month: u32,
    pub exp_year: u32,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoReload {
    pub enabled: bool,
    pub threshold: f64,
    pub target: f64,
    pub monthly_cap: f64,
    pub monthly_spent: f64,
    pub status: String,
    pub available: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoReloadUpdate {
    pub enabled: bool,
    pub threshold: f64,
    pub target: f64,
    pub monthly_cap: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TransactionKind {
    Manual,
    Automatic,
    Subscription,
    Grant,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
    pub id: String,
    pub kind: TransactionKind,
    pub amount: f64,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_message: Option<String>,
    pub created_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Plan {
    Free,
    Premium,
    Enterprise,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
    pub plan: Plan,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub period_end: Option<String>,
    #[serde(default)]
    pub cancel_at_period_end: bool,
    /// Ids of the add-ons you hold.
    #[serde(default)]
    pub addons: Vec<String>,
}

/// Something an app sells on top of Premium, on the same subscription. Prices
/// are in dollars per `interval`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Addon {
    pub id: String,
    pub name: String,
    pub price: f64,
    /// What it costs without Premium yet, since buying it adds Premium too.
    pub with_premium: f64,
    pub currency: String,
    pub interval: String,
}

/// The `options` argument of `subscribe`: where Stripe returns to, and the
/// add-on to buy instead of Premium alone.
#[derive(Debug, Clone, Default)]
pub struct SubscribeOptions {
    pub return_url: Option<String>,
    pub addon: Option<String>,
}

/// The `options` argument of `cancel_subscription`: the add-on to stop, or
/// `None` to end Premium.
#[derive(Debug, Clone, Default)]
pub struct CancelOptions {
    pub addon: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Summary {
    pub balance: f64,
    pub currency: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<PaymentMethod>,
    pub auto_reload: AutoReload,
    pub subscription: Subscription,
    pub recent_transactions: Vec<Transaction>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireSummary {
    balance_micros: f64,
    currency: String,
    #[serde(default)]
    payment_method: Option<PaymentMethod>,
    auto_reload: Value,
    #[serde(default)]
    subscription: Option<Subscription>,
    recent_transactions: Vec<Value>,
}

impl AutoReload {
    pub fn from_json(json: &Value) -> AutoReload {
        let number = |key: &str| json[key].as_f64().unwrap_or(0.0);
        AutoReload {
            enabled: json["enabled"].as_bool().unwrap_or(false),
            threshold: number("thresholdMicros") / 1_000_000.0,
            target: number("targetMicros") / 1_000_000.0,
            monthly_cap: number("monthlyCapCents") / 100.0,
            monthly_spent: number("monthlySpentCents") / 100.0,
            status: json["status"].as_str().unwrap_or_default().to_string(),
            available: json["available"] == Value::Bool(true),
        }
    }
}

impl Transaction {
    pub fn from_json(json: &Value) -> Transaction {
        let text = |key: &str| json[key].as_str().map(str::to_string);
        Transaction {
            id: text("id").unwrap_or_default(),
            kind: serde_json::from_value(json["kind"].clone()).unwrap_or(TransactionKind::Manual),
            amount: json["amountCents"].as_f64().unwrap_or(0.0) / 100.0,
            status: text("status").unwrap_or_default(),
            failure_message: text("failureMessage"),
            created_at: text("createdAt").unwrap_or_default(),
            completed_at: text("completedAt"),
        }
    }
}

/// The `{ cursor, max }` query of paged lists: `cursor` items skipped from the
/// newest, `max` the page size.
#[derive(Debug, Clone, Copy)]
pub struct PageQuery {
    pub cursor: u32,
    pub max: u32,
}

/// The `{ url }` checkout, setup, portal and subscribe calls resolve to.
#[derive(Debug, Clone, Deserialize)]
pub struct RedirectUrl {
    pub url: String,
}

/// The `options` argument of checkout, setup, portal and subscribe. Stripe
/// returns to `return_url` when it is a trusted app origin, else the Fauna app.
#[derive(Debug, Clone, Default)]
pub struct ReturnOptions {
    pub return_url: Option<String>,
}

async fn request<T: DeserializeOwned>(token: &str, request: reqwest::RequestBuilder) -> Result<T> {
    let response = request
        .header("Authorization", format!("Token {token}"))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn get(token: &str) -> Result<Summary> {
    let value: WireSummary =
        request(token, client().get(format!("{}/billing", crate::get_url()))).await?;
    Ok(Summary {
        balance: value.balance_micros / 1_000_000.0,
        currency: value.currency,
        payment_method: value.payment_method,
        auto_reload: AutoReload::from_json(&value.auto_reload),
        subscription: value.subscription.unwrap_or(Subscription {
            plan: Plan::Free,
            status: "none".to_string(),
            period_end: None,
            cancel_at_period_end: false,
            addons: Vec::new(),
        }),
        recent_transactions: value
            .recent_transactions
            .iter()
            .map(Transaction::from_json)
            .collect(),
    })
}

/// Start a Stripe Checkout top-up for the caller's personal wallet.
pub async fn checkout(token: &str, amount: f64, options: &ReturnOptions) -> Result<RedirectUrl> {
    let amount_cents = (amount * 100.0).round();
    if !amount_cents.is_finite() || amount_cents.abs() > 9_007_199_254_740_991.0 {
        return Err(Error::Message("Invalid top-up amount.".to_string()));
    }
    request(
        token,
        client()
            .post(format!("{}/billing/checkout", crate::get_url()))
            .json(&json!({ "amountCents": amount_cents as i64, "returnUrl": options.return_url })),
    )
    .await
}

pub async fn setup_payment_method(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
    request(
        token,
        client()
            .post(format!("{}/billing/payment-method/setup", crate::get_url()))
            .json(&json!({ "returnUrl": options.return_url })),
    )
    .await
}

pub async fn update_auto_reload(token: &str, update: &AutoReloadUpdate) -> Result<AutoReload> {
    let value: Value = request(
        token,
        client()
            .patch(format!("{}/billing/auto-reload", crate::get_url()))
            .json(&json!({
                "enabled": update.enabled,
                "thresholdCents": (update.threshold * 100.0).round() as i64,
                "targetCents": (update.target * 100.0).round() as i64,
                "monthlyCapCents": (update.monthly_cap * 100.0).round() as i64,
            })),
    )
    .await?;
    Ok(AutoReload::from_json(&value))
}

pub async fn open_portal(token: &str, options: &ReturnOptions) -> Result<RedirectUrl> {
    request(
        token,
        client()
            .post(format!(
                "{}/billing/payment-method/portal",
                crate::get_url()
            ))
            .json(&json!({ "returnUrl": options.return_url })),
    )
    .await
}

/// Subscribe to Premium, or with `addon`, buy an add-on. With a subscription
/// already, the add-on joins it at once (the URL then returns to `return_url`,
/// or opens the invoice when the card needs confirming); otherwise Checkout sells
/// Premium and the add-on together. Open the returned URL.
pub async fn subscribe(token: &str, options: &SubscribeOptions) -> Result<RedirectUrl> {
    request(
        token,
        client()
            .post(format!(
                "{}/billing/subscription/checkout",
                crate::get_url()
            ))
            .json(&json!({ "returnUrl": options.return_url, "addon": options.addon })),
    )
    .await
}

/// End Premium at the period's end (add-ons end with it), or with `addon`, stop
/// that add-on now with a prorated credit.
pub async fn cancel_subscription(token: &str, options: &CancelOptions) -> Result<Subscription> {
    request(
        token,
        client()
            .post(format!("{}/billing/subscription/cancel", crate::get_url()))
            .json(&json!({ "addon": options.addon })),
    )
    .await
}

/// The add-ons for sale.
pub async fn addons(token: &str) -> Result<Vec<Addon>> {
    request(
        token,
        client().get(format!("{}/billing/addons", crate::get_url())),
    )
    .await
}

pub async fn transactions(token: &str, query: PageQuery) -> Result<Vec<Transaction>> {
    let rows: Vec<Value> = request(
        token,
        client().get(format!(
            "{}/billing/transactions?cursor={}&max={}",
            crate::get_url(),
            query.cursor,
            query.max
        )),
    )
    .await?;
    Ok(rows.iter().map(Transaction::from_json).collect())
}

#[derive(Debug, Clone, Serialize)]
pub struct UsagePoint {
    pub day: String,
    pub service: String,
    pub base: f64,
    pub spread: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PrincipalKind {
    User,
    Group,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Usage {
    pub principal_kind: PrincipalKind,
    pub since: String,
    pub usage: Vec<UsagePoint>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireUsagePoint {
    day: String,
    service: String,
    base_micros: f64,
    spread_micros: f64,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireUsage {
    principal_kind: PrincipalKind,
    since: String,
    usage: Vec<WireUsagePoint>,
}

/// Daily base/spread usage for the caller's wallet, or a group's (member-only).
/// `days` bounds the window server-side (default 30, max 180).
pub async fn usage(token: &str, group_id: Option<&str>, days: Option<u32>) -> Result<Usage> {
    let mut query = format!("days={}", days.unwrap_or(30));
    if let Some(group_id) = group_id {
        query.push_str(&format!("&groupId={}", encode(group_id)));
    }
    let value: WireUsage = request(
        token,
        client().get(format!("{}/billing/usage?{query}", crate::get_url())),
    )
    .await?;
    Ok(Usage {
        principal_kind: value.principal_kind,
        since: value.since,
        usage: value
            .usage
            .into_iter()
            .map(|point| UsagePoint {
                day: point.day,
                service: point.service,
                base: point.base_micros / 1_000_000.0,
                spread: point.spread_micros / 1_000_000.0,
            })
            .collect(),
    })
}

/// US dollars, the way `Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })` prints them.
pub fn format(amount: f64) -> String {
    let cents = (amount.abs() * 100.0).round() as u64;
    let dollars = (cents / 100).to_string();
    let mut grouped = String::new();
    for (index, digit) in dollars.chars().enumerate() {
        if index > 0 && (dollars.len() - index).is_multiple_of(3) {
            grouped.push(',');
        }
        grouped.push(digit);
    }
    let sign = if amount < 0.0 && cents > 0 { "-" } else { "" };
    format!("{sign}${grouped}.{:02}", cents % 100)
}