fauna-api 1.0.865

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::billing::PageQuery;
use crate::error::Result;
use crate::http::{client, ok};

// Private: a wallet's books, for Fauna's own billing screen. A person reads their own wallet,
// one of their keys' (`principal`, `apikey:{id}`) or a group's they're in (`group_id`).

/// Which wallet to read: the caller's own unless one is named.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Wallet {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub principal: Option<String>,
}

/// A wallet at the end of one UTC day, in dollars: its given credit, paid money, what open
/// holds set aside and what it owes, and the money that came in and went out that day.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LedgerDay {
    pub day: String,
    pub credit: f64,
    pub paid: f64,
    pub held: f64,
    pub debt: f64,
    pub money_in: f64,
    pub money_out: f64,
}

impl LedgerDay {
    pub fn from_json(json: &Value) -> LedgerDay {
        let dollars = |key: &str| json[key].as_f64().unwrap_or(0.0) / 1_000_000.0;
        LedgerDay {
            day: json["day"].as_str().unwrap_or_default().to_string(),
            credit: dollars("creditMicros"),
            paid: dollars("paidMicros"),
            held: dollars("heldMicros"),
            debt: dollars("debtMicros"),
            money_in: dollars("inMicros"),
            money_out: dollars("outMicros"),
        }
    }
}

/// One movement of money in or out of a wallet: from one account to another
/// (`{owner}/{kind}`, `fauna/{book}` or `outside`), in dollars, with why it moved and what it
/// belongs to.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LedgerTransfer {
    pub id: String,
    pub from: String,
    pub to: String,
    pub amount: f64,
    pub reason: String,
    pub reference: String,
    pub app: String,
    pub service: String,
    pub created_at: String,
}

impl LedgerTransfer {
    pub fn from_json(json: &Value) -> LedgerTransfer {
        let text = |key: &str| json[key].as_str().unwrap_or_default().to_string();
        LedgerTransfer {
            id: text("id"),
            from: text("from"),
            to: text("to"),
            amount: json["amountMicros"].as_f64().unwrap_or(0.0) / 1_000_000.0,
            reason: text("reason"),
            reference: text("reference"),
            app: text("app"),
            service: text("service"),
            created_at: text("createdAt"),
        }
    }
}

fn wallet_query(wallet: &Wallet) -> Vec<(&'static str, String)> {
    let mut query = Vec::new();
    if let Some(group_id) = &wallet.group_id {
        query.push(("groupId", group_id.clone()));
    }
    if let Some(principal) = &wallet.principal {
        query.push(("principal", principal.clone()));
    }
    query
}

/// A wallet's last `days` UTC days (default 30, at most 180), oldest first.
pub async fn days(token: &str, wallet: &Wallet, days: Option<u32>) -> Result<Vec<LedgerDay>> {
    let mut query = wallet_query(wallet);
    query.push(("days", days.unwrap_or(30).to_string()));
    let response = client()
        .get(format!("{}/billing/ledger/days", crate::get_url()))
        .header("Authorization", format!("Token {token}"))
        .query(&query)
        .send()
        .await?;
    let value: Value = ok(response).await?.json().await?;
    Ok(value["days"]
        .as_array()
        .into_iter()
        .flatten()
        .map(LedgerDay::from_json)
        .collect())
}

/// A wallet's transfers in and out, newest first.
pub async fn transfers(
    token: &str,
    query: PageQuery,
    wallet: &Wallet,
) -> Result<Vec<LedgerTransfer>> {
    let mut params = wallet_query(wallet);
    params.push(("cursor", query.cursor.to_string()));
    params.push(("max", query.max.to_string()));
    let response = client()
        .get(format!("{}/billing/ledger/transfers", crate::get_url()))
        .header("Authorization", format!("Token {token}"))
        .query(&params)
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(LedgerTransfer::from_json).collect())
}