//! Toolkits: install the one a person chose into a newly born file, through //! ordinary signed receipts, and read the `cotton_toolkits` rows back. No //! start writes a kit row (72nd amendment). use crate::mcp::dispatch::Ctx; use crate::mcp::protocol::ToolFailure; use cotton_core::toolkits::KitTool; use rusqlite::types::Value as SqlValue; use cotton_store::{ driver::Driver, mint::{Actor, Held, JobName}, }; use serde_json::{json, Value}; use std::collections::BTreeSet; use std::sync::Arc; /// A kit as an install reads it: its id and its tools, in order. #[derive(Debug, Clone, PartialEq)] pub struct Kit { pub id: String, pub tools: Vec, } /// The kit a new database is made from: the personal database's row at `id` /// when it has one (`personal` is that database), else this build's shipped /// kit at that id — a phone that has not received its kit rows yet still /// makes a database offline — and none when the person deleted that kit or /// no kit has the id. pub fn kit(personal: Option<&Driver>, id: &str) -> std::result::Result, String> { if let Some(db) = personal { let workspace = db .get("SELECT workspace_id FROM _meta", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.text("workspace_id").map(str::to_string)) .unwrap_or_default(); if let Some(row) = read(db, &workspace)?.into_iter().find(|kit| kit.id == id) { return Ok(Some(Kit { id: row.id, tools: row.tools })); } let gone = db .get( "SELECT 1 FROM _tombstones WHERE tbl = ?1 AND row_id = ?2 \ UNION ALL SELECT 1 FROM _gone WHERE tbl = ?1 AND row_id = ?2", &[SqlValue::Text(TOOLKITS.into()), SqlValue::Text(id.into())], ) .map_err(|error| error.to_string())? .is_some(); if gone { return Ok(None); } } Ok(cotton_core::toolkits::shipped() .into_iter() .find(|kit| kit.id == id) .map(|kit| Kit { id: kit.id, tools: kit.tools })) } /// Install `kit` into a newly born file, through ordinary signed receipts: /// each tool it carries by the same install `import_tool` runs /// (`install_package`: its tables, its tool, its pictures and, when the kit /// says, its sample rows), in the kit's order — a kit tool named by id from /// the kit's own package — then Home's arrangement: each tool's list on Home. /// No tool is built in (72nd amendment), so nothing else joins. pub fn install( db: &Driver, kit: &Kit, now: chrono::DateTime, random: Arc, held: Held, ) -> std::result::Result<(), ToolFailure> { let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string()); let file = cotton_store::file_identity::read_file_identity(db) .map_err(fail)? .ok_or_else(|| ToolFailure::new("the new database has no identity yet"))?; let owner = db .get("SELECT owner_id FROM _meta", &[]) .map_err(fail)? .and_then(|row| row.text("owner_id").map(str::to_string)) .unwrap_or_default(); let services = crate::mcp::dispatch::ToolServices::none(); let audit = |_: &str, _: &str| {}; let actor = Actor::DeviceJob(JobName::named("toolkit").map_err(fail)?); let mut ctx = Ctx::for_worker(db, &file, &owner, actor, "toolkit", now, random, &services, &audit).held_as(held); for tool in &kit.tools { match tool { KitTool::Package { package } => { let carried = carried_package(&kit.id, package)?; crate::mcp::handlers::tool_packages::install_package(&mut ctx, &carried, crate::mcp::handlers::tool_packages::Door::Kit, package.with_samples) .map_err(|failure| ToolFailure::new(format!("kit {:?}: {}", kit.id, failure.0)))?; } KitTool::Kit(id) => { let package = cotton_core::kit::package(id) .ok_or_else(|| ToolFailure::new(format!("kit {:?}: {id:?} is no kit tool", kit.id)))? .map_err(|error| ToolFailure::new(format!("kit {:?}: {error}", kit.id)))?; crate::mcp::handlers::tool_packages::install_package(&mut ctx, &package.package, crate::mcp::handlers::tool_packages::Door::Import, false) .map_err(|failure| ToolFailure::new(format!("kit {:?}: {}", kit.id, failure.0)))?; } } } let tools: Vec = kit.tools.iter().map(|tool| tool.key().to_string()).collect(); let view_ids = tools.iter().map(|key| cotton_core::rules::home_arrangement::tool_view(key)).collect(); let arrangement = cotton_core::rules::home_arrangement::HomeArrangement { project_slugs: Vec::new(), tools, view_ids }; crate::home_arrangement::save(&mut ctx, &arrangement)?; ctx.commit() } /// A package as kit `kit` carries it, in the form `install_package` installs: /// its pictures decoded from the base64 the row keeps them in. pub fn carried_package( kit: &str, package: &cotton_core::toolkits::KitPackage, ) -> std::result::Result { let pictures = package .pictures .iter() .map(|(name, encoded)| { use base64::Engine; base64::engine::general_purpose::STANDARD .decode(encoded) .map(|bytes| (name.clone(), bytes)) .map_err(|_| ToolFailure::new(format!("kit {kit:?}: picture {name:?} is not base64"))) }) .collect::>()?; Ok(cotton_core::definitions::package::ToolPackage { board: package.board.clone(), tool: package.tool.clone(), tables: package.tables.clone(), pictures, samples: package.samples.clone(), }) } /// The table the kits are kept in, in the personal database. pub const TOOLKITS: &str = "cotton_toolkits"; /// One kit row as a reader answers it. #[derive(Debug, Clone, PartialEq, serde::Serialize)] pub struct KitRow { pub id: String, pub name: String, pub description: Option, pub picture: Option, pub tools: Vec, pub shipped: bool, pub position: i64, } /// Every kit this file holds, in the chooser's order (position, then name). pub fn read(db: &Driver, workspace: &str) -> std::result::Result, String> { db.all( &format!( "SELECT id, name, description, picture, tools, shipped, position FROM {TOOLKITS} \ WHERE workspace_id = ? ORDER BY position, name, id" ), &[SqlValue::Text(workspace.into())], ) .map_err(|error| error.to_string())? .iter() .map(|row| { let id = row.text("id").unwrap_or_default().to_string(); let tools = serde_json::from_str(row.text("tools").unwrap_or("[]")) .map_err(|error| format!("toolkit {id:?}: its tools cannot be read: {error}"))?; let picture = match row.text("picture") { Some(text) => Some( serde_json::from_str(text) .map_err(|error| format!("toolkit {id:?}: its picture cannot be read: {error}"))?, ), None => None, }; Ok(KitRow { name: row.text("name").unwrap_or_default().to_string(), description: row.text("description").map(str::to_string), picture, tools, shipped: row.int("shipped") == Some(1), position: row.int("position").unwrap_or_default(), id, }) }) .collect() } /// The kit a database makes (`save_toolkit`): every tool installed here, /// carried as a package (its tool, the tables it lists, the pictures it /// carries) — read from the file alone, with nothing else held. pub fn compose(db: &Driver) -> std::result::Result, String> { use cotton_core::definitions::{TableDefinition, ToolDefinition}; use cotton_core::toolkits::KitPackage; let file = cotton_store::link_rule::this_file(db).map_err(|error| error.to_string())?; let workspace = file.id.ok_or("the database has no identity yet")?; // A kit installs its packages in order and a package may need a table // another one brings: the order this file installed them in (rowid), // which met every such need when they were installed. let keys: Vec = db .all( &format!("SELECT id FROM {} WHERE workspace_id = ? ORDER BY rowid", crate::definitions::TOOL_DEFINITIONS), &[SqlValue::Text(workspace.clone())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); let definition =|table: &str, id: &str| -> std::result::Result, String> { Ok(db .get( &format!("SELECT definition FROM {table} WHERE workspace_id = ? AND id = ?"), &[SqlValue::Text(workspace.clone()), SqlValue::Text(id.into())], ) .map_err(|error| error.to_string())? .and_then(|row| row.text("definition").map(str::to_string))) }; let mut tools = Vec::new(); for key in &keys { let Some(text) = definition(crate::definitions::TOOL_DEFINITIONS, key)? else { continue }; let tool: ToolDefinition = serde_json::from_str(&text).map_err(|error| format!("tool {key:?}: {error}"))?; let builtin_ids: Vec = cotton_core::definitions::builtin_table_definitions().iter().map(|table| table.id.clone()).collect(); let tables = tool .tables .iter() .filter(|id| !builtin_ids.contains(*id)) .map(|id| { let text = definition(crate::definitions::TABLE_DEFINITIONS, id)? .ok_or_else(|| format!("tool {key:?} lists table {id:?}, which this database does not hold"))?; TableDefinition::from_json(&text).map_err(|error| format!("table {id:?}: {error}")) }) .collect::, String>>()?; let pictures = crate::tool_pictures::package_pictures(db, &workspace, key)?; tools.push(KitTool::Package { package: KitPackage { board: crate::presentation::board(db, &workspace, key)?.map(|resolved| cotton_core::definitions::board::BoardDefinition::strict(&resolved.definition).map_err(|why| why.to_string())).transpose()?, tool, tables, samples: Default::default(), with_samples: false, pictures }, }); } Ok(tools) } /// Whether `id` is a kit this build ships — an id a person's kit never takes. pub fn is_shipped_id(id: &str) -> bool { cotton_core::toolkits::shipped().iter().any(|kit| kit.id == id) } /// The ids a new kit may not take in this personal database: every kit row's, /// every kit this build ships (deleted here or not), every kit deleted here. pub fn taken_ids(db: &Driver, workspace: &str) -> std::result::Result, String> { let mut taken: BTreeSet = read(db, workspace)?.into_iter().map(|kit| kit.id).collect(); taken.extend(cotton_core::toolkits::shipped().into_iter().map(|kit| kit.id)); let gone = db .all( "SELECT row_id FROM _tombstones WHERE tbl = ?1 UNION SELECT row_id FROM _gone WHERE tbl = ?1", &[SqlValue::Text(TOOLKITS.into())], ) .map_err(|error| error.to_string())?; taken.extend(gone.iter().filter_map(|row| row.text("row_id").map(str::to_string))); Ok(taken) } /// `slug` when no kit holds it, else the first of `slug-2`, `slug-3`, … that is free. pub fn fresh_id(slug: &str, taken: &BTreeSet) -> String { if !taken.contains(slug) { return slug.to_string(); } (2..).map(|n| format!("{slug}-{n}")).find(|id| !taken.contains(id)).expect("a free id") } /// A kit's id from its name: lowercase words joined by hyphens (`Home /// kitchen` → `home-kitchen`), the shape the shipped kits' ids have. pub fn kit_id(name: &str) -> String { name.replace(['\'', '\u{2019}'], "") .split(|c: char| !c.is_alphanumeric()) .filter(|word| !word.is_empty()) .map(str::to_lowercase) .collect::>() .join("-") } /// A kit's tools by the names Home gives them, in order: a kit tool's name /// (Todos for `todos`), a carried tool's own name. pub fn tool_names(tools: &[KitTool]) -> Vec { let tools_by_key = kit_tools(); tools .iter() .map(|tool| match tool { KitTool::Kit(key) => tools_by_key .iter() .find(|(id, _)| id == key) .map(|(_, name)| name.clone()) .unwrap_or_else(|| key.clone()), KitTool::Package { package } => package.tool.name.clone(), }) .collect() } /// Every kit tool, `(id, name)` — its package's own name. fn kit_tools() -> Vec<(String, String)> { cotton_core::kit::ids() .into_iter() .map(|id| { let name = cotton_core::kit::package(id) .and_then(Result::ok) .map_or_else(|| id.to_string(), |package| package.package.tool.name); (id.to_string(), name) }) .collect() } /// The kit tool a person names, by its id (`todos`) or its name (`Todos`, /// any case); `None` when no kit tool is called that. pub fn kit_key(word: &str) -> Option { kit_tools() .into_iter() .find(|(key, name)| key == word || name.eq_ignore_ascii_case(word)) .map(|(key, _)| key) } /// What "What is it for?" offers: the personal database's kits in its order /// (`personal` is that database), or this build's shipped kits while it holds /// no kit rows yet. Each kit as the app decodes it — `id`, `name`, /// `startingTools` (its tools' names, in order), `toolIds` (their keys), /// `picture` (the kit's own, or null) and `description`. pub fn chooser(personal: Option<&Driver>) -> std::result::Result, String> { let rows = match personal { Some(db) => { let workspace = db .get("SELECT workspace_id FROM _meta", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.text("workspace_id").map(str::to_string)) .unwrap_or_default(); read(db, &workspace)? .into_iter() .map(|kit| (kit.id, kit.name, kit.description, kit.picture, kit.tools)) .collect::>() } None => Vec::new(), }; let rows = if rows.is_empty() { cotton_core::toolkits::shipped() .into_iter() .map(|kit| (kit.id, kit.name, kit.description, kit.picture.map(|picture| json!(picture)), kit.tools)) .collect() } else { rows }; Ok(rows .into_iter() .map(|(id, name, description, picture, tools)| { let names = tool_names(&tools); json!({ "id": id, "name": name, "description": description, "picture": picture, "startingTools": names, "toolIds": tools.iter().map(KitTool::key).collect::>(), }) }) .collect()) }