1use std::collections::{BTreeMap, BTreeSet};
48use std::fs;
49use std::io;
50use std::path::{Path, PathBuf};
51use std::sync::{Arc, RwLock};
52
53use serde::{Deserialize, Serialize};
54use serde_json::{json, Value};
55
56use crate::audit::{self, AuditFilter, AuditSink};
57use crate::auth;
58use crate::bom;
59use crate::catalog;
60use crate::lifecycle;
61use crate::model::{
62 groups, ApiToken, AttributeDef, AuditEvent, EntityRef, Category, Company, DocumentClass, Lifecycle, Lock, NumberMode, Part, PartType, Revision, Session, Settings,
63 Timestamp, Use, User,
64};
65use crate::scripting::{self, HookResult, Scripts};
66use crate::security::{Security, ServerConfig};
67use crate::sourcing;
68use crate::sql::{self, Durability, Sql};
69use crate::table::Parts;
70use crate::Error;
71
72pub const CHANGE_LOG_LIMIT: usize = 4096;
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct Change {
79 pub seq: u64,
80 pub key: String,
81}
82
83#[derive(Debug, Default, Serialize, Deserialize)]
86pub struct State {
87 #[serde(default)]
88 pub workflows: Vec<crate::workflow::Definition>,
89 #[serde(default)]
90 pub workflow_runs: Vec<crate::workflow::Run>,
91 #[serde(default)]
92 pub bom_configuration: crate::bom_config::Configuration,
93 #[serde(default)]
94 pub seq: u64,
95 #[serde(default)]
96 pub users: Vec<User>,
97 #[serde(default)]
101 pub sessions: crate::journal::Journaled<Session>,
102 #[serde(default)]
104 pub api_tokens: Vec<ApiToken>,
105 #[serde(default)]
106 pub part_types: Vec<PartType>,
107 #[serde(default)]
108 pub parts: Parts,
109 #[serde(default)]
111 pub categories: Vec<Category>,
112 #[serde(default)]
114 pub manufacturers: Vec<Company>,
115 #[serde(default)]
117 pub suppliers: Vec<Company>,
118 #[serde(default)]
120 pub settings: Settings,
121 #[serde(default)]
122 pub changes: Vec<Change>,
123 #[serde(default)]
129 pub changes_from: u64,
130 #[serde(default)]
132 pub change_orders: Vec<crate::model::ChangeOrder>,
133 #[serde(default)]
136 pub eco_numbering: crate::model::EcoNumbering,
137 #[serde(default)]
140 pub workspace: crate::workspace::Workspace,
141}
142
143impl State {
144 pub(crate) fn touch_part(&mut self, part_id: &str) {
150 let keys: Vec<String> = self
151 .part(part_id)
152 .map(|part| part.revisions.iter().map(|r| r.document_key(&part.id)).collect())
153 .unwrap_or_default();
154 for key in keys {
155 self.touch(key);
156 }
157 }
158
159 pub(crate) fn touch(&mut self, key: String) {
162 let seq = self.seq;
163 self.changes.retain(|change| change.key != key);
164 self.changes.push(Change { seq, key });
165 if self.changes.len() > CHANGE_LOG_LIMIT {
166 let excess = self.changes.len() - CHANGE_LOG_LIMIT;
167 let dropped: Vec<Change> = self.changes.drain(..excess).collect();
168 if let Some(last) = dropped.last() {
169 self.changes_from = self.changes_from.max(last.seq);
170 }
171 }
172 }
173
174 pub fn user(&self, id: &str) -> Option<&User> {
175 self.users.iter().find(|u| u.id == id)
176 }
177
178 pub fn user_by_name(&self, username: &str) -> Option<&User> {
179 let username = username.trim().to_ascii_lowercase();
180 self.users
181 .iter()
182 .find(|u| u.username.to_ascii_lowercase() == username)
183 }
184
185 pub fn part(&self, id: &str) -> Option<&Part> {
186 self.parts.get(id)
187 }
188
189 pub fn part_type(&self, id: &str) -> Option<&PartType> {
190 self.part_types.iter().find(|t| t.id == id)
191 }
192
193 pub fn part_by_id_or_number(&self, key: &str) -> Option<&Part> {
195 let key = key.trim();
196 self.part(key).or_else(|| self.part_with_number(key))
197 }
198
199 pub fn part_with_number(&self, number: &str) -> Option<&Part> {
204 let number = number.trim();
205 self.parts.iter().find(|p| p.number.eq_ignore_ascii_case(number))
206 }
207
208 pub fn changes_floor(&self) -> u64 {
211 self.changes_from
212 }
213}
214
215#[derive(Clone)]
222pub struct Db {
223 root: PathBuf,
224 state: Arc<RwLock<State>>,
225 scripts: Arc<Scripts>,
226 security: Arc<Security>,
227 sql: Arc<Sql>,
229 _lock: Arc<crate::dirlock::DirLock>,
232 backups: Arc<crate::backup::Status>,
234 pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
235}
236
237pub fn now() -> Timestamp {
239 std::time::SystemTime::now()
240 .duration_since(std::time::UNIX_EPOCH)
241 .map(|d| d.as_secs())
242 .unwrap_or(0)
243}
244
245impl Db {
246 pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
253 Self::open_with_scripts(root, None)
254 }
255
256 pub fn open_with_scripts(
260 root: impl Into<PathBuf>,
261 scripts: Option<PathBuf>,
262 ) -> io::Result<(Self, Option<String>)> {
263 Self::open_with(root, scripts, Durability::Full)
264 }
265
266 pub fn open_with(
269 root: impl Into<PathBuf>,
270 scripts: Option<PathBuf>,
271 durability: Durability,
272 ) -> io::Result<(Self, Option<String>)> {
273 let root = root.into();
274 let lock = crate::dirlock::DirLock::acquire(&root)?;
278 fs::create_dir_all(root.join("models"))?;
279 let scripts = Scripts::new(scripts.unwrap_or_else(|| root.join("scripts")))?;
280 if let Some(report) = migrate_files(&root, false)? {
281 eprintln!("brep-plm: {report}");
282 }
283 let sql = Sql::open_with(root.join(SQLITE_FILE), durability).map_err(io::Error::other)?;
284 let loaded = sql.load().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
285 let fresh = loaded.is_none();
286 let mut state = loaded.unwrap_or_default();
287 if state.parts.iter().any(|p| p.id != p.number || p.revisions.iter().any(|r| r.id != r.label)) {
288 return Err(io::Error::new(io::ErrorKind::InvalidData,
289 "legacy opaque model IDs are no longer supported; stop the server and reset its data directory"));
290 }
291 let before = sql::small_value(&mut state);
292
293 let mut seeded = None;
294 if state.part_types.is_empty() {
295 state.part_types.push(PartType {
298 id: "component".into(),
299 name: "Component".into(),
300 prefix: "CPART".into(),
301 digits: 9,
302 next: 1,
303 created_at: now(),
304 mode: Default::default(),
305 });
306 }
307 if state.users.is_empty() {
308 let password = auth::random_token(12);
309 state.users.push(User {
310 id: auth::new_id(),
311 username: "admin".into(),
312 display_name: "Administrator".into(),
313 email: String::new(),
314 password: auth::hash_password(&password),
315 groups: vec![groups::ADMIN.into()],
316 active: true,
317 created_at: now(),
318 });
319 seeded = Some(password);
320 }
321 let after = sql::small_value(&mut state);
322 if fresh || before != after {
323 let change = sql::Change {
324 before: &if fresh { Value::Object(Default::default()) } else { before },
325 after: &after,
326 parts: Vec::new(),
327 categories: &state.categories,
328 reindex: Vec::new(),
329 all_parts: &state.parts,
330 workspace: Vec::new(),
331 sessions: Vec::new(),
332 };
333 sql.write(&change, Vec::new()).map_err(io::Error::other)?;
334 }
335
336 let db = Db {
337 root,
338 state: Arc::new(RwLock::new(state)),
339 scripts: Arc::new(scripts),
340 security: Arc::new(Security::default()),
341 sql: Arc::new(sql),
342 _lock: Arc::new(lock),
343 backups: Arc::new(crate::backup::Status::default()),
344 bake_worker: Arc::new(crate::bake_worker::Controller::default()),
345 };
346 match db.sweep_blobs() {
349 Ok(0) => {}
350 Ok(n) => eprintln!("brep-plm: removed {n} unreferenced attachment file(s)"),
351 Err(error) => eprintln!("brep-plm: could not sweep attachment files: {error}"),
352 }
353 db.initialize_geometry().map_err(io::Error::other)?;
354 db.initialize_bom_occurrences().map_err(io::Error::other)?;
355 db.recover_workflows().map_err(io::Error::other)?;
356 Ok((db, seeded))
357 }
358
359 fn initialize_geometry(&self) -> Result<(), Error> {
362 let pending = self.read(|state| state.parts.iter().flat_map(|p| p.revisions.iter()
363 .filter(|r| !r.content_hash.is_empty() && r.geometry_content_hash != r.content_hash)
364 .map(|r| (p.id.clone(), r.id.clone(), r.content_hash.clone(), r.document_key(&p.id))))
365 .collect::<Vec<_>>());
366 if pending.is_empty() { return Ok(()); }
367 let mut updates = Vec::new();
368 for (part, revision, hash, key) in pending {
369 let body = self.read_document(&key)?.unwrap_or_default();
370 updates.push((part, revision, hash, crate::geometry::contains_geometry(&body)));
371 }
372 self.mutate(|state| {
373 for (part, revision, hash, geometry) in updates {
374 let r = find_revision_mut(state, &part, &revision)?.1;
375 if r.content_hash == hash { r.has_geometry = geometry; r.geometry_content_hash = hash; }
376 state.touch(crate::identity::document_key(&part, &revision));
377 }
378 Ok(())
379 })
380 }
381
382 pub fn root(&self) -> &Path {
385 &self.root
386 }
387
388 pub fn stop_bake_worker(&self) -> Result<crate::bake_worker::Status, Error> {
390 self.bake_worker.stop(self.security.config.bake_worker.as_ref())
391 }
392
393 pub fn scripts(&self) -> &Scripts {
394 &self.scripts
395 }
396
397 pub fn with_config(mut self, config: ServerConfig) -> Self {
400 self.security = Arc::new(Security { config, ..Security::default() });
401 self
402 }
403
404 pub fn backups(&self) -> &crate::backup::Status {
406 &self.backups
407 }
408
409 pub fn security(&self) -> &Security {
411 &self.security
412 }
413
414 pub fn script_editor_allowed(&self) -> bool {
417 !self.security.config.lock_script_editor && self.read(|state| state.settings.script_editor_enabled)
418 }
419
420 pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
422 let state = self.state.read().unwrap_or_else(|e| e.into_inner());
423 f(&state)
424 }
425
426 pub fn mutate<R>(&self, f: impl FnOnce(&mut State) -> Result<R, Error>) -> Result<R, Error> {
443 let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
444 let before = sql::small_value(&mut state);
445 state.parts.begin();
446 state.workspace.begin();
447 state.sessions.begin();
448 state.seq += 1;
449 match f(&mut state) {
450 Ok(value) => {
451 let touched = state.parts.commit();
452 let entries = state.workspace.commit();
453 let sessions = state.sessions.commit();
454 match self.persist(&mut state, &before, &touched, &entries, &sessions) {
455 Ok(()) => Ok(value),
456 Err(error) => {
457 state.parts.undo(touched);
458 state.workspace.undo(entries);
459 state.sessions.undo(sessions);
460 restore_small(&mut state, &before)?;
461 Err(error)
462 }
463 }
464 }
465 Err(error) => {
466 state.parts.rollback();
467 state.workspace.rollback();
468 state.sessions.rollback();
469 restore_small(&mut state, &before)?;
470 Err(error)
471 }
472 }
473 }
474
475 fn persist(
477 &self,
478 state: &mut State,
479 before: &Value,
480 touched: &[crate::table::Touched],
481 entries: &[crate::journal::Touched<crate::model::WorkspaceEntry>],
482 sessions: &[crate::journal::Touched<Session>],
483 ) -> Result<(), Error> {
484 let after = sql::small_value(state);
485 let mut old_parts = Vec::new();
488 let mut new_parts = Vec::new();
489 let mut changed = Vec::new();
490 for t in touched {
491 let now_part = &state.parts[t.position];
492 let now_value = serde_json::to_value(now_part).map_err(Error::internal)?;
493 let was_value = match &t.before {
494 Some(part) => Some(serde_json::to_value(part).map_err(Error::internal)?),
495 None => None,
496 };
497 if was_value.as_ref() == Some(&now_value) {
498 continue;
499 }
500 old_parts.extend(was_value);
501 new_parts.push(now_value);
502 changed.push((t.position, now_part));
503 }
504 let (old_entries, new_entries, workspace) = journal_rows(&state.workspace, entries)?;
507 let (old_sessions, new_sessions, session_rows) = journal_rows(&state.sessions, sessions)?;
508 let mut old = before.clone();
509 let mut new = after.clone();
510 if let (Some(o), Some(n)) = (old.as_object_mut(), new.as_object_mut()) {
511 o.insert("parts".into(), Value::Array(old_parts));
512 n.insert("parts".into(), Value::Array(new_parts));
513 o.insert("workspace".into(), Value::Array(old_entries));
514 n.insert("workspace".into(), Value::Array(new_entries));
515 o.insert("sessions".into(), Value::Array(old_sessions));
516 n.insert("sessions".into(), Value::Array(new_sessions));
517 }
518 let events = audit::refine(audit::diff(&old, &new, &audit::current_actor(), now(), state.seq));
519 let mut reindex = Vec::new();
523 if before.get("categories") != after.get("categories") {
524 let old_categories: Vec<Category> =
525 serde_json::from_value(before.get("categories").cloned().unwrap_or_default()).unwrap_or_default();
526 let moved: BTreeSet<String> = old_categories
527 .iter()
528 .chain(state.categories.iter())
529 .map(|c| c.id.to_ascii_lowercase())
530 .filter(|id| catalog::path_name(&old_categories, id) != catalog::path_name(&state.categories, id))
531 .collect();
532 reindex = state
533 .parts
534 .iter()
535 .enumerate()
536 .filter(|(_, p)| moved.contains(&p.category.to_ascii_lowercase()))
537 .map(|(i, _)| i)
538 .collect();
539 }
540 let change = sql::Change {
541 before,
542 after: &after,
543 parts: changed,
544 categories: &state.categories,
545 reindex,
546 all_parts: &state.parts,
547 workspace,
548 sessions: session_rows,
549 };
550 self.sql.write(&change, events).map(|_| ()).map_err(|error| {
551 if sql::is_constraint(&error) {
552 Error::conflict(format!("the store refused the change: {error}"))
553 } else {
554 Error::internal(error)
555 }
556 })
557 }
558
559 pub fn record(&self, action: &str, entity: EntityRef, detail: impl Into<String>) {
562 let event = AuditEvent {
563 id: 0,
564 at: now(),
565 actor: audit::current_actor(),
566 action: action.to_string(),
567 entity,
568 changes: BTreeMap::new(),
569 detail: detail.into(),
570 seq: 0,
571 };
572 if let Err(error) = self.sql.append(vec![event]) {
573 eprintln!("brep-plm: audit: could not append to the log: {error}");
574 }
575 }
576
577 pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
579 self.sql.query(filter).map_err(Error::internal)
580 }
581
582 pub fn sql(&self) -> &Sql {
584 &self.sql
585 }
586
587 pub(crate) fn document_path(&self, key: &str) -> Result<PathBuf, Error> {
590 let (part, revision) = crate::identity::split_key(key)
591 .ok_or_else(|| Error::bad_request(format!("'{key}' is not a usable document key")))?;
592 Ok(self.root.join(crate::identity::model_path(&part, &revision)))
593 }
594
595 pub fn read_document(&self, key: &str) -> Result<Option<String>, Error> {
597 let path = self.document_path(key)?;
598 match fs::read_to_string(path) {
599 Ok(text) => Ok(Some(text)),
600 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
601 Err(error) => Err(Error::internal(error)),
602 }
603 }
604
605 pub fn write_document(&self, part_id: &str, revision_id: &str, body: &str) -> Result<u64, Error> {
619 self.write_document_inner(part_id, revision_id, body, None)
620 }
621
622 pub fn write_import_document(&self, user: &User, part_id: &str, revision_id: &str, expected_hash: &str, body: &str, uses: &Value) -> Result<u64, Error> {
626 self.write_document_inner(part_id, revision_id, body, Some((user, expected_hash, uses)))
627 }
628
629 fn write_document_inner(&self, part_id: &str, revision_id: &str, body: &str, import: Option<(&User, &str, &Value)>) -> Result<u64, Error> {
630 let key = crate::identity::document_key(part_id, revision_id);
631 let path = self.document_path(&key)?;
632 let hash = auth::content_hash(body);
633 let embedded = crate::thumbnail::embedded(self.root(), body)?;
634 let has_geometry = crate::geometry::contains_geometry(body);
635 self.mutate(move |state| {
636 let imported_uses = if let Some((user, expected, uses)) = import {
637 check_writable(state, user, part_id, revision_id)?;
638 let revision = state.part(part_id).and_then(|p| p.revision(revision_id))
639 .ok_or_else(|| Error::not_found("revision"))?;
640 if revision.content_hash != expected {
641 return Err(Error::conflict("the document changed since the import was reviewed; review it again"));
642 }
643 Some(bom::check_uses(state, part_id, uses)?)
644 } else { None };
645 let current = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
646 let defs = state.bom_configuration.part_fields.get(¤t.part_type).cloned().unwrap_or_default();
647 let mut canonical = current.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?.clone();
648 if let Ok(document) = serde_json::from_str::<Value>(body) {
649 if let Some(occurrences) = crate::bom_config::document_occurrences(&document) {
650 if let Some(occurrences) = crate::bom_config::capture_occurrences(state, part_id, revision_id, &json!({"occurrences":occurrences}))? {
651 canonical.occurrences = occurrences;
652 }
653 }
654 }
655 let normalized = if !defs.is_empty() || !canonical.occurrences.is_empty() {
656 let mut document: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("A CAD document must be JSON"))?;
657 let original = document.clone();
658 if !canonical.attributes_initialized && !defs.is_empty() {
659 for def in &defs {
660 if let Some(value) = document["partAttributes"].as_object().and_then(|attrs|attrs.iter().find(|(key,_)|key.to_ascii_lowercase()==def.key).map(|(_,value)|value)) {
661 if let Some(value) = catalog::check_value(def, value).map_err(Error::bad_request)? {
662 canonical.attributes.insert(def.key.clone(), value);
663 }
664 }
665 }
666 canonical.attributes_initialized = true;
667 }
668 crate::bom_config::overlay(&canonical, &defs, &mut document);
669 if document != original {Some(serde_json::to_string(&document).map_err(Error::internal)?)} else {None}
670 } else { None };
671 let body = normalized.as_deref().unwrap_or(body);
672 let hash = if normalized.is_some() { auth::content_hash(body) } else { hash };
673 let size = body.len() as u64;
674 let part = state.parts.get_mut(&part_id)
675 .ok_or_else(|| Error::not_found("part"))?;
676 let number = part.number.clone();
677 let revision = part
678 .revision_mut(revision_id)
679 .ok_or_else(|| Error::not_found("revision"))?;
680 if !revision.lifecycle.is_editable() {
681 return Err(Error::conflict(format!(
682 "{number} revision {} is {} and cannot be written — start a new revision",
683 revision.label,
684 revision.lifecycle.as_str()
685 )));
686 }
687 if let Some(parent) = path.parent() {
688 fs::create_dir_all(parent).map_err(Error::internal)?;
689 }
690 let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
691 let thumbnail = embedded.as_ref().map(|image| {
692 let user = import.map(|(user, _, _)| user.id.as_str())
693 .or_else(|| revision.lock.as_ref().map(|lock| lock.user_id.as_str()))
694 .unwrap_or(&revision.created_by);
695 image.place(self.root(), &hash, user)
696 }).transpose()?;
697 revision.attributes = canonical.attributes;
698 revision.attributes_initialized = canonical.attributes_initialized;
699 revision.occurrences = canonical.occurrences;
700 write_atomic(&path, body).map_err(Error::internal)?;
701 if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
702 if let Some(uses) = imported_uses {
703 revision.uses = uses;
704 }
705 revision.has_geometry = has_geometry;
706 revision.geometry_content_hash = hash.clone();
707 revision.content_hash = hash;
708 revision.size = size;
709 revision.modified_at = now();
710 if revision.needs_bake() {
714 if let Some(bake) = revision.bake.as_mut() {
715 bake.status = crate::model::BakeStatus::Done;
716 bake.error = "superseded by a saved document".into();
717 bake.finished_by = None;
718 bake.finished_at = Some(now());
719 }
720 }
721 crate::review::document_changed(state, part_id, revision_id);
723 state.touch(key);
724 if embedded.is_some() {
725 if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
726 }
727 Ok(state.seq)
728 })
729 }
730
731 pub fn remove_document(&self, key: &str) -> Result<(), Error> {
734 let path = self.document_path(key)?;
735 match fs::remove_file(path) {
736 Ok(()) => Ok(()),
737 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
738 Err(error) => Err(Error::internal(error)),
739 }
740 }
741}
742
743pub const SQLITE_FILE: &str = "plm.sqlite";
745
746pub fn session_expired(settings: &Settings, session: &Session, now: Timestamp) -> bool {
751 let idle = now.saturating_sub(session.last_seen) > settings.session_idle_minutes.saturating_mul(60);
752 let old = settings.session_max_hours > 0
753 && now.saturating_sub(session.created_at) > settings.session_max_hours.saturating_mul(3600);
754 idle || old
755}
756
757impl Db {
758 pub fn prune_sessions(&self) -> Result<usize, Error> {
772 let at = now();
773 let expired = self.read(|state| state.sessions.iter().filter(|s| session_expired(&state.settings, s, at)).count());
774 if expired == 0 {
775 return Ok(0);
776 }
777 audit::as_actor(crate::model::Actor::system(), || {
778 self.mutate(move |state| {
779 let settings = state.settings.clone();
780 let before = state.sessions.len();
781 state.sessions.retain(|s| !session_expired(&settings, s, at));
782 Ok(before - state.sessions.len())
783 })
784 })
785 }
786}
787
788#[allow(clippy::type_complexity)]
792fn journal_rows<'a, T>(
793 list: &'a crate::journal::Journaled<T>,
794 touched: &'a [crate::journal::Touched<T>],
795) -> Result<(Vec<Value>, Vec<Value>, Vec<(String, Option<&'a T>)>), Error>
796where
797 T: crate::journal::Keyed + Clone + PartialEq + Serialize,
798{
799 let mut old = Vec::new();
800 let mut new = Vec::new();
801 let mut rows = Vec::new();
802 for (t, now) in list.changed(touched) {
803 old.extend(t.before.as_ref().map(serde_json::to_value).transpose().map_err(Error::internal)?);
804 new.extend(now.map(serde_json::to_value).transpose().map_err(Error::internal)?);
805 rows.push((t.key.clone(), now));
806 }
807 Ok((old, new, rows))
808}
809
810fn restore_small(state: &mut State, before: &Value) -> Result<(), Error> {
811 let parts = std::mem::take(&mut state.parts);
812 let workspace = std::mem::take(&mut state.workspace);
813 let sessions = std::mem::take(&mut state.sessions);
814 *state = serde_json::from_value(before.clone()).map_err(Error::internal)?;
815 state.parts = parts;
816 state.workspace = workspace;
817 state.sessions = sessions;
818 Ok(())
819}
820
821pub fn migrate_files(root: &Path, dry_run: bool) -> io::Result<Option<String>> {
835 let json = root.join("plm.json");
836 let audit_file = root.join("audit.jsonl");
837 let sqlite = root.join(SQLITE_FILE);
838 let stamp = now();
839 if sqlite.exists() {
840 if json.exists() && !dry_run {
841 let migrated = Sql::open(&sqlite).and_then(|sql| sql.meta("migrated_from")).map_err(io::Error::other)?;
842 if migrated.is_some() {
843 fs::rename(&json, root.join(format!("plm.json.migrated-{stamp}")))?;
844 if audit_file.exists() {
845 fs::rename(&audit_file, root.join(format!("audit.jsonl.migrated-{stamp}")))?;
846 }
847 return Ok(Some("moved aside a plm.json left by an interrupted migration".into()));
848 }
849 }
850 return Ok(None);
851 }
852 if !json.exists() {
853 return Ok(None);
854 }
855 let text = fs::read_to_string(&json)?;
856 let mut state: State = serde_json::from_str(&text)
857 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{json:?}: {e}")))?;
858 let mut events = Vec::new();
859 let mut skipped = 0usize;
860 if audit_file.exists() {
861 use std::io::BufRead;
862 for line in io::BufReader::new(fs::File::open(&audit_file)?).lines() {
863 let line = line?;
864 if line.trim().is_empty() {
865 continue;
866 }
867 match serde_json::from_str::<AuditEvent>(&line) {
868 Ok(event) => events.push(event),
869 Err(_) => skipped += 1,
872 }
873 }
874 }
875 let building = if dry_run {
876 std::env::temp_dir().join(format!("brep-plm-dry-run-{}-{stamp}.sqlite", std::process::id()))
877 } else {
878 root.join("plm.sqlite.migrating")
879 };
880 let remove_building = |path: &Path| {
881 for suffix in ["", "-wal", "-shm"] {
882 let _ = fs::remove_file(format!("{}{suffix}", path.display()));
883 }
884 };
885 remove_building(&building);
886 let event_count = events.len();
887 let counts = {
888 let sql = Sql::open(&building).map_err(io::Error::other)?;
889 sql.import(&mut state, events).map_err(io::Error::other)?;
890 sql.set_meta(
891 "migrated_from",
892 &json!({ "at": stamp, "plm_json_bytes": text.len(), "audit_events": event_count, "audit_lines_skipped": skipped })
893 .to_string(),
894 )
895 .map_err(io::Error::other)?;
896 sql.checkpoint().map_err(io::Error::other)?;
897 sql.counts().map_err(io::Error::other)?
898 };
899 let summary: Vec<String> = counts.iter().map(|(table, n)| format!("{table} {n}")).collect();
900 let mut report = format!(
901 "{} plm.json{} into {}: {}",
902 if dry_run { "dry run: would import" } else { "imported" },
903 if audit_file.exists() { " and audit.jsonl" } else { "" },
904 SQLITE_FILE,
905 summary.join(", ")
906 );
907 if skipped > 0 {
908 report.push_str(&format!(" ({skipped} unreadable audit line(s) skipped)"));
909 }
910 if dry_run {
911 remove_building(&building);
912 return Ok(Some(report));
913 }
914 for suffix in ["-wal", "-shm"] {
915 let _ = fs::remove_file(format!("{}{suffix}", building.display()));
916 }
917 fs::rename(&building, &sqlite)?;
918 fs::rename(&json, root.join(format!("plm.json.migrated-{stamp}")))?;
919 if audit_file.exists() {
920 fs::rename(&audit_file, root.join(format!("audit.jsonl.migrated-{stamp}")))?;
921 }
922 report.push_str(&format!("; the old files are now *.migrated-{stamp}"));
923 Ok(Some(report))
924}
925
926pub(crate) fn write_atomic(path: &Path, body: &str) -> io::Result<()> {
929 let temp = path.with_extension("tmp");
930 fs::write(&temp, body)?;
931 fs::rename(&temp, path)
932}
933
934impl Db {
939 pub fn create_part(
942 &self,
943 author: &User,
944 part_type_id: &str,
945 name: &str,
946 description: &str,
947 category: &str,
948 ) -> Result<Part, Error> {
949 self.create_part_with(
950 author,
951 &PartSpec {
952 part_type: part_type_id.to_string(),
953 name: name.to_string(),
954 description: description.to_string(),
955 category: category.to_string(),
956 ..PartSpec::default()
957 },
958 )
959 }
960
961 pub fn create_part_with(&self, author: &User, spec: &PartSpec) -> Result<Part, Error> {
970 check_origin(spec.origin)?;
971 let external_ref = spec.external_ref.trim().to_string();
972 let origin = spec.origin;
973 let name = spec.name.trim().to_string();
974 if name.is_empty() {
975 return Err(Error::bad_request("a part needs a name"));
976 }
977 let kind = self
978 .read(|state| state.part_type(&spec.part_type).cloned())
979 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", spec.part_type)))?;
980 let typed = spec.number.trim().to_string();
981 let tags = catalog::tidy_tags(spec.tags.iter().cloned());
982 let part_view = json!({
983 "name": name,
984 "description": spec.description.trim(),
985 "category": spec.category.trim(),
986 "tags": tags,
987 "attributes": spec.attributes,
988 "document_class": spec.document_class,
989 });
990
991 let given: Option<String> = match &kind.mode {
992 NumberMode::Counter => {
993 if !typed.is_empty() {
994 return Err(Error::bad_request(format!(
995 "part type '{}' numbers by its counter — leave the number empty",
996 kind.id
997 )));
998 }
999 None
1000 }
1001 NumberMode::Free => {
1002 if typed.is_empty() {
1003 return Err(Error::bad_request(format!(
1004 "part type '{}' takes the number you type — enter one",
1005 kind.id
1006 )));
1007 }
1008 Some(typed)
1009 }
1010 NumberMode::Pattern { regex } => {
1011 let pattern = full_match(regex)?;
1012 if typed.is_empty() {
1013 return Err(Error::bad_request(format!(
1014 "part type '{}' takes a typed number matching {regex} — enter one",
1015 kind.id
1016 )));
1017 }
1018 if !pattern.is_match(&typed) {
1019 return Err(Error::bad_request(format!(
1020 "'{typed}' does not match part type '{}' ({regex})",
1021 kind.id
1022 )));
1023 }
1024 Some(typed)
1025 }
1026 NumberMode::Script { script } => {
1027 let input = json!({
1028 "requested": typed,
1029 "partType": kind,
1030 "part": part_view,
1031 "user": scripting::user_json(author),
1032 });
1033 let answer = match scripting::run(self, author, script, "partNumber", &input)? {
1034 HookResult::Absent => {
1035 return Err(Error::conflict(format!(
1036 "part type '{}' numbers by the script '{script}', which is not in the scripts directory",
1037 kind.id
1038 )))
1039 }
1040 HookResult::Refused(failure) => {
1041 return Err(Error::conflict(format!("{script}: {}", failure.message)))
1042 }
1043 HookResult::Returned(success) => success.value,
1044 };
1045 let number = scripting::string_answer(&answer, "number").ok_or_else(|| {
1046 Error::conflict(format!(
1047 "{script}: partNumber() must return the number, or {{ number }} — it returned {answer}"
1048 ))
1049 })?;
1050 if spec.exact && !number.eq_ignore_ascii_case(&typed) {
1051 return Err(Error::conflict(format!(
1052 "{script} would number it {number}, not {typed} — a family row names its own number"
1053 )));
1054 }
1055 Some(number)
1056 }
1057 };
1058 if let Some(number) = &given {
1059 check_number(number)?;
1060 }
1061
1062 let requested_label = spec.label.trim().to_string();
1063 let label = self.decide_label(author, None, &part_view, &requested_label, "A")?;
1064 if spec.exact {
1065 exact_label(&requested_label, &label)?;
1066 }
1067
1068 let author_id = author.id.clone();
1069 let document_class = spec.document_class;
1070 let description = spec.description.trim().to_string();
1071 let requested_category = spec.category.trim().to_string();
1072 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1073 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1074 }
1075 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1076 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1077 }
1078 let requested_values = spec.attributes.clone();
1079 let workspace = spec.workspace.clone();
1080 self.mutate(move |state| {
1081 let category = known_category(&state.categories, &requested_category)?;
1084 let mut attributes = BTreeMap::new();
1085 catalog::apply_values(&state.categories, &category, &mut attributes, &requested_values)?;
1086 let current = state
1087 .part_types
1088 .iter_mut()
1089 .find(|t| t.id == kind.id)
1090 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", kind.id)))?;
1091 if current.mode != kind.mode {
1092 return Err(Error::conflict(format!(
1093 "part type '{}' changed its numbering while this part was being created — try again",
1094 kind.id
1095 )));
1096 }
1097 let (number, sequence) = match given {
1098 Some(number) => (number, 0),
1099 None => {
1100 let mut sequence = current.next;
1103 let mut number = current.format_number(sequence);
1104 while sequence <= current.capacity()
1105 && state_has_number(&state.parts, &number)
1106 {
1107 sequence += 1;
1108 number = current.format_number(sequence);
1109 }
1110 if sequence > current.capacity() {
1111 return Err(Error::conflict(format!(
1112 "part type '{}' is exhausted: {} digits cannot spell {}",
1113 current.id, current.digits, sequence
1114 )));
1115 }
1116 current.next = sequence + 1;
1117 (number, sequence)
1118 }
1119 };
1120 if let Some(owner) = state.part_with_number(&number) {
1121 return Err(Error::conflict(format!(
1122 "part number {number} already exists ({})",
1123 owner.name
1124 )));
1125 }
1126
1127 external_ref_clash(state, &kind.id, &external_ref, "")?;
1128 let stamp = now();
1129 let mut revision = Revision::draft(label.clone(), label, author_id.clone(), stamp);
1130 revision.origin = origin;
1131 let part = Part {
1132 id: number.clone(),
1133 number,
1134 part_type: kind.id.clone(),
1135 sequence,
1136 document_class,
1137 name,
1138 description,
1139 category,
1140 tags,
1141 external_ref,
1142 attributes,
1143 sourcing: Vec::new(),
1144 member_part_type: String::new(),
1145 attachments: Vec::new(),
1146 created_by: author_id,
1147 created_at: stamp,
1148 revisions: vec![revision],
1149 };
1150 state.parts.push(part.clone());
1151 state.touch(part.revisions[0].document_key(&part.id));
1152 if let Some(folder) = &workspace {
1153 crate::workspace::link_new_part(state, &part.created_by, folder, &part)?;
1154 }
1155 Ok(part)
1156 })
1157 }
1158
1159 fn decide_label(
1162 &self,
1163 user: &User,
1164 part: Option<&Part>,
1165 part_view: &Value,
1166 requested: &str,
1167 suggested: &str,
1168 ) -> Result<String, Error> {
1169 let existing: Vec<&str> = part
1170 .map(|p| p.revisions.iter().map(|r| r.label.as_str()).collect())
1171 .unwrap_or_default();
1172 let input = json!({
1173 "requested": requested,
1174 "suggested": suggested,
1175 "existing": existing,
1176 "part": part.map(|p| serde_json::to_value(p).unwrap_or(Value::Null)).unwrap_or_else(|| part_view.clone()),
1177 "user": scripting::user_json(user),
1178 });
1179 let label = match scripting::run(self, user, scripting::REVISION_LABEL, "revisionLabel", &input)? {
1180 HookResult::Absent => {
1181 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1182 }
1183 HookResult::Refused(failure) => {
1184 return Err(Error::conflict(format!("{}: {}", scripting::REVISION_LABEL, failure.message)))
1185 }
1186 HookResult::Returned(success) => match &success.value {
1187 Value::Null => {
1189 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1190 }
1191 other => scripting::string_answer(other, "label").ok_or_else(|| {
1192 Error::conflict(format!(
1193 "{}: revisionLabel() must return the label, or {{ label }} — it returned {other}",
1194 scripting::REVISION_LABEL
1195 ))
1196 })?,
1197 },
1198 };
1199 check_label(&label)?;
1200 Ok(label)
1201 }
1202
1203 pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
1205 self.create_revision_labelled(author, part_id, "")
1206 }
1207
1208 pub fn create_revision_labelled(
1221 &self,
1222 author: &User,
1223 part_id: &str,
1224 label: &str,
1225 ) -> Result<Revision, Error> {
1226 self.create_revision_as(author, part_id, label, false, crate::model::Origin::Authored)
1227 }
1228
1229 pub fn create_revision_from(
1233 &self,
1234 author: &User,
1235 part_id: &str,
1236 label: &str,
1237 origin: crate::model::Origin,
1238 ) -> Result<Revision, Error> {
1239 check_origin(origin)?;
1240 self.create_revision_as(author, part_id, label, false, origin)
1241 }
1242
1243 pub(crate) fn create_revision_as(
1247 &self,
1248 author: &User,
1249 part_id: &str,
1250 label: &str,
1251 exact: bool,
1252 origin: crate::model::Origin,
1253 ) -> Result<Revision, Error> {
1254 let part = self
1255 .read(|state| state.part(part_id).cloned())
1256 .ok_or_else(|| Error::not_found("part"))?;
1257 let single = !self.read(|state| state.settings.allow_multiple_open_drafts);
1258 if let Some(open) = part.open_draft().filter(|_| single) {
1259 return Err(one_draft_refusal(open, &part));
1260 }
1261 let suggested = suggest_label(&part);
1262 let requested = label.trim();
1263 let label = self.decide_label(author, Some(&part), &Value::Null, requested, &suggested)?;
1264 if exact {
1265 exact_label(requested, &label)?;
1266 }
1267
1268 let carried_revision = part.current_release().or(part.latest()).map(|r| r.id.clone());
1269 let carried = part.current_release().or(part.latest()).map(|r| r.document_key(part_id));
1270 let carried_body = match carried {
1271 Some(key) => self.read_document(&key)?,
1272 None => None,
1273 };
1274 let carried_hash = carried_body.as_deref().map(auth::content_hash);
1275
1276 let author_id = author.id.clone();
1277 let revision = self.mutate(move |state| {
1278 if !state.settings.allow_multiple_open_drafts {
1281 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1282 if let Some(open) = part.open_draft() {
1283 return Err(one_draft_refusal(open, part));
1284 }
1285 }
1286 let part = state.parts.get_mut(&part_id)
1287 .ok_or_else(|| Error::not_found("part"))?;
1288 if let Some(clash) = part.revision_by_label(&label) {
1289 return Err(Error::conflict(format!(
1290 "{} already has a revision labelled {}",
1291 part.number, clash.label
1292 )));
1293 }
1294 let stamp = now();
1295 let mut revision = Revision::draft(label.clone(), label, author_id, stamp);
1296 revision.origin = origin;
1297 if let Some(previous) = carried_revision.as_deref().and_then(|id| part.revision(id)) {
1298 revision.has_geometry = previous.has_geometry;
1299 revision.attributes = previous.attributes.clone();
1300 revision.attributes_initialized = previous.attributes_initialized;
1301 revision.occurrences = previous.occurrences.clone();
1302 }
1303 revision.uses = carried_revision
1305 .as_deref()
1306 .and_then(|id| part.revision(id))
1307 .map(|r| r.uses.clone())
1308 .unwrap_or_default();
1309 revision.attachments = carried_revision
1312 .as_deref()
1313 .and_then(|id| part.revision(id))
1314 .map(|r| {
1315 r.attachments
1316 .iter()
1317 .map(|a| crate::model::Attachment { id: auth::new_id(), ..a.clone() })
1318 .collect()
1319 })
1320 .unwrap_or_default();
1321 revision.thumbnail = carried_revision
1324 .as_deref()
1325 .and_then(|id| part.revision(id))
1326 .and_then(|r| r.thumbnail.clone())
1327 .filter(|t| carried_hash.as_deref() == Some(t.content_hash.as_str()));
1328 part.revisions.push(revision.clone());
1329 state.touch(revision.document_key(part_id));
1330 Ok(revision)
1331 })?;
1332
1333 if let Some(body) = carried_body {
1334 self.write_document(part_id, &revision.id, &body)?;
1335 }
1336 Ok(revision)
1337 }
1338
1339 pub fn update_part(&self, key: &str, fields: &Value) -> Result<Part, Error> {
1351 let Some(fields) = fields.as_object() else {
1352 return Err(Error::bad_request("the fields to change must be an object"));
1353 };
1354 for name in fields.keys() {
1355 if !matches!(
1356 name.as_str(),
1357 "name" | "description" | "category" | "tags" | "external_ref" | "attributes" | "member_part_type"
1358 ) {
1359 return Err(Error::bad_request(format!(
1360 "'{name}' cannot be changed — only name, description, category, tags, attributes, external_ref and member_part_type"
1361 )));
1362 }
1363 }
1364 let fields = fields.clone();
1365 let key = key.to_string();
1366 self.mutate(move |state| {
1367 let id = state
1368 .part_by_id_or_number(&key)
1369 .map(|p| p.id.clone())
1370 .ok_or_else(|| Error::not_found("part"))?;
1371 if let Some(value) = fields.get("external_ref") {
1372 let reference = value.as_str().map(str::trim).unwrap_or_default();
1373 let kind = state.part(&id).map(|p| p.part_type.clone()).unwrap_or_default();
1374 external_ref_clash(state, &kind, reference, &id)?;
1375 }
1376 let State { parts, categories, settings, part_types, .. } = &mut *state;
1379 let part = parts.get_mut(&id).expect("found above");
1380 if let Some(value) = fields.get("member_part_type") {
1381 let requested = value.as_str().map(str::trim).unwrap_or_default();
1382 if part.document_class == DocumentClass::Normal && !requested.is_empty() {
1383 return Err(Error::bad_request(
1384 "only a family or a template has a member part type",
1385 ));
1386 }
1387 if !requested.is_empty() && !part_types.iter().any(|t| t.id == requested) {
1388 return Err(Error::bad_request(format!("no part type '{requested}'")));
1389 }
1390 part.member_part_type = requested.to_string();
1391 }
1392 let before = (part.category.clone(), part.attributes.clone());
1393 let updated = apply_part_fields(categories, part, &fields)?;
1394
1395 if settings.lock_released_attributes
1399 && part.catalog_frozen()
1400 && before != (updated.category.clone(), updated.attributes.clone())
1401 {
1402 return Err(Error::conflict(format!(
1403 "{} is released and its category and attributes are locked — start a new revision to change them",
1404 part.number
1405 )));
1406 }
1407 Ok(updated)
1408 })
1409 }
1410}
1411
1412fn exact_label(requested: &str, decided: &str) -> Result<(), Error> {
1416 if !requested.is_empty() && !decided.eq_ignore_ascii_case(requested) {
1417 return Err(Error::conflict(format!(
1418 "{} would label it {decided}, not {requested} — a family row names its own revision",
1419 scripting::REVISION_LABEL
1420 )));
1421 }
1422 Ok(())
1423}
1424
1425fn bake_gate(revision: &Revision) -> Result<(), Error> {
1428 match &revision.bake {
1429 Some(bake) if revision.needs_bake() => Err(Error::conflict(format!(
1430 "revision {} is waiting for a bake ({}{}) — it releases once a CAD worker has baked it, or once someone saves it from the CAD app",
1431 revision.label,
1432 bake.status.as_str(),
1433 if bake.error.is_empty() { String::new() } else { format!(": {}", bake.error) }
1434 ))),
1435 _ => Ok(()),
1436 }
1437}
1438
1439fn one_draft_refusal(open: &Revision, part: &Part) -> Error {
1441 Error::conflict(format!(
1442 "revision {} of {} is still open — release or delete it first (this server allows one revision in work at a time)",
1443 open.label, part.number
1444 ))
1445}
1446
1447impl Db {
1448 pub fn settings(&self) -> Settings {
1450 self.read(|state| state.settings.clone())
1451 }
1452
1453 pub fn update_settings(&self, fields: &Value) -> Result<Settings, Error> {
1458 let Some(fields) = fields.as_object() else {
1459 return Err(Error::bad_request("the settings to change must be an object"));
1460 };
1461 let mut merged = serde_json::to_value(self.settings()).map_err(Error::internal)?;
1462 for (key, value) in fields {
1463 let slot = merged
1464 .get_mut(key)
1465 .ok_or_else(|| Error::bad_request(format!("there is no setting '{key}'")))?;
1466 if slot.is_boolean() && !value.is_boolean() {
1467 return Err(Error::bad_request(format!("'{key}' must be true or false")));
1468 }
1469 if slot.is_u64() {
1470 let minimum = if key == "session_idle_minutes" { 5 } else { 0 };
1471 match value.as_u64() {
1472 Some(n) if n >= minimum => {}
1473 _ => {
1474 return Err(Error::bad_request(format!(
1475 "'{key}' must be a whole number of at least {minimum}"
1476 )))
1477 }
1478 }
1479 }
1480 *slot = value.clone();
1481 }
1482 self.read(|state| crate::review::normalize_settings_json(state, &mut merged))?;
1483 let settings: Settings = serde_json::from_value(merged)
1484 .map_err(|e| Error::bad_request(format!("those settings do not read: {e}")))?;
1485 self.mutate(move |state| {
1486 let mut settings = settings;
1489 crate::review::check_settings(state, &mut settings)?;
1490 crate::lifecycle::check_options(&settings.status_options)?;
1491 state.settings = settings.clone();
1492 Ok(settings)
1493 })
1494 }
1495}
1496
1497fn apply_part_fields(
1500 categories: &[Category],
1501 part: &mut Part,
1502 fields: &serde_json::Map<String, Value>,
1503) -> Result<Part, Error> {
1504 let text = |value: &Value| value.as_str().map(|s| s.trim().to_string());
1505 if let Some(value) = fields.get("name") {
1506 let name = text(value)
1507 .filter(|n| !n.is_empty())
1508 .ok_or_else(|| Error::bad_request("a part needs a name"))?;
1509 part.name = name;
1510 }
1511 if let Some(value) = fields.get("description") {
1512 part.description = text(value).unwrap_or_default();
1513 }
1514 if let Some(value) = fields.get("category") {
1515 let requested = text(value).unwrap_or_default();
1516 if requested != part.category {
1520 part.category = known_category(categories, &requested)?;
1521 }
1522 }
1523 if let Some(value) = fields.get("external_ref") {
1524 part.external_ref = text(value).unwrap_or_default();
1525 }
1526 if let Some(value) = fields.get("tags") {
1527 part.tags = catalog::tidy_tags(
1528 value
1529 .as_array()
1530 .ok_or_else(|| Error::bad_request("tags must be a list of strings"))?
1531 .iter()
1532 .filter_map(|t| t.as_str().map(str::to_string)),
1533 );
1534 }
1535 if let Some(value) = fields.get("attributes") {
1538 let changes = value
1539 .as_object()
1540 .ok_or_else(|| Error::bad_request("attributes must be an object of key: value"))?;
1541 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1542 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1543 }
1544 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1545 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1546 }
1547 catalog::apply_values(categories, &part.category, &mut part.attributes, changes)?;
1548 }
1549 Ok(part.clone())
1550}
1551
1552fn known_category(categories: &[Category], requested: &str) -> Result<String, Error> {
1557 let requested = requested.trim();
1558 if requested.is_empty() {
1559 return Ok(String::new());
1560 }
1561 catalog::find(categories, requested)
1562 .map(|c| c.id.clone())
1563 .ok_or_else(|| Error::bad_request(format!("there is no category '{requested}'")))
1564}
1565
1566#[derive(Debug, Clone, Default)]
1569pub struct PartFilter {
1570 pub q: String,
1573 pub category: String,
1576 pub tag: String,
1578 pub manufacturer: String,
1581 pub supplier: String,
1583 pub attributes: Vec<AttributeFilter>,
1586 pub external_ref: String,
1588 pub part_type: String,
1590}
1591
1592#[derive(Debug, Clone, Default, PartialEq)]
1596pub struct AttributeFilter {
1597 pub key: String,
1598 pub values: Vec<String>,
1600 pub min: Option<String>,
1602 pub max: Option<String>,
1603}
1604
1605impl AttributeFilter {
1606 pub fn from_query(pairs: &[(String, String)]) -> Result<Vec<AttributeFilter>, Error> {
1610 let mut out: Vec<AttributeFilter> = Vec::new();
1611 for (name, value) in pairs {
1612 let Some(rest) = name.strip_prefix("attr.") else { continue };
1613 let (key, bound) = match rest.rsplit_once('.') {
1614 Some((key, "min")) => (key, Some(true)),
1615 Some((key, "max")) => (key, Some(false)),
1616 Some((_, other)) if !rest.is_empty() => {
1617 return Err(Error::bad_request(format!(
1620 "'{name}': an attribute filter is attr.<key>, attr.<key>.min or attr.<key>.max, not .{other}"
1621 )));
1622 }
1623 _ => (rest, None),
1624 };
1625 let key = key.trim();
1626 if key.is_empty() {
1627 return Err(Error::bad_request(format!("'{name}' names no attribute")));
1628 }
1629 let at = match out.iter().position(|f| f.key == key) {
1630 Some(i) => i,
1631 None => {
1632 out.push(AttributeFilter { key: key.to_string(), ..AttributeFilter::default() });
1633 out.len() - 1
1634 }
1635 };
1636 let filter = &mut out[at];
1637 match bound {
1638 None => filter.values.push(value.clone()),
1639 Some(true) => filter.min = Some(value.clone()),
1640 Some(false) => filter.max = Some(value.clone()),
1641 }
1642 }
1643 Ok(out)
1644 }
1645}
1646
1647#[derive(Debug, Clone)]
1650pub struct AttributeMatcher {
1651 key: String,
1652 any_of: Vec<Value>,
1653 min: Option<f64>,
1654 max: Option<f64>,
1655}
1656
1657impl AttributeMatcher {
1658 fn matches(&self, part: &Part) -> bool {
1659 let geometry = Value::Bool(part.latest().is_some_and(|r| r.has_geometry));
1660 let thumbnail = Value::Bool(crate::thumbnail::of_part(part).is_some());
1661 let have = if self.key == "has_geometry" { &geometry } else if self.key == "has_thumbnail" { &thumbnail } else {
1662 let Some(value) = part.attributes.get(&self.key).filter(|v| !v.is_null()) else { return false };
1663 value
1664 };
1665 let number = have.as_f64();
1666 let equal = |want: &Value| match (want, have) {
1667 (Value::Number(w), Value::Number(h)) => w.as_f64() == h.as_f64(),
1668 (Value::String(w), Value::String(h)) => w.eq_ignore_ascii_case(h.trim()),
1669 (w, h) => w == h,
1670 };
1671 (self.any_of.is_empty() || self.any_of.iter().any(equal))
1672 && self.min.is_none_or(|min| number.is_some_and(|n| n >= min))
1673 && self.max.is_none_or(|max| number.is_some_and(|n| n <= max))
1674 }
1675}
1676
1677pub fn attribute_matchers(state: &State, filter: &PartFilter) -> Result<Vec<AttributeMatcher>, Error> {
1687 use crate::model::{AttributeDef, AttributeKind};
1688 let category = catalog::find(&state.categories, filter.category.trim()).map(|c| c.id.clone());
1689 let mut out = Vec::new();
1690 for condition in &filter.attributes {
1691 let key = condition.key.as_str();
1692 if matches!(key, "has_geometry" | "has_thumbnail") {
1693 if condition.min.is_some() || condition.max.is_some() {
1694 return Err(Error::bad_request(format!("{key} is a boolean and has no range")));
1695 }
1696 let any_of = condition.values.iter().map(|v| match v.as_str() {
1697 "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)),
1698 _ => Err(Error::bad_request(format!("attr.{key} must be true or false"))),
1699 }).collect::<Result<Vec<_>, _>>()?;
1700 out.push(AttributeMatcher { key: key.into(), any_of, min: None, max: None });
1701 continue;
1702 }
1703 let defs: Vec<(String, AttributeDef)> = match &category {
1704 Some(id) => catalog::schema(&state.categories, id)?
1705 .into_iter()
1706 .filter(|e| e.def.key == key)
1707 .map(|e| (id.clone(), e.def))
1708 .collect(),
1709 None => state
1710 .categories
1711 .iter()
1712 .flat_map(|c| c.attributes.iter().filter(|d| d.key == key).map(move |d| (c.id.clone(), d.clone())))
1713 .collect(),
1714 };
1715 let Some((first_category, def)) = defs.first().cloned() else {
1716 return Err(Error::bad_request(match &category {
1717 Some(id) => format!("the category '{id}' has no attribute '{key}'"),
1718 None => format!("no category has an attribute '{key}'"),
1719 }));
1720 };
1721 if let Some((other, clash)) = defs.iter().find(|(_, d)| d.kind.as_str() != def.kind.as_str()) {
1722 return Err(Error::bad_request(format!(
1723 "'{key}' is a {} in '{first_category}' but a {} in '{other}' — give a category to filter by it",
1724 def.kind.as_str(),
1725 clash.kind.as_str()
1726 )));
1727 }
1728 let mut any_of = Vec::new();
1729 for raw in &condition.values {
1730 let read = defs.iter().map(|(_, d)| catalog::check_value(d, &Value::String(raw.clone())));
1733 let mut first_error = None;
1734 let mut value = None;
1735 for result in read {
1736 match result {
1737 Ok(v) => {
1738 value = v;
1739 first_error = None;
1740 break;
1741 }
1742 Err(e) => {
1743 first_error.get_or_insert(e);
1744 }
1745 }
1746 }
1747 if let Some(error) = first_error {
1748 return Err(Error::bad_request(format!("attr.{key}: {error}")));
1749 }
1750 let Some(value) = value else {
1751 return Err(Error::bad_request(format!("attr.{key} is empty — leave it out to filter on nothing")));
1752 };
1753 any_of.push(value);
1754 }
1755 let bound = |raw: &Option<String>, which: &str| -> Result<Option<f64>, Error> {
1756 let Some(raw) = raw else { return Ok(None) };
1757 if !matches!(def.kind, AttributeKind::Number { .. }) {
1758 return Err(Error::bad_request(format!(
1759 "attr.{key}.{which}: '{key}' is a {}, and only a number has a range",
1760 def.kind.as_str()
1761 )));
1762 }
1763 raw.trim()
1764 .parse::<f64>()
1765 .ok()
1766 .filter(|n| n.is_finite())
1767 .map(Some)
1768 .ok_or_else(|| Error::bad_request(format!("attr.{key}.{which} must be a number, not '{raw}'")))
1769 };
1770 out.push(AttributeMatcher {
1771 key: key.to_string(),
1772 any_of,
1773 min: bound(&condition.min, "min")?,
1774 max: bound(&condition.max, "max")?,
1775 });
1776 }
1777 Ok(out)
1778}
1779
1780#[derive(Debug, Default)]
1782pub struct PartPage {
1783 pub parts: Vec<Part>,
1784 pub next: Option<String>,
1786 cursors: Vec<i64>,
1787}
1788
1789impl PartPage {
1790 fn finish(&mut self, limit: Option<usize>) {
1792 if let Some(limit) = limit {
1793 if self.parts.len() > limit {
1794 self.parts.truncate(limit);
1795 self.next = self.cursors.get(limit - 1).map(|c| c.to_string());
1796 }
1797 }
1798 self.cursors.clear();
1799 }
1800}
1801
1802struct Matcher {
1805 needle: String,
1806 tag: String,
1807 within: Option<BTreeSet<String>>,
1810 uncategorized: bool,
1811 manufacturer: Option<Option<String>>,
1814 supplier: Option<Option<String>>,
1815 external_ref: String,
1816 part_type: String,
1817 attributes: Option<Vec<AttributeMatcher>>,
1821}
1822
1823impl Matcher {
1824 fn new(state: &State, filter: &PartFilter) -> Self {
1825 let within = match filter.category.trim() {
1826 "" => None,
1827 UNCATEGORIZED => Some(BTreeSet::new()),
1828 id => Some(catalog::descendants(&state.categories, id)),
1829 };
1830 let company = |which: sourcing::Companies, key: &str| -> Option<Option<String>> {
1831 let key = key.trim();
1832 if key.is_empty() {
1833 return None;
1834 }
1835 Some(sourcing::find_company(which.list(state), key).map(|c| c.id.clone()))
1836 };
1837 Matcher {
1838 needle: filter.q.trim().to_ascii_lowercase(),
1839 tag: filter.tag.trim().to_string(),
1840 within,
1841 uncategorized: filter.category.trim() == UNCATEGORIZED,
1842 manufacturer: company(sourcing::Companies::Manufacturers, &filter.manufacturer),
1843 supplier: company(sourcing::Companies::Suppliers, &filter.supplier),
1844 attributes: attribute_matchers(state, filter).ok(),
1845 external_ref: filter.external_ref.trim().to_string(),
1846 part_type: filter.part_type.trim().to_string(),
1847 }
1848 }
1849
1850 fn impossible(&self) -> bool {
1853 matches!(self.manufacturer, Some(None)) || matches!(self.supplier, Some(None)) || self.attributes.is_none()
1854 }
1855
1856 fn matches(&self, categories: &[Category], part: &Part) -> bool {
1857 (match &self.within {
1858 None => true,
1859 Some(_) if self.uncategorized => catalog::find(categories, &part.category).is_none(),
1860 Some(ids) => ids.contains(&part.category.to_ascii_lowercase()),
1861 }) && (self.tag.is_empty() || part.tags.iter().any(|t| t.eq_ignore_ascii_case(&self.tag)))
1862 && (match &self.manufacturer {
1863 None => true,
1864 Some(None) => false,
1865 Some(Some(id)) => part.sourcing.iter().any(|mp| &mp.manufacturer == id),
1866 })
1867 && (match &self.supplier {
1868 None => true,
1869 Some(None) => false,
1870 Some(Some(id)) => part.sourcing.iter().flat_map(|mp| &mp.offers).any(|o| &o.supplier == id),
1871 })
1872 && (self.external_ref.is_empty() || part.external_ref == self.external_ref)
1873 && (self.part_type.is_empty() || part.part_type == self.part_type)
1874 && self.attributes.as_ref().is_some_and(|all| all.iter().all(|a| a.matches(part)))
1875 && (self.needle.is_empty() || part_matches(categories, part, &self.needle))
1876 }
1877}
1878
1879pub const UNCATEGORIZED: &str = "_none";
1882
1883impl Db {
1884 pub fn search_parts(&self, query: &str) -> Vec<Part> {
1887 self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
1888 }
1889
1890 pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
1892 self.find_parts_page(filter, None, None).parts
1893 }
1894
1895 pub fn find_parts_page(&self, filter: &PartFilter, after: Option<&str>, limit: Option<usize>) -> PartPage {
1908 let matcher = self.read(|state| Matcher::new(state, filter));
1909 let after: Option<i64> = after.and_then(|a| a.trim().parse().ok());
1910 let limit = limit.map(|l| l.max(1));
1911 if matcher.impossible() {
1912 return PartPage::default();
1913 }
1914 if !matcher.external_ref.is_empty() {
1917 return self.scanned_page(&matcher, after, limit);
1918 }
1919 match self.indexed_page(&matcher, after, limit) {
1920 Ok(page) => page,
1921 Err(error) => {
1922 eprintln!("brep-plm: search index: {error}; answering from a scan");
1923 self.scanned_page(&matcher, after, limit)
1924 }
1925 }
1926 }
1927
1928 fn indexed_page(&self, matcher: &Matcher, mut after: Option<i64>, limit: Option<usize>) -> rusqlite::Result<PartPage> {
1929 let categories: Option<Vec<String>> = match (&matcher.within, matcher.uncategorized) {
1930 (Some(ids), false) => Some(ids.iter().cloned().collect()),
1931 _ => None,
1932 };
1933 let needle = (matcher.needle.chars().count() >= 3).then_some(matcher.needle.as_str());
1934 let mut page = PartPage::default();
1935 let wanted = limit.map(|l| l + 1);
1937 let batch = wanted.map(|w| w.max(256));
1938 loop {
1939 let rows = self.sql.candidates(&sql::Candidates {
1940 needle,
1941 categories: categories.as_deref(),
1942 uncategorized: matcher.uncategorized,
1943 tag: (!matcher.tag.is_empty()).then_some(matcher.tag.as_str()),
1944 manufacturer: matcher.manufacturer.as_ref().and_then(|m| m.as_deref()),
1945 supplier: matcher.supplier.as_ref().and_then(|s| s.as_deref()),
1946 after,
1947 limit: batch,
1948 })?;
1949 let exhausted = batch.is_none_or(|b| rows.len() < b);
1950 let full = self.read(|state| {
1951 for (ord, id) in &rows {
1952 after = Some(*ord);
1953 let Some(part) = state.parts.get(id) else { continue };
1954 if matcher.matches(&state.categories, part) {
1955 page.parts.push(part.clone());
1956 page.cursors.push(*ord);
1957 if wanted.is_some_and(|w| page.parts.len() >= w) {
1958 return true;
1959 }
1960 }
1961 }
1962 false
1963 });
1964 if full || exhausted {
1965 break;
1966 }
1967 }
1968 page.finish(limit);
1969 Ok(page)
1970 }
1971
1972 fn scanned_page(&self, matcher: &Matcher, after: Option<i64>, limit: Option<usize>) -> PartPage {
1973 let mut page = PartPage::default();
1974 self.read(|state| {
1975 for (ord, part) in state.parts.iter().enumerate() {
1976 let ord = ord as i64;
1977 if after.is_some_and(|a| ord <= a) || !matcher.matches(&state.categories, part) {
1978 continue;
1979 }
1980 page.parts.push(part.clone());
1981 page.cursors.push(ord);
1982 if limit.is_some_and(|l| page.parts.len() > l) {
1983 break;
1984 }
1985 }
1986 });
1987 page.finish(limit);
1988 page
1989 }
1990
1991 pub fn find_parts_scanning(&self, filter: &PartFilter) -> Vec<Part> {
1994 let matcher = self.read(|state| Matcher::new(state, filter));
1995 if matcher.impossible() {
1996 return Vec::new();
1997 }
1998 self.scanned_page(&matcher, None, None).parts
1999 }
2000
2001 pub fn checkout(
2003 &self,
2004 user: &User,
2005 part_id: &str,
2006 revision_id: &str,
2007 client_id: &str,
2008 ) -> Result<(), Error> {
2009 let user_id = user.id.clone();
2010 let client_id = client_id.to_string();
2011 self.mutate(move |state| {
2012 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2013 if !revision.lifecycle.is_editable() {
2014 return Err(Error::conflict(format!(
2015 "revision {} is {} — only a draft can be checked out",
2016 revision.label,
2017 revision.lifecycle.as_str()
2018 )));
2019 }
2020 if let Some(lock) = &revision.lock {
2021 if lock.user_id != user_id {
2022 return Err(Error::conflict(
2023 "already checked out by another user".to_string(),
2024 ));
2025 }
2026 }
2029 revision.lock = Some(Lock {
2030 user_id,
2031 client_id,
2032 acquired_at: now(),
2033 });
2034 state.touch_part(part_id);
2035 Ok(())
2036 })
2037 }
2038
2039 pub fn checkin(
2042 &self,
2043 user: &User,
2044 part_id: &str,
2045 revision_id: &str,
2046 force: bool,
2047 ) -> Result<(), Error> {
2048 let user_id = user.id.clone();
2049 let may_break = user.can_checkin();
2050 self.mutate(move |state| {
2051 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2052 let Some(lock) = revision.lock.clone() else {
2053 return Err(Error::conflict("nothing is checked out".to_string()));
2054 };
2055 if lock.user_id != user_id {
2056 if !force {
2057 return Err(Error::forbidden(
2058 "another user holds this lock — breaking it needs the check-in group",
2059 ));
2060 }
2061 if !may_break {
2062 return Err(Error::forbidden(
2063 "breaking another user's lock needs the check-in group",
2064 ));
2065 }
2066 }
2067 revision.lock = None;
2068 state.touch_part(part_id);
2069 Ok(())
2070 })
2071 }
2072
2073 pub fn transition(
2082 &self,
2083 user: &User,
2084 part_id: &str,
2085 revision_id: &str,
2086 to: Lifecycle,
2087 ) -> Result<Vec<String>, Error> {
2088 self.transition_checked(user, part_id, revision_id, to, None, None)
2089 }
2090
2091 pub fn transition_reviewed(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str) -> Result<Vec<String>, Error> {
2092 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), None)
2093 }
2094
2095 pub(crate) fn transition_workflow(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str, run_id: &str) -> Result<Vec<String>, Error> {
2096 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), Some(run_id))
2097 }
2098
2099 fn transition_checked(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: Option<&str>, workflow_run: Option<&str>) -> Result<Vec<String>, Error> {
2100 if let Some(expected) = expected_hash {
2101 let (_, revision) = self.snapshot(part_id, revision_id)?;
2102 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2103 }
2104 lifecycle::check_enabled(&self.settings(), to)?;
2105 if to == Lifecycle::Released { self.read(|s|crate::workflow::release_gate(s,part_id,revision_id,workflow_run))?; }
2106 if to == Lifecycle::Superseded {
2107 return Err(Error::bad_request(
2108 "superseded is applied automatically when a newer revision releases",
2109 ));
2110 }
2111 if to == Lifecycle::Released && !user.can_checkin() {
2112 return Err(Error::forbidden("releasing needs the check-in group"));
2113 }
2114 if matches!(to, Lifecycle::InReview | Lifecycle::Draft) && !user.can_author() {
2116 return Err(Error::forbidden("submitting for review, or withdrawing, needs the author group"));
2117 }
2118 if to == Lifecycle::InReview {
2120 return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
2121 }
2122
2123 if matches!(to, Lifecycle::Released | Lifecycle::Obsolete) {
2126 self.read(|state| eco_hold_gate(state, part_id, revision_id, to))?;
2127 }
2128
2129 let mut seen_hash = None;
2133 if to == Lifecycle::Released {
2134 let (part, revision) = self.snapshot(part_id, revision_id)?;
2135 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2136 self.read(|state| catalog_gate(&state.categories, &part))?;
2137 self.read(|state| children_gate(state, &part, &revision))?;
2138 self.read(|state| review_gate(state, &part, &revision))?;
2139 if revision.lock.is_some() {
2140 return Err(Error::conflict(format!(
2141 "revision {} is checked out — check it in before releasing",
2142 revision.label
2143 )));
2144 }
2145 bake_gate(&revision)?;
2146 let input = self.read(|state| release_input(state, &part, &revision, user));
2147 match scripting::run(self, user, scripting::BEFORE_RELEASE, "beforeRelease", &input)? {
2148 HookResult::Absent | HookResult::Returned(_) => {}
2149 HookResult::Refused(failure) => {
2150 return Err(Error::conflict(format!(
2151 "{} refused the release: {}",
2152 scripting::BEFORE_RELEASE,
2153 failure.message
2154 )))
2155 }
2156 }
2157 seen_hash = Some(revision.content_hash.clone());
2158 }
2159
2160 let user_id = user.id.clone();
2161 self.mutate(move |state| {
2162 lifecycle::check_enabled(&state.settings, to)?;
2163 if to == Lifecycle::Released { crate::workflow::release_gate(state,part_id,revision_id,workflow_run)?; }
2164 if let Some(expected) = expected_hash {
2165 let revision = state.part(part_id).and_then(|p|p.revision(revision_id)).ok_or_else(||Error::not_found("revision"))?;
2166 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2167 }
2168 if to == Lifecycle::Released {
2169 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2172 catalog_gate(&state.categories, part)?;
2173 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
2174 let field_problems = crate::bom_config::release_problems(state, part, revision);
2175 if !field_problems.is_empty() { return Err(Error::conflict(field_problems.join("; "))); }
2176 children_gate(state, part, revision)?;
2177 review_gate(state, part, revision)?;
2178 }
2179 if matches!(to, Lifecycle::Released | Lifecycle::Obsolete) {
2180 eco_hold_gate(state, part_id, revision_id, to)?;
2181 }
2182 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2183 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2184 if revision.lifecycle == Lifecycle::InReview && to == Lifecycle::Draft {
2186 if let Some(review) = revision.live_review_mut() {
2187 crate::review::withdraw(review, &user_id, now());
2188 }
2189 }
2190 if let Some(hash) = &seen_hash {
2191 if *hash != revision.content_hash {
2192 return Err(Error::conflict(format!(
2193 "revision {} changed while {} was checking it — release it again",
2194 revision.label,
2195 scripting::BEFORE_RELEASE
2196 )));
2197 }
2198 }
2199 if to == Lifecycle::Released {
2200 bake_gate(revision)?;
2201 if let Some(lock) = &revision.lock {
2202 return Err(Error::conflict(format!(
2203 "revision {} is checked out (held since {}) — check it in before releasing",
2204 revision.label, lock.acquired_at
2205 )));
2206 }
2207 crate::review::close_on_release(revision, &user_id, now());
2208 revision.released_by = Some(user_id);
2209 revision.released_at = Some(now());
2210 revision.lock = None;
2211 }
2212 revision.lifecycle = to;
2213 let released_id = revision.id.clone();
2214
2215 if to == Lifecycle::Released {
2219 let part = state.parts.get_mut(&part_id)
2220 .ok_or_else(|| Error::not_found("part"))?;
2221 for other in part.revisions.iter_mut() {
2222 if other.id != released_id && other.lifecycle == Lifecycle::Released {
2223 other.lifecycle = Lifecycle::Superseded;
2224 }
2225 }
2226 }
2227 state.touch_part(&part_id);
2228 Ok(())
2229 })?;
2230
2231 let mut warnings = Vec::new();
2232 if matches!(to, Lifecycle::Released | Lifecycle::Obsolete) {
2233 if let Some(number) = self.read(|state| crate::eco::standalone_holder(state, part_id, revision_id).map(|e| e.number.clone())) {
2234 warnings.push(format!(
2235 "{} outside {number}, which names this revision — that change order will not release until the item is removed",
2236 if to == Lifecycle::Released { "released" } else { "obsoleted" }
2237 ));
2238 }
2239 }
2240 if to == Lifecycle::Draft {
2241 warnings.extend(self.review_withdrawn(user, part_id, revision_id));
2242 }
2243 if to == Lifecycle::Released {
2244 let (part, revision) = self.snapshot(part_id, revision_id)?;
2245 let unreleased = self.read(|state| bom::unreleased_children(state, &revision));
2248 if !unreleased.is_empty() {
2249 warnings.push(format!("released, but it uses unreleased parts: {}", unreleased.join("; ")));
2250 }
2251 let input = self.read(|state| release_input(state, &part, &revision, user));
2252 match scripting::run(self, user, scripting::AFTER_RELEASE, "afterRelease", &input) {
2253 Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => {}
2254 Ok(HookResult::Refused(failure)) => warnings.push(format!(
2255 "released, but {} failed: {}",
2256 scripting::AFTER_RELEASE,
2257 failure.message
2258 )),
2259 Err(error) => warnings.push(format!(
2260 "released, but {} could not run: {}",
2261 scripting::AFTER_RELEASE,
2262 error.message
2263 )),
2264 }
2265 }
2266 Ok(warnings)
2267 }
2268
2269 pub(crate) fn snapshot(&self, part_id: &str, revision_id: &str) -> Result<(Part, Revision), Error> {
2271 self.read(|state| {
2272 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2273 let revision = part
2274 .revision(revision_id)
2275 .ok_or_else(|| Error::not_found("revision"))?;
2276 Ok((part.clone(), revision.clone()))
2277 })
2278 }
2279
2280 pub fn delete_draft(&self, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2283 let user_id = user.id.clone();
2284 let may_break = user.can_checkin();
2285 let key = crate::identity::document_key(part_id, revision_id);
2286 let root = self.root().to_path_buf();
2287 self.mutate(|state| {
2288 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2289 if !revision.lifecycle.is_editable() {
2290 return Err(Error::conflict(
2291 "only a draft can be deleted — release history is permanent".to_string(),
2292 ));
2293 }
2294 if let Some(lock) = &revision.lock {
2295 if lock.user_id != user_id && !may_break {
2296 return Err(Error::forbidden(
2297 "another user has this draft checked out",
2298 ));
2299 }
2300 }
2301 let part = state.parts.get_mut(&part_id)
2302 .ok_or_else(|| Error::not_found("part"))?;
2303 if part.revisions.len() == 1 {
2304 return Err(Error::conflict(
2305 "a part keeps at least one revision".to_string(),
2306 ));
2307 }
2308 if let Some((parent, rev)) = pinned_by(state, part_id, revision_id) {
2311 return Err(Error::conflict(format!(
2312 "this revision is used by {parent} rev {rev} — remove it from that list first"
2313 )));
2314 }
2315 let part = state.parts.get_mut(&part_id)
2316 .ok_or_else(|| Error::not_found("part"))?;
2317 let thumbnail = part.revision(revision_id).and_then(|r| r.thumbnail.as_ref()).map(|t| t.sha256.clone());
2318 part.revisions.retain(|r| r.id != revision_id);
2319 if let Some(sha) = thumbnail {
2320 crate::attach::remove_if_unreferenced(state, &root, &sha)?;
2321 }
2322 state.touch(key.clone());
2323 Ok(())
2324 })?;
2325 self.remove_document(&key)
2326 }
2327
2328 pub fn changes_since(&self, since: u64) -> (u64, bool, Vec<String>) {
2331 self.read(|state| {
2332 let stale = since < state.changes_floor();
2333 let keys: Vec<String> = state
2334 .changes
2335 .iter()
2336 .filter(|c| c.seq > since)
2337 .map(|c| c.key.clone())
2338 .collect::<BTreeSet<_>>()
2339 .into_iter()
2340 .collect();
2341 (state.seq, stale, keys)
2342 })
2343 }
2344}
2345
2346#[derive(Debug, Clone, Default)]
2353pub struct CategoryChange {
2354 pub name: Option<String>,
2355 pub parent: Option<String>,
2357 pub attributes: Option<Vec<AttributeDef>>,
2359}
2360
2361impl Db {
2362 pub fn create_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2366 let id = catalog::normalize_id(id)?;
2367 let name = change.name.unwrap_or_default().trim().to_string();
2368 if name.is_empty() {
2369 return Err(Error::bad_request("a category needs a name"));
2370 }
2371 let attributes = catalog::check_definitions(change.attributes.unwrap_or_default())?;
2372 let parent = change.parent.unwrap_or_default().trim().to_string();
2373 self.mutate(move |state| {
2374 if catalog::find(&state.categories, &id).is_some() {
2375 return Err(Error::conflict(format!("category '{id}' exists")));
2376 }
2377 let parent = if parent.is_empty() {
2378 String::new()
2379 } else {
2380 catalog::find(&state.categories, &parent)
2381 .map(|c| c.id.clone())
2382 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2383 };
2384 let category = Category { id, name, parent, attributes, created_at: now() };
2385 state.categories.push(category.clone());
2386 catalog::check_tree(&state.categories)?;
2387 Ok(category)
2388 })
2389 }
2390
2391 pub fn update_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2398 let attributes = change.attributes.map(catalog::check_definitions).transpose()?;
2399 let id = id.trim().to_string();
2400 self.mutate(move |state| {
2401 let index = state
2402 .categories
2403 .iter()
2404 .position(|c| c.id.eq_ignore_ascii_case(&id))
2405 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
2406 if let Some(name) = change.name {
2407 let name = name.trim().to_string();
2408 if name.is_empty() {
2409 return Err(Error::bad_request("a category needs a name"));
2410 }
2411 state.categories[index].name = name;
2412 }
2413 if let Some(parent) = change.parent {
2414 let parent = parent.trim();
2415 state.categories[index].parent = if parent.is_empty() {
2416 String::new()
2417 } else {
2418 catalog::find(&state.categories, parent)
2419 .map(|c| c.id.clone())
2420 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2421 };
2422 }
2423 if let Some(attributes) = attributes {
2424 state.categories[index].attributes = attributes;
2425 }
2426 catalog::check_tree(&state.categories)?;
2430 Ok(state.categories[index].clone())
2431 })
2432 }
2433
2434 pub fn delete_category(&self, id: &str) -> Result<(), Error> {
2438 let id = id.trim().to_string();
2439 self.mutate(move |state| {
2440 let category = catalog::find(&state.categories, &id)
2441 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?
2442 .id
2443 .clone();
2444 if let Some(child) = state.categories.iter().find(|c| c.parent.eq_ignore_ascii_case(&category)) {
2445 return Err(Error::conflict(format!(
2446 "category '{category}' has a sub-category '{}' — move or delete it first",
2447 child.id
2448 )));
2449 }
2450 let used = state
2451 .parts
2452 .iter()
2453 .filter(|p| p.category.eq_ignore_ascii_case(&category))
2454 .count();
2455 if used > 0 {
2456 return Err(Error::conflict(format!(
2457 "category '{category}' holds {used} part{} — move them to another category first",
2458 if used == 1 { "" } else { "s" }
2459 )));
2460 }
2461 state.categories.retain(|c| c.id != category);
2462 Ok(())
2463 })
2464 }
2465}
2466
2467fn part_matches(categories: &[Category], part: &Part, needle: &str) -> bool {
2470 let hit = |text: &str| text.to_ascii_lowercase().contains(needle);
2471 hit(&part.number)
2472 || hit(&part.name)
2473 || hit(&part.description)
2474 || hit(&part.category)
2475 || hit(&catalog::path_name(categories, &part.category))
2476 || part.tags.iter().any(|t| hit(t))
2477 || part.attributes.values().any(|value| match value {
2478 Value::String(text) => hit(text),
2479 Value::Number(n) => hit(&n.to_string()),
2480 _ => false,
2481 })
2482 || part.sourcing.iter().any(|mp| hit(&mp.mpn) || mp.offers.iter().any(|o| hit(&o.spn)))
2483}
2484
2485fn catalog_gate(categories: &[Category], part: &Part) -> Result<(), Error> {
2489 let problems = catalog::release_problems(categories, part);
2490 if problems.is_empty() {
2491 return Ok(());
2492 }
2493 Err(Error::conflict(format!(
2494 "{} cannot release until its catalog values are complete: {}",
2495 part.number,
2496 problems.join("; ")
2497 )))
2498}
2499
2500fn eco_hold_gate(state: &State, part_id: &str, revision_id: &str, to: Lifecycle) -> Result<(), Error> {
2506 if !state.settings.eco_holds_revisions {
2507 return Ok(());
2508 }
2509 match crate::eco::standalone_holder(state, part_id, revision_id) {
2510 Some(eco) => Err(Error::conflict(format!(
2511 "this revision is in {} ({}) — {} it through the change order, or take it out of there first",
2512 eco.number,
2513 eco.state.as_str(),
2514 if to == Lifecycle::Released { "release" } else { "obsolete" }
2515 ))),
2516 None => Ok(()),
2517 }
2518}
2519
2520fn review_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2522 let (rule, _) = crate::review::rule_for(&state.settings, &state.categories, part);
2523 crate::review::release_gate(revision, &rule, &part.number)
2524}
2525
2526fn children_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2527 if !state.settings.require_released_children {
2528 return Ok(());
2529 }
2530 let problems = bom::unreleased_children(state, revision);
2531 if problems.is_empty() {
2532 return Ok(());
2533 }
2534 Err(Error::conflict(format!(
2535 "{} rev {} cannot release until everything it uses is released: {}",
2536 part.number,
2537 revision.label,
2538 problems.join("; ")
2539 )))
2540}
2541
2542fn pinned_by(state: &State, part_id: &str, revision_id: &str) -> Option<(String, String)> {
2545 state.parts.iter().find_map(|parent| {
2546 parent.revisions.iter().find_map(|rev| {
2547 rev.uses
2548 .iter()
2549 .any(|u| u.part == part_id && u.revision == revision_id)
2550 .then(|| (parent.number.clone(), rev.label.clone()))
2551 })
2552 })
2553}
2554
2555pub fn check_writable(state: &State, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2559 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2560 let revision = part
2561 .revision(revision_id)
2562 .ok_or_else(|| Error::not_found("revision"))?;
2563 if !revision.lifecycle.is_editable() {
2564 return Err(Error::conflict(format!(
2565 "{} revision {} is {} and cannot be written — start a new revision",
2566 part.number,
2567 revision.label,
2568 revision.lifecycle.as_str()
2569 )));
2570 }
2571 match &revision.lock {
2572 None => Err(Error::conflict(format!(
2573 "{} revision {} is not checked out — check it out before saving",
2574 part.number, revision.label
2575 ))),
2576 Some(lock) if lock.user_id != user.id => {
2577 let holder = state
2578 .user(&lock.user_id)
2579 .map(|u| u.username.clone())
2580 .unwrap_or_else(|| "another user".to_string());
2581 Err(Error::conflict(format!(
2582 "{} revision {} is checked out by {holder}",
2583 part.number, revision.label
2584 )))
2585 }
2586 Some(_) => Ok(()),
2587 }
2588}
2589
2590impl Db {
2591 pub fn set_uses(&self, user: &User, part_id: &str, revision_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
2598 let user = user.clone();
2599 let body = body.clone();
2600 self.mutate(move |state| {
2601 check_writable(state, &user, part_id, revision_id)?;
2602 let uses = bom::check_uses(state, part_id, &body)?;
2603 let occurrences = crate::bom_config::capture_occurrences(state, part_id, revision_id, &body)?;
2604 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2605 revision.uses = uses.clone();
2606 if let Some(occurrences) = occurrences { revision.occurrences = occurrences; }
2607 crate::bom_config::synchronize_uses(revision);
2608 revision.modified_at = now();
2609 state.touch(crate::identity::document_key(part_id, revision_id));
2610 Ok(uses)
2611 })
2612 }
2613}
2614
2615pub(crate) fn release_input(state: &State, part: &Part, revision: &Revision, user: &User) -> Value {
2617 json!({
2618 "part": part,
2619 "sourcing": sourcing::resolved(state, part),
2620 "revision": revision,
2621 "uses": bom::resolved_uses(state, revision),
2622 "unreleased_children": bom::unreleased_children(state, revision),
2623 "document_key": revision.document_key(&part.id),
2624 "user": scripting::user_json(user),
2625 })
2626}
2627
2628fn state_has_number(parts: &[Part], number: &str) -> bool {
2630 parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
2631}
2632
2633pub fn full_match(pattern: &str) -> Result<regex::Regex, Error> {
2636 regex::Regex::new(&format!("^(?:{pattern})$"))
2637 .map_err(|e| Error::bad_request(format!("'{pattern}' is not a usable pattern: {e}")))
2638}
2639
2640pub const MAX_IDENTIFIER: usize = 64;
2642
2643pub fn check_number(number: &str) -> Result<(), Error> {
2646 check_identifier(number, "a part number")
2647}
2648
2649pub fn check_label(label: &str) -> Result<(), Error> {
2651 check_identifier(label, "a revision label")
2652}
2653
2654fn check_identifier(text: &str, what: &str) -> Result<(), Error> {
2655 if text.trim().is_empty() {
2656 return Err(Error::bad_request(format!("{what} cannot be empty")));
2657 }
2658 if text.trim() != text {
2659 return Err(Error::bad_request(format!("{what} cannot start or end with a space")));
2660 }
2661 if text.chars().any(char::is_control) {
2662 return Err(Error::bad_request(format!("{what} cannot hold control characters")));
2663 }
2664 if text.chars().count() > MAX_IDENTIFIER {
2665 return Err(Error::bad_request(format!("{what} is at most {MAX_IDENTIFIER} characters")));
2666 }
2667 Ok(())
2668}
2669
2670pub fn suggest_label(part: &Part) -> String {
2675 let mut candidate = lifecycle::next_revision_label(part.latest().map(|r| r.label.as_str()));
2676 while part.revision_by_label(&candidate).is_some() {
2677 candidate = lifecycle::next_revision_label(Some(&candidate));
2678 }
2679 candidate
2680}
2681
2682#[derive(Debug, Clone, Default)]
2685pub struct PartSpec {
2686 pub part_type: String,
2687 pub number: String,
2688 pub name: String,
2689 pub description: String,
2690 pub category: String,
2691 pub document_class: DocumentClass,
2692 pub label: String,
2693 pub tags: Vec<String>,
2694 pub attributes: serde_json::Map<String, Value>,
2697 pub exact: bool,
2700 pub external_ref: String,
2703 pub origin: crate::model::Origin,
2706 pub workspace: Option<String>,
2710}
2711
2712pub fn external_ref_clash(state: &State, part_type: &str, external_ref: &str, except: &str) -> Result<(), Error> {
2718 if external_ref.is_empty() {
2719 return Ok(());
2720 }
2721 match state.parts.iter().find(|p| p.id != except && p.part_type == part_type && p.external_ref == external_ref) {
2722 Some(owner) => Err(Error::conflict(format!(
2723 "external_ref '{external_ref}' is already {} ({}) — look it up with ?external_ref= and use that part",
2724 owner.number, part_type
2725 ))),
2726 None => Ok(()),
2727 }
2728}
2729
2730pub fn check_origin(origin: crate::model::Origin) -> Result<(), Error> {
2732 if origin == crate::model::Origin::Generated {
2733 return Err(Error::bad_request("origin 'generated' is set by Generate alone — use authored or imported"));
2734 }
2735 Ok(())
2736}
2737
2738pub(crate) fn find_revision_mut<'a>(
2740 state: &'a mut State,
2741 part_id: &str,
2742 revision_id: &str,
2743) -> Result<(String, &'a mut Revision), Error> {
2744 let part = state.parts.get_mut(&part_id)
2745 .ok_or_else(|| Error::not_found("part"))?;
2746 let number = part.number.clone();
2747 let revision = part
2748 .revision_mut(revision_id)
2749 .ok_or_else(|| Error::not_found("revision"))?;
2750 Ok((number, revision))
2751}