//! A BUSINESS'S OBJECT ON THE PHONE.//!//! A business app (Sharmila's Yoga Zone, Nancy's Naga Kitchen) runs against//! one Cloudflare Worker object (`apps/business`): the object holds the rows//! and decides everything — who may read what, what an act does — and the//! phone keeps a local cache of what it may see, filled by snapshot sync from//! a version cursor, and posts every write to the object. The phone decides//! nothing about the data; it renders.//!//! The cache is one SQLite file per business beside the app's data//! (`business/<slug>/cache.db`): the served definitions verbatim, the rows//! (table, id, data, owner, version, deleted), and the cursor. The role the//! credential holds is kept with it, because what the cache holds is what that//! role may see: a sign-in or a sign-out empties it and starts the cursor over.//!//! What a page draws comes from the cache through the core's own renderers —//! the table's card (`records::card`), the slip's title and line — over//! records whose computed columns (lookups, rollups, formulas) are worked out//! here from the cached rows, as the object does for its decisions. A view's//! `read` (table, where, period) and `sort` are read as the owner's deck reads//! them.//!//! **The credential crosses this boundary once, inward.** `business.signIn`//! hands it to Swift, which puts it in the Keychain; every later call takes//! it back as an argument and puts it on one header. Nothing here keeps it,//! logs it, or says it in a refusal.use std::collections::{HashMap, HashSet};use std::path::PathBuf;use cotton_client::transport::object::{bearer, routes, ObjectAddress, ObjectRefusal};use cotton_client::transport::{Exchange, SocketExchange};use cotton_core::definitions::computed::{Computed, RollupOp};use cotton_core::definitions::{TableDefinition, ToolDefinition};use rusqlite::{params, Connection, OptionalExtension};use serde_json::{json, Map, Value};usecrate::handle::CottonHandle;usecrate::methods::MethodError;/// How deep a chain of lookups runs before it is cut.const MAX_RESOLVE_DEPTH: usize = 12;/// The methods this module answers.pubconst METHODS: &[&str] = &["business.sync","business.pages","business.code","business.signIn","business.signOut","business.act",];/// `business.*`: every request names the Worker's `server` and the business's/// `slug`; a signed-in call carries `credential`; a reading call may carry/// `zone`.pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { call_with(handle, method, request, &SocketExchange)}pubfn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: &dynExchange) -> Result<Value, MethodError> {let (object, cache) = opened(handle, request)?;let credential = request.get("credential").and_then(Value::as_str).map(str::trim).filter(|c| !c.is_empty());let zone = request.get("zone").and_then(Value::as_str).filter(|z| !z.is_empty());match method {"business.sync" => object.sync(exchange, &cache, credential),"business.pages" => object.pages(&cache, zone),"business.code" => object.code(exchange, text(request, "phone")?, &device_id(handle)?),"business.signIn" => object.sign_in( exchange, &cache, text(request, "challengeId")?, text(request, "code")?, request.get("name").and_then(Value::as_str), request.get("nameAfter").and_then(Value::as_bool) == Some(true), &device_id(handle)?, ),"business.signOut" => object.sign_out(exchange, &cache, credential),"business.act" => object.act( exchange, &cache, credential, text(request, "act")?, request.get("args").and_then(Value::as_object).cloned().unwrap_or_default(), zone, ), other => Err(MethodError::new("unknown_method", format!("{other} is not a business method"))), }}/// The object `address` names (`{server, slug}`), and this phone's cache of it.pub(crate) fn opened(handle: &CottonHandle, address: &Value) -> Result<(Object, Cache), MethodError> {let object = Object::named(text(address, "server")?, text(address, "slug")?)?;let cache = Cache::open(handle.data_dir().join("business").join(object.address.slug()).join("cache.db"))?;Ok((object, cache))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { request .get(field) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .ok_or_else(|| MethodError::new("bad_request", format!("`{field}` is missing")))}fn device_id(handle: &CottonHandle) -> Result<String, MethodError> { handle .client() .self_device_id() .ok_or_else(|| MethodError::new("device_key_unreadable", "this device has no device identity"))}// ── the object over HTTP ───────────────────────────────────────────────────/// One business's object: where it answers (`ObjectAddress`, the Worker's own/// host rule) and what the phone asks of it.#[derive(Debug)]pubstructObject {pub address: ObjectAddress,}implFrom<ObjectRefusal> forMethodError {fn from(refusal: ObjectRefusal) -> MethodError {// A 5xx or 429 that carried no word of its own (a gateway's page, not// the object's JSON) is said as the object not answering, never as a// refusal a person could act on.if refusal.transient() && refusal.code == "refused" {returnMethodError::new(cotton_client::transport::object::UNANSWERED, format!("{}, status {}", refusal.message, refusal.status)); }MethodError::new(&refusal.code, refusal.message) }}implObject {pubfn named(server: &str, slug: &str) -> Result<Object, MethodError> {ObjectAddress::named(server, slug).map(|address| Object { address }).map_err(|reason| MethodError::new("bad_request", reason)) }/// Where a photo key is fetched from: the base the phone puts the key after.fn photos(&self) -> String {self.address.url(routes::PHOTOS) }fn send(&self, exchange: &dynExchange, method: &str, path: &str, headers: Vec<(String, String)>, body: Option<Value>) -> Result<Value, MethodError> {Ok(self.address.send(exchange, method, path, headers, body.as_ref())?) }// ── sync ───────────────────────────────────────────────────────────/// Pull the definitions when they changed and every row changed since the/// cursor, as the credential's role may see them. Answers the version, the/// role, and the signed-in person.pubfn sync(&self, exchange: &dynExchange, cache: &Cache, credential: Option<&str>) -> Result<Value, MethodError> {letmut headers = Vec::new();ifletSome(etag) = cache.meta("etag") { headers.push(("If-None-Match".into(), format!("\"{etag}\""))); }let definitions = self.send(exchange, "GET", routes::DEFINITIONS, headers, None)?;if definitions["unchanged"] != json!(true) {let etag = definitions["etag"].as_str().unwrap_or_default().to_string(); cache.replace_definitions(&definitions, &etag)?; }let me = match credential {Some(credential) => {let me = self.send(exchange, "GET", routes::ME, bearer(credential), None)?;Some(me["person"].clone()) }None => None, };let role = me.as_ref().and_then(|p| p["role"].as_str()).unwrap_or("public").to_string();if cache.meta("role").as_deref() != Some(role.as_str()) {// What the cache holds is what one role may see: a role change starts over. cache.wipe_rows()?; cache.set_meta("role", Some(&role))?; } cache.set_meta("person", me.as_ref().map(|p| p.to_string()).as_deref())?;let since = cache.meta("cursor").and_then(|c| c.parse::<i64>().ok()).unwrap_or(0);let headers = credential.map(bearer).unwrap_or_default();// Page by page until an answer carries no `next`: each page lands in its own// transaction, and the cursor holds the new version only once the last has.letmut path = format!("{}?since={since}", routes::SYNC);letmut changed = 0;let version = loop {let answer = self.send(exchange, "GET", &path, headers.clone(), None)?;let rows = answer["rows"].as_array().cloned().unwrap_or_default();let version = answer["version"].as_i64().unwrap_or(since); cache.apply(&rows, version)?; changed += rows.len();match answer["next"].as_str() {Some(next) => path = format!("{}?cursor={next}", routes::SYNC),None => break version, } };Ok(json!({"version": version,"changed": changed,"role": role,"person": me,"business": cache.definitions().map(|d| d["business"].clone()).unwrap_or(Value::Null), })) }// ── sign-in ────────────────────────────────────────────────────────pubfn code(&self, exchange: &dynExchange, phone: &str, device_id: &str) -> Result<Value, MethodError> {let answer = self.send(exchange, "POST", routes::CODE, Vec::new(), Some(json!({"phone": phone, "device_id": device_id})))?;let challenge = answer["challenge_id"].as_str().ok_or_else(|| MethodError::new("refused", "the object sent no challenge"))?;letmut said = json!({"challengeId": challenge, "expiresIn": answer["expires_in"], "sentTo": crate::phone::personal_object::sent_to(phone)});// Whether the object knows the number: a new person is asked their name with the code.ifletSome(known) = answer["known"].as_bool() { said["known"] = json!(known); }Ok(said) }/// With `name_after` and no name, a number the object has no person for answers `{nameNeeded: true}` once its code/// is proved; the card then sends the same code with the name (`personal_object::sign_in`).pubfn sign_in(&self, exchange: &dynExchange, cache: &Cache, challenge: &str, code: &str, name: Option<&str>, name_after: bool, device_id: &str) -> Result<Value, MethodError> {letmut body = json!({"challenge_id": challenge, "code": code, "device_id": device_id});ifletSome(name) = name.map(str::trim).filter(|n| !n.is_empty()) { body["name"] = json!(name); }if name_after { body["name_after"] = json!(true); }let answer = self.send(exchange, "POST", routes::SIGN_IN, Vec::new(), Some(body))?;if answer["name_needed"].as_bool() == Some(true) {returnOk(json!({"nameNeeded": true})); }let credential = answer["credential"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| MethodError::new("refused", "the object granted no credential"))?;let person = answer["person"].clone();// A new role sees other rows: the cache starts over for it. cache.wipe_rows()?; cache.set_meta("role", person["role"].as_str())?; cache.set_meta("person", Some(&person.to_string()))?;Ok(json!({"credential": credential, "person": person, "expiresIn": answer["expires_in"]})) }pubfn sign_out(&self, exchange: &dynExchange, cache: &Cache, credential: Option<&str>) -> Result<Value, MethodError> {ifletSome(credential) = credential {// A credential the object no longer knows is already out.matchself.send(exchange, "POST", routes::SIGN_OUT, bearer(credential), None) {Ok(_) => {}Err(refusal) if refusal.code == "credential_revoked" || refusal.code == "not_signed_in" => {}Err(refusal) => returnErr(refusal), } } cache.wipe_rows()?; cache.set_meta("role", Some("public"))?; cache.set_meta("person", None)?;Ok(json!({"ok": true})) }// ── acts ───────────────────────────────────────────────────────────/// Post one act to the object and take its answer into the cache: every/// row it changed, at the version it made.pubfn act(&self, exchange: &dynExchange, cache: &Cache, credential: Option<&str>, act: &str, args: Map<String, Value>, zone: Option<&str>) -> Result<Value, MethodError> {let headers = credential.map(bearer).unwrap_or_default();letmut args = args;if act == "record_act" {// The phone answers each pick under its argument (`data.amount`); the object takes them in the act's order.ifletOk(defs) = Definitions::read(cache) { picked_in_order(&defs, &mut args); } }let answer = self.send(exchange, "POST", routes::ACT, headers, Some(json!({"act": act, "args": args})))?;let rows = answer["changed"].as_array().cloned().unwrap_or_default();let version = answer["version"].as_i64().unwrap_or(0); cache.apply(&rows, version)?;let defs = Definitions::read(cache)?;let role = cache.meta("role").unwrap_or_else(|| "public".into());let person = cache.person();let now = chrono::Utc::now();let zone = zone.unwrap_or(&defs.zone);let resolver = Resolver::new(&defs, cache);let lines = Lines::shipped();let changed: Vec<Value> = rows .iter() .filter_map(|row| {let table = row["table"].as_str()?;let id = row["id"].as_str()?;if row["deleted"] == json!(true) {returnSome(json!({"table": table, "id": id, "deleted": true})); }let definition = defs.table(table)?;let data = row["data"].as_object()?;let resolved = resolver.resolve(definition, id, data);letmut drawn = drawn_record(&resolver, definition, id, &resolved, zone, now, &lines, writes(&role, definition)); drawn["owner"] = row["owner"].clone(); drawn["acts"] = json!(acts_on(&defs, definition, id, &resolved, &role, person.as_ref(), row["owner"].as_str()));Some(drawn) }) .collect();Ok(json!({"version": version,"changed": changed,"made": answer["made"],"notices": answer["notices"], })) }// ── pages ──────────────────────────────────────────────────────────/// Every tool's views the cached role may read, each with its rows drawn/// from the cache: the whole of what the phone shows.pubfn pages(&self, cache: &Cache, zone: Option<&str>) -> Result<Value, MethodError> {let defs = Definitions::read(cache)?;let role = cache.meta("role").unwrap_or_else(|| "public".into());let person = cache.person();let now = chrono::Utc::now();let zone = zone.unwrap_or(&defs.zone);let today = cotton_core::transforms::zoned_clock::local_day(now.timestamp_millis(), zone) .map_err(|_| MethodError::new("bad_request", format!("{zone} is not a time zone")))?;let resolver = Resolver::new(&defs, cache);let lines = Lines::shipped();let where_day = cotton_core::records::Zone::at(cotton_core::records::where_zone(Some(zone)).tz, now);letmut tools = Vec::new();for tool in &defs.tools {letmut views = Vec::new();for view in &tool.views {if !reads(&role, &view.visibility) {continue; }letSome(table) = view.read.get("table").and_then(Value::as_str) else { continue };letSome(definition) = defs.table(table) else { continue };let clauses = cotton_core::records::parse_where(definition, view.read.get("where")).unwrap_or_default();let period = view.read.get("period").and_then(Value::as_str);letmut records: Vec<(String, Option<String>, Map<String, Value>)> = cache .rows(table)? .into_iter() .map(|(id, owner, data)| {let resolved = resolver.resolve(definition, &id, &data); (id, owner, resolved) }) .filter(|(_, _, data)| clauses.iter().all(|clause| cotton_core::records::holds(data, clause, &where_day))) .collect();ifletSome(period) = period { records = in_period(records, definition, period, today); }let sort = view.sort.as_ref().or(definition.sort.as_ref());ifletSome(sort) = sort { records.sort_by(|a, b| compare(&a.2, &b.2, sort)); }let rows: Vec<Value> = records .iter() .map(|(id, owner, data)| {letmut drawn = drawn_record(&resolver, definition, id, data, zone, now, &lines, writes(&role, definition)); drawn["owner"] = json!(owner); drawn["acts"] = json!(acts_on(&defs, definition, id, data, &role, person.as_ref(), owner.as_deref())); drawn }) .collect();// A next-day view is a day's: the phone says which.let day = (period == Some("next_day")).then(|| definition.date.as_deref().and_then(|date| records.first().and_then(|r| r.2.get(date)).and_then(Value::as_str).map(|d| d.get(0..10).unwrap_or(d).to_string()))).flatten(); views.push(json!({"id": view.id,"label": view.label,"visibility": view.visibility,"is_default": view.is_default,"face": view.face,"table": table,"day": day,"count": rows.len(),"rows": rows, })); }if views.is_empty() {continue; } tools.push(json!({"tool": tool.id,"name": tool.name,"picture": tool.picture,"card_stock": tool.card_stock,"views": views, })); }Ok(json!({"business": defs.business,"role": role,"person": person,"version": cache.meta("cursor").and_then(|c| c.parse::<i64>().ok()).unwrap_or(0),"photos": self.photos(),"tools": tools, })) }}/// Turn a record act's pick answers, keyed by argument (`data.amount` nested/// as `{"data": {"amount": …}}`), into the object's `picked` list in the/// act's own order, taking them out of the data they were keyed under.fn picked_in_order(defs: &Definitions, args: &mutMap<String, Value>) {if args.contains_key("picked") {return; }let (Some(table), Some(act)) = (args.get("table").and_then(Value::as_str), args.get("act").and_then(Value::as_str)) else { return };letSome(definition) = defs.table(table) else { return };letSome(act) = definition.acts.iter().flatten().find(|a| a.id == act) else { return };let picks = act.ordered_picks();if picks.is_empty() {return; }letmut picked = Vec::new();for pick in picks { picked.push(take_path(args, &pick.argument).unwrap_or(Value::Null)); } args.insert("picked".into(), Value::Array(picked));}/// Remove and answer the value at a dotted path (`data.amount`), nested or flat.fn take_path(args: &mutMap<String, Value>, path: &str) -> Option<Value> {ifletSome(flat) = args.remove(path) {returnSome(flat); }letmut keys = path.split('.').collect::<Vec<_>>();let last = keys.pop()?;letmut at = args;for key in keys { at = at.get_mut(key)?.as_object_mut()?; } at.remove(last)}/// Whether a role reads a view of this visibility: `public` everyone,/// `customer` a signed-in member and up, `staff` staff and the owner,/// `owner` the owner.fn reads(role: &str, visibility: &str) -> bool {let rank = |role: &str| match role {"owner" => 3,"staff" => 2,"member" => 1, _ => 0, };let floor = match visibility {"public" => 0,"customer" => 1,"staff" => 2, _ => 3, }; rank(role) >= floor}// ── the cache ──────────────────────────────────────────────────────────────const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS definitions (id INTEGER PRIMARY KEY CHECK (id = 1), json TEXT NOT NULL, etag TEXT NOT NULL);CREATE TABLE IF NOT EXISTS rows ( table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, owner TEXT, version INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (table_id, id));CREATE INDEX IF NOT EXISTS rows_table ON rows (table_id, deleted);";/// One business's cache: what this phone may see of the object, as of a cursor.pubstructCache { db: Connection,}implCache {pubfn open(path: PathBuf) -> Result<Cache, MethodError> {ifletSome(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|error| MethodError::new("io", format!("the business cache's folder could not be made ({error})")))?; }let db = Connection::open(&path).map_err(|error| MethodError::new("io", format!("the business cache could not be opened ({error})")))?; db.execute_batch(SCHEMA).map_err(sql)?;Ok(Cache { db }) }pubfn in_memory() -> Result<Cache, MethodError> {let db = Connection::open_in_memory().map_err(sql)?; db.execute_batch(SCHEMA).map_err(sql)?;Ok(Cache { db }) }pubfn meta(&self, key: &str) -> Option<String> {self.db.query_row("SELECT value FROM meta WHERE key = ?1", params![key], |row| row.get::<_, String>(0)).optional().ok().flatten() }pubfn set_meta(&self, key: &str, value: Option<&str>) -> Result<(), MethodError> {match value {Some(value) => self.db.execute("INSERT INTO meta (key, value) VALUES (?1, ?2) ON CONFLICT (key) DO UPDATE SET value = excluded.value", params![key, value]),None => self.db.execute("DELETE FROM meta WHERE key = ?1", params![key]), } .map(|_| ()) .map_err(sql) }fn person(&self) -> Option<Value> {self.meta("person").and_then(|p| serde_json::from_str(&p).ok()).filter(|p: &Value| p.is_object()) }pubfn replace_definitions(&self, answer: &Value, etag: &str) -> Result<(), MethodError> {self.db .execute("INSERT INTO definitions (id, json, etag) VALUES (1, ?1, ?2) ON CONFLICT (id) DO UPDATE SET json = excluded.json, etag = excluded.etag", params![answer.to_string(), etag]) .map_err(sql)?;self.set_meta("etag", Some(etag)) }pubfn definitions(&self) -> Option<Value> {self.db .query_row("SELECT json FROM definitions WHERE id = 1", [], |row| row.get::<_, String>(0)) .optional() .ok() .flatten() .and_then(|text| serde_json::from_str(&text).ok()) }/// Take synced rows in: a live row replaces its earlier self, a tombstone/// removes it; then the cursor moves.pubfn apply(&self, rows: &[Value], version: i64) -> Result<(), MethodError> {let tx = self.db.unchecked_transaction().map_err(sql)?;for row in rows {let (Some(table), Some(id)) = (row["table"].as_str(), row["id"].as_str()) else { continue };if row["deleted"] == json!(true) { tx.execute("DELETE FROM rows WHERE table_id = ?1 AND id = ?2", params![table, id]).map_err(sql)?;continue; }let data = row.get("data").filter(|d| d.is_object()).map(Value::to_string).unwrap_or_else(|| "{}".into()); tx.execute("INSERT INTO rows (table_id, id, data, owner, version, deleted) VALUES (?1, ?2, ?3, ?4, ?5, 0) ON CONFLICT (table_id, id) DO UPDATE SET data = excluded.data, owner = excluded.owner, version = excluded.version, deleted = 0", params![table, id, data, row["owner"].as_str(), row["version"].as_i64().unwrap_or(version)], ) .map_err(sql)?; } tx.execute("INSERT INTO meta (key, value) VALUES ('cursor', ?1) ON CONFLICT (key) DO UPDATE SET value = excluded.value", params![version.to_string()]).map_err(sql)?; tx.commit().map_err(sql) }pubfn wipe_rows(&self) -> Result<(), MethodError> {self.db.execute_batch("DELETE FROM rows; DELETE FROM meta WHERE key = 'cursor';").map_err(sql) }/// Every live row of a table, oldest first: `(id, owner, data)`.pubfn rows(&self, table: &str) -> Result<Vec<(String, Option<String>, Map<String, Value>)>, MethodError> {letmut statement = self.db.prepare("SELECT id, owner, data FROM rows WHERE table_id = ?1 AND deleted = 0 ORDER BY rowid").map_err(sql)?;let rows = statement .query_map(params![table], |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?, row.get::<_, String>(2)?))) .map_err(sql)? .filter_map(Result::ok) .map(|(id, owner, data)| (id, owner, serde_json::from_str::<Value>(&data).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default())) .collect();Ok(rows) }pubfn row(&self, table: &str, id: &str) -> Option<Map<String, Value>> {self.db .query_row("SELECT data FROM rows WHERE table_id = ?1 AND id = ?2 AND deleted = 0", params![table, id], |row| row.get::<_, String>(0)) .optional() .ok() .flatten() .and_then(|text| serde_json::from_str::<Value>(&text).ok()) .and_then(|v| v.as_object().cloned()) }/// The live rows of `table` whose `column` holds `value`: a rollup's source rows.pubfn linked(&self, table: &str, column: &str, value: &str) -> Vec<(String, Map<String, Value>)> {letOk(mut statement) = self.db.prepare("SELECT id, data FROM rows WHERE table_id = ?1 AND deleted = 0 AND json_extract(data, ?2) = ?3 ORDER BY rowid") else { returnVec::new() }; statement .query_map(params![table, format!("$.{column}"), value], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))) .map(|rows| { rows.filter_map(Result::ok) .map(|(id, data)| (id, serde_json::from_str::<Value>(&data).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default())) .collect() }) .unwrap_or_default() }}fn sql(error: rusqlite::Error) -> MethodError {MethodError::new("io", format!("the business cache refused ({error})"))}// ── the served definitions ─────────────────────────────────────────────────/// The business's definitions as the object serves them: the package tool and/// table JSON, read into the core's own types.pubstructDefinitions {pub business: Value,pub tools: Vec<ToolDefinition>,pub tables: Vec<TableDefinition>, by_id: HashMap<String, usize>,pub zone: String,}implDefinitions {pubfn read(cache: &Cache) -> Result<Definitions, MethodError> {let served = cache.definitions().ok_or_else(|| MethodError::new("not_synced", "this business has not been synced yet"))?;Definitions::of(&served) }pubfn of(served: &Value) -> Result<Definitions, MethodError> {let tools: Vec<ToolDefinition> = served["tools"] .as_array() .into_iter() .flatten() .filter_map(|tool| serde_json::from_value(tool.clone()).ok()) .collect();let tables: Vec<TableDefinition> = served["tables"] .as_array() .into_iter() .flatten() .filter_map(|table| serde_json::from_value(table.clone()).ok()) .collect();if tables.is_empty() {returnErr(MethodError::new("bad_definitions", "the object's definitions name no table this phone reads")); }let by_id = tables.iter().enumerate().map(|(i, t)| (t.id.clone(), i)).collect();let zone = served["business"]["timezone"].as_str().unwrap_or("Asia/Kolkata").to_string();Ok(Definitions { business: served["business"].clone(), tools, tables, by_id, zone }) }pubfn table(&self, id: &str) -> Option<&TableDefinition> {self.by_id.get(id).map(|i| &self.tables[*i]) }/// The tool that reserves on `slot_table`, with its rule.fn reserving(&self, slot_table: &str) -> Option<(&ToolDefinition, &cotton_core::definitions::reserve::Reservation)> {self.tools.iter().find_map(|tool| tool.reserve.as_ref().filter(|r| r.slot_table == slot_table).map(|r| (tool, r))) }/// Whether `claim_table` is a tool's claim table.fn claims(&self, claim_table: &str) -> bool {self.tools.iter().any(|tool| tool.reserve.as_ref().is_some_and(|r| r.claim_table == claim_table)) }}// ── computed columns from the cache ────────────────────────────────────────/// Works out a record's computed columns from the cached rows, once each per/// call: lookups through links, rollups over the rows that link back,/// formulas over the record. A record asked for from inside its own/// resolution answers its stored columns (the yoga session's `present` sums/// its bookings', whose `photo` looks the session's up).structResolver<'a> { defs: &'a Definitions, cache: &'a Cache, memo: std::cell::RefCell<HashMap<(String, String), Map<String, Value>>>, in_progress: std::cell::RefCell<HashSet<(String, String)>>,}impl<'a> Resolver<'a> {fn new(defs: &'a Definitions, cache: &'a Cache) -> Self {Resolver { defs, cache, memo: Default::default(), in_progress: Default::default() } }fn resolve(&self, definition: &TableDefinition, id: &str, data: &Map<String, Value>) -> Map<String, Value> {self.resolve_at(definition, id, data, 0) }fn resolve_at(&self, definition: &TableDefinition, id: &str, data: &Map<String, Value>, depth: usize) -> Map<String, Value> {let key = (definition.id.clone(), id.to_string());ifletSome(done) = self.memo.borrow().get(&key) {return done.clone(); }letmut out = data.clone(); out.insert("id".into(), json!(id));for column in &definition.columns { out.entry(column.key.clone()).or_insert(Value::Null); }if depth > MAX_RESOLVE_DEPTH || self.in_progress.borrow().contains(&key) {return out; }self.in_progress.borrow_mut().insert(key.clone());letmut formulas = Vec::new();for column in &definition.columns {match &column.computed {None => {}Some(Computed::Formula(_)) => formulas.push(column),Some(Computed::Lookup(lookup)) => {let value = self.lookup(definition, &out, &lookup.through, &lookup.column, depth); out.insert(column.key.clone(), value); }Some(Computed::Rollup(rollup)) => {let value = self.rollup(id, rollup, depth); out.insert(column.key.clone(), value); }Some(_) => {} } }self.in_progress.borrow_mut().remove(&key);for _ in0..4 {letmut settled = true;for column in &formulas {letSome(Computed::Formula(formula)) = &column.computed else { continue };let value = formula_value(formula, &out);if out.get(&column.key) != Some(&value) { settled = false; } out.insert(column.key.clone(), value); }if settled {break; } }self.memo.borrow_mut().insert(key, out.clone()); out }fn lookup(&self, definition: &TableDefinition, record: &Map<String, Value>, through: &str, column: &str, depth: usize) -> Value {letSome(target) = record.get(through).and_then(Value::as_str) else { returnValue::Null };letSome(link_to) = definition.columns.iter().find(|c| c.key == through).and_then(|c| c.link_to.as_deref()) else { returnValue::Null };letSome(linked) = self.defs.table(link_to) else { returnValue::Null };letSome(data) = self.cache.row(link_to, target) else { returnValue::Null };let resolved = self.resolve_at(linked, target, &data, depth + 1); resolved.get(column).cloned().unwrap_or(Value::Null) }fn rollup(&self, id: &str, rollup: &cotton_core::definitions::computed::Rollup, depth: usize) -> Value {letSome(source) = self.defs.table(&rollup.table) else { returnValue::Null };letmut rows = self.cache.linked(&rollup.table, &rollup.link, id);ifletSome(filter) = &rollup.where_ { rows.retain(|(_, data)| data.get(&filter.column).and_then(Value::as_str).is_some_and(|held| filter.values.iter().any(|v| v == held))); }if rollup.op == RollupOp::Count {return json!(rows.len()); }letSome(column) = &rollup.column else { returnValue::Null };let computed = source.columns.iter().any(|c| &c.key == column && c.computed.is_some());let values: Vec<Value> = rows .iter() .map(|(row_id, data)| if computed { self.resolve_at(source, row_id, data, depth + 1).get(column).cloned().unwrap_or(Value::Null) } else { data.get(column).cloned().unwrap_or(Value::Null) }) .collect(); cotton_core::cotton_rules::computed::rollup(rollup.op, rows.len(), &values) }}/// A formula over the record: the one arithmetic/// (`cotton_rules::computed::formula`), `flip_when` read off the record.fn formula_value(formula: &cotton_core::definitions::computed::Formula, record: &Map<String, Value>) -> Value {let parts: Vec<Value> = formula.of.iter().map(|k| record.get(k).cloned().unwrap_or(Value::Null)).collect();let flip = formula.flip_when.as_ref().is_some_and(|flip| { record.get(&flip.column).and_then(cotton_core::cotton_rules::computed::words_of).is_some_and(|held| flip.values.contains(&held)) }); cotton_core::cotton_rules::computed::formula(formula.op, &parts, flip, formula.separator.as_deref())}// ── views: period and sort ─────────────────────────────────────────────────typeRecord = (String, Option<String>, Map<String, Value>);/// The records whose own day (the table's `date` column) falls in `period`,/// read from `today` (a day number): today, tomorrow, next_7_days (today and/// the six after it), this_month, or next_day — the first day after today/// that holds any record.fn in_period(records: Vec<Record>, definition: &TableDefinition, period: &str, today: i64) -> Vec<Record> {letSome(date) = definition.date.as_deref() else { return records };let day_of = |data: &Map<String, Value>| -> Option<i64> {let text = data.get(date)?.as_str()?;let day = chrono::NaiveDate::parse_from_str(text.get(0..10)?, "%Y-%m-%d").ok()?;Some(day.signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1)?).num_days()) };match period {"today" => records.into_iter().filter(|r| day_of(&r.2) == Some(today)).collect(),"tomorrow" => records.into_iter().filter(|r| day_of(&r.2) == Some(today + 1)).collect(),"next_7_days" => records.into_iter().filter(|r| day_of(&r.2).is_some_and(|d| d >= today && d < today + 7)).collect(),"this_month" => {let month = cotton_core::transforms::zoned_clock::day_key(today); records.into_iter().filter(|r| r.2.get(date).and_then(Value::as_str).is_some_and(|d| d.get(0..7) == month.get(0..7))).collect() }"next_day" => {let next = records.iter().filter_map(|r| day_of(&r.2)).filter(|d| *d > today).min();match next {Some(next) => records.into_iter().filter(|r| day_of(&r.2) == Some(next)).collect(),None => Vec::new(), } } _ => records, }}pub(crate) fn compare(a: &Map<String, Value>, b: &Map<String, Value>, sort: &cotton_core::definitions::ListSort) -> std::cmp::Ordering {let order = compare_values(a.get(&sort.column), b.get(&sort.column));let order = if sort.descending == Some(true) { order.reverse() } else { order };match (&sort.tie, order) { (Some(tie), std::cmp::Ordering::Equal) => compare_values(a.get(tie), b.get(tie)), _ => order, }}fn compare_values(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {use std::cmp::Ordering;match (a, b) { (None | Some(Value::Null), None | Some(Value::Null)) => Ordering::Equal, (None | Some(Value::Null), _) => Ordering::Greater, (_, None | Some(Value::Null)) => Ordering::Less, (Some(Value::Number(x)), Some(Value::Number(y))) => x.as_f64().partial_cmp(&y.as_f64()).unwrap_or(Ordering::Equal), (Some(Value::String(x)), Some(Value::String(y))) => x.to_lowercase().cmp(&y.to_lowercase()), (Some(Value::Bool(x)), Some(Value::Bool(y))) => x.cmp(y), (Some(x), Some(y)) => x.to_string().cmp(&y.to_string()), }}// ── drawing a record and its acts ──────────────────────────────────────────/// The shipped words a business's cards are said in.structLines { words: cotton_core::records::page::Words, cards: cotton_core::rules::shell_lines::LineSet,}implLines {fn shipped() -> Lines {let rows = cotton_core::rules::shell_lines::shipped_rows();Lines { words: cotton_core::records::page::Words::of_rows(&rows), cards: cotton_core::records::card::card_words(&rows) } }}/// Whether a role may write rows of a table directly, as the object rules/// it: the owner writes everything, staff every table but the owner's, a/// member or the public nothing (they act). An empty date place offers/// "Add date" only to a writer.fn writes(role: &str, definition: &TableDefinition) -> bool {match definition.visibility.as_deref().unwrap_or("staff") {"owner" => role == "owner", _ => matches!(role, "staff" | "owner"), }}/// One record as a page draws it: its data whole with the computed columns/// filled, its table's card resolved under `@card`, and the slip's title and/// line. The records it links to are read from the cache: a people place/// names them by id (`Around::people`, name and picture), and every other/// place says the linked record's name, never its id — a pack says its/// member, a session its class.#[allow(clippy::too_many_arguments)]fn drawn_record(resolver: &Resolver, definition: &TableDefinition, id: &str, data: &Map<String, Value>, zone: &str, now: chrono::DateTime<chrono::Utc>, lines: &Lines, writable: bool) -> Value {use cotton_core::definitions::ColumnType;letmut whole = data.clone();let people_keys: HashSet<&str> = definition .card .as_ref() .map(|card| cotton_core::records::card::linked_places(card, definition).into_iter().map(|(_, key, _)| key).collect()) .unwrap_or_default();letmut people: HashMap<String, cotton_core::records::card::CardPerson> = HashMap::new();letmut shown = data.clone();for column in &definition.columns {if column.column_type != ColumnType::Link {continue; }letSome(target) = column.link_to.as_deref().and_then(|table| resolver.defs.table(table)) else { continue };let ids: Vec<String> = match data.get(&column.key) {Some(Value::String(one)) if !one.is_empty() => vec![one.clone()],Some(Value::Array(many)) => many.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(), _ => continue, };let names_place = !people_keys.contains(column.key.as_str());letmut names = Vec::new();for linked_id in &ids {letSome(row) = resolver.cache.row(&target.id, linked_id) else { continue };if names_place { names.push(cotton_core::records::receipt::record_name(target, &Value::Object(row))); } else { people.insert(linked_id.clone(), cotton_core::records::card::CardPerson::of(target, &row, &lines.words.dates)); } }if names_place && !names.is_empty() {let value = if ids.len() == 1 { Value::String(names.remove(0)) } else { Value::Array(names.into_iter().map(Value::String).collect()) }; shown.insert(column.key.clone(), value); } }ifletSome(card) = &definition.card {let around = cotton_core::records::card::Around { group: None, people: Some(&people), writable, thread: None };let resolved = cotton_core::records::card::resolve(card, definition, id, &shown, zone, now, &lines.words, &lines.cards, around);ifletSome(value) = resolved.and_then(|card| serde_json::to_value(card).ok()) { whole.insert(cotton_core::records::card::CARD_KEY.into(), value); } } json!({"table": definition.id,"id": id,"data": whole,"title": cotton_core::records::receipt::record_name(definition, &Value::Object(shown.clone())),"line": cotton_core::records::page::slip_line(definition, &shown, Some(zone), Some(now)), })}/// The acts a role takes on a record, as the object runs them: each one the/// table defines whose `when` holds, as the SAME act object `shell.opened`/// answers (`card_actions::CardAction`), ranked by the same rule/// (`card_actions::ranked`: the act that reserves primary and first, the/// kit's named acts, the rest, every act that takes the record away last/// and red), with the words the phone posts back (`business.act` with `act`/// and `args`, the picks asked first):////// ```json/// { "id", "label", "kind": "command", "rank": "main|more|away", "primary",/// "red", "icon"?, "act": "book|cancel|record_act", "args": {…},/// "picks": [pick…], "verb", "confirm"? }/// ```/// A member/// books a slot (`book`) and cancels their own claim (`cancel`); a stranger is/// offered the booking too and the phone signs them in first; staff and the/// owner run every record act (`record_act`) with its picks.fn acts_on(defs: &Definitions, definition: &TableDefinition, id: &str, record: &Map<String, Value>, role: &str, person: Option<&Value>, owner: Option<&str>) -> Vec<Value> {let staff = matches!(role, "staff" | "owner");let member = role == "member";let own = person.and_then(|p| p["id"].as_str()).is_some_and(|me| owner == Some(me));letmut acts = Vec::new();for act in definition.acts.iter().flatten() {if !act.when.iter().flat_map(|when| when.iter()).all(|(key, wanted)| when_matches(record.get(key), wanted)) {continue; }let verb = act.verb.as_deref().unwrap_or_default();let picks: Vec<Value> = act.ordered_picks().iter().filter_map(|pick| serde_json::to_value(pick).ok()).collect();let said = match verb {"reserve_record"if defs.reserving(&definition.id).is_some() => {if staff { json!({"act": "record_act", "args": {"table": definition.id, "id": id, "act": act.id}, "picks": picks}) } else {// A member books for themselves: the quantity is the only pick they answer.let quantity = defs.reserving(&definition.id).and_then(|(_, r)| r.quantity_column.clone()).map(|q| format!("data.{q}"));let asked: Vec<Value> = picks.into_iter().filter(|p| p["kind"] == "number" && Some(p["argument"].as_str().unwrap_or_default()) == quantity.as_deref()).map(|mut p| { p["argument"] = json!("quantity"); p }).collect(); json!({"act": "book", "args": {"slot": id}, "picks": asked}) } }"cancel_reservation"if defs.claims(&definition.id) => {if !(staff || (member && own)) {continue; } json!({"act": "cancel", "args": {"id": id}, "picks": []}) } _ => {if !staff {continue; } json!({"act": "record_act", "args": {"table": definition.id, "id": id, "act": act.id}, "picks": picks}) } };letmut card = cotton_core::rules::card_actions::CardAction::command(act);// A business act says its picks whole (`picks: [pick…]`, what the// phone asks before business.act); the held card's `picks: true` is// for a shell asking shell.opened, and serialised beside the array// it would overwrite it with a bare yes. card.asks = false; card.extra = said.as_object().cloned().unwrap_or_default(); card.extra.insert("verb".into(), json!(verb));ifletSome(confirm) = &act.confirm { card.extra.insert("confirm".into(), json!(confirm)); } acts.push(card); } cotton_core::rules::card_actions::ranked(definition, acts) .into_iter() .filter_map(|act| serde_json::to_value(act).ok()) .collect()}/// An act's `when` as the deck reads it: equal, one of a list asked for, or/// among a list held; an absent value reads as `false`.pub(crate) fn when_matches(value: Option<&Value>, wanted: &Value) -> bool {let held = match value {None | Some(Value::Null) => &Value::Bool(false),Some(v) => v, };if same(held, wanted) {returntrue; }ifletValue::Array(any) = wanted {return any.iter().any(|one| when_matches(Some(held), one)); } matches!(held, Value::Array(items) if items.iter().any(|one| same(one, wanted)))}fn same(a: &Value, b: &Value) -> bool {match (a, b) { (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(), _ => a == b, }}#[cfg(test)]#[path = "business_tests.rs"]mod tests;