- ActionInboxService 新增 get_workbench_stats 和 get_team_overview - Handler 新增 /health/action-inbox/stats 和 /team 端点 - 注册 health.action-inbox.team 权限码
539 lines
17 KiB
Rust
539 lines
17 KiB
Rust
use chrono::{DateTime, Utc};
|
|
use erp_core::types::PaginatedResponse;
|
|
use sea_orm::{DatabaseBackend, DatabaseConnection, FromQueryResult, Statement};
|
|
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
|
|
use crate::error::HealthError;
|
|
|
|
// ── DTO ──────────────────────────────────────────────────────────────
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum ActionType {
|
|
AiSuggestion,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum ActionPriority {
|
|
Urgent,
|
|
High,
|
|
Medium,
|
|
Low,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum ActionStatus {
|
|
Pending,
|
|
InProgress,
|
|
Completed,
|
|
Dismissed,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct ActionItem {
|
|
pub id: String,
|
|
pub action_type: ActionType,
|
|
pub priority: ActionPriority,
|
|
pub status: ActionStatus,
|
|
pub title: String,
|
|
pub summary: String,
|
|
pub patient_id: Uuid,
|
|
pub patient_name: String,
|
|
pub source_ref: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct ThreadEvent {
|
|
pub step: String,
|
|
pub label: String,
|
|
pub status: ActionStatus,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub detail: Option<String>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub timestamp: Option<DateTime<Utc>>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub operator: Option<String>,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub link_to: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct ActionDefinition {
|
|
pub key: String,
|
|
pub label: String,
|
|
pub variant: String,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub api_endpoint: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct ThreadResponse {
|
|
pub action_item: ActionItem,
|
|
pub thread: Vec<ThreadEvent>,
|
|
pub available_actions: Vec<ActionDefinition>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct ActionInboxQuery {
|
|
pub status: Option<String>,
|
|
#[serde(rename = "type")]
|
|
pub action_type: Option<String>,
|
|
pub page: Option<u64>,
|
|
pub page_size: Option<u64>,
|
|
}
|
|
|
|
// ── 内部查询结构体 ──────────────────────────────────────────────────
|
|
|
|
#[derive(Debug, FromQueryResult)]
|
|
struct ActionItemRow {
|
|
id: Uuid,
|
|
suggestion_type: String,
|
|
risk_level: String,
|
|
status: String,
|
|
params: Option<serde_json::Value>,
|
|
created_at: DateTime<Utc>,
|
|
updated_at: DateTime<Utc>,
|
|
patient_id: Uuid,
|
|
patient_name: String,
|
|
result_content: Option<String>,
|
|
_analysis_id: Uuid,
|
|
}
|
|
|
|
#[derive(Debug, FromQueryResult)]
|
|
struct CountRow {
|
|
cnt: i64,
|
|
}
|
|
|
|
#[derive(Debug, FromQueryResult)]
|
|
struct SuggestionDetail {
|
|
id: Uuid,
|
|
suggestion_type: String,
|
|
risk_level: String,
|
|
status: String,
|
|
params: Option<serde_json::Value>,
|
|
workflow_instance_id: Option<Uuid>,
|
|
reanalysis_id: Option<Uuid>,
|
|
created_at: DateTime<Utc>,
|
|
updated_at: DateTime<Utc>,
|
|
_analysis_id: Uuid,
|
|
patient_id: Uuid,
|
|
patient_name: String,
|
|
result_content: Option<String>,
|
|
analysis_created_at: DateTime<Utc>,
|
|
}
|
|
|
|
// ── 辅助函数 ────────────────────────────────────────────────────────
|
|
|
|
fn risk_to_priority(risk: &str) -> ActionPriority {
|
|
match risk {
|
|
"high" => ActionPriority::Urgent,
|
|
"medium" => ActionPriority::High,
|
|
"low" => ActionPriority::Medium,
|
|
_ => ActionPriority::Low,
|
|
}
|
|
}
|
|
|
|
fn suggestion_status_to_action(status: &str) -> ActionStatus {
|
|
match status {
|
|
"pending" => ActionStatus::Pending,
|
|
"approved" => ActionStatus::InProgress,
|
|
"executed" => ActionStatus::Completed,
|
|
_ => ActionStatus::Dismissed, // rejected, expired, parse_failed
|
|
}
|
|
}
|
|
|
|
fn suggestion_type_to_title(suggestion_type: &str) -> String {
|
|
match suggestion_type {
|
|
"followup" => "建议安排随访".into(),
|
|
"appointment" => "建议预约复查".into(),
|
|
"alert" => "建议关注指标异常".into(),
|
|
_ => "AI 健康建议".into(),
|
|
}
|
|
}
|
|
|
|
fn extract_title(params: &Option<serde_json::Value>, suggestion_type: &str) -> String {
|
|
params
|
|
.as_ref()
|
|
.and_then(|p| p.get("reason"))
|
|
.and_then(|v| v.as_str())
|
|
.map(|s| s.to_string())
|
|
.unwrap_or_else(|| suggestion_type_to_title(suggestion_type))
|
|
}
|
|
|
|
// ── 公开 API ────────────────────────────────────────────────────────
|
|
|
|
pub async fn list_action_items(
|
|
db: &DatabaseConnection,
|
|
tenant_id: Uuid,
|
|
query: &ActionInboxQuery,
|
|
) -> Result<PaginatedResponse<ActionItem>, HealthError> {
|
|
let page = query.page.unwrap_or(1).max(1);
|
|
let page_size = query.page_size.unwrap_or(20).min(100);
|
|
let offset = (page - 1) * page_size;
|
|
|
|
let status_filter = match query.status.as_deref() {
|
|
Some("pending") => "AND s.status = 'pending'",
|
|
Some("in_progress") => "AND s.status = 'approved'",
|
|
Some("completed") => "AND s.status = 'executed'",
|
|
Some("dismissed") => "AND s.status IN ('rejected', 'expired', 'parse_failed')",
|
|
_ => "",
|
|
};
|
|
|
|
let data_sql = format!(
|
|
r#"
|
|
SELECT s.id, s.suggestion_type, s.risk_level, s.status, s.params,
|
|
s.created_at, s.updated_at,
|
|
a.patient_id, p.name AS patient_name,
|
|
a.result_content, a.id AS analysis_id
|
|
FROM ai_suggestion s
|
|
JOIN ai_analysis a ON s.analysis_id = a.id
|
|
JOIN patient p ON a.patient_id = p.id
|
|
WHERE s.tenant_id = $1
|
|
AND s.deleted_at IS NULL
|
|
{status_filter}
|
|
ORDER BY
|
|
CASE s.risk_level WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
|
|
s.created_at DESC
|
|
LIMIT $2 OFFSET $3
|
|
"#
|
|
);
|
|
|
|
let rows: Vec<ActionItemRow> = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(
|
|
DatabaseBackend::Postgres,
|
|
data_sql,
|
|
[
|
|
tenant_id.into(),
|
|
(page_size as i64).into(),
|
|
(offset as i64).into(),
|
|
],
|
|
),
|
|
)
|
|
.all(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?;
|
|
|
|
let count_sql = format!(
|
|
r#"
|
|
SELECT COUNT(*) AS cnt
|
|
FROM ai_suggestion s
|
|
JOIN ai_analysis a ON s.analysis_id = a.id
|
|
WHERE s.tenant_id = $1
|
|
AND s.deleted_at IS NULL
|
|
{status_filter}
|
|
"#
|
|
);
|
|
|
|
let count_row: Option<CountRow> = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(DatabaseBackend::Postgres, count_sql, [tenant_id.into()]),
|
|
)
|
|
.one(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?;
|
|
|
|
let total = count_row.map(|r| r.cnt).unwrap_or(0) as u64;
|
|
|
|
let items: Vec<ActionItem> = rows
|
|
.into_iter()
|
|
.map(|r| ActionItem {
|
|
id: format!("ai_suggestion:{}", r.id),
|
|
action_type: ActionType::AiSuggestion,
|
|
priority: risk_to_priority(&r.risk_level),
|
|
status: suggestion_status_to_action(&r.status),
|
|
title: extract_title(&r.params, &r.suggestion_type),
|
|
summary: r.result_content.unwrap_or_default().chars().take(100).collect(),
|
|
patient_id: r.patient_id,
|
|
patient_name: r.patient_name,
|
|
source_ref: r.id.to_string(),
|
|
created_at: r.created_at,
|
|
updated_at: r.updated_at,
|
|
})
|
|
.collect();
|
|
|
|
Ok(PaginatedResponse {
|
|
data: items,
|
|
total,
|
|
page,
|
|
page_size,
|
|
total_pages: if page_size > 0 { (total + page_size - 1) / page_size } else { 0 },
|
|
})
|
|
}
|
|
|
|
pub async fn get_action_thread(
|
|
db: &DatabaseConnection,
|
|
tenant_id: Uuid,
|
|
source_ref: &str,
|
|
) -> Result<Option<ThreadResponse>, HealthError> {
|
|
let suggestion_id = source_ref
|
|
.strip_prefix("ai_suggestion:")
|
|
.ok_or_else(|| HealthError::Validation("无效的 source_ref 格式".into()))?;
|
|
let uuid = Uuid::parse_str(suggestion_id)
|
|
.map_err(|e| HealthError::Validation(format!("无效的 UUID: {e}")))?;
|
|
|
|
let detail: Option<SuggestionDetail> = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(
|
|
DatabaseBackend::Postgres,
|
|
r#"
|
|
SELECT s.id, s.suggestion_type, s.risk_level, s.status, s.params,
|
|
s.workflow_instance_id, s.reanalysis_id,
|
|
s.created_at, s.updated_at,
|
|
s.analysis_id, a.patient_id, p.name AS patient_name,
|
|
a.result_content, a.created_at AS analysis_created_at
|
|
FROM ai_suggestion s
|
|
JOIN ai_analysis a ON s.analysis_id = a.id
|
|
JOIN patient p ON a.patient_id = p.id
|
|
WHERE s.id = $1 AND s.tenant_id = $2 AND s.deleted_at IS NULL
|
|
"#,
|
|
[uuid.into(), tenant_id.into()],
|
|
),
|
|
)
|
|
.one(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?;
|
|
|
|
let detail = match detail {
|
|
Some(d) => d,
|
|
None => return Ok(None),
|
|
};
|
|
|
|
let action_status = suggestion_status_to_action(&detail.status);
|
|
|
|
// ── 拼装线程时间线 ──
|
|
let mut thread = Vec::new();
|
|
|
|
// Step 1: AI 分析完成
|
|
thread.push(ThreadEvent {
|
|
step: "ai_analysis".into(),
|
|
label: "AI 分析完成".into(),
|
|
status: ActionStatus::Completed,
|
|
detail: None,
|
|
timestamp: Some(detail.analysis_created_at),
|
|
operator: None,
|
|
link_to: Some("/health/ai-analysis".into()),
|
|
});
|
|
|
|
// Step 2: 医生审批
|
|
let approval_status = match detail.status.as_str() {
|
|
"approved" | "executed" => ActionStatus::Completed,
|
|
"rejected" => ActionStatus::Dismissed,
|
|
_ => ActionStatus::InProgress,
|
|
};
|
|
let is_terminal = matches!(approval_status, ActionStatus::Completed | ActionStatus::Dismissed);
|
|
thread.push(ThreadEvent {
|
|
step: "doctor_approval".into(),
|
|
label: "医生审批".into(),
|
|
status: approval_status,
|
|
detail: None,
|
|
timestamp: if is_terminal {
|
|
Some(detail.updated_at)
|
|
} else {
|
|
None
|
|
},
|
|
operator: None,
|
|
link_to: None,
|
|
});
|
|
|
|
// Step 3: 执行安排
|
|
let has_workflow = detail.workflow_instance_id.is_some();
|
|
if has_workflow || detail.status == "approved" || detail.status == "executed" {
|
|
thread.push(ThreadEvent {
|
|
step: "action_dispatched".into(),
|
|
label: "执行安排".into(),
|
|
status: if has_workflow {
|
|
ActionStatus::Completed
|
|
} else {
|
|
ActionStatus::Pending
|
|
},
|
|
detail: None,
|
|
timestamp: None,
|
|
operator: None,
|
|
link_to: None,
|
|
});
|
|
}
|
|
|
|
// Step 4: 再分析对比
|
|
if detail.reanalysis_id.is_some() || detail.status == "executed" {
|
|
thread.push(ThreadEvent {
|
|
step: "reanalysis".into(),
|
|
label: "前后对比".into(),
|
|
status: if detail.reanalysis_id.is_some() {
|
|
ActionStatus::Completed
|
|
} else {
|
|
ActionStatus::Pending
|
|
},
|
|
detail: None,
|
|
timestamp: None,
|
|
operator: None,
|
|
link_to: detail.reanalysis_id.map(|id| format!("/health/ai-analysis/{id}")),
|
|
});
|
|
}
|
|
|
|
// ── 动态操作按钮 ──
|
|
let available_actions = match detail.status.as_str() {
|
|
"pending" => vec![
|
|
ActionDefinition {
|
|
key: "approve".into(),
|
|
label: "批准并执行".into(),
|
|
variant: "primary".into(),
|
|
api_endpoint: Some(format!("/api/v1/ai/suggestions/{}/approve", detail.id)),
|
|
},
|
|
ActionDefinition {
|
|
key: "reject".into(),
|
|
label: "拒绝".into(),
|
|
variant: "danger".into(),
|
|
api_endpoint: Some(format!("/api/v1/ai/suggestions/{}/approve", detail.id)),
|
|
},
|
|
],
|
|
"approved" => vec![ActionDefinition {
|
|
key: "acknowledge".into(),
|
|
label: "标记已知悉".into(),
|
|
variant: "default".into(),
|
|
api_endpoint: None,
|
|
}],
|
|
"executed" => vec![ActionDefinition {
|
|
key: "view_comparison".into(),
|
|
label: "查看前后对比".into(),
|
|
variant: "primary".into(),
|
|
api_endpoint: Some(format!(
|
|
"/api/v1/ai/suggestions/{}/comparison",
|
|
detail.id
|
|
)),
|
|
}],
|
|
_ => vec![],
|
|
};
|
|
|
|
let action_item = ActionItem {
|
|
id: format!("ai_suggestion:{}", detail.id),
|
|
action_type: ActionType::AiSuggestion,
|
|
priority: risk_to_priority(&detail.risk_level),
|
|
status: action_status,
|
|
title: extract_title(&detail.params, &detail.suggestion_type),
|
|
summary: detail
|
|
.result_content
|
|
.unwrap_or_default()
|
|
.chars()
|
|
.take(100)
|
|
.collect(),
|
|
patient_id: detail.patient_id,
|
|
patient_name: detail.patient_name,
|
|
source_ref: detail.id.to_string(),
|
|
created_at: detail.created_at,
|
|
updated_at: detail.updated_at,
|
|
};
|
|
|
|
Ok(Some(ThreadResponse {
|
|
action_item,
|
|
thread,
|
|
available_actions,
|
|
}))
|
|
}
|
|
|
|
// ── 工作台统计 ──────────────────────────────────────────────────────
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct WorkbenchStats {
|
|
pub total_pending: u64,
|
|
pub ai_suggestion_pending: u64,
|
|
pub urgent_alerts: u64,
|
|
pub followup_due: u64,
|
|
pub completion_rate: Option<f64>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct TeamMemberOverview {
|
|
pub user_id: Uuid,
|
|
pub name: String,
|
|
pub title: String,
|
|
pub pending_count: u64,
|
|
pub completed_count: u64,
|
|
pub overdue_count: u64,
|
|
pub completion_rate: f64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct RiskDistribution {
|
|
pub high: u64,
|
|
pub medium: u64,
|
|
pub low: u64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct TeamOverview {
|
|
pub members: Vec<TeamMemberOverview>,
|
|
pub risk_distribution: RiskDistribution,
|
|
pub total_pending: u64,
|
|
pub total_completed: u64,
|
|
}
|
|
|
|
pub async fn get_workbench_stats(
|
|
db: &DatabaseConnection,
|
|
tenant_id: Uuid,
|
|
) -> Result<WorkbenchStats, HealthError> {
|
|
let ai_pending: i64 = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(
|
|
DatabaseBackend::Postgres,
|
|
"SELECT COUNT(*) AS cnt FROM ai_suggestion WHERE tenant_id = $1 AND status = 'pending' AND deleted_at IS NULL",
|
|
[tenant_id.into()],
|
|
),
|
|
)
|
|
.one(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?
|
|
.map(|r: CountRow| r.cnt)
|
|
.unwrap_or(0);
|
|
|
|
let urgent_alerts: i64 = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(
|
|
DatabaseBackend::Postgres,
|
|
"SELECT COUNT(*) AS cnt FROM alert WHERE tenant_id = $1 AND severity = 'urgent' AND status = 'active' AND deleted_at IS NULL",
|
|
[tenant_id.into()],
|
|
),
|
|
)
|
|
.one(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?
|
|
.map(|r: CountRow| r.cnt)
|
|
.unwrap_or(0);
|
|
|
|
let followup_due: i64 = FromQueryResult::find_by_statement(
|
|
Statement::from_sql_and_values(
|
|
DatabaseBackend::Postgres,
|
|
"SELECT COUNT(*) AS cnt FROM follow_up_plan WHERE tenant_id = $1 AND status = 'scheduled' AND next_date <= NOW() AND deleted_at IS NULL",
|
|
[tenant_id.into()],
|
|
),
|
|
)
|
|
.one(db)
|
|
.await
|
|
.map_err(|e| HealthError::DbError(e.to_string()))?
|
|
.map(|r: CountRow| r.cnt)
|
|
.unwrap_or(0);
|
|
|
|
let total_pending = (ai_pending + urgent_alerts + followup_due) as u64;
|
|
|
|
Ok(WorkbenchStats {
|
|
total_pending,
|
|
ai_suggestion_pending: ai_pending as u64,
|
|
urgent_alerts: urgent_alerts as u64,
|
|
followup_due: followup_due as u64,
|
|
completion_rate: None,
|
|
})
|
|
}
|
|
|
|
pub async fn get_team_overview(
|
|
db: &DatabaseConnection,
|
|
_tenant_id: Uuid,
|
|
) -> Result<TeamOverview, HealthError> {
|
|
// Phase 1: 返回空结构,待后续实现团队查询
|
|
Ok(TeamOverview {
|
|
members: vec![],
|
|
risk_distribution: RiskDistribution { high: 0, medium: 0, low: 0 },
|
|
total_pending: 0,
|
|
total_completed: 0,
|
|
})
|
|
}
|