//! 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};usecrate::mcp::handlers::tables::{figure_total_in_snapshot, FigureRows, FigureTotal};usecrate::mcp::protocol::ToolFailure;usecrate::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`.pubfn worked_figures(db: &Driver, workspace: &str, today: NaiveDate) -> Result<Map<String, Value>, ToolFailure> {let definitions = crate::definitions::shared_table_definitions_from_driver(db, workspace)?;let read = ReadDb::new(db, workspace);letmut lines = Map::new();letmut resolved = FigureRows::new();for definition in &definitions.definitions {letSome(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.pubfn part_line(db: &Driver, workspace: &str, part: &Value, today: NaiveDate) -> Result<Option<String>, ToolFailure> {letmut summary = Map::new();for key in ["table", "op", "column", "where", "period"] {ifletSome(value) = part.get(key).filter(|value| !value.is_null()) { summary.insert(key.to_string(), value.clone()); } }letmut figure = serde_json::json!({ "read": "part", "many": part["many"], "summary": summary });ifletSome(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, &mutFigureRows::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: &mutFigureRows,) -> Vec<String> {letSome((column, _)) = cotton_core::records::opening_column(definition) else { returnVec::new() };letSome(mut tool) = definition.tool.clone() else { returnVec::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)]structWorked { 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: &mutFigureRows,) -> Vec<(String, String)> {letmut totals: BTreeMap<&str, Option<Worked>> = BTreeMap::new();for figure in &tool.figures {letSome(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()));letmut 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, };ifletSome(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<Worked>>, plus: &[String], minus: &[String]) -> Option<Worked> {letmut sum = 0_i64;letmut currency: Option<String> = None;letmut 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 {returnNone; }// A term with no rows has no currency, and adds nothing to disagree with.ifletSome(code) = worked.total.currency.filter(|_| worked.total.total != 0) {match ¤cy {Some(held) if *held != code => returnNone, _ => 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<String> {let total = &worked.total;if total.total == 0 || total.mixed {returnNone; }if !worked.amount && total.total == 1 {ifletSome(one) = &figure.one {returnSome(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() };letmut 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;