Skip to main content

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