use chrono::{DateTime, Utc};
use rustango::sql::Auto;
use rustango::Model;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowStatus {
InProgress,
Approved,
NeedsChanges,
Cancelled,
}
impl WorkflowStatus {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::InProgress => "in_progress",
Self::Approved => "approved",
Self::NeedsChanges => "needs_changes",
Self::Cancelled => "cancelled",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"in_progress" => Self::InProgress,
"approved" => Self::Approved,
"needs_changes" => Self::NeedsChanges,
"cancelled" => Self::Cancelled,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
InProgress,
Approved,
Rejected,
Skipped,
}
impl TaskStatus {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::InProgress => "in_progress",
Self::Approved => "approved",
Self::Rejected => "rejected",
Self::Skipped => "skipped",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"in_progress" => Self::InProgress,
"approved" => Self::Approved,
"rejected" => Self::Rejected,
"skipped" => Self::Skipped,
_ => return None,
})
}
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_workflow",
app = "cms",
display = "name",
admin(
list_display = "name, active, created_at",
ordering = "name",
list_filter = "active",
)
)]
pub struct Workflow {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(max_length = 100, index)]
pub name: String,
#[rustango(max_length = 255)]
pub description: String,
pub active: bool,
pub require_reapproval_on_edit: bool,
#[rustango(auto_now_add)]
pub created_at: Auto<DateTime<Utc>>,
#[rustango(auto_now)]
pub updated_at: Auto<DateTime<Utc>>,
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_workflow_task",
app = "cms",
display = "name",
admin(
list_display = "workflow_id, sort_order, name, role_id",
ordering = "workflow_id, sort_order",
list_filter = "workflow_id",
)
)]
pub struct WorkflowTask {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(fk = "cms_workflow", on = "id", index)]
pub workflow_id: i64,
#[rustango(max_length = 100)]
pub name: String,
#[rustango(fk = "rustango_roles", on = "id", index)]
pub role_id: i64,
pub sort_order: i32,
#[rustango(max_length = 64, default = "'group_approval'")]
pub kind: String,
#[rustango(max_length = 500, default = "''")]
pub webhook_url: String,
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_workflow_state",
app = "cms",
display = "page_id",
admin(
list_display = "page_id, workflow_id, status, current_task_id, requested_by, requested_at",
ordering = "-requested_at",
list_filter = "status, workflow_id",
)
)]
pub struct WorkflowState {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(fk = "cms_page", on = "id", index)]
pub page_id: i64,
#[rustango(fk = "cms_workflow", on = "id", index)]
pub workflow_id: i64,
#[rustango(max_length = 16, index)]
pub status: String,
pub current_task_id: Option<i64>,
#[rustango(fk = "rustango_users", on = "id", index)]
pub requested_by: i64,
#[rustango(auto_now_add)]
pub requested_at: Auto<DateTime<Utc>>,
pub finished_at: Option<DateTime<Utc>>,
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_task_state",
app = "cms",
display = "id",
admin(
list_display = "workflow_state_id, task_id, status, decided_by, decided_at",
ordering = "-decided_at",
list_filter = "status",
)
)]
pub struct TaskState {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(fk = "cms_workflow_state", on = "id", index)]
pub workflow_state_id: i64,
#[rustango(fk = "cms_workflow_task", on = "id", index)]
pub task_id: i64,
#[rustango(max_length = 16, index)]
pub status: String,
pub comment: String,
pub decided_by: Option<i64>,
pub decided_at: Option<DateTime<Utc>>,
}
pub async fn active_state_for_page(
pool: &rustango::sql::Pool,
page_id: i64,
) -> Result<Option<WorkflowState>, rustango::sql::ExecError> {
Ok(latest_state_for_page(pool, page_id).await?.filter(|st| {
st.status == WorkflowStatus::InProgress.as_str() || st.status == WorkflowStatus::NeedsChanges.as_str()
}))
}
pub async fn latest_state_for_page(
pool: &rustango::sql::Pool,
page_id: i64,
) -> Result<Option<WorkflowState>, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let rows: Vec<WorkflowState> = WorkflowState::objects()
.where_(WorkflowState::page_id.eq(page_id))
.order_by(&[("requested_at", true), ("id", true)]) .fetch(pool)
.await?;
Ok(rows.into_iter().next())
}
pub async fn history_for_page(
pool: &rustango::sql::Pool,
page_id: i64,
) -> Result<Vec<TaskState>, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let ids: Vec<i64> = WorkflowState::objects()
.where_(WorkflowState::page_id.eq(page_id))
.fetch(pool)
.await?
.into_iter()
.filter_map(|st| st.id.get().copied())
.collect();
if ids.is_empty() {
return Ok(Vec::new());
}
TaskState::objects()
.where_(TaskState::workflow_state_id.is_in(ids))
.order_by(&[("id", false)])
.fetch(pool)
.await
}
pub async fn find_by_name(
pool: &rustango::sql::Pool,
name: &str,
) -> Result<Option<Workflow>, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let rows: Vec<Workflow> = Workflow::objects()
.where_(Workflow::name.eq(name.to_owned()))
.where_(Workflow::active.eq(true))
.fetch(pool)
.await?;
Ok(rows.into_iter().next())
}
pub async fn review_workflow_for_type(
pool: &rustango::sql::Pool,
page_type_id: i64,
) -> Result<Option<Workflow>, rustango::sql::ExecError> {
use rustango::core::Column as _;
let Some(pt) = crate::page_type_model::PageType::objects()
.where_(crate::page_type_model::PageType::id.eq(page_type_id))
.first(pool)
.await?
else {
return Ok(None);
};
let Some(name) = pt.workflow_name() else {
return Ok(None);
};
let Some(wf) = find_by_name(pool, &name).await? else {
return Ok(None);
};
let has_steps = !tasks_for(pool, wf.id.get().copied().unwrap_or_default()).await?.is_empty();
Ok(has_steps.then_some(wf))
}
pub async fn page_types_using(
pool: &rustango::sql::Pool,
name: &str,
) -> Result<Vec<crate::page_type_model::PageType>, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
crate::page_type_model::PageType::objects()
.where_(crate::page_type_model::PageType::workflow.eq(name.to_owned()))
.fetch(pool)
.await
}
pub async fn rebind_page_types(
pool: &rustango::sql::Pool,
old: &str,
new: &str,
) -> Result<usize, rustango::sql::ExecError> {
let types = page_types_using(pool, old).await?;
let n = types.len();
for mut pt in types {
new.clone_into(&mut pt.workflow);
pt.save(pool).await?;
}
Ok(n)
}
pub async fn tasks_for(
pool: &rustango::sql::Pool,
workflow_id: i64,
) -> Result<Vec<WorkflowTask>, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
WorkflowTask::objects()
.where_(WorkflowTask::workflow_id.eq(workflow_id))
.order_by(&[("sort_order", false), ("id", false)])
.fetch(pool)
.await
}
pub async fn submit_for_review(
pool: &rustango::sql::Pool,
page_id: i64,
workflow: &Workflow,
tasks: &[WorkflowTask],
requested_by: i64,
) -> Result<WorkflowState, rustango::sql::ExecError> {
use rustango::sql::Auto;
let workflow_id = workflow.id.get().copied().unwrap_or_default();
let first_task_id = tasks.first().and_then(|t| t.id.get().copied());
let mut state = WorkflowState {
id: Auto::Unset,
page_id,
workflow_id,
status: WorkflowStatus::InProgress.as_str().to_owned(),
current_task_id: first_task_id,
requested_by,
requested_at: Auto::Unset,
finished_at: None,
};
state.insert(pool).await?;
if let Some(task_id) = first_task_id {
let state_id = state.id.get().copied().unwrap_or_default();
let mut ts = TaskState {
id: Auto::Unset,
workflow_state_id: state_id,
task_id,
status: TaskStatus::InProgress.as_str().to_owned(),
comment: String::new(),
decided_by: None,
decided_at: None,
};
ts.insert(pool).await?;
}
advance_through_auto_approve_chain(pool, &mut state, tasks, page_id, requested_by).await?;
Ok(state)
}
async fn advance_through_auto_approve_chain(
pool: &rustango::sql::Pool,
state: &mut WorkflowState,
tasks: &[WorkflowTask],
page_id: i64,
requested_by: i64,
) -> Result<(), rustango::sql::ExecError> {
use crate::page::Page;
use rustango::core::Column as _;
use rustango::sql::Auto;
let page: Page = match Page::objects()
.where_(Page::id.eq(page_id))
.first(pool)
.await?
{
Some(p) => p,
None => return Ok(()),
};
loop {
let Some(current_task_id) = state.current_task_id else {
return Ok(());
};
let Some(current_task) = tasks
.iter()
.find(|t| t.id.get().copied() == Some(current_task_id))
else {
return Ok(());
};
let kind = crate::task_kind::find(¤t_task.kind)
.unwrap_or_else(|| Box::new(crate::task_kind::GroupApprovalKind));
let ctx = crate::task_kind::AssignedTask {
task: current_task,
page: &page,
requested_by,
};
match kind.on_assign(&ctx) {
crate::task_kind::AssignOutcome::WaitForHuman => return Ok(()),
crate::task_kind::AssignOutcome::AutoApprove => {
let state_id = state.id.get().copied().unwrap_or_default();
let now = Utc::now();
if let Some(mut ts) = TaskState::objects()
.where_(TaskState::workflow_state_id.eq(state_id))
.where_(TaskState::task_id.eq(current_task_id))
.where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
.first(pool)
.await?
{
ts.status = TaskStatus::Approved.as_str().to_owned();
ts.decided_by = None;
ts.decided_at = Some(now);
ts.comment = format!("auto-approved by `{}` task kind", current_task.kind);
ts.save(pool).await?;
}
let current_sort = current_task.sort_order;
let next = tasks
.iter()
.filter(|t| t.sort_order > current_sort)
.min_by_key(|t| t.sort_order);
if let Some(next_task) = next {
let next_id = next_task.id.get().copied().unwrap_or_default();
state.current_task_id = Some(next_id);
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
let mut ts = TaskState {
id: Auto::Unset,
workflow_state_id: state_id,
task_id: next_id,
status: TaskStatus::InProgress.as_str().to_owned(),
comment: String::new(),
decided_by: None,
decided_at: None,
};
ts.insert(pool).await?;
} else {
state.current_task_id = None;
state.status = WorkflowStatus::Approved.as_str().to_owned();
state.finished_at = Some(now);
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
return Ok(());
}
}
}
}
}
#[derive(Debug, Clone)]
pub enum ApproveOutcome {
Advanced { next_task_id: i64 },
Finished,
AlreadyDecided,
}
async fn claim_task(
pool: &rustango::sql::Pool,
state_id: i64,
task_id: i64,
to: TaskStatus,
decided_by: i64,
comment: &str,
) -> Result<bool, rustango::sql::ExecError> {
use rustango::core::{Column as _, SqlValue};
use rustango::sql::UpdaterPool as _;
let changed = TaskState::objects()
.where_(TaskState::workflow_state_id.eq(state_id))
.where_(TaskState::task_id.eq(task_id))
.where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
.update()
.set("status", SqlValue::from(to.as_str()))
.set("decided_by", SqlValue::from(decided_by))
.set("decided_at", SqlValue::from(Utc::now()))
.set("comment", SqlValue::from(comment.to_owned()))
.execute_pool(pool)
.await?;
Ok(changed > 0)
}
pub async fn approve_current(
pool: &rustango::sql::Pool,
state: &mut WorkflowState,
tasks: &[WorkflowTask],
decided_by: i64,
comment: &str,
) -> Result<ApproveOutcome, rustango::sql::ExecError> {
use rustango::sql::Auto;
let state_id = state.id.get().copied().unwrap_or_default();
let current_task_id = state.current_task_id.unwrap_or_default();
let now = Utc::now();
let Some(current_sort) = tasks
.iter()
.find(|t| t.id.get().copied() == Some(current_task_id))
.map(|t| t.sort_order)
else {
return Ok(ApproveOutcome::AlreadyDecided);
};
if !claim_task(pool, state_id, current_task_id, TaskStatus::Approved, decided_by, comment).await? {
return Ok(ApproveOutcome::AlreadyDecided);
}
let next = tasks
.iter()
.filter(|t| t.sort_order > current_sort)
.min_by_key(|t| t.sort_order);
if let Some(next_task) = next {
let next_id = next_task.id.get().copied().unwrap_or_default();
state.current_task_id = Some(next_id);
state.status = WorkflowStatus::InProgress.as_str().to_owned();
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
let mut ts = TaskState {
id: Auto::Unset,
workflow_state_id: state_id,
task_id: next_id,
status: TaskStatus::InProgress.as_str().to_owned(),
comment: String::new(),
decided_by: None,
decided_at: None,
};
ts.insert(pool).await?;
advance_through_auto_approve_chain(pool, state, tasks, state.page_id, decided_by).await?;
if state.status == WorkflowStatus::Approved.as_str() {
Ok(ApproveOutcome::Finished)
} else if let Some(advanced_id) = state.current_task_id {
Ok(ApproveOutcome::Advanced {
next_task_id: advanced_id,
})
} else {
Ok(ApproveOutcome::Finished)
}
} else {
state.current_task_id = None;
state.status = WorkflowStatus::Approved.as_str().to_owned();
state.finished_at = Some(now);
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
Ok(ApproveOutcome::Finished)
}
}
pub async fn reject_current(
pool: &rustango::sql::Pool,
state: &mut WorkflowState,
decided_by: i64,
comment: &str,
) -> Result<bool, rustango::sql::ExecError> {
let state_id = state.id.get().copied().unwrap_or_default();
let current_task_id = state.current_task_id.unwrap_or_default();
let now = Utc::now();
if !claim_task(pool, state_id, current_task_id, TaskStatus::Rejected, decided_by, comment).await? {
return Ok(false);
}
state.status = WorkflowStatus::NeedsChanges.as_str().to_owned();
state.finished_at = Some(now);
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
Ok(true)
}
pub async fn cancel(
pool: &rustango::sql::Pool,
state: &mut WorkflowState,
decided_by: i64,
) -> Result<(), rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let state_id = state.id.get().copied().unwrap_or_default();
let now = Utc::now();
let inflight: Vec<TaskState> = TaskState::objects()
.where_(TaskState::workflow_state_id.eq(state_id))
.where_(TaskState::status.eq(TaskStatus::InProgress.as_str().to_owned()))
.fetch(pool)
.await?;
for mut ts in inflight {
ts.status = TaskStatus::Skipped.as_str().to_owned();
ts.decided_by = Some(decided_by);
ts.decided_at = Some(now);
ts.save(pool).await?;
}
state.status = WorkflowStatus::Cancelled.as_str().to_owned();
state.finished_at = Some(now);
state.current_task_id = None;
state
.save_partial(&["status", "current_task_id", "finished_at"], pool)
.await?;
crate::pending_change::discard(pool, state.page_id).await?;
Ok(())
}
pub async fn has_prior_approval(
pool: &rustango::sql::Pool,
page_id: i64,
) -> Result<bool, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let rows: Vec<WorkflowState> = WorkflowState::objects()
.where_(WorkflowState::page_id.eq(page_id))
.where_(WorkflowState::status.eq(WorkflowStatus::Approved.as_str().to_owned()))
.fetch(pool)
.await?;
Ok(!rows.is_empty())
}