zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The account: who you are, what you spent, the ledger, receipts and
//! payouts. Money never moves from here: top-up and withdrawal are pages of
//! the hub's web console, and `zc billing` prints their addresses.

use serde_json::Value;

use super::client::{enc, Client};
use super::fmt::*;
use super::{Fail, Out, Parsed};

pub fn me(c: &Client, sub: &str) -> Result<Out, Fail> {
    match sub {
        "status" => {
            let v = c.get("/api/accounts/me/status")?;
            Ok((v.clone(), flat_doc(&v)))
        }
        "profile" => {
            let v = c.get("/api/accounts/me")?;
            Ok((v.clone(), flat_doc(&v)))
        }
        _ => Err(Fail::Usage("usage: zc me [status|profile]".into())),
    }
}

pub fn usage_doc(stats: &Value) -> Doc {
    Doc::kv(vec![
        ("spent this month", yen_of(stats, "credits_this_month")),
        ("spent last month", yen_of(stats, "credits_last_month")),
        ("compute hours", num(stats, "compute_hours", 1)),
        ("jobs", st(stats, "total_jobs")),
        ("success rate", num(stats, "success_rate", 1)),
        ("average per job", yen_of(stats, "avg_credits_per_job")),
        ("earned (all time)", yen_of(stats, "total_gains")),
        ("earned this month", yen_of(stats, "gains_this_month")),
        ("hours lent", num(stats, "gains_compute_hours", 1)),
    ])
}

pub fn top_jobs_table(v: &Value) -> Table {
    let mut t = Table::new(&["JOB", "SPENT", "RUNS", "AVG HOURS", "AVG COST"]);
    for j in items(v, "jobs") {
        t.rows.push(vec![
            clip(&st(j, "job_name"), 48),
            yen_of(j, "total_credits"),
            st(j, "runs"),
            num(j, "avg_hours", 2),
            yen_of(j, "avg_credits"),
        ]);
    }
    t
}

pub fn daily_table(v: &Value) -> Table {
    let mut t = Table::new(&["DAY", "SPENT"]);
    let labels = v["labels"].as_array().cloned().unwrap_or_default();
    let data = v["data"].as_array().cloned().unwrap_or_default();
    for (l, d) in labels.iter().zip(data.iter()) {
        t.rows.push(vec![
            l.as_str().unwrap_or("-").to_string(),
            d.as_f64().map(yen).unwrap_or_else(|| "-".into()),
        ]);
    }
    t
}

pub fn usage(c: &Client, sub: &str, a: &Parsed) -> Result<Out, Fail> {
    match sub {
        "" | "stats" => {
            let v = c.get("/api/usage/stats")?;
            Ok((v.clone(), usage_doc(&v)))
        }
        "top" => {
            let v = c.get_q(
                "/api/usage/top-jobs",
                &[("limit", a.opt("limit").unwrap_or(""))],
            )?;
            Ok((v.clone(), Doc::table(top_jobs_table(&v))))
        }
        "daily" => {
            let v = c.get_q(
                "/api/usage/charts/daily",
                &[("days", a.opt("days").unwrap_or(""))],
            )?;
            Ok((v.clone(), Doc::table(daily_table(&v))))
        }
        _ => Err(Fail::Usage("usage: zc usage [stats|top|daily]".into())),
    }
}

pub fn tx_table(v: &Value) -> Doc {
    let mut t = Table::new(&["ID", "WHEN", "TYPE", "JOB", "CREDITS", "STATUS", "HOURS"]);
    for x in items(v, "transactions") {
        t.rows.push(vec![
            st(x, "id"),
            when(x, "created_at"),
            st(x, "transaction_type"),
            clip(&st(x, "job_name"), 36),
            num(x, "credits_amount", 2),
            st(x, "status"),
            num(x, "compute_hours", 2),
        ]);
    }
    let doc = Doc::table(t);
    match (v["page"].as_u64(), v["pages"].as_u64(), v["total"].as_u64()) {
        (Some(p), Some(pages), Some(total)) => {
            doc.with_note(format!("page {p} of {pages}, {total} in all"))
        }
        _ => doc,
    }
}

