feat(ai): Copilot 基因化 Phase 0 Task 1-4 — 迁移 + Entity + 规则引擎
- 4 表迁移: copilot_rules, copilot_insights, copilot_risk_snapshots, copilot_chat_logs - 4 个 SeaORM Entity 对应新表 - JSONLogic 规则引擎 (evaluate + evaluate_rules) + 5 个单元测试
This commit is contained in:
1
crates/erp-ai/src/copilot/mod.rs
Normal file
1
crates/erp-ai/src/copilot/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod rules;
|
||||
201
crates/erp-ai/src/copilot/rules.rs
Normal file
201
crates/erp-ai/src/copilot/rules.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
use serde_json::Value;
|
||||
|
||||
/// 评估 JSONLogic 表达式,支持子集:> >= < <= == != and or ! in var
|
||||
/// 对畸形规则表达式返回 false 而非 panic(规则存储在数据库中,不应导致服务崩溃)
|
||||
pub fn evaluate(expr: &Value, data: &Value) -> bool {
|
||||
match expr {
|
||||
Value::Object(map) => {
|
||||
if let Some(op) = map.get(">") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return compare_f64(&a, &b) == std::cmp::Ordering::Greater;
|
||||
}
|
||||
if let Some(op) = map.get(">=") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return matches!(
|
||||
compare_f64(&a, &b),
|
||||
std::cmp::Ordering::Greater | std::cmp::Ordering::Equal
|
||||
);
|
||||
}
|
||||
if let Some(op) = map.get("<") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return compare_f64(&a, &b) == std::cmp::Ordering::Less;
|
||||
}
|
||||
if let Some(op) = map.get("<=") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return matches!(
|
||||
compare_f64(&a, &b),
|
||||
std::cmp::Ordering::Less | std::cmp::Ordering::Equal
|
||||
);
|
||||
}
|
||||
if let Some(op) = map.get("==") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return a == b;
|
||||
}
|
||||
if let Some(op) = map.get("!=") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let a = resolve_value(&args[0], data);
|
||||
let b = resolve_value(&args[1], data);
|
||||
return a != b;
|
||||
}
|
||||
if let Some(op) = map.get("and") {
|
||||
return match op.as_array() {
|
||||
Some(arr) => arr.iter().all(|e| evaluate(e, data)),
|
||||
None => false,
|
||||
};
|
||||
}
|
||||
if let Some(op) = map.get("or") {
|
||||
return match op.as_array() {
|
||||
Some(arr) => arr.iter().any(|e| evaluate(e, data)),
|
||||
None => false,
|
||||
};
|
||||
}
|
||||
if let Some(op) = map.get("!") {
|
||||
return !evaluate(op, data);
|
||||
}
|
||||
if let Some(op) = map.get("in") {
|
||||
let args = match op.as_array() {
|
||||
Some(a) if a.len() == 2 => a,
|
||||
_ => return false,
|
||||
};
|
||||
let val = resolve_value(&args[0], data);
|
||||
let collection = resolve_value(&args[1], data);
|
||||
return match collection.as_array() {
|
||||
Some(arr) => arr.contains(&val),
|
||||
None => false,
|
||||
};
|
||||
}
|
||||
false
|
||||
}
|
||||
Value::Bool(b) => *b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析 {"var": "path.to.field"} 引用,支持点分路径
|
||||
fn resolve_value(expr: &Value, data: &Value) -> Value {
|
||||
if let Value::Object(map) = expr
|
||||
&& let Some(var_path) = map.get("var").and_then(|v| v.as_str())
|
||||
{
|
||||
return var_path.split('.').fold(data.clone(), |acc, key| {
|
||||
acc.get(key).cloned().unwrap_or(Value::Null)
|
||||
});
|
||||
}
|
||||
expr.clone()
|
||||
}
|
||||
|
||||
fn compare_f64(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
let a_num = value_to_f64(a);
|
||||
let b_num = value_to_f64(b);
|
||||
a_num
|
||||
.partial_cmp(&b_num)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
fn value_to_f64(v: &Value) -> f64 {
|
||||
v.as_f64()
|
||||
.or_else(|| v.as_i64().map(|n| n as f64))
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// 规则数据:(id, name, condition_expr, score, severity, suggestion)
|
||||
pub type RuleData = (
|
||||
uuid::Uuid,
|
||||
String,
|
||||
serde_json::Value,
|
||||
i16,
|
||||
String,
|
||||
Option<String>,
|
||||
);
|
||||
|
||||
/// 匹配结果:(id, name, score, severity, suggestion)
|
||||
pub type MatchedRuleData = (uuid::Uuid, String, i16, String, Option<String>);
|
||||
|
||||
/// 对患者数据评估所有启用的规则,返回匹配的规则和总分
|
||||
pub fn evaluate_rules(rules: &[RuleData], patient_data: &Value) -> Vec<MatchedRuleData> {
|
||||
rules
|
||||
.iter()
|
||||
.filter(|(_, _, cond, _, _, _)| evaluate(cond, patient_data))
|
||||
.map(|(id, name, _, score, severity, suggestion)| {
|
||||
(
|
||||
*id,
|
||||
name.clone(),
|
||||
*score,
|
||||
severity.clone(),
|
||||
suggestion.clone(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_simple_comparison_gt() {
|
||||
let expr = serde_json::json!({ ">": [{"var": "systolic"}, 140] });
|
||||
let data = serde_json::json!({"systolic": 155});
|
||||
assert!(evaluate(&expr, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simple_comparison_lt() {
|
||||
let expr = serde_json::json!({ "<": [{"var": "egfr"}, 60] });
|
||||
let data = serde_json::json!({"egfr": 45});
|
||||
assert!(evaluate(&expr, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_and_combination() {
|
||||
let expr = serde_json::json!({
|
||||
"and": [
|
||||
{ ">=": [{"var": "systolic.prev1"}, 140] },
|
||||
{ ">=": [{"var": "systolic.prev2"}, 140] }
|
||||
]
|
||||
});
|
||||
let data = serde_json::json!({"systolic": {"prev1": 145, "prev2": 150}});
|
||||
assert!(evaluate(&expr, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_change_pct() {
|
||||
let expr = serde_json::json!({ ">": [{"var": "creatinine.change_pct"}, 20] });
|
||||
let data = serde_json::json!({"creatinine": {"change_pct": 25}});
|
||||
assert!(evaluate(&expr, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_matching() {
|
||||
let expr = serde_json::json!({ "<": [{"var": "egfr"}, 60] });
|
||||
let data = serde_json::json!({"egfr": 75});
|
||||
assert!(!evaluate(&expr, &data));
|
||||
}
|
||||
}
|
||||
31
crates/erp-ai/src/entity/copilot_chat_logs.rs
Normal file
31
crates/erp-ai/src/entity/copilot_chat_logs.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "copilot_chat_logs")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
pub user_message: String,
|
||||
pub intent_classification: Option<String>,
|
||||
pub ai_raw_response: Option<String>,
|
||||
pub layer1_result: Option<serde_json::Value>,
|
||||
pub layer2_result: Option<serde_json::Value>,
|
||||
pub violations_found: Option<serde_json::Value>,
|
||||
pub fix_strategy: Option<String>,
|
||||
pub final_response: String,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
pub created_by: Option<Uuid>,
|
||||
pub updated_by: Option<Uuid>,
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
pub version_lock: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
32
crates/erp-ai/src/entity/copilot_insights.rs
Normal file
32
crates/erp-ai/src/entity/copilot_insights.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "copilot_insights")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
pub insight_type: String,
|
||||
pub source: String,
|
||||
pub severity: Option<String>,
|
||||
pub title: String,
|
||||
pub content: serde_json::Value,
|
||||
pub rule_matches: Option<serde_json::Value>,
|
||||
pub llm_supplement: Option<String>,
|
||||
pub expires_at: DateTimeUtc,
|
||||
pub is_read: bool,
|
||||
pub is_dismissed: bool,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
pub created_by: Option<Uuid>,
|
||||
pub updated_by: Option<Uuid>,
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
pub version_lock: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
28
crates/erp-ai/src/entity/copilot_risk_snapshots.rs
Normal file
28
crates/erp-ai/src/entity/copilot_risk_snapshots.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "copilot_risk_snapshots")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub patient_id: Uuid,
|
||||
pub risk_score: i16,
|
||||
pub risk_level: String,
|
||||
pub rule_details: serde_json::Value,
|
||||
pub llm_summary: Option<String>,
|
||||
pub computed_at: DateTimeUtc,
|
||||
pub data_freshness: Option<serde_json::Value>,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
pub created_by: Option<Uuid>,
|
||||
pub updated_by: Option<Uuid>,
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
pub version_lock: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
29
crates/erp-ai/src/entity/copilot_rules.rs
Normal file
29
crates/erp-ai/src/entity/copilot_rules.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "copilot_rules")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub tenant_id: Uuid,
|
||||
pub name: String,
|
||||
pub category: String,
|
||||
pub condition_expr: serde_json::Value,
|
||||
pub score: i16,
|
||||
pub severity: String,
|
||||
pub suggestion: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub sort_order: i32,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
pub created_by: Option<Uuid>,
|
||||
pub updated_by: Option<Uuid>,
|
||||
pub deleted_at: Option<DateTimeUtc>,
|
||||
pub version_lock: i32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
@@ -8,3 +8,7 @@ pub mod ai_risk_threshold;
|
||||
pub mod ai_suggestion;
|
||||
pub mod ai_tenant_config;
|
||||
pub mod ai_usage;
|
||||
pub mod copilot_chat_logs;
|
||||
pub mod copilot_insights;
|
||||
pub mod copilot_risk_snapshots;
|
||||
pub mod copilot_rules;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod config;
|
||||
pub mod copilot;
|
||||
pub mod dto;
|
||||
pub mod entity;
|
||||
pub mod error;
|
||||
|
||||
Reference in New Issue
Block a user