//! Home's Today deck reads (`cotton_core::rules::today_deck`): //! `cards.birthdays {days?, timezone?}` — the people whose birthday comes //! round today and in the days after; `cards.moneyDue {days?, timezone?}` — //! expected transactions and subscriptions' next charges in the same days; //! `cards.factLabels {}` — the words each face's facts are labelled with. //! A database without the money tables owes nothing. use crate::methods::MethodError; use crate::shell::client::ClientController; use cotton_core::definitions::TableDefinition; use cotton_core::records::page::Words; use cotton_core::rules::today_deck::{self, MoneyRows, DAYS_AHEAD}; use cotton_core::transforms::zoned_clock; use serde_json::{json, Map, Value}; pub fn birthdays(client: &ClientController, request: &Value) -> Result { let (zone, today, days) = reach(client, request)?; let people = match table(client, "person")? { Some(_) => rows(client, "person", json!({ "birthday": { "present": true } }))?, None => Vec::new(), }; let words = words(client); Ok(json!({ "birthdays": today_deck::birthdays(&people, today, days, &zone, &words) })) } pub fn money_due(client: &ClientController, request: &Value) -> Result { let (zone, today, days) = reach(client, request)?; let read = |id: &str, filter: Value| -> Result { match table(client, id)? { Some(definition) => Ok(Some((definition, rows(client, id, filter)?))), None => Ok(None), } }; let transactions = read("transaction", json!({ "status": "expected" }))?; let subscriptions = read("subscription", json!({ "status": "active" }))?; let words = words(client); let due = today_deck::money_due(money(&transactions), money(&subscriptions), today, days, &zone, client.clock().now(), &words); Ok(json!({ "due": due })) } pub fn fact_labels(client: &ClientController, _request: &Value) -> Result { let rows = client .with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))) .unwrap_or_default(); Ok(json!({ "labels": today_deck::fact_labels(&rows) })) } type Held = Option<(TableDefinition, Vec<(String, Map)>)>; fn money(held: &Held) -> Option> { held.as_ref().map(|(definition, rows)| MoneyRows { definition, rows }) } /// The reader's zone, today in it, and how many days ahead to read. fn reach(client: &ClientController, request: &Value) -> Result<(String, i64, i64), MethodError> { let zone = request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string(); let today = zoned_clock::local_day(client.clock().now().timestamp_millis(), &zone) .map_err(|_| MethodError::new("bad_request", "timezone is a named time zone"))?; let days = match request.get("days") { None | Some(Value::Null) => DAYS_AHEAD, Some(days) => days.as_i64().filter(|days| (0..=366).contains(days)).ok_or_else(|| MethodError::new("bad_request", "days is a count of days ahead, 0 to 366"))?, }; Ok((zone, today, days)) } fn words(client: &ClientController) -> Words { let rows = client .with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))) .unwrap_or_default(); Words::of_rows(&rows) } /// The table's definition, or none where this database holds no such table. fn table(client: &ClientController, id: &str) -> Result, MethodError> { let mut found = None; client .read_rows("cards.today", &mut |ctx| { found = cotton_tools::definitions::shared_table_definitions(ctx) .map_err(|failure| failure.to_string())? .definitions .iter() .find(|definition| definition.id == id) .cloned(); Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; Ok(found) } /// Every row of `table` the filter holds, page by page, as (id, columns). fn rows(client: &ClientController, table: &str, filter: Value) -> Result)>, MethodError> { let mut found = Vec::new(); let mut page = 0; loop { let answer = client .read_tool("list_records", json!({ "table": table, "where": filter, "limit": 200, "page": page }).as_object().unwrap()) .map_err(|why| MethodError::new("unreadable", why))?; for record in answer["records"].as_array().into_iter().flatten() { let data = record.get("data").unwrap_or(record); let (Some(id), Some(columns)) = (record["id"].as_str().or(data["id"].as_str()), data.as_object()) else { continue }; found.push((id.to_string(), columns.clone())); } match answer["next_page"].as_i64() { Some(next) if next > page => page = next, _ => return Ok(found), } } } #[cfg(test)] #[path = "today_deck_tests.rs"] mod tests;