/// Recent rows of the overview panel: the same columns, newest first.
pub fn recent_table(v: &Value) -> Doc {
    tx_table(v)
}

pub fn transactions(c: &Client, sub: &str, a: &Parsed) -> Result<Out, Fail> {
    match sub {
        "ls" | "list" | "" => {
            let q = [
                ("page", a.opt("page").unwrap_or("")),
                ("limit", a.opt("limit").unwrap_or("")),
                ("type", a.opt("type").unwrap_or("")),
                ("status", a.opt("status").unwrap_or("")),
                ("gains", if a.flag("gains") { "true" } else { "" }),
            ];
            let v = c.get_q("/api/transactions", &q)?;
            Ok((v.clone(), tx_table(&v)))
        }
        "show" => {
            let id = a
                .pos
                .first()
                .ok_or_else(|| Fail::Usage("usage: zc tx show ID".into()))?;
            let v = c.get(&format!("/api/transactions/{}", enc(id)))?;
            Ok((v.clone(), flat_doc(&v)))
        }
        _ => Err(Fail::Usage(
            "usage: zc tx ls [--page N] [--limit N] [--type T] [--status S] [--gains] | show ID"
                .into(),
        )),
    }
}

pub fn receipt(c: &Client, a: &Parsed) -> Result<Out, Fail> {
    let hash = a.pos.first().ok_or_else(|| {
        Fail::Usage("usage: zc receipt HASH (sha256 of the signed receipt)".into())
    })?;
    let v = c.get(&format!("/api/receipts/{}", enc(hash)))?;
    Ok((v.clone(), flat_doc(&v)))
}

pub fn payouts_doc(p: &Value) -> Doc {
    let mut h = Table::new(&["WHEN", "CREDITS", "STATUS"]);
    for w in items(&p["history"], "history") {
        h.rows.push(vec![
            when(w, "created_at"),
            num(w, "credits", 2),
            st(w, "status"),
        ]);
    }
    let due = p["requirements_due"]
        .as_array()
        .map(|a| {
            a.iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join(", ")
        })
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "-".into());
    Doc::kv(vec![
        ("account", st(p, "account_state")),
        ("payouts enabled", st(p, "payouts_enabled")),
        ("withdrawable", num(p, "withdrawable_credits", 2)),
        ("pending", num(p, "pending_credits", 2)),
        ("minimum", num(p, "min_withdrawal_credits", 2)),
        ("currency", st(p, "currency")),
        ("still needed", due),
    ])
    .with_table(h)
    .with_note("to connect or withdraw, open the page: zc billing payout")
}

pub fn payouts(c: &Client) -> Result<Out, Fail> {
    let v = c.get("/api/payouts/status")?;
    Ok((v.clone(), payouts_doc(&v)))
}

pub fn quotas_doc(q: &Value) -> Doc {
    let line = |used: &str, limit: &str| match q.get(limit).and_then(Value::as_u64) {
        Some(l) => format!("{} of {l}", st(q, used)),
        None => format!("{}, no limit", st(q, used)),
    };
    Doc::kv(vec![
        (
            "last 5 hours",
            line("requests_this_period", "rate_limit_per_period"),
        ),
        (
            "this week",
            line("requests_this_week", "rate_limit_per_week"),
        ),
        (
            "this month",
            line("requests_this_month", "rate_limit_per_month"),
        ),
    ])
}

pub fn quotas(c: &Client) -> Result<Out, Fail> {
    let v = c.get("/api/dashboard/quotas")?;
    Ok((v.clone(), quotas_doc(&v)))
}

/// `zc billing topup|payout`: the hub page, never a request.
pub fn billing(sub: &str, web: &str) -> Result<Out, Fail> {
    let (path, what) = match sub {
        "topup" | "top-up" | "credits" => ("/billing", "add credits"),
        "payout" | "payouts" | "withdraw" => {
            ("/provide/earnings", "connect a payout account or withdraw")
        }
        _ => return Err(Fail::Usage("usage: zc billing topup|payout".into())),
    };
    let url = format!("{web}{path}");
    Ok((
        serde_json::json!({"url": url}),
        Doc::note(format!(
            "To {what}, open {url} in your browser; money moves only there."
        )),
    ))
}