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