Skip to main content

brep_app/panels/
plm.rs

1//! Lifecycle in the CAD UI: the revision picker and the checkout verbs for a
2//! document opened from the PLM.
3//!
4//! # What it decides
5//!
6//! - **Session editing is always allowed.** [`access_for`] turns a revision's
7//!   server view into save permissions: saving to that revision requires a
8//!   draft or in-review revision checked out by this user. Released revisions,
9//!   another user's checkout, and pending permissions only restrict saving.
10//!   The session copy stays editable and can be saved to another destination.
11//! - **The verbs** a revision offers ([`verbs`]): Check out on an editable
12//!   revision nobody holds; Check in on one this user holds; Break lock only to
13//!   the check-in group, on one someone else holds; Release on an editable one to
14//!   the check-in group; New revision to authors. The server decides every one
15//!   of them again, and its refusal is shown as it sent it.
16//! - **Which revision opens** (D13): the NEWEST, drafts included — the one
17//!   created last ([`newest`]); the picker lets the user choose another.
18//!
19//! # How it talks to the server
20//!
21//! Through [`PlmLifecycle`], one method per route, so the panel is tested
22//! against a fake and the real client (`crate::plm::client`) implements the
23//! same trait. Every call returns a [`PlmFuture`]; the panel keeps at most one
24//! in flight and polls it each frame ([`PlmPanel::poll`]), because a panel
25//! draws synchronously. Each answer re-reads the part, so what the picker shows
26//! is always the server's word.
27//!
28//! # With no server
29//!
30//! None of this exists: the shell builds a [`PlmPanel`] only for a document
31//! that came from a PLM, and a file-based document has none.
32
33use std::task::{Context, Poll, Waker};
34
35use eframe::egui;
36use serde::Deserialize;
37
38use crate::document::Access;
39use crate::plm::PlmFuture;
40
41/// The `client_id` the app takes a lock under, so a lock says which client of
42/// a user holds it (the server defaults to `"web"`).
43pub const CLIENT_ID: &str = "brep-app";
44
45// ===========================================================================
46// What the server answers (`GET /api/parts/:id`), read tolerantly
47// ===========================================================================
48
49/// One part and its revisions, as `GET /api/parts/:id` answers. Fields this
50/// app does not read are ignored; a missing one takes its default.
51#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
52#[serde(default)]
53pub struct PartDetail {
54    pub id: String,
55    pub number: String,
56    pub name: String,
57    /// `normal`, `family` or `template`.
58    pub document_class: String,
59    /// Creation order, oldest first.
60    pub revision_views: Vec<RevisionView>,
61    /// The label a new revision gets when nobody types one.
62    pub suggested_label: String,
63    /// Whether another revision may start while one is in work.
64    pub multiple_open_drafts: bool,
65}
66
67/// One revision with its lock, review, bake and provenance.
68#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
69#[serde(default)]
70pub struct RevisionView {
71    pub id: String,
72    pub label: String,
73    /// `draft`, `inreview`, `released`, `superseded` or `obsolete`.
74    pub lifecycle: String,
75    /// A draft or in review: its document may change, under a lock.
76    pub editable: bool,
77    pub created_at: u64,
78    pub modified_at: u64,
79    /// Who holds the lock, as a name a person reads.
80    pub locked_by: Option<String>,
81    pub locked_by_me: bool,
82    pub locked_at: Option<u64>,
83    pub released_by: Option<String>,
84    pub released_at: Option<u64>,
85    /// `part/<part>/rev/<revision>` — the store key its document lives at.
86    pub document_key: String,
87    /// `authored`, `imported` or `generated`.
88    pub origin: String,
89    pub family: Option<Provenance>,
90    pub template: Option<Provenance>,
91    /// `pending`, `claimed`, `failed` or `done`; absent when never queued.
92    pub bake: Option<String>,
93    pub bake_error: String,
94    /// A generated member whose document changed since Generate wrote it.
95    pub hand_edited: bool,
96    /// Lines in its uses list: more than none makes it an assembly.
97    pub uses: usize,
98    pub review: Option<ReviewSummary>,
99    pub comments: usize,
100}
101
102/// Where a generated or spun-out revision came from.
103#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
104#[serde(default)]
105pub struct Provenance {
106    pub part_id: String,
107    pub number: String,
108    pub revision_label: String,
109}
110
111/// The current review round, in brief.
112#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
113#[serde(default)]
114pub struct ReviewSummary {
115    pub status: String,
116    pub live: bool,
117    pub approvals: usize,
118    pub required_approvals: u32,
119    pub may_decide: bool,
120}
121
122/// A new revision, as `POST /api/parts/:id/revisions` answers.
123#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
124#[serde(default)]
125pub struct NewRevision {
126    pub id: String,
127    pub label: String,
128}
129
130/// One line of `GET /api/parts/:id/history`, the part's audit trail. A change
131/// the app made with a token is logged as the token's owner, `via: token`.
132#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
133#[serde(default)]
134pub struct HistoryEvent {
135    pub id: u64,
136    pub at: u64,
137    pub actor: HistoryActor,
138    pub action: String,
139    pub entity: HistoryEntity,
140    pub detail: String,
141}
142
143#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
144#[serde(default)]
145pub struct HistoryActor {
146    pub username: String,
147    /// `session`, `token` or `system`.
148    pub via: String,
149}
150
151#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
152#[serde(default)]
153pub struct HistoryEntity {
154    pub kind: String,
155    pub id: String,
156    pub label: String,
157}
158
159/// What the signed-in user may do, from `/api/me`.
160#[derive(Debug, Clone, Copy, Default, PartialEq)]
161pub struct Rights {
162    pub can_author: bool,
163    pub can_checkin: bool,
164}
165
166// ===========================================================================
167// The server, as the panel needs it
168// ===========================================================================
169
170/// The lifecycle routes, one method each. Errors are the server's sentence.
171pub trait PlmLifecycle {
172    /// What the signed-in user may do: `/api/me`'s `can_author` and
173    /// `can_checkin`, resolved by the server from the groups.
174    fn rights(&self) -> PlmFuture<Rights>;
175    /// `GET /api/parts/:id`.
176    fn part(&self, part: &str) -> PlmFuture<PartDetail>;
177    /// `POST /api/parts/:id/revisions/:rev/checkout` with [`CLIENT_ID`].
178    fn checkout(&self, part: &str, revision: &str) -> PlmFuture<()>;
179    /// `POST …/checkin`; `force` breaks someone else's lock (check-in group).
180    fn checkin(&self, part: &str, revision: &str, force: bool) -> PlmFuture<()>;
181    /// `POST …/state` with `{"to": to}`; answers the release's warnings.
182    fn set_state(&self, part: &str, revision: &str, to: &str) -> PlmFuture<Vec<String>>;
183    /// `POST /api/parts/:id/revisions` with `{"label"}`; empty takes the
184    /// server's suggestion.
185    fn create_revision(&self, part: &str, label: &str) -> PlmFuture<NewRevision>;
186    /// `GET /api/parts/:id/history`, newest first.
187    fn history(&self, part: &str) -> PlmFuture<Vec<HistoryEvent>>;
188}
189
190// ===========================================================================
191// The rules, as pure functions
192// ===========================================================================
193
194/// The revision that opens when a part is opened by number (D13): the one
195/// created last, drafts included. Ties keep the later one in the list, which
196/// is creation order.
197pub fn newest(part: &PartDetail) -> Option<&RevisionView> {
198    part.revision_views
199        .iter()
200        .enumerate()
201        .max_by_key(|(i, r)| (r.created_at, *i))
202        .map(|(_, r)| r)
203}
204
205/// Whether the session copy may be saved to `revision`, and if not, why.
206pub fn access_for(revision: &RevisionView) -> Access {
207    access_with(revision, Rights { can_author: true, can_checkin: true })
208}
209
210/// [`access_for`] for a user with `rights`: an account that may not write
211/// is told so, not to check out what it cannot.
212pub fn access_with(revision: &RevisionView, rights: Rights) -> Access {
213    let label = &revision.label;
214    if !rights.can_author && !revision.locked_by_me {
215        return Access::read_only(format!("revision {label}: {}", crate::document::owned_save::VIEW_ONLY));
216    }
217    if !revision.editable {
218        let state = match revision.lifecycle.as_str() {
219            "released" => "released",
220            "superseded" => "superseded",
221            "obsolete" => "obsolete",
222            other => other,
223        };
224        return Access::read_only(format!("revision {label} is {state} and cannot be saved to"));
225    }
226    match (&revision.locked_by, revision.locked_by_me) {
227        (Some(_), true) => Access::Editable,
228        (Some(who), false) => Access::read_only(format!("revision {label} is checked out by {who}")),
229        (None, _) => Access::read_only(format!("revision {label} is not checked out — saving requires checkout")),
230    }
231}
232
233/// A lifecycle action the panel offers.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum Verb {
236    CheckOut,
237    CheckIn,
238    BreakLock,
239    Release,
240    NewRevision,
241    /// Open the review pane's submit form (S4 owns the form and the route).
242    Submit,
243    /// Open the review pane on the revision's current round.
244    Review,
245}
246
247impl Verb {
248    /// The verb's hit key in the PLM pane: `plm/lifecycle:verb:<key>`.
249    pub fn key(self) -> &'static str {
250        match self {
251            Verb::CheckOut => "check-out",
252            Verb::CheckIn => "check-in",
253            Verb::BreakLock => "break-lock",
254            Verb::Release => "release",
255            Verb::NewRevision => "new-revision",
256            Verb::Submit => "submit",
257            Verb::Review => "review",
258
259        }
260    }
261
262    pub fn label(self) -> &'static str {
263        match self {
264            Verb::CheckOut => "Check out",
265            Verb::CheckIn => "Check in",
266            Verb::BreakLock => "Break lock",
267            Verb::Release => "Release",
268            Verb::NewRevision => "New revision",
269            Verb::Submit => "Submit for review",
270            Verb::Review => "Review…",
271
272        }
273    }
274}
275
276/// The verbs `revision` of `part` offers to a user with `rights`, in the order
277/// the panel draws them.
278pub fn verbs(part: &PartDetail, revision: &RevisionView, rights: Rights) -> Vec<Verb> {
279    let mut out = Vec::new();
280    if revision.editable {
281        match (&revision.locked_by, revision.locked_by_me) {
282            (None, _) if rights.can_author => out.push(Verb::CheckOut),
283            (Some(_), true) => out.push(Verb::CheckIn),
284            (Some(_), false) if rights.can_checkin => out.push(Verb::BreakLock),
285            _ => {}
286        }
287        // Held by someone else, a release would land on their work in progress.
288        let held_by_other = revision.locked_by.is_some() && !revision.locked_by_me;
289        if rights.can_checkin && !held_by_other {
290            out.push(Verb::Release);
291        }
292    }
293    let open_draft = part.revision_views.iter().any(|r| r.editable);
294    if rights.can_author && (part.multiple_open_drafts || !open_draft) {
295        out.push(Verb::NewRevision);
296    }
297    let live_review = revision.review.as_ref().is_some_and(|r| r.live);
298    // Only the lock holder submits, or any author while nobody holds it (ruling 2026-09-25).
299    let held_by_other = revision.locked_by.is_some() && !revision.locked_by_me;
300    if revision.editable && revision.lifecycle == "draft" && rights.can_author && !live_review && !held_by_other {
301        out.push(Verb::Submit);
302    }
303    if revision.review.is_some() {
304        out.push(Verb::Review);
305    }
306    out
307}
308
309/// One line of the picker: the label and everything the server says about the
310/// revision that a person deciding which one to open needs.
311pub fn describe(revision: &RevisionView) -> String {
312    let mut parts = vec![format!("{} — {}", revision.label, revision.lifecycle)];
313    match (&revision.locked_by, revision.locked_by_me) {
314        (Some(_), true) => parts.push("checked out by you".into()),
315        (Some(who), false) => parts.push(format!("checked out by {who}")),
316        (None, _) => {}
317    }
318    if let Some(review) = &revision.review {
319        if review.live {
320            parts.push(format!("in review {}/{}", review.approvals, review.required_approvals));
321        } else {
322            parts.push(format!("review {}", review.status));
323        }
324    }
325    if let Some(bake) = &revision.bake {
326        if revision.bake_error.is_empty() {
327            parts.push(format!("bake {bake}"));
328        } else {
329            parts.push(format!("bake {bake}: {}", revision.bake_error));
330        }
331    }
332    if revision.hand_edited {
333        parts.push("hand-edited".into());
334    }
335    if revision.uses > 0 {
336        parts.push(format!("{} uses", revision.uses));
337    }
338    if revision.origin != "authored" && !revision.origin.is_empty() {
339        parts.push(revision.origin.clone());
340    }
341    if let Some(family) = &revision.family {
342        parts.push(format!("from family {} {}", family.number, family.revision_label));
343    }
344    if let Some(template) = &revision.template {
345        parts.push(format!("from template {} {}", template.number, template.revision_label));
346    }
347    parts.join(" · ")
348}
349
350// ===========================================================================
351// The panel
352// ===========================================================================
353
354/// A request in flight, polled once a frame.
355struct Pending<T> {
356    future: PlmFuture<T>,
357}
358
359impl<T> Pending<T> {
360    fn new(future: PlmFuture<T>) -> Self {
361        Self { future }
362    }
363
364    fn poll(&mut self) -> Option<Result<T, String>> {
365        let mut cx = Context::from_waker(Waker::noop());
366        match self.future.as_mut().poll(&mut cx) {
367            Poll::Ready(result) => Some(result),
368            Poll::Pending => None,
369        }
370    }
371}
372
373/// What is in flight.
374enum Work {
375    Part(Pending<PartDetail>),
376    /// A verb; on success the part is re-read.
377    Verb(Verb, Pending<String>),
378    History(Pending<Vec<HistoryEvent>>),
379}
380
381/// What happened this frame that the shell acts on.
382#[derive(Debug, Clone, PartialEq)]
383pub enum PanelEvent {
384    /// The shown revision's permission to save changed.
385    Access(Access),
386    /// The user chose another revision to open (its store key).
387    Open(String),
388    /// Open the review pane on a revision: its submit form, or its round
389    /// (`panels::plm_review`, S4).
390    OpenReview { part: String, revision: String },
391    /// A re-read the user's own verb did not cause found the shown revision
392    /// (or its part) changed on the PLM: the shell says so once.
393    Moved(Moved),
394}
395
396/// What changed on the PLM under an open revision, by someone or something
397/// other than this pane's own verb.
398#[derive(Debug, Clone, PartialEq)]
399pub enum Moved {
400    /// The user's lock went; `holder` holds it now, if anyone does, and `by`
401    /// says how (read from the part's history).
402    LockLost { holder: Option<String>, by: LockGone },
403    /// Someone else checked it out.
404    CheckedOutBy(String),
405    /// It was frozen (`released`, `obsolete` or `superseded`), `by` whom when
406    /// known.
407    Lifecycle { to: String, by: Option<String> },
408    /// The part was renamed.
409    Renamed(String),
410}
411
412/// How a lock the user held went, as the part's history tells it.
413#[derive(Debug, Clone, PartialEq)]
414pub enum LockGone {
415    /// The history did not say (or could not be read).
416    Unknown,
417    /// The user checked it in (on the web, or from another client).
418    You,
419    /// Someone else broke it.
420    BrokenBy(String),
421}
422
423/// How the lock on `revision_id` last went, from the part's `history`: its
424/// newest check-in or broken lock.
425pub fn lock_gone(history: &[HistoryEvent], revision_id: &str) -> LockGone {
426    let last = history
427        .iter()
428        .filter(|e| e.entity.kind == "revision" && e.entity.id == revision_id && matches!(e.action.as_str(), "checkin" | "break-lock"))
429        .max_by_key(|e| e.id);
430    match last {
431        Some(e) if e.action == "break-lock" && !e.actor.username.is_empty() => LockGone::BrokenBy(e.actor.username.clone()),
432        Some(e) if e.action == "checkin" => LockGone::You,
433        _ => LockGone::Unknown,
434    }
435}
436
437/// What moved between two reads of `revision_id` of a part: `before` and
438/// `after`, in the order the shell announces them.
439pub fn moved(before: &PartDetail, after: &PartDetail, revision_id: &str) -> Vec<Moved> {
440    let mut out = Vec::new();
441    let find = |part: &PartDetail| part.revision_views.iter().find(|r| r.id == revision_id).cloned();
442    if let (Some(old), Some(new)) = (find(before), find(after)) {
443        let frozen = matches!(new.lifecycle.as_str(), "released" | "obsolete" | "superseded");
444        // A frozen revision has no lock to take back: its own notice says
445        // what Save does now, and "check it out again" would be wrong.
446        if !frozen && old.locked_by_me && !new.locked_by_me {
447            out.push(Moved::LockLost { holder: new.locked_by.clone(), by: LockGone::Unknown });
448        } else if !frozen && !new.locked_by_me && new.locked_by.is_some() && new.locked_by != old.locked_by {
449            out.push(Moved::CheckedOutBy(new.locked_by.clone().unwrap_or_default()));
450        }
451        // Only a move that freezes it is news here: a submit for review is
452        // the user's own (the review pane's), and its save warning is D8's.
453        if old.lifecycle != new.lifecycle && frozen {
454            let by = (new.lifecycle == "released").then(|| new.released_by.clone()).flatten();
455            out.push(Moved::Lifecycle { to: new.lifecycle.clone(), by });
456        }
457    }
458    if before.name != after.name && !after.name.is_empty() {
459        out.push(Moved::Renamed(after.name.clone()));
460    }
461    out
462}
463
464/// The lifecycle panel for ONE document opened from the PLM.
465pub struct PlmPanel {
466    part_id: String,
467    /// The revision the document shows.
468    revision_id: String,
469    rights: Rights,
470    part: Option<PartDetail>,
471    history: Option<Vec<HistoryEvent>>,
472    work: Option<Work>,
473    /// The last sentence to show: a refusal, a release warning, a success.
474    message: Option<String>,
475    /// Typed into the New revision field; empty takes the suggestion.
476    new_label: String,
477    /// The access last reported, so an unchanged one is not re-sent.
478    reported: Option<Access>,
479    /// A new revision was started: open the newest once the part is re-read.
480    open_newest_after: bool,
481    /// New revision was pressed in the pane: show what uses the part, then
482    /// start only on the user's confirmation.
483    confirm_new: bool,
484    /// Events a press raised without a server call, handed out by the next poll.
485    queued: Vec<PanelEvent>,
486    /// The re-read in flight follows this pane's own verb: what it finds
487    /// changed is the user's doing, not news.
488    after_verb: bool,
489    /// A lost lock waiting for the history to say who: the holder now.
490    asking_who: Option<Option<String>>,
491}
492
493impl PlmPanel {
494    /// A panel for `part_id` showing `revision_id`, which asks for the part at
495    /// once.
496    pub fn new(server: &dyn PlmLifecycle, part_id: &str, revision_id: &str, rights: Rights) -> Self {
497        let mut panel = Self {
498            part_id: part_id.to_string(),
499            revision_id: revision_id.to_string(),
500            rights,
501            part: None,
502            history: None,
503            work: None,
504            message: None,
505            new_label: String::new(),
506            reported: None,
507            open_newest_after: false,
508            confirm_new: false,
509            queued: Vec::new(),
510            after_verb: false,
511            asking_who: None,
512        };
513        panel.work = Some(Work::Part(Pending::new(server.part(part_id))));
514        panel
515    }
516
517    pub(crate) fn matches_document(&self, part: &str, revision: &str) -> bool {
518        self.part_id == part && self.revision_id == revision
519    }
520
521    pub fn part(&self) -> Option<&PartDetail> {
522        self.part.as_ref()
523    }
524
525    pub fn revision(&self) -> Option<&RevisionView> {
526        self.part.as_ref()?.revision_views.iter().find(|r| r.id == self.revision_id)
527    }
528
529    pub fn message(&self) -> Option<&str> {
530        self.message.as_deref()
531    }
532
533    pub fn busy(&self) -> bool {
534        self.work.is_some()
535    }
536
537    fn refreshing(&self) -> bool {
538        self.part.is_some() && matches!(self.work, Some(Work::Part(_)))
539    }
540
541    /// Keep the revision's actions mounted during read-only background refreshes.
542    /// Mutating requests still suppress duplicate actions.
543    /// What the signed-in user may do, as this panel was given it.
544    pub fn rights(&self) -> Rights {
545        self.rights
546    }
547
548    pub fn offered(&self) -> Vec<Verb> {
549        match (&self.part, self.revision()) {
550            (Some(part), Some(revision)) if self.work.is_none() || self.refreshing() => {
551                let offered = verbs(part, revision, self.rights);
552                offered
553            }
554            _ => Vec::new(),
555        }
556    }
557
558    /// Start `verb` on the shown revision. Ignored while a request is in flight
559    /// or when the revision does not offer it.
560    pub fn press(&mut self, server: &dyn PlmLifecycle, verb: Verb) {
561        if !self.offered().contains(&verb) {
562            return;
563        }
564        if self.refreshing() { self.work = None; }
565        let (part, rev) = (self.part_id.clone(), self.revision_id.clone());
566        // The review pane are S4's: these open them.
567        match verb {
568            Verb::Submit | Verb::Review => {
569                self.queued.push(PanelEvent::OpenReview { part, revision: rev });
570                return;
571            }
572
573            _ => {}
574        }
575        let done = |label: &'static str| move |_| label.to_string();
576        let future: PlmFuture<String> = match verb {
577            Verb::CheckOut => map(server.checkout(&part, &rev), done("Checked out")),
578            Verb::CheckIn => map(server.checkin(&part, &rev, false), done("Checked in")),
579            Verb::BreakLock => map(server.checkin(&part, &rev, true), done("Lock broken")),
580            Verb::Release => map(server.set_state(&part, &rev, "released"), |warnings: Vec<String>| {
581                if warnings.is_empty() { "Released".to_string() } else { format!("Released — {}", warnings.join("; ")) }
582            }),
583            Verb::Submit | Verb::Review => unreachable!("opened above"),
584            Verb::NewRevision => map(server.create_revision(&part, self.new_label.trim()), |r: NewRevision| {
585                format!("Revision {} started", r.label)
586            }),
587        };
588        self.message = None;
589        self.work = Some(Work::Verb(verb, Pending::new(future)));
590    }
591
592    /// Re-read the part: another client may have changed the revision (a
593    /// submit, a release, a broken lock). Ignored while a request is in flight.
594    pub fn refresh(&mut self, server: &dyn PlmLifecycle) {
595        if self.work.is_none() {
596            self.work = Some(Work::Part(Pending::new(server.part(&self.part_id))));
597        }
598    }
599
600    /// Ask for the part's history.
601    pub fn load_history(&mut self, server: &dyn PlmLifecycle) {
602        if self.refreshing() { self.work = None; }
603        if self.work.is_none() {
604            self.work = Some(Work::History(Pending::new(server.history(&self.part_id))));
605        }
606    }
607
608    pub fn history(&self) -> Option<&[HistoryEvent]> {
609        self.history.as_deref()
610    }
611
612    /// Drive the request in flight one step. Returns what the shell must act
613    /// on: the document's new access, or a revision to open.
614    pub fn poll(&mut self, server: &dyn PlmLifecycle) -> Vec<PanelEvent> {
615        let mut events = std::mem::take(&mut self.queued);
616        let Some(work) = self.work.as_mut() else { return events };
617        match work {
618            Work::Part(pending) => match pending.poll() {
619                None => return events,
620                Some(Ok(part)) => {
621                    if let Some(before) = self.part.as_ref().filter(|_| !std::mem::take(&mut self.after_verb)) {
622                        let changes = moved(before, &part, &self.revision_id);
623                        // The last sentence ("Checked out") is about a state
624                        // that is gone.
625                        if !changes.is_empty() {
626                            self.message = None;
627                        }
628                        for change in changes {
629                            match change {
630                                // Who took it is one history read away.
631                                Moved::LockLost { holder, .. } => self.asking_who = Some(holder),
632                                other => events.push(PanelEvent::Moved(other)),
633                            }
634                        }
635                    }
636                    self.part = Some(part);
637                    self.work = self
638                        .asking_who
639                        .is_some()
640                        .then(|| Work::History(Pending::new(server.history(&self.part_id))));
641                }
642                Some(Err(error)) => {
643                    self.message = Some(error);
644                    self.work = None;
645                    self.after_verb = false;
646                }
647            },
648            Work::Verb(verb, pending) => {
649                let verb = *verb;
650                match pending.poll() {
651                    None => return events,
652                    Some(result) => {
653                        let new_revision = verb == Verb::NewRevision;
654                        self.work = Some(Work::Part(Pending::new(server.part(&self.part_id))));
655                        self.after_verb = true;
656                        match result {
657                            Ok(sentence) => {
658                                self.message = Some(sentence);
659                                if new_revision {
660                                    self.new_label.clear();
661                                }
662                            }
663                            Err(error) => {
664                                self.message = Some(error);
665                            }
666                        }
667                        // A new revision is opened once the part is re-read.
668                        self.open_newest_after = new_revision;
669                        return events;
670                    }
671                }
672            }
673            Work::History(pending) => match pending.poll() {
674                None => return events,
675                Some(result) => {
676                    self.work = None;
677                    let asked = self.asking_who.take();
678                    let by = match &result {
679                        Ok(history) => lock_gone(history, &self.revision_id),
680                        Err(_) => LockGone::Unknown,
681                    };
682                    match result {
683                        Ok(history) => self.history = Some(history),
684                        // The read was the notice's, not the user's: its
685                        // failure is not the pane's sentence.
686                        Err(error) if asked.is_none() => self.message = Some(error),
687                        Err(_) => {}
688                    }
689                    if let Some(holder) = asked {
690                        events.push(PanelEvent::Moved(Moved::LockLost { holder, by }));
691                    }
692                }
693            },
694        }
695        if std::mem::take(&mut self.open_newest_after) {
696            if let Some(revision) = self.part.as_ref().and_then(newest) {
697                if revision.id != self.revision_id {
698                    events.push(PanelEvent::Open(revision.document_key.clone()));
699                }
700            }
701        }
702        if let Some(revision) = self.revision() {
703            let access = access_with(revision, self.rights);
704            if self.reported.as_ref() != Some(&access) {
705                self.reported = Some(access.clone());
706                events.push(PanelEvent::Access(access));
707            }
708        }
709        events
710    }
711
712    /// Poll, then draw. Returns what the shell must act on, as [`Self::poll`].
713    pub fn ui(&mut self, ui: &mut egui::Ui, server: &dyn PlmLifecycle) -> Vec<PanelEvent> {
714        let mut events = self.poll(server);
715        let mut hits = std::collections::HashMap::new();
716        events.extend(self.draw(ui, server, &mut crate::panels::plm_host::SectionHits::new("lifecycle", &mut hits)));
717        events
718    }
719
720    /// Draw the panel without polling — for a host that polls every panel
721    /// itself ([`crate::panels::plm_host::PlmHost::sync`]). Returns the picks
722    /// made on this frame (another revision to open); a pressed verb's answer
723    /// arrives through the next [`Self::poll`].
724    ///
725    /// Hit keys (under `plm/`): `lifecycle:revision:<label>` for each picker
726    /// row, `lifecycle:verb:<Verb::key>` for each verb, `lifecycle:new-label`,
727    /// `lifecycle:history:load`.
728    pub fn draw(
729        &mut self,
730        ui: &mut egui::Ui,
731        server: &dyn PlmLifecycle,
732        hits: &mut crate::panels::plm_host::SectionHits<'_>,
733    ) -> Vec<PanelEvent> {
734        self.draw_with(ui, server, hits, &mut |_| {})
735    }
736
737    /// [`Self::draw`], with `before_new_revision` drawn in the New revision
738    /// confirmation — the host shows where the part is used there, so a user
739    /// sees what a change reaches before starting one (S6's where-used).
740    ///
741    /// Extra hit keys: `lifecycle:new-revision:start`, `lifecycle:new-revision:cancel`.
742    pub fn draw_with(
743        &mut self,
744        ui: &mut egui::Ui,
745        server: &dyn PlmLifecycle,
746        hits: &mut crate::panels::plm_host::SectionHits<'_>,
747        before_new_revision: &mut dyn FnMut(&mut egui::Ui),
748    ) -> Vec<PanelEvent> {
749        let mut events = Vec::new();
750        if self.busy() {
751            ui.ctx().request_repaint();
752        }
753        let Some(part) = self.part.clone() else {
754            ui.horizontal(|ui| {
755                ui.spinner();
756                ui.label("Reading the part from the PLM…");
757            });
758            if let Some(message) = &self.message {
759                ui.colored_label(ui.visuals().error_fg_color, message);
760            }
761            return events;
762        };
763        ui.heading(format!("{} {}", part.number, part.name));
764        if let Some(revision) = self.revision() {
765            let access = access_with(revision, self.rights);
766            match &access {
767                Access::Editable => ui.label(format!("Revision {} — checked out by you", revision.label)),
768                Access::ReadOnly { reason } => ui.label(format!("Read-only: {reason}")),
769            };
770        }
771        ui.separator();
772        ui.label("Revisions");
773        for revision in part.revision_views.iter().rev() {
774            let shown = revision.id == self.revision_id;
775            let response = ui.selectable_label(shown, describe(revision));
776            hits.put(&format!("revision:{}", revision.label), response.rect);
777            if response.clicked() && !shown {
778                events.push(PanelEvent::Open(revision.document_key.clone()));
779            }
780        }
781        ui.separator();
782        let offered = self.offered();
783        ui.horizontal_wrapped(|ui| {
784            for verb in offered.iter().copied().filter(|v| *v != Verb::NewRevision) {
785                let label = verb.label();
786                let button = ui.button(label);
787                hits.put(&format!("verb:{}", verb.key()), button.rect);
788                if button.clicked() {
789                    self.press(server, verb);
790                }
791            }
792        });
793        if offered.contains(&Verb::NewRevision) {
794            ui.horizontal(|ui| {
795                let field = ui.add(egui::TextEdit::singleline(&mut self.new_label).hint_text(part.suggested_label.as_str()).desired_width(80.0));
796                hits.put("new-label", field.rect);
797                let button = ui.button(format!("{}…", Verb::NewRevision.label()));
798                hits.put(&format!("verb:{}", Verb::NewRevision.key()), button.rect);
799                if button.clicked() {
800                    self.confirm_new = true;
801                }
802            });
803            if self.confirm_new {
804                egui::Frame::group(ui.style()).show(ui, |ui| {
805                    ui.label("Before starting a new revision: where this part is used");
806                    before_new_revision(ui);
807                    ui.horizontal(|ui| {
808                        let label = if self.new_label.trim().is_empty() { part.suggested_label.clone() } else { self.new_label.trim().to_string() };
809                        let start = ui.button(format!("Start revision {label}"));
810                        hits.put("new-revision:start", start.rect);
811                        if start.clicked() {
812                            self.confirm_new = false;
813                            self.press(server, Verb::NewRevision);
814                        }
815                        let cancel = ui.button("Cancel");
816                        hits.put("new-revision:cancel", cancel.rect);
817                        if cancel.clicked() {
818                            self.confirm_new = false;
819                        }
820                    });
821                });
822            }
823        } else {
824            self.confirm_new = false;
825        }
826        ui.horizontal(|ui| {
827            let refresh = ui.add_enabled(!self.busy() || self.refreshing(), egui::Button::new("Refresh"));
828            hits.put("refresh", refresh.rect);
829            if refresh.clicked() {
830                self.refresh(server);
831            }
832            if self.busy() && !self.refreshing() {
833                ui.spinner();
834            }
835        });
836        if let Some(message) = &self.message {
837            ui.label(message);
838        }
839        ui.separator();
840        egui::CollapsingHeader::new("History").id_salt("plm-lifecycle-history").show(ui, |ui| {
841            match &self.history {
842                None => {
843                    let button = ui.button("Load history");
844                    hits.put("history:load", button.rect);
845                    if button.clicked() {
846                        self.load_history(server);
847                    }
848                }
849                Some(events) if events.is_empty() => {
850                    ui.label("No changes recorded.");
851                }
852                Some(events) => {
853                    for event in events {
854                        let what = if event.entity.label.is_empty() { &event.entity.kind } else { &event.entity.label };
855                        ui.label(format!("{} {} {} ({})", event.actor.username, event.action, what, event.actor.via));
856                    }
857                }
858            }
859        });
860        events
861    }
862}
863
864// ===========================================================================
865// Over the PLM client
866// ===========================================================================
867
868/// The routes over [`crate::plm::client::PlmClient`]. An `Rc`, because each
869/// answer is a future the panel keeps across frames, and it must hold the
870/// client that sends it.
871impl PlmLifecycle for std::rc::Rc<crate::plm::client::PlmClient> {
872    fn rights(&self) -> PlmFuture<Rights> {
873        #[derive(Deserialize, Default)]
874        #[serde(default)]
875        struct Can {
876            can_author: bool,
877            can_checkin: bool,
878        }
879        let client = self.clone();
880        Box::pin(async move {
881            let can: Can = json(client.call("GET", "/api/me", None).await)?;
882            Ok(Rights { can_author: can.can_author, can_checkin: can.can_checkin })
883        })
884    }
885
886    fn part(&self, part: &str) -> PlmFuture<PartDetail> {
887        let (client, path) = (self.clone(), crate::plm::identity::part_path(&part));
888        Box::pin(async move { json(client.call("GET", &path, None).await) })
889    }
890
891    fn checkout(&self, part: &str, revision: &str) -> PlmFuture<()> {
892        let (client, path) = (self.clone(), format!("{}/checkout", crate::plm::identity::revision_path(&part, &revision)));
893        let body = serde_json::json!({ "client_id": CLIENT_ID }).to_string().into_bytes();
894        Box::pin(async move { unit(client.call("POST", &path, Some(body)).await) })
895    }
896
897    fn checkin(&self, part: &str, revision: &str, force: bool) -> PlmFuture<()> {
898        let (client, path) = (self.clone(), format!("{}/checkin", crate::plm::identity::revision_path(&part, &revision)));
899        let body = serde_json::json!({ "force": force }).to_string().into_bytes();
900        Box::pin(async move { unit(client.call("POST", &path, Some(body)).await) })
901    }
902
903    fn set_state(&self, part: &str, revision: &str, to: &str) -> PlmFuture<Vec<String>> {
904        #[derive(Deserialize, Default)]
905        #[serde(default)]
906        struct Answer {
907            warnings: Vec<String>,
908        }
909        let (client, path) = (self.clone(), format!("{}/state", crate::plm::identity::revision_path(&part, &revision)));
910        let body = serde_json::json!({ "to": to }).to_string().into_bytes();
911        Box::pin(async move { json::<Answer>(client.call("POST", &path, Some(body)).await).map(|a| a.warnings) })
912    }
913
914    fn create_revision(&self, part: &str, label: &str) -> PlmFuture<NewRevision> {
915        let (client, path) = (self.clone(), format!("{}/revisions", crate::plm::identity::part_path(&part)));
916        let body = serde_json::json!({ "label": label }).to_string().into_bytes();
917        Box::pin(async move { json(client.call("POST", &path, Some(body)).await) })
918    }
919
920    fn history(&self, part: &str) -> PlmFuture<Vec<HistoryEvent>> {
921        let (client, path) = (self.clone(), format!("{}/history", crate::plm::identity::part_path(&part)));
922        Box::pin(async move { json(client.call("GET", &path, None).await) })
923    }
924}
925
926/// A 2xx answer's JSON body, or the server's sentence.
927fn json<T: for<'de> Deserialize<'de>>(
928    answer: Result<crate::plm::PlmResponse, crate::plm::client::PlmError>,
929) -> Result<T, String> {
930    let response = answer.map_err(|e| e.to_string())?;
931    serde_json::from_slice(&response.body).map_err(|e| format!("the PLM answered in a shape this app does not read: {e}"))
932}
933
934fn unit(answer: Result<crate::plm::PlmResponse, crate::plm::client::PlmError>) -> Result<(), String> {
935    answer.map(|_| ()).map_err(|e| e.to_string())
936}
937
938/// `future` with its value mapped.
939fn map<T: 'static, U: 'static>(future: PlmFuture<T>, f: impl FnOnce(T) -> U + 'static) -> PlmFuture<U> {
940    Box::pin(async move { future.await.map(f) })
941}
942