feat(realtime): 新增 RID 目标与登记档案的人工关联绑定功能

- 新增 target_binding 模块,支持在目标详情面板中搜索、绑定和
  解除 RID 与本地登记档案的人工关联
- 实时目标详情中移除内联档案查询逻辑,改用 TargetBinding 组件
- 档案保存后自动将搜索框设为新记录序列号并跳回首页,避免分页
  遗漏;监听 rid-workspace-view 和 focus 事件以刷新档案列表
- 重构首页卡片预览图为 SVG 方案,增加 caption 说明文字,
  调整白色主题配色以匹配新设计
```
This commit is contained in:
2026-10-24 16:11:58 +08:00
parent 18c5178d8f
commit d4dff5c417
15 changed files with 575 additions and 86 deletions
+211
View File
@@ -0,0 +1,211 @@
//! Explicit RID-to-record associations; classification remains attached to the RID identity.
use crate::{error::Result, store::Store};
use rusqlite::{Connection, OptionalExtension, params};
use serde::Deserialize;
use serde_json::{Value, json};
pub fn init(db: &Connection) -> Result<()> {
db.execute_batch("CREATE TABLE IF NOT EXISTS target_record_bindings(
target_id TEXT PRIMARY KEY COLLATE BINARY,
record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE
); CREATE INDEX IF NOT EXISTS target_record_binding_record ON target_record_bindings(record_id);")?;
Ok(())
}
fn validate(target: &str) -> Result<()> {
if !rid_shared::target_lists::valid_target_id(target) {
return Err("RID 目标标识无效".into());
}
Ok(())
}
fn bound(db: &Connection, target: &str) -> Result<Option<String>> {
Ok(db
.query_row(
"SELECT record_id FROM target_record_bindings WHERE target_id=?1",
[target],
|r| r.get(0),
)
.optional()?)
}
pub fn resolve(store: &Store, target: &str) -> Result<Value> {
validate(target)?;
let binding = bound(&store.db, target)?;
let automatic: Option<String> = if binding.is_none() {
store
.db
.query_row(
"SELECT id FROM records WHERE serial_no=?1 COLLATE BINARY",
[target],
|r| r.get(0),
)
.optional()?
} else {
None
};
let id = binding.as_ref().or(automatic.as_ref());
let record = id
.map(|id| store.get(id).map(crate::archive::public))
.transpose()?;
Ok(
json!({"targetId":target,"bindingRecordId":binding,"matchSource":if binding.is_some(){"manual"}else if automatic.is_some(){"serial"}else{"none"},"record":record}),
)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Mutation {
// Required JSON null or string prevents clients silently omitting concurrency checks.
expected_record_id: Value,
record_id: Value,
}
fn nullable_id(value: &Value) -> Result<Option<&str>> {
match value {
Value::Null => Ok(None),
Value::String(id) if crate::store::valid_id(id) => Ok(Some(id)),
_ => Err("档案标识无效".into()),
}
}
pub fn save(store: &mut Store, target: &str, mutation: Mutation) -> Result<Value> {
validate(target)?;
let expected = nullable_id(&mutation.expected_record_id)?;
let record = nullable_id(&mutation.record_id)?;
let tx = store
.db
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
if bound(&tx, target)?.as_deref() != expected {
return Err("关联已被其他页面修改,请刷新关联后重试".into());
}
if let Some(id) = record {
let exists: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM records WHERE id=?1)",
[id],
|r| r.get(0),
)?;
if !exists {
return Err("登记档案已不存在,请重新搜索".into());
}
tx.execute("INSERT INTO target_record_bindings(target_id,record_id) VALUES(?1,?2) ON CONFLICT(target_id) DO UPDATE SET record_id=excluded.record_id",params![target,id])?;
} else {
tx.execute(
"DELETE FROM target_record_bindings WHERE target_id=?1",
[target],
)?;
}
tx.commit()?;
resolve(store, target)
}
#[cfg(test)]
mod tests {
use super::*;
fn change(expected: Option<&str>, record: Option<&str>) -> Mutation {
serde_json::from_value(json!({"expectedRecordId":expected,"recordId":record})).unwrap()
}
#[test]
fn association_persists_is_exact_and_preserves_classification() {
let dir = tempfile::tempdir().unwrap();
let mut s = Store::open(dir.path().into()).unwrap();
let r = s
.register(json!({"serialNo":"SERIAL-001","modelName":"Test","ownerName":"Owner"}))
.unwrap();
let id = r["record"]["id"].as_str().unwrap();
assert_eq!(resolve(&s, "SERIAL-001").unwrap()["matchSource"], "serial");
assert!(resolve(&s, "serial-001").unwrap()["record"].is_null());
crate::target_lists::save(
&mut s.db,
"RID-001",
rid_shared::target_lists::Mutation {
list_kind: rid_shared::target_lists::ListKind::Black,
note: String::new(),
expected_revision: 0,
},
)
.unwrap();
let result = save(&mut s, "RID-001", change(None, Some(id))).unwrap();
assert_eq!(result["record"]["serialNo"], "SERIAL-001");
assert_eq!(result["matchSource"], "manual");
assert!(save(&mut s, "RID-001", change(None, None)).is_err());
assert!(save(&mut s, "RID-001", change(Some(id), Some(&"f".repeat(36)))).is_err());
drop(s);
let mut s = Store::open(dir.path().into()).unwrap();
assert_eq!(resolve(&s, "RID-001").unwrap()["bindingRecordId"], id);
save(&mut s, "RID-001", change(Some(id), None)).unwrap();
assert!(resolve(&s, "RID-001").unwrap()["record"].is_null());
assert_eq!(crate::target_lists::load(&s.db).unwrap().entries.len(), 1);
save(&mut s, "RID-001", change(None, Some(id))).unwrap();
s.delete(id, None).unwrap();
assert!(resolve(&s, "RID-001").unwrap()["record"].is_null());
assert!(resolve(&s, "bad id").is_err());
}
#[tokio::test]
async fn http_binding_validation_and_origin_protection() {
use axum::{body::Body, http::Request};
use tower::ServiceExt;
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path().into()).unwrap();
let r = store.register(json!({"serialNo":"HTTP-001"})).unwrap();
let id = r["record"]["id"].as_str().unwrap().to_owned();
let (tx, mut rx) = tokio::sync::mpsc::channel::<crate::Job>(8);
let worker = std::thread::spawn(move || {
while let Some(crate::Job::Execute(job)) = rx.blocking_recv() {
job(&mut store);
}
});
let app = crate::http::router(crate::Worker(tx));
for (method, body, origin, status) in [
("PUT", json!({"recordId":id}), None, 400),
(
"PUT",
json!({"expectedRecordId":null,"recordId":id}),
Some("https://foreign.example"),
403,
),
(
"PUT",
json!({"expectedRecordId":null,"recordId":id}),
None,
200,
),
("GET", Value::Null, None, 200),
(
"PUT",
json!({"expectedRecordId":null,"recordId":null}),
None,
400,
),
(
"PUT",
json!({"expectedRecordId":id,"recordId":null}),
None,
200,
),
] {
let mut request = Request::builder()
.method(method)
.uri("/api/target-bindings/RID-HTTP");
if let Some(origin) = origin {
request = request.header("origin", origin);
}
let response = app
.clone()
.oneshot(request.body(Body::from(body.to_string())).unwrap())
.await
.unwrap();
assert_eq!(response.status().as_u16(), status, "{method} {body}");
if method == "GET" {
let bytes = axum::body::to_bytes(response.into_body(), 65536)
.await
.unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(value["record"]["serialNo"], "HTTP-001");
}
}
drop(app);
worker.join().unwrap();
}
}