Skip to main content

brep_plm/
jobs.rs

1//! The jobs floor queue: serialized builds of released manufacturing
2//! instructions, signed off step by step on the shop floor.
3//!
4//! One job is one build of one released instructions revision. Its steps are
5//! a snapshot of that revision's step order (reading order: a step's children
6//! before it), taken when the job is made; a released document never changes, so
7//! the snapshot is what the floor builds. Each step is signed once, in order,
8//! by an operator (or an author or admin), who records the serial of every
9//! unit the step adds of a part marked `Serial_Tracked` and the values of the
10//! step's fields (what its author asked to be recorded there: ticks, choices,
11//! text, measurements, serial numbers), which the server reads against the
12//! field definitions it snapshot with the step: a required field left empty,
13//! a value the field cannot hold, or a measurement outside limits that must
14//! be inside refuses the sign-off, whatever the page checked. A serial of a part
15//! is in at most one job that is not cancelled: `GET /api/serials` answers
16//! which build took it. Only the check-in group reopens a signed step (and every step after
17//! it), and the audit keeps both.
18//!
19//! No inventory: no stock, no locations, no consumption. The queue is a step
20//! towards an ERP system, not one.
21//!
22//! Every write below is one read-modify-write inside [`Db::mutate`], which
23//! holds the store's write lock from the first read to the commit: two
24//! tablets never both read a step unsigned, and no write is lost. Jobs are
25//! journaled ([`crate::journal::Journaled`]): a write stores and audits only
26//! the jobs it touched, one `meta` row each.
27
28use 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    /// Queued or in progress: its serials are taken.
57    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    /// `JOB000001`: handed out in order, never reused.
65    pub id: String,
66    pub instructions: Instructs,
67    pub assembly: Instructs,
68    /// The serial of the unit being built, when it has one.
69    #[serde(default)]
70    pub serial: String,
71    pub status: JobStatus,
72    /// The queue's order: lowest first, ties by number.
73    pub position: i64,
74    /// A user id, or empty for anyone.
75    #[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    /// The store sequence of the job's last change: a floor tablet polls
84    /// the queue and re-reads what moved.
85    #[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    /// The instructions' step id.
93    pub step: String,
94    /// The sub-assembly the step helps build (the occurrence its parent step
95    /// places): empty at the top level. Named for the chapters that held a
96    /// sub-assembly's steps before the step tree.
97    #[serde(default)]
98    pub chapter: String,
99    #[serde(default)]
100    pub title: String,
101    /// What the step adds, with the units that need a serial.
102    #[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    /// The step's fields as the instructions define them (a snapshot, like
113    /// the adds): what the sign-off's values are read against. Empty for a
114    /// step without fields and for a job made before fields existed.
115    #[serde(default, skip_serializing_if = "Vec::is_empty")]
116    pub field_defs: Vec<brep_instructions::fields::StepField>,
117    /// The values recorded at sign-off, one per field that was filled in.
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub fields: Vec<FieldEntry>,
120}
121
122/// One field's recorded value.
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub struct FieldEntry {
125    /// The field's id in the instructions (`MF12`).
126    pub id: String,
127    /// Its label when the step was signed.
128    #[serde(default)]
129    pub label: String,
130    /// `true` for a tick, the option (or an array of them) for a choice,
131    /// text, or a number for a measurement.
132    pub value: Value,
133    /// A measurement's unit.
134    #[serde(default, skip_serializing_if = "String::is_empty")]
135    pub unit: String,
136    /// A measurement with limits: whether the value was inside them, as
137    /// the server judged it.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub in_limits: Option<bool>,
140}
141
142/// One field's value as a sign-off sends it. A page may send the label,
143/// unit and its own in-limits reading beside it; the server takes only the
144/// id and the value and works the rest out from the step's definitions.
145#[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    /// One occurrence path per unit (`ACOMP1:ACOMP3`).
155    pub occurrences: Vec<String>,
156    /// The PLM part id when the add names a part this server knows, else
157    /// the document's text.
158    #[serde(default)]
159    pub part: String,
160    /// One serial per occurrence at sign-off: the part's `Serial_Tracked`
161    /// attribute, or the document marks the add.
162    pub serial_tracked: bool,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub struct SerialEntry {
167    pub occurrence: String,
168    /// The PLM part. A sign-off need not send it: the server takes it from
169    /// the step's add for that occurrence.
170    #[serde(default)]
171    pub part: String,
172    pub serial: String,
173}
174
175/// Whether a part (its newest revision's type attributes, then its catalog
176/// attributes) is marked `Serial_Tracked`, the attribute name the app and
177/// server agreed (matched without regard to case).
178pub 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
188/// The sub-assembly a step helps build: the occurrence its parent step
189/// places; empty at the top level.
190fn 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
199/// The steps a job signs, read with the instructions crate's own model (a
200/// schema-1 document's chapters read as the tree): every step in reading
201/// order (a step's children before it, as the wizard orders them), leaving
202/// out a step that needs no sign-off and records nothing (a step with fields
203/// is on the checklist: its values are captured with its sign-off).
204pub 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        // A step that needs no sign-off and has no field to record is not on
211        // the floor's checklist.
212        .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
247/// Who may sign a step: operators, authors and admins.
248pub 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
252/// Who may reopen a signed step: the check-in group and admins.
253pub fn can_reopen(user: &User) -> bool {
254    [groups::CHECKIN, groups::ADMIN].iter().any(|g| user.groups.iter().any(|u| u == g))
255}
256
257/// Where a part's serial is taken: the job (live or done; a cancelled job
258/// frees its serials) and the step that took it.
259pub 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    /// The instructions part, by id or number.
271    pub instructions: String,
272    /// Its revision, by id or label: a released one.
273    pub revision: String,
274    #[serde(default)]
275    pub serial: String,
276    /// How many jobs to queue (each its own build). One by default.
277    #[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    /// The values of the step's fields: `[{id, value}]`.
288    #[serde(default)]
289    pub fields: Vec<FieldInput>,
290}
291
292/// The sign-off's field values read against the step's definitions: one
293/// entry per field that was filled in, in the step's order. Refused: a value
294/// for a field the step does not have, a field given twice, a value its
295/// field cannot hold, a required field left empty, and a measurement outside
296/// limits that must be inside.
297pub 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    /// Queue `quantity` jobs building one released instructions revision.
327    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        // The document is read outside the lock: a released revision's bytes
337        // never change, and the lifecycle is checked again inside it.
338        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    /// Change a job's place in the queue, who it is assigned to, or cancel
398    /// it (`status: "cancelled"`; a cancelled job frees its serials).
399    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    /// Sign one step of a job, in order, with the serials it captures.
436    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            // Exactly one serial per occurrence of each serial-tracked add,
466            // and no serial for anything else.
467            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    /// Reopen a signed step and every step after it: the check-in group, with
514    /// a reason the audit keeps. A done job is in progress again.
515    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}