//! A place is personal text plus one stable reference. Only a pick fills the //! dataset-owned country/time zone facts; an unmatched string stays untouched. use crate::definitions::{ColumnType, TableDefinition}; use super::Data; use serde_json::Value; /// Why a place pick is refused, as a typed fact; said in the database's /// `refusal` lines (`records.place.*`). `Lookup` carries the I/O seam's own /// refusal through. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PlaceRefusal { NoPlaceColumns { column: String }, FilledByChoosing { sibling: String, column: String }, DifferentId, SaveLocationFirst, Lookup(String), } impl PlaceRefusal { /// The refusal in `rows`' words, the kit's for a line they have none of. #[must_use] pub fn say(&self, rows: &[crate::rules::shell_lines::LineRow]) -> String { let (line, fills): (&str, Vec<(&str, &str)>) = match self { PlaceRefusal::NoPlaceColumns { column } => ("no_place_columns", vec![("column", column)]), PlaceRefusal::FilledByChoosing { sibling, column } => ("filled_by_choosing", vec![("key", sibling), ("column", column)]), PlaceRefusal::DifferentId => ("different_id", vec![]), PlaceRefusal::SaveLocationFirst => ("save_location_first", vec![]), PlaceRefusal::Lookup(said) => return said.clone(), }; crate::rules::shell_lines::resolve("refusal", &format!("records.place.{line}"), rows, &fills) .unwrap_or_else(|| format!("refusal.records.place.{line}")) } } impl std::fmt::Display for PlaceRefusal { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.say(&[])) } } pub struct PickedPlace { pub id: String, pub name: String, pub country: String, pub zone: String, /// The published row's coordinates and the version it was read at, copied /// in where the definition names those siblings. pub lat: Option, pub lng: Option, pub version: Option, } /// The siblings a definition may add beyond id, country and zone: kept only /// where a file stores them (a copy gains them from the object's definitions). pub fn extra_siblings(siblings: &crate::definitions::PlaceColumns) -> impl Iterator { [siblings.lat.as_ref(), siblings.lng.as_ref(), siblings.version.as_ref()].into_iter().flatten() } pub fn valid_id(id: &str) -> bool { id.strip_prefix("geonames:").is_some_and(|id| !id.is_empty() && id.bytes().all(|c| c.is_ascii_digit()) && id.parse::().is_ok_and(|id| id > 0)) || id.strip_prefix("location:").is_some_and(|id| id.len() == 36 && id.bytes().enumerate().all(|(n, c)| if [8,13,18,23].contains(&n) { c == b'-' } else { c.is_ascii_hexdigit() })) } /// A personal place is kept only against an explicit dataset neighbour. pub fn kept(value: &Value) -> Option<(&str, &str)> { let object = value.as_object()?; let words = object.get("kept")?.as_str()?; let near = object.get("near")?.as_str()?; (object.len() == 2 && !words.trim().is_empty() && near.starts_with("geonames:") && valid_id(near)).then_some((words, near)) } /// Called after ordinary input validation, before the first record write. /// The closure is the I/O seam: dataset reads or the person's saved location. pub fn resolve( definition: &TableDefinition, patch: &Data, mut lookup: impl FnMut(&str) -> Result, ) -> Result { let mut resolved = patch.clone(); for column in definition.columns.iter().filter(|c| c.column_type == ColumnType::Place) { let siblings = column.place.as_ref().ok_or_else(|| PlaceRefusal::NoPlaceColumns { column: column.key.clone() })?; for sibling in [&siblings.id, &siblings.country, &siblings.zone].into_iter().chain(extra_siblings(siblings)) { if patch.contains_key(sibling) { return Err(PlaceRefusal::FilledByChoosing { sibling: sibling.clone(), column: column.key.clone() }); } } let Some(value) = patch.get(&column.key) else { continue; }; if let Some(id) = value.get("place").and_then(Value::as_str) { let picked = lookup(id).map_err(PlaceRefusal::Lookup)?; if picked.id != id { return Err(PlaceRefusal::DifferentId); } resolved.insert(column.key.clone(), Value::String(picked.name)); resolved.insert(siblings.id.clone(), Value::String(picked.id)); resolved.insert(siblings.country.clone(), Value::String(picked.country)); resolved.insert(siblings.zone.clone(), Value::String(picked.zone)); let number = |n: Option| n.and_then(serde_json::Number::from_f64).map_or(Value::Null, Value::Number); if let Some(key) = &siblings.lat { resolved.insert(key.clone(), number(picked.lat)); } if let Some(key) = &siblings.lng { resolved.insert(key.clone(), number(picked.lng)); } if let Some(key) = &siblings.version { resolved.insert(key.clone(), picked.version.map_or(Value::Null, Value::String)); } } else if kept(value).is_some() { return Err(PlaceRefusal::SaveLocationFirst); } else { for key in [&siblings.id, &siblings.country, &siblings.zone].into_iter().chain(extra_siblings(siblings)) { resolved.insert(key.clone(), Value::Null); } } } Ok(resolved) } /// Legacy imports/engines write plain text. Mint the invalidation beside that /// text so every device sees an unpicked value, rather than a stale old link. pub fn invalidate_unpicked(columns: &[(String, crate::definitions::PlaceColumns)], patch: &mut Data) { for (text, siblings) in columns { if (patch.contains_key(text) || patch.contains_key(&siblings.country) || patch.contains_key(&siblings.zone)) && !patch.contains_key(&siblings.id) { patch.insert(siblings.id.clone(), Value::Null); patch.entry(siblings.country.clone()).or_insert(Value::Null); patch.entry(siblings.zone.clone()).or_insert(Value::Null); } } } /// The shipped engines' physical tables, derived once from their definitions. pub fn builtin_columns() -> &'static std::collections::BTreeMap<&'static str, Vec<(String, crate::definitions::PlaceColumns)>> { static COLUMNS: std::sync::OnceLock>> = std::sync::OnceLock::new(); COLUMNS.get_or_init(|| { crate::definitions::builtin_table_definitions().iter().filter_map(|definition| { let table = crate::definitions::builtin_store_table(&definition.id)?; let columns: Vec<_> = definition.columns.iter().filter_map(|column| column.place.clone().map(|place| (column.key.clone(), place))).collect(); (!columns.is_empty()).then_some((table, columns)) }).collect() }) }