//! RECORDS — one record of any table, read and written through its //! [`TableDefinition`], and the CHANGE every write leaves behind. //! //! The pure half of the generic verbs (`cotton_tools::records`): what a value //! of each column type looks like, whether a create or a patch fits a table, //! what a write changed, and what undoing a change must write. Nothing here //! opens a file; the tools read the stored state, ask these functions, and //! write what they answer. //! //! # Value encoding //! //! The shared definition format names the eleven column types but not their //! JSON. It is decided here, once, and [`check_value`] enforces it: //! //! | type | JSON value | //! |----------------------|-----------------------------------------------------| //! | `text`, `longtext` | a string | //! | `date` | a `"YYYY-MM-DD"` string, a real calendar day | //! | `time` | an `"HH:MM"` string, 24-hour | //! | `number` | a JSON number | //! | `amount` | a JSON INTEGER in minor units (paise, cents) | //! | `choice` | one of the column's `choices`, exactly | //! | `link` | the target record's id, a non-empty string | //! | `photo`, `file` | the media object key, a non-empty string | //! | `bool` | `true` or `false` | //! //! An amount is never a float: `12.5` and even `12.0` are REFUSED, never //! rounded, because a rounded amount is a wrong amount (the money rule). A //! `null` clears a column, and is refused on a required one. A key the //! definition does not declare is refused rather than kept: a value no column //! names would never be drawn and never be found. //! //! A BUILT-IN table's own timestamp columns (`due_at`, `updated_at`) are //! answered as the RFC 3339 strings their engine stores, and a write to a //! built-in's date column may send either form — its engine decides what it //! keeps ([`validate_create`] and [`validate_patch`] ask the definition). The //! A table a person defined takes days, except `last_revealed` on a secret //! reveal policy: its audit write takes an exact RFC 3339 instant. //! //! # Changes //! //! Every write is one [`Change`]: a byline (who wrote it), the values //! BEFORE and AFTER, and the verb. Create's `before` is null and its `after` //! the whole record; delete is the mirror; update and link carry only the //! keys that changed; reorder carries each moved record's position keyed by //! its id. [`plan_undo`] turns a change back into the write that reverses it, //! and refuses when undoing would overwrite something written since. use std::collections::BTreeSet; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use crate::definitions::{Column, ColumnFormat, ColumnType, SummaryOp, TableDefinition}; pub mod amount; pub mod backup; pub mod card; pub mod chart; pub mod live; pub mod moves; pub mod page; pub mod receipt; pub mod refusal; pub use chart::{chart, chart_at, ChartBucket, ChartSeries, LeftOut}; /// One record's values, keyed by column key. pub type Data = Map; /// The public value of an account number: its last four ASCII digits. /// Imported masks and separators carry no additional identifying text. pub fn account_number_ending(number: &str) -> String { let mut digits: Vec = number.chars().filter(char::is_ascii_digit).rev().take(4).collect(); digits.reverse(); digits.into_iter().collect() } /// Project typed stored columns into their public read values. Never use this /// projection as the baseline of a mutation: the stored identifier stays intact. pub fn project_read_data(definition: &TableDefinition, data: &mut Data) { for column in &definition.columns { if column.column_type == ColumnType::AccountNumber || (definition.id == "money_account" && column.key == "number_mask") { if let Some(value) = data.get_mut(&column.key) { if !value.is_null() { *value = value.as_str().map(account_number_ending).map(Value::from).unwrap_or(Value::Null); } } } } } /// Borrow ordinary records; copy only when a private account value needs a /// public projection. Lists must not copy large text bodies for this check. pub fn public_read_data<'a>(definition: &TableDefinition, data: &'a Data) -> std::borrow::Cow<'a, Data> { if reads_public_as_stored(definition) { return std::borrow::Cow::Borrowed(data); } let mut public = data.clone(); project_read_data(definition, &mut public); std::borrow::Cow::Owned(public) } /// Whether a read says every value of `definition` as it is stored /// (`public_read_data` changes nothing): no account number is masked. pub fn reads_public_as_stored(definition: &TableDefinition) -> bool { !definition.columns.iter().any(|column| column.column_type == ColumnType::AccountNumber || (definition.id == "money_account" && column.key == "number_mask")) } /// Why a record, a patch or an undo is refused — each one a typed fact the /// reading edge says in the database's `refusal` lines (`records.*`), a /// sentence a person can act on. `Display` says the kit's words. #[derive(Debug, Clone, PartialEq, Eq)] pub enum RecordError { NotAnObject, UnknownColumn { plural: String, column: String }, Required { column: String }, Readonly { column: String }, Computed { column: String }, WrongType { column: String, wanted: Wanted, found: Found }, NotWholeAmount { column: String, found: String }, NotAChoice { column: String, found: String, choices: String }, NothingToChange, NoOrder { plural: String }, BadReorder, NotALink { column: String }, AlreadyUndone, ChangedSince { what: Changed }, Malformed(Malformation), MoveUndoNeedsCoordinator, RevealRefused(RevealRefusal), BadWhere { column: String, reason: WhereRefusal }, CannotNarrow { plural: String, column: String }, } /// What a column takes, named in a [`RecordError::WrongType`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Wanted { Attachments, Place, Text, WebAddress, Date, Time, Number, Bytes, MinorUnits, ChoiceList, OneChoice, LinkId, MediaKey, Bool, DateColumn, NumberOrAmountColumn, LinkColumn, Timezone, } impl Wanted { fn line(self) -> &'static str { match self { Wanted::Attachments => "attachments", Wanted::Place => "place", Wanted::Text => "text", Wanted::WebAddress => "web_address", Wanted::Date => "date", Wanted::Time => "time", Wanted::Number => "number", Wanted::Bytes => "bytes", Wanted::MinorUnits => "minor_units", Wanted::ChoiceList => "choice_list", Wanted::OneChoice => "one_choice", Wanted::LinkId => "link_id", Wanted::MediaKey => "media_key", Wanted::Bool => "bool", Wanted::DateColumn => "date_column", Wanted::NumberOrAmountColumn => "number_or_amount_column", Wanted::LinkColumn => "link_column", Wanted::Timezone => "timezone", } } } /// What a [`RecordError::WrongType`] found instead. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Found { /// The value sent, as `describe` writes it. Value(String), /// A definition's column of another type (a chart's or a sparkline's). AnotherType, } /// What changed since an undone change was made. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Changed { Record { id: String }, Order, /// Named by the tool that refuses (an album and why). Said(String), } /// Why a change cannot be undone, its record being malformed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Malformation { NoRecord, NotAnObject { side: String }, } /// Why a copy of a revealed value is refused. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RevealRefusal { InvalidCount, AlreadyCopied, Incomplete, } /// Why a `where` is refused. #[derive(Debug, Clone, PartialEq, Eq)] pub enum WhereRefusal { NotAnObject { found: String }, OneRecordId { column: String, found: String }, Null, OneShape, ValuesEmpty, NotEmpty, MonthRange { found: String }, MonthOnlyDate, WithinDaysRange { found: String }, WithinDaysOnlyDate, BoundNumber { found: String }, BoundOnlyNumber, OnWord { found: String }, OnOnlyDate, PresentBool { found: String }, NotACondition { said: String }, EachOneValue { found: String }, AddableToOneAlbum, NoNot { plural: String }, NoMonth { plural: String }, NoWithinDays { plural: String }, NoBound { plural: String }, NoOn { plural: String }, } /// The verb a change records — what the write DID. /// /// An undo records the verb it performed, not "undo": undoing a create is a /// `delete`, undoing a delete a `restore`. The change it reversed points at it /// through `undone_by`, and it can itself be undone like any other. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Verb { Create, Update, Delete, Restore, Reorder, Link, /// A cross-database coordinator moved the record's home. Move, /// The destination half of a cross-database move. #[serde(rename = "move_in")] MoveIn, } impl Verb { pub const ALL: [Verb; 8] = [ Verb::Create, Verb::Update, Verb::Delete, Verb::Restore, Verb::Reorder, Verb::Link, Verb::Move, Verb::MoveIn, ]; pub fn as_str(self) -> &'static str { match self { Verb::Create => "create", Verb::Update => "update", Verb::Delete => "delete", Verb::Restore => "restore", Verb::Reorder => "reorder", Verb::Link => "link", Verb::Move => "move", Verb::MoveIn => "move_in", } } pub fn parse(text: &str) -> Option { Verb::ALL.into_iter().find(|verb| verb.as_str() == text) } } /// One change, as `cotton_changes` stores it and every write answers it. /// /// `record_id` is `None` for a change that spans several records (a reorder). #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Change { pub id: String, pub table_id: String, pub record_id: Option, pub verb: Verb, pub byline: String, pub before: Value, pub after: Value, pub created_at: String, pub undone_by: Option, } /// Columns a generic read NEVER answers, whatever a definition declares: the /// sealed value of a password, its hint, a document's password, and every /// digest or sealed token the store keeps. A built-in's read columns are its /// shipped definition's, intersected with the store's own columns, less these. pub const SENSITIVE_COLUMNS: &[&str] = &[ "value_enc", "hint", "password", "secret_hash", "token_hash", "token_digest", "refresh_token_enc", "sync_token", ]; /// Is `key` a column no generic read answers? The named ones, and anything /// shaped like a sealed value or a digest. pub fn is_sensitive_column(key: &str) -> bool { SENSITIVE_COLUMNS.contains(&key) || key.ends_with("_enc") || key.ends_with("_hash") || key.ends_with("_digest") || key.contains("password") } /// The key a record's PICTURES travel under, beside its columns: a list of /// `{kind, id, caption}` (`kind` photo, video or document; `caption` the /// record's own words for it, null for none). No column type holds a list of /// objects, so it is not a column: a read of a table whose engine keeps /// pictures ([`carries_attachments`]) answers it (absent when there are none), /// and a patch may write it — the WHOLE ordered list, null or `[]` taking every /// picture off — through that engine's own attachment write. pub const ATTACHMENTS_KEY: &str = "attachments"; /// The key a record's LINKS travel under, beside its columns: the records it /// points at as `[{table, id, title, container, when_kind, when}]`, answered by /// the engine (a thought's, the records it became). Read only, never a column. pub const LINKS_KEY: &str = "links"; /// The built-in tables whose engine keeps an ordered list of pictures on each /// record (`cotton_note_attachments`, `cotton_thought_attachments`). pub const ATTACHMENT_TABLES: &[&str] = &["note", "thought"]; /// Does a read of `definition` answer [`ATTACHMENTS_KEY`], and a patch take it? pub fn carries_attachments(definition: &TableDefinition) -> bool { definition.has_engine() && ATTACHMENT_TABLES.contains(&definition.id.as_str()) } /// The shape a patch's [`ATTACHMENTS_KEY`] must have — the engine checks the /// rest (that each picture exists, how many a record may carry). fn check_attachments(value: &Value) -> Result<(), RecordError> { let wrong = || RecordError::WrongType { column: ATTACHMENTS_KEY.to_string(), wanted: Wanted::Attachments, found: Found::Value(describe(value)), }; match value { Value::Null => Ok(()), Value::Array(entries) => { for entry in entries { let fits = entry.as_object().is_some_and(|entry| { entry.get("kind").is_some_and(Value::is_string) && entry.get("id").is_some_and(Value::is_string) && entry .get("caption") .is_none_or(|caption| caption.is_null() || caption.is_string()) }); if !fits { return Err(wrong()); } } Ok(()) } _ => Err(wrong()), } } /// The byline a write carries when the caller names nobody. pub const DEFAULT_ASSISTANT_BYLINE: &str = "assistant"; /// The byline the app's own writes carry. pub const USER_BYLINE: &str = "user"; // ── values ────────────────────────────────────────────────────────────────── fn describe(value: &Value) -> String { match value { Value::Null => "null".into(), Value::Bool(b) => b.to_string(), Value::Number(n) => n.to_string(), Value::String(s) => format!("{s:?}"), Value::Array(_) => "a list".into(), Value::Object(_) => "an object".into(), } } /// `"YYYY-MM-DD"`, exactly, and a day the calendar has. pub fn is_date(text: &str) -> bool { text.len() == 10 && chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d") .is_ok_and(|day| day.format("%Y-%m-%d").to_string() == text) } /// `"--MM-DD"`, exactly: a yearly date's day with no year (a birthday whose /// year nobody knows), a day some year has — 29 February included. pub fn is_yearless_date(text: &str) -> bool { text.strip_prefix("--").is_some_and(|month_day| is_date(&format!("2000-{month_day}"))) } /// `"HH:MM"`, exactly, 24-hour. pub fn is_time(text: &str) -> bool { text.len() == 5 && chrono::NaiveTime::parse_from_str(text, "%H:%M") .is_ok_and(|time| time.format("%H:%M").to_string() == text) } /// An RFC 3339 instant, the form a built-in engine stores its timestamps in. /// An absolute http(s) address with a host — what a tap can open. Other /// schemes are refused: a `url` column is a place on the web, not a handle /// into another app. pub fn is_web_address(text: &str) -> bool { match url::Url::parse(text) { Ok(parsed) => { matches!(parsed.scheme(), "http" | "https") && parsed.host_str().is_some_and(|host| !host.is_empty()) && text.trim() == text } Err(_) => false, } } pub fn is_instant(text: &str) -> bool { chrono::DateTime::parse_from_rfc3339(text).is_ok() } /// Does `value` (never null — the caller decides what null means) fit /// `column`? See the module header for the encoding. pub fn check_value(column: &Column, value: &Value) -> Result<(), RecordError> { check_value_as(column, value, false) } /// [`check_value`] for a column of `definition`: a built-in's date column also /// takes an RFC 3339 instant, and so does any date column read `ago` — a /// value said against now ("5 min ago") is an instant by its nature, and the /// owner's Machines tool (11 Oct 2026) is the first user table to keep one; /// so is one read as a calendar date and time, which has no time without one. pub fn check_value_in( definition: &TableDefinition, column: &Column, value: &Value, ) -> Result<(), RecordError> { let reveal_timestamp = column.key == "last_revealed" && definition.columns.iter().any(|c| c.reveal.is_some()); let said_as_instant = matches!(column.format, Some(ColumnFormat::Ago | ColumnFormat::CalendarDatetime | ColumnFormat::Countdown)); check_value_as(column, value, definition.has_engine() || reveal_timestamp || said_as_instant) } fn check_value_as(column: &Column, value: &Value, instants: bool) -> Result<(), RecordError> { let wrong = |wanted: Wanted| RecordError::WrongType { column: column.key.clone(), wanted, found: Found::Value(describe(value)), }; match column.column_type { ColumnType::Place => { if value.is_string() || value.as_object().is_some_and(|object| { object.len() == 1 && object.get("place").and_then(Value::as_str).is_some_and(place::valid_id) }) || place::kept(value).is_some() { Ok(()) } else { Err(wrong(Wanted::Place)) } } ColumnType::Text | ColumnType::Longtext | ColumnType::AccountNumber => { value.as_str().map(|_| ()).ok_or_else(|| wrong(Wanted::Text)) } ColumnType::Url => match value.as_str() { Some(text) if is_web_address(text) => Ok(()), _ => Err(wrong(Wanted::WebAddress)), }, ColumnType::Date => match value.as_str() { Some(text) if is_date(text) => Ok(()), // A yearly date is written as every read says it: "--MM-DD" where // the year is not known. Some(text) if column.yearly == Some(true) && is_yearless_date(text) => Ok(()), Some(text) if instants && is_instant(text) => Ok(()), _ => Err(wrong(Wanted::Date)), }, ColumnType::Time => match value.as_str() { Some(text) if is_time(text) => Ok(()), _ => Err(wrong(Wanted::Time)), }, ColumnType::Number => { if value.is_number() { Ok(()) } else { Err(wrong(Wanted::Number)) } } ColumnType::Bytes => { if value.as_u64().is_some() { Ok(()) } else { Err(wrong(Wanted::Bytes)) } } ColumnType::Amount => { if value.is_i64() { Ok(()) } else if value.is_number() { Err(RecordError::NotWholeAmount { column: column.key.clone(), found: describe(value), }) } else { Err(wrong(Wanted::MinorUnits)) } } // A several-choice column holds a list, each entry one of its choices. ColumnType::Choice if column.multiple == Some(true) => { let choices = column.choices.as_deref().unwrap_or(&[]); let Some(items) = value.as_array() else { return Err(wrong(Wanted::ChoiceList)); }; for item in items { match item.as_str() { Some(text) if choices.iter().any(|choice| choice == text) => {} Some(text) => { return Err(RecordError::NotAChoice { column: column.key.clone(), found: text.to_string(), choices: choices.join(", "), }) } None => return Err(wrong(Wanted::ChoiceList)), } } Ok(()) } // A choice column whose choices are the record's own (`choices_from`) // and none of the definition's: the engine that // answers those choices judges the value on the write, here only its // shape. ColumnType::Choice if column.choices.is_none() && column.choices_from.is_some() => match value.as_str() { Some(_) => Ok(()), None => Err(wrong(Wanted::OneChoice)), }, ColumnType::Choice => { let choices = column.choices.as_deref().unwrap_or(&[]); match value.as_str() { Some(text) if choices.iter().any(|choice| choice == text) => Ok(()), Some(text) => Err(RecordError::NotAChoice { column: column.key.clone(), found: text.to_string(), choices: choices.join(", "), }), None => Err(wrong(Wanted::OneChoice)), } } ColumnType::Link => match value.as_str() { Some(text) if !text.trim().is_empty() => Ok(()), _ => Err(wrong(Wanted::LinkId)), }, ColumnType::Photo | ColumnType::File => match value.as_str() { Some(text) if !text.trim().is_empty() => Ok(()), _ => Err(wrong(Wanted::MediaKey)), }, ColumnType::Bool => { if value.is_boolean() { Ok(()) } else { Err(wrong(Wanted::Bool)) } } } } fn as_object(value: &Value) -> Result<&Data, RecordError> { value.as_object().ok_or(RecordError::NotAnObject) } fn column_for<'d>(definition: &'d TableDefinition, key: &str) -> Result<&'d Column, RecordError> { definition .column(key) .ok_or_else(|| RecordError::UnknownColumn { plural: definition.plural.clone(), column: key.to_string(), }) } /// A computed column is the core's to work out: no write names it. fn not_computed(column: &Column) -> Result<(), RecordError> { match column.computed { Some(_) => Err(RecordError::Computed { column: column.key.clone(), }), None => Ok(()), } } /// Who authors a write, as the readonly rule reads it ([`Column::readonly`]). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Author<'a> { /// The app on a person's own device: its code making a record (the /// reader keeping a highlight), never a person typing, for the app offers /// no editor for a readonly column. App, /// An authenticated MCP token; a table's declared producer is one. Token(&'a str), /// Anyone else: an OAuth connector, Undo, a job, a package's rows. Other, } /// THE READONLY RULE: a readonly column is one no person edits. On a table /// an engine keeps, the engine writes it. Otherwise it is written by the /// table's declared producer, on create and patch alike; and, where the /// table declares no producer, by the app as it makes the record. Nothing /// else names it: no patch, and no create from a token or connector. fn authored_column(definition: &TableDefinition, column: &Column, author: Author<'_>, creating: bool) -> Result<(), RecordError> { not_computed(column)?; // Native engines enforce their own write policy. if definition.has_engine() || column.readonly != Some(true) { return Ok(()); } let allowed = match (&definition.producer, author) { (Some(producer), Author::Token(identity)) => !identity.is_empty() && identity == producer.token_id, (None, Author::App) => creating, _ => false, }; if allowed { Ok(()) } else { Err(RecordError::Readonly { column: column.key.clone() }) } } /// A new record's data, checked against its table: every key a declared /// column, every value of its column's type, every required column present. /// Nulls are dropped — a new record simply lacks them — and a column the data /// leaves out takes its `default` when it has one, so a row made from one /// typed line still lands in its table's resting state ("active"). pub fn validate_create(definition: &TableDefinition, data: &Value) -> Result { validate_create_as(definition, data, Author::Other) } /// Validate an authored create as its author, which the readonly rule reads. pub fn validate_create_as(definition: &TableDefinition, data: &Value, author: Author<'_>) -> Result { let data = as_object(data)?; let mut clean = Data::new(); for (key, value) in data { let column = column_for(definition, key)?; if value.is_null() { continue; } authored_column(definition, column, author, true)?; check_value_in(definition, column, value)?; clean.insert(key.clone(), value.clone()); } for column in &definition.columns { if let Some(default) = &column.default { if !clean.contains_key(&column.key) { clean.insert(column.key.clone(), default.clone()); } } } for column in &definition.columns { if column.required == Some(true) && !clean.contains_key(&column.key) { return Err(RecordError::Required { column: column.key.clone(), }); } } Ok(clean) } /// A patch, checked against its table: every key a declared column, every /// value of its type or null (clear), and no required column cleared. An /// empty patch is refused. pub fn validate_patch(definition: &TableDefinition, patch: &Value) -> Result { validate_patch_as(definition, patch, Author::Other) } /// Validate an authored patch as its author, which the readonly rule reads. pub fn validate_patch_as(definition: &TableDefinition, patch: &Value, author: Author<'_>) -> Result { let patch = as_object(patch)?; if patch.is_empty() { return Err(RecordError::NothingToChange); } for (key, value) in patch { if key == ATTACHMENTS_KEY && carries_attachments(definition) { check_attachments(value)?; continue; } let column = column_for(definition, key)?; authored_column(definition, column, author, false)?; if value.is_null() { if column.required == Some(true) { return Err(RecordError::Required { column: column.key.clone(), }); } continue; } check_value_in(definition, column, value)?; } Ok(patch.clone()) } /// A patch without the readonly columns it merely repeats: a key whose column is /// readonly and whose value is what the row already holds is not a write to it /// (architect, 21 Oct 2026 — the Machines and Quota reporters send the row's /// readonly key columns back unchanged), so it is dropped before validation and /// the rest of the patch is judged on its own; a changed readonly value stays /// and is refused by name as before. An absent stored value counts as null. pub fn without_unchanged_readonly(definition: &TableDefinition, patch: &Value, stored: &Data) -> Value { let Some(patch) = patch.as_object() else { return patch.clone() }; let kept: Data = patch .iter() .filter(|(key, value)| { let repeats = definition.column(key).is_some_and(|column| { column.readonly == Some(true) && column.computed.is_none() && stored.get(key.as_str()).unwrap_or(&Value::Null) == *value }); !repeats }) .map(|(key, value)| (key.clone(), value.clone())) .collect(); Value::Object(kept) } /// Validate persisted reveal metadata while the caller holds its write transaction. /// Once copied, a value cannot be un-revealed by clearing the count or Undo. pub fn validate_reveal_patch( definition: &TableDefinition, before: &Data, patch: &Data, ) -> Result<(), RecordError> { let policies: Vec<_> = definition .columns .iter() .filter_map(|c| c.reveal.as_ref()) .collect(); if policies.is_empty() || (!patch.contains_key("reveal_count") && !patch.contains_key("last_revealed")) { return Ok(()); } let count = match before.get("reveal_count") { None | Some(Value::Null) => 0.0, Some(value) => value .as_f64() .filter(|v| *v >= 0.0 && v.fract() == 0.0) .ok_or_else(|| RecordError::RevealRefused(RevealRefusal::InvalidCount))?, }; if policies.iter().any(|p| p.once) && count > 0.0 { return Err(RecordError::RevealRefused(RevealRefusal::AlreadyCopied)); } if patch.get("reveal_count").and_then(Value::as_f64) != Some(count + 1.0) || patch .get("last_revealed") .and_then(Value::as_str) .is_none_or(|s| !is_instant(s)) { return Err(RecordError::RevealRefused(RevealRefusal::Incomplete)); } Ok(()) } /// `data` with `patch` laid over it; a null in the patch removes the key. pub fn apply_patch(data: &Data, patch: &Data) -> Data { let mut out = data.clone(); for (key, value) in patch { if value.is_null() { out.remove(key); } else { out.insert(key.clone(), value.clone()); } } out } fn get_or_null<'a>(data: &'a Data, key: &str) -> &'a Value { data.get(key).unwrap_or(&Value::Null) } /// Two values are the same value: numbers compare by what they are worth, so /// `1` and `1.0` are one position. A value that has been through the file can /// come back in the other spelling (SQLite's JSON writes `1.0` as `1`), and a /// diff or an undo check that told them apart would see a change nobody made. pub fn same_value(a: &Value, b: &Value) -> bool { match (a, b) { (Value::Number(x), Value::Number(y)) => match (x.as_i64(), y.as_i64()) { (Some(x), Some(y)) => x == y, _ => x.as_f64() == y.as_f64(), }, (Value::Array(x), Value::Array(y)) => { x.len() == y.len() && x.iter().zip(y).all(|(x, y)| same_value(x, y)) } (Value::Object(x), Value::Object(y)) => { x.len() == y.len() && x.iter() .all(|(key, value)| y.get(key).is_some_and(|other| same_value(value, other))) } _ => a == b, } } /// What changed from `before` to `after`: only the keys whose value differs, /// each side holding its value or null where the key is absent. pub fn diff(before: &Data, after: &Data) -> (Data, Data) { let keys: BTreeSet<&String> = before.keys().chain(after.keys()).collect(); let mut was = Data::new(); let mut now = Data::new(); for key in keys { let (old, new) = (get_or_null(before, key), get_or_null(after, key)); if !same_value(old, new) { was.insert(key.clone(), old.clone()); now.insert(key.clone(), new.clone()); } } (was, now) } /// Do `current`'s values equal `expected`'s on every key `expected` names /// (absent reads as null)? pub fn matches_on(current: &Data, expected: &Data) -> bool { expected .iter() .all(|(key, value)| same_value(get_or_null(current, key), value)) } /// When a record was last edited. A change's `before` carries it (a note's as /// its column, a made table's record beside its data) so an Undo can put it /// back and leave no trace: the Home list orders by it. Every write moves it, /// so two writes never collide on it ([`plan_undo`]). pub const EDITED_AT: &str = "updated_at"; /// Are `a` and `b` the same record — every key of either equal (absent reads /// as null)? pub fn same_record(a: &Data, b: &Data) -> bool { matches_on(a, b) && matches_on(b, a) } // ── what a write changed beside the record ────────────────────────────────── /// The first character of a key a change's `before` or `after` holds that is /// NOT a column: what the built-in's engine changed BESIDE the record the /// write named — the album a picture was put in, who named an album. No /// column key can start with it (a key starts with a lowercase letter). /// /// Each such key's value is `{"was": …, "now": …}`, and it rides on the side /// of the change that holds the record — `after`, or `before` for a delete — /// so a create's `before` and a delete's `after` stay null. An undo compares /// the record on its columns alone ([`plan_undo`]) and hands these keys to the /// built-in, which checks they still stand and puts each `was` back through /// its own engine; an undo that cannot is refused, never reported as done. pub const BESIDE: char = '@'; /// What ticking a repeating todo moves beside it: the ids of its series' /// earlier occurrences that are missed, so the receipt can count the run it /// cleared and Undo can open it again. pub const MISSED: &str = "@missed"; /// Is `key` one of what a write changed beside the record? pub fn is_beside(key: &str) -> bool { key.starts_with(BESIDE) } /// What moved beside the record between two readings of it — each `@` key /// whose value differs, as `{"was", "now"}`. pub fn beside_moved(before: &Data, after: &Data) -> Data { let (was, now) = diff(before, after); was.into_iter() .filter(|(key, _)| is_beside(key)) .map(|(key, old)| { let new = now.get(&key).cloned().unwrap_or(Value::Null); let mut pair = Data::new(); pair.insert("was".into(), old); pair.insert("now".into(), new); (key, Value::Object(pair)) }) .collect() } /// A change side without what moved beside the record — the record alone. pub fn record_part(side: &Value) -> Value { match side { Value::Object(data) => Value::Object( data.iter() .filter(|(key, _)| !is_beside(key)) .map(|(key, value)| (key.clone(), value.clone())) .collect(), ), other => other.clone(), } } /// What a change says moved beside its record, from whichever side holds it. pub fn beside_of(change: &Change) -> Data { [&change.before, &change.after] .into_iter() .filter_map(Value::as_object) .flat_map(|data| data.iter()) .filter(|(key, _)| is_beside(key)) .map(|(key, value)| (key.clone(), value.clone())) .collect() } // ── reorder and link ──────────────────────────────────────────────────────── /// The order column a reorder writes, or the refusal a table without one /// answers. pub fn order_column(definition: &TableDefinition) -> Result<&str, RecordError> { definition .order .as_deref() .ok_or_else(|| RecordError::NoOrder { plural: definition.plural.clone(), }) } /// The positions a reorder writes: the listed records take `1, 2, 3 …` in the /// order given. Records not listed keep the positions they have. Ids must be /// distinct and there must be at least one. pub fn plan_reorder(ids: &[String]) -> Result, RecordError> { let distinct: BTreeSet<&String> = ids.iter().collect(); if ids.is_empty() || distinct.len() != ids.len() || ids.iter().any(|id| id.is_empty()) { return Err(RecordError::BadReorder); } Ok(ids .iter() .enumerate() .map(|(index, id)| (id.clone(), (index + 1) as f64)) .collect()) } /// The link column `key` names, or the refusal. pub fn link_column<'d>( definition: &'d TableDefinition, key: &str, ) -> Result<&'d Column, RecordError> { let column = column_for(definition, key)?; if column.column_type != ColumnType::Link { return Err(RecordError::NotALink { column: key.to_string(), }); } Ok(column) } // ── undo ──────────────────────────────────────────────────────────────────── /// The write that reverses a change. #[derive(Debug, Clone, PartialEq)] pub enum Inverse { /// Undo a create or a restore: delete the record. Delete { record_id: String }, /// Undo a delete: bring the record back as it was. Restore { record_id: String, data: Data }, /// Undo an update or a link: put the changed keys back — those no later /// write has taken. `taken` names the ones left as they are. Patch { record_id: String, patch: Data, taken: Vec }, /// Undo a reorder: put each moved record back at its old position (null: /// it had none). Reorder { positions: Data }, } impl Inverse { /// The verb the undo's own change records. pub fn verb(&self) -> Verb { match self { Inverse::Delete { .. } => Verb::Delete, Inverse::Restore { .. } => Verb::Restore, Inverse::Patch { .. } => Verb::Update, Inverse::Reorder { .. } => Verb::Reorder, } } } /// What is stored NOW for the records a change touched. #[derive(Debug, Clone, PartialEq)] pub enum Current { /// One record: its data, or `None` when it is deleted or missing. Record(Option), /// A reorder's records: each id's position now (null: none, or gone). Positions(Data), } /// A field one change wrote: `(record id, column key)`, the key `*` for the /// whole record (a create, a delete, a restore). fn touched(change: &Change) -> BTreeSet<(String, String)> { let mut out = BTreeSet::new(); let keys_of = |value: &Value| -> Vec { value .as_object() .map(|object| object.keys().cloned().collect()) .unwrap_or_default() }; match (change.verb, &change.record_id) { (Verb::Reorder, _) => { for id in keys_of(&change.after) .into_iter() .chain(keys_of(&change.before)) { out.insert((id, ORDER_FIELD.to_string())); } } (Verb::Create | Verb::Delete | Verb::Restore | Verb::Move | Verb::MoveIn, Some(id)) => { out.insert((id.clone(), "*".to_string())); } (Verb::Update | Verb::Link, Some(id)) => { for key in keys_of(&change.after) .into_iter() .chain(keys_of(&change.before)) .filter(|key| key != EDITED_AT) { out.insert((id.clone(), key)); } } (_, None) => {} } out } /// The field a reorder writes, whatever the table calls its order column: a /// reorder and an update of that column touch the same thing. const ORDER_FIELD: &str = "@order"; fn overlaps( a: &BTreeSet<(String, String)>, b: &BTreeSet<(String, String)>, order_key: Option<&str>, ) -> bool { let normalise = |(id, key): &(String, String)| -> (String, String) { if Some(key.as_str()) == order_key { (id.clone(), ORDER_FIELD.to_string()) } else { (id.clone(), key.clone()) } }; let a: BTreeSet<(String, String)> = a.iter().map(normalise).collect(); let b: BTreeSet<(String, String)> = b.iter().map(normalise).collect(); a.iter().any(|(id, key)| { b.iter().any(|(other, other_key)| { id == other && (key == "*" || other_key == "*" || key == other_key) }) }) } /// Decide the undo of `change`, or refuse it. /// /// - A change already undone is refused. /// - A LATER change (`later`: every change recorded after it on the same /// table) that touched the same record fields refuses it — except a later /// change that was itself undone, and the undo that reversed it, which /// cancel out. /// - What is stored now (`current`) must still be what the change left: an /// edit made outside the generic verbs records no change, and would /// otherwise be silently overwritten. /// - An update or a link is undone KEY BY KEY: a key a later change touched, /// or whose value is no longer the one this change left, is TAKEN — kept as /// it is and named in `taken` — and the rest go back. Only when every key /// is taken is the undo refused. /// /// `order_key` is the table's order column, so a reorder and an update of that /// column are seen as touching the same field. pub fn plan_undo( change: &Change, later: &[Change], current: &Current, order_key: Option<&str>, ) -> Result { if change.undone_by.is_some() { return Err(RecordError::AlreadyUndone); } if matches!(change.verb, Verb::Move | Verb::MoveIn) { return Err(RecordError::MoveUndoNeedsCoordinator); } let cancelled: BTreeSet<&str> = later .iter() .filter_map(|other| other.undone_by.as_deref().map(|by| [other.id.as_str(), by])) .flatten() .collect(); // The record is compared on its columns alone: what moved beside it is // the built-in's to check and put back (`BESIDE`). let change = &Change { before: record_part(&change.before), after: record_part(&change.after), ..change.clone() }; let mine = touched(change); let standing = || { later .iter() .filter(|other| other.id != change.id && !cancelled.contains(other.id.as_str())) }; let per_key = matches!(change.verb, Verb::Update | Verb::Link); if let Some(other) = standing().find(|other| { let theirs = touched(other); // A per-key undo meets a later edit key by key below; a later change // to the WHOLE record (a delete, a restore) still stands in its way. let whole = theirs.iter().any(|(_, key)| key == "*"); (!per_key || whole) && overlaps(&mine, &theirs, order_key) }) { return Err(RecordError::ChangedSince { what: match &other.record_id { Some(id) => Changed::Record { id: id.clone() }, None => Changed::Order, }, }); } let record = || { change .record_id .clone() .ok_or_else(|| RecordError::Malformed(Malformation::NoRecord)) }; let object = |value: &Value, side: &str| -> Result { value .as_object() .cloned() .ok_or_else(|| RecordError::Malformed(Malformation::NotAnObject { side: side.to_string() })) }; let changed_since = |what: Changed| RecordError::ChangedSince { what }; match change.verb { Verb::Create | Verb::Restore => { let record_id = record()?; let after = object(&change.after, "after")?; match current { Current::Record(Some(now)) if same_record(now, &after) => { Ok(Inverse::Delete { record_id }) } _ => Err(changed_since(Changed::Record { id: record_id.to_string() })), } } Verb::Delete => { let record_id = record()?; let before = object(&change.before, "before")?; match current { Current::Record(None) => Ok(Inverse::Restore { record_id, data: before, }), _ => Err(changed_since(Changed::Record { id: record_id.to_string() })), } } Verb::Update | Verb::Link => { let record_id = record()?; let before = object(&change.before, "before")?; let after = object(&change.after, "after")?; let Current::Record(Some(now)) = current else { return Err(changed_since(Changed::Record { id: record_id.to_string() })); }; let later_keys: BTreeSet<(String, String)> = standing().flat_map(touched).collect(); let is_taken = |key: &str| { key != EDITED_AT && (overlaps( &BTreeSet::from([(record_id.clone(), key.to_string())]), &later_keys, order_key, ) || !same_value(get_or_null(now, key), get_or_null(&after, key))) }; let taken: Vec = before .keys() .chain(after.keys()) .filter(|key| is_taken(key)) .cloned() .collect::>() .into_iter() .collect(); let mut patch: Data = before .into_iter() .filter(|(key, _)| !taken.contains(key)) .collect(); if taken.is_empty() { return Ok(Inverse::Patch { record_id, patch, taken }); } // Something stands on the record since: its edited time stays. patch.remove(EDITED_AT); if patch.is_empty() { return Err(changed_since(Changed::Record { id: record_id.to_string() })); } Ok(Inverse::Patch { record_id, patch, taken }) } Verb::Reorder => { let before = object(&change.before, "before")?; let after = object(&change.after, "after")?; match current { Current::Positions(now) if matches_on(now, &after) => { Ok(Inverse::Reorder { positions: before }) } _ => Err(changed_since(Changed::Order)), } } Verb::Move | Verb::MoveIn => Err(RecordError::MoveUndoNeedsCoordinator), } } // ── where ─────────────────────────────────────────────────────────────────── /// What one `where` entry asks of its column. #[derive(Debug, Clone, PartialEq)] pub enum Condition { /// The column holds exactly this value. A column holding several values /// (`multiple`) has no generic reading of this: the readers refuse it /// unless its table narrows it itself. Is(Value), /// The column holds one of these values (`{"values": [...]}`). OneOf(Vec), /// The column holds something — not null and not the empty text — or, /// with `false`, nothing (`{"present": bool}`). Present(bool), /// The column holds a value that is none of these (`{"not": [...]}`): a /// record holding nothing holds no value, so it never matches — "balance /// not 0" answers the people something is owed between, never the people /// with no money rows at all. NoneOf(Vec), /// A date column holds a day in this month, 1–12, whatever its year /// (`{"month": 11}`): "birthdays in November", "renewals in March". /// Only a date column takes it. Month(i64), /// A date column holds a moment in a window of days (of 24 hours) about /// now ([`DayWindow`]): `{"within_days": 7}` "this week's moods", /// `{"before_days": 14}` "not seen in two weeks", `{"ahead_days": 14}` /// "ends in the next two weeks". Only a date column takes it. WithinDays(DayWindow), /// A number column holds a number no more, or no less, than this /// (`{"at_most": 30}` "ready in half an hour", `{"at_least": 4}` "rated /// four or more"). A record holding nothing holds no number, so it is in /// no bound. Only a number column takes it. Bound(NumberBound), /// A date column holds a day named against today on this device's own /// calendar ([`DayOn`]): `{"on": "today"}` "today's entries", /// `{"on": "this_day"}` "on this day in earlier years". A moment is read /// as its day where the device stands; a bare day is that day. Only a date /// column takes it. On(DayOn), } /// The day an [`Condition::On`] keeps, against the device's own today. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DayOn { /// Today itself (`today`). Today, /// Today's month and day in an earlier year (`this_day`): a journal's /// On this day. A 29 February is kept only on a 29 February. ThisDay, /// Today or any day after it (`from_today`): a trip that has not ended, /// a booking still to come. FromToday, /// Any day before today (`before_today`): a trip that is over. BeforeToday, } impl DayOn { /// The `where` word that names this day. pub fn word(self) -> &'static str { match self { DayOn::Today => "today", DayOn::ThisDay => "this_day", DayOn::FromToday => "from_today", DayOn::BeforeToday => "before_today", } } } /// The side of a number a [`Condition::Bound`] keeps, the number itself kept. #[derive(Debug, Clone, Copy, PartialEq)] pub enum NumberBound { /// No more than this (`at_most`). AtMost(f64), /// No less than this (`at_least`). AtLeast(f64), } impl NumberBound { /// Does `number` lie inside the bound? pub fn keeps(self, number: f64) -> bool { match self { NumberBound::AtMost(most) => number <= most, NumberBound::AtLeast(least) => number >= least, } } /// The SQL comparison and the number it is made against. pub fn sql(self) -> (&'static str, f64) { match self { NumberBound::AtMost(most) => ("<=", most), NumberBound::AtLeast(least) => (">=", least), } } } /// The window of days a date is read in, against now. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DayWindow { /// No more than so many days back, or later (`within_days`). Within(i64), /// More than so many days back (`before_days`): a date that is not kept /// is in no window. Before(i64), /// From yesterday to so many days ahead (`ahead_days`), so a day that is /// today, read as its midnight, is in it. Ahead(i64), } impl DayWindow { /// The `where` word that names this window. pub fn word(self) -> &'static str { match self { DayWindow::Within(_) => "within_days", DayWindow::Before(_) => "before_days", DayWindow::Ahead(_) => "ahead_days", } } } /// One entry of `list_records`' `where`: a column of the table, and what it /// must hold. #[derive(Debug, Clone, PartialEq)] pub struct WhereClause { pub column: String, pub condition: Condition, /// On a day named against today ([`Condition::On`]) over a range's last /// day: the range's first day, read where the last holds nothing (a /// column whose `until` is this one). A trip given only the day it /// starts is a trip of that one day, so it stands in Upcoming and Past /// as `cotton_rules::trips::span` reads it (13 Nov 2026). pub first_day: Option, } /// `list_records`' `where`, checked against `definition`: an object of column /// keys, each mapped to a value (`{"status": "open"}`), a list of values or /// `{"values": [...]}` (any one of them), `{"not": [...]}` (a value none of /// them), or `{"present": true | false}` — the shapes a page section's `when` /// already spells. Every entry must hold /// together, and every key must be a DECLARED column; a value is checked /// against its column's type exactly as a write's is. An unknown column, a /// null (say `{"present": false}`), an empty list or any other key is /// REFUSED, never ignored — a filter that silently narrowed nothing would /// answer the whole table as if it were the part asked for. Absent or null /// `where` narrows nothing. /// /// Whether the table can then FILTER on that column is the reader's question /// (a built-in answers some columns only through its engine), asked after /// this one. pub fn parse_where( definition: &TableDefinition, value: Option<&Value>, ) -> Result, RecordError> { let entries = match value { None | Some(Value::Null) => return Ok(Vec::new()), Some(Value::Object(entries)) => entries, Some(other) => { return Err(RecordError::BadWhere { column: String::new(), reason: WhereRefusal::NotAnObject { found: describe(other) }, }) } }; let bad = |column: &str, reason: WhereRefusal| RecordError::BadWhere { column: column.to_string(), reason, }; let mut out = Vec::with_capacity(entries.len()); for (name, wanted) in entries { if is_engine_where_key(definition, name) { let Some(id) = wanted.as_str().map(str::trim).filter(|id| !id.is_empty()) else { return Err(bad( name, WhereRefusal::OneRecordId { column: name.clone(), found: describe(wanted) }, )); }; out.push(WhereClause { column: name.clone(), condition: Condition::Is(Value::from(id)), first_day: None, }); continue; } let column = column_for(definition, name)?; let condition = match wanted { Value::Null => { return Err(bad( name, WhereRefusal::Null, )) } // A list of values is any one of them — the shape a definition's // own `where` says it in, `{"values": [...]}` spelled short. Value::Array(values) => any_of(definition, column, name, values)?, Value::Object(shape) => { let mut keys = shape.keys(); let (Some(only), None) = (keys.next(), keys.next()) else { return Err(bad( name, WhereRefusal::OneShape, )); }; match (only.as_str(), &shape[only]) { ("values", Value::Array(values)) if !values.is_empty() => { any_of(definition, column, name, values)? } ("values", _) => { return Err(bad(name, WhereRefusal::ValuesEmpty)) } ("not", Value::Array(values)) if !values.is_empty() => { let Condition::OneOf(values) = any_of(definition, column, name, values)? else { unreachable!("any_of answers OneOf") }; Condition::NoneOf(values) } ("not", _) => { return Err(bad(name, WhereRefusal::NotEmpty)) } ("month", month) if column.column_type == ColumnType::Date => { match month.as_i64().filter(|month| (1..=12).contains(month)) { Some(month) => Condition::Month(month), None => { return Err(bad( name, WhereRefusal::MonthRange { found: describe(month) }, )) } } } ("month", _) => { return Err(bad(name, WhereRefusal::MonthOnlyDate)) } (word @ ("within_days" | "before_days" | "ahead_days"), days) if column.column_type == ColumnType::Date => { match days.as_i64().filter(|days| *days >= 1) { Some(days) => Condition::WithinDays(match word { "before_days" => DayWindow::Before(days), "ahead_days" => DayWindow::Ahead(days), _ => DayWindow::Within(days), }), None => { return Err(bad( name, WhereRefusal::WithinDaysRange { found: describe(days) }, )) } } } ("within_days" | "before_days" | "ahead_days", _) => { return Err(bad(name, WhereRefusal::WithinDaysOnlyDate)) } (word @ ("at_most" | "at_least"), bound) if column.column_type == ColumnType::Number => { match bound.as_f64() { Some(number) => Condition::Bound(match word { "at_most" => NumberBound::AtMost(number), _ => NumberBound::AtLeast(number), }), None => { return Err(bad( name, WhereRefusal::BoundNumber { found: describe(bound) }, )) } } } ("at_most" | "at_least", _) => { return Err(bad(name, WhereRefusal::BoundOnlyNumber)) } ("on", day) if column.column_type == ColumnType::Date => { match day.as_str() { Some("today") => Condition::On(DayOn::Today), Some("this_day") => Condition::On(DayOn::ThisDay), Some("from_today") => Condition::On(DayOn::FromToday), Some("before_today") => Condition::On(DayOn::BeforeToday), _ => return Err(bad(name, WhereRefusal::OnWord { found: describe(day) })), } } ("on", _) => { return Err(bad(name, WhereRefusal::OnOnlyDate)) } ("present", Value::Bool(present)) => Condition::Present(*present), ("present", other) => { return Err(bad( name, WhereRefusal::PresentBool { found: describe(other) }, )) } (other, _) => { return Err(bad( name, WhereRefusal::NotACondition { said: format!("{other:?}") }, )) } } } value => { check_value_in(definition, column, value)?; Condition::Is(value.clone()) } }; let first_day = matches!(condition, Condition::On(_)) .then(|| definition.columns.iter().find(|first| first.until.as_deref() == Some(name.as_str())).map(|first| first.key.clone())) .flatten(); out.push(WhereClause { column: name.clone(), condition, first_day, }); } Ok(out) } /// Any one of `values`, each checked against the column as a write's is. fn any_of( definition: &TableDefinition, column: &Column, name: &str, values: &[Value], ) -> Result { if values.is_empty() { return Err(RecordError::BadWhere { column: name.to_string(), reason: WhereRefusal::ValuesEmpty, }); } for value in values { if value.is_null() || value.is_array() || value.is_object() { return Err(RecordError::BadWhere { column: name.to_string(), reason: WhereRefusal::EachOneValue { found: describe(value) }, }); } check_value_in(definition, column, value)?; } Ok(Condition::OneOf(values.to_vec())) } /// `where` keys a built-in's ENGINE answers that are no column of its table: /// `(table, key)`. Each takes ONE record id — no `values`, no `present` — and /// [`parse_where`] accepts it on that built-in alone; the reader narrows by it /// through the table's own entry in the tools' `NARROWINGS`, and a key no /// entry answers is refused there, never ignored. /// /// `photo.addable_to`: the photos an album can still take by hand — not in it /// already, and admitted by `rules::media::albums::album_admits_by_hand` (no /// screenshot, no picture of information). The album's add picker lists them. pub const ENGINE_WHERE_KEYS: &[(&str, &str)] = &[("photo", "addable_to")]; /// Is `key` one of [`ENGINE_WHERE_KEYS`] on this (built-in) table? pub fn is_engine_where_key(definition: &TableDefinition, key: &str) -> bool { definition.has_engine() && definition.column(key).is_none() && ENGINE_WHERE_KEYS .iter() .any(|(table, engine_key)| *table == definition.id && *engine_key == key) } /// Does a record's `data` hold what one `where` entry asks — for a reader /// that answers its records from memory (a built-in VIEW the engine computes) /// rather than filtering in SQL: the same value (numbers by worth, /// [`same_value`]), any one of the values, a value none of them, or something /// / nothing, where an /// absent key, a null and the empty text are all nothing. A column holding /// several values (a list) is never "the same value" as one of them. A day /// named against today ([`Condition::On`]) is today in `zone`, the /// workspace's or the device's as the caller knows it ([`where_zone`]), never /// the machine's. pub fn holds(data: &Data, clause: &WhereClause, zone: &Zone) -> bool { let mut value = get_or_null(data, &clause.column); if let Some(first) = clause.first_day.as_deref().filter(|_| !something(value)) { value = get_or_null(data, first); } match &clause.condition { Condition::Is(wanted) => !value.is_array() && same_value(value, wanted), Condition::OneOf(wanted) => { !value.is_array() && wanted.iter().any(|one| same_value(value, one)) } Condition::NoneOf(unwanted) => { !value.is_array() && something(value) && !unwanted.iter().any(|one| same_value(value, one)) } Condition::Present(present) => something(value) == *present, Condition::Month(month) => in_month(value, *month), Condition::WithinDays(days) => within_days(value, *days, chrono::Utc::now()), Condition::Bound(bound) => in_bound(value, *bound), Condition::On(day) => on_day(value, *day, zone.today, &zone.tz), } } /// Where a `where` that names a day stands ([`holds`]): today, and the zone /// a moment is read as its day in — the reader's, never the machine's. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Zone { pub tz: chrono_tz::Tz, pub today: chrono::NaiveDate, } impl Zone { /// Today in `tz` at `now`. pub fn at(tz: chrono_tz::Tz, now: chrono::DateTime) -> Zone { Zone { tz, today: now.with_timezone(&tz).date_naive() } } /// Today as the reader named it (`YYYY-MM-DD`), where it names one. pub fn on(self, today: Option<&str>) -> Zone { match today.and_then(|day| chrono::NaiveDate::parse_from_str(day.trim(), "%Y-%m-%d").ok()) { Some(today) => Zone { today, ..self }, None => self, } } } /// The zone a `where` reads today in ([`holds`]): the one named, else UTC, /// today being now there. pub fn where_zone(zone: Option<&str>) -> Zone { Zone::at(zone.and_then(|zone| zone.parse().ok()).unwrap_or(chrono_tz::UTC), chrono::Utc::now()) } /// A date value falls on `day` against `today` ([`Condition::On`]): a bare /// day ("2026-11-12") is that day; a moment with its offset is read as its /// day in `zone`, where the device stands. Nothing, a text that is no date or /// a list is on no day. pub fn on_day(value: &Value, day: DayOn, today: chrono::NaiveDate, zone: &Z) -> bool { use chrono::Datelike; let Some(text) = value.as_str().map(str::trim) else { return false }; let held = chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").ok().or_else(|| { chrono::DateTime::parse_from_rfc3339(text).ok().map(|at| at.with_timezone(zone).date_naive()) }); held.is_some_and(|held| match day { DayOn::Today => held == today, DayOn::ThisDay => held.month() == today.month() && held.day() == today.day() && held.year() < today.year(), DayOn::FromToday => held >= today, DayOn::BeforeToday => held < today, }) } /// A number value lies inside `bound` ([`Condition::Bound`]); nothing, a /// text or a list is in no bound. pub fn in_bound(value: &Value, bound: NumberBound) -> bool { value.as_f64().is_some_and(|number| bound.keeps(number)) } /// A date value — a day or an instant — falls in `window` about `now` /// ([`Condition::WithinDays`]). A bare day reads as its UTC midnight, as /// SQLite's `julianday` reads it. pub fn within_days(value: &Value, window: DayWindow, now: chrono::DateTime) -> bool { let Some(text) = value.as_str().map(str::trim) else { return false }; let at = chrono::DateTime::parse_from_rfc3339(text) .map(|at| at.with_timezone(&chrono::Utc)) .ok() .or_else(|| { chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d") .ok() .and_then(|day| day.and_hms_opt(0, 0, 0)) .map(|midnight| midnight.and_utc()) }); at.is_some_and(|at| match window { DayWindow::Within(days) => at >= now - chrono::Duration::days(days), DayWindow::Before(days) => at < now - chrono::Duration::days(days), DayWindow::Ahead(days) => at >= now - chrono::Duration::days(1) && at <= now + chrono::Duration::days(days), }) } /// A date value — "1992-08-17", "--08-17" or a day with its time — falls in /// `month` (1–12), whatever its year ([`Condition::Month`]). pub fn in_month(value: &Value, month: i64) -> bool { value .as_str() .and_then(crate::transforms::zoned_clock::yearly_month_day) .is_some_and(|(held, _)| held == month) } /// A value that is something: not null and not blank text. fn something(value: &Value) -> bool { match value { Value::Null => false, Value::String(text) => !text.trim().is_empty(), _ => true, } } /// One figure of a tile's `summary`, computed over the table's live rows: /// `{ op, column, label, value, currency }`. `value` is null when no row /// qualifies (a min over nothing) or, for an amount sum, when the rows do /// not share one currency — then `currency` says `"mixed"`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SummaryValue { pub op: SummaryOp, #[serde(skip_serializing_if = "Option::is_none")] pub column: Option, #[serde(skip_serializing_if = "Option::is_none")] pub label: Option, pub value: Value, #[serde(skip_serializing_if = "Option::is_none")] pub currency: Option, /// The figure as a face writes it, label and all ("£45.98 a month", /// "Fri 9 Oct next renewal", "mixed currencies a month"): the phone /// draws these and never spells the value itself. #[serde(skip_serializing_if = "Option::is_none")] pub words: Option, } /// Every figure the definition's tile asks for, over `rows` — the one /// place the arithmetic lives, so the Mac, the phone and an assistant read /// the same total. `rows` are the table's live records' data; each figure /// keeps those its `where` holds for, then counts, sums, or takes the /// smallest or largest. A date compares as written (YYYY-MM-DD orders); /// a number or amount by size. An amount sum carries the column's currency — /// the text itself, or the currency column it names, read per row. pub fn summarize(definition: &TableDefinition, rows: &[Data], words: &crate::records::page::Words, zone: &Zone) -> Result, RecordError> { summarize_by(definition, &definition.tile.summary, rows, words, zone) } /// [`summarize`] for any list of figures in a tile's shape — a group head's /// (`ListGrouping::summary`) over that group's rows. pub fn summarize_by(definition: &TableDefinition, summaries: &[crate::definitions::TileSummary], rows: &[Data], words: &crate::records::page::Words, zone: &Zone) -> Result, RecordError> { let projected: Vec; let rows = if definition.columns.iter().any(|column| column.column_type == ColumnType::AccountNumber || (definition.id == "money_account" && column.key == "number_mask")) { projected = rows.iter().map(|row| { let mut row = row.clone(); project_read_data(definition, &mut row); row }).collect(); projected.as_slice() } else { rows }; let mut figures = Vec::with_capacity(summaries.len()); for summary in summaries { let filter = summary .where_ .as_ref() .map(|filter| serde_json::to_value(filter).expect("an ordered map is JSON")); let clauses = parse_where(definition, filter.as_ref())?; let kept: Vec<&Data> = rows .iter() .filter(|row| clauses.iter().all(|clause| holds(row, clause, zone))) .collect(); let column = summary .column .as_deref() .and_then(|key| definition.column(key)); let (value, currency) = match (summary.op, column) { (SummaryOp::Count, _) | (_, None) => (json!(kept.len()), None), (SummaryOp::Sum, Some(column)) => { let values = kept.iter().map(|row| get_or_null(row, &column.key)); let total = sum_numbers(values); if column.column_type == ColumnType::Amount { match one_currency(definition, column, &kept) { Ok(currency) => (total, currency), Err(mixed) => (Value::Null, Some(mixed)), } } else { (total, None) } } (op, Some(column)) => { let mut values: Vec<&Value> = kept .iter() .map(|row| get_or_null(row, &column.key)) .filter(|value| !value.is_null()) .collect(); values.sort_by(|a, b| compare_values(a, b)); let picked = match op { SummaryOp::Min => values.first(), _ => values.last(), }; // Amounts in two currencies have no least or greatest — the // same "mixed" Sum answers, never a winner picked across them. if column.column_type == ColumnType::Amount { match one_currency(definition, column, &kept) { Ok(currency) => (picked.map(|value| (*value).clone()).unwrap_or(Value::Null), currency), Err(mixed) => (Value::Null, Some(mixed)), } } else { (picked.map(|value| (*value).clone()).unwrap_or(Value::Null), None) } } }; let mut figure = SummaryValue { op: summary.op, column: summary.column.clone(), label: summary.label.clone(), value, currency, words: None, }; figure.words = Some(summary_words(column.filter(|_| summary.op != SummaryOp::Count), &figure, words)); figures.push(figure); } Ok(figures) } /// A tile figure as a face writes it: the value by its column's type, then /// its label. Mixed currencies say the money line; no value says a dash so /// the label still reads. fn summary_words(column: Option<&Column>, figure: &SummaryValue, words: &crate::records::page::Words) -> String { let said = if figure.currency.as_deref() == Some("mixed") { words.money.say("mixed", &[]).unwrap_or_default() } else { match (&figure.value, column.map(|column| column.column_type)) { (Value::Null, _) => "\u{2014}".to_string(), (value, Some(ColumnType::Amount)) => page::figure_words(value, true, figure.currency.as_deref(), &words.money).unwrap_or_default(), (Value::String(text), Some(ColumnType::Date)) => page::Moment::parse(text, "Etc/UTC") .map(|at| words.dates.weekday_date(at.day, crate::transforms::zoned_clock::civil_from_days(at.day).0)) .unwrap_or_else(|| text.clone()), (Value::String(text), _) => text.clone(), (value, _) => page::figure_words(value, false, None, &words.money).unwrap_or_default(), } }; match figure.label.as_deref().filter(|label| !label.is_empty()) { Some(label) => format!("{said} {label}"), None => said, } } /// A sparkline's points, as the face draws them: each `value` placed at `t` /// across the window (0 its start, 1 now) and scaled between `low` and /// `high`; `last` is the one value the face writes. No points is an empty line. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SparklinePoints { pub table: String, /// The line's own columns, so a page with two lines knows which is which. pub value: String, pub at: String, pub days: u32, pub points: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub low: Option, #[serde(skip_serializing_if = "Option::is_none")] pub high: Option, #[serde(skip_serializing_if = "Option::is_none")] pub last: Option, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SparklinePoint { /// The `at` value as the record holds it. pub at: String, pub value: f64, pub t: f64, } /// The points of `line` over `rows` — the live records of `of`, the table the /// line names — in the window ending `now`: the one place the arithmetic /// lives, so every face draws the same line. `of`'s `value` column must be a /// number or amount and its `at` a date; a row missing either is left out. A /// date is placed at its day's start (UTC), an instant where it is. A line /// with a `link` keeps the rows whose link column holds `record` (a page's /// record); with no record to hold, it keeps none. pub fn sparkline( line: &crate::definitions::Sparkline, of: &TableDefinition, rows: &[Data], record: Option<&str>, now: chrono::DateTime, ) -> Result { let wrong = |column: &str, wanted: Wanted| RecordError::WrongType { column: format!("{}.{column}", of.id), wanted, found: Found::AnotherType, }; match of.column(&line.value).map(|column| column.column_type) { Some(ColumnType::Number | ColumnType::Amount) => {} Some(_) => return Err(wrong(&line.value, Wanted::NumberOrAmountColumn)), None => return Err(RecordError::UnknownColumn { plural: of.plural.clone(), column: line.value.clone() }), } match of.column(&line.at).map(|column| column.column_type) { Some(ColumnType::Date) => {} Some(_) => return Err(wrong(&line.at, Wanted::DateColumn)), None => return Err(RecordError::UnknownColumn { plural: of.plural.clone(), column: line.at.clone() }), } if let Some(link) = &line.link { match of.column(link).map(|column| column.column_type) { Some(ColumnType::Link) => {} Some(_) => return Err(wrong(link, Wanted::LinkColumn)), None => return Err(RecordError::UnknownColumn { plural: of.plural.clone(), column: link.clone() }), } } let holds_record = |row: &Data| match (&line.link, record) { (None, _) => true, (Some(_), None) => false, (Some(link), Some(record)) => match get_or_null(row, link) { Value::String(id) => id == record, Value::Array(ids) => ids.iter().any(|id| id.as_str() == Some(record)), _ => false, }, }; let days = line.days(); let span = chrono::Duration::days(i64::from(days)); let from = now - span; let mut points: Vec<(chrono::DateTime, SparklinePoint)> = rows .iter() .filter(|row| holds_record(row)) .filter_map(|row| { let at = get_or_null(row, &line.at).as_str()?; let value = get_or_null(row, &line.value).as_f64()?; let instant = chrono::DateTime::parse_from_rfc3339(at) .map(|instant| instant.with_timezone(&chrono::Utc)) .ok() .or_else(|| { chrono::NaiveDate::parse_from_str(at, "%Y-%m-%d") .ok() .and_then(|day| day.and_hms_opt(0, 0, 0)) .map(|start| start.and_utc()) })?; if instant < from || instant > now { return None; } let t = (instant - from).num_seconds() as f64 / span.num_seconds() as f64; Some((instant, SparklinePoint { at: at.to_string(), value, t })) }) .collect(); points.sort_by(|a, b| a.0.cmp(&b.0)); let points: Vec = points.into_iter().map(|(_, point)| point).collect(); let low = points.iter().map(|point| point.value).reduce(f64::min); let high = points.iter().map(|point| point.value).reduce(f64::max); let last = points.last().map(|point| point.value); Ok(SparklinePoints { table: of.id.clone(), value: line.value.clone(), at: line.at.clone(), days, points, low, high, last }) } /// Whole numbers stay whole; one fraction anywhere makes the total a float. pub fn sum_numbers<'a>(values: impl Iterator) -> Value { let mut whole: i64 = 0; let mut fraction: f64 = 0.0; let mut any_fraction = false; for value in values { if let Some(n) = value.as_i64() { whole = whole.saturating_add(n); } else if let Some(f) = value.as_f64() { any_fraction = true; fraction += f; } } if any_fraction { json!(whole as f64 + fraction) } else { json!(whole) } } /// The one currency the kept rows share for an amount column: the column's /// `currency` text as written, or — when it names another column — that /// column's value, which every kept row must agree on. `Err("mixed")` when /// they do not; `Ok(None)` when nothing says. fn one_currency(definition: &TableDefinition, column: &Column, kept: &[&Data]) -> Result, String> { let Some(currency) = column.currency.as_deref() else { return Ok(None); }; if definition.column(currency).is_none() { return Ok(Some(currency.to_string())); } let mut found: Option = None; for row in kept { let Some(text) = get_or_null(row, currency).as_str() else { continue; }; match &found { None => found = Some(text.to_string()), Some(one) if one == text => {} Some(_) => return Err("mixed".into()), } } Ok(found) } pub fn compare_values(a: &Value, b: &Value) -> std::cmp::Ordering { match (a.as_f64(), b.as_f64()) { (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal), _ => a.as_str().unwrap_or("").cmp(b.as_str().unwrap_or("")), } } /// Plain text match over a record's title and its text columns, the way /// `list_records`' `query` reads a table a person defined: case-insensitive, /// every word of the query somewhere in those columns. pub fn matches_query(definition: &TableDefinition, data: &Data, query: &str) -> bool { let haystack: String = searchable_columns(definition) .iter() .filter_map(|key| { let text = data.get(*key)?.as_str()?; Some(if definition.column(key).is_some_and(|column| column.column_type == ColumnType::AccountNumber) || (definition.id == "money_account" && *key == "number_mask") { account_number_ending(text) } else { text.to_string() }) }) .collect::>() .join("\n") .to_lowercase(); query .split_whitespace() .all(|word| haystack.contains(&word.to_lowercase())) } /// The columns `query` reads: the title first, then every text and long-text /// column. pub fn searchable_columns(definition: &TableDefinition) -> Vec<&str> { let mut out = vec![definition.title.as_str()]; for column in &definition.columns { if matches!( column.column_type, ColumnType::Text | ColumnType::Longtext | ColumnType::Url | ColumnType::Place | ColumnType::AccountNumber ) && column.key != definition.title { out.push(column.key.as_str()); } } out } #[cfg(test)] #[path = "records_tests.rs"] mod tests; pub mod place; #[cfg(test)] mod place_tests; /// One group's head (`ListGrouping::summary`): the value its rows hold in /// the group's column, and the line each of its figures says — "₹1,200 in" /// — a figure with nothing to say (no rows it counts, an amount at nothing, /// amounts in more than one currency) left out. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct GroupHead { pub value: Value, pub lines: Vec, } /// The heads of a grouped list over all of its `rows`, one per value of the /// group's column in the order the rows first hold it; none for a list whose /// group says no figures. pub fn group_heads(definition: &TableDefinition, rows: &[Data], words: &crate::records::page::Words, zone: &Zone) -> Result, RecordError> { let Some(group) = definition.group.as_ref().filter(|group| !group.summary.is_empty()) else { return Ok(Vec::new()); }; // Each group found by its value's text: a whole table's rows over a // few hundred people, never a walk of the groups per row. let mut groups: Vec<(Value, Vec)> = Vec::new(); let mut at: std::collections::HashMap = std::collections::HashMap::new(); for row in rows { let value = get_or_null(row, &group.column).clone(); match at.get(&value.to_string()) { Some(&held) => groups[held].1.push(row.clone()), None => { at.insert(value.to_string(), groups.len()); groups.push((value, vec![row.clone()])); } } } groups .into_iter() .map(|(value, members)| { let figures = summarize_by(definition, &group.summary, &members, words, zone)?; Ok(group_head(definition, value, &figures, words)) }) .collect() } /// The columns a store reads to work one group figure out in SQL /// ([`figure_from_store`]): the column it totals or picks (none for a /// count), and the column holding each row's currency where an amount's /// currency is another column. pub fn figure_columns<'a>(definition: &'a TableDefinition, summary: &'a crate::definitions::TileSummary) -> (Option<&'a Column>, Option<&'a str>) { let column = summary.column.as_deref().and_then(|key| definition.column(key)).filter(|_| summary.op != SummaryOp::Count); let currency = column .filter(|column| column.column_type == ColumnType::Amount) .and_then(|column| column.currency.as_deref()) .filter(|currency| definition.column(currency).is_some()); (column, currency) } /// One group figure from what a store worked out over the group's rows: /// `value` the count, the total (null over no numbers) or the least or /// greatest; `currencies` how many currencies the rows hold and one of them, /// where [`figure_columns`] names a currency column. The same figure /// [`summarize_by`] says over the rows themselves. pub fn figure_from_store(definition: &TableDefinition, summary: &crate::definitions::TileSummary, value: Value, currencies: Option<(i64, Option)>) -> SummaryValue { let (column, _) = figure_columns(definition, summary); let (value, currency) = match column { None => (value, None), Some(column) => { let value = if summary.op == SummaryOp::Sum && value.is_null() { json!(0) } else { value }; let currency = column.currency.as_deref().filter(|_| column.column_type == ColumnType::Amount); match (currency, currencies) { (None, _) => (value, None), (Some(_), Some((held, _))) if held > 1 => (Value::Null, Some("mixed".to_string())), (Some(_), Some((_, one))) => (value, one), (Some(fixed), None) => (value, Some(fixed.to_string())), } } }; SummaryValue { op: summary.op, column: summary.column.clone(), label: summary.label.clone(), value, currency, words: None } } /// One group's head from its figures: each figure's line, silent at /// nothing, as [`group_heads`] says them. pub fn group_head(definition: &TableDefinition, value: Value, figures: &[SummaryValue], words: &crate::records::page::Words) -> GroupHead { GroupHead { value, lines: figures.iter().filter_map(|figure| figure_line(definition, figure, words)).collect() } } /// The running column whose opening an ungrouped list says above its first /// row (`running.opening_label`), with those words. pub fn opening_column(definition: &TableDefinition) -> Option<(&str, &str)> { if definition.group.is_some() { return None; } definition.columns.iter().find_map(|column| match &column.computed { Some(crate::definitions::computed::Computed::Running(running)) => { running.opening_label.as_deref().map(|label| (column.key.as_str(), label)) } _ => None, }) } /// The one head an ungrouped list says above its first row: its running's /// opening as an amount, then the words (Ahead's "₹1,20,000 held today"); /// silent at nothing, as every head line is. Its value is null: the list's /// one section is no group's. pub fn opening_head(definition: &TableDefinition, opening: &Value, currency: Option<&str>, words: &crate::records::page::Words) -> Option { let (key, label) = opening_column(definition)?; let figure = SummaryValue { op: SummaryOp::Sum, column: Some(key.to_string()), label: Some(label.to_string()), value: opening.clone(), currency: currency.map(str::to_string), words: None, }; figure_line(definition, &figure, words).map(|line| GroupHead { value: Value::Null, lines: vec![line] }) } /// A figure as its line: the amount in its currency, or the number, then /// its label. fn figure_line(definition: &TableDefinition, figure: &SummaryValue, words: &crate::records::page::Words) -> Option { let amount = figure.column.as_deref().and_then(|key| definition.column(key)).is_some_and(|column| column.column_type == ColumnType::Amount) && figure.op != SummaryOp::Count; let said = if amount { // An amount at nothing says nothing: a square person's head is quiet. let minor = figure.value.as_i64().filter(|minor| *minor != 0)?; crate::records::amount::amount(minor, figure.currency.as_deref(), &words.money).said(crate::records::amount::MoneyForm::Money, &words.money) } else { match &figure.value { Value::Number(number) => number.to_string(), Value::String(text) if !text.is_empty() => text.clone(), _ => return None, } }; Some(match figure.label.as_deref().filter(|label| !label.trim().is_empty()) { Some(label) => format!("{said} {label}"), None => said, }) }