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