231 lines
8.1 KiB
Rust
231 lines
8.1 KiB
Rust
//! Read-only approvals inbox and display metadata shared with order details.
|
|
use crate::{
|
|
auth::Principal,
|
|
jobs::Error,
|
|
pagination::{Cursor, PageQuery},
|
|
};
|
|
use axum::{
|
|
Json,
|
|
extract::{Query, State},
|
|
http::{HeaderMap, StatusCode},
|
|
};
|
|
use chrono::{DateTime, Utc};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Value, json};
|
|
use sqlx::{Postgres, Row, Transaction};
|
|
use std::collections::{BTreeMap, HashMap};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Clone, Copy, Default, Deserialize, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Status {
|
|
#[default]
|
|
Pending,
|
|
History,
|
|
}
|
|
|
|
#[derive(Default, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Filters {
|
|
tenant_id: Option<Uuid>,
|
|
#[serde(default)]
|
|
status: Status,
|
|
limit: Option<u16>,
|
|
cursor: Option<String>,
|
|
#[serde(default)]
|
|
count_only: bool,
|
|
}
|
|
|
|
pub(super) async fn summaries(
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
p: &Principal,
|
|
ids: &[Uuid],
|
|
) -> Result<HashMap<Uuid, Value>, Error> {
|
|
let inventory = p.permits_scope("inventory:read")
|
|
&& crate::permissions::allowed(tx, &p.name, "inventory:read").await?;
|
|
let rows = sqlx::query(include_str!("order_summary.sql"))
|
|
.bind(ids)
|
|
.bind(inventory)
|
|
.fetch_all(&mut **tx)
|
|
.await?;
|
|
let mut items = HashMap::with_capacity(rows.len());
|
|
for row in rows {
|
|
let action = row.get::<Option<String>, _>("action");
|
|
let revision = row.get::<Option<Value>, _>("script_revision");
|
|
let reason = row.get::<Option<String>, _>("reason");
|
|
let title = revision
|
|
.as_ref()
|
|
.and_then(|r| r["name"].as_str())
|
|
.or_else(|| reason.as_deref().filter(|s| !s.trim().is_empty()))
|
|
.unwrap_or("Auftrag");
|
|
let plan_id: Uuid = row.get("plan_id");
|
|
items.insert(plan_id, json!({
|
|
"title": title, "action": action, "reason": reason, "script_revision": revision,
|
|
"tenant_id":row.get::<Uuid,_>("tenant_id"), "customer_name":row.get::<String,_>("customer_name"),
|
|
"operation_id":row.get::<Option<Uuid>,_>("operation_id"), "plan_id":plan_id,
|
|
"plan_hash":row.get::<String,_>("plan_hash"), "requester":row.get::<String,_>("requester"),
|
|
"targets":row.get::<Value,_>("targets"), "created_at":row.get::<DateTime<Utc>,_>("created_at"),
|
|
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"), "approval_state":row.get::<Option<String>,_>("approval_state"),
|
|
"decision":row.get::<Option<Value>,_>("decision"),
|
|
}));
|
|
}
|
|
Ok(items)
|
|
}
|
|
|
|
pub(super) async fn summary(
|
|
tx: &mut Transaction<'_, Postgres>,
|
|
p: &Principal,
|
|
plan: Uuid,
|
|
) -> Result<Value, Error> {
|
|
summaries(tx, p, &[plan])
|
|
.await?
|
|
.remove(&plan)
|
|
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))
|
|
}
|
|
|
|
pub async fn inbox(
|
|
State(s): State<crate::State>,
|
|
h: HeaderMap,
|
|
Query(q): Query<Filters>,
|
|
) -> Result<Json<Value>, Error> {
|
|
let p = crate::jobs::principal(&s, &h, false).await?;
|
|
list(&s, &p, q).await.map(Json)
|
|
}
|
|
|
|
type Key = (DateTime<Utc>, Uuid, Uuid, Uuid); // created_at, tenant_id, operation_id, plan_id
|
|
|
|
async fn select_tenant(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
|
|
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
|
.bind(tenant.to_string())
|
|
.execute(&mut **tx)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn list(s: &crate::State, p: &Principal, q: Filters) -> Result<Value, Error> {
|
|
if p.session_hash.is_none() || !p.operator {
|
|
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
|
|
}
|
|
if q.tenant_id.is_some_and(|id| !p.tenants.contains(&id)) {
|
|
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
|
}
|
|
let mut tenants = p.tenants.clone();
|
|
tenants.sort_unstable();
|
|
tenants.dedup();
|
|
|
|
// Counts, page boundaries and rows must use the same memberships and
|
|
// approval states. Only switch the transaction to an authenticated tenant.
|
|
let mut tx = s.pool.begin().await?;
|
|
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
let mut permitted = Vec::new();
|
|
let mut customers = Vec::new();
|
|
for tenant in tenants {
|
|
select_tenant(&mut tx, tenant).await?;
|
|
if crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
|
|
&& crate::permissions::allowed(&mut tx, &p.name, "plans:approve").await?
|
|
{
|
|
let name: String = sqlx::query_scalar("SELECT name FROM tenants WHERE tenant_id=$1")
|
|
.bind(tenant)
|
|
.fetch_one(&mut *tx)
|
|
.await?;
|
|
customers.push(json!({"tenant_id":tenant, "name":name}));
|
|
permitted.push(tenant);
|
|
}
|
|
}
|
|
if q.tenant_id
|
|
.is_some_and(|tenant| !permitted.contains(&tenant))
|
|
{
|
|
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
|
}
|
|
let scope = format!(
|
|
"approvals:{}",
|
|
rmm_domain::jobs::hash(
|
|
json!([q.tenant_id, q.status, permitted])
|
|
.to_string()
|
|
.as_bytes()
|
|
)
|
|
);
|
|
let mut page = Cursor::parse(
|
|
s,
|
|
p,
|
|
&scope,
|
|
PageQuery {
|
|
cursor: q.cursor,
|
|
limit: q.limit,
|
|
},
|
|
)
|
|
.map_err(|s| Error(s, crate::auth::error_code(s)))?;
|
|
let cap = usize::from(page.limit);
|
|
let mut pending_count = 0i64;
|
|
let mut keys: Vec<Key> = Vec::new();
|
|
for tenant in permitted
|
|
.iter()
|
|
.copied()
|
|
.filter(|id| q.tenant_id.is_none_or(|t| t == *id))
|
|
{
|
|
select_tenant(&mut tx, tenant).await?;
|
|
pending_count += sqlx::query_scalar::<_,i64>(
|
|
"SELECT count(*) FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
|
WHERE r.created_at <= $1 AND r.approval_state='pending_approval' AND p.expires_at>now()"
|
|
).bind(page.as_of).fetch_one(&mut *tx).await?;
|
|
if q.count_only {
|
|
continue;
|
|
}
|
|
let rows:Vec<Key> = sqlx::query_as(
|
|
"SELECT r.created_at,r.tenant_id,r.operation_id,r.plan_id
|
|
FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
|
WHERE r.created_at <= $1 AND (r.approval_state='pending_approval' AND p.expires_at>now()) = $2
|
|
AND ($3::timestamptz IS NULL OR (r.created_at,r.tenant_id,r.operation_id)<($3,$4,$5))
|
|
ORDER BY r.created_at DESC,r.tenant_id DESC,r.operation_id DESC LIMIT $6"
|
|
).bind(page.as_of).bind(matches!(q.status,Status::Pending)).bind(page.last_created_at)
|
|
.bind(page.last_tenant).bind(page.last).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
|
keys.extend(rows);
|
|
keys.sort_unstable_by(|a, b| b.cmp(a));
|
|
keys.truncate(cap + 1);
|
|
}
|
|
let truncated = keys.len() > cap;
|
|
keys.truncate(cap);
|
|
let next = if truncated {
|
|
let (date, tenant, id, _) = keys[cap - 1];
|
|
page.last_tenant = Some(tenant);
|
|
page.last_created_at = Some(date);
|
|
Some(
|
|
page.next(s, id)
|
|
.map_err(|s| Error(s, crate::auth::error_code(s)))?,
|
|
)
|
|
} else {
|
|
None
|
|
};
|
|
let mut by_customer: BTreeMap<Uuid, Vec<Uuid>> = BTreeMap::new();
|
|
for (_, tenant, _, plan) in &keys {
|
|
by_customer.entry(*tenant).or_default().push(*plan);
|
|
}
|
|
let mut rows = HashMap::new();
|
|
for (tenant, ids) in by_customer {
|
|
select_tenant(&mut tx, tenant).await?;
|
|
rows.extend(
|
|
summaries(&mut tx, p, &ids)
|
|
.await?
|
|
.into_iter()
|
|
.map(|(id, row)| ((tenant, id), row)),
|
|
);
|
|
}
|
|
let mut items = Vec::with_capacity(keys.len());
|
|
for (_, tenant, _, plan) in keys {
|
|
items.push(rows.remove(&(tenant, plan)).ok_or(Error(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
"DEPENDENCY_UNAVAILABLE",
|
|
))?);
|
|
}
|
|
tx.commit().await?;
|
|
Ok(
|
|
json!({"items":items,"customers":customers,"can_review":!permitted.is_empty(),"pending_count":pending_count,"next_cursor":next,"as_of":page.as_of,
|
|
"truncated":truncated,"completeness":if truncated{"partial"}else{"complete"}}),
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|