zc2 0.0.50

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `GET /v2/ledger?by=day|product|node&from=&to=` (ADR ZC-0019 ยง2): the hub's
//! provider ledger (`/api/provide/ledger`), amounts in yen as the hub returns
//! them, reshaped to the one grouping the caller asked for.

use serde_json::{json, Value};

pub const GROUPS: [&str; 3] = ["day", "product", "node"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Query {
    pub by: &'static str,
    /// `YYYY-MM-DD`, the account's zone.
    pub from: Option<String>,
    pub to: Option<String>,
}

fn date(label: &str, v: Option<&str>) -> Result<Option<String>, String> {
    match v.map(str::trim).filter(|v| !v.is_empty()) {
        None => Ok(None),
        Some(d) => chrono::NaiveDate::parse_from_str(d, "%Y-%m-%d")
            .map(|d| Some(d.format("%Y-%m-%d").to_string()))
            .map_err(|_| format!("{label} {d:?} is not a date (YYYY-MM-DD)")),
    }
}

impl Query {
    pub fn parse(by: &str, from: Option<&str>, to: Option<&str>) -> Result<Self, String> {
        let by = GROUPS
            .iter()
            .copied()
            .find(|g| *g == by.trim())
            .ok_or_else(|| format!("by {by:?}: use day, product or node"))?;
        let (from, to) = (date("from", from)?, date("to", to)?);
        if let (Some(f), Some(t)) = (&from, &to) {
            if f > t {
                return Err(format!("from {f} is after to {t}"));
            }
        }
        Ok(Self { by, from, to })
    }
}

/// The response body: the grouping the caller asked for, the totals, and the
/// range and zone it covers. `groups` is the hub's `by_<by>` untouched.
pub fn view(q: &Query, tz: &str, hub: &Value) -> Value {
    json!({
        "unit": "jpy",
        "by": q.by,
        "from": q.from,
        "to": q.to,
        "tz": hub.get("tz").and_then(Value::as_str).unwrap_or(tz),
        "groups": hub.get(format!("by_{}", q.by)).cloned().unwrap_or(Value::Null),
        "totals": hub.get("totals").cloned().unwrap_or(Value::Null),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_query_is_validated() {
        let q = Query::parse("day", Some("2026-11-01"), Some("2026-11-10")).unwrap();
        assert_eq!(q.by, "day");
        assert_eq!(q.from.as_deref(), Some("2026-11-01"));
        assert_eq!(Query::parse("node", None, Some("")).unwrap().to, None);
        for (by, from, to) in [
            ("week", None, None),
            ("", None, None),
            ("day", Some("yesterday"), None),
            ("day", Some("2026-13-01"), None),
            ("day", Some("2026-11-10"), Some("2026-11-01")),
        ] {
            assert!(Query::parse(by, from, to).is_err(), "{by} {from:?} {to:?}");
        }
    }

    #[test]
    fn the_view_keeps_the_hubs_yen_and_picks_the_grouping() {
        let hub = json!({
            "rows": [{"day": "2026-11-09", "node": "n1", "product": "spaces",
                      "earned": 12.5, "spent": 0.0, "fake_earned": 0.0}],
            "by_day": [{"day": "2026-11-09", "earned": 12.5, "spent": 0.0}],
            "by_node": [{"node": "n1", "earned": 12.5, "spent": 0.0}],
            "by_product": [{"product": "spaces", "earned": 12.5, "spent": 0.0}],
            "totals": {"earned": 12.5, "spent": 0.0, "fake_earned": 0.0},
            "tz": "Asia/Tokyo"
        });
        let q = Query::parse("product", Some("2026-11-01"), None).unwrap();
        let v = view(&q, "UTC", &hub);
        assert_eq!(v["unit"], "jpy");
        assert_eq!(v["by"], "product");
        assert_eq!(v["groups"], hub["by_product"]);
        assert_eq!(v["totals"]["earned"], 12.5);
        assert_eq!(v["from"], "2026-11-01");
        assert_eq!(v["to"], Value::Null);
        assert_eq!(v["tz"], "Asia/Tokyo", "the hub's zone wins");
        let day = view(&Query::parse("day", None, None).unwrap(), "UTC", &hub);
        assert_eq!(day["groups"][0]["day"], "2026-11-09");
        // A hub that sends less: nulls, not an error.
        let v = view(&q, "UTC", &json!({}));
        assert_eq!(
            (v["groups"].is_null(), v["tz"].as_str()),
            (true, Some("UTC"))
        );
    }
}