//! Two counts a page's facts line says (Spec 11 facts): a note's length in//! words, and how often a repeating todo was done before this occurrence.use cotton_core::definitions::TableDefinition;use rusqlite::types::ValueasSqlValue;use serde_json::Value;usesuper::{sql_err, Stored};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::Valid;/// A body's words: what whitespace separates, punctuation alone not counted.pubfn word_count(text: &str) -> u64 { text.split_whitespace().filter(|word| word.chars().any(char::is_alphanumeric)).count() as u64}/// Answer `note.words` and `todo.done_before` on every record read.pub(super) fn record_counts(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {if !definition.has_engine() || records.is_empty() {returnOk(()); }match definition.id.as_str() {"note" => {for record in records.iter_mut() {ifletSome(body) = record.data.get("body").and_then(Value::as_str) {let words = word_count(body); record.data.insert("words".into(), Value::from(words)); } } }"todo" => {let driver = ctx.read.driver();for record in records.iter_mut() {// Only an occurrence of a series has a before; a one-off says nothing.// A series is said only while its recurrence is present (a// soft reference reads as empty once that row is gone).let sql = format!("SELECT count(*) AS n FROM cotton_todos o JOIN cotton_todos t ON t.id = ? AND t.workspace_id = o.workspace_id WHERE o.workspace_id = ? AND {} AND o.recurrence_id = t.recurrence_id AND o.id <> t.id AND o.status = 'done' AND o.trashed_at IS NULL AND o.occurrence_at < t.occurrence_at", cotton_store::soft_refs::soft_names("t.recurrence_id", "cotton_todo_recurrences"), );let row = driver .get( &sql, &[SqlValue::Text(record.id.clone()), SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(sql_err)?;let done = row.and_then(|row| row.int("n")).unwrap_or(0); record.data.insert("done_before".into(), Value::from(done)); } } _ => {} }Ok(())}