Skip to main content

brep_plm/api/
parts.rs

1//! Parts, revisions, checkout and lifecycle.
2//!
3//! The handlers are thin: every rule that could be got wrong twice — number
4//! allocation, one-draft-per-part, who may break a lock, what a released
5//! revision may become — lives in [`crate::db`] and [`crate::lifecycle`], and
6//! these functions decide only who is asking.
7
8use axum::extract::{Path, Query, State};
9use axum::http::HeaderMap;
10use axum::response::{IntoResponse, Response};
11use axum::Json;
12use serde::{Deserialize, Serialize};
13
14use super::{blocking, ok_seq, require_author, require_user, Shared};
15use crate::catalog::{self, Effective};
16use crate::db::{suggest_label, PartFilter, PartSpec};
17use crate::model::{DocumentClass, Lifecycle, Part, Revision};
18use crate::Error;
19
20/// A part in a list: enough to show a row, never the revision payloads.
21#[derive(Debug, Serialize)]
22pub struct PartRow {
23    pub has_geometry: bool,
24    /// Whether the part has the current preview used by the Parts listing.
25    pub has_thumbnail: bool,
26    pub id: String,
27    pub number: String,
28    pub name: String,
29    pub part_type: String,
30    pub document_class: DocumentClass,
31    /// A catalog category id, or empty for uncategorized parts.
32    pub category: String,
33    /// "Fasteners / Screws" when `category` names a category; empty when the
34    /// part is uncategorized.
35    pub category_path: String,
36    pub tags: Vec<String>,
37    pub revisions: usize,
38    pub latest_label: String,
39    pub latest_state: &'static str,
40    pub locked: bool,
41    /// The preferred MPN, or else the first; empty with no sourcing.
42    pub mpn: String,
43    /// Where the part comes from in another system; empty for none.
44    pub external_ref: String,
45    /// The newest revision (by creation, drafts included): its id, its
46    /// origin (`authored`, `imported`, `generated`) and its document's
47    /// content hash (lowercase hex SHA-256 of the bytes as PUT; empty with
48    /// no document). What a library re-import compares against.
49    pub latest_revision_id: String,
50    pub latest_origin: Option<crate::model::Origin>,
51    pub latest_content_hash: String,
52    /// The part's catalog values, canonical (numbers and flags as JSON
53    /// numbers and booleans), when the listing asks `include=attributes`.
54    /// Every stored value, inert ones included.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub attributes: Option<std::collections::BTreeMap<String, serde_json::Value>>,
57    /// Where to fetch the part's thumbnail (its newest revision's that is
58    /// current, [`crate::thumbnail`]), versioned by the picture; empty when
59    /// it has none.
60    pub thumbnail_url: String,
61}
62
63impl PartRow {
64    fn new(categories: &[crate::model::Category], part: &Part) -> Self {
65        let latest = part.latest();
66        Self {
67            has_geometry: latest.is_some_and(|r| r.has_geometry),
68            has_thumbnail: crate::thumbnail::of_part(part).is_some(),
69            id: part.id.clone(),
70            number: part.number.clone(),
71            name: part.name.clone(),
72            part_type: part.part_type.clone(),
73            document_class: part.document_class,
74            category: part.category.clone(),
75            category_path: catalog::path_name(categories, &part.category),
76            tags: part.tags.clone(),
77            revisions: part.revisions.len(),
78            latest_label: latest.map(|r| r.label.clone()).unwrap_or_default(),
79            latest_state: latest.map(|r| r.lifecycle.as_str()).unwrap_or("—"),
80            locked: part.revisions.iter().any(|r| r.lock.is_some()),
81            mpn: part
82                .sourcing
83                .iter()
84                .find(|mp| mp.preferred)
85                .or(part.sourcing.first())
86                .map(|mp| mp.mpn.clone())
87                .unwrap_or_default(),
88            attributes: None,
89            external_ref: part.external_ref.clone(),
90            latest_revision_id: latest.map(|r| r.id.clone()).unwrap_or_default(),
91            latest_origin: latest.map(|r| r.origin),
92            latest_content_hash: latest.map(|r| r.content_hash.clone()).unwrap_or_default(),
93            thumbnail_url: crate::thumbnail::part_url(part),
94        }
95    }
96}
97
98#[derive(Debug, Deserialize)]
99pub struct Search {
100    #[serde(default)]
101    pub q: String,
102    /// A category id — the parts in it and beneath it — or `_none` for the
103    /// uncategorized.
104    #[serde(default)]
105    pub category: String,
106    #[serde(default)]
107    pub tag: String,
108    /// A manufacturer id or name: parts with a manufacturer part from it.
109    #[serde(default)]
110    pub manufacturer: String,
111    /// A supplier id or name: parts with an offer from it.
112    #[serde(default)]
113    pub supplier: String,
114    /// Page size, default 50. `next` is `null` on the last page.
115    #[serde(default)]
116    pub limit: Option<usize>,
117    /// The `next` of the page before.
118    #[serde(default)]
119    pub after: Option<String>,
120    /// `attributes`: each row also carries the part's attribute values.
121    #[serde(default)]
122    pub include: String,
123    /// Exact: the part(s) a library import made for this entry.
124    #[serde(default)]
125    pub external_ref: String,
126    /// Exact part type id.
127    #[serde(default)]
128    pub part_type: String,
129}
130
131/// The largest page a client may ask for.
132pub const MAX_PAGE: usize = 1000;
133
134/// Search and filter parts ([`crate::db::Db::find_parts_page`]), one page
135/// and the cursor to the next.
136pub async fn list_parts(
137    State(db): State<Shared>,
138    headers: HeaderMap,
139    Query(search): Query<Search>,
140    Query(pairs): Query<Vec<(String, String)>>,
141) -> Result<Json<serde_json::Value>, Error> {
142    require_user(&db, &headers)?;
143    let filter = PartFilter {
144        q: search.q,
145        category: search.category,
146        tag: search.tag,
147        manufacturer: search.manufacturer,
148        supplier: search.supplier,
149        attributes: crate::db::AttributeFilter::from_query(&pairs)?,
150        external_ref: search.external_ref,
151        part_type: search.part_type,
152    };
153    // Conditions that do not read are refused, not answered with nothing.
154    db.read(|state| crate::db::attribute_matchers(state, &filter))?;
155    let with_attributes = match search.include.trim() {
156        "" => false,
157        "attributes" => true,
158        other => return Err(Error::bad_request(format!("include={other}: the only thing a row can include is 'attributes'"))),
159    };
160    let limit = search.limit.unwrap_or(50).clamp(1, MAX_PAGE);
161    let page = db.find_parts_page(&filter, search.after.as_deref(), Some(limit));
162    let rows: Vec<PartRow> = db.read(|state| {
163        page.parts
164            .iter()
165            .map(|p| {
166                let mut row = PartRow::new(&state.categories, p);
167                if with_attributes {
168                    let mut attributes = p.attributes.clone();
169                    attributes.insert("has_geometry".into(), serde_json::json!(row.has_geometry));
170                    attributes.insert("has_thumbnail".into(), serde_json::json!(row.has_thumbnail));
171                    row.attributes = Some(attributes);
172                }
173                row
174            })
175            .collect()
176    });
177    Ok(Json(serde_json::json!({ "parts": rows, "next": page.next })))
178}
179
180/// One part with its revisions, each carrying who holds it.
181#[derive(Debug, Serialize)]
182pub struct PartDetail {
183    pub has_geometry: bool,
184    /// Whether the part has the current preview used by the Parts listing.
185    pub has_thumbnail: bool,
186    #[serde(flatten)]
187    pub part: Part,
188    pub revision_views: Vec<RevisionView>,
189    /// The label the next revision gets when nobody types one.
190    pub suggested_label: String,
191    /// "Fasteners / Screws"; empty when uncategorized.
192    pub category_path: String,
193    /// Every attribute the part's category defines, inherited ones first.
194    /// Empty when uncategorized.
195    pub schema: Vec<Effective>,
196    /// Keys the part holds a value for that its category does not define —
197    /// left by a move between categories. Kept, shown, and inert.
198    pub inert: Vec<String>,
199    /// The administrator's lock on released catalog values applies to this
200    /// part right now: its category and attributes change only once a new
201    /// revision is in work.
202    pub catalog_locked: bool,
203    /// Whether another revision may be started while one is in work.
204    pub multiple_open_drafts: bool,
205    /// The part's sourcing with company names resolved beside their ids
206    /// ([`crate::sourcing::resolved`]). `sourcing` on the part itself carries
207    /// the ids alone.
208    pub sourcing_view: serde_json::Value,
209    /// The revision "open by number" fills in (D13): the newest by
210    /// creation, drafts included — the last of `revision_views`, named so a
211    /// client need not know that. Absent for a part with no revision.
212    pub newest_revision: Option<NewestRevision>,
213    /// The part's thumbnail URL ([`PartRow::thumbnail_url`]); empty for none.
214    pub thumbnail_url: String,
215}
216
217/// The newest revision of a part, whatever its state.
218#[derive(Debug, Serialize)]
219pub struct NewestRevision {
220    pub id: String,
221    pub label: String,
222    pub lifecycle: &'static str,
223    pub document_key: String,
224}
225
226/// A revision with the lock resolved to a name — the id alone tells the page
227/// nothing it can display.
228#[derive(Debug, Serialize)]
229pub struct RevisionView {
230    pub id: String,
231    pub label: String,
232    pub lifecycle: &'static str,
233    pub editable: bool,
234    pub content_hash: String,
235    pub size: u64,
236    pub created_at: u64,
237    pub modified_at: u64,
238    pub locked_by: Option<String>,
239    pub locked_by_me: bool,
240    pub locked_at: Option<u64>,
241    pub released_by: Option<String>,
242    pub released_at: Option<u64>,
243    pub document_key: String,
244    /// `authored`, `imported` or `generated`.
245    pub origin: crate::model::Origin,
246    /// The family that generated this revision, when one did.
247    pub family: Option<Provenance>,
248    /// The template this revision was spun out of, when it was.
249    pub template: Option<Provenance>,
250    /// `pending`, `claimed`, `failed` or `done` — absent when nothing was
251    /// queued to bake.
252    pub bake: Option<&'static str>,
253    pub bake_error: String,
254    /// A generated member whose document changed since Generate wrote it.
255    pub hand_edited: bool,
256    /// How many lines the revision's uses list has: more than none makes it
257    /// an assembly.
258    pub uses: usize,
259    /// The current review round, in brief — absent when it never had one.
260    pub review: Option<ReviewSummary>,
261    /// How many comments its discussion has.
262    pub comments: usize,
263    /// This revision's thumbnail, current or stale; absent with none.
264    pub thumbnail: Option<ThumbnailView>,
265}
266
267/// A revision's thumbnail in brief.
268#[derive(Debug, Serialize)]
269pub struct ThumbnailView {
270    /// Whether it pictures the document as it is now. A stale one is not
271    /// served; this says one existed.
272    pub current: bool,
273    /// Where to fetch it; empty when stale.
274    pub url: String,
275    pub width: u32,
276    pub height: u32,
277    pub renderer: String,
278    pub content_hash: String,
279}
280
281/// A review round in one line of the revision table.
282#[derive(Debug, Serialize)]
283pub struct ReviewSummary {
284    pub status: &'static str,
285    pub live: bool,
286    /// Approvals given on the document as it is now: the ones that count.
287    pub approvals: usize,
288    /// Approvals given on an older version: they need renewing (D8).
289    pub stale_approvals: usize,
290    pub required_approvals: u32,
291    /// Whether the person looking is one of its reviewers.
292    pub may_decide: bool,
293}
294
295/// Where a generated revision came from, with the source resolved to a
296/// number a person recognises.
297#[derive(Debug, Serialize)]
298pub struct Provenance {
299    pub part_id: String,
300    pub number: String,
301    pub revision_label: String,
302    pub values: std::collections::BTreeMap<String, String>,
303}
304
305pub async fn get_part(
306    State(db): State<Shared>,
307    headers: HeaderMap,
308    Path(id): Path<String>,
309) -> Result<Json<PartDetail>, Error> {
310    let user = require_user(&db, &headers)?;
311    db.read(|state| {
312        // An id, or a number as a person types it (D13).
313        let part = state.part_by_id_or_number(&id).ok_or_else(|| Error::not_found("part"))?;
314        let revision_views = part
315            .revisions
316            .iter()
317            .map(|revision| view(state, part, revision, &user.id))
318            .collect();
319        let schema = match catalog::find(&state.categories, &part.category) {
320            Some(category) => catalog::schema(&state.categories, &category.id)?,
321            None => Vec::new(),
322        };
323        let inert = part
324            .attributes
325            .keys()
326            .filter(|key| !schema.iter().any(|e| &e.def.key == *key))
327            .cloned()
328            .collect();
329        Ok(Json(PartDetail {
330            has_geometry: part.latest().is_some_and(|r| r.has_geometry),
331            has_thumbnail: crate::thumbnail::of_part(part).is_some(),
332            part: part.clone(),
333            revision_views,
334            suggested_label: suggest_label(part),
335            category_path: catalog::path_name(&state.categories, &part.category),
336            schema,
337            inert,
338            catalog_locked: state.settings.lock_released_attributes && part.catalog_frozen(),
339            multiple_open_drafts: state.settings.allow_multiple_open_drafts,
340            sourcing_view: crate::sourcing::resolved(state, part),
341            newest_revision: part.latest().map(|r| NewestRevision {
342                id: r.id.clone(),
343                label: r.label.clone(),
344                lifecycle: r.lifecycle.as_str(),
345                document_key: r.document_key(&part.id),
346            }),
347            thumbnail_url: crate::thumbnail::part_url(part),
348        }))
349    })
350}
351
352fn view(
353    state: &crate::db::State,
354    part: &Part,
355    revision: &Revision,
356    viewer_id: &str,
357) -> RevisionView {
358    let name_of = |id: &str| {
359        state
360            .user(id)
361            .map(|u| {
362                if u.display_name.is_empty() {
363                    u.username.clone()
364                } else {
365                    u.display_name.clone()
366                }
367            })
368            .unwrap_or_else(|| "(removed user)".to_string())
369    };
370    RevisionView {
371        id: revision.id.clone(),
372        label: revision.label.clone(),
373        lifecycle: revision.lifecycle.as_str(),
374        editable: revision.lifecycle.is_editable(),
375        content_hash: revision.content_hash.clone(),
376        size: revision.size,
377        created_at: revision.created_at,
378        modified_at: revision.modified_at,
379        locked_by: revision.lock.as_ref().map(|l| name_of(&l.user_id)),
380        locked_by_me: revision
381            .lock
382            .as_ref()
383            .is_some_and(|l| l.user_id == viewer_id),
384        locked_at: revision.lock.as_ref().map(|l| l.acquired_at),
385        released_by: revision.released_by.as_deref().map(name_of),
386        released_at: revision.released_at,
387        document_key: revision.document_key(&part.id),
388        origin: revision.origin,
389        family: revision.family.as_ref().map(|stamp| provenance(state, &stamp.family_part, &stamp.family_revision, &stamp.values)),
390        template: revision
391            .template
392            .as_ref()
393            .map(|stamp| provenance(state, &stamp.template_part, &stamp.template_revision, &stamp.values)),
394        bake: revision.bake.as_ref().map(|b| b.status.as_str()),
395        bake_error: revision.bake.as_ref().map(|b| b.error.clone()).unwrap_or_default(),
396        hand_edited: revision.family.as_ref().is_some_and(|s| s.generated_hash != revision.content_hash),
397        uses: revision.uses.len(),
398        review: revision.review().map(|r| ReviewSummary {
399            status: r.status.as_str(),
400            live: r.is_live(),
401            approvals: r.approvers(&revision.content_hash).len(),
402            stale_approvals: r.stale_approvers(&revision.content_hash).len(),
403            required_approvals: r.required_approvals,
404            may_decide: r.is_live() && state.user(viewer_id).is_some_and(|u| crate::review::is_reviewer(r, u)),
405        }),
406        comments: revision.comments.len(),
407        thumbnail: revision.thumbnail.as_ref().map(|t| ThumbnailView {
408            current: crate::thumbnail::current(revision).is_some(),
409            url: crate::thumbnail::revision_url(&part.id, revision),
410            width: t.width,
411            height: t.height,
412            renderer: t.renderer.clone(),
413            content_hash: t.content_hash.clone(),
414        }),
415    }
416}
417
418fn provenance(
419    state: &crate::db::State,
420    part_id: &str,
421    revision_id: &str,
422    values: &std::collections::BTreeMap<String, String>,
423) -> Provenance {
424    let part = state.part(part_id);
425    Provenance {
426        part_id: part_id.to_string(),
427        number: part.map(|p| p.number.clone()).unwrap_or_else(|| "(removed part)".into()),
428        revision_label: part
429            .and_then(|p| p.revision(revision_id))
430            .map(|r| r.label.clone())
431            .unwrap_or_else(|| "(deleted revision)".into()),
432        values: values.clone(),
433    }
434}
435
436#[derive(Debug, Deserialize)]
437pub struct NewPart {
438    /// Required, except for instructions, which default to their own type
439    /// ([`crate::db::Db::instructions_part_type`]).
440    #[serde(default)]
441    pub part_type: String,
442    pub name: String,
443    #[serde(default)]
444    pub description: String,
445    #[serde(default)]
446    pub category: String,
447    /// The typed number. Refused by a counter type, required by free-text and
448    /// pattern types, handed to the script of a script type.
449    #[serde(default)]
450    pub number: String,
451    /// `normal`, `family` or `template` (or `.nBREP` / `.fBREP` / `.tBREP`).
452    #[serde(default)]
453    pub document_class: String,
454    /// The first revision's label; empty takes `A`.
455    #[serde(default)]
456    pub label: String,
457    #[serde(default)]
458    pub tags: Vec<String>,
459    /// Catalog values, checked against `category`'s schema.
460    #[serde(default)]
461    pub attributes: serde_json::Map<String, serde_json::Value>,
462    /// Where the part comes from in another system (a KiCad library id);
463    /// unique among parts of the same type (`409` naming the one that has it).
464    #[serde(default)]
465    pub external_ref: String,
466    /// The first revision's origin: `authored` (default) or `imported`.
467    #[serde(default)]
468    pub origin: crate::model::Origin,
469    /// The creator's workspace folder the new part is linked into; empty is
470    /// the top ([`crate::workspace::link_on_create`]).
471    #[serde(default)]
472    pub workspace_folder: String,
473    /// A machine import making many parts (the adoption importer, a library
474    /// import): nothing is linked.
475    #[serde(default)]
476    pub bulk: bool,
477}
478
479/// Create a part. It may run the type's number script and the label script,
480/// so it runs on the blocking pool — a script can wait on the network.
481pub async fn create_part(
482    State(db): State<Shared>,
483    headers: HeaderMap,
484    Json(body): Json<NewPart>,
485) -> Result<Json<Part>, Error> {
486    let user = require_author(&db, &headers)?;
487    let document_class = DocumentClass::parse(&body.document_class).ok_or_else(|| {
488        Error::bad_request(format!(
489            "'{}' is not a document class — normal, family, template or instructions",
490            body.document_class
491        ))
492    })?;
493    let part_type = if document_class == DocumentClass::Instructions && body.part_type.trim().is_empty() {
494        let db = db.clone();
495        blocking(move || db.instructions_part_type()).await?
496    } else {
497        body.part_type
498    };
499    let spec = PartSpec {
500        part_type,
501        number: body.number,
502        name: body.name,
503        description: body.description,
504        category: body.category,
505        document_class,
506        label: body.label,
507        tags: body.tags,
508        attributes: body.attributes,
509        exact: false,
510        external_ref: body.external_ref,
511        origin: body.origin,
512        workspace: crate::workspace::link_on_create(body.origin, body.bulk, &body.workspace_folder),
513    };
514    let part = blocking(move || db.create_part_with(&user, &spec)).await?;
515    Ok(Json(part))
516}
517
518/// Change a part's name, description, category, tags or attribute values
519/// (`attributes` merges; `null` clears a key). The author group and up, the
520/// same people who create parts. The number, type and document class are
521/// identity and are refused ([`crate::db::Db::update_part`]).
522///
523/// No lock is needed: these are the PART's fields, not a revision's document,
524/// and checkout guards documents.
525pub async fn update_part(
526    State(db): State<Shared>,
527    headers: HeaderMap,
528    Path(id): Path<String>,
529    Json(body): Json<serde_json::Value>,
530) -> Result<Json<Part>, Error> {
531    require_author(&db, &headers)?;
532    // Only by id here: a part number in a URL could collide with an id.
533    if db.read(|state| state.part(&id).is_none()) {
534        return Err(Error::not_found("part"));
535    }
536    Ok(Json(db.update_part(&id, &body)?))
537}
538
539#[derive(Debug, Deserialize, Default)]
540pub struct NewRevision {
541    /// Free text; empty takes the suggestion.
542    #[serde(default)]
543    pub label: String,
544    /// `authored` (default) or `imported` — a library re-import's revision.
545    #[serde(default)]
546    pub origin: crate::model::Origin,
547}
548
549pub async fn create_revision(
550    State(db): State<Shared>,
551    headers: HeaderMap,
552    Path(id): Path<String>,
553    body: Option<Json<NewRevision>>,
554) -> Result<Json<Revision>, Error> {
555    let user = require_author(&db, &headers)?;
556    let (label, origin) = body.map(|Json(b)| (b.label, b.origin)).unwrap_or_default();
557    let revision = blocking(move || db.create_revision_from(&user, &id, &label, origin)).await?;
558    Ok(Json(revision))
559}
560
561#[derive(Debug, Deserialize, Default)]
562pub struct CheckoutBody {
563    /// Which client of this user is taking the lock. The same person can hold
564    /// a browser and a desktop session at once, and the break dialog has to be
565    /// able to say which.
566    #[serde(default)]
567    pub client_id: String,
568}
569
570pub async fn checkout(
571    State(db): State<Shared>,
572    headers: HeaderMap,
573    Path((id, revision)): Path<(String, String)>,
574    body: Option<Json<CheckoutBody>>,
575) -> Result<Response, Error> {
576    let user = require_author(&db, &headers)?;
577    let client = body.map(|Json(b)| b.client_id).unwrap_or_default();
578    let client = if client.trim().is_empty() { "web".to_string() } else { client };
579    db.checkout(&user, &id, &revision, &client)?;
580    Ok(ok_seq(&db))
581}
582
583#[derive(Debug, Deserialize, Default)]
584pub struct CheckinBody {
585    /// Break someone else's lock. Needs the check-in group; the server checks,
586    /// not the page.
587    #[serde(default)]
588    pub force: bool,
589}
590
591pub async fn checkin(
592    State(db): State<Shared>,
593    headers: HeaderMap,
594    Path((id, revision)): Path<(String, String)>,
595    body: Option<Json<CheckinBody>>,
596) -> Result<Response, Error> {
597    let user = require_user(&db, &headers)?;
598    let force = body.map(|Json(b)| b.force).unwrap_or(false);
599    db.checkin(&user, &id, &revision, force)?;
600    Ok(ok_seq(&db))
601}
602
603#[derive(Debug, Deserialize)]
604pub struct StateBody {
605    pub to: String,
606}
607
608pub async fn set_state(
609    State(db): State<Shared>,
610    headers: HeaderMap,
611    Path((id, revision)): Path<(String, String)>,
612    Json(body): Json<StateBody>,
613) -> Result<Response, Error> {
614    let user = require_user(&db, &headers)?;
615    let to = match body.to.trim().to_ascii_lowercase().as_str() {
616        "draft" => Lifecycle::Draft,
617        "inreview" | "in-review" | "review" => Lifecycle::InReview,
618        "released" | "release" => Lifecycle::Released,
619        "superseded" => Lifecycle::Superseded,
620        "obsolete" => Lifecycle::Obsolete,
621        other => return Err(Error::bad_request(format!("'{other}' is not a lifecycle state"))),
622    };
623    let handle = db.clone();
624    let warnings = blocking(move || handle.transition(&user, &id, &revision, to)).await?;
625    let seq = db.read(|state| state.seq);
626    Ok(Json(serde_json::json!({ "ok": true, "seq": seq, "warnings": warnings })).into_response())
627}
628
629pub async fn delete_revision(
630    State(db): State<Shared>,
631    headers: HeaderMap,
632    Path((id, revision)): Path<(String, String)>,
633) -> Result<Response, Error> {
634    let user = require_author(&db, &headers)?;
635    db.delete_draft(&user, &id, &revision)?;
636    Ok(ok_seq(&db))
637}