Cotton code
156 lines · 7.0 KB · RustRaw
//! What the faces draw (`health.summary`): a day, read against the weeks//! before it, and a range, as each metric's series with its mean, least,//! most and total. Pure over the rows the tables hold (their `data` maps).use std::collections::BTreeMap;use serde_json::{json, Map, Value};use super::catalog::{self, Fold};/// How many days before a day make its "usual".pub const USUAL_DAYS: i64 = 28;fn day_of(row: &Map<String, Value>) -> Option<&str> {    row.get("day").and_then(Value::as_str)}fn value_of(row: &Map<String, Value>) -> Option<f64> {    row.get("value").and_then(Value::as_f64)}fn round(value: f64) -> Value {    super::rows::kept(value)}/// The day `days` before `day` (`YYYY-MM-DD`).pub fn day_before(day: &str, days: i64) -> Option<String> {    let date = chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").ok()?;    Some((date - chrono::Duration::days(days)).format("%Y-%m-%d").to_string())}/// Does a metric total over a range (a sum of days) or only average?fn totals(fold: Fold) -> bool {    matches!(fold, Fold::Sum | Fold::Sleep | Fold::Minutes | Fold::Hours | Fold::Count)}/// One day: each metric it holds, in the catalogue's order, with its usual/// (the mean of the [`USUAL_DAYS`] days before that hold it); the night's/// sleep by stage; the day's workouts and measurements, earliest first.////// `days` are `health_day` rows from `day` minus [`USUAL_DAYS`] to `day`.pub fn day(day: &str, days: &[Map<String, Value>], workouts: &[Map<String, Value>], measurements: &[Map<String, Value>]) -> Value {    let mut metrics = Vec::new();    for metric in catalog::METRICS {        let of = |row: &&Map<String, Value>| row.get("metric").and_then(Value::as_str) == Some(metric.key);        let Some(today) = days.iter().filter(of).find(|row| day_of(row) == Some(day)) else { continue };        let before: Vec<f64> = days.iter().filter(of).filter(|row| day_of(row).is_some_and(|on| on < day)).filter_map(|row| value_of(row)).collect();        let usual = (!before.is_empty()).then(|| before.iter().sum::<f64>() / before.len() as f64);        metrics.push(json!({            "metric": metric.key,            "unit": metric.unit,            "fold": metric.fold,            "value": today.get("value").cloned().unwrap_or(Value::Null),            "min": today.get("min").cloned().unwrap_or(Value::Null),            "max": today.get("max").cloned().unwrap_or(Value::Null),            "state": today.get("state").cloned().unwrap_or(Value::Null),            "usual": usual.map(round),        }));    }    let stage = |key: &str| metrics.iter().find(|metric| metric["metric"] == key).map(|metric| metric["value"].clone()).unwrap_or(Value::Null);    let sleep = json!({        "asleep": stage("sleep_asleep"),        "in_bed": stage("sleep_in_bed"),        "core": stage("sleep_core"),        "deep": stage("sleep_deep"),        "rem": stage("sleep_rem"),        "awake": stage("sleep_awake"),    });    let mut workouts: Vec<&Map<String, Value>> = workouts.iter().filter(|row| day_of(row) == Some(day)).collect();    workouts.sort_by(|a, b| a.get("started_at").and_then(Value::as_str).cmp(&b.get("started_at").and_then(Value::as_str)));    let mut measurements: Vec<&Map<String, Value>> = measurements.iter().filter(|row| day_of(row) == Some(day)).collect();    measurements.sort_by(|a, b| a.get("measured_at").and_then(Value::as_str).cmp(&b.get("measured_at").and_then(Value::as_str)));    json!({        "day": day,        "metrics": metrics,        "sleep": sleep,        "workouts": workouts.iter().map(|row| workout(row)).collect::<Vec<_>>(),        "measurements": measurements.iter().map(|row| measurement(row)).collect::<Vec<_>>(),    })}fn pick(row: &Map<String, Value>, keys: &[&str]) -> Value {    let mut out = Map::new();    for key in keys {        out.insert((*key).to_string(), row.get(*key).cloned().unwrap_or(Value::Null));    }    Value::Object(out)}fn workout(row: &Map<String, Value>) -> Value {    pick(row, &["id", "kind", "day", "started_at", "ended_at", "minutes", "distance_m", "energy_kcal", "heart_rate_avg", "heart_rate_max", "device"])}fn measurement(row: &Map<String, Value>) -> Value {    pick(row, &["id", "kind", "day", "measured_at", "value", "second", "unit", "context"])}/// A range, `from` to `to` inclusive: each metric that holds a day in it,/// in the catalogue's order, with its days (ascending), mean, least, most,/// latest and, where days add up, total; the workouts' count and minutes/// by kind.pub fn range(from: &str, to: &str, days: &[Map<String, Value>], workouts: &[Map<String, Value>]) -> Value {    let within = |row: &&Map<String, Value>| day_of(row).is_some_and(|day| day >= from && day <= to);    let mut metrics = Vec::new();    for metric in catalog::METRICS {        let mut series: Vec<(&str, Option<f64>, Option<&Value>)> = days            .iter()            .filter(within)            .filter(|row| row.get("metric").and_then(Value::as_str) == Some(metric.key))            .filter_map(|row| Some((day_of(row)?, value_of(row), row.get("state"))))            .collect();        if series.is_empty() {            continue;        }        series.sort_by(|a, b| a.0.cmp(b.0));        let values: Vec<f64> = series.iter().filter_map(|(_, value, _)| *value).collect();        let sum: f64 = values.iter().sum();        let mean = (!values.is_empty()).then(|| sum / values.len() as f64);        metrics.push(json!({            "metric": metric.key,            "unit": metric.unit,            "fold": metric.fold,            "days": series.iter().map(|(day, value, state)| json!({ "day": day, "value": value.map(round), "state": state.cloned().unwrap_or(Value::Null) })).collect::<Vec<_>>(),            "days_with": series.len(),            "mean": mean.map(round),            "min": values.iter().copied().reduce(f64::min).map(round),            "max": values.iter().copied().reduce(f64::max).map(round),            "latest": series.iter().rev().find_map(|(_, value, _)| *value).map(round),            "total": (totals(metric.fold) && !values.is_empty()).then(|| round(sum)),        }));    }    let mut kinds: BTreeMap<String, (i64, f64)> = BTreeMap::new();    let mut count = 0i64;    let mut minutes = 0f64;    for row in workouts.iter().filter(within) {        let kind = row.get("kind").and_then(Value::as_str).unwrap_or("other").to_string();        let length = row.get("minutes").and_then(Value::as_f64).unwrap_or(0.0);        let held = kinds.entry(kind).or_default();        held.0 += 1;        held.1 += length;        count += 1;        minutes += length;    }    let mut by_kind: Vec<(String, (i64, f64))> = kinds.into_iter().collect();    by_kind.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1).then(a.0.cmp(&b.0)));    json!({        "from": from,        "to": to,        "metrics": metrics,        "workouts": {            "count": count,            "minutes": round(minutes),            "kinds": by_kind.into_iter().map(|(kind, (count, minutes))| json!({ "kind": kind, "count": count, "minutes": round(minutes) })).collect::<Vec<_>>(),        },    })}