Skip to main content

brep_plm/
tools.rs

1//! The tools library: the hand tools, drivers and fixtures manufacturing
2//! instructions name in their steps (a name, a picture and a spec).
3//!
4//! A step keeps the tool's id AND a snapshot of its name and spec, so a PDF or
5//! an offline copy needs no server; the library is where the picker finds
6//! them. A tool is therefore never deleted, only retired: old instructions
7//! still name it, and the picker stops offering it.
8//!
9//! The list lives in the state like the companies of [`crate::sourcing`]:
10//! every write is audited by the store's diff, and a picture is a blob of the
11//! attachment store ([`crate::attach`]), kept while a tool references it.
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16use crate::attach::{self, Staged};
17use crate::db::{now, Db, State};
18use crate::model::{Timestamp, User};
19use crate::Error;
20
21/// Picture media types: raster images a browser shows without running
22/// anything (no SVG, which can carry script).
23pub const PICTURE_TYPES: [&str; 3] = ["image/png", "image/jpeg", "image/webp"];
24
25/// The largest picture, in bytes.
26pub const PICTURE_MAX: u64 = 2 * 1024 * 1024;
27
28const MAX_NAME: usize = 200;
29const MAX_TEXT: usize = 2000;
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct Tool {
33    /// `TL-000001`: handed out in order, never reused.
34    pub id: String,
35    pub name: String,
36    /// What a step needs to know about it: a size, a range, a setting.
37    #[serde(default)]
38    pub spec: String,
39    /// Free text a library is sorted by (`Torque wrench`, `Fixture`).
40    #[serde(default)]
41    pub kind: String,
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub picture: Option<Picture>,
44    /// Hidden from the picker; instructions that name it keep their snapshot.
45    #[serde(default)]
46    pub retired: bool,
47    pub created_by: String,
48    pub created_at: Timestamp,
49    pub modified_at: Timestamp,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct Picture {
54    pub sha256: String,
55    pub media_type: String,
56    pub size: u64,
57}
58
59/// The picture blobs the library references ([`attach::referenced`]).
60pub fn pictures(state: &State) -> impl Iterator<Item = &str> {
61    state.tools.iter().filter_map(|t| t.picture.as_ref().map(|p| p.sha256.as_str()))
62}
63
64fn text(fields: &Map<String, Value>, key: &str, max: usize) -> Result<Option<String>, Error> {
65    match fields.get(key) {
66        None => Ok(None),
67        Some(Value::String(s)) if s.chars().count() <= max => Ok(Some(s.trim().to_string())),
68        Some(Value::String(_)) => Err(Error::bad_request(format!("a tool's {key} is at most {max} characters"))),
69        Some(_) => Err(Error::bad_request(format!("a tool's {key} is text"))),
70    }
71}
72
73/// Apply `fields` (`name`, `spec`, `kind`, `retired`) to `tool`, refusing
74/// anything else and a name another live tool has.
75fn apply(state: &State, tool: &mut Tool, fields: &Value) -> Result<(), Error> {
76    let fields = fields.as_object().ok_or_else(|| Error::bad_request("a tool is a JSON object"))?;
77    if let Some(key) = fields.keys().find(|k| !["name", "spec", "kind", "retired"].contains(&k.as_str())) {
78        return Err(Error::bad_request(format!("a tool has no field '{key}'")));
79    }
80    if let Some(name) = text(fields, "name", MAX_NAME)? {
81        tool.name = name;
82    }
83    if let Some(spec) = text(fields, "spec", MAX_TEXT)? {
84        tool.spec = spec;
85    }
86    if let Some(kind) = text(fields, "kind", MAX_NAME)? {
87        tool.kind = kind;
88    }
89    match fields.get("retired") {
90        None => {}
91        Some(Value::Bool(retired)) => tool.retired = *retired,
92        Some(_) => return Err(Error::bad_request("retired is true or false")),
93    }
94    if tool.name.is_empty() {
95        return Err(Error::bad_request("a tool needs a name"));
96    }
97    if !tool.retired {
98        if let Some(twin) = state.tools.iter().find(|t| t.id != tool.id && !t.retired && t.name.eq_ignore_ascii_case(&tool.name)) {
99            return Err(Error::conflict(format!("{} is already called '{}'", twin.id, twin.name)));
100        }
101    }
102    Ok(())
103}
104
105impl Db {
106    pub fn create_tool(&self, user: &User, fields: &Value) -> Result<Tool, Error> {
107        let fields = fields.clone();
108        let user_id = user.id.clone();
109        self.mutate(move |state| {
110            state.next_tool += 1;
111            let stamp = now();
112            let mut tool = Tool {
113                id: format!("TL-{:06}", state.next_tool),
114                name: String::new(),
115                spec: String::new(),
116                kind: String::new(),
117                picture: None,
118                retired: false,
119                created_by: user_id,
120                created_at: stamp,
121                modified_at: stamp,
122            };
123            apply(state, &mut tool, &fields)?;
124            state.tools.push(tool.clone());
125            Ok(tool)
126        })
127    }
128
129    pub fn update_tool(&self, id: &str, fields: &Value) -> Result<Tool, Error> {
130        let (id, fields) = (id.to_string(), fields.clone());
131        self.mutate(move |state| {
132            let index = state.tools.iter().position(|t| t.id == id).ok_or_else(|| Error::not_found("tool"))?;
133            let mut tool = state.tools[index].clone();
134            apply(state, &mut tool, &fields)?;
135            tool.modified_at = now();
136            state.tools[index] = tool.clone();
137            Ok(tool)
138        })
139    }
140
141    /// Set a tool's picture to an uploaded image; the old one's blob goes
142    /// when nothing else references it.
143    pub fn set_tool_picture(&self, id: &str, staged: Staged, media_type: &str) -> Result<Tool, Error> {
144        let media_type = media_type.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
145        if !PICTURE_TYPES.contains(&media_type.as_str()) {
146            return Err(Error::bad_request(format!("a tool picture is PNG, JPEG or WebP, not '{media_type}'")));
147        }
148        if staged.size > PICTURE_MAX {
149            return Err(Error {
150                status: axum::http::StatusCode::PAYLOAD_TOO_LARGE,
151                message: format!("a tool picture is at most {} MB", PICTURE_MAX / (1024 * 1024)),
152            });
153        }
154        let (id, root) = (id.to_string(), self.root().to_path_buf());
155        self.mutate(move |state| {
156            let index = state.tools.iter().position(|t| t.id == id).ok_or_else(|| Error::not_found("tool"))?;
157            attach::place(&root, &staged)?;
158            let old = state.tools[index].picture.replace(Picture { sha256: staged.sha256.clone(), media_type, size: staged.size });
159            state.tools[index].modified_at = now();
160            if let Some(old) = old {
161                attach::remove_if_unreferenced(state, &root, &old.sha256)?;
162            }
163            Ok(state.tools[index].clone())
164        })
165    }
166}