fauna-api 1.0.759

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

use super::contacts::post as send;
use crate::authentification::{Credentials, CredentialsOrApiKey};
use crate::error::Result;
use crate::integrations::Platform;
use crate::parrot::generative::{Text, Voice};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InboxGroup {
    pub id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Inbox {
    pub id: String,
    pub name: String,
    pub created_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<InboxGroup>,
    /// An agent is on for this inbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<bool>,
}

fn text(value: &Value, fallback: &str) -> String {
    match value {
        Value::Null => fallback.to_string(),
        Value::String(text) => text.clone(),
        value => value.to_string(),
    }
}

fn truthy(value: &Value) -> bool {
    match value {
        Value::Null => false,
        Value::Bool(value) => *value,
        Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
        Value::String(text) => !text.is_empty(),
        _ => true,
    }
}

impl Inbox {
    fn from_json(raw: &Value) -> Inbox {
        let group = &raw["group"];
        Inbox {
            id: text(&raw["id"], "undefined"),
            name: raw["name"].as_str().unwrap_or_default().to_string(),
            created_at: crate::tickets::parse_date(&raw["createdAt"]).unwrap_or_default(),
            group: group.is_object().then(|| InboxGroup {
                id: text(&group["id"], "undefined"),
                name: text(&group["name"], ""),
                icon: truthy(&group["icon"]).then(|| text(&group["icon"], "")),
            }),
            agent: truthy(&raw["agent"]).then_some(true),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InboxAccount {
    pub platform: Platform,
    pub account_id: String,
}

async fn post(
    authorization: &CredentialsOrApiKey,
    path: &str,
    body: Value,
) -> Result<reqwest::Response> {
    send(authorization, path, Some(body)).await
}

fn inboxes(json: &Value) -> Vec<Inbox> {
    json.as_array()
        .into_iter()
        .flatten()
        .map(Inbox::from_json)
        .collect()
}

pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Inbox>> {
    let json: Value = post(authorization, "/cicada/inboxes", json!({}))
        .await?
        .json()
        .await?;
    Ok(inboxes(&json))
}

pub async fn create(authorization: &CredentialsOrApiKey, name: &str) -> Result<Inbox> {
    let json: Value = post(
        authorization,
        "/cicada/inboxes/create",
        json!({ "name": name }),
    )
    .await?
    .json()
    .await?;
    Ok(Inbox::from_json(&json))
}

pub async fn rename(
    authorization: &CredentialsOrApiKey,
    inbox_id: &str,
    name: &str,
) -> Result<Inbox> {
    let json: Value = post(
        authorization,
        "/cicada/inboxes/rename",
        json!({ "inbox": inbox_id, "name": name }),
    )
    .await?
    .json()
    .await?;
    Ok(Inbox::from_json(&json))
}

pub async fn remove(authorization: &CredentialsOrApiKey, inbox_id: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/inboxes/delete",
        json!({ "inbox": inbox_id }),
    )
    .await?;
    Ok(())
}

pub async fn move_to_group(
    authorization: &CredentialsOrApiKey,
    inbox_id: &str,
    group_id: &str,
) -> Result<Inbox> {
    let json: Value = post(
        authorization,
        "/cicada/inboxes/move",
        json!({ "inbox": inbox_id, "group": group_id }),
    )
    .await?
    .json()
    .await?;
    Ok(Inbox::from_json(&json))
}

pub async fn assign(
    authorization: &CredentialsOrApiKey,
    inbox_id: &str,
    account: &InboxAccount,
) -> Result<()> {
    post(
        authorization,
        "/cicada/inboxes/accounts",
        json!({ "inbox": inbox_id, "platform": account.platform, "accountId": account.account_id }),
    )
    .await?;
    Ok(())
}

pub async fn list_accounts(
    authorization: &CredentialsOrApiKey,
    inbox_id: &str,
) -> Result<Vec<InboxAccount>> {
    Ok(post(
        authorization,
        "/cicada/inboxes/accounts/list",
        json!({ "inbox": inbox_id }),
    )
    .await?
    .json()
    .await?)
}

/// Each inbox has at most one agent, with its own model and "System prompt"
/// (`instructions`). It answers the inbox's new messages and reaches people
/// from the inbox's own accounts. `daily_limit` and `spent_today` are dollars per
/// UTC day; at the limit the agent pauses until midnight UTC. `reasoning` is one
/// of the text model's catalog tiers, empty for its default; `voice_model` is the
/// realtime voice the agent talks with on calls, None for the catalog's first.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSettings {
    pub model: Text,
    pub reasoning: String,
    pub voice_model: Option<Voice>,
    pub instructions: String,
    pub daily_limit: f64,
    pub spent_today: f64,
    pub enabled_at: DateTime<Utc>,
}

impl AgentSettings {
    pub fn from_json(json: &Value) -> AgentSettings {
        AgentSettings {
            model: serde_json::from_value(json["model"].clone()).unwrap_or(Text::Auto),
            reasoning: text(&json["reasoning"], ""),
            voice_model: serde_json::from_value(json["voiceModel"].clone()).ok(),
            instructions: text(&json["instructions"], ""),
            daily_limit: json["dailyLimit"].as_f64().unwrap_or_default(),
            spent_today: json["spentToday"].as_f64().unwrap_or_default(),
            enabled_at: crate::tickets::parse_date(&json["enabledAt"]).unwrap_or_default(),
        }
    }
}

pub async fn get_agent(
    authorization: &CredentialsOrApiKey,
    inbox: &str,
) -> Result<Option<AgentSettings>> {
    let text = post(
        authorization,
        "/cicada/inboxes/agent",
        json!({ "inbox": inbox }),
    )
    .await?
    .text()
    .await?;
    if text.trim().is_empty() {
        return Ok(None);
    }
    Ok(Some(AgentSettings::from_json(&serde_json::from_str(
        &text,
    )?)))
}

/// The `settings` argument of `set_agent`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentDraft {
    pub model: Text,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub voice_model: Option<Voice>,
    pub instructions: String,
    pub daily_limit: f64,
}

/// Turns the agent on (it answers messages sent from now on) or updates it.
pub async fn set_agent(
    authorization: &CredentialsOrApiKey,
    inbox: &str,
    settings: &AgentDraft,
) -> Result<AgentSettings> {
    let mut body = Map::new();
    body.insert("inbox".to_string(), Value::from(inbox));
    if let Value::Object(fields) = serde_json::to_value(settings)? {
        body.extend(fields);
    }
    let json: Value = post(
        authorization,
        "/cicada/inboxes/agent/set",
        Value::Object(body),
    )
    .await?
    .json()
    .await?;
    Ok(AgentSettings::from_json(&json))
}

pub async fn clear_agent(authorization: &CredentialsOrApiKey, inbox: &str) -> Result<()> {
    post(
        authorization,
        "/cicada/inboxes/agent/clear",
        json!({ "inbox": inbox }),
    )
    .await?;
    Ok(())
}

/// The `call` argument of `agent_call`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentCallRequest {
    pub to: String,
    pub directions: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
}

/// `{ calling, from, callId }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacedCall {
    pub calling: String,
    pub from: String,
    pub call_id: String,
}

/// Has the inbox's agent phone `to` from one of the inbox's lines (`from`, or its first)
/// and follow `directions`. Returns once the call is placed; the transcript lands on the
/// thread with that number. Owners only; counts toward the agent's daily limit.
pub async fn agent_call(
    authorization: &Credentials,
    inbox: &str,
    call: &AgentCallRequest,
) -> Result<PlacedCall> {
    let mut body = Map::new();
    body.insert("inbox".to_string(), Value::from(inbox));
    if let Value::Object(fields) = serde_json::to_value(call)? {
        body.extend(fields);
    }
    Ok(post(
        &CredentialsOrApiKey::Credentials(authorization.clone()),
        "/cicada/inboxes/agent/call",
        Value::Object(body),
    )
    .await?
    .json()
    .await?)
}