//! A record's CARD resolved at read (`definitions::card`): the corner's //! "why now" and each of the face's places said in T1's forms through the //! database's line sets, and the pace band and plate. The app draws what is //! attached under [`CARD_KEY`] and composes no words. use serde::Serialize; use serde_json::{Map, Value}; use super::page::{fact_words, form_words, labelled_fact_words, read_fact, says_more_than_its_value, years_completed, DateAge, DateWords, Moment, Words, FACT_JOIN}; use crate::definitions::card::{CardFace, CardField, CardSlot, CornerFact, FaceId}; use crate::definitions::{ColumnType, Form, TableDefinition}; use crate::transforms::pace::{animal, Pace}; use crate::rules::shell_lines::{LineRow, LineSet}; use crate::transforms::zoned_clock::{civil_from_days, day_number, next_yearly_occurrence, yearly_month_day}; /// Where a record's resolved card travels in its data. pub const CARD_KEY: &str = "@card"; /// A record's card as the app draws it. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ResolvedCard { pub face: FaceId, /// The corner's words; absent when nothing calls for attention. #[serde(skip_serializing_if = "Option::is_none")] pub corner: Option, /// Whether the corner's date is behind: drawn in the late ink. #[serde(skip_serializing_if = "std::ops::Not::not")] pub pressing: bool, /// The pace band: the paper's tint. #[serde(skip_serializing_if = "Option::is_none")] pub pace: Option, /// The band's plate, `0..8`, when the card carries the pace art. #[serde(skip_serializing_if = "Option::is_none")] pub plate: Option, /// Each place the definition fills, by its slot's name: words for text /// and dates, a bool for the check. pub fields: Map, /// Recent visible messages, resolved before a thread card is returned. #[serde(skip_serializing_if = "Option::is_none")] pub thread: Option, } /// This month's recent postings. Balances are the Worker's stored values; /// resolving a card never reconstructs a balance on the phone. pub fn statement_rows( recent: &[(String, Map)], zone: &str, now: chrono::DateTime, words: &Words, ) -> Vec { let Some(today) = Moment::now(now, zone) else { return Vec::new() }; let (year, month, _) = civil_from_days(today.day); let mut rows: Vec<_> = recent.iter().filter_map(|(id, data)| { let date = Moment::parse(data.get("occurred_on")?.as_str()?, zone)?; let (y, m, _) = civil_from_days(date.day); if (y, m) != (year, month) || data.get("status").and_then(Value::as_str) != Some("actual") || data.get("moves_money") == Some(&Value::Bool(false)) { return None; } let currency = data.get("currency").and_then(Value::as_str); let money = |key| data.get(key).and_then(|value| super::page::figure_words(value, true, currency, &words.money)); let direction = data.get("direction").and_then(Value::as_str); let amount = if data.get("amount_known") == Some(&Value::Bool(false)) { None } else { money("amount_minor") }; Some((date, id, serde_json::json!({ "date": words.dates.day_month(date.day, year), "narration": data.get("description").and_then(Value::as_str), "debit": if direction == Some("out") { amount.clone() } else { None }, "credit": if direction == Some("in") { amount } else { None }, "balance": money("balance_after_minor") }))) }).collect(); rows.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(a.1))); rows.truncate(6); rows.reverse(); rows.into_iter().map(|(_, _, row)| row).collect() } /// The six recent notes a thread card carries before the face is drawn. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ThreadHistory { pub count: Option, pub earlier: Vec, pub last: Option, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ThreadLine { pub id: String, pub words: String, pub mine: bool, pub time: Option, pub sender: Option, } /// Say a thread's recent messages with the same date parts as its chat. /// The caller reads only the newest six visible rows and the oldest stamp. #[allow(clippy::too_many_arguments)] pub fn thread_history( layout: &crate::definitions::ConversationLayout, messages: &TableDefinition, group: bool, recent: &[(String, Map)], total: u64, oldest: Option<&str>, zone: &str, now: chrono::DateTime, words: &Words, format: &LineSet, ) -> ThreadHistory { // A queued note stays where it was written, even after acknowledgement. let delivery = |data: &Map| -> Option { if layout.queue.is_none() || data.get("direction").and_then(Value::as_str) != Some("out") || !matches!(data.get("channel").and_then(Value::as_str), Some("whatsapp" | "instagram")) { return None; } match data.get("send_state").and_then(Value::as_str) { Some("queued" | "sending" | "failed") => Some(false), Some("sent" | "delivered" | "read") => Some(data.get("external_id").and_then(Value::as_str).is_some_and(|id| !id.is_empty())), _ => None, } }; let moment = |data: &Map| -> Option { if delivery(data).is_some() { if let Some(created) = data.get("created_at").and_then(Value::as_str) { return Some(created.to_string()); } } data.get(&layout.at).and_then(Value::as_str).map(str::to_string) }; let mut ordered: Vec<_> = recent.iter().collect(); ordered.sort_by(|(_, a), (_, b)| match (moment(a), moment(b)) { (Some(a), Some(b)) => match (chrono::DateTime::parse_from_rfc3339(&a), chrono::DateTime::parse_from_rfc3339(&b)) { (Ok(a), Ok(b)) => a.cmp(&b), _ => a.cmp(&b), }, (Some(_), None) => std::cmp::Ordering::Less, (None, Some(_)) => std::cmp::Ordering::Greater, _ => std::cmp::Ordering::Equal, }); let mut lines: Vec<_> = ordered .into_iter() .rev() .take(6) .collect::>() .into_iter() .rev() .map(|(id, data)| { let mut said = data.get(&layout.body).and_then(Value::as_str).unwrap_or_default().trim().to_string(); if said.is_empty() { if let Some((column, value)) = layout.blank_body.as_deref().and_then(|key| Some((messages.column(key)?, data.get(key)?))) { said = fact_words(messages, column, value, data, Some(zone), Some(now), words).unwrap_or_default(); } } let stamp = if delivery(data) == Some(false) { None } else { data.get(&layout.at).and_then(Value::as_str) }; let time = stamp .and_then(|stamp| super::page::stamp_parts(stamp, zone, now, &words.dates)) .map(|parts| match parts.clock { None => parts.dated, Some(clock) if parts.recent == clock => clock, Some(clock) if parts.near.is_some() => format!("{} {clock}", parts.weekday_date.split_whitespace().next().unwrap_or_default()), Some(_) => parts.dated, }); let sender = group .then(|| { layout .color_by .as_deref() .and_then(|key| text(data, key)) .map(|name| name.trim().to_string()) .filter(|name| !name.is_empty()) }) .flatten(); ThreadLine { id: id.clone(), words: said, mine: data .get(&layout.mine.column) .and_then(Value::as_str) .is_some_and(|value| layout.mine.values.iter().any(|choice| choice == value)), time, sender, } }) .collect(); let count = (total > 0).then(|| { let n = crate::rules::shell_lines::number(total as i64); let said = format .say(if total == 1 { "since.message.one" } else { "since.message.many" }, &[("n", &n)]) .expect("the kit ships the message count lines"); oldest .and_then(|stamp| Moment::parse(stamp, zone)) .map_or_else(|| said.clone(), |at| format!("{said} {}", civil_from_days(at.day).0)) }); let last = lines.pop(); ThreadHistory { count, earlier: lines, last } } /// One person a card's people place names: their name as a sentence names /// them and the key of their picture, never an id. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct CardPerson { pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub picture: Option, } impl CardPerson { /// A linked record as the people place says it: its name in display /// form, and its slip's photo when that column holds a picture. pub fn of(definition: &TableDefinition, data: &Map, dates: &DateWords) -> CardPerson { let picture = definition .slip .photo .as_deref() .filter(|photo| definition.column(photo).is_some_and(|column| column.column_type == ColumnType::Photo)) .and_then(|photo| text(data, photo)); let mut name = super::receipt::record_name_in(definition, &Value::Object(data.clone()), dates); if let Some(mask) = definition.card.as_ref() .and_then(|card| card.fields.iter().find(|field| field.slot == CardSlot::Mask)) .and_then(|field| field.column.as_deref()) .and_then(|key| text(data, key)) { name.push_str(FACT_JOIN); name.push_str(&mask); } CardPerson { name, picture } } } /// What a card reads beyond its own record, read by the caller once for a /// whole answer: the group the record stands in, and the records its people /// and account places' link columns name, by id. #[derive(Debug, Clone, Copy)] pub struct Around<'a> { pub group: Option<&'a str>, /// A thread's visible recent notes, read before resolving its card. pub thread: Option<&'a ThreadHistory>, pub people: Option<&'a std::collections::HashMap>, /// Whether the reader may write this record: an empty date place offers /// "Add date" only to someone who can add one, never to a business's /// public or a member reading the studio's cards. pub writable: bool, } impl Default for Around<'_> { /// A record in the reader's own database: theirs to write. fn default() -> Self { Around { group: None, people: None, writable: true, thread: None } } } /// The people place's column and the table it links to, when the card has /// one. pub fn people_place<'a>(card: &'a CardFace, definition: &'a TableDefinition) -> Option<(&'a str, &'a str)> { linked_places(card, definition).into_iter().find(|(slot, ..)| *slot == CardSlot::People).map(|(_, key, table)| (key, table)) } /// Each place that names linked records — the people, the account — with /// its column and the table it links to: what the caller reads, once per /// answer, for [`Around::people`]. pub fn linked_places<'a>(card: &'a CardFace, definition: &'a TableDefinition) -> Vec<(CardSlot, &'a str, &'a str)> { card.fields .iter() .filter(|field| matches!(field.slot, CardSlot::People | CardSlot::Account | CardSlot::Album | CardSlot::RecommendedBy | CardSlot::Title)) .filter_map(|field| { let key = field.column.as_deref()?; Some((field.slot, key, definition.column(key)?.link_to.as_deref()?)) }) .collect() } /// The ids a link value names, one or a list, in order. pub fn linked_ids(value: Option<&Value>) -> Vec { match value { Some(Value::String(id)) if !id.is_empty() => vec![id.clone()], Some(Value::Array(ids)) => ids.iter().filter_map(Value::as_str).filter(|id| !id.is_empty()).map(str::to_string).collect(), _ => Vec::new(), } } /// The people a people place says, at most its `max`, and how many more. fn people<'a>(field: &CardField, data: &Map, around: Around<'a>) -> Option<(Vec<&'a CardPerson>, usize)> { let known = around.people?; let named: Vec<&CardPerson> = linked_ids(data.get(field.column.as_deref()?)).iter().filter_map(|id| known.get(id)).collect(); if named.is_empty() { return None; } let shown = field.max.map_or(named.len(), |max| named.len().min(max as usize)); let more = named.len() - shown; Some((named.into_iter().take(shown).collect(), more)) } /// Where the people place's count of the rest travels beside it ("+2"). pub const PEOPLE_MORE: &str = "people_more"; /// Where a card's own labels for its places travel, keyed by place. pub const LABELS: &str = "labels"; /// The `cards` set as a database says it. pub fn card_words(rows: &[LineRow]) -> LineSet { LineSet::of_rows("cards", rows).expect("the kit ships the cards set") } /// How many days ahead of `today` a date column's value falls: negative /// behind; a yearly date counts to its next time round (never behind). pub fn days_ahead(definition: &TableDefinition, column: &str, data: &Map, zone: &str, today: i64) -> Option { let text = data.get(column)?.as_str()?; if definition.column(column)?.yearly == Some(true) { let (month, day) = yearly_month_day(text)?; let (year, m, d) = next_yearly_occurrence(month, day, civil_from_days(today)); return Some(day_number(year, m, d) - today); } Some(Moment::parse(text, zone)?.day - today) } /// Whether a corner fact calls for attention now: its date at most `within` /// days ahead (a day behind always does), or at least `behind` days back. fn holds(fact: &CornerFact, definition: &TableDefinition, data: &Map, zone: &str, today: i64) -> Option { let ahead = days_ahead(definition, &fact.column, data, zone, today)?; if fact.ahead && ahead < 0 { return None; } let calls = match (fact.within, fact.behind) { (Some(within), _) => ahead <= i64::from(within), (None, Some(behind)) => -ahead >= i64::from(behind), (None, None) => false, }; calls.then_some(ahead) } /// A yes/no value that is set: true, or a number other than nought. fn set(value: &Value) -> bool { match value { Value::Bool(set) => *set, Value::Number(number) => number.as_i64().is_some_and(|number| number != 0), _ => false, } } fn text(data: &Map, key: &str) -> Option { match data.get(key)? { Value::String(text) if !text.trim().is_empty() => Some(text.clone()), Value::Number(number) => Some(number.to_string()), _ => None, } } /// A column's value as a list, where it holds one: an array, or the JSON /// text of one as a text column keeps it. fn list(value: Option<&Value>) -> Option> { match value? { Value::Array(items) => Some(items.clone()), Value::String(text) if text.trim_start().starts_with('[') => serde_json::from_str(text).ok(), _ => None, } } /// A slot's name as the app reads it under `fields`. fn slot_name(slot: CardSlot) -> Option { Some(serde_json::to_value(slot).ok()?.as_str()?.to_string()) } /// One record's card, against the reader's `now` in `zone`. #[allow(clippy::too_many_arguments)] pub fn resolve( card: &CardFace, definition: &TableDefinition, record_id: &str, data: &Map, zone: &str, now: chrono::DateTime, words: &Words, cards: &LineSet, around: Around, ) -> Option { let today = Moment::now(now, zone)?; let moment = |key: &str| data.get(key).and_then(Value::as_str).and_then(|text| Moment::parse(text, zone)); let done = card.pace.as_ref().is_some_and(|pace| { data.get(&pace.done.column).and_then(Value::as_str).is_some_and(|value| pace.done.values.iter().any(|done| done == value)) }); let pace = card.pace.as_ref().map(|inputs| { let repeats = inputs.repeat.as_deref().is_some_and(|key| text(data, key).is_some()); Pace::of(moment(&inputs.date), today, done, repeats) }); let say = |key: &str, form: Form| { let column = definition.column(key)?; form_words(definition, column, data.get(key)?, data, Some(zone), Some(now), form, words) }; // The corner says the day alone; a timed date's clock is the foot's. let say_day = |key: &str, form: Form| { let column = definition.column(key)?; let text = data.get(key)?.as_str()?; let day = match column.yearly == Some(true) { true => text.to_string(), false => { let (year, month, day) = civil_from_days(Moment::parse(text, zone)?.day); format!("{year:04}-{month:02}-{day:02}") } }; form_words(definition, column, &Value::String(day), data, Some(zone), Some(now), form, words) }; // A finished record says only its done facts ("Done yesterday"), an // open one only the rest. let corner = card .corner .iter() .filter(|fact| fact.done == done) .find_map(|fact| { let ahead = holds(fact, definition, data, zone, today.day)?; let said = say_day(&fact.column, fact.form)?; let words = match &fact.line { Some(line) => cards.say(line, &[("said", &said)])?, None => said, }; // A fact read off a date gone (a birthday is never behind) is // pressing only where it says the record is owed. Some((ahead < 0 && fact.line.is_none(), words)) }); let mut fields: Map = card .fields .iter() .filter_map(|field| { // The group place names no column: it says the group the record // stands in, read from its membership by the caller. let Some(key) = field.column.as_deref() else { let group = (field.slot == CardSlot::Group).then_some(around.group).flatten()?; return Some((slot_name(field.slot)?, Value::String(group.to_string()))); }; // A value kept under a key of the column's object (a document's // facts): an amount in the object's own currency, a day as the // date place says it, a name as kept. if let Some(at) = field.at.as_deref() { let object = match data.get(key)? { Value::Object(object) => object.clone(), Value::String(text) => serde_json::from_str::>(text).ok()?, _ => return None, }; let said = match field.slot { CardSlot::Amount => { let minor = object.get(at)?.as_i64()?; let currency = object.get("currency").and_then(Value::as_str).map(str::trim).filter(|code| !code.is_empty()); crate::records::amount::amount(minor, currency, &words.money).said(crate::records::amount::MoneyForm::Money, &words.money) } CardSlot::Expires => { let day = Moment::parse(object.get(at)?.as_str()?.trim(), zone)?.day; words.dates.weekday_date(day, civil_from_days(today.day).0) } _ => object.get(at)?.as_str()?.trim().to_string(), }; return (!said.is_empty()).then(|| Some((slot_name(field.slot)?, Value::String(said)))).flatten(); } // The people place names whom its link column holds, as the // caller read them; one it could not read is left out. if field.slot == CardSlot::People { let (shown, _) = people(field, data, around)?; return Some((slot_name(field.slot)?, serde_json::to_value(shown).ok()?)); } // The ink, seal and weather places say their choice's stored // value: the face draws by it, never by the label, which is copy. if matches!(field.slot, CardSlot::Ink | CardSlot::Seal | CardSlot::Weather) { let value = data.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())?; return Some((slot_name(field.slot)?, Value::String(value.to_string()))); } // The state place says its choice's label only for the values it // names; an open record says nothing there. A yes/no column in // `also` that is set stands there first, said by its own name (a // film still converting on the Mac, whatever its status). if field.slot == CardSlot::State { if let Some(flag) = field.also.iter().find(|flag| data.get(flag.as_str()).is_some_and(set)) { return Some((slot_name(field.slot)?, Value::String(definition.column(flag)?.label()))); } let value = data.get(key).and_then(Value::as_str).filter(|value| field.only.iter().any(|only| only == value))?; let label = definition.column(key)?.choice_label(value); return Some((slot_name(field.slot)?, Value::String(label))); } // The account place says the linked account's name, as read; the // album place the first linked album's. if matches!(field.slot, CardSlot::Account | CardSlot::Album) { let id = linked_ids(data.get(key)).into_iter().next()?; let name = around.people?.get(&id)?.name.clone(); return Some((slot_name(field.slot)?, Value::String(name))); } // Who recommended it: the linked person's name, as read, else the // name kept as text. if field.slot == CardSlot::RecommendedBy { let linked = linked_ids(data.get(key)).into_iter().next().and_then(|id| Some(around.people?.get(&id)?.name.clone())); let named = linked.or_else(|| field.also.iter().find_map(|key| text(data, key)))?; return Some((slot_name(field.slot)?, Value::String(named))); } // The unread place is a dot: yes, or one of the values it names. if field.slot == CardSlot::Unread { let unread = match data.get(key) { Some(Value::Bool(unread)) => *unread, Some(Value::Number(number)) => number.as_i64().is_some_and(|number| number != 0), Some(Value::String(value)) => field.only.iter().any(|only| only == value), _ => false, }; return Some((slot_name(field.slot)?, Value::Bool(unread))); } // An undated record's date place asks for one, where a person may // write it: "Add date". A date kept elsewhere says nothing. if field.slot == CardSlot::Date && data.get(key).is_none_or(|value| value.is_null() || value.as_str() == Some("")) { let writable = around.writable && definition.column(key).is_some_and(|column| column.readonly != Some(true)) && definition.readonly_when.as_deref().is_none_or(|kept| data.get(kept).is_none_or(Value::is_null)); return writable.then(|| Some((slot_name(field.slot)?, Value::String(cards.say("date.add", &[])?)))).flatten(); } // The span says its first day to its last, or the one day. if field.slot == CardSlot::Span { let year = civil_from_days(today.day).0; // The first day reads off the field's own column, never a // binding the diagnostics guard reads as a credential's name. let first = field.column.as_deref().and_then(|start| moment(start))?.day; let last = field.also.first().and_then(|end| moment(end)).map(|at| at.day).filter(|last| *last > first); let from = words.dates.weekday_date(first, year); let said = match last { Some(last) => cards.say("span.between", &[("from", &from), ("to", &words.dates.weekday_date(last, year))])?, None => from, }; return Some((slot_name(field.slot)?, Value::String(said))); } // The wishes and star places are switches: yes or no, never words. if matches!(field.slot, CardSlot::Wishes | CardSlot::Star) { let wished = matches!(data.get(key), Some(Value::Bool(true))) || data.get(key).and_then(Value::as_i64).is_some_and(|flag| flag != 0); return Some((slot_name(field.slot)?, Value::Bool(wished))); } // The age a yearly date comes round to next, said in the dates' // words; a day kept without its year says the age is not known. if field.slot == CardSlot::Turns { let text = data.get(key)?.as_str()?.trim(); let Some(born) = (!text.starts_with("--")).then(|| Moment::parse(text, zone)).flatten().map(|at| civil_from_days(at.day)) else { return Some((slot_name(field.slot)?, Value::String(cards.say("turns.unknown", &[])?))); }; let next = next_yearly_occurrence(born.1, born.2, civil_from_days(today.day)); let age = years_completed(born, next)?; return Some((slot_name(field.slot)?, Value::String(DateAge::Turns(age).words(&words.dates)))); } // The end place says its clock alone on the day the record // starts, else its day, with its clock when it keeps one. if field.slot == CardSlot::Ends { let end = moment(key)?; let start = field.also.first().and_then(|start| moment(start)); let said = match start { Some(start) if start.day == end.day && end.timed() => end.clock(&words.dates), _ => { let day = words.dates.weekday_date(end.day, civil_from_days(today.day).0); if end.timed() { format!("{day}{FACT_JOIN}{}", end.clock(&words.dates)) } else { day } } }; return Some((slot_name(field.slot)?, Value::String(said))); } // The repeats place says the rule in words, as the page does. if field.slot == CardSlot::Repeats { let column = definition.column(key)?; let said = fact_words(definition, column, data.get(key)?, data, Some(zone), Some(now), words).filter(|said| !said.trim().is_empty())?; return Some((slot_name(field.slot)?, Value::String(said))); } // The kept-by place says the table's own words while it is kept. if field.slot == CardSlot::KeptBy { text(data, key)?; return Some((slot_name(field.slot)?, Value::String(definition.kept_by.as_ref()?.says.clone()))); } // The phone place says the first number its column keeps. if field.slot == CardSlot::Phone { let first = match list(data.get(key)) { Some(numbers) => numbers.iter().find_map(|number| number.as_str().map(str::trim).filter(|number| !number.is_empty()).map(str::to_string)), None => text(data, key).map(|number| number.trim().to_string()), }?; return Some((slot_name(field.slot)?, Value::String(first))); } // The facts place says each of its columns under its label, as // the record page said it; one with no value is left out, and // none at all leaves the place empty. if field.slot == CardSlot::Facts { let facts: Vec = std::iter::once(key) .chain(field.also.iter().map(String::as_str)) .filter_map(|key| { let column = definition.column(key)?; let said = labelled_fact_words(definition, column, data.get(key)?, data, Some(zone), Some(now), words) .filter(|said| !said.trim().is_empty())?; Some(serde_json::json!({"label": column.label(), "said": said})) }) .collect(); return (!facts.is_empty()).then(|| Some((slot_name(field.slot)?, Value::Array(facts)))).flatten(); } // The hours left until the date's instant, on the reader's clock. if field.slot == CardSlot::HoursLeft { let at = moment(key)?; let minutes = (at.day - today.day) * 24 * 60 + at.minute - today.minute; let said = match minutes { ..=0 => cards.say("quota.reset", &[])?, 1..=59 => cards.say("quota.under_an_hour", &[])?, 60..=119 => cards.say("quota.hour_left", &[])?, _ => cards.say("quota.hours_left", &[("n", &(minutes / 60).to_string())])?, }; return Some((slot_name(field.slot)?, Value::String(said))); } // The weekday the date's instant falls on, while it is ahead. if field.slot == CardSlot::ResetsOn { let at = moment(key)?; if (at.day, at.minute) <= (today.day, today.minute) { return None; } let day = words.dates.weekday_name(crate::transforms::zoned_clock::weekday_of_day_number(at.day)); return Some((slot_name(field.slot)?, Value::String(cards.say("quota.resets_on", &[("day", &day)])?))); } // A trend is the numbers its list holds, oldest first. if field.slot == CardSlot::Trend { let points: Vec = list(data.get(key))? .into_iter() .filter_map(|point| match point { Value::Number(number) => Some(Value::Number(number)), Value::String(text) => serde_json::Number::from_f64(text.trim().parse().ok()?).map(Value::Number), _ => None, }) .collect(); return (!points.is_empty()).then(|| Some((slot_name(field.slot)?, Value::Array(points)))).flatten(); } // A dial is two numbers the face draws: the used part and its whole. if matches!(field.slot, CardSlot::MemoryDial | CardSlot::DiskDial | CardSlot::LoadDial) { let number = |column: &str| match data.get(column)? { Value::Number(number) => Some(number.clone()), Value::String(text) => serde_json::Number::from_f64(text.trim().parse().ok()?), _ => None, }; let used = number(key)?; let total = number(field.also.first()?)?; return Some((slot_name(field.slot)?, serde_json::json!({"used": used, "total": total}))); } // The gauge's parts and a book's pages are numbers the face // draws, never words. if matches!(field.slot, CardSlot::Used | CardSlot::Free | CardSlot::Limit | CardSlot::Pages) { let number = match data.get(key)? { Value::Number(number) => number.clone(), Value::String(text) => serde_json::Number::from_f64(text.trim().parse().ok()?)?, _ => return None, }; return Some((slot_name(field.slot)?, Value::Number(number))); } // A list (a mood's emotions, a meeting's speakers) passes through // as a list of words: a choice's in its labels, a person or other // object by its name, anything else as its text. if let Some(items) = list(data.get(key)) { let column = definition.column(key); // A stored value the cards set has words for, said in them. let value_words = |column: &str, value: String| cards.say(&format!("values.{column}.{value}"), &[]).unwrap_or(value); let said: Vec = items .iter() .filter_map(|item| { let text = match item { Value::String(text) => text.trim().to_string(), Value::Number(number) => number.to_string(), Value::Object(object) => ["name", "label", "title"].iter().find_map(|key| object.get(*key)?.as_str())?.trim().to_string(), _ => return None, }; if text.is_empty() { return None; } Some(Value::String(match column { Some(column) if column.column_type == ColumnType::Choice => column.choice_label(&text), _ => value_words(key, text), })) }) .collect(); return (!said.is_empty()).then(|| Some((slot_name(field.slot)?, Value::Array(said)))).flatten(); } let said = match (field.slot, field.form) { (CardSlot::Check, _) => return Some((slot_name(field.slot)?, Value::Bool(done))), (CardSlot::Date | CardSlot::NextCharge | CardSlot::Started | CardSlot::LastRead | CardSlot::Expires, form) => say(key, form.unwrap_or(Form::WeekdayDate)), (CardSlot::Amount | CardSlot::Price, form) => say(key, form.unwrap_or(Form::Money)), (CardSlot::Count, form) => say(key, form.unwrap_or(Form::Count)), (CardSlot::LastWished, form) => say(key, form.unwrap_or(Form::Relative)), (CardSlot::Year, None) if definition.column(key).is_some_and(|column| column.column_type == ColumnType::Date) => say(key, Form::Year), (_, Some(form)) => say(key, form), // A choice is said in its label ("Monthly"), never its value. (_, None) => match definition.column(key) { // A title over a link says the linked record's name, as // read (a statement's account: "Larkspur Card"). Some(column) if field.slot == CardSlot::Title && column.column_type == ColumnType::Link => { let id = linked_ids(data.get(key)).into_iter().next()?; Some(around.people?.get(&id)?.name.clone()) } Some(column) if column.column_type == ColumnType::Choice => { data.get(key).and_then(Value::as_str).filter(|value| !value.is_empty()).map(|value| column.choice_label(value)) } // A date is said as its column's format says it on the // page — a countdown from the reader's now ("resets in // 2 d 23 h", "has reset"), never its stored instant. Some(column) if column.column_type == ColumnType::Date && column.format.is_some() => { fact_words(definition, column, data.get(key)?, data, Some(zone), Some(now), words) } // A column whose reading says more than its value ("from 10 // guests", "60 min") before its count words is said through it. Some(column) if says_more_than_its_value(column) && field.slot != CardSlot::Number => { read_fact(definition, column, data.get(key)?, data, Some(zone), Some(now), words) } // A number with count words is said in them ("1 page", // "3 pages"), as the page says it. Some(column) if column.column_type == ColumnType::Number && column.units.is_some() && field.slot != CardSlot::Number => { fact_words(definition, column, data.get(key)?, data, Some(zone), Some(now), words) } // A time is the clock ("7:00 am"), never its stored digits. Some(column) if column.column_type == ColumnType::Time => { fact_words(definition, column, data.get(key)?, data, Some(zone), Some(now), words) } _ => text(data, key), }, }; // A joined field stands on whichever of its columns hold a value; // every other field needs its own. let said = match said { Some(said) => Some(said), None if field.line.is_none() && !field.also.is_empty() => None, None => return None, }; // A stored value the cards set has words for ("whatsapp" → // "WhatsApp", under `values.`) is said in them. let value_words = |column: &str, value: &str| cards.say(&format!("values.{column}.{value}"), &[]).unwrap_or_else(|| value.to_string()); // A joined column is said in its column's own words — a time as // the clock ("7:00 am"), a number through its reading ("60 min"), // a choice in its label — and a plain text or bare number as kept. // A stored value the cards set has words for is said in them // first, whatever its column ("monthly" → "month", not "Monthly"). let also_words = |key: &str| -> Option { let column = definition.column(key)?; let value = data.get(key)?; if let Some(said) = value.as_str().and_then(|value| cards.say(&format!("values.{key}.{}", value.trim()), &[])) { return Some(said); } if says_more_than_its_value(column) { return read_fact(definition, column, value, data, Some(zone), Some(now), words); } match column.column_type { ColumnType::Text | ColumnType::Longtext => Some(value_words(key, &text(data, key)?)), ColumnType::Number if column.units.is_none() && column.format.is_none() => text(data, key), ColumnType::Link | ColumnType::Photo | ColumnType::File => None, _ => fact_words(definition, column, value, data, Some(zone), Some(now), words), } }; let value = Value::String(match (&field.line, said) { (Some(line), Some(said)) => { let also: Vec<(&str, String)> = field.also.iter().map(|key| Some((key.as_str(), also_words(key)?))).collect::>()?; let mut fills: Vec<(&str, &str)> = vec![("said", said.as_str())]; fills.extend(also.iter().map(|(key, words)| (*key, words.as_str()))); // A number column's line is picked by its count (`{n}`): // "1 episode", "3 episodes", whatever the column says of // its own words. let count = definition.column(key).filter(|column| column.column_type == ColumnType::Number) .and_then(|_| data.get(key)).and_then(|value| match value { Value::Number(number) => number.as_f64(), Value::String(text) => text.trim().parse().ok(), _ => None, }) .map(|n: f64| if n.fract() == 0.0 { format!("{}", n as i64) } else { n.to_string() }); if let Some(count) = &count { fills.push(("n", count.as_str())); } cards.say(line, &fills)? } (None, said) if !field.also.is_empty() => { let join = cards.say("join", &[]).unwrap_or_default(); let parts: Vec = said.into_iter().chain(field.also.iter().filter_map(|key| also_words(key))).collect(); if parts.is_empty() { return None; } parts.join(&join) } (_, said) => said?, }); Some((slot_name(field.slot)?, value)) }) .collect(); // A place this card labels in its own words (Money's Future: "Due"), // said only where the place itself says something. let labels: Map = card .fields .iter() .filter_map(|field| { let slot = slot_name(field.slot)?; fields.contains_key(&slot).then_some(())?; Some((slot, Value::String(cards.say(field.label.as_deref()?, &[])?))) }) .collect(); if !labels.is_empty() { fields.insert(LABELS.into(), Value::Object(labels)); } let more = card.fields.iter().find(|field| field.slot == CardSlot::People).and_then(|field| people(field, data, around)); if let Some((_, more)) = more.filter(|(_, more)| *more > 0) { if let Some(said) = cards.say("people.more", &[("n", &more.to_string())]) { fields.insert(PEOPLE_MORE.into(), Value::String(said)); } } Some(ResolvedCard { face: card.faces.iter().find(|rule| { data.get(&rule.when.column).and_then(Value::as_str).is_some_and(|value| rule.when.values.iter().any(|choice| choice == value)) }).map_or(card.face, |rule| rule.face), pressing: corner.as_ref().is_some_and(|(pressing, _)| *pressing), corner: corner.map(|(_, words)| words), plate: card.art.and(pace).map(|_| animal(record_id)), pace, fields, thread: around.thread.cloned(), }) } /// How many of a group's lines its card says: the latest three. pub const GROUP_LINES: usize = 3; /// One card of a group deck: the record the group's link names (its id, "" /// for the rows that name none), how many rows the group holds, and its card. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct GroupCard { pub value: String, pub count: usize, pub card: ResolvedCard, } /// The column a group card (`FaceId::GROUP`, Money's By person) deals its /// rows by: its people place's, when that place reads a link. None for any /// other card. pub fn group_by<'a>(card: &'a CardFace, definition: &TableDefinition) -> Option<&'a str> { if card.face != FaceId::GROUP { return None; } card.fields.iter().find(|field| field.slot == CardSlot::People).and_then(|field| field.column.as_deref()) .filter(|by| definition.column(by).is_some_and(|column| column.link_to.is_some())) } /// The group a row is dealt into: the first record its `by` column names, /// "" for none (every row naming nobody is one group). pub fn group_of(by: &str, row: &Map) -> String { linked_ids(row.get(by)).into_iter().next().unwrap_or_default() } /// How many cards a group deck deals over `rows`: its distinct groups, so a /// fan's tile counts the deck it opens (By person counts people, not rows). pub fn group_count<'a>(by: &str, rows: impl IntoIterator>) -> usize { rows.into_iter().map(|row| group_of(by, row)).collect::>().len() } /// A group deck's cards (`FaceId::GROUP`): one per record the card's /// people place's link column names, over EVERY row of the view in its /// order — the groups in the order their first row stands, so a list read /// newest first deals the latest dealings first. Each card says the linked /// record's name and picture (`people`, read by the caller), the figures the /// table's group says over the group's rows where that group is by the same /// column (Owed's "between you"), and the group's first [`GROUP_LINES`] /// rows, each said through the card's other places as a card of its own. #[allow(clippy::too_many_arguments)] pub fn deal_groups( card: &CardFace, definition: &TableDefinition, rows: &[(String, Map)], people: &std::collections::HashMap, zone: &str, now: chrono::DateTime, words: &Words, cards: &LineSet, ) -> Vec { let Some(by) = card.fields.iter().find(|field| field.slot == CardSlot::People).and_then(|field| field.column.as_deref()) else { return Vec::new(); }; let mut groups: Vec<(String, Vec<&(String, Map)>)> = Vec::new(); for row in rows { let value = group_of(by, &row.1); match groups.iter_mut().find(|(held, _)| *held == value) { Some((_, members)) => members.push(row), None => groups.push((value, vec![row])), } } let nets: std::collections::HashMap> = match definition.group.as_ref().filter(|group| group.column == by) { Some(_) => { let data: Vec> = rows.iter().map(|(_, data)| data.clone()).collect(); super::group_heads(definition, &data, words, &super::where_zone(Some(zone))) .unwrap_or_default() .into_iter() .map(|head| (linked_ids(Some(&head.value)).into_iter().next().unwrap_or_default(), head.lines)) .collect() } None => std::collections::HashMap::new(), }; // Each line is the record said through the card's other places. let line = CardFace { fields: card.fields.iter().filter(|field| field.slot != CardSlot::People).cloned().collect(), corner: Vec::new(), pace: None, art: None, ..card.clone() }; groups .into_iter() .map(|(value, members)| { let person = people.get(&value); let mut fields = Map::new(); let title = person.map(|person| person.name.clone()).or_else(|| value.is_empty().then(|| cards.say("group.nobody", &[])).flatten()); if let Some(title) = title { fields.insert("title".into(), Value::String(title)); } if let Some(picture) = person.and_then(|person| person.picture.clone()) { fields.insert("photo".into(), Value::String(picture)); } if let Some(net) = nets.get(&value).filter(|net| !net.is_empty()) { fields.insert("net".into(), Value::Array(net.iter().cloned().map(Value::String).collect())); } let lines: Vec = members .iter() .take(GROUP_LINES) .filter_map(|(id, data)| resolve(&line, definition, id, data, zone, now, words, cards, Around::default())) .map(|said| Value::Object(said.fields)) .collect(); fields.insert("lines".into(), Value::Array(lines)); if members.len() > GROUP_LINES { if let Some(more) = cards.say("people.more", &[("n", &(members.len() - GROUP_LINES).to_string())]) { fields.insert("more".into(), Value::String(more)); } } let count = members.len(); GroupCard { value, count, card: ResolvedCard { thread: None, face: FaceId::GROUP, corner: None, pressing: false, pace: None, plate: None, fields } } }) .collect() } #[cfg(test)] mod tests { use super::*; use crate::definitions::builtin_table_definitions; use serde_json::json; /// RULE: A thread's core card carries six complete slips, in chat order, /// with the first year's count, direction, sender and the chat's clock. #[test] fn thread_history_is_whole_before_a_card_is_drawn() { let definitions = builtin_table_definitions(); let table = definitions.iter().find(|table| table.id == "thread").unwrap(); let messages = definitions.iter().find(|table| table.id == "message").unwrap(); let layout = table.conversation.as_ref().unwrap(); let rows: Vec<_> = (0..8).rev().map(|n| (format!("m-{n}"), json!({"display_body":format!(" Invented line {n} "),"direction":if n%2==1 {"out"} else {"in"},"paper_sender":"Invented writer","sent_at":format!("2026-10-30T03:0{n}:00Z")} ).as_object().unwrap().clone())).collect(); let now = chrono::DateTime::parse_from_rfc3339("2026-10-30T04:00:00Z").unwrap().to_utc(); let format = LineSet::shipped("format").unwrap(); let history = thread_history(layout, messages, true, &rows, 1234, Some("2020-01-01T00:00:00Z"), "Asia/Kolkata", now, Words::shipped(), &format); assert_eq!(history.earlier.iter().map(|line| line.id.as_str()).collect::>(), ["m-2", "m-3", "m-4", "m-5", "m-6"]); let last = history.last.as_ref().unwrap(); assert_eq!(last.id, "m-7"); assert_eq!(last.words, "Invented line 7"); assert!(last.mine); assert_eq!(last.time.as_deref(), Some("8:37 am")); assert_eq!(last.sender.as_deref(), Some("Invented writer")); assert!(history.count.as_deref().unwrap().ends_with("2020")); let said = resolve(table.card.as_ref().unwrap(), table, "t-1", json!({"title":"Invented thread"}).as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &card_words(&crate::rules::shell_lines::shipped_rows()), Around {thread:Some(&history), ..Around::default()}).unwrap(); assert_eq!(said.thread, Some(history)); let direct = thread_history(layout, messages, false, &rows, 8, None, "Asia/Kolkata", now, Words::shipped(), &format); assert!(direct.earlier.iter().all(|line| line.sender.is_none())); assert!(direct.last.unwrap().sender.is_none()); let empty = thread_history(layout, messages, false, &[], 0, None, "Asia/Kolkata", now, Words::shipped(), &format); assert!(empty.count.is_none() && empty.last.is_none() && empty.earlier.is_empty()); } /// RULE: A queued slip stays at its created time and says no sent clock /// until the transport acknowledges it with an external id. #[test] fn thread_history_keeps_queue_order_without_inventing_a_sent_time() { let definitions = builtin_table_definitions(); let table = definitions.iter().find(|table| table.id == "thread").unwrap(); let messages = definitions.iter().find(|table| table.id == "message").unwrap(); let rows = vec![ ("pending".into(), json!({"display_body":"Pending", "direction":"out", "channel":"whatsapp", "send_state":"sent", "created_at":"2026-10-30T03:10:00Z", "sent_at":"2026-10-30T03:00:00Z"}).as_object().unwrap().clone()), ("in".into(), json!({"display_body":"Hello", "sent_at":"2026-10-30T03:05:00Z"}).as_object().unwrap().clone()), ]; let now = chrono::DateTime::parse_from_rfc3339("2026-10-30T04:00:00Z").unwrap().to_utc(); let history = thread_history(table.conversation.as_ref().unwrap(), messages, false, &rows, 2, None, "Asia/Kolkata", now, Words::shipped(), &LineSet::shipped("format").unwrap()); assert_eq!(history.earlier[0].id, "in"); assert_eq!(history.last.as_ref().unwrap().id, "pending"); assert!(history.last.unwrap().time.is_none()); } fn todo() -> TableDefinition { builtin_table_definitions().iter().find(|table| table.id == "todo").unwrap().clone() } fn at(text: &str) -> chrono::DateTime { chrono::DateTime::parse_from_rfc3339(text).unwrap().with_timezone(&chrono::Utc) } /// RULE: A place whose column has both a reading and count words is /// said through its reading ("from 10 guests"), and under its label a /// fact says its count words ("10 guests"), never a bare figure. #[test] fn a_catering_card_reads_its_guests_in_the_subtitle_and_counts_them_under_their_label() { let kitchen = crate::toolkits::shipped_kit_tools().into_iter().find(|package| package.tool.id == "kitchen").expect("the kitchen package ships"); let table = kitchen.tables.iter().find(|table| table.id == "kitchen_catering").unwrap().clone(); let card = table.card.clone().expect("catering carries a card"); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"name": "Naga dinner for a party", "description": "Smoked pork", "guests_from": 10, "price_from": 34900, "currency": "INR", "notice_days": 3, "available": true}); let read = resolve(&card, &table, "c-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(read.fields["subtitle"], json!("from 10 guests · 3 days' notice")); assert_eq!(read.fields["facts"], json!([ {"label": "A plate from", "said": "₹349"}, {"label": "For", "said": "10 guests"}, {"label": "Notice", "said": "3 days"}, ])); } /// RULE: A joined column is said in its own words — a time as the clock /// after the day, a number through its reading — and a place whose /// column has a reading says it; a session's card then carries its /// clock, not "All day", and "60 min", not "60". #[test] fn a_session_card_says_its_clock_after_the_day_and_its_numbers_through_their_readings() { let yoga = crate::toolkits::shipped_kit_tools().into_iter().find(|package| package.tool.id == "yoga").expect("the yoga package ships"); let table = yoga.tables.iter().find(|table| table.id == "yoga_session").unwrap().clone(); let card = table.card.clone().expect("a session carries a card"); let now = at("2026-10-24T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"name": "Iyengar Hatha Flow", "on": "2026-10-26", "starts": "07:00", "minutes": 60, "places_left": 20}); let read = resolve(&card, &table, "s-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(read.fields["date"], json!("Mon 26 Oct · 7:00 am")); assert_eq!(read.fields["subtitle"], json!("60 min")); assert_eq!(read.fields["place"], json!("20 places left")); } /// RULE: "Add date" is an offer to write, so an empty date place says it /// only to a reader who may write the record — never to a business's /// public reading a dateless event. #[test] fn an_empty_date_place_offers_add_date_only_to_a_reader_who_may_write() { let table = todo(); let card = table.card.clone().unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"title": "Undated", "status": "open"}); let own = resolve(&card, &table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(own.fields["date"], json!("Add date")); let reading = resolve(&card, &table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around { writable: false, ..Around::default() }).unwrap(); assert!(reading.fields.get("date").is_none(), "{:?}", reading.fields); } #[test] fn a_todo_card_says_its_corner_only_when_it_calls_for_attention() { let table = todo(); let card = table.card.clone().expect("the kit's todo carries a card"); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let late = read(json!({"title": "Pay the September GST", "status": "open", "due_at": "2026-10-16"})); assert_eq!(late.corner.as_deref(), Some("6 days late")); assert!(late.pressing); assert_eq!(late.pace, Some(Pace::Late)); assert_eq!(late.plate, Some(animal("t-1"))); assert_eq!(late.fields["title"], json!("Pay the September GST")); assert_eq!(late.fields["check"], json!(false)); assert_eq!(late.fields["date"], json!("Fri 16 Oct")); let tomorrow = read(json!({"title": "Call", "status": "open", "due_at": "2026-10-23"})); assert_eq!(tomorrow.corner.as_deref(), Some("Tomorrow")); assert!(!tomorrow.pressing); assert_eq!(tomorrow.pace, Some(Pace::Soon)); let later = read(json!({"title": "Book", "status": "open", "due_at": "2026-10-30"})); assert_eq!(later.corner.as_deref(), Some("Fri 30 Oct"), "a day to come says its day"); let soon = read(json!({"title": "Book", "status": "open", "due_at": "2026-10-27T18:30:00+05:30"})); assert_eq!(soon.corner.as_deref(), Some("in 5 days"), "the corner never says the clock"); assert_eq!(soon.fields["date"], json!("Tue 27 Oct · 6:30 pm"), "the foot does"); let today = read(json!({"title": "Dig", "status": "open", "due_at": "2026-10-22T06:48:00+05:30"})); assert_eq!((today.corner.as_deref(), today.pressing), (Some("Today"), false)); let yesterday = read(json!({"title": "Pay", "status": "open", "due_at": "2026-10-21"})); assert_eq!(yesterday.corner.as_deref(), Some("1 day late"), "the late form never says yesterday"); assert!(yesterday.pressing); let long = read(json!({"title": "Pay", "status": "open", "due_at": "2026-09-01"})); assert_eq!(long.corner.as_deref(), Some("51 days late")); assert_eq!(later.pace, Some(Pace::Upcoming)); let someday = read(json!({"title": "Read", "status": "open"})); assert_eq!((someday.corner, someday.pace), (None, Some(Pace::Someday))); let done = read(json!({"title": "Pay", "status": "done", "due_at": "2026-10-16"})); assert_eq!(done.corner, None, "a finished record calls for nothing"); assert_eq!(done.pace, Some(Pace::Done)); assert_eq!(done.fields["check"], json!(true)); } // RULE: a list a card names — a mood's emotions, a meeting's speakers — // reaches the card as a list of words, never dropped: a choice's items in // their labels, a speaker by name, kept as an array or as its JSON text. #[test] fn a_list_reaches_its_card_as_a_list_of_words() { // The kit's todo, made over into an invented table with lists. let mut table = serde_json::to_value(todo()).unwrap(); let made = json!({ "id": "synthetic_mood", "title": "line", "columns": [ {"key": "line", "name": "Words", "type": "text"}, {"key": "emotions", "name": "Emotions", "type": "choice", "choices": ["calm", "tired"], "labels": {"calm": "At ease"}}, {"key": "speakers", "name": "Speakers", "type": "longtext"} ], "card": {"face": "mood", "fields": [{"slot": "title", "column": "line"}, {"slot": "subtitle", "column": "emotions"}, {"slot": "body", "column": "speakers"}]} }); for (key, value) in made.as_object().unwrap() { table[key] = value.clone(); } let table: TableDefinition = serde_json::from_value(table).expect("a synthetic table"); let card = table.card.clone().unwrap(); let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let read = |data: serde_json::Value| { resolve(&card, &table, "m-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let held = read(json!({"line": "A slow morning", "emotions": ["calm", "tired"], "speakers": "[{\"name\": \"Invented Asha\"}, \"Invented Ravi\"]"})); assert_eq!(held.fields["subtitle"], json!(["At ease", "Tired"])); assert_eq!(held.fields["body"], json!(["Invented Asha", "Invented Ravi"])); let empty = read(json!({"line": "Nothing named", "emotions": []})); assert!(empty.fields.get("subtitle").is_none(), "an empty list leaves its place empty"); } // RULE: a song's length reads as a player's clock — "3:42", and the hours // before it once there are any ("1:04:05") — never "3 min 42 s". #[test] fn a_length_in_the_clock_form_reads_as_a_players_clock() { let mut table = serde_json::to_value(todo()).unwrap(); for (key, value) in json!({ "id": "synthetic_track", "title": "title", "columns": [{"key": "title", "name": "Title", "type": "text"}, {"key": "duration", "name": "Length", "type": "number", "format": "duration"}], "card": {"face": "track", "fields": [{"slot": "title", "column": "title"}, {"slot": "length", "column": "duration", "form": "clock"}]} }) .as_object() .unwrap() { table[key] = value.clone(); } let table: TableDefinition = serde_json::from_value(table).expect("a synthetic table"); let card = table.card.clone().unwrap(); let cards = LineSet::shipped("cards").unwrap(); let length = |seconds: f64| { let data = json!({"title": "An invented song", "duration": seconds}); resolve(&card, &table, "s-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-23T10:00:00+05:30"), Words::shipped(), &cards, Around::default()) .unwrap() .fields .get("length") .cloned() }; assert_eq!(length(222.0), Some(json!("3:42"))); assert_eq!(length(59.4), Some(json!("0:59"))); assert_eq!(length(3845.0), Some(json!("1:04:05"))); } // RULE: a card never shows a record number (owner's ruling, 22 Oct // 2026). Its foot may say the group the record stands in, read from the // record's membership and never a column, and its state, a choice's own // label said only for the values the card names — an open todo says no // state at all. #[test] fn a_card_says_its_group_and_only_the_states_it_names() { let table = todo(); let cards = LineSet::shipped("cards").unwrap(); let mut card = table.card.clone().unwrap(); card.fields.retain(|field| !matches!(field.slot, CardSlot::Group | CardSlot::State)); card.fields.push(serde_json::from_value(json!({"slot": "group"})).unwrap()); card.fields.push(serde_json::from_value(json!({"slot": "state", "column": "status", "only": ["dropped", "missed"]})).unwrap()); card.validate(&table, "card").expect("a group place and a state place"); let now = at("2026-10-22T10:00:00+05:30"); let read = |data: serde_json::Value, group: Option<&str>| { resolve(&card, &table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around { group, ..Around::default() }).unwrap() }; let grouped = read(json!({"title": "Call", "status": "open"}), Some("Errands")); assert_eq!(grouped.fields["group"], json!("Errands")); assert!(grouped.fields.get("state").is_none(), "an open todo says no state"); let dropped = read(json!({"title": "Call", "status": "dropped"}), None); assert_eq!(dropped.fields["state"], json!("Dropped")); assert!(dropped.fields.get("group").is_none(), "a record in no group says none"); assert!(read(json!({"title": "Call", "status": "done"}), None).fields.get("state").is_none(), "done is not named"); for bad in [ json!({"slot": "group", "column": "title"}), json!({"slot": "state", "column": "status"}), json!({"slot": "state", "column": "status", "only": ["waiting"]}), json!({"slot": "state", "column": "title", "only": ["x"]}), json!({"slot": "title", "column": "title", "only": ["x"]}), json!({"slot": "title"}), ] { let mut wrong = table.card.clone().unwrap(); wrong.fields.retain(|field| !matches!(field.slot, CardSlot::Title | CardSlot::Group | CardSlot::State)); wrong.fields.push(serde_json::from_value(bad.clone()).unwrap()); assert!(wrong.validate(&table, "card").is_err(), "{bad} is refused"); } } // A person's card says what calls now in the corner — a birthday within // the week, or a long silence — and its places join the columns the kit // names in the cards set's words, so a rewording is data: the channel a // person was last reached on is said by name, and a subtitle stands on // whichever of role, organisation and city are held. #[test] fn a_person_card_says_what_calls_now_and_joins_its_columns() { let table = builtin_table_definitions().iter().find(|table| table.id == "person").unwrap().clone(); let card = table.card.clone().expect("the kit's person carries a card"); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "p-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let soon = read(json!({ "full_name": "Asha Rao", "role_title": "Architect", "org": "Studio Lumen", "city": "Pune", "birthday": "--10-25", "reached_at": "2026-10-20", "thread_channel": "whatsapp" })); assert_eq!(soon.corner.as_deref(), Some("Birthday in 3 days")); assert!(!soon.pressing, "a birthday is never owed"); assert_eq!(soon.fields["title"], json!("Asha Rao")); assert_eq!(soon.fields["subtitle"], json!("Architect · Studio Lumen · Pune")); // The kit names no city slot until every phone decodes one (CardSlot::City // reached the core on 30 Oct 2026; a phone built before it reads the // person table as unreadable when the kit names it). assert!(!soon.fields.contains_key("city"), "the shipped kit names no city slot yet"); assert_eq!(soon.fields["reached"], json!("Last spoke 2 days ago on WhatsApp")); let quiet = read(json!({"full_name": "Ben Ade", "city": "Lagos", "reached_at": "2026-08-20", "thread_channel": "sms"})); assert_eq!(quiet.corner.as_deref(), Some("Not reached in 9 weeks")); assert_eq!(quiet.fields["subtitle"], json!("Lagos"), "a subtitle stands on the columns held"); assert_eq!(quiet.fields["reached"], json!("Last spoke 2 months ago on Messages")); let bare = read(json!({"full_name": "Cleo", "reached_at": "2026-10-21"})); assert_eq!(bare.corner, None); assert!(bare.fields.get("subtitle").is_none()); assert!(bare.fields.get("reached").is_none(), "a reached line without its channel is not said"); } // RULE: a birthday card says the day it comes round with its weekday's // whole name, the age it turns — or that the age is not known, for a // day kept without its year — how the person was last wished in its // choice's label, a number to call them on, and counts down to the day // in its corner however far off it is. #[test] fn a_birthday_card_says_its_weekday_whole_its_age_or_none_and_how_they_were_wished() { let mut table = builtin_table_definitions().iter().find(|table| table.id == "person").unwrap().clone(); table.columns.push( serde_json::from_value(json!({"key": "own_birthdays__last_wished_via", "name": "Wished on", "type": "choice", "choices": ["call", "whatsapp"], "labels": {"call": "A call", "whatsapp": "WhatsApp"}})) .unwrap(), ); let card: CardFace = serde_json::from_value(json!({"face": "birthday", "fields": [ {"slot": "title", "column": "full_name"}, {"slot": "date", "column": "birthday", "form": "weekday_name_date"}, {"slot": "turns", "column": "birthday"}, {"slot": "wished_via", "column": "own_birthdays__last_wished_via"}, {"slot": "phone", "column": "phones"} ], "corner": [{"column": "birthday", "form": "next_occurrence", "within": 366, "line": "corner.birthday"}]})) .unwrap(); card.validate(&table, "card").expect("the birthday card reads the person's columns"); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "p-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let known = read(json!({"full_name": "Invented Asha", "birthday": "1991-10-27", "own_birthdays__last_wished_via": "whatsapp", "phones": ["+91 90000 00001", "+91 90000 00002"]})); assert_eq!(known.fields["date"], json!("Tuesday 27 Oct")); assert_eq!(known.fields["turns"], json!("turns 35")); assert_eq!(known.fields["wished_via"], json!("WhatsApp")); assert_eq!(known.fields["phone"], json!("+91 90000 00001"), "the first number kept"); assert_eq!(known.corner.as_deref(), Some("Birthday in 5 days")); let yearless = read(json!({"full_name": "Invented Ravi", "birthday": "--03-02", "phones": "+91 90000 00003"})); assert_eq!(yearless.fields["turns"], json!("Age not known")); assert_eq!(yearless.fields["date"], json!("Tuesday 2 Mar 2027"), "next year's day says its year"); assert_eq!(yearless.corner.as_deref(), Some("Birthday in 4 months"), "the corner counts down however far off"); assert_eq!(yearless.fields["phone"], json!("+91 90000 00003")); assert!(yearless.fields.get("wished_via").is_none(), "never wished, nothing said"); for bad in [ json!({"slot": "wished_via", "column": "full_name"}), json!({"slot": "phone", "column": "birthday"}), json!({"slot": "album", "column": "full_name"}), ] { let mut wrong = card.clone(); wrong.fields.push(serde_json::from_value(bad.clone()).unwrap()); assert!(wrong.validate(&table, "card").is_err(), "{bad} is refused"); } } // RULE: a finished todo says when it was done in its corner ("Done // yesterday") and no late or coming fact; an open one never says a // done fact. A done fact needs the card's pace, which says finished. #[test] fn a_finished_todo_says_when_it_was_done_and_an_open_one_never_does() { let table = todo(); let card = table.card.clone().unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let yesterday = read(json!({"title": "Pay", "status": "done", "due_at": "2026-10-16", "completed_at": "2026-10-21T18:00:00+05:30"})); assert_eq!((yesterday.corner.as_deref(), yesterday.pressing), (Some("Done yesterday"), false)); let today = read(json!({"title": "Pay", "status": "done", "completed_at": "2026-10-22T08:00:00+05:30"})); assert_eq!(today.corner.as_deref(), Some("Done today")); assert_eq!(read(json!({"title": "Pay", "status": "done"})).corner, None, "no day kept, nothing said"); let open = read(json!({"title": "Pay", "status": "open", "completed_at": "2026-10-21", "due_at": "2026-10-16"})); assert_eq!(open.corner.as_deref(), Some("6 days late"), "an open todo says no done fact"); let mut bare = card.clone(); bare.art = None; bare.pace = None; bare.fields.retain(|field| field.slot != CardSlot::Check); assert!(bare.validate(&table, "card").is_err(), "a done fact without the pace is refused"); } // RULE: a photo card says its day with the year always, whom it is with // and the album it is in, each linked record by the name the caller read. #[test] fn a_photo_card_says_its_year_whom_it_is_with_and_its_album() { for id in ["photo", "media"] { let table = builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone(); let card = table.card.clone().expect("the kit's photo carries a card"); let places: Vec<_> = linked_places(&card, &table).into_iter().map(|(slot, key, linked)| (slot, key.to_string(), linked.to_string())).collect(); assert!(places.contains(&(CardSlot::Album, "albums".into(), "album".into())), "the caller reads the album's name"); let known: std::collections::HashMap = [ ("p-asha", "Invented Asha"), ("a-goa", "Invented Goa trip"), ] .into_iter() .map(|(id, name)| (id.to_string(), CardPerson { name: name.into(), picture: None })) .collect(); let data = json!({"key": "k", "caption": "Beach", "taken_at": "2026-10-03T09:00:00+05:30", "people": ["p-asha"], "albums": ["a-goa"]}); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let said = resolve(&card, &table, "ph-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around { group: None, people: Some(&known), writable: true, thread: None }).unwrap(); assert_eq!(said.fields["date"], json!("Sat 3 Oct 2026 · 9:00 am")); assert_eq!(said.fields["people"][0]["name"], json!("Invented Asha")); assert_eq!(said.fields["album"], json!("Invented Goa trip")); } } // RULE: a secret's card says the username under its own label, when it // was last used and when it runs out — never the secret itself. #[test] fn a_secret_card_says_its_username_last_use_and_expiry_never_its_value() { let table = builtin_table_definitions().iter().find(|table| table.id == "secret").unwrap().clone(); let card = table.card.clone().expect("the kit's secret carries a card"); let data = json!({"name": "Invented bank", "kind": "login", "site": "bank.invented.example", "username": "ada", "last_used_at": "2026-10-20", "expires_at": "2027-01-31"}); let cards = LineSet::shipped("cards").unwrap(); let said = resolve(&card, &table, "s-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(said.fields["body"], json!("ada")); assert_eq!(said.fields["date"], json!("2 days ago")); assert_eq!(said.fields["expires"], json!("Sun 31 Jan 2027")); assert_eq!(said.fields[LABELS], json!({"body": "Username", "date": "Last used", "expires": "Expires"})); assert!(said.fields.values().all(|value| !value.to_string().contains("password"))); } // RULE: a card may label a place in its own words (Money's Future says // its date "Due", its payee "To"), sent under `fields.labels` only where // the place says something; a label that is no `label.` line of the // cards set is refused at save. #[test] fn a_card_labels_its_places_in_its_own_words_and_files_its_tag() { let mut table = serde_json::to_value(todo()).unwrap(); for (key, value) in json!({ "id": "synthetic_transaction", "title": "title", "columns": [{"key": "title", "name": "Title", "type": "text"}, {"key": "description", "name": "Description", "type": "text"}, {"key": "occurred_on", "name": "On", "type": "date"}, {"key": "tag", "name": "Tag", "type": "text"}], "card": {"face": "transaction.receipt", "fields": [ {"slot": "title", "column": "title", "label": "label.money.to"}, {"slot": "subtitle", "column": "description", "label": "label.money.for"}, {"slot": "date", "column": "occurred_on", "label": "label.money.due"}, {"slot": "tag", "column": "tag"} ]} }) .as_object() .unwrap() { table[key] = value.clone(); } let table: TableDefinition = serde_json::from_value(table).expect("a synthetic table"); let card = table.card.clone().unwrap(); card.validate(&table, "card").expect("labels of the cards set"); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"title": "Invented Power Co", "occurred_on": "2026-10-30", "tag": "Bills"}); let said = resolve(&card, &table, "x-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(said.fields[LABELS], json!({"title": "To", "date": "Due"}), "no description, no label for it"); assert_eq!(said.fields["tag"], json!("Bills")); let mut wrong = card.clone(); wrong.fields[0].label = Some("deck.search".into()); assert!(wrong.validate(&table, "card").is_err(), "a label is a label line"); } // RULE: a document's card says what its reading kept in its facts — the // amount in the facts' own currency, the day it expires — its period as // a span, and its file and its pages apart, each under its own label. #[test] fn a_document_card_says_its_amount_expiry_period_file_and_pages_apart() { let table = builtin_table_definitions().iter().find(|table| table.id == "document").unwrap().clone(); let card = table.card.clone().expect("the kit's document carries a card"); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"title": "Invented insurance", "type_line": "PDF", "page_count": 3, "period_start": "2026-04-01", "period_end": "2027-03-31", "facts": "{\"total_minor\": 1250000, \"currency\": \"INR\", \"expires_on\": \"2027-03-31\"}", "created_at": "2026-10-20"}); let said = resolve(&card, &table, "d-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(said.fields["subtitle"], json!("PDF")); assert_eq!(said.fields["count"], json!("3")); assert_eq!(said.fields["amount"], json!("₹12,500")); assert_eq!(said.fields["expires"], json!("Wed 31 Mar 2027")); assert_eq!(said.fields["span"], json!("Wed 1 Apr – Wed 31 Mar 2027")); assert_eq!(said.fields[LABELS], json!({"subtitle": "File", "count": "Pages", "span": "Period", "amount": "Amount"})); let bare = json!({"title": "Invented note", "facts": "{}"}); let bare = resolve(&card, &table, "d-2", bare.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert!(bare.fields.get("amount").is_none() && bare.fields.get("expires").is_none(), "nothing kept, nothing said"); let mut wrong = card.clone(); wrong.fields.push(serde_json::from_value(json!({"slot": "title", "column": "facts", "at": "x"})).unwrap()); wrong.fields.retain(|field| field.slot != CardSlot::Title || field.at.is_some()); assert!(wrong.validate(&table, "card").is_err(), "only amount, expires and holder read a key"); } // RULE: an event's card says when it ends — its clock alone on the day // it starts, its day on another — and how it repeats in words; its // corner counts down to the day ("Today", "Tomorrow", "in 6 days") and // says nothing once it has passed. #[test] fn an_event_card_says_its_end_its_rule_and_counts_down_only_ahead() { let table = builtin_table_definitions().iter().find(|table| table.id == "event").unwrap().clone(); let card = table.card.clone().expect("the kit's event carries a card"); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "e-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let evening = read(json!({"title": "Invented dinner", "starts_at": "2026-10-22T18:30:00+05:30", "ends_at": "2026-10-22T20:00:00+05:30", "rrule": "FREQ=WEEKLY;BYDAY=TH"})); assert_eq!(evening.fields["ends"], json!("8:00 pm")); assert_eq!(evening.corner.as_deref(), Some("Today")); assert!(evening.fields["repeats"].as_str().is_some_and(|said| !said.contains("FREQ")), "{}", evening.fields["repeats"]); let trip = read(json!({"title": "Invented trip", "starts_at": "2026-10-28", "ends_at": "2026-10-31"})); assert_eq!(trip.fields["ends"], json!("Sat 31 Oct")); assert_eq!(trip.corner.as_deref(), Some("in 6 days")); assert!(trip.fields.get("repeats").is_none()); assert_eq!(read(json!({"title": "Invented call", "starts_at": "2026-10-23T09:00:00+05:30"})).corner.as_deref(), Some("Tomorrow")); assert_eq!(read(json!({"title": "Invented gig", "starts_at": "2026-10-20T19:00:00+05:30"})).corner, None, "a day gone says nothing"); assert_eq!(read(json!({"title": "Invented fair", "starts_at": "2026-11-20"})).corner, None, "a week off says nothing yet"); } /// What the app's deck decodes from `@card` (`DeckCard` in /// apps/cotton/Sources/CottonUI/Deck/DeckCard.swift), key by key. fn deck_reads(card: &Value) -> Result<(), String> { let card = card.as_object().ok_or("card")?; for key in card.keys() { if !["face", "corner", "pressing", "pace", "plate", "fields"].contains(&key.as_str()) { return Err(format!("unread:{key}")); } } card.get("face").and_then(Value::as_str).filter(|face| !face.is_empty()).ok_or("face")?; if card.get("corner").is_some_and(|corner| !corner.is_string()) { return Err("corner".into()); } if card.get("pressing").is_some_and(|pressing| !pressing.is_boolean()) { return Err("pressing".into()); } if let Some(pace) = card.get("pace") { let pace = pace.as_str().ok_or("pace")?; if !["late", "soon", "upcoming", "someday", "done"].contains(&pace) { return Err(format!("pace:{pace}")); } } if let Some(plate) = card.get("plate") { plate.as_u64().filter(|plate| *plate < 8).ok_or("plate")?; } let fields = card.get("fields").and_then(Value::as_object).ok_or("fields")?; for (slot, value) in fields { if slot == LABELS { // The places this card labels in its own words: an object // of slot to words, each slot one the card fills (the faces // read `card.fields["labels"][slot]`, TodoCardFace, CassetteFace). let labels = value.as_object().ok_or("labels")?; for (place, label) in labels { if !fields.contains_key(place) { return Err(format!("labels:{place}")); } label.as_str().filter(|label| !label.is_empty()).ok_or_else(|| format!("labels:{place}:words"))?; } continue; } if serde_json::from_value::(Value::String(slot.clone())).is_err() { return Err(format!("slot:{slot}")); } match (slot.as_str(), value) { ("check" | "unread", Value::Bool(_)) => {} ("check" | "unread", _) => return Err(format!("bool:{slot}")), ("used" | "free" | "limit", Value::Number(_)) => {} ("used" | "free" | "limit", _) => return Err(format!("number:{slot}")), (_, Value::String(_)) => {} (slot, _) => return Err(format!("words:{slot}")), } } Ok(()) } // RULE: the `@card` a read attaches is exactly the shape the app's deck // decodes (DeckCard.swift): face, corner, pressing, pace, plate and // fields, each of the type it reads, pace one of the deck's five bands // and every field a slot name holding words (the check and the unread // dot a bool, the gauge's used, free and limit a number), beside // `labels`, the card's own words for its places (slot to words, each // a place the card fills: the todo's "Done" over its check). The deck // drops a card it cannot read, so a new key or a changed type here would // empty the deck; change both sides together. #[test] fn every_shipped_card_resolves_to_the_shape_the_deck_decodes() { let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let faced: Vec<_> = builtin_table_definitions().iter().filter(|table| table.card.is_some()).collect(); assert!(faced.iter().any(|table| table.id == "todo")); let late = json!({"title": "Errand", "notes": "Synthetic", "status": "open", "due_at": "2026-09-10T05:30:00+05:30"}); for table in faced { let card = table.card.as_ref().unwrap(); for data in [json!({}), late.clone()] { let read = resolve(card, table, "0192f3e1-7c2a-7b11-9d4e-58ab12c09f3a", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()) .unwrap_or_else(|| panic!("{}", table.id)); let json = serde_json::to_value(&read).unwrap(); deck_reads(&json).unwrap_or_else(|why| panic!("{}:{why}:{json}", table.id)); } } } #[test] fn money_wears_the_first_matching_face_and_says_its_account_and_balances() { let table = &crate::kit::table("transaction").unwrap(); let mut card = table.card.clone().unwrap(); card.validate(table, "card").unwrap(); let account = &crate::kit::table("money_account").unwrap(); account.card.as_ref().unwrap().validate(account, "card").unwrap(); assert!(linked_places(&card, table).contains(&(CardSlot::Account, "account_id", "money_account"))); let known = [("a-1".to_string(), CardPerson::of(account, json!({"name": "Invented Savings"}).as_object().unwrap(), &Words::shipped().dates))].into(); let cards = LineSet::shipped("cards").unwrap(); let data = |direction: &str| json!({"description": "Invented groceries", "payee_text": "Invented shop", "direction": direction, "tag": "Groceries", "notes": "Invented note", "occurred_on": "2026-10-22", "status": "expected", "amount_minor": 50000, "currency": "INR", "account_id": "a-1", "balance_before_minor": 12450000, "balance_after_minor": 12400000}); let read = |card: &CardFace, data: Value| resolve(card, table, "t-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around { people: Some(&known), ..Around::default() }).unwrap(); assert_eq!(read(&card, data("in")).face, "transaction.cheque"); let out = read(&card, data("out")); assert_eq!(out.face, "transaction.receipt"); assert_eq!(out.fields["title"], "Invented groceries"); assert_eq!(out.fields["subtitle"], "Groceries"); assert_eq!(out.fields["body"], "Invented note"); assert_eq!(out.fields["account"], "Invented Savings"); assert_eq!(out.fields["amount"], "₹500"); assert_eq!(out.fields["date"], "Thu 22 Oct"); assert_eq!(out.fields["state"], "Expected"); assert_eq!(out.corner.as_deref(), Some("Today")); assert_eq!(out.fields["facts"], json!([{"label": "Balance before", "said": "₹1,24,500"}, {"label": "Balance after", "said": "₹1,24,000"}])); let mut actual = data("out"); actual["status"] = json!("actual"); actual["occurred_on"] = json!("2026-10-21"); let actual = read(&card, actual); assert!(actual.fields.get("state").is_none()); assert!(actual.corner.is_none()); card.faces.push(card.faces[0].clone()); card.faces[1].face = card.face; assert_eq!(read(&card, data("in")).face, "transaction.cheque", "the first holding rule wins"); card.faces.clear(); assert_eq!(read(&card, data("in")).face, "transaction.receipt", "no rule uses the default"); assert_eq!(read(&card, json!({})).face, "transaction.receipt", "no matching value uses the default"); let statement = resolve(account.card.as_ref().unwrap(), account, "a-1", json!({"name": "Invented Savings", "institution": "Invented Bank", "number_mask": "•• 4242", "balance_minor": 12450000, "currency": "INR"}).as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(statement.face, "account.statement"); assert_eq!(statement.fields["mask"], "ending 4242"); assert_eq!(statement.fields["amount"], "₹1,24,500"); } // An event's picture is its own photo column: a row that names one // reaches its card with that picture, and a row that names none draws // no picture at all (the face draws one only when the card has one). #[test] fn an_event_with_a_picture_reaches_its_card_with_it() { let tables = builtin_table_definitions(); let table = tables.iter().find(|table| table.id == "event").unwrap().clone(); let card = table.card.clone().expect("the kit's event carries a card"); assert!(card.fields.iter().any(|field| field.slot == CardSlot::Photo && field.column.as_deref() == Some("picture"))); let column = table.column("picture").expect("an event has a picture of its own"); assert_eq!(column.column_type, ColumnType::Photo); assert_ne!(column.readonly, Some(true), "the person gives it"); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let read = |data: serde_json::Value| { resolve(&card, &table, "e-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let pictured = read(json!({"title": "Invented dinner", "starts_at": "2026-10-24T19:30:00+05:30", "picture": "db-1/photos/invented.jpg"})); assert_eq!(pictured.fields["photo"], json!("db-1/photos/invented.jpg")); let plain = read(json!({"title": "Invented dinner", "starts_at": "2026-10-24T19:30:00+05:30"})); assert!(plain.fields.get("photo").is_none(), "no picture, no place for one"); } // An event's card names its guests as the caller read them, once for the // whole answer (a read carries no link expansion): each by name and // picture key, never an id, in the record's own order, at most the // definition's `max`, and the rest said as a count in the cards set's // words. A guest the caller could not read is left out (architect's // ruling on people, 22 Oct 2026). #[test] fn an_event_card_names_its_people_up_to_its_max_and_counts_the_rest() { let tables = builtin_table_definitions(); let table = tables.iter().find(|table| table.id == "event").unwrap().clone(); let person = tables.iter().find(|table| table.id == "person").unwrap().clone(); let mut card = table.card.clone().expect("the kit's event carries a card"); // The kit's board names every guest; this test caps the place at three to prove the max rule. for field in card.fields.iter_mut().filter(|field| field.slot == CardSlot::People) { field.max = Some(3); } assert_eq!(people_place(&card, &table), Some(("people", "person"))); let now = at("2026-10-22T10:00:00+05:30"); let cards = LineSet::shipped("cards").unwrap(); let dates = &Words::shipped().dates; let known: std::collections::HashMap = [ ("p-1", json!({"full_name": "Asha Rao", "avatar_key": "objects/asha"})), ("p-2", json!({"full_name": "Ben Ade"})), ("p-3", json!({"full_name": "Chen Wei", "avatar_key": "objects/chen"})), ("p-4", json!({"full_name": "Dara Ode"})), ("p-5", json!({"full_name": "Esi Mensah"})), ] .into_iter() .map(|(id, data)| (id.to_string(), CardPerson::of(&person, data.as_object().unwrap(), dates))) .collect(); let read = |data: serde_json::Value, people: Option<&std::collections::HashMap>| { let around = Around { group: None, people, writable: true, thread: None }; resolve(&card, &table, "e-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, around).unwrap() }; let event = |people: serde_json::Value| json!({"title": "Dinner", "starts_at": "2026-10-24T19:30:00+05:30", "people": people}); let full = read(event(json!(["p-3", "gone", "p-1", "p-2", "p-4", "p-5"])), Some(&known)); assert_eq!( full.fields["people"], json!([{"name": "Chen Wei", "picture": "objects/chen"}, {"name": "Asha Rao", "picture": "objects/asha"}, {"name": "Ben Ade"}]), "three named in the record's order, a guest not read left out" ); assert_eq!(full.fields[PEOPLE_MORE], json!("+2")); let two = read(event(json!(["p-2", "p-4"])), Some(&known)); assert_eq!(two.fields["people"], json!([{"name": "Ben Ade"}, {"name": "Dara Ode"}])); assert!(two.fields.get(PEOPLE_MORE).is_none(), "nobody more, no count"); assert!(read(event(json!([])), Some(&known)).fields.get("people").is_none(), "nobody names no place"); assert!(read(event(json!(["p-1"])), None).fields.get("people").is_none(), "unread people name no place"); // The place reads a link column, as names alone, and only it names a max. for wrong in [ json!({"slot": "people", "column": "title"}), json!({"slot": "people", "column": "people", "max": 0}), json!({"slot": "people", "column": "people", "line": "field.issuer"}), json!({"slot": "body", "column": "notes", "max": 2}), ] { let mut bad = card.clone(); bad.fields.retain(|field| !matches!(field.slot, CardSlot::People | CardSlot::Body)); bad.fields.push(serde_json::from_value(wrong.clone()).unwrap()); assert!(bad.validate(&table, "card").is_err(), "{wrong} is refused"); } } /// An invented table carrying `card`, its columns as given. fn invented(columns: Value, card: Value) -> TableDefinition { serde_json::from_value(json!({ "id": "invented", "name": "Invented", "plural": "Invented", "picture": null, "builtin": false, "engine": null, "title": "name", "date": null, "project": null, "order": null, "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [], "instructions": "Invented.", "columns": columns, "card": card })) .unwrap() } // The faces past a todo's say what their tools hold (cards row 1, 23 Oct // 2026): a price in its currency for its period, the next charge as a // day, a choice in its label; a gauge's parts as the numbers the face // draws; an account by the linked account's name as the caller read it; // a count, an amount and the unread dot. The invented rows stand for a // subscription, a quota, a machine and a transaction. #[test] fn the_new_faces_say_prices_gauges_accounts_and_the_unread_dot() { let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let read = |table: &TableDefinition, data: Value, around: Around| { let card = table.card.as_ref().unwrap(); card.validate(table, "card").unwrap(); resolve(card, table, "r-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, around).unwrap() }; let subscription = invented( json!([{"key": "name", "type": "text"}, {"key": "amount", "type": "amount", "currency": "currency"}, {"key": "currency", "type": "text"}, {"key": "cycle", "type": "choice", "choices": ["monthly", "yearly"]}, {"key": "next_renewal", "type": "date"}, {"key": "status", "type": "choice", "choices": ["active", "paused"]}]), json!({"face": "subscription", "fields": [{"slot": "title", "column": "name"}, {"slot": "price", "column": "amount"}, {"slot": "period", "column": "cycle"}, {"slot": "next_charge", "column": "next_renewal"}, {"slot": "state", "column": "status", "only": ["paused"]}]}), ); let paid = read(&subscription, json!({"name": "Invented cloud", "amount": 7500, "currency": "INR", "cycle": "monthly", "next_renewal": "2026-11-01", "status": "active"}), Around::default()); assert_eq!(paid.face, "subscription"); assert_eq!(paid.fields["title"], json!("Invented cloud")); assert_eq!(paid.fields["price"], json!("₹75")); assert_eq!(paid.fields["period"], json!("Monthly"), "a choice is said in its label"); assert_eq!(paid.fields["next_charge"], json!("Sun 1 Nov")); assert!(paid.fields.get("state").is_none(), "an active subscription says no state"); let quota = invented( json!([{"key": "name", "type": "text"}, {"key": "week_pct", "type": "number"}, {"key": "resets_line", "type": "text"}]), json!({"face": "quota", "fields": [{"slot": "title", "column": "name"}, {"slot": "used", "column": "week_pct"}, {"slot": "period", "column": "resets_line"}]}), ); let week = read("a, json!({"name": "Invented account", "week_pct": 96, "resets_line": "resets in 2d 23h"}), Around::default()); assert_eq!((week.fields["used"].clone(), week.fields["period"].clone()), (json!(96), json!("resets in 2d 23h"))); assert!(week.fields.get("limit").is_none(), "a gauge with no limit is out of a hundred"); // A reset kept as its instant counts down from the reader's now, and // once passed says so — never the countdown of an old reading (the // walk's "resets in 2h 24m" beside "7 days ago", 23 Oct 2026). let instant = invented( json!([{"key": "name", "type": "text"}, {"key": "week_pct", "type": "number"}, {"key": "week_resets_at", "type": "date", "format": "countdown", "units": {"one": "resets in {n}", "other": "resets in {n}", "zero": "has reset"}}]), json!({"face": "quota", "fields": [{"slot": "title", "column": "name"}, {"slot": "used", "column": "week_pct"}, {"slot": "period", "column": "week_resets_at"}]}), ); let ahead = read(&instant, json!({"name": "Invented account", "week_pct": 40, "week_resets_at": "2026-10-25T03:30:00Z"}), Around::default()); assert_eq!(ahead.fields["period"], json!("resets in 2 d 23 h")); let passed = read(&instant, json!({"name": "Invented account", "week_pct": 96, "week_resets_at": "2026-10-16T06:54:00Z"}), Around::default()); assert_eq!(passed.fields["period"], json!("has reset")); // A reset kept as a bare day (the sampler's, 23 Oct 2026) is over // once the reader's day is past it, and said as its day until then. let day = |held: &str| read(&instant, json!({"name": "Invented account", "week_pct": 96, "week_resets_at": held}), Around::default()).fields["period"].clone(); assert_eq!(day("2026-10-16"), json!("has reset")); assert_eq!(day("2026-10-25"), json!("25 Oct 2026")); let machine = invented( json!([{"key": "name", "type": "text"}, {"key": "disk_free_gb", "type": "number"}, {"key": "disk_total_gb", "type": "number"}]), json!({"face": "machine", "fields": [{"slot": "title", "column": "name"}, {"slot": "free", "column": "disk_free_gb"}, {"slot": "limit", "column": "disk_total_gb"}]}), ); let disk = read(&machine, json!({"name": "invented-mac", "disk_free_gb": 581, "disk_total_gb": "926"}), Around::default()); assert_eq!((disk.fields["free"].clone(), disk.fields["limit"].clone()), (json!(581), json!(926.0))); let account = invented(json!([{"key": "name", "type": "text"}]), json!({"face": "account.statement", "fields": [{"slot": "title", "column": "name"}]})); let transaction = invented( json!([{"key": "name", "type": "text"}, {"key": "amount_minor", "type": "amount", "currency": "currency"}, {"key": "currency", "type": "text"}, {"key": "account_id", "type": "link", "link_to": "money_account"}]), json!({"face": "transaction.receipt", "fields": [{"slot": "title", "column": "name"}, {"slot": "amount", "column": "amount_minor"}, {"slot": "account", "column": "account_id"}]}), ); let known: std::collections::HashMap = [("a-1".to_string(), CardPerson::of(&account, json!({"name": "Invented Bank"}).as_object().unwrap(), &Words::shipped().dates))].into(); let spent = read(&transaction, json!({"name": "Groceries", "amount_minor": 125000, "currency": "INR", "account_id": "a-1"}), Around { group: None, people: Some(&known), writable: true, thread: None }); assert_eq!(spent.fields["amount"], json!("₹1,250")); assert_eq!(spent.fields["account"], json!("Invented Bank"), "the account by its name, never its id"); let unread = read(&transaction, json!({"name": "Groceries", "account_id": "a-1"}), Around::default()); assert!(unread.fields.get("account").is_none(), "an account the caller did not read names no place"); let tables = builtin_table_definitions(); let email = tables.iter().find(|table| table.id == "email_thread").unwrap(); let mail = read(email, json!({"subject": "Invented invoice", "sender": "Invented Ltd", "email_count": 1204, "read_state": "unread", "amount_minor": 49900, "currency": "INR"}), Around::default()); assert_eq!(mail.face, "email"); assert_eq!((mail.fields["count"].clone(), mail.fields["unread"].clone(), mail.fields["amount"].clone()), (json!("1,204"), json!(true), json!("₹499"))); let read_mail = read(email, json!({"subject": "Invented", "read_state": "read"}), Around::default()); assert_eq!(read_mail.fields["unread"], json!(false)); } // RULE: each new place reads the column type it draws, refused at save. #[test] fn the_new_places_read_columns_of_their_type() { let columns = json!([{"key": "name", "type": "text"}, {"key": "n", "type": "number"}, {"key": "sum", "type": "amount"}, {"key": "on", "type": "date"}, {"key": "seen", "type": "bool"}, {"key": "to", "type": "link", "link_to": "money_account"}, {"key": "state", "type": "choice", "choices": ["read", "unread"]}]); let card = |fields: Value| -> CardFace { serde_json::from_value(json!({"face": "machine", "fields": fields})).unwrap() }; let table = invented(columns.clone(), Value::Null); for (fields, why) in [ (json!([{"slot": "used", "column": "name"}]), "a gauge part on text"), (json!([{"slot": "limit", "column": "n", "form": "count"}]), "a gauge part said in words"), (json!([{"slot": "used", "column": "n"}, {"slot": "free", "column": "n"}, {"slot": "limit", "column": "n"}]), "used and free"), (json!([{"slot": "free", "column": "n"}]), "free with no limit"), (json!([{"slot": "price", "column": "n"}]), "a price on a number"), (json!([{"slot": "amount", "column": "name"}]), "an amount on text"), (json!([{"slot": "count", "column": "name"}]), "a count on text"), (json!([{"slot": "next_charge", "column": "name"}]), "a next charge on text"), (json!([{"slot": "account", "column": "name"}]), "an account on text"), (json!([{"slot": "unread", "column": "state"}]), "an unread choice naming no values"), (json!([{"slot": "unread", "column": "state", "only": ["opened"]}]), "an unread value not a choice"), (json!([{"slot": "unread", "column": "seen", "only": ["true"]}]), "a yes/no unread naming values"), (json!([{"slot": "unread", "column": "name"}]), "an unread on text"), (json!([{"slot": "count", "column": "n", "only": ["1"]}]), "only on a count"), ] { assert!(card(fields).validate(&table, "card").is_err(), "{why}"); } card(json!([{"slot": "used", "column": "n"}, {"slot": "limit", "column": "n"}, {"slot": "amount", "column": "sum", "form": "money_signed"}, {"slot": "next_charge", "column": "on"}, {"slot": "account", "column": "to"}, {"slot": "unread", "column": "seen"}, {"slot": "count", "column": "n"}, {"slot": "mask", "column": "name"}, {"slot": "period", "column": "state"}])) .validate(&table, "card") .unwrap(); } // RULE (tolerant reading): a card a newer build wrote reads on this one — // a face it cannot draw reads as no card, so the table keeps its page, // and a place it does not name is left off; the table itself still reads. #[test] fn a_newer_face_or_place_reads_as_no_card_or_no_place() { let columns = json!([{"key": "name", "type": "text"}]); let newer = invented(columns.clone(), json!({"face": "hologram", "fields": [{"slot": "title", "column": "name"}]})); assert_eq!(newer.card, None); let placed = invented(columns, json!({"face": "machine", "fields": [{"slot": "sparkle", "column": "name"}, {"slot": "title", "column": "name"}]})); let card = placed.card.expect("a known face reads"); assert_eq!(card.fields.iter().map(|field| field.slot).collect::>(), vec![CardSlot::Title]); } // A tool view draws its own face over its table's (cards row 6): the // Birthdays view over people says the next birthday, the age it comes // round to (or that it is not known), the wishes switch, yes or no, and // when they were last wished; People // keeps its person card. #[test] fn a_view_draws_its_own_birthday_face_over_the_tables_card() { let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let people = invented( json!([{"key": "name", "type": "text"}, {"key": "birthday", "type": "date", "yearly": true}, {"key": "wish", "type": "bool"}, {"key": "last_wished", "type": "date"}]), json!({"face": "person.rolodex", "fields": [{"slot": "title", "column": "name"}]}), ); let view: crate::definitions::tool_views::ToolView = serde_json::from_value(json!({ "id": "birthdays", "label": "Birthdays", "read": {"table": "invented"}, "card": {"face": "birthday", "fields": [ {"slot": "title", "column": "name"}, {"slot": "date", "column": "birthday"}, {"slot": "turns", "column": "birthday"}, {"slot": "wishes", "column": "wish"}, {"slot": "last_wished", "column": "last_wished"} ]} })) .unwrap(); let drawn = view.over(&people); let card = drawn.card.as_ref().unwrap(); card.validate(&drawn, "card").unwrap(); assert_eq!(people.card.as_ref().unwrap().face, "person.rolodex", "the table keeps its own card"); let read = |data: Value| resolve(card, &drawn, "p-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap(); let known = read(json!({"name": "Invented Asha", "birthday": "1991-11-04", "wish": true, "last_wished": "2025-11-04"})); assert_eq!(known.face, "birthday"); assert_eq!(known.fields["date"], "Wed 4 Nov"); assert_eq!(known.fields["turns"], "turns 35"); assert_eq!(known.fields["wishes"], true); assert!(known.fields["last_wished"].as_str().is_some_and(|said| !said.is_empty())); let yearless = read(json!({"name": "Invented Ravi", "birthday": "--10-25", "wish": false})); assert_eq!(yearless.fields["turns"], "Age not known", "a day kept without its year says its age is not known"); assert_eq!(yearless.fields["wishes"], false); assert!(yearless.fields.get("last_wished").is_none()); } #[test] fn the_birthday_places_read_columns_of_their_type() { let columns = json!([{"key": "name", "type": "text"}, {"key": "birthday", "type": "date", "yearly": true}, {"key": "met", "type": "date"}, {"key": "wish", "type": "bool"}]); let refused = |field: Value| { let table = invented(columns.clone(), json!({"face": "birthday", "fields": [field]})); table.card.as_ref().unwrap().validate(&table, "card").is_err() }; assert!(refused(json!({"slot": "turns", "column": "met"})), "turns needs a yearly date"); assert!(refused(json!({"slot": "turns", "column": "birthday", "form": "turns"}))); assert!(refused(json!({"slot": "wishes", "column": "name"}))); assert!(refused(json!({"slot": "last_wished", "column": "wish"}))); assert!(!refused(json!({"slot": "last_wished", "column": "met"}))); } #[test] fn a_view_whose_face_is_newer_than_this_build_keeps_the_tables_card() { let view: crate::definitions::tool_views::ToolView = serde_json::from_value(json!({ "id": "later", "label": "Later", "read": {"table": "invented"}, "card": {"face": "hologram", "fields": []} })) .unwrap(); assert!(view.card.is_none()); } // Cards row 9: an album says the days it spans and how many it holds; an // undated todo asks for a date ("Add date"), and a timed one says its day // and its hour together. #[test] fn an_album_spans_its_days_and_an_undated_card_asks_for_a_date() { let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let album = crate::definitions::builtin_table_definition("album").unwrap(); let card = album.card.as_ref().unwrap(); card.validate(album, "card").unwrap(); let read = |table: &TableDefinition, data: Value| { resolve(table.card.as_ref().unwrap(), table, "r-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let trip = read(album, json!({"title": "Invented hills", "member_count": 1204, "starts_at": "2026-10-03", "ends_at": "2026-10-09"})); assert_eq!(trip.face, "album.carousel"); assert_eq!(trip.fields["span"], "Sat 3 Oct – Fri 9 Oct"); assert_eq!(trip.fields["count"], "1,204"); let day = read(album, json!({"title": "Invented picnic", "starts_at": "2026-10-03", "ends_at": "2026-10-03"})); assert_eq!(day.fields["span"], "Sat 3 Oct"); let todo = todo(); let undated = read(&todo, json!({"title": "Invented errand", "status": "open"})); assert_eq!(undated.fields["date"], "Add date"); let timed = read(&todo, json!({"title": "Invented call", "status": "open", "due_at": "2026-10-24T09:30:00.000Z"})); assert_eq!(timed.fields["date"], "Sat 24 Oct · 3:00 pm"); } // A diary page's seal and weather say their choice's stored value, which // the face draws by, and its star is a switch; no mood leaves the seal // out, so the face presses none. #[test] fn a_diary_page_says_its_seal_weather_and_star_by_value() { let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-11-12T21:00:00+05:30"); let entry = crate::kit::table("journal_entry").unwrap(); let card = entry.card.as_ref().unwrap(); card.validate(&entry, "card").unwrap(); let read = |data: Value| { resolve(card, &entry, "r-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let page = read(json!({"day": "2026-11-12", "title": "Invented evening", "mood": "great", "weather": "rain", "place": "Invented hill", "starred": true})); assert_eq!(page.face, "journal.diary"); assert_eq!(page.fields["seal"], "great"); assert_eq!(page.fields["weather"], "rain"); assert_eq!(page.fields["place"], "Invented hill"); assert_eq!(page.fields["star"], true); let bare = read(json!({"day": "2026-11-12", "starred": false})); assert!(bare.fields.get("seal").is_none() && bare.fields.get("weather").is_none()); assert_eq!(bare.fields["star"], false); } #[test] fn linked_account_keeps_its_mask_on_the_receipt() { let account = crate::kit::table("money_account").unwrap(); let data = json!({"name":"Synthetic savings", "number_mask":"XXXX1234"}); let linked = CardPerson::of(&account, data.as_object().unwrap(), &Words::shipped().dates); assert_eq!(linked.name, "Synthetic savings · XXXX1234"); } #[test] fn statement_rows_carry_only_this_months_postings_and_stored_balances() { let rows = [ ("old", json!({"occurred_on":"2026-09-30","status":"actual","direction":"out","amount_minor":10000})), ("debit", json!({"occurred_on":"2026-10-04","description":"Sample groceries","status":"actual","direction":"out","amount_minor":190800,"currency":"INR","balance_after_minor":6775300})), ("credit", json!({"occurred_on":"2026-10-05","description":"Sample refund","status":"actual","direction":"in","amount_minor":10000,"currency":"INR","balance_after_minor":6785300})), ("future", json!({"occurred_on":"2026-10-06","status":"expected","direction":"out","amount_minor":20000})), ].into_iter().map(|(id, data)| (id.to_string(), data.as_object().unwrap().clone())).collect::>(); let said = statement_rows(&rows, "Asia/Kolkata", at("2026-10-31T10:00:00+05:30"), Words::shipped()); assert_eq!(said.len(), 2); assert_eq!(said[0]["narration"], "Sample groceries"); assert_eq!(said[0]["debit"], "₹1,908"); assert!(said[0]["credit"].is_null()); assert_eq!(said[0]["balance"], "₹67,753"); assert_eq!(said[1]["credit"], "₹100"); let mut unknown = rows[1].clone(); unknown.1.insert("amount_known".into(), Value::Bool(false)); let unknown = statement_rows(&[unknown], "Asia/Kolkata", at("2026-10-31T10:00:00+05:30"), Words::shipped()); assert!(unknown[0]["debit"].is_null(), "an unknown amount never becomes a zero debit"); } /// RULE (coordinator, 6 Nov 2026): a statement card is titled by its /// bank or card and its period; a title over a link says the linked /// record's name, as read. #[test] fn a_statement_card_is_titled_by_its_account_and_period() { let tool: Value = serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join("kits/personal/tools/money/manifest.json")).unwrap()).unwrap(); let view = tool["views"].as_array().unwrap().iter().find(|view| view["id"] == "statements").unwrap(); let card: CardFace = serde_json::from_value(view["card"].clone()).unwrap(); let statement = crate::kit::table("statement").unwrap(); let account = crate::kit::table("money_account").unwrap(); let mut people = std::collections::HashMap::new(); people.insert("a-card".to_string(), CardPerson::of(&account, json!({"name": "Larkspur Card"}).as_object().unwrap(), &Words::shipped().dates)); assert!(linked_places(&card, &statement).contains(&(CardSlot::Title, "account_id", "money_account")), "the title's account is read for it"); let data = json!({"account_id": "a-card", "kind": "credit_card", "period_start": "2026-10-07", "period_end": "2026-11-05", "currency": "INR"}); let around = Around { people: Some(&people), ..Around::default() }; let read = resolve(&card, &statement, "s-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-11-06T10:00:00+05:30"), Words::shipped(), &LineSet::shipped("cards").unwrap(), around).unwrap(); assert_eq!(read.fields["title"], "Larkspur Card, 7 Oct 2026 – 5 Nov 2026"); } #[test] fn device_card_keeps_platform_without_repeating_kind() { let table = crate::definitions::builtin_table_definition("device").unwrap(); let read = resolve(table.card.as_ref().unwrap(), table, "synthetic-phone", json!({"name": "Sample phone", "kind": "iPhone", "platform": "ios"}).as_object().unwrap(), "Asia/Kolkata", at("2026-10-31T10:00:00+05:30"), Words::shipped(), &LineSet::shipped("cards").unwrap(), Around::default()).unwrap(); assert_eq!(read.fields["facts"], json!([{"label": "Platform", "said": "iPhone"}])); } #[test] fn every_shipped_table_opens_on_a_card_and_a_plain_one_says_its_facts_under_their_labels() { let bare: Vec<&str> = builtin_table_definitions().iter().filter(|table| table.card.is_none()).map(|table| table.id.as_str()).collect(); assert_eq!(bare, Vec::<&str>::new(), "a table with no card opens the old record page"); for table in builtin_table_definitions() { table.card.as_ref().unwrap().validate(table, "card").unwrap_or_else(|error| panic!("{}: {error}", table.id)); } let cards = LineSet::shipped("cards").unwrap(); let backup = crate::definitions::builtin_table_definition("backup").unwrap(); let card = backup.card.as_ref().unwrap(); assert_eq!(card.face, "plain"); let data = json!({"state": "stale", "kept": 4}); let read = resolve(card, backup, "b-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-10-22T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(read.fields["title"], json!("No recent copy")); assert_eq!(read.fields["facts"], json!([{"label": "Copies kept", "said": "4"}]), "a fact with no value is left out"); let mut linked = card.clone(); let thread_member = crate::definitions::builtin_table_definition("thread_member").unwrap(); linked.fields = vec![CardField { slot: CardSlot::Facts, column: Some("person_id".into()), only: vec![], form: None, also: vec![], line: None, max: None, label: None, at: None, chooses: None, markdown: false }]; assert!(linked.validate(thread_member, "card").is_err(), "a link is never a fact"); } // RULE: a group deck deals one card per record its people place names, // in the order the list first reaches each, saying that record's name // and picture, the figures the table's group says for it, and its // latest three lines; a table whose group is by another column says no // figures, and rows naming no one stand under "No one". #[test] fn a_group_deck_deals_one_card_per_person_with_the_net_and_the_latest_lines() { let mut table = serde_json::to_value(todo()).unwrap(); let made = json!({ "id": "synthetic_owed", "title": "description", "columns": [ {"key": "description", "name": "What", "type": "text"}, {"key": "occurred_on", "name": "Date", "type": "date"}, {"key": "amount_minor", "name": "Amount", "type": "amount", "currency": "currency"}, {"key": "owed_signed", "name": "Signed", "type": "amount", "currency": "currency"}, {"key": "currency", "type": "text"}, {"key": "counterparty_person_id", "name": "Person", "type": "link", "link_to": "person"} ], "group": {"column": "counterparty_person_id", "summary": [{"op": "sum", "column": "owed_signed", "label": "between you"}]}, "card": {"face": "group", "fields": [ {"slot": "people", "column": "counterparty_person_id"}, {"slot": "title", "column": "description"}, {"slot": "amount", "column": "amount_minor"}, {"slot": "date", "column": "occurred_on"} ]} }); for (key, value) in made.as_object().unwrap() { table[key] = value.clone(); } table.as_object_mut().unwrap().remove("upcoming"); let table: TableDefinition = serde_json::from_value(table).expect("a synthetic table"); let card = table.card.clone().unwrap(); card.validate(&table, "card").expect("the group card validates"); let cards = LineSet::shipped("cards").unwrap(); let now = at("2026-10-22T10:00:00+05:30"); let row = |id: &str, what: &str, day: &str, amount: i64, signed: i64, person: Option<&str>| { let mut data = json!({"description": what, "occurred_on": day, "amount_minor": amount, "owed_signed": signed, "currency": "INR"}); if let Some(person) = person { data["counterparty_person_id"] = json!(person); } (id.to_string(), data.as_object().unwrap().clone()) }; // Newest first, as the view reads. let rows = vec![ row("t-1", "Invented dinner", "2026-10-20", 60000, 60000, Some("p-asha")), row("t-2", "Invented cab", "2026-10-18", 20000, -20000, Some("p-ravi")), row("t-3", "Invented tickets", "2026-10-15", 150000, 150000, Some("p-asha")), row("t-4", "Invented lunch", "2026-10-12", 40000, -40000, Some("p-asha")), row("t-5", "Invented books", "2026-10-02", 10000, 10000, Some("p-asha")), row("t-6", "Invented tip", "2026-10-01", 5000, 5000, None), ]; let mut people = std::collections::HashMap::new(); people.insert("p-asha".to_string(), CardPerson { name: "Invented Asha".into(), picture: Some("photo:asha".into()) }); people.insert("p-ravi".to_string(), CardPerson { name: "Invented Ravi".into(), picture: None }); let dealt = deal_groups(&card, &table, &rows, &people, "Asia/Kolkata", now, Words::shipped(), &cards); let order: Vec<(&str, usize)> = dealt.iter().map(|group| (group.value.as_str(), group.count)).collect(); assert_eq!(order, vec![("p-asha", 4), ("p-ravi", 1), ("", 1)]); let asha = &dealt[0].card; assert_eq!(asha.face, FaceId::GROUP); assert_eq!(asha.fields["title"], json!("Invented Asha")); assert_eq!(asha.fields["photo"], json!("photo:asha")); assert_eq!(asha.fields["net"], json!(["₹1,800 between you"])); let lines = asha.fields["lines"].as_array().unwrap(); assert_eq!(lines.len(), GROUP_LINES); assert_eq!(lines[0]["title"], json!("Invented dinner")); assert_eq!(lines[0]["amount"], json!("₹600")); assert_eq!(lines[0]["date"], json!("Tue 20 Oct")); assert_eq!(lines[2]["title"], json!("Invented lunch")); assert!(lines[0].get("people").is_none(), "a line never says the group's own person"); assert_eq!(asha.fields["more"], json!("+1")); let ravi = &dealt[1].card; assert_eq!(ravi.fields["net"], json!(["−₹200 between you"])); assert!(ravi.fields.get("photo").is_none() && ravi.fields.get("more").is_none()); assert_eq!(dealt[2].card.fields["title"], json!("No one")); // A group by another column says no figures. let mut other = table.clone(); other.group.as_mut().unwrap().column = "description".into(); let quiet = deal_groups(&card, &other, &rows, &people, "Asia/Kolkata", now, Words::shipped(), &cards); assert!(quiet.iter().all(|group| group.card.fields.get("net").is_none())); // A group card names its people place. let mut bare = card.clone(); bare.fields.retain(|field| field.slot != CardSlot::People); assert!(bare.validate(&table, "card").is_err()); } /// RULE (the Pages walk, 13 Nov 2026: "26.0 min read"): a kept page's /// clipping says its reading time in whole minutes, and the starred flag /// stands beside its state. #[test] fn a_kept_pages_clipping_says_its_minutes_whole() { let table = &crate::kit::table("page").unwrap(); let card = table.card.clone().unwrap(); card.validate(table, "card").unwrap(); let cards = LineSet::shipped("cards").unwrap(); let data = json!({"title": "An invented harbour", "url": "https://gazette.example/a", "host": "gazette.example", "state": "unread", "own_pages__minutes": 26, "own_pages__byline": "A. Writer"}); let read = resolve(&card, table, "p-1", data.as_object().unwrap(), "Asia/Kolkata", at("2026-11-13T10:00:00+05:30"), Words::shipped(), &cards, Around::default()).unwrap(); assert_eq!(read.face, "page.clipping"); assert_eq!(read.fields["length"], "26 min read"); } }