Skip to main content

brep_plm/
review.rs

1//! Review and approval (round 9 item 4).
2//!
3//! Moving a revision to `InReview` opens a review round ([`Review`]) on it:
4//! who may decide, how many approvals the release needs, an optional due date.
5//! Reviewers approve, or reject with a comment; a rejection sends the revision
6//! back to Draft and ends the round, and the author submits again for a new
7//! one. Release is refused until the round's rule is met. Anyone who can read
8//! a part reads its discussion ([`Comment`]).
9//!
10//! # The rule
11//!
12//! The rule comes from the settings ([`Settings::review_rule`]) unless an
13//! override covers the part ([`Settings::review_overrides`]): the NEAREST
14//! category with one — the part's own, then its parent's, up to the root —
15//! then the part's type. The default needs 0 approvals, so until an
16//! administrator sets a rule a draft releases exactly as it did before
17//! reviews existed, and a submitted revision's round is approved the moment
18//! it opens.
19//!
20//! The rule is COPIED into the round when it opens. Changing the settings
21//! changes the next round, never one under way; an administrator or the
22//! check-in group can change a round's reviewers, required approvals and due
23//! date directly.
24//!
25//! # Hooks
26//!
27//! * `reviewers.js` — `reviewers(input)` runs when a revision is submitted,
28//!   outside the store lock, and may return `{ reviewers, required_approvals,
29//!   due, allow_self_approval }` to replace any of them, `null` for no opinion,
30//!   or throw to refuse the submission.
31//! * `review-event.js` — `reviewEvent(input)` runs after every review event
32//!   commits (opened, approve, reject, withdrawn, comment, updated). It
33//!   cannot undo anything: a throw comes back as a warning. This is the
34//!   notification hook — a webhook, a chat message, an email relay — since
35//!   scripts may make HTTP requests.
36//!
37//! The release gate itself stays in `beforeRelease`, which sees the revision
38//! and so its `reviews`.
39
40use serde::Serialize;
41use serde_json::{json, Value};
42
43use crate::catalog;
44use crate::db::{self, now, Db, State};
45use crate::lifecycle;
46use crate::model::{
47    groups, Comment, Decision, Lifecycle, Part, Review, ReviewOverride, ReviewRule, ReviewStatus, ReviewerKind,
48    ReviewerRef, Revision, Settings, User, Verdict,
49};
50use crate::scripting::{self, HookResult};
51use crate::Error;
52
53/// An override for a part type.
54pub const SCOPE_PART_TYPE: &str = "part_type";
55/// An override for a category and everything under it.
56pub const SCOPE_CATEGORY: &str = "category";
57
58/// The longest comment the server keeps.
59pub const MAX_COMMENT: usize = 10_000;
60
61/// The most approvals a rule may ask for — more is a typo.
62pub const MAX_APPROVALS: u32 = 50;
63
64// ===========================================================================
65// The rule
66// ===========================================================================
67
68/// The rule for `part`, and what decided it: `category:<id>`,
69/// `part-type:<id>` or `settings`.
70pub fn rule_for(settings: &Settings, categories: &[crate::model::Category], part: &Part) -> (ReviewRule, String) {
71    let find = |scope: &str, id: &str| -> Option<&ReviewOverride> {
72        settings
73            .review_overrides
74            .iter()
75            .find(|o| o.scope == scope && o.id.eq_ignore_ascii_case(id))
76    };
77    if let Ok(chain) = catalog::chain(categories, &part.category) {
78        // Root first; the nearest category wins, so walk it backwards.
79        for category in chain.iter().rev() {
80            if let Some(found) = find(SCOPE_CATEGORY, &category.id) {
81                return (found.rule.clone(), format!("category:{}", category.id));
82            }
83        }
84    }
85    if let Some(found) = find(SCOPE_PART_TYPE, &part.part_type) {
86        return (found.rule.clone(), format!("part-type:{}", part.part_type));
87    }
88    (settings.review_rule.clone(), "settings".to_string())
89}
90
91/// A new round from `rule`, opened by `by`.
92pub fn open_round(rule: &ReviewRule, source: &str, by: &str, at: u64) -> Review {
93    let mut review = Review {
94        id: crate::auth::new_id(),
95        status: ReviewStatus::Open,
96        opened_by: by.to_string(),
97        opened_at: at,
98        reviewers: rule.reviewers.clone(),
99        required_approvals: rule.required_approvals,
100        allow_self_approval: rule.allow_self_approval,
101        due: (rule.due_days > 0).then(|| at + u64::from(rule.due_days) * 86_400),
102        rule_source: source.to_string(),
103        decisions: Vec::new(),
104        closed_by: None,
105        closed_at: None,
106    };
107    // No decisions yet: only a rule needing none is met, whatever the hash.
108    refresh(&mut review, "");
109    review
110}
111
112/// Set a live round's status from its decisions, judged on the subject as it
113/// is now (`current`, its content hash): a rejection rejects it, a rule met
114/// by current approvals approves it, and otherwise it is open. A round
115/// approved on a document that has since been saved goes back to open.
116pub fn refresh(review: &mut Review, current: &str) {
117    if !review.is_live() {
118        return;
119    }
120    review.status = if review.decisions.iter().any(|d| d.verdict == Verdict::Reject) {
121        ReviewStatus::Rejected
122    } else if review.is_met(current) {
123        ReviewStatus::Approved
124    } else {
125        ReviewStatus::Open
126    };
127}
128
129/// What a change order's round decides on: every item's revision and its
130/// document's content hash, in a stable order, hashed. Saving any item's
131/// document — or changing the items — changes it, so approvals given before
132/// go stale as a revision's do.
133pub fn eco_subject_hash(state: &State, eco: &crate::model::ChangeOrder) -> String {
134    let mut lines: Vec<String> = eco
135        .items
136        .iter()
137        .map(|item| {
138            let hash = state
139                .part(&item.part_id)
140                .and_then(|p| p.revision(&item.revision_id))
141                .map(|r| r.content_hash.clone())
142                .unwrap_or_default();
143            serde_json::json!([item.part_id, item.revision_id, hash]).to_string()
144        })
145        .collect();
146    lines.sort();
147    crate::auth::content_hash(&lines.join("\n"))
148}
149
150/// A revision's document hash changed (a save, a bake result, a generated
151/// document): re-judge its live round, and every live change-order round
152/// naming it, on what the reviewers would now be approving. A change order
153/// whose round was approved goes back to in review until its approvals are
154/// renewed (and forward again if the document returns to what they saw).
155pub fn document_changed(state: &mut State, part_id: &str, revision_id: &str) {
156    if let Some(revision) = state.parts.get_mut(part_id).and_then(|p| p.revision_mut(revision_id)) {
157        let hash = revision.content_hash.clone();
158        if let Some(review) = revision.live_review_mut() {
159            refresh(review, &hash);
160        }
161    }
162    let affected: Vec<usize> = state
163        .change_orders
164        .iter()
165        .enumerate()
166        .filter(|(_, eco)| eco.state.is_open() && eco.items.iter().any(|i| i.part_id == part_id && i.revision_id == revision_id))
167        .filter(|(_, eco)| eco.reviews.last().is_some_and(|r| r.is_live()))
168        .map(|(i, _)| i)
169        .collect();
170    for index in affected {
171        let hash = eco_subject_hash(state, &state.change_orders[index]);
172        let eco = &mut state.change_orders[index];
173        if let Some(round) = eco.reviews.last_mut() {
174            refresh(round, &hash);
175            if matches!(eco.state, crate::model::EcoState::Approved | crate::model::EcoState::InReview) {
176                eco.state = if round.status == ReviewStatus::Approved {
177                    crate::model::EcoState::Approved
178                } else {
179                    crate::model::EcoState::InReview
180                };
181            }
182        }
183    }
184}
185
186/// Whether `user` is one of the round's reviewers — named, in a named group,
187/// or, when it names nobody, in the check-in group. Says nothing about
188/// whether their approval would COUNT ([`Review::approvers`]).
189pub fn is_reviewer(review: &Review, user: &User) -> bool {
190    if !user.active {
191        return false;
192    }
193    if review.reviewers.is_empty() {
194        return user.can_checkin();
195    }
196    review.reviewers.iter().any(|r| match r.kind {
197        ReviewerKind::User => r.id == user.id,
198        ReviewerKind::Group => user.in_group(&r.id),
199    })
200}
201
202/// Whether `user` may take part in a discussion: signed in, and more than a
203/// viewer or a bake worker.
204pub fn may_comment(user: &User) -> bool {
205    user.active && user.groups.iter().any(|g| g != groups::VIEWER && g != groups::WORKER)
206}
207
208/// Reviewers as the API and scripts give them — `"user:ada"`,
209/// `"group:quality"`, a bare username, or `{ kind, id }` with a user's id or
210/// username — as refs to users that exist and groups by name.
211pub fn parse_reviewers(state: &State, value: &Value) -> Result<Vec<ReviewerRef>, Error> {
212    let Some(items) = value.as_array() else {
213        return Err(Error::bad_request("reviewers must be a list, like [\"user:ada\", \"group:quality\"]"));
214    };
215    let mut out: Vec<ReviewerRef> = Vec::new();
216    for item in items {
217        let (kind, id) = match item {
218            Value::String(text) => match text.trim().split_once(':') {
219                Some((kind, id)) => (kind.trim().to_ascii_lowercase(), id.trim().to_string()),
220                None => ("user".to_string(), text.trim().to_string()),
221            },
222            Value::Object(map) => (
223                map.get("kind").and_then(Value::as_str).unwrap_or("user").trim().to_ascii_lowercase(),
224                map.get("id").and_then(Value::as_str).unwrap_or("").trim().to_string(),
225            ),
226            other => return Err(Error::bad_request(format!("{other} is not a reviewer"))),
227        };
228        if id.is_empty() {
229            return Err(Error::bad_request("a reviewer needs a user or a group"));
230        }
231        let reviewer = match kind.as_str() {
232            "user" => {
233                let user = state
234                    .user(&id)
235                    .or_else(|| state.user_by_name(&id))
236                    .ok_or_else(|| Error::bad_request(format!("there is no user '{id}'")))?;
237                ReviewerRef { kind: ReviewerKind::User, id: user.id.clone() }
238            }
239            "group" => {
240                db::check_label(&id).map_err(|_| Error::bad_request(format!("'{id}' is not a group name")))?;
241                ReviewerRef { kind: ReviewerKind::Group, id }
242            }
243            other => return Err(Error::bad_request(format!("'{other}' is not a reviewer kind — use user or group"))),
244        };
245        if !out.contains(&reviewer) {
246            out.push(reviewer);
247        }
248    }
249    Ok(out)
250}
251
252/// Rewrite the reviewer lists in a settings object as `{ kind, id }`, so a
253/// rule may be written with `"user:ada"` and `"group:quality"` shorthands.
254pub fn normalize_settings_json(state: &State, settings: &mut Value) -> Result<(), Error> {
255    let mut rules: Vec<&mut Value> = Vec::new();
256    let Some(object) = settings.as_object_mut() else { return Ok(()) };
257    let mut overrides = None;
258    for (key, value) in object.iter_mut() {
259        match key.as_str() {
260            "review_rule" | "eco_review_rule" => rules.push(value),
261            "review_overrides" => overrides = Some(value),
262            _ => {}
263        }
264    }
265    if let Some(Value::Array(items)) = overrides {
266        rules.extend(items.iter_mut().filter_map(|o| o.get_mut("rule")));
267    }
268    for rule in rules {
269        if let Some(reviewers) = rule.get_mut("reviewers") {
270            let parsed = parse_reviewers(state, reviewers)?;
271            *reviewers = serde_json::to_value(parsed).map_err(Error::internal)?;
272        }
273    }
274    Ok(())
275}
276
277/// Check a rule and resolve its user reviewers to ids, so a rule typed with
278/// usernames is stored with ids and survives a rename.
279pub fn check_rule(state: &State, rule: &mut ReviewRule) -> Result<(), Error> {
280    if rule.required_approvals > MAX_APPROVALS {
281        return Err(Error::bad_request(format!("a review needs at most {MAX_APPROVALS} approvals")));
282    }
283    rule.reviewers = parse_reviewers(state, &serde_json::to_value(&rule.reviewers).map_err(Error::internal)?)?;
284    Ok(())
285}
286
287/// Check the settings' review rule and overrides against the store, as
288/// [`Db::update_settings`] stores them.
289pub fn check_settings(state: &State, settings: &mut Settings) -> Result<(), Error> {
290    check_rule(state, &mut settings.review_rule)?;
291    check_rule(state, &mut settings.eco_review_rule)?;
292    let mut seen: Vec<(String, String)> = Vec::new();
293    for o in &mut settings.review_overrides {
294        o.id = o.id.trim().to_string();
295        match o.scope.as_str() {
296            SCOPE_PART_TYPE => {
297                let kind = state
298                    .part_types
299                    .iter()
300                    .find(|t| t.id.eq_ignore_ascii_case(&o.id))
301                    .ok_or_else(|| Error::bad_request(format!("a review override names part type '{}', which does not exist", o.id)))?;
302                o.id = kind.id.clone();
303            }
304            SCOPE_CATEGORY => {
305                let category = catalog::find(&state.categories, &o.id)
306                    .ok_or_else(|| Error::bad_request(format!("a review override names category '{}', which does not exist", o.id)))?;
307                o.id = category.id.clone();
308            }
309            other => {
310                return Err(Error::bad_request(format!(
311                    "a review override's scope is part_type or category, not '{other}'"
312                )))
313            }
314        }
315        let key = (o.scope.clone(), o.id.to_ascii_lowercase());
316        if seen.contains(&key) {
317            return Err(Error::bad_request(format!("two review overrides name {} '{}'", o.scope, o.id)));
318        }
319        seen.push(key);
320        check_rule(state, &mut o.rule)?;
321    }
322    Ok(())
323}
324
325/// Refuse a release that the revision's review does not allow, or say
326/// nothing. `rule` is the rule for the part as it stands.
327pub fn release_gate(revision: &Revision, rule: &ReviewRule, number: &str) -> Result<(), Error> {
328    let current = revision.content_hash.as_str();
329    match revision.reviews.last().filter(|r| r.is_live()) {
330        Some(review) if review.is_met(current) => Ok(()),
331        Some(review) => Err(Error::conflict(format!(
332            "{number} rev {} needs {} approval(s) before it can release, and has {}{}",
333            revision.label,
334            review.required_approvals,
335            review.approvers(current).len(),
336            stale_clause(review, current)
337        ))),
338        None if rule.required_approvals > 0 => Err(Error::conflict(format!(
339            "{number} rev {} needs {} approval(s) before it can release — submit it for review first",
340            revision.label, rule.required_approvals
341        ))),
342        None => Ok(()),
343    }
344}
345
346/// Who may submit a revision for review (operator ruling, 2026-09-25): the user holding
347/// its lock, or any author while nobody does. A revision someone else has checked out is
348/// theirs to submit — they may be about to save — and the refusal names them.
349pub fn submit_lock_gate(state: &State, user: &User, number: &str, revision: &Revision) -> Result<(), Error> {
350    match revision.lock.as_ref().filter(|lock| lock.user_id != user.id) {
351        Some(lock) => {
352            let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
353            Err(Error::conflict(format!(
354                "{number} rev {} is checked out by {holder} — only {holder} can submit it for review (or check it in first)",
355                revision.label
356            )))
357        }
358        None => Ok(()),
359    }
360}
361
362/// `" — N approval(s) were given on an older version and need renewing"`
363/// when a round has approvals that no longer count, else nothing: the tail
364/// of a release refusal, so the person releasing knows why approvals they
365/// can see do not count.
366pub fn stale_clause(review: &Review, current: &str) -> String {
367    match review.stale_approvers(current).len() {
368        0 => String::new(),
369        n => format!(" — {n} approval(s) were given on an older version and need renewing"),
370    }
371}
372
373/// End the live round of a revision that just released.
374pub fn close_on_release(revision: &mut Revision, by: &str, at: u64) {
375    if let Some(review) = revision.live_review_mut() {
376        review.closed_by = Some(by.to_string());
377        review.closed_at = Some(at);
378    }
379}
380
381/// End the live round of a revision pulled back to Draft by its author.
382pub fn withdraw(review: &mut Review, by: &str, at: u64) {
383    if review.is_live() {
384        review.status = ReviewStatus::Withdrawn;
385        review.closed_by = Some(by.to_string());
386        review.closed_at = Some(at);
387    }
388}
389
390/// Record `user`'s verdict on a live round, with every rule a decision is
391/// held to. The caller moves the subject back to Draft on a rejection.
392/// `current` is the subject's content hash now: the decision is recorded as
393/// given on it, and counts only while it stays the same (D8).
394pub fn record_decision(
395    review: &mut Review,
396    user: &User,
397    verdict: Verdict,
398    comment: &str,
399    at: u64,
400    current: &str,
401) -> Result<(), Error> {
402    if !review.is_live() {
403        return Err(Error::conflict("this review is over — submit again for a new one"));
404    }
405    if !is_reviewer(review, user) {
406        return Err(Error::forbidden(if review.reviewers.is_empty() {
407            "this review is decided by the check-in group".to_string()
408        } else {
409            "you are not one of this review's reviewers".to_string()
410        }));
411    }
412    if user.id == review.opened_by && !review.allow_self_approval && verdict == Verdict::Approve {
413        return Err(Error::forbidden(
414            "you submitted this for review, and your own approval does not count here",
415        ));
416    }
417    let comment = comment.trim();
418    if verdict == Verdict::Reject && comment.is_empty() {
419        return Err(Error::bad_request("a rejection needs a comment saying what to change"));
420    }
421    if comment.chars().count() > MAX_COMMENT {
422        return Err(Error::bad_request(format!("a comment is at most {MAX_COMMENT} characters")));
423    }
424    // Approving again is refused only when the standing approval is on THIS
425    // version: renewing a stale approval is exactly what is wanted.
426    let latest = review.decisions.iter().rev().find(|d| d.user_id == user.id);
427    if verdict == Verdict::Approve && latest.is_some_and(|d| d.verdict == Verdict::Approve && d.is_current(current)) {
428        return Err(Error::conflict("you have already approved this version"));
429    }
430    review.decisions.push(Decision {
431        user_id: user.id.clone(),
432        verdict,
433        comment: comment.to_string(),
434        at,
435        content_hash: Some(current.to_string()),
436    });
437    refresh(review, current);
438    if verdict == Verdict::Reject {
439        review.closed_by = Some(user.id.clone());
440        review.closed_at = Some(at);
441    }
442    Ok(())
443}
444
445/// Add a comment to `comments`, answering `parent` when it is given.
446pub fn push_comment(comments: &mut Vec<Comment>, user: &User, body: &str, parent: &str, at: u64) -> Result<Comment, Error> {
447    if !may_comment(user) {
448        return Err(Error::forbidden("commenting needs more than the viewer group"));
449    }
450    let body = body.trim();
451    if body.is_empty() {
452        return Err(Error::bad_request("a comment needs some text"));
453    }
454    if body.chars().count() > MAX_COMMENT {
455        return Err(Error::bad_request(format!("a comment is at most {MAX_COMMENT} characters")));
456    }
457    let parent = parent.trim();
458    if !parent.is_empty() && !comments.iter().any(|c| c.id == parent) {
459        return Err(Error::not_found("the comment being answered"));
460    }
461    let comment = Comment {
462        id: crate::auth::new_id(),
463        author: user.id.clone(),
464        at,
465        body: body.to_string(),
466        parent: parent.to_string(),
467    };
468    comments.push(comment.clone());
469    Ok(comment)
470}
471
472/// What a submitter, an administrator or the check-in group may change on
473/// a live round.
474#[derive(Debug, Clone, Default)]
475pub struct RoundChange {
476    pub reviewers: Option<Value>,
477    pub required_approvals: Option<u32>,
478    /// Unix seconds; 0 clears it.
479    pub due: Option<u64>,
480}
481
482/// Apply `change` to a live round, as `user`; `current` is the subject's
483/// content hash, which the round's status is re-judged on.
484pub fn change_round(state: &State, review: &mut Review, user: &User, change: &RoundChange, current: &str) -> Result<(), Error> {
485    if !review.is_live() {
486        return Err(Error::conflict("this review is over"));
487    }
488    let manager = user.can_checkin();
489    if !manager && user.id != review.opened_by {
490        return Err(Error::forbidden("a review is changed by its submitter or the check-in group"));
491    }
492    if let Some(required) = change.required_approvals {
493        if !manager {
494            return Err(Error::forbidden("changing how many approvals a review needs takes the check-in group"));
495        }
496        if required > MAX_APPROVALS {
497            return Err(Error::bad_request(format!("a review needs at most {MAX_APPROVALS} approvals")));
498        }
499        review.required_approvals = required;
500    }
501    if let Some(reviewers) = &change.reviewers {
502        review.reviewers = parse_reviewers(state, reviewers)?;
503    }
504    if let Some(due) = change.due {
505        review.due = (due > 0).then_some(due);
506    }
507    refresh(review, current);
508    Ok(())
509}
510
511// ===========================================================================
512// What the page shows
513// ===========================================================================
514
515/// A reviewer with their name, and what they have said.
516#[derive(Debug, Serialize)]
517pub struct ReviewerView {
518    pub kind: ReviewerKind,
519    pub id: String,
520    pub name: String,
521    /// For a user: `approve`, `reject` or empty. For a group: the members
522    /// who approved.
523    pub verdict: String,
524    pub approved_by: Vec<String>,
525}
526
527/// A decision with the reviewer's name.
528#[derive(Debug, Serialize)]
529pub struct DecisionView {
530    pub user_id: String,
531    pub name: String,
532    pub verdict: Verdict,
533    pub comment: String,
534    pub at: u64,
535    /// The subject's content hash it was given on; `null` for a decision
536    /// recorded before decisions carried one.
537    pub content_hash: Option<String>,
538    /// Given on the subject as it is now. `false`: "on an older version" —
539    /// an approval that no longer counts until it is renewed.
540    pub current: bool,
541}
542
543/// A review round as the page shows it.
544#[derive(Debug, Serialize)]
545pub struct ReviewView {
546    pub id: String,
547    pub status: &'static str,
548    pub opened_by: String,
549    pub opened_at: u64,
550    pub required_approvals: u32,
551    /// Approvals that count: given on the subject as it is now.
552    pub approvals: usize,
553    /// Standing approvals given on an older version (or before decisions
554    /// carried a hash): they count again only when renewed.
555    pub stale_approvals: usize,
556    pub met: bool,
557    pub allow_self_approval: bool,
558    pub due: Option<u64>,
559    pub overdue: bool,
560    pub rule_source: String,
561    pub reviewers: Vec<ReviewerView>,
562    pub decisions: Vec<DecisionView>,
563    pub closed_by: Option<String>,
564    pub closed_at: Option<u64>,
565    /// Whether the person looking may approve or reject it now.
566    pub can_decide: bool,
567    /// Whether they may change its reviewers, due date (and, for the
568    /// check-in group, required approvals).
569    pub can_change: bool,
570    pub live: bool,
571}
572
573/// A comment with its author's name.
574#[derive(Debug, Serialize)]
575pub struct CommentView {
576    pub id: String,
577    pub author: String,
578    pub author_id: String,
579    pub at: u64,
580    pub body: String,
581    pub parent: String,
582}
583
584fn name_of(state: &State, id: &str) -> String {
585    state
586        .user(id)
587        .map(|u| if u.display_name.is_empty() { u.username.clone() } else { u.display_name.clone() })
588        .unwrap_or_else(|| id.to_string())
589}
590
591/// A round as the page shows it; `current` is the subject's content hash now,
592/// which decides which approvals count and which are on an older version.
593pub fn view(state: &State, review: &Review, viewer: &User, current: &str) -> ReviewView {
594    let approvers = review.approvers(current);
595    let latest = |user_id: &str| -> String {
596        review
597            .decisions
598            .iter()
599            .rev()
600            .find(|d| d.user_id == user_id)
601            .map(|d| d.verdict.as_str().to_string())
602            .unwrap_or_default()
603    };
604    let reviewers = review
605        .reviewers
606        .iter()
607        .map(|r| match r.kind {
608            ReviewerKind::User => ReviewerView {
609                kind: r.kind,
610                id: r.id.clone(),
611                name: name_of(state, &r.id),
612                verdict: latest(&r.id),
613                approved_by: Vec::new(),
614            },
615            ReviewerKind::Group => ReviewerView {
616                kind: r.kind,
617                id: r.id.clone(),
618                name: r.id.clone(),
619                verdict: String::new(),
620                approved_by: approvers
621                    .iter()
622                    .filter(|id| state.user(id).is_some_and(|u| u.in_group(&r.id)))
623                    .map(|id| name_of(state, id))
624                    .collect(),
625            },
626        })
627        .collect();
628    let live = review.is_live();
629    // An approval on an older version does not stop them deciding again.
630    let already_approved = review
631        .decisions
632        .iter()
633        .rev()
634        .find(|d| d.user_id == viewer.id)
635        .is_some_and(|d| d.verdict == Verdict::Approve && d.is_current(current));
636    ReviewView {
637        id: review.id.clone(),
638        status: review.status.as_str(),
639        opened_by: name_of(state, &review.opened_by),
640        opened_at: review.opened_at,
641        required_approvals: review.required_approvals,
642        approvals: approvers.len(),
643        stale_approvals: review.stale_approvers(current).len(),
644        met: review.is_met(current),
645        allow_self_approval: review.allow_self_approval,
646        due: review.due,
647        overdue: live && review.due.is_some_and(|due| due < now()),
648        rule_source: review.rule_source.clone(),
649        reviewers,
650        decisions: review
651            .decisions
652            .iter()
653            .map(|d| DecisionView {
654                user_id: d.user_id.clone(),
655                name: name_of(state, &d.user_id),
656                verdict: d.verdict,
657                comment: d.comment.clone(),
658                at: d.at,
659                content_hash: d.content_hash.clone(),
660                current: d.is_current(current),
661            })
662            .collect(),
663        closed_by: review.closed_by.as_deref().map(|id| name_of(state, id)),
664        closed_at: review.closed_at,
665        can_decide: live && is_reviewer(review, viewer) && !already_approved,
666        can_change: live && (viewer.can_checkin() || viewer.id == review.opened_by),
667        live,
668    }
669}
670
671pub fn comment_views(state: &State, comments: &[Comment]) -> Vec<CommentView> {
672    comments
673        .iter()
674        .map(|c| CommentView {
675            id: c.id.clone(),
676            author: name_of(state, &c.author),
677            author_id: c.author.clone(),
678            at: c.at,
679            body: c.body.clone(),
680            parent: c.parent.clone(),
681        })
682        .collect()
683}
684
685/// One revision's review panel: the current round, the ones before it, the
686/// discussion, and the rule a new round would open with.
687#[derive(Debug, Serialize)]
688pub struct RevisionReview {
689    pub part_id: String,
690    pub number: String,
691    pub revision_id: String,
692    pub label: String,
693    pub lifecycle: &'static str,
694    pub current: Option<ReviewView>,
695    pub history: Vec<ReviewView>,
696    pub comments: Vec<CommentView>,
697    /// The rule a submission would open a round with now.
698    pub rule: ReviewRule,
699    pub rule_source: String,
700    pub can_comment: bool,
701}
702
703/// One entry in a person's review inbox.
704#[derive(Debug, Clone, Serialize)]
705pub struct InboxItem {
706    /// `revision` or `eco`.
707    pub kind: &'static str,
708    /// The page link's target: a part id or a change order id.
709    pub target: String,
710    /// A revision's id; empty for a change order.
711    pub revision_id: String,
712    /// `CPART000000001 rev B`, or a change order's number.
713    pub title: String,
714    pub name: String,
715    pub status: &'static str,
716    pub opened_by: String,
717    pub opened_at: u64,
718    pub due: Option<u64>,
719    pub overdue: bool,
720    pub approvals: usize,
721    pub required_approvals: u32,
722}
723
724/// What is waiting on a person, and what they have waiting on others.
725#[derive(Debug, Default, Serialize)]
726pub struct Inbox {
727    /// Live rounds they may decide and have not approved yet.
728    pub waiting_on_me: Vec<InboxItem>,
729    /// Live rounds they submitted.
730    pub submitted: Vec<InboxItem>,
731    /// `waiting_on_me.len()`, for the badge.
732    pub count: usize,
733}
734
735/// A live round's inbox entry.
736pub fn inbox_item(
737    state: &State,
738    review: &Review,
739    kind: &'static str,
740    target: &str,
741    revision_id: &str,
742    title: String,
743    name: &str,
744    current: &str,
745) -> InboxItem {
746    InboxItem {
747        kind,
748        target: target.to_string(),
749        revision_id: revision_id.to_string(),
750        title,
751        name: name.to_string(),
752        status: review.status.as_str(),
753        opened_by: name_of(state, &review.opened_by),
754        opened_at: review.opened_at,
755        due: review.due,
756        overdue: review.due.is_some_and(|due| due < now()),
757        approvals: review.approvers(current).len(),
758        required_approvals: review.required_approvals,
759    }
760}
761
762/// Where `review` goes in `user`'s inbox. A reviewer whose approval went
763/// stale is waiting again.
764pub fn file_item(inbox: &mut Inbox, review: &Review, user: &User, current: &str, item: impl FnOnce() -> InboxItem) {
765    if !review.is_live() {
766        return;
767    }
768    let mine = review.opened_by == user.id;
769    let approved = review
770        .decisions
771        .iter()
772        .rev()
773        .find(|d| d.user_id == user.id)
774        .is_some_and(|d| d.verdict == Verdict::Approve && d.is_current(current));
775    let may_decide = is_reviewer(review, user) && !approved && !(mine && !review.allow_self_approval);
776    if !(mine || may_decide) {
777        return;
778    }
779    let item = item();
780    if may_decide {
781        inbox.waiting_on_me.push(item.clone());
782    }
783    if mine {
784        inbox.submitted.push(item);
785    }
786}
787
788// ===========================================================================
789// The store's review operations on revisions
790// ===========================================================================
791
792/// What a submission may ask for beyond the rule: more reviewers, a due date.
793#[derive(Debug, Clone, Default)]
794pub struct Submission {
795    /// Reviewers ADDED to the rule's.
796    pub reviewers: Option<Value>,
797    /// Unix seconds.
798    pub due: Option<u64>,
799    /// A comment posted with the submission.
800    pub note: String,
801}
802
803impl Db {
804    /// Submit a draft for review: open a round and move it to `InReview`.
805    ///
806    /// The rule is found, and the `reviewers` hook asked, on a snapshot and
807    /// OUTSIDE the store lock; the locked write then re-checks that the move is
808    /// still allowed. After it commits the `review-event` hook is told.
809    pub fn submit_for_review(
810        &self,
811        user: &User,
812        part_id: &str,
813        revision_id: &str,
814        submission: &Submission,
815    ) -> Result<Vec<String>, Error> {
816        lifecycle::check_enabled(&self.settings(), Lifecycle::InReview)?;
817        let (part, revision) = self.snapshot(part_id, revision_id)?;
818        lifecycle::check_transition(revision.lifecycle, Lifecycle::InReview).map_err(Error::conflict)?;
819        self.read(|state| submit_lock_gate(state, user, &part.number, &revision))?;
820        let (mut rule, mut source) = self.read(|state| rule_for(&state.settings, &state.categories, &part));
821        if let Some(extra) = &submission.reviewers {
822            let added = self.read(|state| parse_reviewers(state, extra))?;
823            for reviewer in added {
824                if !rule.reviewers.contains(&reviewer) {
825                    rule.reviewers.push(reviewer);
826                }
827            }
828        }
829        let mut round = open_round(&rule, &source, &user.id, now());
830        if let Some(due) = submission.due.filter(|d| *d > 0) {
831            round.due = Some(due);
832        }
833        let input = json!({
834            "part": part,
835            "revision": revision,
836            "rule": {
837                "required_approvals": round.required_approvals,
838                "reviewers": round.reviewers,
839                "due": round.due,
840                "allow_self_approval": round.allow_self_approval,
841                "source": source,
842            },
843            "user": scripting::user_json(user),
844        });
845        match scripting::run(self, user, scripting::REVIEWERS, "reviewers", &input)? {
846            HookResult::Absent => {}
847            HookResult::Refused(failure) => {
848                return Err(Error::conflict(format!("{}: {}", scripting::REVIEWERS, failure.message)))
849            }
850            HookResult::Returned(success) => {
851                if let Value::Object(answer) = &success.value {
852                    if let Some(reviewers) = answer.get("reviewers") {
853                        round.reviewers = self
854                            .read(|state| parse_reviewers(state, reviewers))
855                            .map_err(|e| Error::conflict(format!("{}: {}", scripting::REVIEWERS, e.message)))?;
856                    }
857                    if let Some(required) = answer.get("required_approvals") {
858                        round.required_approvals = required
859                            .as_u64()
860                            .filter(|n| *n <= u64::from(MAX_APPROVALS))
861                            .ok_or_else(|| {
862                                Error::conflict(format!(
863                                    "{}: required_approvals must be a whole number up to {MAX_APPROVALS}",
864                                    scripting::REVIEWERS
865                                ))
866                            })? as u32;
867                    }
868                    if let Some(due) = answer.get("due") {
869                        round.due = due.as_u64().filter(|d| *d > 0);
870                    }
871                    if let Some(own) = answer.get("allow_self_approval").and_then(Value::as_bool) {
872                        round.allow_self_approval = own;
873                    }
874                    source.push_str("+script");
875                    round.rule_source = source.clone();
876                    refresh(&mut round, "");
877                } else if !success.value.is_null() {
878                    return Err(Error::conflict(format!(
879                        "{}: reviewers() must return {{ reviewers, required_approvals, due }} or null — it returned {}",
880                        scripting::REVIEWERS,
881                        success.value
882                    )));
883                }
884            }
885        }
886
887        let note = submission.note.clone();
888        let author = user.clone();
889        self.mutate(move |state| {
890            lifecycle::check_enabled(&state.settings, Lifecycle::InReview)?;
891            // Again inside the lock: someone may have checked it out since.
892            let (number, snapshot) = {
893                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
894                (part.number.clone(), part.revision(revision_id).cloned().ok_or_else(|| Error::not_found("revision"))?)
895            };
896            submit_lock_gate(state, &author, &number, &snapshot)?;
897            let (_, revision) = db::find_revision_mut(state, part_id, revision_id)?;
898            lifecycle::check_transition(revision.lifecycle, Lifecycle::InReview).map_err(Error::conflict)?;
899            revision.lifecycle = Lifecycle::InReview;
900            revision.reviews.push(round);
901            if !note.trim().is_empty() {
902                push_comment(&mut revision.comments, &author, &note, "", now())?;
903            }
904            state.touch_part(part_id);
905            Ok(())
906        })?;
907        Ok(self.review_event(user, "opened", part_id, revision_id, None))
908    }
909
910    /// Approve or reject a revision's live round. A rejection ends the round
911    /// and sends the revision back to Draft.
912    pub fn decide_revision(
913        &self,
914        user: &User,
915        part_id: &str,
916        revision_id: &str,
917        verdict: Verdict,
918        comment: &str,
919    ) -> Result<Vec<String>, Error> {
920        let decider = user.clone();
921        let comment = comment.to_string();
922        self.mutate(move |state| {
923            let (number, revision) = db::find_revision_mut(state, part_id, revision_id)?;
924            if revision.lifecycle != Lifecycle::InReview {
925                return Err(Error::conflict(format!(
926                    "{number} rev {} is {}, not in review",
927                    revision.label,
928                    revision.lifecycle.as_str()
929                )));
930            }
931            let current = revision.content_hash.clone();
932            let Some(review) = revision.live_review_mut() else {
933                return Err(Error::conflict(format!("{number} rev {} has no review open", revision.label)));
934            };
935            record_decision(review, &decider, verdict, &comment, now(), &current)?;
936            if verdict == Verdict::Reject {
937                lifecycle::check_transition(revision.lifecycle, Lifecycle::Draft).map_err(Error::conflict)?;
938                revision.lifecycle = Lifecycle::Draft;
939            }
940            state.touch_part(part_id);
941            Ok(())
942        })?;
943        Ok(self.review_event(user, verdict.as_str(), part_id, revision_id, None))
944    }
945
946    /// Change a revision's live round: its reviewers, due date, and (for the
947    /// check-in group) how many approvals it needs.
948    pub fn change_revision_review(
949        &self,
950        user: &User,
951        part_id: &str,
952        revision_id: &str,
953        change: &RoundChange,
954    ) -> Result<Vec<String>, Error> {
955        let editor = user.clone();
956        let change = change.clone();
957        self.mutate(move |state| {
958            let snapshot = state.part(part_id).and_then(|p| p.revision(revision_id)).and_then(|r| r.review()).cloned();
959            let Some(mut review) = snapshot else {
960                return Err(Error::conflict("this revision has no review"));
961            };
962            let current = state
963                .part(part_id)
964                .and_then(|p| p.revision(revision_id))
965                .map(|r| r.content_hash.clone())
966                .unwrap_or_default();
967            change_round(state, &mut review, &editor, &change, &current)?;
968            let (_, revision) = db::find_revision_mut(state, part_id, revision_id)?;
969            if let Some(last) = revision.reviews.last_mut() {
970                *last = review;
971            }
972            Ok(())
973        })?;
974        Ok(self.review_event(user, "updated", part_id, revision_id, None))
975    }
976
977    /// Add a comment to a revision's discussion.
978    pub fn comment_on_revision(
979        &self,
980        user: &User,
981        part_id: &str,
982        revision_id: &str,
983        body: &str,
984        parent: &str,
985    ) -> Result<(Comment, Vec<String>), Error> {
986        let author = user.clone();
987        let body = body.to_string();
988        let parent = parent.to_string();
989        let comment = self.mutate(move |state| {
990            let (_, revision) = db::find_revision_mut(state, part_id, revision_id)?;
991            push_comment(&mut revision.comments, &author, &body, &parent, now())
992        })?;
993        let warnings = self.review_event(user, "comment", part_id, revision_id, Some(&comment));
994        Ok((comment, warnings))
995    }
996
997    /// One revision's review panel, as `viewer` sees it.
998    pub fn revision_review(&self, viewer: &User, part_id: &str, revision_id: &str) -> Result<RevisionReview, Error> {
999        self.read(|state| {
1000            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
1001            let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
1002            let (rule, rule_source) = rule_for(&state.settings, &state.categories, part);
1003            let mut rounds: Vec<ReviewView> =
1004                revision.reviews.iter().map(|r| view(state, r, viewer, &revision.content_hash)).collect();
1005            let current = rounds.pop();
1006            rounds.reverse();
1007            Ok(RevisionReview {
1008                part_id: part.id.clone(),
1009                number: part.number.clone(),
1010                revision_id: revision.id.clone(),
1011                label: revision.label.clone(),
1012                lifecycle: revision.lifecycle.as_str(),
1013                current,
1014                history: rounds,
1015                comments: comment_views(state, &revision.comments),
1016                rule,
1017                rule_source,
1018                can_comment: may_comment(viewer),
1019            })
1020        })
1021    }
1022
1023    /// What is waiting on `user`, and what they submitted.
1024    pub fn inbox(&self, user: &User) -> Inbox {
1025        self.read(|state| {
1026            let mut inbox = Inbox::default();
1027            for part in &state.parts {
1028                for revision in &part.revisions {
1029                    let Some(review) = revision.review() else { continue };
1030                    file_item(&mut inbox, review, user, &revision.content_hash, || {
1031                        inbox_item(
1032                            state,
1033                            review,
1034                            "revision",
1035                            &part.id,
1036                            &revision.id,
1037                            format!("{} rev {}", part.number, revision.label),
1038                            &part.name,
1039                            &revision.content_hash,
1040                        )
1041                    });
1042                }
1043            }
1044            for eco in &state.change_orders {
1045                let Some(review) = eco.reviews.last() else { continue };
1046                let current = eco_subject_hash(state, eco);
1047                file_item(&mut inbox, review, user, &current, || {
1048                    inbox_item(state, review, "eco", &eco.id, "", eco.number.clone(), &eco.title, &current)
1049                });
1050            }
1051            inbox.waiting_on_me.sort_by_key(|i| (i.due.unwrap_or(u64::MAX), i.opened_at));
1052            inbox.submitted.sort_by_key(|i| std::cmp::Reverse(i.opened_at));
1053            inbox.count = inbox.waiting_on_me.len();
1054            inbox
1055        })
1056    }
1057
1058    /// Tell the `review-event` hook that a revision was pulled out of review,
1059    /// when that ended a round.
1060    pub(crate) fn review_withdrawn(&self, user: &User, part_id: &str, revision_id: &str) -> Vec<String> {
1061        let withdrawn = self.read(|state| {
1062            state
1063                .part(part_id)
1064                .and_then(|p| p.revision(revision_id))
1065                .and_then(|r| r.review())
1066                .is_some_and(|r| r.status == ReviewStatus::Withdrawn)
1067        });
1068        if withdrawn {
1069            self.review_event(user, "withdrawn", part_id, revision_id, None)
1070        } else {
1071            Vec::new()
1072        }
1073    }
1074
1075    /// Tell the `review-event` hook about something that just committed on a
1076    /// revision's review. It cannot undo it: a failure is a warning.
1077    fn review_event(
1078        &self,
1079        user: &User,
1080        event: &str,
1081        part_id: &str,
1082        revision_id: &str,
1083        comment: Option<&Comment>,
1084    ) -> Vec<String> {
1085        let input = self.read(|state| {
1086            let part = state.part(part_id)?;
1087            let revision = part.revision(revision_id)?;
1088            Some(json!({
1089                "event": event,
1090                "subject": {
1091                    "kind": "revision",
1092                    "part_id": part.id,
1093                    "number": part.number,
1094                    "name": part.name,
1095                    "revision_id": revision.id,
1096                    "label": revision.label,
1097                    "lifecycle": revision.lifecycle.as_str(),
1098                },
1099                "review": revision.review(),
1100                "comment": comment,
1101                "user": scripting::user_json(user),
1102            }))
1103        });
1104        let Some(input) = input else { return Vec::new() };
1105        hook_warning(self, user, &input)
1106    }
1107}
1108
1109/// Run the `review-event` hook with `input`, returning its failure as a
1110/// warning.
1111pub fn hook_warning(db: &Db, user: &User, input: &Value) -> Vec<String> {
1112    match scripting::run(db, user, scripting::REVIEW_EVENT, "reviewEvent", input) {
1113        Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => Vec::new(),
1114        Ok(HookResult::Refused(failure)) => {
1115            vec![format!("done, but {} failed: {}", scripting::REVIEW_EVENT, failure.message)]
1116        }
1117        Err(error) => vec![format!("done, but {} could not run: {}", scripting::REVIEW_EVENT, error.message)],
1118    }
1119}