1use std::collections::BTreeSet;
29
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32
33use crate::db::{now, Db, State};
34use crate::model::{groups, DocumentClass, Instructs, Lifecycle, Timestamp, User};
35use crate::Error;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum JobStatus {
40 Queued,
41 InProgress,
42 Done,
43 Cancelled,
44}
45
46impl JobStatus {
47 pub fn as_str(self) -> &'static str {
48 match self {
49 JobStatus::Queued => "queued",
50 JobStatus::InProgress => "in_progress",
51 JobStatus::Done => "done",
52 JobStatus::Cancelled => "cancelled",
53 }
54 }
55
56 pub fn is_live(self) -> bool {
58 matches!(self, JobStatus::Queued | JobStatus::InProgress)
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct Job {
64 pub id: String,
66 pub instructions: Instructs,
67 pub assembly: Instructs,
68 #[serde(default)]
70 pub serial: String,
71 pub status: JobStatus,
72 pub position: i64,
74 #[serde(default)]
76 pub assigned_to: String,
77 pub created_by: String,
78 pub created_at: Timestamp,
79 #[serde(default)]
80 pub started_at: Option<Timestamp>,
81 #[serde(default)]
82 pub finished_at: Option<Timestamp>,
83 #[serde(default)]
86 pub modified_seq: u64,
87 pub steps: Vec<JobStep>,
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91pub struct JobStep {
92 pub step: String,
94 #[serde(default)]
98 pub chapter: String,
99 #[serde(default)]
100 pub title: String,
101 #[serde(default)]
103 pub adds: Vec<JobAdd>,
104 #[serde(default)]
105 pub signed_by: Option<String>,
106 #[serde(default)]
107 pub signed_at: Option<Timestamp>,
108 #[serde(default)]
109 pub note: String,
110 #[serde(default)]
111 pub serials: Vec<SerialEntry>,
112 #[serde(default, skip_serializing_if = "Vec::is_empty")]
116 pub field_defs: Vec<brep_instructions::fields::StepField>,
117 #[serde(default, skip_serializing_if = "Vec::is_empty")]
119 pub fields: Vec<FieldEntry>,
120}
121
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub struct FieldEntry {
125 pub id: String,
127 #[serde(default)]
129 pub label: String,
130 pub value: Value,
133 #[serde(default, skip_serializing_if = "String::is_empty")]
135 pub unit: String,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub in_limits: Option<bool>,
140}
141
142#[derive(Debug, Clone, Deserialize)]
146pub struct FieldInput {
147 pub id: String,
148 #[serde(default)]
149 pub value: Value,
150}
151
152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
153pub struct JobAdd {
154 pub occurrences: Vec<String>,
156 #[serde(default)]
159 pub part: String,
160 pub serial_tracked: bool,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub struct SerialEntry {
167 pub occurrence: String,
168 #[serde(default)]
171 pub part: String,
172 pub serial: String,
173}
174
175pub fn serial_tracked(state: &State, part_id: &str) -> bool {
179 let Some(part) = state.part(part_id) else { return false };
180 let truthy = |map: &std::collections::BTreeMap<String, Value>| {
181 map.iter().find(|(k, _)| k.eq_ignore_ascii_case("serial_tracked")).is_some_and(|(_, v)| {
182 v.as_bool().unwrap_or(false) || v.as_str().is_some_and(|s| matches!(s.trim().to_ascii_lowercase().as_str(), "true" | "yes" | "1"))
183 })
184 };
185 part.latest().is_some_and(|r| truthy(&r.attributes)) || truthy(&part.attributes)
186}
187
188fn group_of(instructions: &brep_instructions::model::Instructions, step_id: &str) -> String {
191 instructions
192 .parent_id(step_id)
193 .flatten()
194 .and_then(|parent| instructions.step(parent))
195 .and_then(|parent| parent.adds.iter().find(|add| add.subassembly).and_then(|add| add.occurrences.first().cloned()))
196 .unwrap_or_default()
197}
198
199pub fn snapshot_steps(state: &State, document: &Value) -> Result<Vec<JobStep>, Error> {
205 let block = document.get(brep_instructions::model::BLOCK_KEY).ok_or_else(|| Error::conflict("the document holds no instructions"))?;
206 let instructions = brep_instructions::model::Instructions::from_value(block)
207 .map_err(|e| Error::conflict(format!("the instructions do not read: {e}")))?;
208 let steps: Vec<JobStep> = instructions
209 .steps()
210 .filter(|(_, step)| step.on_checklist())
213 .map(|(_, step)| JobStep {
214 step: step.id.clone(),
215 chapter: group_of(&instructions, &step.id),
216 title: step.title.clone(),
217 adds: step
218 .adds
219 .iter()
220 .map(|add| {
221 let known = state.part_by_id_or_number(&add.part).map(|p| p.id.clone());
222 JobAdd {
223 occurrences: add.occurrences.clone(),
224 serial_tracked: add.serial_tracked || known.as_deref().is_some_and(|id| serial_tracked(state, id)),
225 part: known.unwrap_or_else(|| add.part.clone()),
226 }
227 })
228 .collect(),
229 signed_by: None,
230 signed_at: None,
231 note: String::new(),
232 serials: Vec::new(),
233 field_defs: step.fields.clone(),
234 fields: Vec::new(),
235 })
236 .collect();
237 if steps.is_empty() {
238 return Err(Error::conflict("the instructions have no steps to build"));
239 }
240 let mut seen = BTreeSet::new();
241 if let Some(twice) = steps.iter().find(|s| !seen.insert(s.step.clone())) {
242 return Err(Error::conflict(format!("step id {} is used twice", twice.step)));
243 }
244 Ok(steps)
245}
246
247pub fn can_sign(user: &User) -> bool {
249 [groups::OPERATOR, groups::AUTHOR, groups::ADMIN].iter().any(|g| user.groups.iter().any(|u| u == g))
250}
251
252pub fn can_reopen(user: &User) -> bool {
254 [groups::CHECKIN, groups::ADMIN].iter().any(|g| user.groups.iter().any(|u| u == g))
255}
256
257pub fn serial_holder<'a>(state: &'a State, part: &str, serial: &str) -> Option<(&'a Job, &'a JobStep)> {
260 state.jobs.iter().filter(|j| j.status != JobStatus::Cancelled).find_map(|job| {
261 job.steps
262 .iter()
263 .find(|s| s.serials.iter().any(|e| e.part == part && e.serial.eq_ignore_ascii_case(serial)))
264 .map(|s| (job, s))
265 })
266}
267
268#[derive(Debug, Clone, Deserialize)]
269pub struct NewJob {
270 pub instructions: String,
272 pub revision: String,
274 #[serde(default)]
275 pub serial: String,
276 #[serde(default)]
278 pub quantity: Option<u32>,
279}
280
281#[derive(Debug, Clone, Deserialize)]
282pub struct SignOff {
283 #[serde(default)]
284 pub serials: Vec<SerialEntry>,
285 #[serde(default)]
286 pub note: String,
287 #[serde(default)]
289 pub fields: Vec<FieldInput>,
290}
291
292pub fn read_fields(step: &JobStep, given: &[FieldInput]) -> Result<Vec<FieldEntry>, Error> {
298 use brep_instructions::fields::{blocking, evaluate};
299 for (i, input) in given.iter().enumerate() {
300 if !step.field_defs.iter().any(|f| f.id == input.id) {
301 return Err(Error::conflict(format!("step {} has no field '{}'", step.step, input.id)));
302 }
303 if given[..i].iter().any(|earlier| earlier.id == input.id) {
304 return Err(Error::bad_request(format!("field '{}' is given twice", input.id)));
305 }
306 }
307 let mut entries = Vec::new();
308 let mut open = Vec::new();
309 for field in &step.field_defs {
310 let value = given.iter().find(|input| input.id == field.id).map(|input| &input.value);
311 let read = evaluate(field, value).map_err(Error::bad_request)?;
312 if let Some(reason) = blocking(field, &read) {
313 open.push(reason);
314 }
315 if let Some(value) = read.value {
316 entries.push(FieldEntry { id: field.id.clone(), label: field.label.clone(), value, unit: field.unit().to_string(), in_limits: read.in_limits });
317 }
318 }
319 if !open.is_empty() {
320 return Err(Error::conflict(format!("step {} is not complete: {}", step.step, open.join("; "))));
321 }
322 Ok(entries)
323}
324
325impl Db {
326 pub fn create_jobs(&self, user: &User, request: &NewJob) -> Result<Vec<Job>, Error> {
328 let quantity = request.quantity.unwrap_or(1);
329 if !(1..=500).contains(&quantity) {
330 return Err(Error::bad_request("a request queues 1 to 500 jobs"));
331 }
332 let serial = request.serial.trim().to_string();
333 if quantity > 1 && !serial.is_empty() {
334 return Err(Error::bad_request("a serial names one build: queue one job for it"));
335 }
336 let (part_id, revision_id, path) = self.read(|state| {
339 let part = state.part_by_id_or_number(&request.instructions).ok_or_else(|| Error::not_found("instructions"))?;
340 if part.document_class != DocumentClass::Instructions {
341 return Err(Error::bad_request(format!("{} is not manufacturing instructions", part.number)));
342 }
343 let revision = crate::bom::find_revision(part, &request.revision).ok_or_else(|| Error::not_found("revision"))?;
344 Ok((part.id.clone(), revision.id.clone(), crate::identity::model_path(&part.id, &revision.id)))
345 })?;
346 let document: Value = std::fs::read_to_string(self.root().join(path))
347 .ok()
348 .and_then(|text| serde_json::from_str(&text).ok())
349 .ok_or_else(|| Error::conflict("the instructions revision has no readable document"))?;
350 let user_id = user.id.clone();
351 self.mutate(move |state| {
352 let part = state.part(&part_id).ok_or_else(|| Error::not_found("instructions"))?;
353 let revision = part.revision(&revision_id).ok_or_else(|| Error::not_found("revision"))?;
354 if revision.lifecycle != Lifecycle::Released {
355 return Err(Error::conflict(format!(
356 "{} rev {} is {}: the floor builds released instructions only",
357 part.number,
358 revision.label,
359 revision.lifecycle.as_str()
360 )));
361 }
362 let assembly = revision.instructs.clone().ok_or_else(|| Error::conflict("the instructions instruct no PLM assembly"))?;
363 let steps = snapshot_steps(state, &document)?;
364 if !serial.is_empty() {
365 if let Some(job) = state.jobs.iter().find(|j| j.status != JobStatus::Cancelled && j.assembly.part == assembly.part && j.serial.eq_ignore_ascii_case(&serial)) {
366 return Err(Error::conflict(format!("serial {serial} is {} by {}", if job.status == JobStatus::Done { "already built" } else { "already being built" }, job.id)));
367 }
368 }
369 let mut position = state.jobs.iter().filter(|j| j.status.is_live()).map(|j| j.position).max().unwrap_or(0);
370 let stamp = now();
371 let mut made = Vec::new();
372 for _ in 0..quantity {
373 state.next_job += 1;
374 position += 1;
375 let job = Job {
376 id: format!("JOB{:06}", state.next_job),
377 instructions: Instructs { part: part_id.clone(), revision: revision_id.clone() },
378 assembly: assembly.clone(),
379 serial: serial.clone(),
380 status: JobStatus::Queued,
381 position,
382 assigned_to: String::new(),
383 created_by: user_id.clone(),
384 created_at: stamp,
385 started_at: None,
386 finished_at: None,
387 modified_seq: state.seq,
388 steps: steps.clone(),
389 };
390 state.jobs.push(job.clone());
391 made.push(job);
392 }
393 Ok(made)
394 })
395 }
396
397 pub fn update_job(&self, id: &str, fields: &Value) -> Result<Job, Error> {
400 let fields = fields.as_object().cloned().ok_or_else(|| Error::bad_request("a job change is a JSON object"))?;
401 if let Some(key) = fields.keys().find(|k| !["position", "assigned_to", "status"].contains(&k.as_str())) {
402 return Err(Error::bad_request(format!("a job has no field '{key}' to change")));
403 }
404 let id = id.to_string();
405 self.mutate(move |state| {
406 if let Some(user) = fields.get("assigned_to").and_then(Value::as_str).filter(|u| !u.is_empty()) {
407 if state.user(user).is_none() {
408 return Err(Error::bad_request(format!("no user '{user}'")));
409 }
410 }
411 let seq = state.seq;
412 let job = state.jobs.get_mut(&id).ok_or_else(|| Error::not_found("job"))?;
413 if !job.status.is_live() {
414 return Err(Error::conflict(format!("{} is {}", job.id, job.status.as_str())));
415 }
416 if let Some(position) = fields.get("position") {
417 job.position = position.as_i64().ok_or_else(|| Error::bad_request("position is a whole number"))?;
418 }
419 if let Some(user) = fields.get("assigned_to") {
420 job.assigned_to = user.as_str().ok_or_else(|| Error::bad_request("assigned_to is a user id"))?.to_string();
421 }
422 match fields.get("status").map(|s| s.as_str()) {
423 None => {}
424 Some(Some("cancelled")) => {
425 job.status = JobStatus::Cancelled;
426 job.finished_at = Some(now());
427 }
428 Some(_) => return Err(Error::bad_request("a job's status changes only to cancelled; sign-off moves the rest")),
429 }
430 job.modified_seq = seq;
431 Ok(job.clone())
432 })
433 }
434
435 pub fn sign_step(&self, user: &User, id: &str, step: &str, signoff: &SignOff) -> Result<JobStep, Error> {
437 if !can_sign(user) {
438 return Err(Error::forbidden("signing a step needs the operator, author or admin group"));
439 }
440 let (id, step, user_id) = (id.to_string(), step.to_string(), user.id.clone());
441 let mut signoff = signoff.clone();
442 for entry in &mut signoff.serials {
443 entry.serial = entry.serial.trim().to_string();
444 if entry.serial.is_empty() || entry.serial.chars().count() > 120 {
445 return Err(Error::bad_request("a serial is 1 to 120 characters"));
446 }
447 }
448 if signoff.note.chars().count() > 2000 {
449 return Err(Error::bad_request("a sign-off note is at most 2000 characters"));
450 }
451 self.mutate(move |state| {
452 let job = state.jobs.get(&id).ok_or_else(|| Error::not_found("job"))?;
453 if !job.status.is_live() {
454 return Err(Error::conflict(format!("{} is {}: nothing more is signed", job.id, job.status.as_str())));
455 }
456 let at = job.steps.iter().position(|s| s.step == step).ok_or_else(|| Error::not_found("step"))?;
457 let this = &job.steps[at];
458 if let (Some(by), Some(when)) = (&this.signed_by, this.signed_at) {
459 let name = state.user(by).map_or_else(|| "someone".to_string(), |u| u.username.clone());
460 return Err(Error::conflict(format!("step {} of {} was signed by {name} at {when}", this.step, job.id)));
461 }
462 if let Some(earlier) = job.steps[..at].iter().find(|s| s.signed_at.is_none()) {
463 return Err(Error::conflict(format!("step {} of {} is not signed yet: steps are signed in order", earlier.step, job.id)));
464 }
465 let add_of = |occurrence: &str| this.adds.iter().find(|a| a.occurrences.iter().any(|o| o == occurrence));
468 if let Some(stray) = signoff.serials.iter().find(|e| add_of(&e.occurrence).is_none_or(|a| !a.serial_tracked)) {
469 return Err(Error::conflict(format!("step {} takes no serial for '{}'", this.step, stray.occurrence)));
470 }
471 for add in this.adds.iter().filter(|a| a.serial_tracked) {
472 for occurrence in &add.occurrences {
473 let given = signoff.serials.iter().filter(|e| &e.occurrence == occurrence).count();
474 if given != 1 {
475 return Err(Error::conflict(format!("{occurrence} takes one serial at step {}; {given} given", this.step)));
476 }
477 }
478 }
479 let fields = read_fields(this, &signoff.fields)?;
480 let mut serials = Vec::new();
481 for entry in &signoff.serials {
482 let part = add_of(&entry.occurrence).map(|a| a.part.clone()).unwrap_or_default();
483 if serials.iter().any(|e: &SerialEntry| e.part == part && e.serial.eq_ignore_ascii_case(&entry.serial)) {
484 return Err(Error::conflict(format!("serial {} is given twice", entry.serial)));
485 }
486 if let Some((holder, held_at)) = serial_holder(state, &part, &entry.serial) {
487 return Err(Error::conflict(format!("serial {} of {part} was taken by {} at step {}", entry.serial, holder.id, held_at.step)));
488 }
489 serials.push(SerialEntry { occurrence: entry.occurrence.clone(), part, serial: entry.serial.clone() });
490 }
491 let (seq, stamp) = (state.seq, now());
492 let job = state.jobs.get_mut(&id).expect("the job was read under this lock");
493 let signed = &mut job.steps[at];
494 signed.signed_by = Some(user_id);
495 signed.signed_at = Some(stamp);
496 signed.note = signoff.note.trim().to_string();
497 signed.serials = serials;
498 signed.fields = fields;
499 let signed = signed.clone();
500 if job.status == JobStatus::Queued {
501 job.status = JobStatus::InProgress;
502 job.started_at = Some(stamp);
503 }
504 if job.steps.iter().all(|s| s.signed_at.is_some()) {
505 job.status = JobStatus::Done;
506 job.finished_at = Some(stamp);
507 }
508 job.modified_seq = seq;
509 Ok(signed)
510 })
511 }
512
513 pub fn reopen_step(&self, user: &User, id: &str, step: &str, reason: &str) -> Result<Job, Error> {
516 if !can_reopen(user) {
517 return Err(Error::forbidden("reopening a signed step needs the check-in group"));
518 }
519 let reason = reason.trim().to_string();
520 if reason.is_empty() || reason.chars().count() > 2000 {
521 return Err(Error::bad_request("a reopen gives its reason (at most 2000 characters)"));
522 }
523 let (id, step) = (id.to_string(), step.to_string());
524 self.mutate(move |state| {
525 let seq = state.seq;
526 let job = state.jobs.get_mut(&id).ok_or_else(|| Error::not_found("job"))?;
527 if job.status == JobStatus::Cancelled {
528 return Err(Error::conflict(format!("{} is cancelled", job.id)));
529 }
530 let at = job.steps.iter().position(|s| s.step == step).ok_or_else(|| Error::not_found("step"))?;
531 if job.steps[at].signed_at.is_none() {
532 return Err(Error::conflict(format!("step {step} of {} is not signed", job.id)));
533 }
534 for later in &mut job.steps[at..] {
535 later.signed_by = None;
536 later.signed_at = None;
537 later.serials.clear();
538 later.fields.clear();
539 later.note = String::new();
540 }
541 job.steps[at].note = format!("reopened: {reason}");
542 job.status = if job.steps.iter().any(|s| s.signed_at.is_some()) { JobStatus::InProgress } else { JobStatus::Queued };
543 job.finished_at = None;
544 job.modified_seq = seq;
545 Ok(job.clone())
546 })
547 }
548}