brep_plm/model.rs
1//! The PLM record types, and nothing that acts on them.
2//!
3//! The shape follows the four identity layers the architecture settled on:
4//! **Part** (permanent, owns the number) → **Revision** (the released unit) →
5//! the CAD **document** the revision points at → the **occurrence**, which
6//! lives in the CAD document and never in this server.
7//!
8//! # Slots that are deliberately inert
9//!
10//! [`Origin`] and [`Part::external_ref`] are recorded and served but nothing
11//! here branches on them yet. They are the seams the later
12//! work needs — the KiCad importer stamps `Origin::Imported` and an
13//! `external_ref` of `Timer:NE555D`, a family stamps `Origin::Generated` — and
14//! a field added now costs one line, while a field added after parts exist
15//! costs a migration. Behaviour built ON them is NOT here.
16
17use std::collections::BTreeMap;
18
19use serde::{Deserialize, Serialize};
20
21/// Whole Unix seconds. The only time representation in the server: it
22/// serializes as a number, sorts correctly, and needs no date library.
23pub type Timestamp = u64;
24
25// ===========================================================================
26// Users, groups and sessions
27// ===========================================================================
28
29/// The built-in group names. Groups are plain strings on the user so an
30/// operator can invent more without a migration; these four are the ones the
31/// server itself checks.
32pub mod groups {
33 /// Full authority, including user and part-type administration.
34 pub const ADMIN: &str = "admin";
35 /// May release revisions and BREAK another user's lock — the "check-in
36 /// group" in the architecture.
37 pub const CHECKIN: &str = "checkin";
38 /// May create parts and drafts, and check out their own work.
39 pub const AUTHOR: &str = "author";
40 /// Read-only.
41 pub const VIEWER: &str = "viewer";
42 /// A headless CAD worker: may take bake jobs from the queue and write
43 /// their results (round 8). Nothing else — a worker account cannot
44 /// create parts or release anything.
45 pub const WORKER: &str = "worker";
46}
47
48/// One account. The password is never stored — only the PBKDF2 verifier in
49/// [`crate::auth`], which carries its own salt and iteration count so a later
50/// change of cost does not invalidate existing accounts.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct User {
53 pub id: String,
54 pub username: String,
55 #[serde(default)]
56 pub display_name: String,
57 #[serde(default)]
58 pub email: String,
59 /// `pbkdf2$<iterations>$<b64 salt>$<b64 hash>` — see [`crate::auth`].
60 pub password: String,
61 #[serde(default)]
62 pub groups: Vec<String>,
63 #[serde(default = "yes")]
64 pub active: bool,
65 pub created_at: Timestamp,
66}
67
68fn yes() -> bool {
69 true
70}
71
72impl User {
73 /// Whether this user is in `group`. `admin` answers yes to everything, so
74 /// no call site has to remember to check for it as well.
75 pub fn in_group(&self, group: &str) -> bool {
76 self.active
77 && (self.groups.iter().any(|g| g == group)
78 || self.groups.iter().any(|g| g == groups::ADMIN))
79 }
80
81 /// May create parts and revisions.
82 pub fn can_author(&self) -> bool {
83 self.in_group(groups::AUTHOR)
84 }
85
86 /// May release a revision and break another user's lock.
87 pub fn can_checkin(&self) -> bool {
88 self.in_group(groups::CHECKIN)
89 }
90
91 /// May administer users and part types.
92 pub fn is_admin(&self) -> bool {
93 self.in_group(groups::ADMIN)
94 }
95
96 /// May claim bake jobs and write their results.
97 pub fn can_bake(&self) -> bool {
98 self.in_group(groups::WORKER)
99 }
100}
101
102/// A logged-in browser. Sessions live in the database file like everything
103/// else, so a restarted server does not sign everyone out.
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct Session {
106 pub token: String,
107 pub user_id: String,
108 pub created_at: Timestamp,
109 pub last_seen: Timestamp,
110 /// The CSRF token of this session (synchronizer pattern): handed to the
111 /// page at sign-in and by `/api/me`, and required back in `X-CSRF-Token`
112 /// on every request that changes anything.
113 pub csrf: String,
114}
115
116/// What an API token may do. A token is how a caller that is not a browser —
117/// the CAD app, a bake worker, an organization's own script — signs in. It
118/// acts as the user who owns it, narrowed by its scope; it never acts as more.
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "lowercase")]
121pub enum TokenScope {
122 /// Everything its owner may do, except managing tokens and passwords.
123 #[default]
124 Full,
125 /// Only reads (`GET`).
126 Read,
127 /// Reads, the bake queue and the document store: what a headless CAD
128 /// worker needs and nothing more.
129 Worker,
130}
131
132impl TokenScope {
133 pub fn as_str(self) -> &'static str {
134 match self {
135 TokenScope::Full => "full",
136 TokenScope::Read => "read",
137 TokenScope::Worker => "worker",
138 }
139 }
140}
141
142/// A bearer token for a non-browser caller. The secret is shown ONCE, when it
143/// is created; the server keeps only its SHA-256 (the secret is 256 random
144/// bits, so a slow hash buys nothing) and its first characters, so a person
145/// can tell tokens apart in a list.
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct ApiToken {
148 pub id: String,
149 pub user_id: String,
150 /// What the owner called it ("bake worker on cad-01").
151 pub name: String,
152 pub scope: TokenScope,
153 /// Hex SHA-256 of the whole secret.
154 pub hash: String,
155 /// The secret's first characters, e.g. `plm_3fQ9`.
156 pub prefix: String,
157 pub created_at: Timestamp,
158 #[serde(default)]
159 pub last_used_at: Option<Timestamp>,
160 /// When it stops working; `None` never expires.
161 #[serde(default)]
162 pub expires_at: Option<Timestamp>,
163}
164
165// ===========================================================================
166// Part types — the configurable numbering scheme
167// ===========================================================================
168
169/// A class of part with its OWN numbering scheme. `CPART` + 9 digits is the
170/// seeded default, not a hard-coded rule: prefix and width are data, an
171/// operator adds more types, and [`format_number`](Self::format_number) is the
172/// one place a number is spelled.
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct PartType {
175 /// Stable key used in URLs and on parts (`"component"`).
176 pub id: String,
177 /// What the UI shows (`"Component"`).
178 pub name: String,
179 /// Literal text before the digits (`"CPART"`).
180 pub prefix: String,
181 /// How many digits follow the prefix. The formatted number is ALWAYS this
182 /// long — zero-padded — so every number of a type sorts as text.
183 pub digits: u32,
184 /// The next sequence value to hand out. Allocation bumps it. Used only in
185 /// [`NumberMode::Counter`]; the other modes keep it so switching back to a
186 /// counter resumes where it left off.
187 pub next: u64,
188 pub created_at: Timestamp,
189 /// How this type's numbers are made. Absent in a file written before modes
190 /// existed, which reads as the counter every type used to be.
191 #[serde(default)]
192 pub mode: NumberMode,
193}
194
195/// How a part type's numbers are made. In EVERY mode a number is unique
196/// across all parts, not only within its type — that check lives inside the
197/// store's write, not here.
198#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
199#[serde(tag = "kind", rename_all = "lowercase")]
200pub enum NumberMode {
201 /// `prefix` + `digits` + an auto-incrementing counter. A typed number is
202 /// refused: the counter owns the numbers of a counter type.
203 #[default]
204 Counter,
205 /// Any number the user types — e.g. the ERP purchasing number of a library
206 /// part.
207 Free,
208 /// A typed number that must match `regex` in full.
209 Pattern { regex: String },
210 /// The admin script at `script` (relative to the scripts directory)
211 /// validates the typed number or allocates one, through its `partNumber`
212 /// function.
213 Script { script: String },
214}
215
216impl NumberMode {
217 pub fn kind(&self) -> &'static str {
218 match self {
219 NumberMode::Counter => "counter",
220 NumberMode::Free => "free",
221 NumberMode::Pattern { .. } => "pattern",
222 NumberMode::Script { .. } => "script",
223 }
224 }
225}
226
227impl PartType {
228 /// Spell `sequence` as a part number of this type. The width comes from
229 /// `digits`, never from a literal.
230 pub fn format_number(&self, sequence: u64) -> String {
231 format!(
232 "{prefix}{sequence:0width$}",
233 prefix = self.prefix,
234 sequence = sequence,
235 width = self.digits as usize
236 )
237 }
238
239 /// The highest sequence this type can spell. `digits` 9 → 999_999_999.
240 pub fn capacity(&self) -> u64 {
241 10u64.saturating_pow(self.digits).saturating_sub(1)
242 }
243}
244
245// ===========================================================================
246// Parts and revisions
247// ===========================================================================
248
249/// Where a revision's content came from. Inert today (see the module header).
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
251#[serde(rename_all = "lowercase")]
252pub enum Origin {
253 /// A person made it in the CAD app.
254 #[default]
255 Authored,
256 /// A library import produced it (KiCad today).
257 Imported,
258 /// A part family generated it from a parameter tuple.
259 Generated,
260}
261
262/// What a part's document is for, shown by its file extension. Chosen when
263/// the part is created and NEVER changed: turning a normal part into a family
264/// means a new part.
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
266#[serde(rename_all = "lowercase")]
267pub enum DocumentClass {
268 /// `.nBREP` — placed as-is. Imported parts and family members are normal.
269 #[default]
270 Normal,
271 /// `.fBREP` — a family seed: the model plus the table of its members.
272 Family,
273 /// `.tBREP` — a template whose values are driven by expressions.
274 Template,
275}
276
277impl DocumentClass {
278 pub fn as_str(self) -> &'static str {
279 match self {
280 DocumentClass::Normal => "normal",
281 DocumentClass::Family => "family",
282 DocumentClass::Template => "template",
283 }
284 }
285
286 pub fn parse(text: &str) -> Option<Self> {
287 match text.trim().to_ascii_lowercase().trim_start_matches('.') {
288 "" | "normal" | "nbrep" => Some(DocumentClass::Normal),
289 "family" | "fbrep" => Some(DocumentClass::Family),
290 "template" | "tbrep" => Some(DocumentClass::Template),
291 _ => None,
292 }
293 }
294}
295
296/// The lifecycle states, in the order a revision moves through them.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "lowercase")]
299pub enum Lifecycle {
300 Draft,
301 InReview,
302 Released,
303 Superseded,
304 Obsolete,
305}
306
307impl Lifecycle {
308 /// Whether the revision's document may still be written. This is the ONE
309 /// predicate immutability rests on — see [`crate::lifecycle`].
310 pub fn is_editable(self) -> bool {
311 matches!(self, Lifecycle::Draft | Lifecycle::InReview)
312 }
313
314 pub fn as_str(self) -> &'static str {
315 match self {
316 Lifecycle::Draft => "draft",
317 Lifecycle::InReview => "inreview",
318 Lifecycle::Released => "released",
319 Lifecycle::Superseded => "superseded",
320 Lifecycle::Obsolete => "obsolete",
321 }
322 }
323}
324
325/// Who holds a draft revision checked out.
326///
327/// There is no lease and no expiry: the architecture chose MANUAL break, so a
328/// lock persists until its holder checks in or someone in the check-in group
329/// breaks it. `acquired_at` is what makes a stale lock visible to the person
330/// deciding whether to break it.
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct Lock {
333 pub user_id: String,
334 /// Which client of that user holds it — the same person can be in the
335 /// browser and the desktop build at once.
336 #[serde(default)]
337 pub client_id: String,
338 pub acquired_at: Timestamp,
339}
340
341/// One revision of a part: the released unit of engineering intent, and the
342/// thing a CAD document hangs off.
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct Revision {
345 /// Whether the saved document produces BREP faces. Derived, never user editable.
346 #[serde(default)]
347 pub has_geometry: bool,
348 /// Hash of the document used to derive geometry metadata.
349 #[serde(default)]
350 pub geometry_content_hash: String,
351 /// Values defined by this part's numbered PLM type, owned by this revision.
352 #[serde(default)]
353 pub attributes: BTreeMap<String, serde_json::Value>,
354 #[serde(default)]
355 pub attributes_initialized: bool,
356 /// Individual placements, identified by their CAD feature ids.
357 #[serde(default)]
358 pub occurrences: Vec<crate::bom_config::Occurrence>,
359 /// The revision label itself; its database key is (part_id, id).
360 pub id: String,
361 /// What people call it. FREE TEXT: whoever creates the revision may type it,
362 /// and the store enforces only that it is unique within its part. `A, B, C`
363 /// from [`crate::lifecycle::next_revision_label`] is the suggestion when
364 /// nobody types one. Revisions are ordered by creation — their position in
365 /// [`Part::revisions`] — never by label.
366 pub label: String,
367 pub lifecycle: Lifecycle,
368 #[serde(default)]
369 pub origin: Origin,
370 /// SHA-256 of the document as last written, so a client can detect drift
371 /// without fetching the payload. Empty until something is written.
372 #[serde(default)]
373 pub content_hash: String,
374 #[serde(default)]
375 pub size: u64,
376 /// `None` when nobody has it checked out.
377 #[serde(default)]
378 pub lock: Option<Lock>,
379 pub created_by: String,
380 pub created_at: Timestamp,
381 #[serde(default)]
382 pub modified_at: Timestamp,
383 #[serde(default)]
384 pub released_by: Option<String>,
385 #[serde(default)]
386 pub released_at: Option<Timestamp>,
387 /// Set on a family member's revision by Generate: which family row made
388 /// it, and the fingerprints the next Generate compares to skip an
389 /// unchanged row. `None` for anything a family did not write.
390 #[serde(default, skip_serializing_if = "Option::is_none")]
391 pub family: Option<FamilyStamp>,
392 /// Set on the first revision of a part spun out of a template.
393 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub template: Option<TemplateStamp>,
395 /// The bake this revision's document is waiting for, or had. `None` for
396 /// a document nothing asked to be baked.
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub bake: Option<Bake>,
399 /// What this revision is built from: the "uses" list the CAD app
400 /// publishes on save and release (round 1). The server never reads
401 /// geometry — this list IS the assembly structure, and the BOM,
402 /// where-used and the release gate are all computed from it. Frozen with
403 /// the document once the revision is released.
404 #[serde(default, skip_serializing_if = "Vec::is_empty")]
405 pub uses: Vec<Use>,
406 /// Every review this revision has been through, oldest first: the last
407 /// one is the current round ([`Review`]). A revision is reviewed where it
408 /// lives, so a review costs what its part costs to write.
409 #[serde(default, skip_serializing_if = "Vec::is_empty")]
410 pub reviews: Vec<Review>,
411 /// The discussion on this revision, oldest first; a reply names the
412 /// comment it answers. Anyone who can read the part reads it.
413 #[serde(default, skip_serializing_if = "Vec::is_empty")]
414 pub comments: Vec<Comment>,
415 /// Files that belong to THIS revision — its drawing, its test report.
416 /// Frozen with the revision at release, like its document; a new revision
417 /// starts with the same references (the files are shared, not copied).
418 #[serde(default, skip_serializing_if = "Vec::is_empty")]
419 pub attachments: Vec<Attachment>,
420 /// A picture of the document, made and uploaded by a CAD client or the
421 /// bake worker (the server never renders). It describes the document
422 /// whose hash it carries: once the document changes it is stale, and
423 /// [`crate::thumbnail::current`] no longer serves it.
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 pub thumbnail: Option<Thumbnail>,
426}
427
428/// A revision's thumbnail: a PNG blob beside the attachments, keyed by the
429/// document it pictures.
430#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
431pub struct Thumbnail {
432 /// Lower-case hex SHA-256 of the PNG, and the blob's name.
433 pub sha256: String,
434 pub size: u64,
435 pub width: u32,
436 pub height: u32,
437 /// The revision's `content_hash` when the picture was made.
438 pub content_hash: String,
439 /// The producer's renderer version (`brep-thumb/1`).
440 pub renderer: String,
441 pub uploaded_by: String,
442 pub uploaded_at: Timestamp,
443}
444
445/// A file attached to a part or to one of its revisions.
446///
447/// The bytes live once under `<data>/blobs/`, named by their SHA-256, so two
448/// references to the same file share them; this record is the reference.
449/// A blob goes when the last reference to it does.
450#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
451pub struct Attachment {
452 pub id: String,
453 /// The file name shown and offered on download.
454 pub name: String,
455 /// What the uploader said it is (`application/pdf`). Only a short list of
456 /// safe types is ever shown inline; everything else downloads.
457 pub media_type: String,
458 pub size: u64,
459 /// Lower-case hex SHA-256 of the bytes, and the blob's name.
460 pub sha256: String,
461 /// `datasheet`, `drawing`, `spec`, `image` or `other`.
462 #[serde(default = "other_kind")]
463 pub kind: String,
464 #[serde(default, skip_serializing_if = "String::is_empty")]
465 pub note: String,
466 pub uploaded_by: String,
467 pub uploaded_at: Timestamp,
468}
469
470fn other_kind() -> String {
471 "other".to_string()
472}
473
474/// One line of an assembly revision's "uses" list: which part, which of its
475/// revisions, and how many.
476///
477/// Every occurrence of the same part and revision in the CAD document folds
478/// into ONE line with their count as `quantity`; two lines for the same child
479/// differ in revision or find number.
480#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
481pub struct Use {
482 /// The child [`Part`], by id.
483 pub part: String,
484 /// The child revision, by id — PINNED. Empty is a FLOATING reference:
485 /// whatever revision of the child is currently released (else its newest),
486 /// resolved each time the BOM is read.
487 #[serde(default)]
488 pub revision: String,
489 /// How many per ONE of the parent. Greater than zero; fractional for
490 /// things bought by length or weight.
491 #[serde(default = "one")]
492 pub quantity: f64,
493 /// What `quantity` counts: `each` unless it says otherwise (`mm`, `g`).
494 #[serde(default = "each")]
495 pub unit: String,
496 /// The balloon number on the drawing, when there is one.
497 #[serde(default, skip_serializing_if = "String::is_empty")]
498 pub find_number: String,
499 /// Reference designators (`R1, R2`) or occurrence names, free text.
500 #[serde(default, skip_serializing_if = "String::is_empty")]
501 pub reference: String,
502 #[serde(default, skip_serializing_if = "String::is_empty")]
503 pub notes: String,
504}
505
506fn one() -> f64 {
507 1.0
508}
509
510fn each() -> String {
511 "each".to_string()
512}
513
514impl Revision {
515 /// A new, empty draft.
516 pub fn draft(id: String, label: String, created_by: String, stamp: Timestamp) -> Self {
517 Revision {
518 has_geometry: false,
519 geometry_content_hash: String::new(),
520 attributes: BTreeMap::new(),
521 attributes_initialized: false,
522 occurrences: Vec::new(),
523 id,
524 label,
525 lifecycle: Lifecycle::Draft,
526 origin: Origin::default(),
527 content_hash: String::new(),
528 size: 0,
529 lock: None,
530 created_by,
531 created_at: stamp,
532 modified_at: stamp,
533 released_by: None,
534 released_at: None,
535 family: None,
536 template: None,
537 bake: None,
538 uses: Vec::new(),
539 reviews: Vec::new(),
540 comments: Vec::new(),
541 attachments: Vec::new(),
542 thumbnail: None,
543 }
544 }
545
546 /// The current review round: the last one, whatever its status.
547 pub fn review(&self) -> Option<&Review> {
548 self.reviews.last()
549 }
550
551 /// The current review round, if it is still undecided or approved —
552 /// the one a decision or a release acts on.
553 pub fn live_review_mut(&mut self) -> Option<&mut Review> {
554 self.reviews.last_mut().filter(|r| r.is_live())
555 }
556
557 /// The document still waits for a bake — queued, taken, or failed. A
558 /// revision in this state cannot release: once released its bytes are
559 /// frozen and the bake could never be written.
560 pub fn needs_bake(&self) -> bool {
561 self.bake.as_ref().is_some_and(|bake| bake.status != BakeStatus::Done)
562 }
563
564 /// The store key this revision's document lives at — the key the CAD app's
565 /// `sourceKey` becomes. `part/<part id>/rev/<revision id>`.
566 pub fn document_key(&self, part_id: &str) -> String {
567 crate::identity::document_key(part_id, &self.id)
568 }
569}
570
571/// A part: permanent identity, the number, and its revisions oldest-first.
572#[derive(Debug, Clone, Serialize, Deserialize)]
573pub struct Part {
574 /// The part number itself, stored directly as the database primary key.
575 pub id: String,
576 /// The number (`CPART000000001`, or whatever the type's mode accepted).
577 /// Unique across the server, compared without regard to ASCII case.
578 pub number: String,
579 /// Which [`PartType`] minted or accepted the number.
580 pub part_type: String,
581 /// The counter value the number was spelled from, kept so a renumbering or
582 /// an audit does not have to re-parse the string. `0` for a number that
583 /// did not come from a counter.
584 pub sequence: u64,
585 /// What the part's document is for. Fixed at creation.
586 #[serde(default)]
587 pub document_class: DocumentClass,
588 pub name: String,
589 #[serde(default)]
590 pub description: String,
591 /// The part's ONE primary [`Category`], by id. Empty is uncategorized.
592 /// A value that names no category — text written before the catalog
593 /// existed — loads as-is and reads as uncategorized; it is replaced the
594 /// next time someone sets the category.
595 #[serde(default)]
596 pub category: String,
597 #[serde(default)]
598 pub tags: Vec<String>,
599 /// The upstream library identity for an imported part (`"Timer:NE555D"`),
600 /// which is what makes a re-import idempotent. Inert today.
601 #[serde(default)]
602 pub external_ref: String,
603 /// Catalog attribute values, keyed by [`AttributeDef::key`]. Checked
604 /// against the category's schema when written; COMPLETE (every required
605 /// key present) only at release, because a draft may be unfinished. A
606 /// value whose key the current category does not define is kept — moving
607 /// a part between categories never throws data away — and is inert.
608 #[serde(default)]
609 pub attributes: BTreeMap<String, serde_json::Value>,
610 /// Who makes this part and who sells it: the approved manufacturer parts,
611 /// each with its supplier offers. Part-level, like `attributes`, and NOT
612 /// frozen by [`Settings::lock_released_attributes`] — sourcing changes
613 /// with the market, not with the design.
614 #[serde(default)]
615 pub sourcing: Vec<ManufacturerPart>,
616 /// For a family or a template: the part type its generated parts are
617 /// created in — a family's new members, a template's spin-outs. Empty
618 /// means the family's or template's own type. Inert on a normal part.
619 #[serde(default)]
620 pub member_part_type: String,
621 /// Files that belong to the part whatever its revision — a datasheet, a
622 /// supplier drawing. Not frozen by a release: like sourcing, they follow
623 /// the part, not one design of it. See [`Attachment`].
624 #[serde(default, skip_serializing_if = "Vec::is_empty")]
625 pub attachments: Vec<Attachment>,
626 pub created_by: String,
627 pub created_at: Timestamp,
628 #[serde(default)]
629 pub revisions: Vec<Revision>,
630}
631
632impl Part {
633 pub fn revision(&self, revision_id: &str) -> Option<&Revision> {
634 self.revisions.iter().find(|r| r.id == revision_id)
635 }
636
637 pub fn revision_mut(&mut self, revision_id: &str) -> Option<&mut Revision> {
638 self.revisions.iter_mut().find(|r| r.id == revision_id)
639 }
640
641 /// The newest revision, whatever its state. "Newest" is creation order —
642 /// the list's order — because a free-text label says nothing about age.
643 pub fn latest(&self) -> Option<&Revision> {
644 self.revisions.last()
645 }
646
647 /// The revision labelled `label`, compared without regard to ASCII case —
648 /// `a` and `A` would be two revisions nobody could tell apart aloud.
649 pub fn revision_by_label(&self, label: &str) -> Option<&Revision> {
650 let label = label.trim();
651 self.revisions
652 .iter()
653 .find(|r| r.label.eq_ignore_ascii_case(label))
654 }
655
656 /// The first revision still in work (Draft or InReview), if any. Whether a
657 /// second may be started beside it is the administrator's
658 /// [`Settings::allow_multiple_open_drafts`].
659 pub fn open_draft(&self) -> Option<&Revision> {
660 self.revisions.iter().find(|r| r.lifecycle.is_editable())
661 }
662
663 /// The revision currently Released. A release supersedes every other, so
664 /// there is at most one.
665 pub fn current_release(&self) -> Option<&Revision> {
666 self.revisions.iter().rev().find(|r| r.lifecycle == Lifecycle::Released)
667 }
668
669 /// Whether [`Settings::lock_released_attributes`] would freeze this part's
670 /// catalog values: some revision has been released (whatever it is now),
671 /// and none is in work to carry a change.
672 pub fn catalog_frozen(&self) -> bool {
673 self.revisions.iter().any(|r| r.released_at.is_some()) && self.open_draft().is_none()
674 }
675}
676
677// ===========================================================================
678// Families, templates and the bake queue
679// ===========================================================================
680
681/// What a family's Generate records on a member revision. The document
682/// carries the CAD app's own `familySource` stamp; this is the server's
683/// copy, which is what the family view and the next Generate read without
684/// opening every member document.
685#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
686pub struct FamilyStamp {
687 /// The family part's id.
688 pub family_part: String,
689 /// The family revision whose document the member was generated from.
690 pub family_revision: String,
691 /// The row's values, expression source keyed by expression name.
692 #[serde(default)]
693 pub values: BTreeMap<String, String>,
694 #[serde(default)]
695 pub description: String,
696 /// The CAD app's `row_hash` of the row: part number, description, values.
697 pub values_hash: String,
698 /// The CAD app's `history_hash` of the family: its model less the table.
699 pub history_hash: String,
700 /// [`Revision::content_hash`] of the document as Generate (or its bake)
701 /// wrote it. A member whose hash has moved on since was edited by hand.
702 pub generated_hash: String,
703 pub generated_by: String,
704 pub generated_at: Timestamp,
705}
706
707/// What a template spin-out records on the new part's first revision.
708#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
709pub struct TemplateStamp {
710 pub template_part: String,
711 pub template_revision: String,
712 /// The input values the copy was made with.
713 #[serde(default)]
714 pub values: BTreeMap<String, String>,
715 /// The CAD app's `template_hash` of the template document at the time.
716 pub content_hash: String,
717 pub created_at: Timestamp,
718}
719
720/// Where a bake is. The server never links the kernel, so a document it
721/// assembled (a family member, a template copy) is checked and rebuilt by a
722/// headless CAD worker, which takes the job from the queue.
723#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
724#[serde(rename_all = "lowercase")]
725pub enum BakeStatus {
726 /// Waiting for a worker.
727 Pending,
728 /// A worker has it (see [`Bake::claimed_at`] for the lease).
729 Claimed,
730 /// The worker reported a problem; a person retries it.
731 Failed,
732 /// Baked, or superseded by a document someone saved.
733 Done,
734}
735
736impl BakeStatus {
737 pub fn as_str(self) -> &'static str {
738 match self {
739 BakeStatus::Pending => "pending",
740 BakeStatus::Claimed => "claimed",
741 BakeStatus::Failed => "failed",
742 BakeStatus::Done => "done",
743 }
744 }
745}
746
747/// One revision's bake job. The job's id is the revision's id: a revision has
748/// at most one.
749#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
750pub struct Bake {
751 /// A Force resave job rebuilds this exact saved document. Older generated
752 /// jobs have no snapshot hash and retain their existing bake behavior.
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub resave_hash: Option<String>,
755 pub status: BakeStatus,
756 /// Why it was queued ("generated from family CPART000000012 row M6x20").
757 #[serde(default)]
758 pub reason: String,
759 pub requested_by: String,
760 pub requested_at: Timestamp,
761 #[serde(default)]
762 pub claimed_by: Option<String>,
763 #[serde(default)]
764 pub claimed_at: Option<Timestamp>,
765 /// How many times a worker has taken it.
766 #[serde(default)]
767 pub attempts: u32,
768 /// The worker's report of the last failure.
769 #[serde(default)]
770 pub error: String,
771 #[serde(default)]
772 pub finished_by: Option<String>,
773 #[serde(default)]
774 pub finished_at: Option<Timestamp>,
775}
776
777// ===========================================================================
778// Sourcing — manufacturers, suppliers, and what each offers for a part
779// ===========================================================================
780
781/// A manufacturer or a supplier. The two are separate lists (round 1)
782/// even though they share a shape: a manufacturer part names a
783/// manufacturer, an offer names a supplier, and a company that is both —
784/// one that sells what it makes — appears in each list.
785#[derive(Debug, Clone, Serialize, Deserialize)]
786pub struct Company {
787 /// Generated; never shown to a person.
788 pub id: String,
789 /// Unique within its list, compared without regard to ASCII case.
790 pub name: String,
791 #[serde(default)]
792 pub website: String,
793 #[serde(default)]
794 pub notes: String,
795 #[serde(default)]
796 pub created_at: Timestamp,
797}
798
799/// Where a manufacturer part stands in its maker's catalogue.
800#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
801#[serde(rename_all = "lowercase")]
802pub enum SourcingStatus {
803 #[default]
804 Active,
805 /// Not recommended for new designs.
806 Nrnd,
807 Obsolete,
808}
809
810impl SourcingStatus {
811 pub fn as_str(self) -> &'static str {
812 match self {
813 SourcingStatus::Active => "active",
814 SourcingStatus::Nrnd => "nrnd",
815 SourcingStatus::Obsolete => "obsolete",
816 }
817 }
818}
819
820/// One manufacturer's part that satisfies one of our parts: the MPN.
821#[derive(Debug, Clone, Serialize, Deserialize)]
822pub struct ManufacturerPart {
823 pub id: String,
824 /// The [`Company`] id in the manufacturers list.
825 pub manufacturer: String,
826 /// The manufacturer's part number. Unique per manufacturer within one
827 /// part, compared without regard to ASCII case.
828 pub mpn: String,
829 #[serde(default)]
830 pub status: SourcingStatus,
831 /// The one to buy first. At most one per part.
832 #[serde(default)]
833 pub preferred: bool,
834 #[serde(default)]
835 pub datasheet: String,
836 #[serde(default)]
837 pub notes: String,
838 /// Who sells this MPN, and on what terms.
839 #[serde(default)]
840 pub offers: Vec<SupplierOffer>,
841 #[serde(default)]
842 pub created_at: Timestamp,
843}
844
845/// One supplier's offer for one manufacturer part.
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct SupplierOffer {
848 pub id: String,
849 /// The [`Company`] id in the suppliers list.
850 pub supplier: String,
851 /// The supplier's own part number (SPN).
852 #[serde(default)]
853 pub spn: String,
854 #[serde(default)]
855 pub url: String,
856 /// A currency code as the supplier quotes it (`USD`). Text, not a list:
857 /// nothing here converts between currencies.
858 #[serde(default)]
859 pub currency: String,
860 /// Unit price by quantity, ascending by `qty`.
861 #[serde(default)]
862 pub price_breaks: Vec<PriceBreak>,
863 #[serde(default)]
864 pub lead_time_days: Option<u32>,
865 /// Minimum order quantity.
866 #[serde(default)]
867 pub moq: Option<u64>,
868 /// Stock on hand when last checked, if known.
869 #[serde(default)]
870 pub stock: Option<u64>,
871 #[serde(default)]
872 pub notes: String,
873 /// When the offer was last written — how stale the price is.
874 #[serde(default)]
875 pub updated_at: Timestamp,
876}
877
878/// Buy at least `qty` and each costs `unit_price`.
879#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
880pub struct PriceBreak {
881 pub qty: u64,
882 pub unit_price: f64,
883}
884
885// ===========================================================================
886// The audit log — who changed what, and when
887// ===========================================================================
888
889/// Who made a change.
890#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
891pub struct Actor {
892 /// The user's id; empty for the server itself.
893 #[serde(default)]
894 pub user_id: String,
895 /// The username at the time, kept so the log reads right after a rename
896 /// or a deletion.
897 #[serde(default)]
898 pub username: String,
899 /// How the change arrived: `session` (a browser), `token` (an API token),
900 /// or `system` (the server itself, or a caller with no signed-in user —
901 /// start-up, a test, a sign-in before it succeeds).
902 #[serde(default)]
903 pub via: String,
904 /// The client's address, when the request carried one.
905 #[serde(default, skip_serializing_if = "String::is_empty")]
906 pub ip: String,
907}
908
909impl Actor {
910 /// The server itself.
911 pub fn system() -> Self {
912 Actor { user_id: String::new(), username: String::new(), via: "system".into(), ip: String::new() }
913 }
914}
915
916/// What a change was made to.
917#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
918pub struct EntityRef {
919 /// `part`, `revision`, `user`, `token`, `part-type`, `category`,
920 /// `manufacturer`, `supplier`, `settings`, `script` — or, for a
921 /// collection a later slice adds, its name in the store.
922 pub kind: String,
923 pub id: String,
924 /// What a person calls it: a part number, `CPART000000001 rev B`, a
925 /// username, a category name.
926 #[serde(default)]
927 pub label: String,
928 /// For a revision, its part's id, so a part's history includes its
929 /// revisions' events.
930 #[serde(default, skip_serializing_if = "String::is_empty")]
931 pub part_id: String,
932}
933
934/// One field's value before and after. `null` on a side where the field did
935/// not exist.
936#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
937pub struct FieldChange {
938 pub before: serde_json::Value,
939 pub after: serde_json::Value,
940}
941
942/// One entry of the audit log. Append-only: nothing edits or deletes one.
943#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
944pub struct AuditEvent {
945 /// 1, 2, 3 … in the order events were written.
946 pub id: u64,
947 pub at: Timestamp,
948 pub actor: Actor,
949 /// What happened: `create`, `update`, `delete`, `release`, `checkout`,
950 /// `checkin`, `break-lock`, `document`, `uses`, `sourcing`, `sign-in`,
951 /// `sign-in-failed`, `session-ended`, `script-write`, … See
952 /// `crate::audit` for the full list.
953 pub action: String,
954 pub entity: EntityRef,
955 /// The fields that changed. Secrets (password verifiers, token hashes)
956 /// appear as `"(changed)"`, never as their value.
957 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
958 pub changes: BTreeMap<String, FieldChange>,
959 /// A sentence, for events a field diff does not explain.
960 #[serde(default, skip_serializing_if = "String::is_empty")]
961 pub detail: String,
962 /// The store's sequence number after the change; 0 for an event that
963 /// changed nothing in the store (a failed sign-in, a script file).
964 #[serde(default)]
965 pub seq: u64,
966}
967
968// ===========================================================================
969// Review and approval
970// ===========================================================================
971
972/// Where a review round stands.
973#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
974#[serde(rename_all = "lowercase")]
975pub enum ReviewStatus {
976 /// Waiting for approvals.
977 #[default]
978 Open,
979 /// Its rule is met: enough approvals, no rejection. It may still be
980 /// rejected until the subject is released.
981 Approved,
982 /// A reviewer rejected it; the subject went back to Draft. Final.
983 Rejected,
984 /// The subject was pulled back to Draft by its author. Final.
985 Withdrawn,
986}
987
988impl ReviewStatus {
989 pub fn as_str(self) -> &'static str {
990 match self {
991 ReviewStatus::Open => "open",
992 ReviewStatus::Approved => "approved",
993 ReviewStatus::Rejected => "rejected",
994 ReviewStatus::Withdrawn => "withdrawn",
995 }
996 }
997}
998
999/// Who may review: one user, or everyone in a group.
1000#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1001pub struct ReviewerRef {
1002 /// `user` or `group`.
1003 pub kind: ReviewerKind,
1004 /// A user's id, or a group's name.
1005 pub id: String,
1006}
1007
1008#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1009#[serde(rename_all = "lowercase")]
1010pub enum ReviewerKind {
1011 User,
1012 Group,
1013}
1014
1015/// A reviewer's verdict.
1016#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1017#[serde(rename_all = "lowercase")]
1018pub enum Verdict {
1019 Approve,
1020 Reject,
1021}
1022
1023impl Verdict {
1024 pub fn as_str(self) -> &'static str {
1025 match self {
1026 Verdict::Approve => "approve",
1027 Verdict::Reject => "reject",
1028 }
1029 }
1030}
1031
1032/// One reviewer's decision. A rejection always carries a comment.
1033#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1034pub struct Decision {
1035 pub user_id: String,
1036 pub verdict: Verdict,
1037 #[serde(default, skip_serializing_if = "String::is_empty")]
1038 pub comment: String,
1039 pub at: Timestamp,
1040 /// The document hash approved or rejected by this decision.
1041 pub content_hash: String,
1042}
1043
1044impl Decision {
1045 /// Whether this decision was given on the subject as it is now.
1046 pub fn is_current(&self, current: &str) -> bool {
1047 self.content_hash == current
1048 }
1049}
1050
1051/// One round of review of a revision, opened when its
1052/// subject moves to review.
1053///
1054/// The rule it is judged by is COPIED in when it opens (`required_approvals`,
1055/// `reviewers`, `allow_self_approval`): an administrator changing the
1056/// settings afterwards changes the next round, not one already under way.
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1058pub struct Review {
1059 pub id: String,
1060 #[serde(default)]
1061 pub status: ReviewStatus,
1062 /// Who submitted the subject for review.
1063 pub opened_by: String,
1064 pub opened_at: Timestamp,
1065 /// Who may approve or reject. Empty: anyone in the check-in group.
1066 #[serde(default)]
1067 pub reviewers: Vec<ReviewerRef>,
1068 /// Approvals needed before the subject may release. 0 means none.
1069 #[serde(default)]
1070 pub required_approvals: u32,
1071 /// Whether the person who submitted it may approve it themselves.
1072 #[serde(default)]
1073 pub allow_self_approval: bool,
1074 #[serde(default, skip_serializing_if = "Option::is_none")]
1075 pub due: Option<Timestamp>,
1076 /// What decided the rule: `settings`, `part-type:<id>`,
1077 /// `category:<id>`, and `+script` when the reviewers hook changed it.
1078 #[serde(default)]
1079 pub rule_source: String,
1080 #[serde(default)]
1081 pub decisions: Vec<Decision>,
1082 /// Set when the round ends: a rejection, a withdrawal, or the release it
1083 /// allowed.
1084 #[serde(default, skip_serializing_if = "Option::is_none")]
1085 pub closed_by: Option<String>,
1086 #[serde(default, skip_serializing_if = "Option::is_none")]
1087 pub closed_at: Option<Timestamp>,
1088}
1089
1090impl Review {
1091 /// Still deciding, or approved and not yet used: a decision or a
1092 /// release may act on it.
1093 pub fn is_live(&self) -> bool {
1094 matches!(self.status, ReviewStatus::Open | ReviewStatus::Approved) && self.closed_at.is_none()
1095 }
1096
1097 /// Each user's LATEST decision, if it is an approval that the rule lets
1098 /// count (never the submitter's unless the rule allows it) — whatever
1099 /// version it was given on.
1100 fn standing_approvals(&self) -> Vec<&Decision> {
1101 let mut latest: Vec<&Decision> = Vec::new();
1102 for decision in &self.decisions {
1103 latest.retain(|d| d.user_id != decision.user_id);
1104 latest.push(decision);
1105 }
1106 latest
1107 .into_iter()
1108 .filter(|d| d.verdict == Verdict::Approve && (self.allow_self_approval || d.user_id != self.opened_by))
1109 .collect()
1110 }
1111
1112 /// The users whose approval counts: a standing approval given on the
1113 /// subject as it is now, `current` being its content hash.
1114 pub fn approvers(&self, current: &str) -> Vec<&str> {
1115 self.standing_approvals().into_iter().filter(|d| d.is_current(current)).map(|d| d.user_id.as_str()).collect()
1116 }
1117
1118 /// Standing approvals given on an older version of the subject: they need renewing to count.
1119 pub fn stale_approvers(&self, current: &str) -> Vec<&str> {
1120 self.standing_approvals().into_iter().filter(|d| !d.is_current(current)).map(|d| d.user_id.as_str()).collect()
1121 }
1122
1123 /// Whether the rule is met on the subject as it is now: enough current
1124 /// approvals, and no rejection.
1125 pub fn is_met(&self, current: &str) -> bool {
1126 !self.decisions.iter().any(|d| d.verdict == Verdict::Reject)
1127 && self.approvers(current).len() as u32 >= self.required_approvals
1128 }
1129}
1130
1131/// A comment on a revision.
1132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1133pub struct Comment {
1134 pub id: String,
1135 pub author: String,
1136 pub at: Timestamp,
1137 pub body: String,
1138 /// The comment this one answers; empty for a new thread.
1139 #[serde(default, skip_serializing_if = "String::is_empty")]
1140 pub parent: String,
1141}
1142
1143/// The rule a review round is opened with.
1144#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1145#[serde(default)]
1146pub struct ReviewRule {
1147 /// Approvals needed before release. 0 — the default — means a release
1148 /// needs no review at all, as before reviews existed.
1149 pub required_approvals: u32,
1150 /// Who may decide. Empty: anyone in the check-in group.
1151 pub reviewers: Vec<ReviewerRef>,
1152 /// Days from submission to the due date; 0 for none.
1153 pub due_days: u32,
1154 /// Whether the submitter's own approval counts.
1155 pub allow_self_approval: bool,
1156}
1157
1158/// A rule for the parts of one part type, or of one category and every
1159/// category under it. A category's beats a part type's, and the nearest
1160/// category beats its ancestors.
1161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1162pub struct ReviewOverride {
1163 /// `part_type` or `category`.
1164 pub scope: String,
1165 pub id: String,
1166 pub rule: ReviewRule,
1167}
1168
1169// ===========================================================================
1170// Server settings — the administrator's policy choices
1171// ===========================================================================
1172
1173/// Configurable names and availability of workflow status options.
1174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1175pub struct StatusOption {
1176 pub state: Lifecycle,
1177 pub name: String,
1178 pub enabled: bool,
1179}
1180
1181pub fn default_status_options() -> Vec<StatusOption> {
1182 [(Lifecycle::Draft, "none"), (Lifecycle::InReview, "review"),
1183 (Lifecycle::Released, "released"), (Lifecycle::Obsolete, "obsolete"),
1184 (Lifecycle::Superseded, "superseded")].into_iter()
1185 .map(|(state, name)| StatusOption { state, name: name.into(), enabled: true }).collect()
1186}
1187
1188/// Policy the administrator decides, not code (round 7). Each defaults
1189/// to the PERMISSIVE choice, and a file written before settings existed
1190/// loads with those defaults.
1191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1192#[serde(default)]
1193pub struct Settings {
1194 pub setup_completed: bool,
1195 pub status_options: Vec<StatusOption>,
1196 /// Refuse changes to a part's category and attribute values while the
1197 /// part has no revision in work and at least one released one — so a
1198 /// released part's catalog values change only by starting a new revision.
1199 /// Off by default: attributes stay editable after release.
1200 pub lock_released_attributes: bool,
1201 /// Let a part have more than one revision in work (Draft or InReview) at
1202 /// once. On by default, which is what lets a family row create the
1203 /// revision it names while another is open.
1204 pub allow_multiple_open_drafts: bool,
1205 /// Refuse to release an assembly revision while anything in its "uses"
1206 /// list is not Released — the classic release gate. Off by default: the
1207 /// release goes ahead and says which children are unreleased.
1208 pub require_released_children: bool,
1209 /// A browser session ends after this many minutes without a request.
1210 /// 14 days by default, which is what sessions lasted before this setting.
1211 pub session_idle_minutes: u64,
1212 /// A browser session ends this many hours after sign-in however busy it
1213 /// is. 30 days by default; 0 means no absolute limit.
1214 pub session_max_hours: u64,
1215 /// Let administrators edit and test-run scripts in the browser. On by
1216 /// default. Scripts are fully trusted, so an admin login with the
1217 /// editor on is a shell on the server; turning it off leaves the
1218 /// scripts directory live and editable only on the host. The server's
1219 /// `--lock-script-editor` flag forces it off regardless.
1220 pub script_editor_enabled: bool,
1221 /// The review rule for a revision whose part no override covers. The
1222 /// default needs 0 approvals, so a release works as it did before
1223 /// reviews existed until an administrator sets one.
1224 pub review_rule: ReviewRule,
1225 /// Rules for particular part types and categories ([`ReviewOverride`]).
1226 pub review_overrides: Vec<ReviewOverride>,
1227 /// Let a signed-in user browse (read only) other users' workspaces
1228 /// ([`WorkspaceEntry`]). On by default, the permissive choice of rounds
1229 /// 6-7: a workspace holds links to parts everyone may already read, and
1230 /// files a colleague often needs to see (a customer's photo of a
1231 /// failure). Off, a workspace is its owner's alone; an administrator can
1232 /// still read any, to support a user.
1233 pub workspaces_browsable: bool,
1234}
1235
1236impl Default for Settings {
1237 fn default() -> Self {
1238 Self {
1239 setup_completed: false,
1240 status_options: default_status_options(),
1241 lock_released_attributes: false,
1242 allow_multiple_open_drafts: true,
1243 require_released_children: false,
1244 session_idle_minutes: 14 * 24 * 60,
1245 session_max_hours: 30 * 24,
1246 script_editor_enabled: true,
1247 review_rule: ReviewRule::default(),
1248 review_overrides: Vec::new(),
1249 workspaces_browsable: true,
1250 }
1251 }
1252}
1253
1254// ===========================================================================
1255// Workspaces — each user's folders of links and files (plm-cad-integration D12)
1256// ===========================================================================
1257
1258/// One entry of a user's workspace: a folder, a link to a part, or a file.
1259///
1260/// A workspace replaces directories in PLM mode. It is a tree per user,
1261/// stored flat: each entry names its parent folder (empty at the top). A
1262/// link is never a copy of the part; deleting one never touches the part. A
1263/// file's bytes are blobs in the attachment store, and every replace keeps
1264/// the version before it ([`FileVersion`]).
1265#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1266pub struct WorkspaceEntry {
1267 pub id: String,
1268 /// The user whose workspace this is.
1269 pub owner: String,
1270 /// The folder it is in; empty at the top of the workspace.
1271 #[serde(default)]
1272 pub parent: String,
1273 /// Unique among its folder's entries, ignoring ASCII case.
1274 pub name: String,
1275 pub kind: WorkspaceKind,
1276 /// For a link: the part, and the revision it is pinned to.
1277 #[serde(default, skip_serializing_if = "Option::is_none")]
1278 pub link: Option<WorkspaceLink>,
1279 /// For a file: every version, oldest first; the last is current.
1280 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1281 pub versions: Vec<FileVersion>,
1282 pub created_at: Timestamp,
1283 #[serde(default)]
1284 pub modified_at: Timestamp,
1285}
1286
1287#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1288#[serde(rename_all = "lowercase")]
1289pub enum WorkspaceKind {
1290 Folder,
1291 Link,
1292 File,
1293}
1294
1295impl WorkspaceKind {
1296 pub fn as_str(self) -> &'static str {
1297 match self {
1298 WorkspaceKind::Folder => "folder",
1299 WorkspaceKind::Link => "link",
1300 WorkspaceKind::File => "file",
1301 }
1302 }
1303}
1304
1305/// What a link points at. Held by id, so a part renamed or renumbered is
1306/// still found.
1307#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1308pub struct WorkspaceLink {
1309 pub part_id: String,
1310 /// Empty: the link follows the part's newest revision, drafts included
1311 /// (D13). Else the revision it is pinned to.
1312 #[serde(default)]
1313 pub revision_id: String,
1314}
1315
1316/// One version of a workspace file.
1317#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1318pub struct FileVersion {
1319 /// 1, 2, 3 … in upload order; never reused.
1320 pub version: u32,
1321 pub sha256: String,
1322 pub size: u64,
1323 pub media_type: String,
1324 pub uploaded_by: String,
1325 pub uploaded_at: Timestamp,
1326 /// The version this one restored, when it was made by a restore.
1327 #[serde(default, skip_serializing_if = "Option::is_none")]
1328 pub restored_from: Option<u32>,
1329}
1330
1331// ===========================================================================
1332// The catalog — categories and their typed attribute schemas
1333// ===========================================================================
1334
1335/// A node of the catalog tree. A part has ONE primary category plus free tags
1336/// (round 1). A child category INHERITS every attribute of its ancestors and
1337/// may add its own, but may not redefine one — so "Fasteners" can require a
1338/// material and "Fasteners/Screws" add a thread without ever disagreeing
1339/// about what a material is.
1340#[derive(Debug, Clone, Serialize, Deserialize)]
1341pub struct Category {
1342 /// Stable key, stored on parts (`"screws"`). Never changes.
1343 pub id: String,
1344 /// What the UI shows (`"Screws"`).
1345 pub name: String,
1346 /// The parent's id; empty for a top-level category.
1347 #[serde(default)]
1348 pub parent: String,
1349 /// The attributes THIS category adds. Its effective schema is these plus
1350 /// every ancestor's.
1351 #[serde(default)]
1352 pub attributes: Vec<AttributeDef>,
1353 #[serde(default)]
1354 pub created_at: Timestamp,
1355}
1356
1357/// One typed attribute a category defines.
1358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1359pub struct AttributeDef {
1360 /// The key values are stored under on a part (`"thread"`).
1361 pub key: String,
1362 /// What the UI shows (`"Thread size"`).
1363 pub name: String,
1364 #[serde(flatten)]
1365 pub kind: AttributeKind,
1366 /// Must have a value before a revision of the part can release. A draft
1367 /// may leave it empty.
1368 #[serde(default)]
1369 pub required: bool,
1370}
1371
1372/// What values an attribute takes. Serialized under `type`, beside the
1373/// attribute's other fields: `{"key":"length","name":"Length","type":"number","unit":"mm"}`.
1374#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1375#[serde(tag = "type", rename_all = "lowercase")]
1376pub enum AttributeKind {
1377 Text,
1378 /// A number. `unit` is a label the UI shows, not a conversion.
1379 Number {
1380 #[serde(default)]
1381 unit: String,
1382 },
1383 Bool,
1384 /// One of a fixed list of values.
1385 Enum { values: Vec<String> },
1386}
1387
1388impl AttributeKind {
1389 pub fn as_str(&self) -> &'static str {
1390 match self {
1391 AttributeKind::Text => "text",
1392 AttributeKind::Number { .. } => "number",
1393 AttributeKind::Bool => "bool",
1394 AttributeKind::Enum { .. } => "enum",
1395 }
1396 }
1397}
1398