1use std::collections::BTreeSet;
20
21use serde::Serialize;
22use serde_json::Value;
23
24use crate::model::{AttributeDef, AttributeKind, Category, Part};
25use crate::Error;
26
27pub const MAX_DEPTH: usize = 32;
30
31pub fn find<'a>(categories: &'a [Category], id: &str) -> Option<&'a Category> {
33 let id = id.trim();
34 if id.is_empty() {
35 return None;
36 }
37 categories.iter().find(|c| c.id.eq_ignore_ascii_case(id))
38}
39
40pub fn chain<'a>(categories: &'a [Category], id: &str) -> Result<Vec<&'a Category>, Error> {
42 let mut out: Vec<&Category> = Vec::new();
43 let mut current = id.to_string();
44 loop {
45 let category = find(categories, ¤t).ok_or_else(|| {
46 if out.is_empty() {
47 Error::not_found(format!("category '{current}'"))
48 } else {
49 Error::conflict(format!(
50 "category '{}' names a parent '{current}' that does not exist",
51 out.last().expect("not empty").id
52 ))
53 }
54 })?;
55 if out.iter().any(|seen| seen.id == category.id) {
56 return Err(Error::conflict(format!(
57 "category '{}' would be its own ancestor",
58 category.id
59 )));
60 }
61 if out.len() >= MAX_DEPTH {
62 return Err(Error::conflict(format!(
63 "categories nest at most {MAX_DEPTH} deep"
64 )));
65 }
66 out.push(category);
67 if category.parent.trim().is_empty() {
68 break;
69 }
70 current = category.parent.clone();
71 }
72 out.reverse();
73 Ok(out)
74}
75
76#[derive(Debug, Clone, Serialize)]
78pub struct Effective {
79 #[serde(flatten)]
80 pub def: AttributeDef,
81 pub from: String,
84}
85
86pub fn schema(categories: &[Category], id: &str) -> Result<Vec<Effective>, Error> {
88 Ok(chain(categories, id)?
89 .into_iter()
90 .flat_map(|category| {
91 category.attributes.iter().map(move |def| Effective {
92 def: def.clone(),
93 from: category.id.clone(),
94 })
95 })
96 .collect())
97}
98
99pub fn descendants(categories: &[Category], id: &str) -> BTreeSet<String> {
101 let mut out = BTreeSet::new();
102 let Some(root) = find(categories, id) else {
103 return out;
104 };
105 let mut frontier = vec![root.id.to_ascii_lowercase()];
106 while let Some(next) = frontier.pop() {
107 if !out.insert(next.clone()) {
108 continue; }
110 for child in categories.iter().filter(|c| c.parent.eq_ignore_ascii_case(&next)) {
111 frontier.push(child.id.to_ascii_lowercase());
112 }
113 }
114 out
115}
116
117pub fn path_name(categories: &[Category], id: &str) -> String {
119 match chain(categories, id) {
120 Ok(chain) => chain.iter().map(|c| c.name.as_str()).collect::<Vec<_>>().join(" / "),
121 Err(_) => String::new(),
122 }
123}
124
125fn usable_key(key: &str) -> bool {
128 key.chars().next().is_some_and(|c| c.is_ascii_lowercase())
129 && key
130 .chars()
131 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
132}
133
134pub fn normalize_id(id: &str) -> Result<String, Error> {
137 let id = id.trim().to_ascii_lowercase();
138 if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
139 return Err(Error::bad_request(
140 "a category id is letters, digits, '-' and '_'",
141 ));
142 }
143 Ok(id)
144}
145
146pub fn check_definitions(defs: Vec<AttributeDef>) -> Result<Vec<AttributeDef>, Error> {
149 let mut out: Vec<AttributeDef> = Vec::with_capacity(defs.len());
150 for mut def in defs {
151 def.key = def.key.trim().to_ascii_lowercase();
152 if matches!(def.key.as_str(), "has_geometry" | "has_thumbnail") {
153 return Err(Error::bad_request(format!("{} is a built-in read-only attribute", def.key)));
154 }
155 if !usable_key(&def.key) {
156 return Err(Error::bad_request(format!(
157 "'{}' is not a usable attribute key — start with a letter; then letters, digits, '_' and '-'",
158 def.key
159 )));
160 }
161 def.name = def.name.trim().to_string();
162 if def.name.is_empty() {
163 def.name = def.key.clone();
164 }
165 if out.iter().any(|d| d.key == def.key) {
166 return Err(Error::bad_request(format!("attribute '{}' is defined twice", def.key)));
167 }
168 match &mut def.kind {
169 AttributeKind::Number { unit } => *unit = unit.trim().to_string(),
170 AttributeKind::Enum { values } => {
171 let mut tidy: Vec<String> = Vec::new();
172 for value in values.iter() {
173 let value = value.trim();
174 if value.is_empty() {
175 continue;
176 }
177 if tidy.iter().any(|v| v.eq_ignore_ascii_case(value)) {
178 return Err(Error::bad_request(format!(
179 "attribute '{}' lists '{value}' twice",
180 def.key
181 )));
182 }
183 tidy.push(value.to_string());
184 }
185 if tidy.is_empty() {
186 return Err(Error::bad_request(format!(
187 "attribute '{}' is a list of values and needs at least one",
188 def.key
189 )));
190 }
191 *values = tidy;
192 }
193 AttributeKind::Text | AttributeKind::Bool => {}
194 }
195 out.push(def);
196 }
197 Ok(out)
198}
199
200pub fn check_tree(categories: &[Category]) -> Result<(), Error> {
206 for category in categories {
207 let chain = chain(categories, &category.id)?;
208 let mut owner: Vec<(&str, &str)> = Vec::new();
209 for link in &chain {
210 for def in &link.attributes {
211 if let Some((_, first)) = owner.iter().find(|(key, _)| *key == def.key) {
212 return Err(Error::conflict(format!(
213 "attribute '{}' is defined by '{first}' and again by '{}' — a category inherits its parent's attributes and cannot redefine one",
214 def.key, link.id
215 )));
216 }
217 owner.push((&def.key, &link.id));
218 }
219 }
220 }
221 Ok(())
222}
223
224pub fn check_value(def: &AttributeDef, value: &Value) -> Result<Option<Value>, String> {
230 if value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty()) {
231 return Ok(None);
232 }
233 match &def.kind {
234 AttributeKind::Text => match value {
235 Value::String(text) => Ok(Some(Value::String(text.trim().to_string()))),
236 other => Err(format!("{} takes text, not {other}", def.name)),
237 },
238 AttributeKind::Number { .. } => {
239 let number = match value {
240 Value::Number(n) => n.as_f64(),
241 Value::String(text) => text.trim().parse::<f64>().ok(),
242 _ => None,
243 };
244 match number.filter(|n| n.is_finite()) {
245 Some(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Ok(Some(Value::from(n as i64))),
247 Some(n) => Ok(serde_json::Number::from_f64(n).map(Value::Number)),
248 None => Err(format!("{} takes a number, not {value}", def.name)),
249 }
250 }
251 AttributeKind::Bool => match value {
252 Value::Bool(b) => Ok(Some(Value::Bool(*b))),
253 Value::String(text) => match text.trim().to_ascii_lowercase().as_str() {
254 "true" | "yes" => Ok(Some(Value::Bool(true))),
255 "false" | "no" => Ok(Some(Value::Bool(false))),
256 _ => Err(format!("{} takes yes or no, not {value}", def.name)),
257 },
258 other => Err(format!("{} takes yes or no, not {other}", def.name)),
259 },
260 AttributeKind::Enum { values } => {
261 let text = value.as_str().map(str::trim).unwrap_or_default();
262 match values.iter().find(|v| v.eq_ignore_ascii_case(text)) {
263 Some(canonical) => Ok(Some(Value::String(canonical.clone()))),
264 None => Err(format!("{} is one of {}, not {value}", def.name, values.join(", "))),
265 }
266 }
267 }
268}
269
270pub fn release_problems(categories: &[Category], part: &Part) -> Vec<String> {
275 if part.category.is_empty() { return Vec::new(); }
276 let schema = match schema(categories, &part.category) {
277 Ok(schema) => schema,
278 Err(error) => return vec![error.to_string()],
279 };
280 let mut problems = Vec::new();
281 for Effective { def, .. } in &schema {
282 match part.attributes.get(&def.key) {
283 None => {
284 if def.required {
285 problems.push(format!("{} is required", def.name));
286 }
287 }
288 Some(value) => match check_value(def, value) {
289 Ok(Some(_)) => {}
290 Ok(None) => {
291 if def.required {
292 problems.push(format!("{} is required", def.name));
293 }
294 }
295 Err(message) => problems.push(message),
296 },
297 }
298 }
299 problems
300}
301
302pub fn apply_values(
308 categories: &[Category],
309 category: &str,
310 values: &mut std::collections::BTreeMap<String, Value>,
311 changes: &serde_json::Map<String, Value>,
312) -> Result<(), Error> {
313 let schema = if category.is_empty() { Vec::new() } else { schema(categories, category)? };
314 for (key, value) in changes {
315 let key = key.trim().to_ascii_lowercase();
316 let clearing = value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty());
317 if clearing {
318 values.remove(&key);
319 continue;
320 }
321 let Some(Effective { def, .. }) = schema.iter().find(|e| e.def.key == key) else {
322 return Err(Error::bad_request(if schema.is_empty() && find(categories, category).is_none() {
323 format!("'{key}' cannot be set — choose a category for the part first")
324 } else {
325 format!(
326 "'{key}' is not an attribute of category '{}'",
327 path_name(categories, category)
328 )
329 }));
330 };
331 match check_value(def, value).map_err(Error::bad_request)? {
332 Some(stored) => {
333 values.insert(key, stored);
334 }
335 None => {
336 values.remove(&key);
337 }
338 }
339 }
340 Ok(())
341}
342
343pub fn tidy_tags(tags: impl IntoIterator<Item = String>) -> Vec<String> {
346 let mut out: Vec<String> = Vec::new();
347 for tag in tags {
348 let tag = tag.trim().to_string();
349 if !tag.is_empty() && !out.iter().any(|t| t.eq_ignore_ascii_case(&tag)) {
350 out.push(tag);
351 }
352 }
353 out
354}
355