Skip to main content

brep_plm/api/
bom.rs

1//! Assembly structure over HTTP: a revision's uses list, its BOM, the diff
2//! between two revisions' lists, and where a part is used.
3//!
4//! The rules are in [`crate::bom`] and [`crate::db::Db::set_uses`]; these
5//! handlers decide only who is asking and how the answer is shaped. The CAD
6//! app will write the uses list through the same `PUT` the web page uses.
7
8use axum::extract::{Path, Query, State};
9use axum::http::{header, HeaderMap, StatusCode};
10use axum::response::{IntoResponse, Response};
11use axum::Json;
12use serde::Deserialize;
13use serde_json::{json, Value};
14
15use super::{require_author, require_user, Shared};
16use crate::bom;
17use crate::db::State as Store;
18use crate::model::{Part, Revision};
19use crate::Error;
20
21/// The part named by id or number, and one of its revisions by id or label.
22fn locate<'a>(state: &'a Store, part: &str, revision: &str) -> Result<(&'a Part, &'a Revision), Error> {
23    let part = state.part_by_id_or_number(part).ok_or_else(|| Error::not_found("part"))?;
24    let revision = bom::find_revision(part, revision).ok_or_else(|| Error::not_found("revision"))?;
25    Ok((part, revision))
26}
27
28/// `levels=all` or a count; absent or `0` is every level.
29fn levels(text: &str) -> Result<usize, Error> {
30    match text.trim() {
31        "" | "all" | "0" => Ok(0),
32        n => n
33            .parse::<usize>()
34            .map_err(|_| Error::bad_request(format!("levels must be a number or 'all', not '{n}'"))),
35    }
36}
37
38/// What the list says, with each child resolved to a number and label.
39pub async fn get_uses(
40    State(db): State<Shared>,
41    headers: HeaderMap,
42    Path((id, rev)): Path<(String, String)>,
43) -> Result<Json<Value>, Error> {
44    require_user(&db, &headers)?;
45    db.read(|state| {
46        let (_, revision) = locate(state, &id, &rev)?;
47        Ok(Json(json!({ "uses": bom::resolved_uses(state, revision) })))
48    })
49}
50
51/// Replace the list. The author group, holding the revision's lock, on a
52/// revision in work — the same conditions as saving its document.
53pub async fn put_uses(
54    State(db): State<Shared>,
55    headers: HeaderMap,
56    Path((id, rev)): Path<(String, String)>,
57    Json(body): Json<Value>,
58) -> Result<Json<Value>, Error> {
59    let user = require_author(&db, &headers)?;
60    let (part_id, revision_id) = db.read(|state| {
61        let (part, revision) = locate(state, &id, &rev)?;
62        Ok::<_, Error>((part.id.clone(), revision.id.clone()))
63    })?;
64    db.set_uses(&user, &part_id, &revision_id, &body)?;
65    db.read(|state| {
66        let (_, revision) = locate(state, &part_id, &revision_id)?;
67        Ok(Json(json!({ "ok": true, "seq": state.seq, "uses": bom::resolved_uses(state, revision) })))
68    })
69}
70
71#[derive(Debug, Deserialize, Default)]
72pub struct BomQuery {
73    #[serde(default)]
74    pub levels: String,
75    #[serde(default)]
76    pub flat: bool,
77    /// `csv` for a download; anything else is JSON.
78    #[serde(default)]
79    pub format: String,
80    /// Add an `Attachments` column to the CSV.
81    #[serde(default)]
82    pub attachments: bool,
83    #[serde(default)]
84    pub occurrences: bool,
85}
86
87pub async fn get_bom(
88    State(db): State<Shared>,
89    headers: HeaderMap,
90    Path((id, rev)): Path<(String, String)>,
91    Query(query): Query<BomQuery>,
92) -> Result<Response, Error> {
93    let user = require_user(&db, &headers)?;
94    let depth = levels(&query.levels)?;
95    let result = db.read(|state| {
96        let (part, revision) = locate(state, &id, &rev)?;
97        let mut result = bom::bom(state, part, revision, depth, if query.occurrences {false} else {query.flat});
98        if query.occurrences { result.comparison_lines=Some(result.lines.clone()); crate::bom_config::expand_bom(state, &mut result, query.flat); }
99        Ok::<_, Error>(result)
100    })?;
101    if query.format.eq_ignore_ascii_case("csv") {
102        let name = format!(
103            "{}-{}-bom{}.csv",
104            result.number,
105            result.revision_label,
106            if result.flat { "-flat" } else { "" }
107        )
108        .replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'), "_");
109        return Ok((
110            [
111                (header::CONTENT_TYPE, "text/csv; charset=utf-8".to_string()),
112                (header::CONTENT_DISPOSITION, format!("attachment; filename=\"{name}\"")),
113            ],
114            db.read(|state| {
115                let layout=state.bom_configuration.selections.get(&user.id).and_then(|id|state.bom_configuration.layouts.iter().find(|l|l.id==*id&&(l.owner.is_none()||l.owner.as_deref()==Some(&user.id))));
116                layout.filter(|_|query.occurrences).map(|layout|crate::bom_config::layout_csv(&result,layout,&crate::bom_config::fields(state))).unwrap_or_else(||bom::bom_csv_with(&result,query.attachments))
117            }),
118        )
119            .into_response());
120    }
121    // The ETag is the body's own hash: it moves with anything the BOM view
122    // shows (its lines, their attributes and revision states) and with
123    // nothing else. The web view's 5 s poll sends it back, and an unchanged
124    // BOM costs a 304 instead of megabytes to fetch, parse and compare.
125    let body = serde_json::to_vec(&result).map_err(Error::internal)?;
126    let etag = body_etag(&body);
127    let cache = (header::CACHE_CONTROL, "private, no-cache".to_string());
128    if headers
129        .get(header::IF_NONE_MATCH)
130        .and_then(|v| v.to_str().ok())
131        .is_some_and(|sent| sent.split(',').any(|tag| tag.trim() == etag || tag.trim() == "*"))
132    {
133        return Ok((StatusCode::NOT_MODIFIED, [(header::ETAG, etag), cache]).into_response());
134    }
135    Ok(([(header::CONTENT_TYPE, "application/json".to_string()), (header::ETAG, etag), cache], body).into_response())
136}
137
138/// A strong ETag naming `body`'s bytes.
139fn body_etag(body: &[u8]) -> String {
140    use sha2::{Digest, Sha256};
141    let digest = Sha256::digest(body);
142    format!("\"bom-{}\"", digest[..12].iter().map(|b| format!("{b:02x}")).collect::<String>())
143}
144
145#[derive(Debug, Deserialize)]
146pub struct DiffQuery {
147    pub from: String,
148    pub to: String,
149}
150
151/// What changed in the uses list between two revisions of one part.
152pub async fn diff(
153    State(db): State<Shared>,
154    headers: HeaderMap,
155    Path(id): Path<String>,
156    Query(query): Query<DiffQuery>,
157) -> Result<Json<bom::BomDiff>, Error> {
158    require_user(&db, &headers)?;
159    db.read(|state| {
160        let (part, from) = locate(state, &id, &query.from)?;
161        let to = bom::find_revision(part, &query.to).ok_or_else(|| Error::not_found("revision"))?;
162        Ok(Json(bom::diff(state, part, from, to)))
163    })
164}
165
166#[derive(Debug, Deserialize, Default)]
167pub struct WhereUsedQuery {
168    /// A revision id or label: only uses that point at it. Empty: any.
169    #[serde(default)]
170    pub revision: String,
171    #[serde(default)]
172    pub levels: String,
173}
174
175pub async fn where_used(
176    State(db): State<Shared>,
177    headers: HeaderMap,
178    Path(id): Path<String>,
179    Query(query): Query<WhereUsedQuery>,
180) -> Result<Json<bom::WhereUsed>, Error> {
181    require_user(&db, &headers)?;
182    let depth = levels(&query.levels)?;
183    db.read(|state| {
184        let part = state.part_by_id_or_number(&id).ok_or_else(|| Error::not_found("part"))?;
185        let revision = match query.revision.trim() {
186            "" => None,
187            key => Some(bom::find_revision(part, key).ok_or_else(|| Error::not_found("revision"))?),
188        };
189        Ok(Json(bom::where_used(state, part, revision, depth)))
190    })
191}
192
193/// Replace a part (or one revision of it) in every assembly that uses it
194/// ([`crate::replace`]). `dry_run` answers what would happen and writes
195/// nothing. The author group.
196pub async fn replace(
197    State(db): State<Shared>,
198    headers: HeaderMap,
199    Path(id): Path<String>,
200    Json(request): Json<crate::replace::ReplaceRequest>,
201) -> Result<Json<crate::replace::ReplaceReport>, Error> {
202    let user = require_author(&db, &headers)?;
203    Ok(Json(super::blocking(move || db.replace_everywhere(&user, &id, &request)).await?))
204}