Skip to main content

brep_plm/api/
catalog.rs

1//! The catalog tree: every signed-in user reads it, administrators shape it.
2//!
3//! The rules — inheritance, no redefinition, no cycles, no deleting what is
4//! in use — are in [`crate::catalog`] and [`crate::db::Db`]'s category
5//! operations; these handlers decide only who is asking.
6
7use axum::extract::{Path, State};
8use axum::http::{header, HeaderMap, StatusCode};
9use axum::response::{IntoResponse, Response};
10use axum::Json;
11use serde::{Deserialize, Serialize};
12
13use super::{ok_seq, require_admin, require_user, Shared};
14use crate::catalog::{self, Effective};
15use crate::db::CategoryChange;
16use crate::model::{AttributeDef, Category};
17use crate::Error;
18
19/// A category as the page lists it: its own record plus where it sits.
20#[derive(Debug, Serialize)]
21pub struct CategoryView {
22    #[serde(flatten)]
23    pub category: Category,
24    /// "Fasteners / Screws".
25    pub path: String,
26    /// 0 for a top-level category.
27    pub depth: usize,
28    /// Parts filed directly in this category (not in its sub-categories).
29    pub parts: usize,
30    /// Parts in this category and every category beneath it.
31    pub parts_within: usize,
32}
33
34/// The whole tree, depth-first with siblings by name — the order the page
35/// draws it in, so the page does no tree-building of its own.
36pub async fn list(
37    State(db): State<Shared>,
38    headers: HeaderMap,
39) -> Result<Response, Error> {
40    require_user(&db, &headers)?;
41    db.read(|state| {
42        // The sequence covers category edits and part moves/creation. Compare
43        // under the same guard as the tree, so the validator names these counts.
44        let etag = format!("\"categories-{}\"", state.seq);
45        if headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok())
46            .is_some_and(|value| value.split(',').any(|tag| tag.trim() == etag || tag.trim() == "*"))
47        {
48            return Ok((StatusCode::NOT_MODIFIED, [(header::ETAG, etag),
49                (header::CACHE_CONTROL, "private, no-cache".to_string())]).into_response());
50        }
51        let mut counts = std::collections::BTreeMap::<String, usize>::new();
52        for part in &state.parts {
53            *counts.entry(part.category.to_ascii_lowercase()).or_default() += 1;
54        }
55        let categories = &state.categories;
56        let mut out = Vec::with_capacity(categories.len());
57        let mut roots: Vec<&Category> = categories
58            .iter()
59            .filter(|c| c.parent.is_empty() || catalog::find(categories, &c.parent).is_none())
60            .collect();
61        roots.sort_by_key(|c| c.name.to_ascii_lowercase());
62        let mut stack: Vec<(&Category, usize)> = roots.into_iter().rev().map(|c| (c, 0)).collect();
63        let mut seen = std::collections::BTreeSet::new();
64        while let Some((category, depth)) = stack.pop() {
65            if !seen.insert(category.id.clone()) {
66                continue;
67            }
68            let own = counts.get(&category.id.to_ascii_lowercase()).copied().unwrap_or(0);
69            out.push(CategoryView {
70                category: category.clone(),
71                path: catalog::path_name(categories, &category.id),
72                depth,
73                parts: own,
74                parts_within: own,
75            });
76            let mut children: Vec<&Category> = categories
77                .iter()
78                .filter(|c| c.parent.eq_ignore_ascii_case(&category.id))
79                .collect();
80            children.sort_by_key(|c| c.name.to_ascii_lowercase());
81            stack.extend(children.into_iter().rev().map(|c| (c, depth + 1)));
82        }
83        // Children follow parents in the traversal. Accumulate totals in
84        // reverse order; every part is counted once, even in deep trees.
85        let positions: std::collections::BTreeMap<String, usize> = out.iter().enumerate()
86            .map(|(i, row)| (row.category.id.to_ascii_lowercase(), i)).collect();
87        for i in (0..out.len()).rev() {
88            if let Some(&parent) = positions.get(&out[i].category.parent.to_ascii_lowercase()) {
89                let total = out[i].parts_within;
90                out[parent].parts_within += total;
91            }
92        }
93        Ok(([(header::ETAG, etag), (header::CACHE_CONTROL, "private, no-cache".to_string())],
94            Json(out)).into_response())
95    })
96}
97
98#[derive(Debug, Deserialize)]
99pub struct NewCategory {
100    pub id: String,
101    pub name: String,
102    #[serde(default)]
103    pub parent: String,
104    #[serde(default)]
105    pub attributes: Vec<AttributeDef>,
106}
107
108pub async fn create(
109    State(db): State<Shared>,
110    headers: HeaderMap,
111    Json(body): Json<NewCategory>,
112) -> Result<Json<Category>, Error> {
113    require_admin(&db, &headers)?;
114    Ok(Json(db.create_category(
115        &body.id,
116        CategoryChange {
117            name: Some(body.name),
118            parent: Some(body.parent),
119            attributes: Some(body.attributes),
120        },
121    )?))
122}
123
124#[derive(Debug, Deserialize)]
125pub struct Change {
126    #[serde(default)]
127    pub name: Option<String>,
128    /// `""` moves the category to the top level.
129    #[serde(default)]
130    pub parent: Option<String>,
131    /// Replaces the category's own attribute list.
132    #[serde(default)]
133    pub attributes: Option<Vec<AttributeDef>>,
134}
135
136pub async fn update(
137    State(db): State<Shared>,
138    headers: HeaderMap,
139    Path(id): Path<String>,
140    Json(body): Json<Change>,
141) -> Result<Json<Category>, Error> {
142    require_admin(&db, &headers)?;
143    Ok(Json(db.update_category(
144        &id,
145        CategoryChange { name: body.name, parent: body.parent, attributes: body.attributes },
146    )?))
147}
148
149pub async fn remove(
150    State(db): State<Shared>,
151    headers: HeaderMap,
152    Path(id): Path<String>,
153) -> Result<Response, Error> {
154    require_admin(&db, &headers)?;
155    db.delete_category(&id)?;
156    Ok(ok_seq(&db))
157}
158
159/// A category's effective schema: what a part filed in it can carry.
160#[derive(Debug, Serialize)]
161pub struct Schema {
162    pub category: String,
163    pub path: String,
164    pub attributes: Vec<Effective>,
165}
166
167pub async fn schema(
168    State(db): State<Shared>,
169    headers: HeaderMap,
170    Path(id): Path<String>,
171) -> Result<Json<Schema>, Error> {
172    require_user(&db, &headers)?;
173    db.read(|state| {
174        let category = catalog::find(&state.categories, &id)
175            .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
176        Ok(Json(Schema {
177            category: category.id.clone(),
178            path: catalog::path_name(&state.categories, &category.id),
179            attributes: catalog::schema(&state.categories, &category.id)?,
180        }))
181    })
182}