Skip to main content

rustango_cms/
workflow.rs

1//! Multi-step approval workflows.
2//!
3//! Editors compose a `Workflow` from ordered `WorkflowTask`s. When
4//! they submit a page for review, a `WorkflowState` row tracks
5//! "where in the workflow this page is right now," and a `TaskState`
6//! row records the verdict on each step.
7//!
8//! This module holds the data model + admin CRUD; the page-editor UI
9//! (Submit / Approve / Reject buttons), notifications and
10//! reapproval-on-edit build on it.
11//!
12//! ## Shape
13//!
14//! ```text
15//! Workflow ─< WorkflowTask (ordered by sort_order)
16//!     │
17//!     └─< WorkflowState (one per page-in-flight)
18//!             │
19//!             └─< TaskState (one per step decision)
20//! ```
21//!
22//! ## States
23//!
24//! `WorkflowState.status` is one of: `in_progress`, `approved`,
25//! `needs_changes`, `cancelled`. `TaskState.status` is one of:
26//! `in_progress`, `approved`, `rejected`, `skipped`. The string
27//! representation is stable on disk so future ALTERs don't break
28//! existing rows.
29
30use chrono::{DateTime, Utc};
31use rustango::sql::Auto;
32use rustango::Model;
33use serde::{Deserialize, Serialize};
34
35// ---------------------------------------------------------------
36// Status enums — stored as short strings for grep-ability + cheap
37// migrations.
38// ---------------------------------------------------------------
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum WorkflowStatus {
43    InProgress,
44    Approved,
45    NeedsChanges,
46    Cancelled,
47}
48
49impl WorkflowStatus {
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::InProgress => "in_progress",
54            Self::Approved => "approved",
55            Self::NeedsChanges => "needs_changes",
56            Self::Cancelled => "cancelled",
57        }
58    }
59
60    #[must_use]
61    pub fn parse(s: &str) -> Option<Self> {
62        Some(match s {
63            "in_progress" => Self::InProgress,
64            "approved" => Self::Approved,
65            "needs_changes" => Self::NeedsChanges,
66            "cancelled" => Self::Cancelled,
67            _ => return None,
68        })
69    }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum TaskStatus {
75    InProgress,
76    Approved,
77    Rejected,
78    Skipped,
79}
80
81impl TaskStatus {
82    #[must_use]
83    pub fn as_str(self) -> &'static str {
84        match self {
85            Self::InProgress => "in_progress",
86            Self::Approved => "approved",
87            Self::Rejected => "rejected",
88            Self::Skipped => "skipped",
89        }
90    }
91
92    #[must_use]
93    pub fn parse(s: &str) -> Option<Self> {
94        Some(match s {
95            "in_progress" => Self::InProgress,
96            "approved" => Self::Approved,
97            "rejected" => Self::Rejected,
98            "skipped" => Self::Skipped,
99            _ => return None,
100        })
101    }
102}
103
104// ---------------------------------------------------------------
105// Workflow — the template. Composed of an ordered list of tasks.
106// ---------------------------------------------------------------
107
108#[derive(Model, Debug, Clone, Serialize, Deserialize)]
109#[rustango(
110    table = "cms_workflow",
111    app = "cms",
112    display = "name",
113    admin(
114        list_display = "name, active, created_at",
115        ordering = "name",
116        list_filter = "active",
117    )
118)]
119pub struct Workflow {
120    #[rustango(primary_key)]
121    pub id: Auto<i64>,
122
123    /// Human-readable label shown in the admin (e.g.
124    /// `"Editorial review"`, `"Legal sign-off"`).
125    #[rustango(max_length = 100, index)]
126    pub name: String,
127
128    /// Optional one-line explanation surfaced in the workflow list.
129    #[rustango(max_length = 255)]
130    pub description: String,
131
132    /// Inactive workflows stay in the DB so old `WorkflowState` rows
133    /// don't lose their parent FK, but new submissions filter them
134    /// out.
135    pub active: bool,
136
137    /// When true, a content edit on a page in the Approved state of
138    /// this workflow restarts the workflow from the first task.
139    /// Configured per workflow rather than globally.
140    pub require_reapproval_on_edit: bool,
141
142    #[rustango(auto_now_add)]
143    pub created_at: Auto<DateTime<Utc>>,
144
145    #[rustango(auto_now)]
146    pub updated_at: Auto<DateTime<Utc>>,
147}
148
149// ---------------------------------------------------------------
150// WorkflowTask — one ordered step of a Workflow. v1 only ships the
151// "group approval" shape (any member of a role can approve). Custom
152// task kinds (auto-approve, conditional skip, external webhook)
153// surface in a later PR via a `kind` discriminator.
154// ---------------------------------------------------------------
155
156#[derive(Model, Debug, Clone, Serialize, Deserialize)]
157#[rustango(
158    table = "cms_workflow_task",
159    app = "cms",
160    display = "name",
161    admin(
162        list_display = "workflow_id, sort_order, name, role_id",
163        ordering = "workflow_id, sort_order",
164        list_filter = "workflow_id",
165    )
166)]
167pub struct WorkflowTask {
168    #[rustango(primary_key)]
169    pub id: Auto<i64>,
170
171    #[rustango(fk = "cms_workflow", on = "id", index)]
172    pub workflow_id: i64,
173
174    /// Display name on the action bar ("Editor review",
175    /// "Legal review", "Final publish").
176    #[rustango(max_length = 100)]
177    pub name: String,
178
179    /// Role whose members can approve / reject this step. v1 keeps
180    /// the binding to `rustango_roles`; v2 may widen to "any user"
181    /// or "named user."
182    #[rustango(fk = "rustango_roles", on = "id", index)]
183    pub role_id: i64,
184
185    /// Lower numbers run first. Siblings within the same workflow
186    /// share `workflow_id` and order by this column.
187    pub sort_order: i32,
188
189    /// Task-kind discriminator. Maps to one of the registered
190    /// [`crate::task_kind::TaskKind`] implementations:
191    ///   * `"group_approval"` — default; a role member must click
192    ///     approve / reject via the existing UI.
193    ///   * `"auto_approve"` — completes immediately when assigned,
194    ///     no human interaction.
195    ///   * `"webhook_notify"` — fires `webhook_url` (best-effort)
196    ///     when assigned and then auto-completes; external systems
197    ///     can post their decision back through the usual approve
198    ///     route.
199    ///   * Any string a host registered via `register_task_kind!`.
200    #[rustango(max_length = 64, default = "'group_approval'")]
201    pub kind: String,
202
203    /// URL to POST when this task is assigned. Used by
204    /// `webhook_notify`; other kinds ignore. Empty when unused.
205    #[rustango(max_length = 500, default = "''")]
206    pub webhook_url: String,
207}
208
209// ---------------------------------------------------------------
210// WorkflowState — per page, per submission. A page can have at most
211// one *active* WorkflowState (status != Approved && != Cancelled);
212// historical rows are kept for audit.
213// ---------------------------------------------------------------
214
215#[derive(Model, Debug, Clone, Serialize, Deserialize)]
216#[rustango(
217    table = "cms_workflow_state",
218    app = "cms",
219    display = "page_id",
220    admin(
221        list_display = "page_id, workflow_id, status, current_task_id, requested_by, requested_at",
222        ordering = "-requested_at",
223        list_filter = "status, workflow_id",
224    )
225)]
226pub struct WorkflowState {
227    #[rustango(primary_key)]
228    pub id: Auto<i64>,
229
230    #[rustango(fk = "cms_page", on = "id", index)]
231    pub page_id: i64,
232
233    #[rustango(fk = "cms_workflow", on = "id", index)]
234    pub workflow_id: i64,
235
236    /// `WorkflowStatus::as_str()`.
237    #[rustango(max_length = 16, index)]
238    pub status: String,
239
240    /// The task currently waiting on a decision. `None` when the
241    /// workflow finished (approved or cancelled).
242    pub current_task_id: Option<i64>,
243
244    /// Editor who submitted the page for review.
245    #[rustango(fk = "rustango_users", on = "id", index)]
246    pub requested_by: i64,
247
248    #[rustango(auto_now_add)]
249    pub requested_at: Auto<DateTime<Utc>>,
250
251    /// Filled when the workflow reaches a terminal state
252    /// (approved / cancelled). Nullable while in flight.
253    pub finished_at: Option<DateTime<Utc>>,
254}
255
256// ---------------------------------------------------------------
257// TaskState — one row per WorkflowTask decision on a given
258// WorkflowState. Carries the reviewer + a free-form comment.
259// ---------------------------------------------------------------
260
261#[derive(Model, Debug, Clone, Serialize, Deserialize)]
262#[rustango(
263    table = "cms_task_state",
264    app = "cms",
265    display = "id",
266    admin(
267        list_display = "workflow_state_id, task_id, status, decided_by, decided_at",
268        ordering = "-decided_at",
269        list_filter = "status",
270    )
271)]
272pub struct TaskState {
273    #[rustango(primary_key)]
274    pub id: Auto<i64>,
275
276    #[rustango(fk = "cms_workflow_state", on = "id", index)]
277    pub workflow_state_id: i64,
278
279    #[rustango(fk = "cms_workflow_task", on = "id", index)]
280    pub task_id: i64,
281
282    /// `TaskStatus::as_str()`.
283    #[rustango(max_length = 16, index)]
284    pub status: String,
285
286    /// Reviewer's note shown in the audit panel. Empty string =
287    /// "no comment."
288    pub comment: String,
289
290    /// Reviewer who set this status. `None` while the task is still
291    /// in_progress.
292    pub decided_by: Option<i64>,
293
294    pub decided_at: Option<DateTime<Utc>>,
295}
296
297// ---------------------------------------------------------------
298// Helpers used by the page-editor handlers.
299// ---------------------------------------------------------------
300
301/// Look up the active (non-finished, non-cancelled) `WorkflowState`
302/// for a page. Returns at most one row — a page is in at most one
303/// active workflow at a time. Historical rows (approved / cancelled)
304/// are filtered out.
305///
306/// # Errors
307/// Driver / query failures.
308pub async fn active_state_for_page(
309    pool: &rustango::sql::Pool,
310    page_id: i64,
311) -> Result<Option<WorkflowState>, rustango::sql::ExecError> {
312    // Judged on the latest round only: a resubmission starts a new
313    // state and leaves the earlier `needs_changes` one behind, which must
314    // not come back once the new round is approved.
315    Ok(latest_state_for_page(pool, page_id).await?.filter(|st| {
316        st.status == WorkflowStatus::InProgress.as_str() || st.status == WorkflowStatus::NeedsChanges.as_str()
317    }))
318}
319
320/// The page's most recent review round, whatever its outcome.
321///
322/// # Errors
323/// Driver / query failures.
324pub async fn latest_state_for_page(
325    pool: &rustango::sql::Pool,
326    page_id: i64,
327) -> Result<Option<WorkflowState>, rustango::sql::ExecError> {
328    use rustango::core::Column as _;
329    use rustango::sql::FetcherPool as _;
330
331    let rows: Vec<WorkflowState> = WorkflowState::objects()
332        .where_(WorkflowState::page_id.eq(page_id))
333        .order_by(&[("requested_at", true), ("id", true)]) // newest first
334        .fetch(pool)
335        .await?;
336    Ok(rows.into_iter().next())
337}
338
339/// Every decision on the page across all its review rounds, oldest first
340/// — a rejection's reason stays visible after the resubmission.
341///
342/// # Errors
343/// Driver / query failures.
344pub async fn history_for_page(
345    pool: &rustango::sql::Pool,
346    page_id: i64,
347) -> Result<Vec<TaskState>, rustango::sql::ExecError> {
348    use rustango::core::Column as _;
349    use rustango::sql::FetcherPool as _;
350
351    let ids: Vec<i64> = WorkflowState::objects()
352        .where_(WorkflowState::page_id.eq(page_id))
353        .fetch(pool)
354        .await?
355        .into_iter()
356        .filter_map(|st| st.id.get().copied())
357        .collect();
358    if ids.is_empty() {
359        return Ok(Vec::new());
360    }
361    TaskState::objects()
362        .where_(TaskState::workflow_state_id.is_in(ids))
363        .order_by(&[("id", false)])
364        .fetch(pool)
365        .await
366}
367
368/// Look up a workflow by its (case-sensitive) `name`. The name acts
369/// as the slug returned from `PageTypeHandler::workflow_slug()`. Only
370/// returns active workflows; inactive ones are treated as missing so
371/// editors can disable a workflow without invalidating every
372/// page-type binding.
373///
374/// # Errors
375/// Driver / query failures.
376pub async fn find_by_name(
377    pool: &rustango::sql::Pool,
378    name: &str,
379) -> Result<Option<Workflow>, rustango::sql::ExecError> {
380    use rustango::core::Column as _;
381    use rustango::sql::FetcherPool as _;
382
383    let rows: Vec<Workflow> = Workflow::objects()
384        .where_(Workflow::name.eq(name.to_owned()))
385        .where_(Workflow::active.eq(true))
386        .fetch(pool)
387        .await?;
388    Ok(rows.into_iter().next())
389}
390
391/// The active workflow pages of `page_type_id` go through before they
392/// are published, if any: the type's handler slug or the one chosen in
393/// the admin, resolved to an active workflow with at least one step.
394/// Pages of such a type go live only through review — except for
395/// superusers (the callers check).
396///
397/// # Errors
398/// Driver / query failures.
399pub async fn review_workflow_for_type(
400    pool: &rustango::sql::Pool,
401    page_type_id: i64,
402) -> Result<Option<Workflow>, rustango::sql::ExecError> {
403    use rustango::core::Column as _;
404    
405    let Some(pt) = crate::page_type_model::PageType::objects()
406        .where_(crate::page_type_model::PageType::id.eq(page_type_id))
407        .first(pool)
408        .await?
409    else {
410        return Ok(None);
411    };
412    let Some(name) = pt.workflow_name() else {
413        return Ok(None);
414    };
415    let Some(wf) = find_by_name(pool, &name).await? else {
416        return Ok(None);
417    };
418    let has_steps = !tasks_for(pool, wf.id.get().copied().unwrap_or_default()).await?.is_empty();
419    Ok(has_steps.then_some(wf))
420}
421
422/// The page types chosen in the admin to go through the workflow `name`.
423///
424/// # Errors
425/// Driver / query failures.
426pub async fn page_types_using(
427    pool: &rustango::sql::Pool,
428    name: &str,
429) -> Result<Vec<crate::page_type_model::PageType>, rustango::sql::ExecError> {
430    use rustango::core::Column as _;
431    use rustango::sql::FetcherPool as _;
432    crate::page_type_model::PageType::objects()
433        .where_(crate::page_type_model::PageType::workflow.eq(name.to_owned()))
434        .fetch(pool)
435        .await
436}
437
438/// Point the page types that use workflow `old` at its new name `new`
439/// (page types store the name). Returns how many moved.
440///
441/// # Errors
442/// Driver / query failures.
443pub async fn rebind_page_types(
444    pool: &rustango::sql::Pool,
445    old: &str,
446    new: &str,
447) -> Result<usize, rustango::sql::ExecError> {
448    let types = page_types_using(pool, old).await?;
449    let n = types.len();
450    for mut pt in types {
451        new.clone_into(&mut pt.workflow);
452        pt.save(pool).await?;
453    }
454    Ok(n)
455}
456
457/// Fetch the ordered task list for a workflow id.
458///
459/// # Errors
460/// Driver / query failures.
461pub async fn tasks_for(
462    pool: &rustango::sql::Pool,
463    workflow_id: i64,
464) -> Result<Vec<WorkflowTask>, rustango::sql::ExecError> {
465    use rustango::core::Column as _;
466    use rustango::sql::FetcherPool as _;
467
468    WorkflowTask::objects()
469        .where_(WorkflowTask::workflow_id.eq(workflow_id))
470        .order_by(&[("sort_order", false), ("id", false)])
471        .fetch(pool)
472        .await
473}
474
475/// Submit a page for review: create a new `WorkflowState` pinned to
476/// the first task + an `in_progress` `TaskState`. Caller must have
477/// already verified the page is in Draft or NeedsChanges state and
478/// the workflow has at least one task.
479///
480/// # Errors
481/// Driver / query failures.
482pub async fn submit_for_review(
483    pool: &rustango::sql::Pool,
484    page_id: i64,
485    workflow: &Workflow,
486    tasks: &[WorkflowTask],
487    requested_by: i64,
488) -> Result<WorkflowState, rustango::sql::ExecError> {
489    use rustango::sql::Auto;
490
491    let workflow_id = workflow.id.get().copied().unwrap_or_default();
492    let first_task_id = tasks.first().and_then(|t| t.id.get().copied());
493
494    let mut state = WorkflowState {
495        id: Auto::Unset,
496        page_id,
497        workflow_id,
498        status: WorkflowStatus::InProgress.as_str().to_owned(),
499        current_task_id: first_task_id,
500        requested_by,
501        requested_at: Auto::Unset,
502        finished_at: None,
503    };
504    state.insert(pool).await?;
505
506    if let Some(task_id) = first_task_id {
507        let state_id = state.id.get().copied().unwrap_or_default();
508        let mut ts = TaskState {
509            id: Auto::Unset,
510            workflow_state_id: state_id,
511            task_id,
512            status: TaskStatus::InProgress.as_str().to_owned(),
513            comment: String::new(),
514            decided_by: None,
515            decided_at: None,
516        };
517        ts.insert(pool).await?;
518    }
519
520    // #191 — fire the first task's on_assign hook. If the kind
521    // auto-satisfies, advance past it (and through any chained
522    // auto-approve tasks) before returning.
523    advance_through_auto_approve_chain(pool, &mut state, tasks, page_id, requested_by).await?;
524    Ok(state)
525}
526
527/// Auto-approve helper: when the current task's kind reports
528/// `AutoApprove`, mark it approved and advance to the next task,
529/// repeating until we hit a `WaitForHuman` or the workflow
530/// finishes. Called from [`submit_for_review`] after the first
531/// task is assigned and from [`approve_current`] after a human
532/// approves and the next task gets assigned.
533async fn advance_through_auto_approve_chain(
534    pool: &rustango::sql::Pool,
535    state: &mut WorkflowState,
536    tasks: &[WorkflowTask],
537    page_id: i64,
538    requested_by: i64,
539) -> Result<(), rustango::sql::ExecError> {
540    use crate::page::Page;
541    use rustango::core::Column as _;
542    use rustango::sql::Auto;
543
544    // Resolve the live Page row once — every kind's on_assign hook
545    // wants page context.
546    let page: Page = match Page::objects()
547        .where_(Page::id.eq(page_id))
548        .first(pool)
549        .await?
550    {
551        Some(p) => p,
552        None => return Ok(()),
553    };
554
555    loop {
556        let Some(current_task_id) = state.current_task_id else {
557            return Ok(());
558        };
559        let Some(current_task) = tasks
560            .iter()
561            .find(|t| t.id.get().copied() == Some(current_task_id))
562        else {
563            return Ok(());
564        };
565        let kind = crate::task_kind::find(&current_task.kind)
566            .unwrap_or_else(|| Box::new(crate::task_kind::GroupApprovalKind));
567        let ctx = crate::task_kind::AssignedTask {
568            task: current_task,
569            page: &page,
570            requested_by,
571        };
572        match kind.on_assign(&ctx) {
573            crate::task_kind::AssignOutcome::WaitForHuman => return Ok(()),
574            crate::task_kind::AssignOutcome::AutoApprove => {
575                // Mark the in-flight TaskState approved with no
576                // decided_by (system action).
577                let state_id = state.id.get().copied().unwrap_or_default();
578                let now = Utc::now();
579                if let Some(mut ts) = TaskState::objects()
580                    .where_(TaskState::workflow_state_id.eq(state_id))
581                    .where_(TaskState::task_id.eq(current_task_id))
582                    .where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
583                    .first(pool)
584                    .await?
585                {
586                    ts.status = TaskStatus::Approved.as_str().to_owned();
587                    ts.decided_by = None;
588                    ts.decided_at = Some(now);
589                    ts.comment = format!("auto-approved by `{}` task kind", current_task.kind);
590                    ts.save(pool).await?;
591                }
592
593                let current_sort = current_task.sort_order;
594                let next = tasks
595                    .iter()
596                    .filter(|t| t.sort_order > current_sort)
597                    .min_by_key(|t| t.sort_order);
598                if let Some(next_task) = next {
599                    let next_id = next_task.id.get().copied().unwrap_or_default();
600                    state.current_task_id = Some(next_id);
601                    // #73 — save_partial (not save) so the unchanged
602                    // `requested_by -> rustango_users` FK is not re-bound/re-validated;
603                    // a full-row UPDATE 787s on SQLite when the original submitter's
604                    // user row is gone (deleted / deactivated-and-purged).
605                    state
606                        .save_partial(&["status", "current_task_id", "finished_at"], pool)
607                        .await?;
608                    let mut ts = TaskState {
609                        id: Auto::Unset,
610                        workflow_state_id: state_id,
611                        task_id: next_id,
612                        status: TaskStatus::InProgress.as_str().to_owned(),
613                        comment: String::new(),
614                        decided_by: None,
615                        decided_at: None,
616                    };
617                    ts.insert(pool).await?;
618                    // Loop continues — the next task might also be
619                    // an auto-approve, in which case we chain
620                    // through.
621                } else {
622                    state.current_task_id = None;
623                    state.status = WorkflowStatus::Approved.as_str().to_owned();
624                    state.finished_at = Some(now);
625                    // #73 — save_partial (not save) so the unchanged
626                    // `requested_by -> rustango_users` FK is not re-bound/re-validated;
627                    // a full-row UPDATE 787s on SQLite when the original submitter's
628                    // user row is gone (deleted / deactivated-and-purged).
629                    state
630                        .save_partial(&["status", "current_task_id", "finished_at"], pool)
631                        .await?;
632                    return Ok(());
633                }
634            }
635        }
636    }
637}
638
639/// Outcome of approving the current task. `Advanced` means the
640/// workflow moved to the next task; `Finished` means every task
641/// approved and the workflow ended (the caller flips the page to
642/// Published).
643#[derive(Debug, Clone)]
644pub enum ApproveOutcome {
645    Advanced { next_task_id: i64 },
646    Finished,
647    /// There is no step to decide, so nothing changed: another request
648    /// decided it first (a double-click, or two reviewers at once),
649    /// or the current task is no longer in the workflow — finished, or
650    /// removed — which a fallback position would have restarted.
651    AlreadyDecided,
652}
653
654/// Decide the in-progress `TaskState` for `task_id` — one conditional
655/// UPDATE, so of two concurrent decisions exactly one flips the row.
656/// Returns whether this call was the one.
657async fn claim_task(
658    pool: &rustango::sql::Pool,
659    state_id: i64,
660    task_id: i64,
661    to: TaskStatus,
662    decided_by: i64,
663    comment: &str,
664) -> Result<bool, rustango::sql::ExecError> {
665    use rustango::core::{Column as _, SqlValue};
666    use rustango::sql::UpdaterPool as _;
667    let changed = TaskState::objects()
668        .where_(TaskState::workflow_state_id.eq(state_id))
669        .where_(TaskState::task_id.eq(task_id))
670        .where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
671        .update()
672        .set("status", SqlValue::from(to.as_str()))
673        .set("decided_by", SqlValue::from(decided_by))
674        .set("decided_at", SqlValue::from(Utc::now()))
675        .set("comment", SqlValue::from(comment.to_owned()))
676        .execute_pool(pool)
677        .await?;
678    Ok(changed > 0)
679}
680
681/// Approve the current task on a `WorkflowState`. Marks the in-flight
682/// `TaskState` Approved, advances to the next task (or finishes the
683/// workflow when no next task exists).
684///
685/// # Errors
686/// Driver / query failures.
687pub async fn approve_current(
688    pool: &rustango::sql::Pool,
689    state: &mut WorkflowState,
690    tasks: &[WorkflowTask],
691    decided_by: i64,
692    comment: &str,
693) -> Result<ApproveOutcome, rustango::sql::ExecError> {
694    use rustango::sql::Auto;
695
696    let state_id = state.id.get().copied().unwrap_or_default();
697    let current_task_id = state.current_task_id.unwrap_or_default();
698    let now = Utc::now();
699
700    // A state whose current task isn't in this workflow (finished, or
701    // the task was removed) has no step to approve; a fallback position
702    // would restart it from the first task (#770).
703    let Some(current_sort) = tasks
704        .iter()
705        .find(|t| t.id.get().copied() == Some(current_task_id))
706        .map(|t| t.sort_order)
707    else {
708        return Ok(ApproveOutcome::AlreadyDecided);
709    };
710
711    // Claim the in-flight TaskState. Only the request that flips it goes
712    // on to advance; a second approve of the same step (or one racing
713    // it) must not advance again and approve the next step unreviewed.
714    if !claim_task(pool, state_id, current_task_id, TaskStatus::Approved, decided_by, comment).await? {
715        return Ok(ApproveOutcome::AlreadyDecided);
716    }
717
718    // Find the next task (sort_order > current).
719    let next = tasks
720        .iter()
721        .filter(|t| t.sort_order > current_sort)
722        .min_by_key(|t| t.sort_order);
723
724    if let Some(next_task) = next {
725        let next_id = next_task.id.get().copied().unwrap_or_default();
726        state.current_task_id = Some(next_id);
727        state.status = WorkflowStatus::InProgress.as_str().to_owned();
728        // #73 — save_partial (not save) so the unchanged
729        // `requested_by -> rustango_users` FK is not re-bound/re-validated;
730        // a full-row UPDATE 787s on SQLite when the original submitter's
731        // user row is gone (deleted / deactivated-and-purged).
732        state
733            .save_partial(&["status", "current_task_id", "finished_at"], pool)
734            .await?;
735
736        let mut ts = TaskState {
737            id: Auto::Unset,
738            workflow_state_id: state_id,
739            task_id: next_id,
740            status: TaskStatus::InProgress.as_str().to_owned(),
741            comment: String::new(),
742            decided_by: None,
743            decided_at: None,
744        };
745        ts.insert(pool).await?;
746
747        // #191 — if the next task is an auto-approve kind (or chain
748        // of them), advance through them right now. The final state
749        // is either a human-required task or workflow Finished.
750        advance_through_auto_approve_chain(pool, state, tasks, state.page_id, decided_by).await?;
751        if state.status == WorkflowStatus::Approved.as_str() {
752            Ok(ApproveOutcome::Finished)
753        } else if let Some(advanced_id) = state.current_task_id {
754            Ok(ApproveOutcome::Advanced {
755                next_task_id: advanced_id,
756            })
757        } else {
758            Ok(ApproveOutcome::Finished)
759        }
760    } else {
761        state.current_task_id = None;
762        state.status = WorkflowStatus::Approved.as_str().to_owned();
763        state.finished_at = Some(now);
764        // #73 — save_partial (not save) so the unchanged
765        // `requested_by -> rustango_users` FK is not re-bound/re-validated;
766        // a full-row UPDATE 787s on SQLite when the original submitter's
767        // user row is gone (deleted / deactivated-and-purged).
768        state
769            .save_partial(&["status", "current_task_id", "finished_at"], pool)
770            .await?;
771        Ok(ApproveOutcome::Finished)
772    }
773}
774
775/// Reject the current task. Flips the `TaskState` to Rejected and
776/// the `WorkflowState` to NeedsChanges. The submitter can edit and
777/// re-submit; the workflow restarts from the first task on next
778/// submit. Returns `false`, changing nothing, when the step was already
779/// decided.
780///
781/// # Errors
782/// Driver / query failures.
783pub async fn reject_current(
784    pool: &rustango::sql::Pool,
785    state: &mut WorkflowState,
786    decided_by: i64,
787    comment: &str,
788) -> Result<bool, rustango::sql::ExecError> {
789    let state_id = state.id.get().copied().unwrap_or_default();
790    let current_task_id = state.current_task_id.unwrap_or_default();
791    let now = Utc::now();
792
793    // #707 — as in approve_current: only the request that decides the
794    // step changes the workflow.
795    if !claim_task(pool, state_id, current_task_id, TaskStatus::Rejected, decided_by, comment).await? {
796        return Ok(false);
797    }
798
799    state.status = WorkflowStatus::NeedsChanges.as_str().to_owned();
800    state.finished_at = Some(now);
801    // #73 — save_partial (not save): see approve_current; avoids
802    // re-validating the unchanged `requested_by -> rustango_users` FK.
803    state
804        .save_partial(&["status", "current_task_id", "finished_at"], pool)
805        .await?;
806    Ok(true)
807}
808
809/// Cancel an in-flight workflow. Marks the `WorkflowState` Cancelled
810/// and any in-progress `TaskState` Skipped. Used when an editor
811/// pulls the page out of review entirely.
812///
813/// Returns `false`, changing nothing, when the step was already decided.
814///
815/// # Errors
816/// Driver / query failures.
817pub async fn cancel(
818    pool: &rustango::sql::Pool,
819    state: &mut WorkflowState,
820    decided_by: i64,
821) -> Result<(), rustango::sql::ExecError> {
822    use rustango::core::Column as _;
823    use rustango::sql::FetcherPool as _;
824
825    let state_id = state.id.get().copied().unwrap_or_default();
826    let now = Utc::now();
827
828    let inflight: Vec<TaskState> = TaskState::objects()
829        .where_(TaskState::workflow_state_id.eq(state_id))
830        .where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
831        .fetch(pool)
832        .await?;
833    for mut ts in inflight {
834        ts.status = TaskStatus::Skipped.as_str().to_owned();
835        ts.decided_by = Some(decided_by);
836        ts.decided_at = Some(now);
837        ts.save(pool).await?;
838    }
839
840    state.status = WorkflowStatus::Cancelled.as_str().to_owned();
841    state.finished_at = Some(now);
842    state.current_task_id = None;
843    // #73 — save_partial (not save): see approve_current; avoids
844    // re-validating the unchanged `requested_by -> rustango_users` FK.
845    state
846        .save_partial(&["status", "current_task_id", "finished_at"], pool)
847        .await?;
848    // A change held for this review is dropped with it.
849    crate::pending_change::discard(pool, state.page_id).await?;
850    Ok(())
851}
852
853/// True when this page has been through a workflow that finished
854/// approved (i.e. it's a published-via-workflow page). Editors with
855/// `Workflow.require_reapproval_on_edit` set use this signal to
856/// decide whether the next edit kicks off a new review cycle.
857///
858/// # Errors
859/// Driver / query failures.
860pub async fn has_prior_approval(
861    pool: &rustango::sql::Pool,
862    page_id: i64,
863) -> Result<bool, rustango::sql::ExecError> {
864    use rustango::core::Column as _;
865    use rustango::sql::FetcherPool as _;
866
867    let rows: Vec<WorkflowState> = WorkflowState::objects()
868        .where_(WorkflowState::page_id.eq(page_id))
869        .where_(WorkflowState::status.eq(WorkflowStatus::Approved.as_str().to_owned()))
870        .fetch(pool)
871        .await?;
872    Ok(!rows.is_empty())
873}
874