//! The figures a tool's card says that its definition works out itself //! (`tool.figures[]` with a `summary` or a `formula`): Money's "In ₹… · Out //! ₹… · Worth ₹…", read as data, never a count written in code. //! //! Home asks this once per read ([`worked_figures`]): each summary is ONE //! indexed read of its table ([`crate::mcp::handlers::tables::figure_total`]), //! a formula adds and takes away the tool's summaries, and the core says the //! line in the figure's own words — an amount in its own currency, a lowest //! or highest with the day of its row — so the //! app draws the line and composes nothing. A figure at zero says nothing //! (figure or silence); amounts in more than one currency have no one total //! and say nothing either. A figure its table cannot answer is left out and //! logged, never Home's failure: the app never throws on a definition. use std::collections::BTreeMap; use chrono::NaiveDate; use cotton_core::definitions::{ColumnType, SummaryOp, TableDefinition, ToolFigure, ToolHome}; use cotton_store::driver::Driver; use serde_json::{Map, Value}; use crate::mcp::handlers::tables::{figure_total_in_snapshot, FigureRows, FigureTotal}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::ReadDb; /// Every worked figure of every tool `workspace` holds, by its `read`: the /// line the card says, or nothing for a figure that is silent or a `term`. pub fn worked_figures(db: &Driver, workspace: &str, today: NaiveDate) -> Result, ToolFailure> { let definitions = crate::definitions::shared_table_definitions_from_driver(db, workspace)?; let read = ReadDb::new(db, workspace); let mut lines = Map::new(); let mut resolved = FigureRows::new(); for definition in &definitions.definitions { let Some(tool) = &definition.tool else { continue }; if !tool.figures.iter().any(worked) { continue; } for (figure, line) in tool_lines(&read, &definitions.definitions, definition, tool, today, &mut resolved) { lines.insert(figure, Value::String(line)); } } Ok(lines) } /// A Home's `figure` part (a board part: `table`, `op`, `column`, `where`, /// `period`, and the words `many` and `one`) worked out on `workspace` and /// said as a tool card's figure is — the same total, the same words, silence /// at zero. A table the database does not hold is refused by name. pub fn part_line(db: &Driver, workspace: &str, part: &Value, today: NaiveDate) -> Result, ToolFailure> { let mut summary = Map::new(); for key in ["table", "op", "column", "where", "period"] { if let Some(value) = part.get(key).filter(|value| !value.is_null()) { summary.insert(key.to_string(), value.clone()); } } let mut figure = serde_json::json!({ "read": "part", "many": part["many"], "summary": summary }); if let Some(one) = part.get("one").filter(|one| !one.is_null()) { figure["one"] = one.clone(); } let figure: ToolFigure = serde_json::from_value(figure).map_err(|error| ToolFailure::new(format!("That figure does not read: {error}")))?; let summary = figure.summary.as_ref().expect("a part's figure carries its summary"); let definitions = crate::definitions::shared_table_definitions_from_driver(db, workspace)?; let table = definitions .definitions .iter() .find(|table| table.id == summary.table) .ok_or_else(|| crate::definitions::no_tool_draws(db, workspace))?; let amount = summary.op != SummaryOp::Count && summary.column.as_deref().and_then(|key| table.column(key)).is_some_and(|column| column.column_type == ColumnType::Amount); let total = figure_total_in_snapshot(&ReadDb::new(db, workspace), table, summary, today, &mut FigureRows::new())?; Ok(said(&figure, &Worked { total, amount }, &cotton_core::records::amount::MoneyWords::of_rows(&crate::presentation::line_rows(db, workspace)))) } fn worked(figure: &ToolFigure) -> bool { figure.summary.is_some() || figure.formula.is_some() } /// A running list's extrema are the same definition figures its tool says /// on Home. Only summaries of this list's running column belong beside its /// opening; unrelated counts, movement totals and other tables do not. /// The caller supplies the complete window, before pagination or search. pub(crate) fn running_head_lines( read: &ReadDb<'_>, definition: &TableDefinition, today: NaiveDate, resolved: &mut FigureRows, ) -> Vec { let Some((column, _)) = cotton_core::records::opening_column(definition) else { return Vec::new() }; let Some(mut tool) = definition.tool.clone() else { return Vec::new() }; tool.figures.retain(|figure| figure.summary.as_ref().is_some_and(|summary| { summary.table == definition.id && summary.column.as_deref() == Some(column) && matches!(summary.op, SummaryOp::Min | SummaryOp::Max) })); tool_lines(read, std::slice::from_ref(definition), definition, &tool, today, resolved) .into_iter().map(|(_, line)| line).collect() } /// One worked total and whether it is an amount (said in its currency). #[derive(Debug, Clone)] struct Worked { total: FigureTotal, amount: bool, } /// The lines of one tool's worked figures, by `read`. fn tool_lines( read: &ReadDb<'_>, tables: &[TableDefinition], home: &TableDefinition, tool: &ToolHome, today: NaiveDate, resolved: &mut FigureRows, ) -> Vec<(String, String)> { let mut totals: BTreeMap<&str, Option> = BTreeMap::new(); for figure in &tool.figures { let Some(summary) = &figure.summary else { continue }; let worked = tables .iter() .find(|table| table.id == summary.table) .ok_or_else(|| crate::definitions::no_tool_draws(read.driver(), read.workspace_id())) .and_then(|table| { let amount = summary.op != SummaryOp::Count && summary .column .as_deref() .and_then(|key| table.column(key)) .is_some_and(|column| column.column_type == ColumnType::Amount); figure_total_in_snapshot(read, table, summary, today, resolved).map(|total| Worked { total, amount }) }); match worked { Ok(worked) => { totals.insert(figure.read.as_str(), Some(worked)); } Err(failure) => { tracing::warn!(tool = home.id.as_str(), figure = figure.read.as_str(), %failure, "a tool figure could not be worked out"); totals.insert(figure.read.as_str(), None); } } } let words = cotton_core::records::amount::MoneyWords::of_rows(&crate::presentation::line_rows(read.driver(), read.workspace_id())); let mut lines = Vec::new(); for figure in tool.figures.iter().filter(|figure| worked(figure) && !figure.term) { let worked = match (&figure.summary, &figure.formula) { (Some(_), _) => totals.get(figure.read.as_str()).cloned().flatten(), (None, Some(formula)) => combine(&totals, &formula.plus, &formula.minus), (None, None) => None, }; if let Some(line) = worked.and_then(|worked| said(figure, &worked, &words)) { lines.push((figure.read.clone(), line)); } } lines } /// The totals of `plus` less those of `minus`: nothing when any term is /// missing or the terms are in more than one currency. fn combine(totals: &BTreeMap<&str, Option>, plus: &[String], minus: &[String]) -> Option { let mut sum = 0_i64; let mut currency: Option = None; let mut amount = false; for (term, sign) in plus.iter().map(|term| (term, 1_i64)).chain(minus.iter().map(|term| (term, -1_i64))) { let worked = totals.get(term.as_str()).cloned().flatten()?; if worked.total.mixed { return None; } // A term with no rows has no currency, and adds nothing to disagree with. if let Some(code) = worked.total.currency.filter(|_| worked.total.total != 0) { match ¤cy { Some(held) if *held != code => return None, _ => currency = Some(code), } } amount |= worked.amount; sum = sum.checked_add(sign.checked_mul(worked.total.total)?)?; } Some(Worked { total: FigureTotal { total: sum, currency, mixed: false, on: None }, amount }) } /// The figure's line for its total: silence at zero or across currencies; /// `one` for a count of exactly one; else `many` with the total for `{n}` and /// a lowest or highest's day for `{date}` ("20 Oct"; silence with no day). fn said(figure: &ToolFigure, worked: &Worked, words: &cotton_core::records::amount::MoneyWords) -> Option { let total = &worked.total; if total.total == 0 || total.mixed { return None; } if !worked.amount && total.total == 1 { if let Some(one) = &figure.one { return Some(one.clone()); } } let n = if worked.amount { cotton_core::records::amount::amount(total.total, total.currency.as_deref(), words).said(cotton_core::records::amount::MoneyForm::Money, words) } else { total.total.to_string() }; let mut line = figure.many.replace("{n}", &n); if line.contains("{date}") { let on = total.on.as_deref().and_then(|on| on.get(..10))?; let day = NaiveDate::parse_from_str(on, "%Y-%m-%d").ok()?; line = line.replace("{date}", &day.format("%-d %b").to_string()); } Some(line) } #[cfg(test)] #[path = "tool_figures_tests.rs"] mod tests;