| 1 | use axum::extract::{Path, Query, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::models::Role; |
| 6 | use utopia_core::AppError; |
| 7 | use uuid::Uuid; |
| 8 | |
| 9 | use crate::auth::AuthUser; |
| 10 | use crate::error::ApiResult; |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | pub(super) async fn require_kb( |
| 14 | state: &AppState, |
| 15 | user: &utopia_core::models::User, |
| 16 | kb_id: Uuid, |
| 17 | min: Role, |
| 18 | ) -> Result<utopia_core::models::KnowledgeBase, AppError> { |
| 19 | utopia_store::access::require_kb(&state.pool, user, kb_id, min).await |
| 20 | } |
| 21 | |
| 22 | /// `at`:可选 as-of 日期(YYYY-MM-DD 或 RFC3339)——服务端时间旅行。 |
| 23 | fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> { |
| 24 | let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else { |
| 25 | return Ok(None); |
| 26 | }; |
| 27 | if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") { |
| 28 | return Ok(Some(d.and_hms_opt(0, 0, 0).unwrap().and_utc())); |
| 29 | } |
| 30 | chrono::DateTime::parse_from_rfc3339(s) |
| 31 | .map(|t| Some(t.with_timezone(&chrono::Utc))) |
| 32 | .map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into())) |
| 33 | } |
| 34 | |
| 35 | #[derive(Deserialize)] |
| 36 | pub struct OverviewQuery { |
| 37 | #[serde(default)] |
| 38 | pub at: Option<String>, |
| 39 | } |
| 40 | |
| 41 | pub async fn overview( |
| 42 | State(state): State<AppState>, |
| 43 | AuthUser(user): AuthUser, |
| 44 | Path(kb_id): Path<Uuid>, |
| 45 | Query(q): Query<OverviewQuery>, |
| 46 | ) -> ApiResult<Json<serde_json::Value>> { |
| 47 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 48 | let at = parse_at(q.at.as_deref())?; |
| 49 | let (nodes, edges) = utopia_store::graph::overview(&state.pool, kb_id, 150, at).await?; |
| 50 | Ok(Json(json!({ "nodes": nodes, "edges": edges }))) |
| 51 | } |
| 52 | |
| 53 | #[derive(Deserialize)] |
| 54 | pub struct NeighborhoodQuery { |
| 55 | pub entity: Uuid, |
| 56 | #[serde(default)] |
| 57 | pub hops: Option<u8>, |
| 58 | #[serde(default)] |
| 59 | pub at: Option<String>, |
| 60 | } |
| 61 | |
| 62 | pub async fn neighborhood( |
| 63 | State(state): State<AppState>, |
| 64 | AuthUser(user): AuthUser, |
| 65 | Path(kb_id): Path<Uuid>, |
| 66 | Query(q): Query<NeighborhoodQuery>, |
| 67 | ) -> ApiResult<Json<serde_json::Value>> { |
| 68 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 69 | let at = parse_at(q.at.as_deref())?; |
| 70 | let (nodes, edges) = |
| 71 | utopia_store::graph::neighborhood(&state.pool, kb_id, q.entity, q.hops.unwrap_or(2), at) |
| 72 | .await?; |
| 73 | Ok(Json(json!({ "nodes": nodes, "edges": edges }))) |
| 74 | } |
| 75 | |
| 76 | #[derive(Deserialize)] |
| 77 | pub struct EntitySearchQuery { |
| 78 | pub q: String, |
| 79 | } |
| 80 | |
| 81 | pub async fn search_entities( |
| 82 | State(state): State<AppState>, |
| 83 | AuthUser(user): AuthUser, |
| 84 | Path(kb_id): Path<Uuid>, |
| 85 | Query(query): Query<EntitySearchQuery>, |
| 86 | ) -> ApiResult<Json<serde_json::Value>> { |
| 87 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 88 | if query.q.trim().is_empty() { |
| 89 | return Ok(Json(json!({ "entities": [] }))); |
| 90 | } |
| 91 | let entities = utopia_store::graph::search_entities(&state.pool, kb_id, &query.q, 10).await?; |
| 92 | Ok(Json(json!({ "entities": entities }))) |
| 93 | } |
| 94 | |
| 95 | pub async fn entity_detail( |
| 96 | State(state): State<AppState>, |
| 97 | AuthUser(user): AuthUser, |
| 98 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 99 | ) -> ApiResult<Json<serde_json::Value>> { |
| 100 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 101 | let (entity, facts) = utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id).await?; |
| 102 | Ok(Json(json!({ "entity": entity, "facts": facts }))) |
| 103 | } |
| 104 | |
| 105 | #[derive(Deserialize)] |
| 106 | pub struct EntityPatch { |
| 107 | #[serde(default)] |
| 108 | pub type_id: Option<Uuid>, |
| 109 | #[serde(default)] |
| 110 | pub canonical_name: Option<String>, |
| 111 | } |
| 112 | |
| 113 | /// 人工修正实体的类型或名字。抽取给的是初判,此前判错只能整库重抽。 |
| 114 | /// |
| 115 | /// 改名撞上同名实体不拦(两个张伟是"宁分勿合"的正当产物),改完把同名的报回去, |
| 116 | /// 由界面提示是否合并——判定它们是否真是同一个,是人的事。 |
| 117 | pub async fn update_entity( |
| 118 | State(state): State<AppState>, |
| 119 | AuthUser(user): AuthUser, |
| 120 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 121 | Json(req): Json<EntityPatch>, |
| 122 | ) -> ApiResult<Json<serde_json::Value>> { |
| 123 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 124 | if req.type_id.is_none() && req.canonical_name.is_none() { |
| 125 | return Err(AppError::invalid("nothing_to_update", "Nothing to update").into()); |
| 126 | } |
| 127 | let (before, after) = utopia_store::graph::update_entity( |
| 128 | &state.pool, |
| 129 | kb_id, |
| 130 | entity_id, |
| 131 | req.type_id, |
| 132 | req.canonical_name.as_deref(), |
| 133 | ) |
| 134 | .await?; |
| 135 | |
| 136 | // 台账快照自包含:类型以后被删掉,这条记录仍然读得懂。 |
| 137 | // P4 要按 from/to 聚合"一个月里 37 个实体从 Product 挪到 Concept",所以分开记两个动作。 |
| 138 | if before.type_key != after.type_key { |
| 139 | let _ = utopia_store::audit::record( |
| 140 | &state.pool, |
| 141 | Some(kb_id), |
| 142 | user.id, |
| 143 | "entity.retyped", |
| 144 | "entity", |
| 145 | Some(entity_id), |
| 146 | json!({ |
| 147 | "name": after.name, |
| 148 | "from": { "key": before.type_key, "label": before.type_label }, |
| 149 | "to": { "key": after.type_key, "label": after.type_label }, |
| 150 | }), |
| 151 | ) |
| 152 | .await; |
| 153 | } |
| 154 | if before.name != after.name { |
| 155 | let _ = utopia_store::audit::record( |
| 156 | &state.pool, |
| 157 | Some(kb_id), |
| 158 | user.id, |
| 159 | "entity.renamed", |
| 160 | "entity", |
| 161 | Some(entity_id), |
| 162 | json!({ "from": before.name, "to": after.name, "type": after.type_label }), |
| 163 | ) |
| 164 | .await; |
| 165 | } |
| 166 | |
| 167 | let peers = utopia_store::graph::same_name_peers(&state.pool, kb_id, entity_id).await?; |
| 168 | state.emit_review(kb_id); |
| 169 | Ok(Json(json!({ "entity": after, "same_name": peers }))) |
| 170 | } |
| 171 | |
| 172 | pub async fn fact_evidence( |
| 173 | State(state): State<AppState>, |
| 174 | AuthUser(user): AuthUser, |
| 175 | Path((kb_id, fact_id)): Path<(Uuid, Uuid)>, |
| 176 | ) -> ApiResult<Json<serde_json::Value>> { |
| 177 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 178 | let evidence = utopia_store::graph::fact_evidence(&state.pool, fact_id).await?; |
| 179 | Ok(Json(json!({ "evidence": evidence }))) |
| 180 | } |
| 181 | |
| 182 | /// 手动触发抽取(failed 重试 / 补配模型后补抽)。 |
| 183 | pub async fn extract( |
| 184 | State(state): State<AppState>, |
| 185 | AuthUser(user): AuthUser, |
| 186 | Path(document_id): Path<Uuid>, |
| 187 | ) -> ApiResult<Json<serde_json::Value>> { |
| 188 | let doc = utopia_store::documents::get(&state.pool, document_id).await?; |
| 189 | require_kb(&state, &user, doc.kb_id, Role::Editor).await?; |
| 190 | // 手动触发 = 强制全量:清增量标记、解雇在跑的任务、置 queued、建任务,一个事务办完 |
| 191 | let job_id = utopia_store::documents::queue_extraction_one(&state.pool, document_id).await?; |
| 192 | state.emit_document(doc.kb_id, document_id); |
| 193 | Ok(Json(json!({ "job_id": job_id }))) |
| 194 | } |
| 195 | |
| 196 | /// 图谱重建(清算语义,KB admin):清空整个图层后全量重抽。 |
| 197 | /// 与来源级重抽的分工——重抽保留既有决策,重建放弃它们,换取 |
| 198 | /// "当前语料 × 当前本体"的确定性重演(早期脏抽取、本体大改后的收场手段)。 |
| 199 | /// 决策台账与裁决缓存刻意保留(见 store::graph::purge_graph)。 |
| 200 | pub async fn rebuild( |
| 201 | State(state): State<AppState>, |
| 202 | AuthUser(user): AuthUser, |
| 203 | Path(kb_id): Path<Uuid>, |
| 204 | ) -> ApiResult<Json<serde_json::Value>> { |
| 205 | require_kb(&state, &user, kb_id, Role::Admin).await?; |
| 206 | let (entities, facts) = utopia_store::graph::purge_graph(&state.pool, kb_id).await?; |
| 207 | // 任务由 queue_extraction 与状态同事务建好,这里只负责推送 |
| 208 | let ids = utopia_store::documents::queue_extraction(&state.pool, kb_id, None).await?; |
| 209 | for id in &ids { |
| 210 | state.emit_document(kb_id, *id); |
| 211 | } |
| 212 | state.emit_review(kb_id); |
| 213 | let _ = utopia_store::audit::record( |
| 214 | &state.pool, |
| 215 | Some(kb_id), |
| 216 | user.id, |
| 217 | "graph.rebuild", |
| 218 | "kb", |
| 219 | Some(kb_id), |
| 220 | json!({ "entities_removed": entities, "facts_removed": facts, "documents": ids.len() }), |
| 221 | ) |
| 222 | .await; |
| 223 | Ok(Json(json!({ |
| 224 | "entities_removed": entities, "facts_removed": facts, "queued": ids.len() |
| 225 | }))) |
| 226 | } |
| 227 | |
| 228 | #[derive(Deserialize)] |
| 229 | pub struct HistoryQuery { |
| 230 | #[serde(default)] |
| 231 | pub page: i64, |
| 232 | #[serde(default = "default_history_per")] |
| 233 | pub per: i64, |
| 234 | } |
| 235 | |
| 236 | fn default_history_per() -> i64 { |
| 237 | 30 |
| 238 | } |
| 239 | |
| 240 | /// 实体的认知变更历史(记录时间轴):我们何时这么认为、又何时改了主意。 |
| 241 | /// 与 entity_detail(有效时间轴,只看现行)互补。 |
| 242 | pub async fn entity_history( |
| 243 | State(state): State<AppState>, |
| 244 | AuthUser(user): AuthUser, |
| 245 | Path((kb_id, entity_id)): Path<(Uuid, Uuid)>, |
| 246 | Query(q): Query<HistoryQuery>, |
| 247 | ) -> ApiResult<Json<serde_json::Value>> { |
| 248 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 249 | let per = q.per.clamp(1, 200); |
| 250 | let page = q.page.max(0); |
| 251 | let (events, total) = |
| 252 | utopia_store::graph::entity_history(&state.pool, kb_id, entity_id, per, page * per).await?; |
| 253 | Ok(Json(json!({ "events": events, "total": total }))) |
| 254 | } |