| 1 | use axum::extract::{Path, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::models::{KnowledgeBase, Role, User}; |
| 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 | #[derive(Deserialize)] |
| 14 | pub struct CreateKbReq { |
| 15 | pub name: String, |
| 16 | #[serde(default)] |
| 17 | pub kind: Option<String>, |
| 18 | #[serde(default)] |
| 19 | pub description: Option<String>, |
| 20 | #[serde(default)] |
| 21 | pub visibility: Option<String>, |
| 22 | /// 预置本体包的 id,按给定顺序装。空 = 只有十个种子。 |
| 23 | /// |
| 24 | /// **顺序有意义**:第一个包的类会认领同名的种子类(它们没有 IRI), |
| 25 | /// 后面的包撞名时查对齐表。schema.org 放第一个,别的包才对得上。 |
| 26 | #[serde(default)] |
| 27 | pub ontology_packs: Vec<String>, |
| 28 | } |
| 29 | |
| 30 | #[derive(Deserialize)] |
| 31 | pub struct UpdateKbReq { |
| 32 | pub name: Option<String>, |
| 33 | pub description: Option<String>, |
| 34 | pub visibility: Option<String>, |
| 35 | /// 自动扩本体开关(缺省开;关掉不影响"留意",只是变成你点一下的提案) |
| 36 | #[serde(default)] |
| 37 | pub auto_extend_ontology: Option<bool>, |
| 38 | /// 本体语言(`en` | `zh`):跟语料走,不跟界面走。见 docs/decisions/0004 |
| 39 | #[serde(default)] |
| 40 | pub ontology_lang: Option<String>, |
| 41 | } |
| 42 | |
| 43 | /// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。 |
| 44 | pub async fn list( |
| 45 | State(state): State<AppState>, |
| 46 | AuthUser(user): AuthUser, |
| 47 | Path(workspace_id): Path<Uuid>, |
| 48 | ) -> ApiResult<Json<Vec<KnowledgeBase>>> { |
| 49 | utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer) |
| 50 | .await?; |
| 51 | let list = |
| 52 | utopia_store::kbs::list_visible(&state.pool, workspace_id, user.id, user.is_admin).await?; |
| 53 | Ok(Json(list)) |
| 54 | } |
| 55 | |
| 56 | /// 建库:部署管理员(工作区 Admin+ 或系统管理员)。创建者自动进入矩阵为 admin。 |
| 57 | pub async fn create( |
| 58 | State(state): State<AppState>, |
| 59 | AuthUser(user): AuthUser, |
| 60 | Path(workspace_id): Path<Uuid>, |
| 61 | Json(req): Json<CreateKbReq>, |
| 62 | ) -> ApiResult<Json<KnowledgeBase>> { |
| 63 | let name = req.name.trim(); |
| 64 | if name.is_empty() || name.chars().count() > 64 { |
| 65 | return Err(AppError::invalid("bad_name", "Name must be 1-64 characters").into()); |
| 66 | } |
| 67 | let kind = req.kind.as_deref().unwrap_or("knowledge"); |
| 68 | if !matches!(kind, "knowledge" | "memory") { |
| 69 | return Err(AppError::Validation("kind must be 'knowledge' or 'memory'".into()).into()); |
| 70 | } |
| 71 | // 建库是部署管理动作(入口在 System settings):系统管理员或工作区 Admin+。 |
| 72 | // 用户自建库前端默认 restricted,不污染全员切换器;General 由系统初建保持 open |
| 73 | let ws_role = |
| 74 | utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer) |
| 75 | .await?; |
| 76 | if !user.is_admin && ws_role < Role::Admin { |
| 77 | return Err(AppError::Forbidden.into()); |
| 78 | } |
| 79 | let kb = utopia_store::kbs::create( |
| 80 | &state.pool, |
| 81 | workspace_id, |
| 82 | name, |
| 83 | kind, |
| 84 | req.description.as_deref(), |
| 85 | ) |
| 86 | .await?; |
| 87 | if let Some(v) = req.visibility.as_deref() { |
| 88 | utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v), None, None).await?; |
| 89 | } |
| 90 | utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id)) |
| 91 | .await?; |
| 92 | install_packs( |
| 93 | &state, |
| 94 | kb.id, |
| 95 | user.id, |
| 96 | &kb.ontology_lang, |
| 97 | &req.ontology_packs, |
| 98 | ) |
| 99 | .await?; |
| 100 | let kb = utopia_store::kbs::get(&state.pool, kb.id).await?; |
| 101 | Ok(Json(kb)) |
| 102 | } |
| 103 | |
| 104 | /// 我的知识库全景(账户层):可见库 + 我的角色 + 加入信息 + 概览统计。 |
| 105 | pub async fn my_kbs( |
| 106 | State(state): State<AppState>, |
| 107 | AuthUser(user): AuthUser, |
| 108 | Path(workspace_id): Path<Uuid>, |
| 109 | ) -> ApiResult<Json<serde_json::Value>> { |
| 110 | utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer) |
| 111 | .await?; |
| 112 | let kbs = |
| 113 | utopia_store::kbs::list_visible(&state.pool, workspace_id, user.id, user.is_admin).await?; |
| 114 | let ids: Vec<Uuid> = kbs.iter().map(|k| k.id).collect(); |
| 115 | let infos = utopia_store::access::my_kb_infos(&state.pool, &ids, user.id).await?; |
| 116 | let mut rows = Vec::with_capacity(kbs.len()); |
| 117 | for kb in &kbs { |
| 118 | let info = infos.iter().find(|i| i.kb_id == kb.id); |
| 119 | let role = utopia_store::access::kb_role(&state.pool, &user, kb).await?; |
| 120 | rows.push(json!({ |
| 121 | "kb": kb, |
| 122 | "my_role": role.map(|r| r.as_str()), |
| 123 | "joined_at": info.and_then(|i| i.joined_at), |
| 124 | "added_by_name": info.and_then(|i| i.added_by_name.clone()), |
| 125 | "doc_count": info.map(|i| i.doc_count).unwrap_or(0), |
| 126 | "member_count": info.map(|i| i.member_count).unwrap_or(0), |
| 127 | })); |
| 128 | } |
| 129 | Ok(Json(json!({ "kbs": rows }))) |
| 130 | } |
| 131 | |
| 132 | async fn kb_with_role( |
| 133 | state: &AppState, |
| 134 | user: &User, |
| 135 | kb_id: Uuid, |
| 136 | min: Role, |
| 137 | ) -> Result<KnowledgeBase, AppError> { |
| 138 | utopia_store::access::require_kb(&state.pool, user, kb_id, min).await |
| 139 | } |
| 140 | |
| 141 | /// 详情附带调用者在本库的角色:前端据此门控破坏性操作(重建/删除)的入口, |
| 142 | /// 不必让用户点到底才吃 403。 |
| 143 | pub async fn get_one( |
| 144 | State(state): State<AppState>, |
| 145 | AuthUser(user): AuthUser, |
| 146 | Path(id): Path<Uuid>, |
| 147 | ) -> ApiResult<Json<serde_json::Value>> { |
| 148 | let kb = kb_with_role(&state, &user, id, Role::Viewer).await?; |
| 149 | let role = utopia_store::access::kb_role(&state.pool, &user, &kb).await?; |
| 150 | let mut body = serde_json::to_value(&kb).map_err(|e| AppError::Other(e.into()))?; |
| 151 | body["my_role"] = json!(role.map(|r| r.as_str())); |
| 152 | Ok(Json(body)) |
| 153 | } |
| 154 | |
| 155 | /// 库设置(名称/描述/可见性):库 admin 起步。 |
| 156 | pub async fn update( |
| 157 | State(state): State<AppState>, |
| 158 | AuthUser(user): AuthUser, |
| 159 | Path(id): Path<Uuid>, |
| 160 | Json(req): Json<UpdateKbReq>, |
| 161 | ) -> ApiResult<Json<KnowledgeBase>> { |
| 162 | kb_with_role(&state, &user, id, Role::Admin).await?; |
| 163 | let kb = utopia_store::kbs::update( |
| 164 | &state.pool, |
| 165 | id, |
| 166 | req.name.as_deref().map(str::trim), |
| 167 | req.description.as_deref(), |
| 168 | req.visibility.as_deref(), |
| 169 | req.auto_extend_ontology, |
| 170 | req.ontology_lang.as_deref(), |
| 171 | ) |
| 172 | .await?; |
| 173 | // 审计只记不阻断 |
| 174 | let _ = utopia_store::audit::record( |
| 175 | &state.pool, |
| 176 | Some(id), |
| 177 | user.id, |
| 178 | "kb.updated", |
| 179 | "kb", |
| 180 | Some(id), |
| 181 | json!({ "name": req.name, "visibility": req.visibility }), |
| 182 | ) |
| 183 | .await; |
| 184 | Ok(Json(kb)) |
| 185 | } |
| 186 | |
| 187 | pub async fn delete( |
| 188 | State(state): State<AppState>, |
| 189 | AuthUser(user): AuthUser, |
| 190 | Path(id): Path<Uuid>, |
| 191 | ) -> ApiResult<Json<serde_json::Value>> { |
| 192 | let kb = kb_with_role(&state, &user, id, Role::Admin).await?; |
| 193 | utopia_store::kbs::delete(&state.pool, id).await?; |
| 194 | // kb_id 置 NULL:库已级联删除,事件留在部署层(actor 与库名在 detail) |
| 195 | let _ = utopia_store::audit::record( |
| 196 | &state.pool, |
| 197 | None, |
| 198 | user.id, |
| 199 | "kb.deleted", |
| 200 | "kb", |
| 201 | Some(id), |
| 202 | json!({ "name": kb.name }), |
| 203 | ) |
| 204 | .await; |
| 205 | Ok(Json(json!({ "ok": true }))) |
| 206 | } |
| 207 | |
| 208 | // --------------------------------------------------------------------------- |
| 209 | // KB 成员矩阵(库自己的 Settings → Members) |
| 210 | // --------------------------------------------------------------------------- |
| 211 | |
| 212 | pub async fn members( |
| 213 | State(state): State<AppState>, |
| 214 | AuthUser(user): AuthUser, |
| 215 | Path(id): Path<Uuid>, |
| 216 | ) -> ApiResult<Json<serde_json::Value>> { |
| 217 | kb_with_role(&state, &user, id, Role::Admin).await?; |
| 218 | let members = utopia_store::access::kb_members(&state.pool, id).await?; |
| 219 | Ok(Json(json!({ "members": members }))) |
| 220 | } |
| 221 | |
| 222 | #[derive(Deserialize)] |
| 223 | pub struct SetMemberReq { |
| 224 | /// viewer | editor | admin |
| 225 | pub role: String, |
| 226 | } |
| 227 | |
| 228 | pub async fn set_member( |
| 229 | State(state): State<AppState>, |
| 230 | AuthUser(user): AuthUser, |
| 231 | Path((id, user_id)): Path<(Uuid, Uuid)>, |
| 232 | Json(req): Json<SetMemberReq>, |
| 233 | ) -> ApiResult<Json<serde_json::Value>> { |
| 234 | kb_with_role(&state, &user, id, Role::Admin).await?; |
| 235 | utopia_store::access::set_kb_member(&state.pool, id, user_id, &req.role, Some(user.id)).await?; |
| 236 | let _ = utopia_store::audit::record( |
| 237 | &state.pool, |
| 238 | Some(id), |
| 239 | user.id, |
| 240 | "kb.member_set", |
| 241 | "user", |
| 242 | Some(user_id), |
| 243 | json!({ "role": req.role }), |
| 244 | ) |
| 245 | .await; |
| 246 | Ok(Json(json!({ "ok": true }))) |
| 247 | } |
| 248 | |
| 249 | pub async fn remove_member( |
| 250 | State(state): State<AppState>, |
| 251 | AuthUser(user): AuthUser, |
| 252 | Path((id, user_id)): Path<(Uuid, Uuid)>, |
| 253 | ) -> ApiResult<Json<serde_json::Value>> { |
| 254 | kb_with_role(&state, &user, id, Role::Admin).await?; |
| 255 | utopia_store::access::remove_kb_member(&state.pool, id, user_id).await?; |
| 256 | let _ = utopia_store::audit::record( |
| 257 | &state.pool, |
| 258 | Some(id), |
| 259 | user.id, |
| 260 | "kb.member_removed", |
| 261 | "user", |
| 262 | Some(user_id), |
| 263 | json!({}), |
| 264 | ) |
| 265 | .await; |
| 266 | Ok(Json(json!({ "ok": true }))) |
| 267 | } |
| 268 | |
| 269 | /// 库级审计日志(Admin 起步;纯审计展示)。 |
| 270 | pub async fn audit_log( |
| 271 | State(state): State<AppState>, |
| 272 | AuthUser(user): AuthUser, |
| 273 | Path(id): Path<Uuid>, |
| 274 | ) -> ApiResult<Json<serde_json::Value>> { |
| 275 | kb_with_role(&state, &user, id, Role::Admin).await?; |
| 276 | let events = utopia_store::audit::list_for_kb(&state.pool, id, 100).await?; |
| 277 | Ok(Json(json!({ "events": events }))) |
| 278 | } |
| 279 | |
| 280 | /// 建库时装选中的本体包。 |
| 281 | /// |
| 282 | /// **种子本体先落地**:包里的类要认领同名的种子类(`schema:Organization` 接管 |
| 283 | /// `organization`),而认领的前提是那一行已经存在。`ensure_default_ontology` |
| 284 | /// 平时是懒调的(首次读本体或首次抽取时),这里必须显式先跑一次。 |
| 285 | /// |
| 286 | /// **一个包失败不回滚已装的**:本体是加法,装了一半的库仍然可用, |
| 287 | /// 而回滚要撤已经建好的类——那正是 0008 决定不做导入撤销的理由。 |
| 288 | /// 失败信息里带上是哪个包,让人知道从哪补。 |
| 289 | async fn install_packs( |
| 290 | state: &AppState, |
| 291 | kb_id: Uuid, |
| 292 | actor: Uuid, |
| 293 | lang: &str, |
| 294 | pack_ids: &[String], |
| 295 | ) -> ApiResult<()> { |
| 296 | if pack_ids.is_empty() { |
| 297 | return Ok(()); |
| 298 | } |
| 299 | utopia_store::graph::ensure_default_ontology(&state.pool, kb_id, lang).await?; |
| 300 | for id in pack_ids { |
| 301 | let pack = crate::ontology_packs::get(id) |
| 302 | .ok_or_else(|| AppError::invalid("unknown_pack", format!("未知的本体包:{id}")))?; |
| 303 | let bytes = crate::ontology_packs::bytes(pack)?; |
| 304 | crate::owl_import::apply(state, kb_id, actor, pack.filename, &bytes) |
| 305 | .await |
| 306 | .map_err(|e| AppError::Other(anyhow::anyhow!("装本体包 {} 失败:{e}", pack.id)))?; |
| 307 | } |
| 308 | Ok(()) |
| 309 | } |
| 310 | |
| 311 | /// 可选的本体包清单,给建库界面。不需要登录之外的权限——它是静态数据。 |
| 312 | pub async fn list_packs(AuthUser(_): AuthUser) -> ApiResult<Json<serde_json::Value>> { |
| 313 | let packs: Vec<_> = crate::ontology_packs::PACKS |
| 314 | .iter() |
| 315 | .map(|p| { |
| 316 | json!({ |
| 317 | "id": p.id, |
| 318 | "name": p.name, |
| 319 | "summary": p.summary, |
| 320 | "classes": p.classes, |
| 321 | "properties": p.properties, |
| 322 | }) |
| 323 | }) |
| 324 | .collect(); |
| 325 | Ok(Json(json!({ "packs": packs }))) |
| 326 | } |