1use std::collections::{BTreeMap, BTreeSet};
42use std::fs;
43use std::io;
44use std::path::{Path, PathBuf};
45use std::sync::{Arc, RwLock};
46
47use serde::{Deserialize, Serialize};
48use serde_json::{json, Value};
49
50use crate::audit::{self, AuditFilter, AuditSink};
51use crate::auth;
52use crate::bom;
53use crate::catalog;
54use crate::lifecycle;
55use crate::model::{
56 groups, ApiToken, AttributeDef, AuditEvent, EntityRef, Category, Company, DocumentClass, Lifecycle, Lock, NumberMode, Part, PartType, Revision, Session, Settings,
57 Timestamp, Use, User,
58};
59use crate::scripting::{self, HookResult, Scripts};
60use crate::security::{Security, ServerConfig};
61use crate::sourcing;
62use crate::sql::{self, Durability, Sql};
63use crate::table::Parts;
64use crate::Error;
65
66pub const CHANGE_LOG_LIMIT: usize = 4096;
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct Change {
73 pub seq: u64,
74 pub key: String,
75}
76
77#[derive(Debug, Default, Serialize, Deserialize)]
80pub struct State {
81 pub workflows: Vec<crate::workflow::Definition>,
82 pub workflow_runs: Vec<crate::workflow::Run>,
83 pub bom_configuration: crate::bom_config::Configuration,
84 pub seq: u64,
85 pub users: Vec<User>,
86 #[serde(default)]
91 pub sessions: crate::journal::Journaled<Session>,
92 pub api_tokens: Vec<ApiToken>,
94 pub part_types: Vec<PartType>,
95 #[serde(default)]
97 pub parts: Parts,
98 pub categories: Vec<Category>,
100 pub manufacturers: Vec<Company>,
102 pub suppliers: Vec<Company>,
104 pub settings: Settings,
106 pub changes: Vec<Change>,
107 pub changes_from: u64,
113 #[serde(default)]
117 pub workspace: crate::workspace::Workspace,
118}
119
120impl State {
121 pub(crate) fn touch_part(&mut self, part_id: &str) {
127 let keys: Vec<String> = self
128 .part(part_id)
129 .map(|part| part.revisions.iter().map(|r| r.document_key(&part.id)).collect())
130 .unwrap_or_default();
131 for key in keys {
132 self.touch(key);
133 }
134 }
135
136 pub(crate) fn touch(&mut self, key: String) {
139 let seq = self.seq;
140 self.changes.retain(|change| change.key != key);
141 self.changes.push(Change { seq, key });
142 if self.changes.len() > CHANGE_LOG_LIMIT {
143 let excess = self.changes.len() - CHANGE_LOG_LIMIT;
144 let dropped: Vec<Change> = self.changes.drain(..excess).collect();
145 if let Some(last) = dropped.last() {
146 self.changes_from = self.changes_from.max(last.seq);
147 }
148 }
149 }
150
151 pub fn user(&self, id: &str) -> Option<&User> {
152 self.users.iter().find(|u| u.id == id)
153 }
154
155 pub fn user_by_name(&self, username: &str) -> Option<&User> {
156 let username = username.trim().to_ascii_lowercase();
157 self.users
158 .iter()
159 .find(|u| u.username.to_ascii_lowercase() == username)
160 }
161
162 pub fn part(&self, id: &str) -> Option<&Part> {
163 self.parts.get(id)
164 }
165
166 pub fn part_type(&self, id: &str) -> Option<&PartType> {
167 self.part_types.iter().find(|t| t.id == id)
168 }
169
170 pub fn part_by_id_or_number(&self, key: &str) -> Option<&Part> {
172 let key = key.trim();
173 self.part(key).or_else(|| self.part_with_number(key))
174 }
175
176 pub fn part_with_number(&self, number: &str) -> Option<&Part> {
181 let number = number.trim();
182 self.parts.iter().find(|p| p.number.eq_ignore_ascii_case(number))
183 }
184
185 pub fn changes_floor(&self) -> u64 {
188 self.changes_from
189 }
190}
191
192#[derive(Clone)]
199pub struct Db {
200 root: PathBuf,
201 state: Arc<RwLock<State>>,
202 scripts: Arc<Scripts>,
203 security: Arc<Security>,
204 sql: Arc<Sql>,
206 _lock: Arc<crate::dirlock::DirLock>,
209 backups: Arc<crate::backup::Status>,
211 pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
212}
213
214pub fn now() -> Timestamp {
216 std::time::SystemTime::now()
217 .duration_since(std::time::UNIX_EPOCH)
218 .map(|d| d.as_secs())
219 .unwrap_or(0)
220}
221
222impl Db {
223 pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
230 Self::open_with_scripts(root, None)
231 }
232
233 pub fn open_with_scripts(
237 root: impl Into<PathBuf>,
238 scripts: Option<PathBuf>,
239 ) -> io::Result<(Self, Option<String>)> {
240 Self::open_with(root, scripts, Durability::Full)
241 }
242
243 pub fn open_with(
246 root: impl Into<PathBuf>,
247 scripts: Option<PathBuf>,
248 durability: Durability,
249 ) -> io::Result<(Self, Option<String>)> {
250 let root = root.into();
251 let lock = crate::dirlock::DirLock::acquire(&root)?;
255 fs::create_dir_all(root.join("models"))?;
256 let scripts = Scripts::new(scripts.unwrap_or_else(|| root.join("scripts")))?;
257 let sql = Sql::open_with(root.join(SQLITE_FILE), durability).map_err(io::Error::other)?;
258 let loaded = sql.load().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
259 let fresh = loaded.is_none();
260 let mut state = loaded.unwrap_or_default();
261 if state.parts.iter().any(|p| p.id != p.number || p.revisions.iter().any(|r| r.id != r.label)) {
262 return Err(io::Error::new(io::ErrorKind::InvalidData,
263 "part and revision identities must match their current number and label"));
264 }
265 let before = sql::small_value(&mut state);
266
267 let mut seeded = None;
268 if state.part_types.is_empty() {
269 state.part_types.push(PartType {
272 id: "component".into(),
273 name: "Component".into(),
274 prefix: "CPART".into(),
275 digits: 9,
276 next: 1,
277 created_at: now(),
278 mode: Default::default(),
279 });
280 }
281 if state.users.is_empty() {
282 let password = auth::random_token(12);
283 state.users.push(User {
284 id: auth::new_id(),
285 username: "admin".into(),
286 display_name: "Administrator".into(),
287 email: String::new(),
288 password: auth::hash_password(&password),
289 groups: vec![groups::ADMIN.into()],
290 active: true,
291 created_at: now(),
292 });
293 seeded = Some(password);
294 }
295 let after = sql::small_value(&mut state);
296 if fresh || before != after {
297 let change = sql::Change {
298 before: &if fresh { Value::Object(Default::default()) } else { before },
299 after: &after,
300 parts: Vec::new(),
301 categories: &state.categories,
302 reindex: Vec::new(),
303 all_parts: &state.parts,
304 workspace: Vec::new(),
305 sessions: Vec::new(),
306 };
307 sql.write(&change, Vec::new()).map_err(io::Error::other)?;
308 }
309
310 let db = Db {
311 root,
312 state: Arc::new(RwLock::new(state)),
313 scripts: Arc::new(scripts),
314 security: Arc::new(Security::default()),
315 sql: Arc::new(sql),
316 _lock: Arc::new(lock),
317 backups: Arc::new(crate::backup::Status::default()),
318 bake_worker: Arc::new(crate::bake_worker::Controller::default()),
319 };
320 match db.sweep_blobs() {
323 Ok(0) => {}
324 Ok(n) => eprintln!("brep-plm: removed {n} unreferenced attachment file(s)"),
325 Err(error) => eprintln!("brep-plm: could not sweep attachment files: {error}"),
326 }
327 db.recover_workflows().map_err(io::Error::other)?;
328 Ok((db, seeded))
329 }
330
331
332
333 pub fn root(&self) -> &Path {
336 &self.root
337 }
338
339 pub fn stop_bake_worker(&self) -> Result<crate::bake_worker::Status, Error> {
341 self.bake_worker.stop(self.security.config.bake_worker.as_ref())
342 }
343
344 pub fn scripts(&self) -> &Scripts {
345 &self.scripts
346 }
347
348 pub fn with_config(mut self, config: ServerConfig) -> Self {
351 self.security = Arc::new(Security { config, ..Security::default() });
352 self
353 }
354
355 pub fn backups(&self) -> &crate::backup::Status {
357 &self.backups
358 }
359
360 pub fn security(&self) -> &Security {
362 &self.security
363 }
364
365 pub fn script_editor_allowed(&self) -> bool {
368 !self.security.config.lock_script_editor && self.read(|state| state.settings.script_editor_enabled)
369 }
370
371 pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
373 let state = self.state.read().unwrap_or_else(|e| e.into_inner());
374 f(&state)
375 }
376
377 pub fn mutate<R>(&self, f: impl FnOnce(&mut State) -> Result<R, Error>) -> Result<R, Error> {
394 let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
395 let before = sql::small_value(&mut state);
396 state.parts.begin();
397 state.workspace.begin();
398 state.sessions.begin();
399 state.seq += 1;
400 match f(&mut state) {
401 Ok(value) => {
402 let touched = state.parts.commit();
403 let entries = state.workspace.commit();
404 let sessions = state.sessions.commit();
405 match self.persist(&mut state, &before, &touched, &entries, &sessions) {
406 Ok(()) => Ok(value),
407 Err(error) => {
408 state.parts.undo(touched);
409 state.workspace.undo(entries);
410 state.sessions.undo(sessions);
411 restore_small(&mut state, &before)?;
412 Err(error)
413 }
414 }
415 }
416 Err(error) => {
417 state.parts.rollback();
418 state.workspace.rollback();
419 state.sessions.rollback();
420 restore_small(&mut state, &before)?;
421 Err(error)
422 }
423 }
424 }
425
426 fn persist(
428 &self,
429 state: &mut State,
430 before: &Value,
431 touched: &[crate::table::Touched],
432 entries: &[crate::journal::Touched<crate::model::WorkspaceEntry>],
433 sessions: &[crate::journal::Touched<Session>],
434 ) -> Result<(), Error> {
435 let after = sql::small_value(state);
436 let mut old_parts = Vec::new();
439 let mut new_parts = Vec::new();
440 let mut changed = Vec::new();
441 for t in touched {
442 let now_part = &state.parts[t.position];
443 let now_value = serde_json::to_value(now_part).map_err(Error::internal)?;
444 let was_value = match &t.before {
445 Some(part) => Some(serde_json::to_value(part).map_err(Error::internal)?),
446 None => None,
447 };
448 if was_value.as_ref() == Some(&now_value) {
449 continue;
450 }
451 old_parts.extend(was_value);
452 new_parts.push(now_value);
453 changed.push((t.position, now_part));
454 }
455 let (old_entries, new_entries, workspace) = journal_rows(&state.workspace, entries)?;
458 let (old_sessions, new_sessions, session_rows) = journal_rows(&state.sessions, sessions)?;
459 let mut old = before.clone();
460 let mut new = after.clone();
461 if let (Some(o), Some(n)) = (old.as_object_mut(), new.as_object_mut()) {
462 o.insert("parts".into(), Value::Array(old_parts));
463 n.insert("parts".into(), Value::Array(new_parts));
464 o.insert("workspace".into(), Value::Array(old_entries));
465 n.insert("workspace".into(), Value::Array(new_entries));
466 o.insert("sessions".into(), Value::Array(old_sessions));
467 n.insert("sessions".into(), Value::Array(new_sessions));
468 }
469 let events = audit::refine(audit::diff(&old, &new, &audit::current_actor(), now(), state.seq));
470 let mut reindex = Vec::new();
474 if before.get("categories") != after.get("categories") {
475 let old_categories: Vec<Category> =
476 serde_json::from_value(before.get("categories").cloned().unwrap_or_default()).unwrap_or_default();
477 let moved: BTreeSet<String> = old_categories
478 .iter()
479 .chain(state.categories.iter())
480 .map(|c| c.id.to_ascii_lowercase())
481 .filter(|id| catalog::path_name(&old_categories, id) != catalog::path_name(&state.categories, id))
482 .collect();
483 reindex = state
484 .parts
485 .iter()
486 .enumerate()
487 .filter(|(_, p)| moved.contains(&p.category.to_ascii_lowercase()))
488 .map(|(i, _)| i)
489 .collect();
490 }
491 let change = sql::Change {
492 before,
493 after: &after,
494 parts: changed,
495 categories: &state.categories,
496 reindex,
497 all_parts: &state.parts,
498 workspace,
499 sessions: session_rows,
500 };
501 self.sql.write(&change, events).map(|_| ()).map_err(|error| {
502 if sql::is_constraint(&error) {
503 Error::conflict(format!("the store refused the change: {error}"))
504 } else {
505 Error::internal(error)
506 }
507 })
508 }
509
510 pub fn record(&self, action: &str, entity: EntityRef, detail: impl Into<String>) {
513 let event = AuditEvent {
514 id: 0,
515 at: now(),
516 actor: audit::current_actor(),
517 action: action.to_string(),
518 entity,
519 changes: BTreeMap::new(),
520 detail: detail.into(),
521 seq: 0,
522 };
523 if let Err(error) = self.sql.append(vec![event]) {
524 eprintln!("brep-plm: audit: could not append to the log: {error}");
525 }
526 }
527
528 pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
530 self.sql.query(filter).map_err(Error::internal)
531 }
532
533 pub fn sql(&self) -> &Sql {
535 &self.sql
536 }
537
538 pub(crate) fn document_path(&self, key: &str) -> Result<PathBuf, Error> {
541 let (part, revision) = crate::identity::split_key(key)
542 .ok_or_else(|| Error::bad_request(format!("'{key}' is not a usable document key")))?;
543 Ok(self.root.join(crate::identity::model_path(&part, &revision)))
544 }
545
546 pub fn read_document(&self, key: &str) -> Result<Option<String>, Error> {
548 let path = self.document_path(key)?;
549 match fs::read_to_string(path) {
550 Ok(text) => Ok(Some(text)),
551 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
552 Err(error) => Err(Error::internal(error)),
553 }
554 }
555
556 pub fn write_document(&self, part_id: &str, revision_id: &str, body: &str) -> Result<u64, Error> {
570 self.write_document_inner(part_id, revision_id, body, None)
571 }
572
573 pub fn write_import_document(&self, user: &User, part_id: &str, revision_id: &str, expected_hash: &str, body: &str, uses: &Value) -> Result<u64, Error> {
577 self.write_document_inner(part_id, revision_id, body, Some((user, expected_hash, uses)))
578 }
579
580 fn write_document_inner(&self, part_id: &str, revision_id: &str, body: &str, import: Option<(&User, &str, &Value)>) -> Result<u64, Error> {
581 let key = crate::identity::document_key(part_id, revision_id);
582 let path = self.document_path(&key)?;
583 let hash = auth::content_hash(body);
584 let embedded = crate::thumbnail::embedded(self.root(), body)?;
585 let has_geometry = crate::geometry::contains_geometry(body);
586 self.mutate(move |state| {
587 let imported_uses = if let Some((user, expected, uses)) = import {
588 check_writable(state, user, part_id, revision_id)?;
589 let revision = state.part(part_id).and_then(|p| p.revision(revision_id))
590 .ok_or_else(|| Error::not_found("revision"))?;
591 if revision.content_hash != expected {
592 return Err(Error::conflict("the document changed since the import was reviewed; review it again"));
593 }
594 Some(bom::check_uses(state, part_id, uses)?)
595 } else { None };
596 let current = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
597 let defs = state.bom_configuration.part_fields.get(¤t.part_type).cloned().unwrap_or_default();
598 let mut canonical = current.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?.clone();
599 if let Ok(document) = serde_json::from_str::<Value>(body) {
600 if let Some(occurrences) = crate::bom_config::document_occurrences(&document) {
601 if let Some(occurrences) = crate::bom_config::capture_occurrences(state, part_id, revision_id, &json!({"occurrences":occurrences}))? {
602 canonical.occurrences = occurrences;
603 }
604 }
605 }
606 let normalized = if !defs.is_empty() || !canonical.occurrences.is_empty() {
607 let mut document: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("A CAD document must be JSON"))?;
608 let original = document.clone();
609 if !canonical.attributes_initialized && !defs.is_empty() {
610 for def in &defs {
611 if let Some(value) = document["partAttributes"].as_object().and_then(|attrs|attrs.iter().find(|(key,_)|key.to_ascii_lowercase()==def.key).map(|(_,value)|value)) {
612 if let Some(value) = catalog::check_value(def, value).map_err(Error::bad_request)? {
613 canonical.attributes.insert(def.key.clone(), value);
614 }
615 }
616 }
617 canonical.attributes_initialized = true;
618 }
619 crate::bom_config::overlay(&canonical, &defs, &mut document);
620 if document != original {Some(serde_json::to_string(&document).map_err(Error::internal)?)} else {None}
621 } else { None };
622 let body = normalized.as_deref().unwrap_or(body);
623 let hash = if normalized.is_some() { auth::content_hash(body) } else { hash };
624 let size = body.len() as u64;
625 let part = state.parts.get_mut(&part_id)
626 .ok_or_else(|| Error::not_found("part"))?;
627 let number = part.number.clone();
628 let revision = part
629 .revision_mut(revision_id)
630 .ok_or_else(|| Error::not_found("revision"))?;
631 if !revision.lifecycle.is_editable() {
632 return Err(Error::conflict(format!(
633 "{number} revision {} is {} and cannot be written — start a new revision",
634 revision.label,
635 revision.lifecycle.as_str()
636 )));
637 }
638 if let Some(parent) = path.parent() {
639 fs::create_dir_all(parent).map_err(Error::internal)?;
640 }
641 let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
642 let thumbnail = embedded.as_ref().map(|image| {
643 let user = import.map(|(user, _, _)| user.id.as_str())
644 .or_else(|| revision.lock.as_ref().map(|lock| lock.user_id.as_str()))
645 .unwrap_or(&revision.created_by);
646 image.place(self.root(), &hash, user)
647 }).transpose()?;
648 revision.attributes = canonical.attributes;
649 revision.attributes_initialized = canonical.attributes_initialized;
650 revision.occurrences = canonical.occurrences;
651 write_atomic(&path, body).map_err(Error::internal)?;
652 if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
653 if let Some(uses) = imported_uses {
654 revision.uses = uses;
655 }
656 revision.has_geometry = has_geometry;
657 revision.geometry_content_hash = hash.clone();
658 revision.content_hash = hash;
659 revision.size = size;
660 revision.modified_at = now();
661 if revision.needs_bake() {
665 if let Some(bake) = revision.bake.as_mut() {
666 bake.status = crate::model::BakeStatus::Done;
667 bake.error = "superseded by a saved document".into();
668 bake.finished_by = None;
669 bake.finished_at = Some(now());
670 }
671 }
672 crate::review::document_changed(state, part_id, revision_id);
674 state.touch(key);
675 if embedded.is_some() {
676 if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
677 }
678 Ok(state.seq)
679 })
680 }
681
682 pub fn remove_document(&self, key: &str) -> Result<(), Error> {
685 let path = self.document_path(key)?;
686 match fs::remove_file(path) {
687 Ok(()) => Ok(()),
688 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
689 Err(error) => Err(Error::internal(error)),
690 }
691 }
692}
693
694pub const SQLITE_FILE: &str = "plm.sqlite";
696
697pub fn session_expired(settings: &Settings, session: &Session, now: Timestamp) -> bool {
702 let idle = now.saturating_sub(session.last_seen) > settings.session_idle_minutes.saturating_mul(60);
703 let old = settings.session_max_hours > 0
704 && now.saturating_sub(session.created_at) > settings.session_max_hours.saturating_mul(3600);
705 idle || old
706}
707
708impl Db {
709 pub fn prune_sessions(&self) -> Result<usize, Error> {
723 let at = now();
724 let expired = self.read(|state| state.sessions.iter().filter(|s| session_expired(&state.settings, s, at)).count());
725 if expired == 0 {
726 return Ok(0);
727 }
728 audit::as_actor(crate::model::Actor::system(), || {
729 self.mutate(move |state| {
730 let settings = state.settings.clone();
731 let before = state.sessions.len();
732 state.sessions.retain(|s| !session_expired(&settings, s, at));
733 Ok(before - state.sessions.len())
734 })
735 })
736 }
737}
738
739#[allow(clippy::type_complexity)]
743fn journal_rows<'a, T>(
744 list: &'a crate::journal::Journaled<T>,
745 touched: &'a [crate::journal::Touched<T>],
746) -> Result<(Vec<Value>, Vec<Value>, Vec<(String, Option<&'a T>)>), Error>
747where
748 T: crate::journal::Keyed + Clone + PartialEq + Serialize,
749{
750 let mut old = Vec::new();
751 let mut new = Vec::new();
752 let mut rows = Vec::new();
753 for (t, now) in list.changed(touched) {
754 old.extend(t.before.as_ref().map(serde_json::to_value).transpose().map_err(Error::internal)?);
755 new.extend(now.map(serde_json::to_value).transpose().map_err(Error::internal)?);
756 rows.push((t.key.clone(), now));
757 }
758 Ok((old, new, rows))
759}
760
761fn restore_small(state: &mut State, before: &Value) -> Result<(), Error> {
762 let parts = std::mem::take(&mut state.parts);
763 let workspace = std::mem::take(&mut state.workspace);
764 let sessions = std::mem::take(&mut state.sessions);
765 *state = serde_json::from_value(before.clone()).map_err(Error::internal)?;
766 state.parts = parts;
767 state.workspace = workspace;
768 state.sessions = sessions;
769 Ok(())
770}
771
772pub(crate) fn write_atomic(path: &Path, body: &str) -> io::Result<()> {
775 let temp = path.with_extension("tmp");
776 fs::write(&temp, body)?;
777 fs::rename(&temp, path)
778}
779
780impl Db {
785 pub fn create_part(
788 &self,
789 author: &User,
790 part_type_id: &str,
791 name: &str,
792 description: &str,
793 category: &str,
794 ) -> Result<Part, Error> {
795 self.create_part_with(
796 author,
797 &PartSpec {
798 part_type: part_type_id.to_string(),
799 name: name.to_string(),
800 description: description.to_string(),
801 category: category.to_string(),
802 ..PartSpec::default()
803 },
804 )
805 }
806
807 pub fn create_part_with(&self, author: &User, spec: &PartSpec) -> Result<Part, Error> {
816 check_origin(spec.origin)?;
817 let external_ref = spec.external_ref.trim().to_string();
818 let origin = spec.origin;
819 let name = spec.name.trim().to_string();
820 if name.is_empty() {
821 return Err(Error::bad_request("a part needs a name"));
822 }
823 let kind = self
824 .read(|state| state.part_type(&spec.part_type).cloned())
825 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", spec.part_type)))?;
826 let typed = spec.number.trim().to_string();
827 let tags = catalog::tidy_tags(spec.tags.iter().cloned());
828 let part_view = json!({
829 "name": name,
830 "description": spec.description.trim(),
831 "category": spec.category.trim(),
832 "tags": tags,
833 "attributes": spec.attributes,
834 "document_class": spec.document_class,
835 });
836
837 let given: Option<String> = match &kind.mode {
838 NumberMode::Counter => {
839 if !typed.is_empty() {
840 return Err(Error::bad_request(format!(
841 "part type '{}' numbers by its counter — leave the number empty",
842 kind.id
843 )));
844 }
845 None
846 }
847 NumberMode::Free => {
848 if typed.is_empty() {
849 return Err(Error::bad_request(format!(
850 "part type '{}' takes the number you type — enter one",
851 kind.id
852 )));
853 }
854 Some(typed)
855 }
856 NumberMode::Pattern { regex } => {
857 let pattern = full_match(regex)?;
858 if typed.is_empty() {
859 return Err(Error::bad_request(format!(
860 "part type '{}' takes a typed number matching {regex} — enter one",
861 kind.id
862 )));
863 }
864 if !pattern.is_match(&typed) {
865 return Err(Error::bad_request(format!(
866 "'{typed}' does not match part type '{}' ({regex})",
867 kind.id
868 )));
869 }
870 Some(typed)
871 }
872 NumberMode::Script { script } => {
873 let input = json!({
874 "requested": typed,
875 "partType": kind,
876 "part": part_view,
877 "user": scripting::user_json(author),
878 });
879 let answer = match scripting::run(self, author, script, "partNumber", &input)? {
880 HookResult::Absent => {
881 return Err(Error::conflict(format!(
882 "part type '{}' numbers by the script '{script}', which is not in the scripts directory",
883 kind.id
884 )))
885 }
886 HookResult::Refused(failure) => {
887 return Err(Error::conflict(format!("{script}: {}", failure.message)))
888 }
889 HookResult::Returned(success) => success.value,
890 };
891 let number = scripting::string_answer(&answer, "number").ok_or_else(|| {
892 Error::conflict(format!(
893 "{script}: partNumber() must return the number, or {{ number }} — it returned {answer}"
894 ))
895 })?;
896 if spec.exact && !number.eq_ignore_ascii_case(&typed) {
897 return Err(Error::conflict(format!(
898 "{script} would number it {number}, not {typed} — a family row names its own number"
899 )));
900 }
901 Some(number)
902 }
903 };
904 if let Some(number) = &given {
905 check_number(number)?;
906 }
907
908 let requested_label = spec.label.trim().to_string();
909 let label = self.decide_label(author, None, &part_view, &requested_label, "A")?;
910 if spec.exact {
911 exact_label(&requested_label, &label)?;
912 }
913
914 let author_id = author.id.clone();
915 let document_class = spec.document_class;
916 let description = spec.description.trim().to_string();
917 let requested_category = spec.category.trim().to_string();
918 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
919 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
920 }
921 if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
922 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
923 }
924 let requested_values = spec.attributes.clone();
925 let workspace = spec.workspace.clone();
926 self.mutate(move |state| {
927 let category = known_category(&state.categories, &requested_category)?;
930 let mut attributes = BTreeMap::new();
931 catalog::apply_values(&state.categories, &category, &mut attributes, &requested_values)?;
932 let current = state
933 .part_types
934 .iter_mut()
935 .find(|t| t.id == kind.id)
936 .ok_or_else(|| Error::bad_request(format!("no part type '{}'", kind.id)))?;
937 if current.mode != kind.mode {
938 return Err(Error::conflict(format!(
939 "part type '{}' changed its numbering while this part was being created — try again",
940 kind.id
941 )));
942 }
943 let (number, sequence) = match given {
944 Some(number) => (number, 0),
945 None => {
946 let mut sequence = current.next;
949 let mut number = current.format_number(sequence);
950 while sequence <= current.capacity()
951 && state_has_number(&state.parts, &number)
952 {
953 sequence += 1;
954 number = current.format_number(sequence);
955 }
956 if sequence > current.capacity() {
957 return Err(Error::conflict(format!(
958 "part type '{}' is exhausted: {} digits cannot spell {}",
959 current.id, current.digits, sequence
960 )));
961 }
962 current.next = sequence + 1;
963 (number, sequence)
964 }
965 };
966 if let Some(owner) = state.part_with_number(&number) {
967 return Err(Error::conflict(format!(
968 "part number {number} already exists ({})",
969 owner.name
970 )));
971 }
972
973 external_ref_clash(state, &kind.id, &external_ref, "")?;
974 let stamp = now();
975 let mut revision = Revision::draft(label.clone(), label, author_id.clone(), stamp);
976 revision.origin = origin;
977 let part = Part {
978 id: number.clone(),
979 number,
980 part_type: kind.id.clone(),
981 sequence,
982 document_class,
983 name,
984 description,
985 category,
986 tags,
987 external_ref,
988 attributes,
989 sourcing: Vec::new(),
990 member_part_type: String::new(),
991 attachments: Vec::new(),
992 created_by: author_id,
993 created_at: stamp,
994 revisions: vec![revision],
995 };
996 state.parts.push(part.clone());
997 state.touch(part.revisions[0].document_key(&part.id));
998 if let Some(folder) = &workspace {
999 crate::workspace::link_new_part(state, &part.created_by, folder, &part)?;
1000 }
1001 Ok(part)
1002 })
1003 }
1004
1005 fn decide_label(
1008 &self,
1009 user: &User,
1010 part: Option<&Part>,
1011 part_view: &Value,
1012 requested: &str,
1013 suggested: &str,
1014 ) -> Result<String, Error> {
1015 let existing: Vec<&str> = part
1016 .map(|p| p.revisions.iter().map(|r| r.label.as_str()).collect())
1017 .unwrap_or_default();
1018 let input = json!({
1019 "requested": requested,
1020 "suggested": suggested,
1021 "existing": existing,
1022 "part": part.map(|p| serde_json::to_value(p).unwrap_or(Value::Null)).unwrap_or_else(|| part_view.clone()),
1023 "user": scripting::user_json(user),
1024 });
1025 let label = match scripting::run(self, user, scripting::REVISION_LABEL, "revisionLabel", &input)? {
1026 HookResult::Absent => {
1027 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1028 }
1029 HookResult::Refused(failure) => {
1030 return Err(Error::conflict(format!("{}: {}", scripting::REVISION_LABEL, failure.message)))
1031 }
1032 HookResult::Returned(success) => match &success.value {
1033 Value::Null => {
1035 if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
1036 }
1037 other => scripting::string_answer(other, "label").ok_or_else(|| {
1038 Error::conflict(format!(
1039 "{}: revisionLabel() must return the label, or {{ label }} — it returned {other}",
1040 scripting::REVISION_LABEL
1041 ))
1042 })?,
1043 },
1044 };
1045 check_label(&label)?;
1046 Ok(label)
1047 }
1048
1049 pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
1051 self.create_revision_labelled(author, part_id, "")
1052 }
1053
1054 pub fn create_revision_labelled(
1067 &self,
1068 author: &User,
1069 part_id: &str,
1070 label: &str,
1071 ) -> Result<Revision, Error> {
1072 self.create_revision_as(author, part_id, label, false, crate::model::Origin::Authored)
1073 }
1074
1075 pub fn create_revision_from(
1079 &self,
1080 author: &User,
1081 part_id: &str,
1082 label: &str,
1083 origin: crate::model::Origin,
1084 ) -> Result<Revision, Error> {
1085 check_origin(origin)?;
1086 self.create_revision_as(author, part_id, label, false, origin)
1087 }
1088
1089 pub(crate) fn create_revision_as(
1093 &self,
1094 author: &User,
1095 part_id: &str,
1096 label: &str,
1097 exact: bool,
1098 origin: crate::model::Origin,
1099 ) -> Result<Revision, Error> {
1100 let part = self
1101 .read(|state| state.part(part_id).cloned())
1102 .ok_or_else(|| Error::not_found("part"))?;
1103 let single = !self.read(|state| state.settings.allow_multiple_open_drafts);
1104 if let Some(open) = part.open_draft().filter(|_| single) {
1105 return Err(one_draft_refusal(open, &part));
1106 }
1107 let suggested = suggest_label(&part);
1108 let requested = label.trim();
1109 let label = self.decide_label(author, Some(&part), &Value::Null, requested, &suggested)?;
1110 if exact {
1111 exact_label(requested, &label)?;
1112 }
1113
1114 let carried_revision = part.current_release().or(part.latest()).map(|r| r.id.clone());
1115 let carried = part.current_release().or(part.latest()).map(|r| r.document_key(part_id));
1116 let carried_body = match carried {
1117 Some(key) => self.read_document(&key)?,
1118 None => None,
1119 };
1120 let carried_hash = carried_body.as_deref().map(auth::content_hash);
1121
1122 let author_id = author.id.clone();
1123 let revision = self.mutate(move |state| {
1124 if !state.settings.allow_multiple_open_drafts {
1127 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1128 if let Some(open) = part.open_draft() {
1129 return Err(one_draft_refusal(open, part));
1130 }
1131 }
1132 let part = state.parts.get_mut(&part_id)
1133 .ok_or_else(|| Error::not_found("part"))?;
1134 if let Some(clash) = part.revision_by_label(&label) {
1135 return Err(Error::conflict(format!(
1136 "{} already has a revision labelled {}",
1137 part.number, clash.label
1138 )));
1139 }
1140 let stamp = now();
1141 let mut revision = Revision::draft(label.clone(), label, author_id, stamp);
1142 revision.origin = origin;
1143 if let Some(previous) = carried_revision.as_deref().and_then(|id| part.revision(id)) {
1144 revision.has_geometry = previous.has_geometry;
1145 revision.attributes = previous.attributes.clone();
1146 revision.attributes_initialized = previous.attributes_initialized;
1147 revision.occurrences = previous.occurrences.clone();
1148 }
1149 revision.uses = carried_revision
1151 .as_deref()
1152 .and_then(|id| part.revision(id))
1153 .map(|r| r.uses.clone())
1154 .unwrap_or_default();
1155 revision.attachments = carried_revision
1158 .as_deref()
1159 .and_then(|id| part.revision(id))
1160 .map(|r| {
1161 r.attachments
1162 .iter()
1163 .map(|a| crate::model::Attachment { id: auth::new_id(), ..a.clone() })
1164 .collect()
1165 })
1166 .unwrap_or_default();
1167 revision.thumbnail = carried_revision
1170 .as_deref()
1171 .and_then(|id| part.revision(id))
1172 .and_then(|r| r.thumbnail.clone())
1173 .filter(|t| carried_hash.as_deref() == Some(t.content_hash.as_str()));
1174 part.revisions.push(revision.clone());
1175 state.touch(revision.document_key(part_id));
1176 Ok(revision)
1177 })?;
1178
1179 if let Some(body) = carried_body {
1180 self.write_document(part_id, &revision.id, &body)?;
1181 }
1182 Ok(revision)
1183 }
1184
1185 pub fn update_part(&self, key: &str, fields: &Value) -> Result<Part, Error> {
1197 let Some(fields) = fields.as_object() else {
1198 return Err(Error::bad_request("the fields to change must be an object"));
1199 };
1200 for name in fields.keys() {
1201 if !matches!(
1202 name.as_str(),
1203 "name" | "description" | "category" | "tags" | "external_ref" | "attributes" | "member_part_type"
1204 ) {
1205 return Err(Error::bad_request(format!(
1206 "'{name}' cannot be changed — only name, description, category, tags, attributes, external_ref and member_part_type"
1207 )));
1208 }
1209 }
1210 let fields = fields.clone();
1211 let key = key.to_string();
1212 self.mutate(move |state| {
1213 let id = state
1214 .part_by_id_or_number(&key)
1215 .map(|p| p.id.clone())
1216 .ok_or_else(|| Error::not_found("part"))?;
1217 if let Some(value) = fields.get("external_ref") {
1218 let reference = value.as_str().map(str::trim).unwrap_or_default();
1219 let kind = state.part(&id).map(|p| p.part_type.clone()).unwrap_or_default();
1220 external_ref_clash(state, &kind, reference, &id)?;
1221 }
1222 let State { parts, categories, settings, part_types, .. } = &mut *state;
1225 let part = parts.get_mut(&id).expect("found above");
1226 if let Some(value) = fields.get("member_part_type") {
1227 let requested = value.as_str().map(str::trim).unwrap_or_default();
1228 if part.document_class == DocumentClass::Normal && !requested.is_empty() {
1229 return Err(Error::bad_request(
1230 "only a family or a template has a member part type",
1231 ));
1232 }
1233 if !requested.is_empty() && !part_types.iter().any(|t| t.id == requested) {
1234 return Err(Error::bad_request(format!("no part type '{requested}'")));
1235 }
1236 part.member_part_type = requested.to_string();
1237 }
1238 let before = (part.category.clone(), part.attributes.clone());
1239 let updated = apply_part_fields(categories, part, &fields)?;
1240
1241 if settings.lock_released_attributes
1245 && part.catalog_frozen()
1246 && before != (updated.category.clone(), updated.attributes.clone())
1247 {
1248 return Err(Error::conflict(format!(
1249 "{} is released and its category and attributes are locked — start a new revision to change them",
1250 part.number
1251 )));
1252 }
1253 Ok(updated)
1254 })
1255 }
1256}
1257
1258fn exact_label(requested: &str, decided: &str) -> Result<(), Error> {
1262 if !requested.is_empty() && !decided.eq_ignore_ascii_case(requested) {
1263 return Err(Error::conflict(format!(
1264 "{} would label it {decided}, not {requested} — a family row names its own revision",
1265 scripting::REVISION_LABEL
1266 )));
1267 }
1268 Ok(())
1269}
1270
1271fn bake_gate(revision: &Revision) -> Result<(), Error> {
1274 match &revision.bake {
1275 Some(bake) if revision.needs_bake() => Err(Error::conflict(format!(
1276 "revision {} is waiting for a bake ({}{}) — it releases once a CAD worker has baked it, or once someone saves it from the CAD app",
1277 revision.label,
1278 bake.status.as_str(),
1279 if bake.error.is_empty() { String::new() } else { format!(": {}", bake.error) }
1280 ))),
1281 _ => Ok(()),
1282 }
1283}
1284
1285fn one_draft_refusal(open: &Revision, part: &Part) -> Error {
1287 Error::conflict(format!(
1288 "revision {} of {} is still open — release or delete it first (this server allows one revision in work at a time)",
1289 open.label, part.number
1290 ))
1291}
1292
1293impl Db {
1294 pub fn settings(&self) -> Settings {
1296 self.read(|state| state.settings.clone())
1297 }
1298
1299 pub fn update_settings(&self, fields: &Value) -> Result<Settings, Error> {
1304 let Some(fields) = fields.as_object() else {
1305 return Err(Error::bad_request("the settings to change must be an object"));
1306 };
1307 let mut merged = serde_json::to_value(self.settings()).map_err(Error::internal)?;
1308 for (key, value) in fields {
1309 let slot = merged
1310 .get_mut(key)
1311 .ok_or_else(|| Error::bad_request(format!("there is no setting '{key}'")))?;
1312 if slot.is_boolean() && !value.is_boolean() {
1313 return Err(Error::bad_request(format!("'{key}' must be true or false")));
1314 }
1315 if slot.is_u64() {
1316 let minimum = if key == "session_idle_minutes" { 5 } else { 0 };
1317 match value.as_u64() {
1318 Some(n) if n >= minimum => {}
1319 _ => {
1320 return Err(Error::bad_request(format!(
1321 "'{key}' must be a whole number of at least {minimum}"
1322 )))
1323 }
1324 }
1325 }
1326 *slot = value.clone();
1327 }
1328 self.read(|state| crate::review::normalize_settings_json(state, &mut merged))?;
1329 let settings: Settings = serde_json::from_value(merged)
1330 .map_err(|e| Error::bad_request(format!("those settings do not read: {e}")))?;
1331 self.mutate(move |state| {
1332 let mut settings = settings;
1335 crate::review::check_settings(state, &mut settings)?;
1336 crate::lifecycle::check_options(&settings.status_options)?;
1337 state.settings = settings.clone();
1338 Ok(settings)
1339 })
1340 }
1341}
1342
1343fn apply_part_fields(
1346 categories: &[Category],
1347 part: &mut Part,
1348 fields: &serde_json::Map<String, Value>,
1349) -> Result<Part, Error> {
1350 let text = |value: &Value| value.as_str().map(|s| s.trim().to_string());
1351 if let Some(value) = fields.get("name") {
1352 let name = text(value)
1353 .filter(|n| !n.is_empty())
1354 .ok_or_else(|| Error::bad_request("a part needs a name"))?;
1355 part.name = name;
1356 }
1357 if let Some(value) = fields.get("description") {
1358 part.description = text(value).unwrap_or_default();
1359 }
1360 if let Some(value) = fields.get("category") {
1361 let requested = text(value).unwrap_or_default();
1362 part.category = known_category(categories, &requested)?;
1363 }
1364 if let Some(value) = fields.get("external_ref") {
1365 part.external_ref = text(value).unwrap_or_default();
1366 }
1367 if let Some(value) = fields.get("tags") {
1368 part.tags = catalog::tidy_tags(
1369 value
1370 .as_array()
1371 .ok_or_else(|| Error::bad_request("tags must be a list of strings"))?
1372 .iter()
1373 .filter_map(|t| t.as_str().map(str::to_string)),
1374 );
1375 }
1376 if let Some(value) = fields.get("attributes") {
1379 let changes = value
1380 .as_object()
1381 .ok_or_else(|| Error::bad_request("attributes must be an object of key: value"))?;
1382 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
1383 return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
1384 }
1385 if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
1386 return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
1387 }
1388 catalog::apply_values(categories, &part.category, &mut part.attributes, changes)?;
1389 }
1390 Ok(part.clone())
1391}
1392
1393fn known_category(categories: &[Category], requested: &str) -> Result<String, Error> {
1398 let requested = requested.trim();
1399 if requested.is_empty() {
1400 return Ok(String::new());
1401 }
1402 catalog::find(categories, requested)
1403 .map(|c| c.id.clone())
1404 .ok_or_else(|| Error::bad_request(format!("there is no category '{requested}'")))
1405}
1406
1407#[derive(Debug, Clone, Default)]
1410pub struct PartFilter {
1411 pub q: String,
1414 pub category: String,
1417 pub tag: String,
1419 pub manufacturer: String,
1422 pub supplier: String,
1424 pub attributes: Vec<AttributeFilter>,
1427 pub external_ref: String,
1429 pub part_type: String,
1431}
1432
1433#[derive(Debug, Clone, Default, PartialEq)]
1437pub struct AttributeFilter {
1438 pub key: String,
1439 pub values: Vec<String>,
1441 pub min: Option<String>,
1443 pub max: Option<String>,
1444}
1445
1446impl AttributeFilter {
1447 pub fn from_query(pairs: &[(String, String)]) -> Result<Vec<AttributeFilter>, Error> {
1451 let mut out: Vec<AttributeFilter> = Vec::new();
1452 for (name, value) in pairs {
1453 let Some(rest) = name.strip_prefix("attr.") else { continue };
1454 let (key, bound) = match rest.rsplit_once('.') {
1455 Some((key, "min")) => (key, Some(true)),
1456 Some((key, "max")) => (key, Some(false)),
1457 Some((_, other)) if !rest.is_empty() => {
1458 return Err(Error::bad_request(format!(
1461 "'{name}': an attribute filter is attr.<key>, attr.<key>.min or attr.<key>.max, not .{other}"
1462 )));
1463 }
1464 _ => (rest, None),
1465 };
1466 let key = key.trim();
1467 if key.is_empty() {
1468 return Err(Error::bad_request(format!("'{name}' names no attribute")));
1469 }
1470 let at = match out.iter().position(|f| f.key == key) {
1471 Some(i) => i,
1472 None => {
1473 out.push(AttributeFilter { key: key.to_string(), ..AttributeFilter::default() });
1474 out.len() - 1
1475 }
1476 };
1477 let filter = &mut out[at];
1478 match bound {
1479 None => filter.values.push(value.clone()),
1480 Some(true) => filter.min = Some(value.clone()),
1481 Some(false) => filter.max = Some(value.clone()),
1482 }
1483 }
1484 Ok(out)
1485 }
1486}
1487
1488#[derive(Debug, Clone)]
1491pub struct AttributeMatcher {
1492 key: String,
1493 any_of: Vec<Value>,
1494 min: Option<f64>,
1495 max: Option<f64>,
1496}
1497
1498impl AttributeMatcher {
1499 fn matches(&self, part: &Part) -> bool {
1500 let geometry = Value::Bool(part.latest().is_some_and(|r| r.has_geometry));
1501 let thumbnail = Value::Bool(crate::thumbnail::of_part(part).is_some());
1502 let have = if self.key == "has_geometry" { &geometry } else if self.key == "has_thumbnail" { &thumbnail } else {
1503 let Some(value) = part.attributes.get(&self.key).filter(|v| !v.is_null()) else { return false };
1504 value
1505 };
1506 let number = have.as_f64();
1507 let equal = |want: &Value| match (want, have) {
1508 (Value::Number(w), Value::Number(h)) => w.as_f64() == h.as_f64(),
1509 (Value::String(w), Value::String(h)) => w.eq_ignore_ascii_case(h.trim()),
1510 (w, h) => w == h,
1511 };
1512 (self.any_of.is_empty() || self.any_of.iter().any(equal))
1513 && self.min.is_none_or(|min| number.is_some_and(|n| n >= min))
1514 && self.max.is_none_or(|max| number.is_some_and(|n| n <= max))
1515 }
1516}
1517
1518pub fn attribute_matchers(state: &State, filter: &PartFilter) -> Result<Vec<AttributeMatcher>, Error> {
1528 use crate::model::{AttributeDef, AttributeKind};
1529 let category = catalog::find(&state.categories, filter.category.trim()).map(|c| c.id.clone());
1530 let mut out = Vec::new();
1531 for condition in &filter.attributes {
1532 let key = condition.key.as_str();
1533 if matches!(key, "has_geometry" | "has_thumbnail") {
1534 if condition.min.is_some() || condition.max.is_some() {
1535 return Err(Error::bad_request(format!("{key} is a boolean and has no range")));
1536 }
1537 let any_of = condition.values.iter().map(|v| match v.as_str() {
1538 "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)),
1539 _ => Err(Error::bad_request(format!("attr.{key} must be true or false"))),
1540 }).collect::<Result<Vec<_>, _>>()?;
1541 out.push(AttributeMatcher { key: key.into(), any_of, min: None, max: None });
1542 continue;
1543 }
1544 let defs: Vec<(String, AttributeDef)> = match &category {
1545 Some(id) => catalog::schema(&state.categories, id)?
1546 .into_iter()
1547 .filter(|e| e.def.key == key)
1548 .map(|e| (id.clone(), e.def))
1549 .collect(),
1550 None => state
1551 .categories
1552 .iter()
1553 .flat_map(|c| c.attributes.iter().filter(|d| d.key == key).map(move |d| (c.id.clone(), d.clone())))
1554 .collect(),
1555 };
1556 let Some((first_category, def)) = defs.first().cloned() else {
1557 return Err(Error::bad_request(match &category {
1558 Some(id) => format!("the category '{id}' has no attribute '{key}'"),
1559 None => format!("no category has an attribute '{key}'"),
1560 }));
1561 };
1562 if let Some((other, clash)) = defs.iter().find(|(_, d)| d.kind.as_str() != def.kind.as_str()) {
1563 return Err(Error::bad_request(format!(
1564 "'{key}' is a {} in '{first_category}' but a {} in '{other}' — give a category to filter by it",
1565 def.kind.as_str(),
1566 clash.kind.as_str()
1567 )));
1568 }
1569 let mut any_of = Vec::new();
1570 for raw in &condition.values {
1571 let read = defs.iter().map(|(_, d)| catalog::check_value(d, &Value::String(raw.clone())));
1574 let mut first_error = None;
1575 let mut value = None;
1576 for result in read {
1577 match result {
1578 Ok(v) => {
1579 value = v;
1580 first_error = None;
1581 break;
1582 }
1583 Err(e) => {
1584 first_error.get_or_insert(e);
1585 }
1586 }
1587 }
1588 if let Some(error) = first_error {
1589 return Err(Error::bad_request(format!("attr.{key}: {error}")));
1590 }
1591 let Some(value) = value else {
1592 return Err(Error::bad_request(format!("attr.{key} is empty — leave it out to filter on nothing")));
1593 };
1594 any_of.push(value);
1595 }
1596 let bound = |raw: &Option<String>, which: &str| -> Result<Option<f64>, Error> {
1597 let Some(raw) = raw else { return Ok(None) };
1598 if !matches!(def.kind, AttributeKind::Number { .. }) {
1599 return Err(Error::bad_request(format!(
1600 "attr.{key}.{which}: '{key}' is a {}, and only a number has a range",
1601 def.kind.as_str()
1602 )));
1603 }
1604 raw.trim()
1605 .parse::<f64>()
1606 .ok()
1607 .filter(|n| n.is_finite())
1608 .map(Some)
1609 .ok_or_else(|| Error::bad_request(format!("attr.{key}.{which} must be a number, not '{raw}'")))
1610 };
1611 out.push(AttributeMatcher {
1612 key: key.to_string(),
1613 any_of,
1614 min: bound(&condition.min, "min")?,
1615 max: bound(&condition.max, "max")?,
1616 });
1617 }
1618 Ok(out)
1619}
1620
1621#[derive(Debug, Default)]
1623pub struct PartPage {
1624 pub parts: Vec<Part>,
1625 pub next: Option<String>,
1627 cursors: Vec<i64>,
1628}
1629
1630impl PartPage {
1631 fn finish(&mut self, limit: Option<usize>) {
1633 if let Some(limit) = limit {
1634 if self.parts.len() > limit {
1635 self.parts.truncate(limit);
1636 self.next = self.cursors.get(limit - 1).map(|c| c.to_string());
1637 }
1638 }
1639 self.cursors.clear();
1640 }
1641}
1642
1643struct Matcher {
1646 needle: String,
1647 tag: String,
1648 within: Option<BTreeSet<String>>,
1651 uncategorized: bool,
1652 manufacturer: Option<Option<String>>,
1655 supplier: Option<Option<String>>,
1656 external_ref: String,
1657 part_type: String,
1658 attributes: Option<Vec<AttributeMatcher>>,
1662}
1663
1664impl Matcher {
1665 fn new(state: &State, filter: &PartFilter) -> Self {
1666 let within = match filter.category.trim() {
1667 "" => None,
1668 UNCATEGORIZED => Some(BTreeSet::new()),
1669 id => Some(catalog::descendants(&state.categories, id)),
1670 };
1671 let company = |which: sourcing::Companies, key: &str| -> Option<Option<String>> {
1672 let key = key.trim();
1673 if key.is_empty() {
1674 return None;
1675 }
1676 Some(sourcing::find_company(which.list(state), key).map(|c| c.id.clone()))
1677 };
1678 Matcher {
1679 needle: filter.q.trim().to_ascii_lowercase(),
1680 tag: filter.tag.trim().to_string(),
1681 within,
1682 uncategorized: filter.category.trim() == UNCATEGORIZED,
1683 manufacturer: company(sourcing::Companies::Manufacturers, &filter.manufacturer),
1684 supplier: company(sourcing::Companies::Suppliers, &filter.supplier),
1685 attributes: attribute_matchers(state, filter).ok(),
1686 external_ref: filter.external_ref.trim().to_string(),
1687 part_type: filter.part_type.trim().to_string(),
1688 }
1689 }
1690
1691 fn impossible(&self) -> bool {
1694 matches!(self.manufacturer, Some(None)) || matches!(self.supplier, Some(None)) || self.attributes.is_none()
1695 }
1696
1697 fn matches(&self, categories: &[Category], part: &Part) -> bool {
1698 (match &self.within {
1699 None => true,
1700 Some(_) if self.uncategorized => part.category.is_empty(),
1701 Some(ids) => ids.contains(&part.category.to_ascii_lowercase()),
1702 }) && (self.tag.is_empty() || part.tags.iter().any(|t| t.eq_ignore_ascii_case(&self.tag)))
1703 && (match &self.manufacturer {
1704 None => true,
1705 Some(None) => false,
1706 Some(Some(id)) => part.sourcing.iter().any(|mp| &mp.manufacturer == id),
1707 })
1708 && (match &self.supplier {
1709 None => true,
1710 Some(None) => false,
1711 Some(Some(id)) => part.sourcing.iter().flat_map(|mp| &mp.offers).any(|o| &o.supplier == id),
1712 })
1713 && (self.external_ref.is_empty() || part.external_ref == self.external_ref)
1714 && (self.part_type.is_empty() || part.part_type == self.part_type)
1715 && self.attributes.as_ref().is_some_and(|all| all.iter().all(|a| a.matches(part)))
1716 && (self.needle.is_empty() || part_matches(categories, part, &self.needle))
1717 }
1718}
1719
1720pub const UNCATEGORIZED: &str = "_none";
1723
1724impl Db {
1725 pub fn search_parts(&self, query: &str) -> Vec<Part> {
1728 self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
1729 }
1730
1731 pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
1733 self.find_parts_page(filter, None, None).parts
1734 }
1735
1736 pub fn find_parts_page(&self, filter: &PartFilter, after: Option<&str>, limit: Option<usize>) -> PartPage {
1749 let matcher = self.read(|state| Matcher::new(state, filter));
1750 let after: Option<i64> = after.and_then(|a| a.trim().parse().ok());
1751 let limit = limit.map(|l| l.max(1));
1752 if matcher.impossible() {
1753 return PartPage::default();
1754 }
1755 if !matcher.external_ref.is_empty() {
1758 return self.scanned_page(&matcher, after, limit);
1759 }
1760 match self.indexed_page(&matcher, after, limit) {
1761 Ok(page) => page,
1762 Err(error) => {
1763 eprintln!("brep-plm: search index: {error}; answering from a scan");
1764 self.scanned_page(&matcher, after, limit)
1765 }
1766 }
1767 }
1768
1769 fn indexed_page(&self, matcher: &Matcher, mut after: Option<i64>, limit: Option<usize>) -> rusqlite::Result<PartPage> {
1770 let categories: Option<Vec<String>> = match (&matcher.within, matcher.uncategorized) {
1771 (Some(ids), false) => Some(ids.iter().cloned().collect()),
1772 _ => None,
1773 };
1774 let needle = (matcher.needle.chars().count() >= 3).then_some(matcher.needle.as_str());
1775 let mut page = PartPage::default();
1776 let wanted = limit.map(|l| l + 1);
1778 let batch = wanted.map(|w| w.max(256));
1779 loop {
1780 let rows = self.sql.candidates(&sql::Candidates {
1781 needle,
1782 categories: categories.as_deref(),
1783 uncategorized: matcher.uncategorized,
1784 tag: (!matcher.tag.is_empty()).then_some(matcher.tag.as_str()),
1785 manufacturer: matcher.manufacturer.as_ref().and_then(|m| m.as_deref()),
1786 supplier: matcher.supplier.as_ref().and_then(|s| s.as_deref()),
1787 after,
1788 limit: batch,
1789 })?;
1790 let exhausted = batch.is_none_or(|b| rows.len() < b);
1791 let full = self.read(|state| {
1792 for (ord, id) in &rows {
1793 after = Some(*ord);
1794 let Some(part) = state.parts.get(id) else { continue };
1795 if matcher.matches(&state.categories, part) {
1796 page.parts.push(part.clone());
1797 page.cursors.push(*ord);
1798 if wanted.is_some_and(|w| page.parts.len() >= w) {
1799 return true;
1800 }
1801 }
1802 }
1803 false
1804 });
1805 if full || exhausted {
1806 break;
1807 }
1808 }
1809 page.finish(limit);
1810 Ok(page)
1811 }
1812
1813 fn scanned_page(&self, matcher: &Matcher, after: Option<i64>, limit: Option<usize>) -> PartPage {
1814 let mut page = PartPage::default();
1815 self.read(|state| {
1816 for (ord, part) in state.parts.iter().enumerate() {
1817 let ord = ord as i64;
1818 if after.is_some_and(|a| ord <= a) || !matcher.matches(&state.categories, part) {
1819 continue;
1820 }
1821 page.parts.push(part.clone());
1822 page.cursors.push(ord);
1823 if limit.is_some_and(|l| page.parts.len() > l) {
1824 break;
1825 }
1826 }
1827 });
1828 page.finish(limit);
1829 page
1830 }
1831
1832 pub fn find_parts_scanning(&self, filter: &PartFilter) -> Vec<Part> {
1835 let matcher = self.read(|state| Matcher::new(state, filter));
1836 if matcher.impossible() {
1837 return Vec::new();
1838 }
1839 self.scanned_page(&matcher, None, None).parts
1840 }
1841
1842 pub fn checkout(
1844 &self,
1845 user: &User,
1846 part_id: &str,
1847 revision_id: &str,
1848 client_id: &str,
1849 ) -> Result<(), Error> {
1850 let user_id = user.id.clone();
1851 let client_id = client_id.to_string();
1852 self.mutate(move |state| {
1853 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
1854 if !revision.lifecycle.is_editable() {
1855 return Err(Error::conflict(format!(
1856 "revision {} is {} — only a draft can be checked out",
1857 revision.label,
1858 revision.lifecycle.as_str()
1859 )));
1860 }
1861 if let Some(lock) = &revision.lock {
1862 if lock.user_id != user_id {
1863 return Err(Error::conflict(
1864 "already checked out by another user".to_string(),
1865 ));
1866 }
1867 }
1870 revision.lock = Some(Lock {
1871 user_id,
1872 client_id,
1873 acquired_at: now(),
1874 });
1875 state.touch_part(part_id);
1876 Ok(())
1877 })
1878 }
1879
1880 pub fn checkin(
1883 &self,
1884 user: &User,
1885 part_id: &str,
1886 revision_id: &str,
1887 force: bool,
1888 ) -> Result<(), Error> {
1889 let user_id = user.id.clone();
1890 let may_break = user.can_checkin();
1891 self.mutate(move |state| {
1892 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
1893 let Some(lock) = revision.lock.clone() else {
1894 return Err(Error::conflict("nothing is checked out".to_string()));
1895 };
1896 if lock.user_id != user_id {
1897 if !force {
1898 return Err(Error::forbidden(
1899 "another user holds this lock — breaking it needs the check-in group",
1900 ));
1901 }
1902 if !may_break {
1903 return Err(Error::forbidden(
1904 "breaking another user's lock needs the check-in group",
1905 ));
1906 }
1907 }
1908 revision.lock = None;
1909 state.touch_part(part_id);
1910 Ok(())
1911 })
1912 }
1913
1914 pub fn transition(
1923 &self,
1924 user: &User,
1925 part_id: &str,
1926 revision_id: &str,
1927 to: Lifecycle,
1928 ) -> Result<Vec<String>, Error> {
1929 self.transition_checked(user, part_id, revision_id, to, None, None)
1930 }
1931
1932 pub fn transition_reviewed(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str) -> Result<Vec<String>, Error> {
1933 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), None)
1934 }
1935
1936 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> {
1937 self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), Some(run_id))
1938 }
1939
1940 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> {
1941 if let Some(expected) = expected_hash {
1942 let (_, revision) = self.snapshot(part_id, revision_id)?;
1943 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
1944 }
1945 lifecycle::check_enabled(&self.settings(), to)?;
1946 if to == Lifecycle::Released { self.read(|s|crate::workflow::release_gate(s,part_id,revision_id,workflow_run))?; }
1947 if to == Lifecycle::Superseded {
1948 return Err(Error::bad_request(
1949 "superseded is applied automatically when a newer revision releases",
1950 ));
1951 }
1952 if to == Lifecycle::Released && !user.can_checkin() {
1953 return Err(Error::forbidden("releasing needs the check-in group"));
1954 }
1955 if matches!(to, Lifecycle::InReview | Lifecycle::Draft) && !user.can_author() {
1957 return Err(Error::forbidden("submitting for review, or withdrawing, needs the author group"));
1958 }
1959 if to == Lifecycle::InReview {
1961 return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
1962 }
1963
1964 let mut seen_hash = None;
1968 if to == Lifecycle::Released {
1969 let (part, revision) = self.snapshot(part_id, revision_id)?;
1970 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
1971 self.read(|state| catalog_gate(&state.categories, &part))?;
1972 self.read(|state| children_gate(state, &part, &revision))?;
1973 self.read(|state| review_gate(state, &part, &revision))?;
1974 if revision.lock.is_some() {
1975 return Err(Error::conflict(format!(
1976 "revision {} is checked out — check it in before releasing",
1977 revision.label
1978 )));
1979 }
1980 bake_gate(&revision)?;
1981 let input = self.read(|state| release_input(state, &part, &revision, user));
1982 match scripting::run(self, user, scripting::BEFORE_RELEASE, "beforeRelease", &input)? {
1983 HookResult::Absent | HookResult::Returned(_) => {}
1984 HookResult::Refused(failure) => {
1985 return Err(Error::conflict(format!(
1986 "{} refused the release: {}",
1987 scripting::BEFORE_RELEASE,
1988 failure.message
1989 )))
1990 }
1991 }
1992 seen_hash = Some(revision.content_hash.clone());
1993 }
1994
1995 let user_id = user.id.clone();
1996 self.mutate(move |state| {
1997 lifecycle::check_enabled(&state.settings, to)?;
1998 if to == Lifecycle::Released { crate::workflow::release_gate(state,part_id,revision_id,workflow_run)?; }
1999 if let Some(expected) = expected_hash {
2000 let revision = state.part(part_id).and_then(|p|p.revision(revision_id)).ok_or_else(||Error::not_found("revision"))?;
2001 if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
2002 }
2003 if to == Lifecycle::Released {
2004 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2007 catalog_gate(&state.categories, part)?;
2008 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
2009 let field_problems = crate::bom_config::release_problems(state, part, revision);
2010 if !field_problems.is_empty() { return Err(Error::conflict(field_problems.join("; "))); }
2011 children_gate(state, part, revision)?;
2012 review_gate(state, part, revision)?;
2013 }
2014 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2015 lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
2016 if revision.lifecycle == Lifecycle::InReview && to == Lifecycle::Draft {
2018 if let Some(review) = revision.live_review_mut() {
2019 crate::review::withdraw(review, &user_id, now());
2020 }
2021 }
2022 if let Some(hash) = &seen_hash {
2023 if *hash != revision.content_hash {
2024 return Err(Error::conflict(format!(
2025 "revision {} changed while {} was checking it — release it again",
2026 revision.label,
2027 scripting::BEFORE_RELEASE
2028 )));
2029 }
2030 }
2031 if to == Lifecycle::Released {
2032 bake_gate(revision)?;
2033 if let Some(lock) = &revision.lock {
2034 return Err(Error::conflict(format!(
2035 "revision {} is checked out (held since {}) — check it in before releasing",
2036 revision.label, lock.acquired_at
2037 )));
2038 }
2039 crate::review::close_on_release(revision, &user_id, now());
2040 revision.released_by = Some(user_id);
2041 revision.released_at = Some(now());
2042 revision.lock = None;
2043 }
2044 revision.lifecycle = to;
2045 let released_id = revision.id.clone();
2046
2047 if to == Lifecycle::Released {
2051 let part = state.parts.get_mut(&part_id)
2052 .ok_or_else(|| Error::not_found("part"))?;
2053 for other in part.revisions.iter_mut() {
2054 if other.id != released_id && other.lifecycle == Lifecycle::Released {
2055 other.lifecycle = Lifecycle::Superseded;
2056 }
2057 }
2058 }
2059 state.touch_part(&part_id);
2060 Ok(())
2061 })?;
2062
2063 let mut warnings = Vec::new();
2064 if to == Lifecycle::Draft {
2065 warnings.extend(self.review_withdrawn(user, part_id, revision_id));
2066 }
2067 if to == Lifecycle::Released {
2068 let (part, revision) = self.snapshot(part_id, revision_id)?;
2069 let unreleased = self.read(|state| bom::unreleased_children(state, &revision));
2072 if !unreleased.is_empty() {
2073 warnings.push(format!("released, but it uses unreleased parts: {}", unreleased.join("; ")));
2074 }
2075 let input = self.read(|state| release_input(state, &part, &revision, user));
2076 match scripting::run(self, user, scripting::AFTER_RELEASE, "afterRelease", &input) {
2077 Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => {}
2078 Ok(HookResult::Refused(failure)) => warnings.push(format!(
2079 "released, but {} failed: {}",
2080 scripting::AFTER_RELEASE,
2081 failure.message
2082 )),
2083 Err(error) => warnings.push(format!(
2084 "released, but {} could not run: {}",
2085 scripting::AFTER_RELEASE,
2086 error.message
2087 )),
2088 }
2089 }
2090 Ok(warnings)
2091 }
2092
2093 pub(crate) fn snapshot(&self, part_id: &str, revision_id: &str) -> Result<(Part, Revision), Error> {
2095 self.read(|state| {
2096 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2097 let revision = part
2098 .revision(revision_id)
2099 .ok_or_else(|| Error::not_found("revision"))?;
2100 Ok((part.clone(), revision.clone()))
2101 })
2102 }
2103
2104 pub fn delete_draft(&self, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2107 let user_id = user.id.clone();
2108 let may_break = user.can_checkin();
2109 let key = crate::identity::document_key(part_id, revision_id);
2110 let root = self.root().to_path_buf();
2111 self.mutate(|state| {
2112 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2113 if !revision.lifecycle.is_editable() {
2114 return Err(Error::conflict(
2115 "only a draft can be deleted — release history is permanent".to_string(),
2116 ));
2117 }
2118 if let Some(lock) = &revision.lock {
2119 if lock.user_id != user_id && !may_break {
2120 return Err(Error::forbidden(
2121 "another user has this draft checked out",
2122 ));
2123 }
2124 }
2125 let part = state.parts.get_mut(&part_id)
2126 .ok_or_else(|| Error::not_found("part"))?;
2127 if part.revisions.len() == 1 {
2128 return Err(Error::conflict(
2129 "a part keeps at least one revision".to_string(),
2130 ));
2131 }
2132 if let Some((parent, rev)) = pinned_by(state, part_id, revision_id) {
2135 return Err(Error::conflict(format!(
2136 "this revision is used by {parent} rev {rev} — remove it from that list first"
2137 )));
2138 }
2139 let part = state.parts.get_mut(&part_id)
2140 .ok_or_else(|| Error::not_found("part"))?;
2141 let thumbnail = part.revision(revision_id).and_then(|r| r.thumbnail.as_ref()).map(|t| t.sha256.clone());
2142 part.revisions.retain(|r| r.id != revision_id);
2143 if let Some(sha) = thumbnail {
2144 crate::attach::remove_if_unreferenced(state, &root, &sha)?;
2145 }
2146 state.touch(key.clone());
2147 Ok(())
2148 })?;
2149 self.remove_document(&key)
2150 }
2151
2152 pub fn changes_since(&self, since: u64) -> (u64, bool, Vec<String>) {
2155 self.read(|state| {
2156 let stale = since < state.changes_floor();
2157 let keys: Vec<String> = state
2158 .changes
2159 .iter()
2160 .filter(|c| c.seq > since)
2161 .map(|c| c.key.clone())
2162 .collect::<BTreeSet<_>>()
2163 .into_iter()
2164 .collect();
2165 (state.seq, stale, keys)
2166 })
2167 }
2168}
2169
2170#[derive(Debug, Clone, Default)]
2177pub struct CategoryChange {
2178 pub name: Option<String>,
2179 pub parent: Option<String>,
2181 pub attributes: Option<Vec<AttributeDef>>,
2183}
2184
2185impl Db {
2186 pub fn create_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2190 let id = catalog::normalize_id(id)?;
2191 let name = change.name.unwrap_or_default().trim().to_string();
2192 if name.is_empty() {
2193 return Err(Error::bad_request("a category needs a name"));
2194 }
2195 let attributes = catalog::check_definitions(change.attributes.unwrap_or_default())?;
2196 let parent = change.parent.unwrap_or_default().trim().to_string();
2197 self.mutate(move |state| {
2198 if catalog::find(&state.categories, &id).is_some() {
2199 return Err(Error::conflict(format!("category '{id}' exists")));
2200 }
2201 let parent = if parent.is_empty() {
2202 String::new()
2203 } else {
2204 catalog::find(&state.categories, &parent)
2205 .map(|c| c.id.clone())
2206 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2207 };
2208 let category = Category { id, name, parent, attributes, created_at: now() };
2209 state.categories.push(category.clone());
2210 catalog::check_tree(&state.categories)?;
2211 Ok(category)
2212 })
2213 }
2214
2215 pub fn update_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
2222 let attributes = change.attributes.map(catalog::check_definitions).transpose()?;
2223 let id = id.trim().to_string();
2224 self.mutate(move |state| {
2225 let index = state
2226 .categories
2227 .iter()
2228 .position(|c| c.id.eq_ignore_ascii_case(&id))
2229 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
2230 if let Some(name) = change.name {
2231 let name = name.trim().to_string();
2232 if name.is_empty() {
2233 return Err(Error::bad_request("a category needs a name"));
2234 }
2235 state.categories[index].name = name;
2236 }
2237 if let Some(parent) = change.parent {
2238 let parent = parent.trim();
2239 state.categories[index].parent = if parent.is_empty() {
2240 String::new()
2241 } else {
2242 catalog::find(&state.categories, parent)
2243 .map(|c| c.id.clone())
2244 .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
2245 };
2246 }
2247 if let Some(attributes) = attributes {
2248 state.categories[index].attributes = attributes;
2249 }
2250 catalog::check_tree(&state.categories)?;
2254 Ok(state.categories[index].clone())
2255 })
2256 }
2257
2258 pub fn delete_category(&self, id: &str) -> Result<(), Error> {
2262 let id = id.trim().to_string();
2263 self.mutate(move |state| {
2264 let category = catalog::find(&state.categories, &id)
2265 .ok_or_else(|| Error::not_found(format!("category '{id}'")))?
2266 .id
2267 .clone();
2268 if let Some(child) = state.categories.iter().find(|c| c.parent.eq_ignore_ascii_case(&category)) {
2269 return Err(Error::conflict(format!(
2270 "category '{category}' has a sub-category '{}' — move or delete it first",
2271 child.id
2272 )));
2273 }
2274 let used = state
2275 .parts
2276 .iter()
2277 .filter(|p| p.category.eq_ignore_ascii_case(&category))
2278 .count();
2279 if used > 0 {
2280 return Err(Error::conflict(format!(
2281 "category '{category}' holds {used} part{} — move them to another category first",
2282 if used == 1 { "" } else { "s" }
2283 )));
2284 }
2285 state.categories.retain(|c| c.id != category);
2286 Ok(())
2287 })
2288 }
2289}
2290
2291fn part_matches(categories: &[Category], part: &Part, needle: &str) -> bool {
2294 let hit = |text: &str| text.to_ascii_lowercase().contains(needle);
2295 hit(&part.number)
2296 || hit(&part.name)
2297 || hit(&part.description)
2298 || hit(&part.category)
2299 || hit(&catalog::path_name(categories, &part.category))
2300 || part.tags.iter().any(|t| hit(t))
2301 || part.attributes.values().any(|value| match value {
2302 Value::String(text) => hit(text),
2303 Value::Number(n) => hit(&n.to_string()),
2304 _ => false,
2305 })
2306 || part.sourcing.iter().any(|mp| hit(&mp.mpn) || mp.offers.iter().any(|o| hit(&o.spn)))
2307}
2308
2309fn catalog_gate(categories: &[Category], part: &Part) -> Result<(), Error> {
2313 let problems = catalog::release_problems(categories, part);
2314 if problems.is_empty() {
2315 return Ok(());
2316 }
2317 Err(Error::conflict(format!(
2318 "{} cannot release until its catalog values are complete: {}",
2319 part.number,
2320 problems.join("; ")
2321 )))
2322}
2323
2324fn review_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2326 let (rule, _) = crate::review::rule_for(&state.settings, &state.categories, part);
2327 crate::review::release_gate(revision, &rule, &part.number)
2328}
2329
2330fn children_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
2331 if !state.settings.require_released_children {
2332 return Ok(());
2333 }
2334 let problems = bom::unreleased_children(state, revision);
2335 if problems.is_empty() {
2336 return Ok(());
2337 }
2338 Err(Error::conflict(format!(
2339 "{} rev {} cannot release until everything it uses is released: {}",
2340 part.number,
2341 revision.label,
2342 problems.join("; ")
2343 )))
2344}
2345
2346fn pinned_by(state: &State, part_id: &str, revision_id: &str) -> Option<(String, String)> {
2349 state.parts.iter().find_map(|parent| {
2350 parent.revisions.iter().find_map(|rev| {
2351 rev.uses
2352 .iter()
2353 .any(|u| u.part == part_id && u.revision == revision_id)
2354 .then(|| (parent.number.clone(), rev.label.clone()))
2355 })
2356 })
2357}
2358
2359pub fn check_writable(state: &State, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
2363 let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
2364 let revision = part
2365 .revision(revision_id)
2366 .ok_or_else(|| Error::not_found("revision"))?;
2367 if !revision.lifecycle.is_editable() {
2368 return Err(Error::conflict(format!(
2369 "{} revision {} is {} and cannot be written — start a new revision",
2370 part.number,
2371 revision.label,
2372 revision.lifecycle.as_str()
2373 )));
2374 }
2375 match &revision.lock {
2376 None => Err(Error::conflict(format!(
2377 "{} revision {} is not checked out — check it out before saving",
2378 part.number, revision.label
2379 ))),
2380 Some(lock) if lock.user_id != user.id => {
2381 let holder = state
2382 .user(&lock.user_id)
2383 .map(|u| u.username.clone())
2384 .unwrap_or_else(|| "another user".to_string());
2385 Err(Error::conflict(format!(
2386 "{} revision {} is checked out by {holder}",
2387 part.number, revision.label
2388 )))
2389 }
2390 Some(_) => Ok(()),
2391 }
2392}
2393
2394impl Db {
2395 pub fn set_uses(&self, user: &User, part_id: &str, revision_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
2402 let user = user.clone();
2403 let body = body.clone();
2404 self.mutate(move |state| {
2405 check_writable(state, &user, part_id, revision_id)?;
2406 let uses = bom::check_uses(state, part_id, &body)?;
2407 let occurrences = crate::bom_config::capture_occurrences(state, part_id, revision_id, &body)?;
2408 let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
2409 revision.uses = uses.clone();
2410 if let Some(occurrences) = occurrences { revision.occurrences = occurrences; }
2411 crate::bom_config::synchronize_uses(revision);
2412 revision.modified_at = now();
2413 state.touch(crate::identity::document_key(part_id, revision_id));
2414 Ok(uses)
2415 })
2416 }
2417}
2418
2419pub(crate) fn release_input(state: &State, part: &Part, revision: &Revision, user: &User) -> Value {
2421 json!({
2422 "part": part,
2423 "sourcing": sourcing::resolved(state, part),
2424 "revision": revision,
2425 "uses": bom::resolved_uses(state, revision),
2426 "unreleased_children": bom::unreleased_children(state, revision),
2427 "document_key": revision.document_key(&part.id),
2428 "user": scripting::user_json(user),
2429 })
2430}
2431
2432fn state_has_number(parts: &[Part], number: &str) -> bool {
2434 parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
2435}
2436
2437pub fn full_match(pattern: &str) -> Result<regex::Regex, Error> {
2440 regex::Regex::new(&format!("^(?:{pattern})$"))
2441 .map_err(|e| Error::bad_request(format!("'{pattern}' is not a usable pattern: {e}")))
2442}
2443
2444pub const MAX_IDENTIFIER: usize = 64;
2446
2447pub fn check_number(number: &str) -> Result<(), Error> {
2450 check_identifier(number, "a part number")
2451}
2452
2453pub fn check_label(label: &str) -> Result<(), Error> {
2455 check_identifier(label, "a revision label")
2456}
2457
2458fn check_identifier(text: &str, what: &str) -> Result<(), Error> {
2459 if text.trim().is_empty() {
2460 return Err(Error::bad_request(format!("{what} cannot be empty")));
2461 }
2462 if text.trim() != text {
2463 return Err(Error::bad_request(format!("{what} cannot start or end with a space")));
2464 }
2465 if text.chars().any(char::is_control) {
2466 return Err(Error::bad_request(format!("{what} cannot hold control characters")));
2467 }
2468 if text.chars().count() > MAX_IDENTIFIER {
2469 return Err(Error::bad_request(format!("{what} is at most {MAX_IDENTIFIER} characters")));
2470 }
2471 Ok(())
2472}
2473
2474pub fn suggest_label(part: &Part) -> String {
2479 let mut candidate = lifecycle::next_revision_label(part.latest().map(|r| r.label.as_str()));
2480 while part.revision_by_label(&candidate).is_some() {
2481 candidate = lifecycle::next_revision_label(Some(&candidate));
2482 }
2483 candidate
2484}
2485
2486#[derive(Debug, Clone, Default)]
2489pub struct PartSpec {
2490 pub part_type: String,
2491 pub number: String,
2492 pub name: String,
2493 pub description: String,
2494 pub category: String,
2495 pub document_class: DocumentClass,
2496 pub label: String,
2497 pub tags: Vec<String>,
2498 pub attributes: serde_json::Map<String, Value>,
2501 pub exact: bool,
2504 pub external_ref: String,
2507 pub origin: crate::model::Origin,
2510 pub workspace: Option<String>,
2514}
2515
2516pub fn external_ref_clash(state: &State, part_type: &str, external_ref: &str, except: &str) -> Result<(), Error> {
2522 if external_ref.is_empty() {
2523 return Ok(());
2524 }
2525 match state.parts.iter().find(|p| p.id != except && p.part_type == part_type && p.external_ref == external_ref) {
2526 Some(owner) => Err(Error::conflict(format!(
2527 "external_ref '{external_ref}' is already {} ({}) — look it up with ?external_ref= and use that part",
2528 owner.number, part_type
2529 ))),
2530 None => Ok(()),
2531 }
2532}
2533
2534pub fn check_origin(origin: crate::model::Origin) -> Result<(), Error> {
2536 if origin == crate::model::Origin::Generated {
2537 return Err(Error::bad_request("origin 'generated' is set by Generate alone — use authored or imported"));
2538 }
2539 Ok(())
2540}
2541
2542pub(crate) fn find_revision_mut<'a>(
2544 state: &'a mut State,
2545 part_id: &str,
2546 revision_id: &str,
2547) -> Result<(String, &'a mut Revision), Error> {
2548 let part = state.parts.get_mut(&part_id)
2549 .ok_or_else(|| Error::not_found("part"))?;
2550 let number = part.number.clone();
2551 let revision = part
2552 .revision_mut(revision_id)
2553 .ok_or_else(|| Error::not_found("revision"))?;
2554 Ok((number, revision))
2555}