Elffuss BraidHub

kikocis/utopia public

A definition you cannot see is one you cannot argue with (#140)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset1258cb420edffc0efc7674fb0f18f15830a089c0dfad78ebc1567e7accca94d7
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-08-31 18:48 +08:00
CommitterGitHub <noreply@github.com> · 2026-08-31 18:48 +08:00
Parents0c1af9947a69

Browse the files at this changeset

13 files changed

modified crates/utopia-core/src/models.rs +15 −0
@@ -800,6 +800,21 @@
800800 pub domain_keys: Vec<String>,
801801 }
802802
803+/// 一条口径改动之前的样子。
804+///
805+/// **存整版快照而不是差异**(0006):读的时候要回答的是「当时是什么」,
806+/// 而差异得从头重放才答得出来。`before` 是改动前那一行的 `to_jsonb`,
807+/// 去掉了 id 与 kb_id。
808+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
809+pub struct MappingRevision {
810+ pub id: Uuid,
811+ pub before: serde_json::Value,
812+ /// 改的人。**裸外键 + 用户软删除**,所以归因不会因为人离职而丢;
813+ /// 真被硬删过才会是 NULL
814+ pub changed_by_name: Option<String>,
815+ pub changed_at: DateTime<Utc>,
816+}
817+
803818 /// 语义层的一条映射:业务概念 → 数据资产定义(见 `docs/decisions/0011`)。
804819 ///
805820 /// **字段是列,不是 JSON 里的键。** 从前它是一条 `mapped_to` 事实,
added crates/utopia-server/src/api/mapping_routes.rs +148 −0
@@ -0,0 +1,148 @@
1+//! 数据映射 API:口径的列表、改写与改版历史。
2+//!
3+//! 审批(`decide`)留在 `review_routes`——那条端点已经在写审计流水
4+//! (`mapping.decided`),换个界面调它即可,没有理由为了搬页面而搬端点。
5+
6+use axum::extract::{Path, Query, State};
7+use axum::Json;
8+use serde::Deserialize;
9+use serde_json::json;
10+use utopia_core::models::Role;
11+use utopia_core::AppError;
12+use uuid::Uuid;
13+
14+use super::graph_routes::require_kb;
15+use crate::auth::AuthUser;
16+use crate::error::ApiResult;
17+use crate::state::AppState;
18+
19+/// 一页多少条。口径比审阅队列密(一行就是一个定义),一页给得起 25 条
20+const MAPPING_PAGE: i64 = 25;
21+
22+#[derive(Deserialize)]
23+pub struct ListQuery {
24+ /// proposed | confirmed | rejected;缺省 = 全部
25+ status: Option<String>,
26+ q: Option<String>,
27+ limit: Option<i64>,
28+ offset: Option<i64>,
29+}
30+
31+/// 一页口径 + 三种状态各多少。
32+///
33+/// **Viewer 就能看。** 口径是「这个数怎么算」,问数的答案直接由它决定——
34+/// 看得见答案却看不见口径,等于要人信一个不给看的算法。改(`revise`)
35+/// 才要 Editor。
36+pub async fn list(
37+ State(state): State<AppState>,
38+ AuthUser(user): AuthUser,
39+ Path(kb_id): Path<Uuid>,
40+ Query(q): Query<ListQuery>,
41+) -> ApiResult<Json<serde_json::Value>> {
42+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
43+ let status = q.status.as_deref().filter(|s| !s.is_empty());
44+ if let Some(s) = status {
45+ if !matches!(s, "proposed" | "confirmed" | "rejected") {
46+ return Err(AppError::invalid(
47+ "bad_status",
48+ "status must be proposed, confirmed or rejected",
49+ )
50+ .into());
51+ }
52+ }
53+ let needle = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());
54+ let limit = q.limit.unwrap_or(MAPPING_PAGE).clamp(1, 200);
55+ let offset = q.offset.unwrap_or(0).max(0);
56+
57+ let (items, total) =
58+ utopia_store::mappings::page(&state.pool, kb_id, status, needle, limit, offset).await?;
59+ let (proposed, confirmed, rejected) =
60+ utopia_store::mappings::status_counts(&state.pool, kb_id).await?;
61+ Ok(Json(json!({
62+ "items": items,
63+ "total": total,
64+ "counts": { "proposed": proposed, "confirmed": confirmed, "rejected": rejected },
65+ })))
66+}
67+
68+#[derive(Deserialize)]
69+pub struct ReviseReq {
70+ table_name: Option<String>,
71+ expr: Option<String>,
72+ sql: Option<String>,
73+ unit: Option<String>,
74+ summary: Option<String>,
75+ #[serde(default)]
76+ derived: bool,
77+}
78+
79+/// 改一条口径。
80+///
81+/// **在此之前 `mappings::revise` 是零调用的**:函数在、留痕表在、没有路由。
82+/// 于是口径确认之后就再没人改得动,也没人看得见——问数照着它算,人却够不着。
83+pub async fn revise(
84+ State(state): State<AppState>,
85+ AuthUser(user): AuthUser,
86+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,
87+ Json(req): Json<ReviseReq>,
88+) -> ApiResult<Json<serde_json::Value>> {
89+ require_kb(&state, &user, kb_id, Role::Editor).await?;
90+ // 空白等于没填:前端清空一个输入框传来的是 "",落库该是 NULL 而不是空串,
91+ // 否则「有没有配 expr」这个判断要同时问 IS NULL 和 = ''
92+ let clean = |s: &Option<String>| -> Option<String> {
93+ s.as_deref()
94+ .map(str::trim)
95+ .filter(|x| !x.is_empty())
96+ .map(str::to_string)
97+ };
98+ let (table_name, expr, sql, unit, summary) = (
99+ clean(&req.table_name),
100+ clean(&req.expr),
101+ clean(&req.sql),
102+ clean(&req.unit),
103+ clean(&req.summary),
104+ );
105+ if table_name.is_none() && expr.is_none() && sql.is_none() {
106+ return Err(AppError::invalid(
107+ "empty_mapping",
108+ "A mapping needs at least one of table, expression or SQL",
109+ )
110+ .into());
111+ }
112+ utopia_store::mappings::revise(
113+ &state.pool,
114+ kb_id,
115+ mapping_id,
116+ table_name.as_deref(),
117+ expr.as_deref(),
118+ sql.as_deref(),
119+ unit.as_deref(),
120+ summary.as_deref(),
121+ req.derived,
122+ user.id,
123+ )
124+ .await?;
125+ let _ = utopia_store::audit::record(
126+ &state.pool,
127+ Some(kb_id),
128+ user.id,
129+ "mapping.revised",
130+ "concept_mapping",
131+ Some(mapping_id),
132+ json!({}),
133+ )
134+ .await;
135+ Ok(Json(json!({ "ok": true })))
136+}
137+
138+/// 一条口径的改版历史。0006 说留痕是为了答得出「上季度这个数是怎么算的」,
139+/// 这是那句话的兑现处。
140+pub async fn revisions(
141+ State(state): State<AppState>,
142+ AuthUser(user): AuthUser,
143+ Path((kb_id, mapping_id)): Path<(Uuid, Uuid)>,
144+) -> ApiResult<Json<serde_json::Value>> {
145+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
146+ let rows = utopia_store::mappings::revisions(&state.pool, kb_id, mapping_id).await?;
147+ Ok(Json(json!({ "revisions": rows })))
148+}
modified crates/utopia-server/src/api/mod.rs +10 −0
@@ -7,6 +7,7 @@
77 mod events_routes;
88 mod graph_routes;
99 mod kbs;
10+mod mapping_routes;
1011 mod members_routes;
1112 pub(crate) mod ontology_routes;
1213 mod review_routes;
@@ -110,6 +111,15 @@
110111 "/admin/data-sources/{id}/test",
111112 post(datasource_routes::test),
112113 )
114+ .route("/kbs/{id}/mappings", get(mapping_routes::list))
115+ .route(
116+ "/kbs/{id}/mappings/{mapping_id}",
117+ axum::routing::patch(mapping_routes::revise),
118+ )
119+ .route(
120+ "/kbs/{id}/mappings/{mapping_id}/revisions",
121+ get(mapping_routes::revisions),
122+ )
113123 .route("/kbs/{id}/data-sources", get(datasource_routes::mounted))
114124 .route(
115125 "/kbs/{id}/data-sources/available",
modified crates/utopia-server/src/api/review_routes.rs +1 −1
@@ -474,7 +474,7 @@
474474 if !matches!(req.status.as_str(), "confirmed" | "rejected") {
475475 return Err(utopia_core::AppError::invalid(
476476 "bad_status",
477- "status 只能是 confirmed 或 rejected",
477+ "status must be confirmed or rejected",
478478 )
479479 .into());
480480 }
modified crates/utopia-store/src/mappings.rs +91 −1
@@ -8,7 +8,7 @@
88 //! append-only,改之前的那一版进 `concept_mapping_revisions` 留痕即可。
99
1010 use sqlx::PgPool;
11-use utopia_core::models::ConceptMapping;
11+use utopia_core::models::{ConceptMapping, MappingRevision};
1212 use utopia_core::{AppError, AppResult};
1313 use uuid::Uuid;
1414
@@ -205,3 +205,93 @@
205205 tx.commit().await?;
206206 Ok(())
207207 }
208+
209+/// 数据映射页读的:一页口径,可按状态与关键词筛。
210+///
211+/// **`proposed` 与 `confirmed` 那两条查询都不够用**——前者只捞待表态的,
212+/// 后者是给问数拼 prompt 的(无分页、无筛选、限 30 条)。人要看的是全部,
213+/// 包括被自己拒绝过的那些:拒绝留了痕,就该看得见,否则「为什么这个概念
214+/// 没被映射」永远答不上来。
215+pub async fn page(
216+ pool: &PgPool,
217+ kb_id: Uuid,
218+ status: Option<&str>,
219+ q: Option<&str>,
220+ limit: i64,
221+ offset: i64,
222+) -> AppResult<(Vec<ConceptMapping>, i64)> {
223+ // 概念名与数据源名都可搜:人记得住的是「GMV」,也可能是「那个接了 orders 的」
224+ const WHERE: &str = "WHERE m.kb_id = $1
225+ AND ($2::text IS NULL OR m.status = $2)
226+ AND ($3::text IS NULL
227+ OR e.canonical_name ILIKE '%' || $3 || '%'
228+ OR m.source ILIKE '%' || $3 || '%'
229+ OR m.table_name ILIKE '%' || $3 || '%')";
230+ let rows: Vec<ConceptMapping> = sqlx::query_as(&format!(
231+ "SELECT m.id, m.concept_id, e.canonical_name AS concept_name, m.source,
232+ m.table_name, m.expr, m.sql, m.unit, m.summary, m.derived, m.status
233+ FROM concept_mappings m
234+ JOIN entities e ON e.id = m.concept_id
235+ {WHERE}
236+ ORDER BY e.canonical_name, m.source
237+ LIMIT $4 OFFSET $5"
238+ ))
239+ .bind(kb_id)
240+ .bind(status)
241+ .bind(q)
242+ .bind(limit)
243+ .bind(offset)
244+ .fetch_all(pool)
245+ .await?;
246+ let (total,): (i64,) = sqlx::query_as(&format!(
247+ "SELECT count(*) FROM concept_mappings m
248+ JOIN entities e ON e.id = m.concept_id {WHERE}"
249+ ))
250+ .bind(kb_id)
251+ .bind(status)
252+ .bind(q)
253+ .fetch_one(pool)
254+ .await?;
255+ Ok((rows, total))
256+}
257+
258+/// 每种状态各多少。页面的筛选条要显示计数,分三次查是三次全表扫。
259+pub async fn status_counts(pool: &PgPool, kb_id: Uuid) -> AppResult<(i64, i64, i64)> {
260+ let row: (i64, i64, i64) = sqlx::query_as(
261+ "SELECT count(*) FILTER (WHERE status = 'proposed'),
262+ count(*) FILTER (WHERE status = 'confirmed'),
263+ count(*) FILTER (WHERE status = 'rejected')
264+ FROM concept_mappings WHERE kb_id = $1",
265+ )
266+ .bind(kb_id)
267+ .fetch_one(pool)
268+ .await?;
269+ Ok(row)
270+}
271+
272+/// 一条口径改过几次、每次改之前是什么样。
273+///
274+/// `revise` 从建表起就在写 `concept_mapping_revisions`,而**在此之前没有任何
275+/// 地方读它**——留痕留了个寂寞。0006 说留痕是为了「问数回溯历史报表时答得出
276+/// 『上季度这个数是怎么算的』」,那就得有人看得见。
277+pub async fn revisions(
278+ pool: &PgPool,
279+ kb_id: Uuid,
280+ mapping_id: Uuid,
281+) -> AppResult<Vec<MappingRevision>> {
282+ // kb_id 走 JOIN 校验归属:revisions 表自己没有 kb_id,
283+ // 不校验就能拿别的库的口径历史
284+ Ok(sqlx::query_as(
285+ "SELECT r.id, r.before, u.display_name AS changed_by_name, r.changed_at
286+ FROM concept_mapping_revisions r
287+ JOIN concept_mappings m ON m.id = r.mapping_id
288+ LEFT JOIN users u ON u.id = r.changed_by
289+ WHERE r.mapping_id = $2 AND m.kb_id = $1
290+ ORDER BY r.changed_at DESC
291+ LIMIT 50",
292+ )
293+ .bind(kb_id)
294+ .bind(mapping_id)
295+ .fetch_all(pool)
296+ .await?)
297+}
modified web/src/api.ts +74 −19
@@ -394,8 +394,7 @@
394394 right: ReviewSide;
395395 }
396396
397-
398-/** 语义层的一条映射:业务概念 → 数据资产定义(见 docs/decisions/0011)。
397+/** 数据映射的一条口径:业务概念 → 数据资产定义(见 docs/decisions/0011)。
399398 *
400399 * 字段是列而不是 JSON 里的键——从前它是一条 `mapped_to` 事实,
401400 * 这几样全塞在 `object_value` 里。 */
@@ -414,6 +413,15 @@
414413 derived: boolean;
415414 status: "proposed" | "confirmed" | "rejected";
416415 }
416+/** 一条口径改动之前的样子。**整版快照而不是差异**(0006):
417+ * 读的时候要回答的是「当时是什么」,差异得从头重放才答得出来 */
418+export interface MappingRevision {
419+ id: string;
420+ before: Record<string, unknown>;
421+ /** 改的人;用户是软删除的,所以归因不会因为人离职而丢 */
422+ changed_by_name: string | null;
423+ changed_at: string;
424+}
417425 /** 一处公理违规(0002 R0)。判据来自本体自己声明的公理,没声明就不报 */
418426 export interface AxiomViolation {
419427 id: string;
@@ -981,8 +989,7 @@
981989
982990 /** 已停用的账号。**没有它恢复就够不着**——那个人从所有列表里消失,
983991 * 而恢复接口要的正是他的 id */
984- deactivatedUsers: () =>
985- request<OrgUser[]>("/api/v1/users/deactivated"),
992+ deactivatedUsers: () => request<OrgUser[]>("/api/v1/users/deactivated"),
986993 /** 恢复一个停用的账号 */
987994 adminReactivateUser: (userId: string) =>
988995 request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
@@ -1008,6 +1015,51 @@
10081015 request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, {
10091016 method: "POST",
10101017 }),
1018+
1019+ /** 一页口径。**Viewer 就能看**——问数的答案直接由口径决定,
1020+ * 看得见答案却看不见口径,等于要人信一个不给看的算法 */
1021+ mappings: (
1022+ kbId: string,
1023+ opts: {
1024+ status?: "proposed" | "confirmed" | "rejected";
1025+ q?: string;
1026+ limit?: number;
1027+ offset?: number;
1028+ } = {},
1029+ ) => {
1030+ const p = new URLSearchParams();
1031+ if (opts.status) p.set("status", opts.status);
1032+ if (opts.q) p.set("q", opts.q);
1033+ if (opts.limit != null) p.set("limit", String(opts.limit));
1034+ if (opts.offset != null) p.set("offset", String(opts.offset));
1035+ const qs = p.toString();
1036+ return request<{
1037+ items: ConceptMapping[];
1038+ total: number;
1039+ counts: { proposed: number; confirmed: number; rejected: number };
1040+ }>(`/api/v1/kbs/${kbId}/mappings${qs ? `?${qs}` : ""}`);
1041+ },
1042+ /** 改一条口径。改之前那一版自动进 revisions */
1043+ reviseMapping: (
1044+ kbId: string,
1045+ mappingId: string,
1046+ body: {
1047+ table_name?: string | null;
1048+ expr?: string | null;
1049+ sql?: string | null;
1050+ unit?: string | null;
1051+ summary?: string | null;
1052+ derived: boolean;
1053+ },
1054+ ) =>
1055+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/mappings/${mappingId}`, {
1056+ method: "PATCH",
1057+ body: JSON.stringify(body),
1058+ }),
1059+ mappingRevisions: (kbId: string, mappingId: string) =>
1060+ request<{ revisions: MappingRevision[] }>(
1061+ `/api/v1/kbs/${kbId}/mappings/${mappingId}/revisions`,
1062+ ),
10111063 kbDataSources: (kbId: string) =>
10121064 request<{ data_sources: DataSourceView[] }>(
10131065 `/api/v1/kbs/${kbId}/data-sources`,
@@ -1337,9 +1389,10 @@
13371389 /** 值换不动那个 datatype、因而没被改写的条数。改写了 3 条丢下 2 条,
13381390 只报前半句就是报喜不报忧 */
13391391 unconvertible?: number;
1340- }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`,
1341- { method: "POST", body: JSON.stringify(body) },
1342- ),
1392+ }>(`/api/v1/kbs/${kbId}/ontology/adopt-predicate`, {
1393+ method: "POST",
1394+ body: JSON.stringify(body),
1395+ }),
13431396 /** 撤销一次采纳:新写的行作废、旧行复活。关系类型留着 */
13441397 unadoptPredicate: (kbId: string, batchId: string) =>
13451398 request<{ reverted: number }>(
@@ -1402,12 +1455,7 @@
14021455
14031456 /** 审核队列的各档**真实条数**。与列表分开取——列表有一页的上限,数数没有。
14041457 * 从前徽标读的是数组长度,而接口固定只回 100 条,于是 164 条写成 100。 */
1405- review: (
1406- kbId: string,
1407- queue: ReviewQueue,
1408- limit: number,
1409- offset: number,
1410- ) =>
1458+ review: (kbId: string, queue: ReviewQueue, limit: number, offset: number) =>
14111459 request<{
14121460 counts: ReviewCounts;
14131461 queue: ReviewQueue;
@@ -1435,12 +1483,19 @@
14351483 method: "POST",
14361484 body: JSON.stringify({ action }),
14371485 }),
1438- /** 对一条语义层映射表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1439- decideMapping: (kbId: string, mappingId: string, status: "confirmed" | "rejected") =>
1440- request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/mappings/${mappingId}`, {
1441- method: "POST",
1442- body: JSON.stringify({ status }),
1443- }),
1486+ /** 对一条数据映射口径表态(0011)。改状态不删行——拒绝留痕,下一轮探索不再提议它 */
1487+ decideMapping: (
1488+ kbId: string,
1489+ mappingId: string,
1490+ status: "confirmed" | "rejected",
1491+ ) =>
1492+ request<{ ok: boolean }>(
1493+ `/api/v1/kbs/${kbId}/review/mappings/${mappingId}`,
1494+ {
1495+ method: "POST",
1496+ body: JSON.stringify({ status }),
1497+ },
1498+ ),
14441499 /** 跑一遍一致性检查。同步返回——纯计算,没有模型调用也没有网络 */
14451500 runConsistencyCheck: (kbId: string) =>
14461501 request<{
modified web/src/i18n/en.ts +75 −7
@@ -566,7 +566,8 @@
566566 「采购了」出来是 purchases——说"原文说的是 purchases"是假的。
567567 逐字原句就在旁边的证据引文里,没丢。 */
568568 proposedPredicate: (p: string) => `read from the text as “${p}”`,
569- inferredPredicate: "not a relation in the ontology, this is the source's wording",
569+ inferredPredicate:
570+ "not a relation in the ontology, this is the source's wording",
570571 unknownPredicate: "no relation stated",
571572 sectionRef: (filename: string, seq: number) =>
572573 `${filename} · section ${seq} →`,
@@ -614,7 +615,11 @@
614615 derivedOff: "off",
615616 derivedNever: "never",
616617 derivedAgo: (mins: number) =>
617- mins < 1 ? "just now" : mins < 60 ? `${mins} min ago` : `${Math.round(mins / 60)} h ago`,
618+ mins < 1
619+ ? "just now"
620+ : mins < 60
621+ ? `${mins} min ago`
622+ : `${Math.round(mins / 60)} h ago`,
618623 derivedRun: "Run now",
619624 derivedRunning: "Running…",
620625 derivedNoChange: "Nothing changed.",
@@ -738,7 +743,8 @@
738743 defaultChip: "Default",
739744 newKb: "New knowledge base",
740745 packsLabel: "Bundled ontologies",
741- packsHint: "Optional. Packs declare direction, so subject and object cannot come out reversed. More can be imported later.",
746+ packsHint:
747+ "Optional. Packs declare direction, so subject and object cannot come out reversed. More can be imported later.",
742748 packsNone: "None — start from the ten seed relations",
743749 packsCount: (c: number, p: number) => `${c} classes · ${p} properties`,
744750 name: "Name",
@@ -854,14 +860,16 @@
854860 axioms: "Axioms",
855861 axiomsHint:
856862 "What this relation guarantees. These are not descriptions — they change what the system does: the temporal engine closes old values, and the reasoning engine adds edges to the graph.",
857- functionalHint: "One subject, one value at a time. A new value closes the old one.",
863+ functionalHint:
864+ "One subject, one value at a time. A new value closes the old one.",
858865 inverseFunctionalHint: "One object, one subject. A project has one lead.",
859866 transitive: "Transitive",
860867 transitiveHint: "A→B and B→C means A→C. The engine will add those edges.",
861868 symmetric: "Symmetric",
862869 symmetricHint: "A→B means B→A. The engine will add the other direction.",
863870 asymmetric: "Asymmetric",
864- asymmetricHint: "A→B rules out B→A. Both directions get reported as a contradiction.",
871+ asymmetricHint:
872+ "A→B rules out B→A. Both directions get reported as a contradiction.",
865873 irreflexive: "Irreflexive",
866874 irreflexiveHint: "Nothing can point at itself through this relation.",
867875 axiomConflict:
@@ -985,6 +993,66 @@
985993 proposals: "AI proposals",
986994 keyHint: "lowercase_snake_case",
987995 },
996+ mapping: {
997+ title: "Data mapping",
998+ hint: "What business concepts point at in the database, and how they are computed. Ask only answers using confirmed definitions.",
999+ tabDefinitions: "Definitions",
1000+ tabSources: "Data sources",
1001+ filterAll: "All",
1002+ filterProposed: "Pending",
1003+ filterConfirmed: "Confirmed",
1004+ filterRejected: "Rejected",
1005+ searchPlaceholder: "Search concept, source or table…",
1006+ total: (n: number) => `${n} total`,
1007+ range: (from: number, to: number, total: number) =>
1008+ `${from}–${to} of ${total}`,
1009+ prev: "Previous",
1010+ next: "Next",
1011+ empty:
1012+ "No definitions yet. Mount a data source, then run Explore to have an agent propose a first batch.",
1013+ emptyFiltered: "No definitions match.",
1014+ rejectedHint:
1015+ "Rejected ones are listed too — otherwise “why was this concept never mapped?” has no answer.",
1016+ colConcept: "Concept",
1017+ colSource: "Source",
1018+ colDefinition: "How it is computed",
1019+ colStatus: "Status",
1020+ derivedBadge: "Derived",
1021+ noDefinition: "(empty)",
1022+ approve: "Confirm",
1023+ reject: "Reject",
1024+ edit: "Edit",
1025+ editTitle: "Revise definition",
1026+ fieldTable: "Table",
1027+ fieldExpr: "Expression",
1028+ fieldSql: "SQL",
1029+ fieldUnit: "Unit",
1030+ fieldSummary: "Summary",
1031+ fieldDerived: "Derived metric (computed, not a column)",
1032+ save: "Save",
1033+ cancel: "Cancel",
1034+ needOne: "Fill in at least one of table, expression or SQL.",
1035+ history: "Revision history",
1036+ historyHint:
1037+ "A full snapshot of the version before each change. Kept so “how was this number computed last quarter?” has an answer.",
1038+ historyEmpty: "Never revised.",
1039+ historyBy: (who: string) => `Revised by ${who}`,
1040+ historyUnknown: "a removed user",
1041+ sourcesHint:
1042+ "Read-only databases mounted here. Mounting ingests the schema so Ask knows which tables exist before writing SQL.",
1043+ mount: "Mount",
1044+ unmount: "Unmount",
1045+ syncSchema: "Refresh schema",
1046+ schemaSynced: (n: number) => `Schema ingested (${n} tables)`,
1047+ explore: "Explore mappings",
1048+ exploreHint:
1049+ "An agent reads these schemas and proposes metric and dimension definitions. Proposals land in Pending; Ask uses them only once confirmed.",
1050+ exploreQueued: "Exploration queued — proposals will appear under Pending.",
1051+ sourcesEmpty: "No data sources mounted.",
1052+ sourcesNoneAvailable:
1053+ "No data sources registered yet — ask a deployment admin to register one.",
1054+ newConn: "Register a new connection",
1055+ },
9881056 review: {
9891057 title: "Review",
9901058 hint: "Duplicates & low-confidence facts",
@@ -997,7 +1065,7 @@
9971065 railConflicts: "Conflicts",
9981066 railUnconfirmed: "Unconfirmed",
9991067 railLowConfidence: "Low confidence",
1000- railMappings: "Semantic layer",
1068+ railMappings: "Data mapping",
10011069 railViolations: "Axioms",
10021070 railDefects: "Ontology",
10031071 railDecisions: "Decisions",
@@ -1088,7 +1156,7 @@
10881156 * 一条会让人以为界面漏了东西 */
10891157 checkNothingNew: "Nothing new",
10901158 checkClean: (n: number) => `${n} facts checked, no contradictions`,
1091- mappings: "Semantic layer",
1159+ mappings: "Data mapping",
10921160 mappingsHint:
10931161 "Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",
10941162 mappingDerived: "derived",
modified web/src/i18n/zh.ts +69 −5
@@ -566,7 +566,11 @@
566566 derivedOff: "已关闭",
567567 derivedNever: "从未",
568568 derivedAgo: (mins: number) =>
569- mins < 1 ? "刚刚" : mins < 60 ? `${mins} 分钟前` : `${Math.round(mins / 60)} 小时前`,
569+ mins < 1
570+ ? "刚刚"
571+ : mins < 60
572+ ? `${mins} 分钟前`
573+ : `${Math.round(mins / 60)} 小时前`,
570574 derivedRun: "现在跑一遍",
571575 derivedRunning: "推理中…",
572576 derivedNoChange: "没有变化。",
@@ -674,7 +678,8 @@
674678 defaultChip: "默认",
675679 newKb: "新建知识库",
676680 packsLabel: "预置本体",
677- packsHint: "可不选。包里的谓语带方向声明,主宾颠倒进不来。之后还能再导入。",
681+ packsHint:
682+ "可不选。包里的谓语带方向声明,主宾颠倒进不来。之后还能再导入。",
678683 packsNone: "不选 —— 从十个种子关系起步",
679684 packsCount: (c: number, p: number) => `${c} 个类 · ${p} 个属性`,
680685 name: "名称",
@@ -850,7 +855,8 @@
850855 "抽取器产出了这些,但它们不在你的本体里(于是降级成了 concept / related to)。它们是扩展本体的信号。",
851856 dismiss: "忽略",
852857 dismissed: (n: number) => `已忽略(${n})`,
853- dismissedHint: "仍在计数,只是不进建议。如果某一个在你忽略之后涨了,可以撤回。",
858+ dismissedHint:
859+ "仍在计数,只是不进建议。如果某一个在你忽略之后涨了,可以撤回。",
854860 restore: "撤回忽略",
855861 suggest: "用 AI 建议",
856862 suggesting: "分析中…",
@@ -884,6 +890,64 @@
884890 proposals: "AI 提案",
885891 keyHint: "小写下划线命名",
886892 },
893+ mapping: {
894+ title: "数据映射",
895+ hint: "业务概念在数据库里对应什么、怎么算。问数只按确认过的口径回答。",
896+ tabDefinitions: "口径",
897+ tabSources: "数据源",
898+ filterAll: "全部",
899+ filterProposed: "待审批",
900+ filterConfirmed: "已确认",
901+ filterRejected: "已拒绝",
902+ searchPlaceholder: "搜概念、数据源或表名…",
903+ total: (n: number) => `共 ${n} 条`,
904+ range: (from: number, to: number, total: number) =>
905+ `第 ${from}–${to} 条,共 ${total} 条`,
906+ prev: "上一页",
907+ next: "下一页",
908+ empty: "还没有口径。挂上数据源后点「探查映射」,让智能体先提一批。",
909+ emptyFiltered: "没有符合条件的口径。",
910+ rejectedHint:
911+ "拒绝过的也列在这里——否则「这个概念为什么没被映射」永远答不上来。",
912+ colConcept: "概念",
913+ colSource: "数据源",
914+ colDefinition: "怎么算",
915+ colStatus: "状态",
916+ derivedBadge: "派生",
917+ noDefinition: "(未填)",
918+ approve: "确认",
919+ reject: "拒绝",
920+ edit: "编辑",
921+ editTitle: "改口径",
922+ fieldTable: "表",
923+ fieldExpr: "表达式",
924+ fieldSql: "SQL",
925+ fieldUnit: "单位",
926+ fieldSummary: "说明",
927+ fieldDerived: "派生指标(算出来的,不是表里的列)",
928+ save: "保存",
929+ cancel: "取消",
930+ needOne: "表、表达式、SQL 至少填一个。",
931+ history: "改版历史",
932+ historyHint:
933+ "改之前那一版的整版快照。留着是为了答得出「上季度这个数是怎么算的」。",
934+ historyEmpty: "还没有改过。",
935+ historyBy: (who: string) => `由 ${who} 修改`,
936+ historyUnknown: "一位已移除的用户",
937+ sourcesHint:
938+ "已挂载的只读数据库。挂载会摄入库表结构,问数写 SQL 前才知道有哪些表。",
939+ mount: "挂载",
940+ unmount: "卸载",
941+ syncSchema: "刷新结构",
942+ schemaSynced: (n: number) => `结构已摄入(${n} 张表)`,
943+ explore: "探查映射",
944+ exploreHint:
945+ "一个智能体读这些库表结构,提出指标/维度的口径。提出来的落在「待审批」,确认之后问数才会用。",
946+ exploreQueued: "探查已排队——提案稍后出现在「待审批」。",
947+ sourcesEmpty: "没有挂载任何数据源。",
948+ sourcesNoneAvailable: "还没有登记数据源——请部署管理员登记一个。",
949+ newConn: "登记新连接",
950+ },
887951 review: {
888952 title: "审阅",
889953 hint: "重复项与低置信度事实",
@@ -895,7 +959,7 @@
895959 railConflicts: "冲突",
896960 railUnconfirmed: "未确认",
897961 railLowConfidence: "低置信度",
898- railMappings: "语义层",
962+ railMappings: "数据映射",
899963 railViolations: "公理",
900964 railDefects: "本体",
901965 railDecisions: "决定",
@@ -980,7 +1044,7 @@
9801044 * 一条会让人以为界面漏了东西 */
9811045 checkNothingNew: "没有新的",
9821046 checkClean: (n: number) => `查了 ${n} 条事实,没有矛盾`,
983- mappings: "语义层",
1047+ mappings: "数据映射",
9841048 mappingsHint:
9851049 "从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",
9861050 mappingDerived: "派生",
modified web/src/pages/KbSettings.tsx +26 −186
@@ -6,10 +6,8 @@
66 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
77 import { useNavigate, useSearch } from "@tanstack/react-router";
88 import {
9- Database,
109 History as HistoryIcon,
1110 Lock,
12- Plus,
1311 Settings2,
1412 TriangleAlert,
1513 Users,
@@ -46,7 +44,7 @@
4644 return isOpen ? KB_ROLES.filter((r) => r.value !== "viewer") : KB_ROLES;
4745 }
4846
49-type Section = "general" | "members" | "data" | "activity" | "danger";
47+type Section = "general" | "members" | "activity" | "danger";
5048
5149 export function KbSettings() {
5250 const navigate = useNavigate();
@@ -138,7 +136,6 @@
138136 }[] = [
139137 { key: "general", label: S.kbset.general, Icon: Settings2 },
140138 { key: "members", label: S.kbset.members, Icon: Users },
141- { key: "data", label: S.kbset.data, Icon: Database },
142139 { key: "activity", label: S.kbset.activity, Icon: HistoryIcon },
143140 // 默认库不可删除:danger 节整个不出现
144141 ...(isDefault
@@ -345,7 +342,6 @@
345342 {section === "members" && (
346343 <KbMembers kbId={kbId} isOpen={kb.data.visibility === "open"} />
347344 )}
348- {section === "data" && <KbDataSources kbId={kbId} />}
349345
350346 {section === "activity" && <KbActivity kbId={kbId} />}
351347
@@ -513,161 +509,7 @@
513509 ))}
514510 </div>
515511 )}
516- <Pager
517- total={total}
518- pageSize={AUDIT_PAGE}
519- page={page}
520- onPage={setPage}
521- />
522- </div>
523- );
524-}
525-
526-/** 知识库层数据源挂载:从系统已注册的源里挑选;挂载即摄取 schema。
527- 注册新连接是部署级动作:管理员从这里深链去 Deployment settings 的 Data sources。 */
528-function KbDataSources({ kbId }: { kbId: string }) {
529- const queryClient = useQueryClient();
530- const navigate = useNavigate();
531- const me = useQuery({ queryKey: ["me"], queryFn: api.me });
532- const mounted = useQuery({
533- queryKey: ["kbDataSources", kbId],
534- queryFn: () => api.kbDataSources(kbId),
535- });
536- const available = useQuery({
537- queryKey: ["kbDataSourcesAvail", kbId],
538- queryFn: () => api.kbDataSourcesAvailable(kbId),
539- });
540- const [picked, setPicked] = useState("");
541- const [notice, setNotice] = useState<string | null>(null);
542- const invalidate = () =>
543- queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
544-
545- const mount = useMutation({
546- mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
547- onSuccess: (r) => {
548- setPicked("");
549- setNotice(S.kbset.dataSchemaSynced(r.schema_tables));
550- invalidate();
551- },
552- });
553- const unmount = useMutation({
554- mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),
555- onSettled: invalidate,
556- });
557- const sync = useMutation({
558- mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),
559- onSuccess: (r) => setNotice(S.kbset.dataSchemaSynced(r.schema_tables)),
560- });
561- const explore = useMutation({
562- mutationFn: () => api.exploreMappings(kbId),
563- onSuccess: () => setNotice(S.kbset.dataExploreQueued),
564- });
565-
566- const mountedIds = new Set(
567- (mounted.data?.data_sources ?? []).map((d) => d.id),
568- );
569- const mountable = (available.data?.data_sources ?? []).filter(
570- (d) => !mountedIds.has(d.id),
571- );
572-
573- return (
574- <div className="space-y-4">
575- <p className="text-xs text-neutral-500">{S.kbset.dataHint}</p>
576-
577- <div className="glass rounded-xl divide-y divide-white/5">
578- {(mounted.data?.data_sources ?? []).map((d) => (
579- <div key={d.id} className="px-4 py-3 flex items-center gap-3">
580- <div className="min-w-0 flex-1">
581- <div className="text-sm text-neutral-200">{d.name}</div>
582- <div className="text-xs text-neutral-500 font-mono truncate">
583- {d.summary}
584- </div>
585- </div>
586- <button
587- className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
588- disabled={sync.isPending}
589- onClick={() => sync.mutate(d.id)}
590- >
591- {S.kbset.dataSyncSchema}
592- </button>
593- <button
594- className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
595- disabled={unmount.isPending}
596- onClick={() => unmount.mutate(d.id)}
597- >
598- {S.kbset.dataUnmount}
599- </button>
600- </div>
601- ))}
602- {mounted.data?.data_sources.length === 0 && (
603- <p className="px-4 py-6 text-sm text-neutral-500">
604- {S.kbset.dataNone}
605- </p>
606- )}
607- </div>
608-
609- {mountable.length > 0 && (
610- <div className="flex items-center gap-2">
611- <SearchSelect
612- className="flex-1"
613- value={picked}
614- options={mountable.map((d) => ({
615- value: d.id,
616- label: d.name,
617- hint: d.summary,
618- }))}
619- onChange={setPicked}
620- placeholder={S.kbset.dataMount + "…"}
621- />
622- <button
623- className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"
624- disabled={!picked || mount.isPending}
625- onClick={() => mount.mutate(picked)}
626- >
627- {S.kbset.dataMount}
628- </button>
629- </div>
630- )}
631- {/* 连接注册在部署层:管理员给直达入口,其他人指路找管理员 */}
632- {me.data?.is_admin ? (
633- <button
634- className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
635- onClick={() =>
636- navigate({ to: "/admin", search: { tab: "datasources" } })
637- }
638- >
639- <Plus size={12} />
640- {S.kbset.dataNewConn}
641- </button>
642- ) : (
643- mountable.length === 0 &&
644- available.data &&
645- (mounted.data?.data_sources.length ?? 0) === 0 && (
646- <p className="text-xs text-neutral-600">
647- {S.kbset.dataNoneAvailable}
648- </p>
649- )
650- )}
651- {(mounted.data?.data_sources.length ?? 0) > 0 && (
652- <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
653- <p className="text-xs text-neutral-500 flex-1">
654- {S.kbset.dataExploreHint}
655- </p>
656- <button
657- className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
658- disabled={explore.isPending}
659- onClick={() => explore.mutate()}
660- >
661- {S.kbset.dataExplore}
662- </button>
663- </div>
664- )}
665- {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}
666- {(mount.isError || sync.isError || explore.isError) && (
667- <p className="text-xs text-rose-400">
668- {((mount.error ?? sync.error ?? explore.error) as Error).message}
669- </p>
670- )}
512+ <Pager total={total} pageSize={AUDIT_PAGE} page={page} onPage={setPage} />
671513 </div>
672514 );
673515 }
@@ -751,32 +593,30 @@
751593 功能坏了,而不是"没人可加"。空列表由 SearchSelect 自己说
752594 (它有 noMatches 空态),这里不必再加一句话 */}
753595 <div className="mt-3 flex gap-2 items-center border-t border-white/5 pt-3">
754- <SearchSelect
755- className="flex-1"
756- value={addUserId}
757- onChange={setAddUserId}
758- placeholder={S.kbset.addMember}
759- options={addable.map((u) => ({
760- value: u.id,
761- label: u.display_name,
762- hint: u.email,
763- }))}
764- />
765- <Dropdown
766- className="w-24"
767- value={addRole}
768- onChange={setAddRole}
769- options={rolesFor(isOpen)}
770- />
771- <button
772- className="u-btn u-btn-primary px-3 py-1.5 text-xs"
773- disabled={!addUserId || setMember.isPending}
774- onClick={() =>
775- setMember.mutate({ userId: addUserId, role: addRole })
776- }
777- >
778- {S.members.add}
779- </button>
596+ <SearchSelect
597+ className="flex-1"
598+ value={addUserId}
599+ onChange={setAddUserId}
600+ placeholder={S.kbset.addMember}
601+ options={addable.map((u) => ({
602+ value: u.id,
603+ label: u.display_name,
604+ hint: u.email,
605+ }))}
606+ />
607+ <Dropdown
608+ className="w-24"
609+ value={addRole}
610+ onChange={setAddRole}
611+ options={rolesFor(isOpen)}
612+ />
613+ <button
614+ className="u-btn u-btn-primary px-3 py-1.5 text-xs"
615+ disabled={!addUserId || setMember.isPending}
616+ onClick={() => setMember.mutate({ userId: addUserId, role: addRole })}
617+ >
618+ {S.members.add}
619+ </button>
780620 </div>
781621 </div>
782622 );
added web/src/pages/Mappings.tsx +587 −0
@@ -0,0 +1,587 @@
1+// 数据映射:业务概念在数据库里对应什么、怎么算。
2+//
3+// **这一页在此之前不存在**,而它管的东西一直都在:口径由探查任务提出、在
4+// 「审阅」里被确认,然后沉进问数的 system prompt——人再也看不见它,也改不动。
5+// `mappings::revise` 连同它的留痕表从建表起就是零调用的。
6+//
7+// 审批留在同一个端点上(`review/mappings/{id}`,那里已经在写审计流水),
8+// 搬的是界面不是逻辑:判断一条口径对不对要看得见表结构,而那在这一页。
9+import { useState } from "react";
10+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
11+import { Database, History, Pencil, Plus } from "lucide-react";
12+import { useNavigate } from "@tanstack/react-router";
13+import { api, type ConceptMapping } from "../api";
14+import { S } from "../i18n";
15+import { useKb } from "../kb";
16+import { toast } from "../toast";
17+import {
18+ Chip,
19+ type ChipTone,
20+ EmptyState,
21+ ErrorText,
22+ Loading,
23+ Pager,
24+ PageTitle,
25+ SearchSelect,
26+ cn,
27+} from "../ui";
28+
29+const PAGE = 25;
30+
31+type StatusFilter = "all" | "proposed" | "confirmed" | "rejected";
32+
33+const TONE: Record<string, ChipTone> = {
34+ proposed: "warn",
35+ confirmed: "success",
36+ rejected: "neutral",
37+};
38+
39+/** 「这个数怎么算」。SQL / 表达式 / 表名按这个优先级取一个——
40+ * 三者都在回答同一个问题,而 SQL 最具体、表名最粗 */
41+const howComputed = (m: ConceptMapping) =>
42+ m.sql ?? m.expr ?? m.table_name ?? null;
43+
44+const statusLabel = (s: string) =>
45+ s === "proposed"
46+ ? S.mapping.filterProposed
47+ : s === "confirmed"
48+ ? S.mapping.filterConfirmed
49+ : S.mapping.filterRejected;
50+
51+export function Mappings() {
52+ const { kb } = useKb();
53+ const queryClient = useQueryClient();
54+ const [tab, setTab] = useState<"definitions" | "sources">("definitions");
55+ const [status, setStatus] = useState<StatusFilter>("all");
56+ const [q, setQ] = useState("");
57+ const [page, setPage] = useState(0);
58+
59+ const data = useQuery({
60+ queryKey: ["mappings", kb?.id, status, q, page],
61+ queryFn: () =>
62+ api.mappings(kb!.id, {
63+ status: status === "all" ? undefined : status,
64+ q: q || undefined,
65+ limit: PAGE,
66+ offset: page * PAGE,
67+ }),
68+ enabled: !!kb,
69+ });
70+
71+ const refresh = () =>
72+ queryClient.invalidateQueries({ queryKey: ["mappings", kb?.id] });
73+
74+ if (!kb) return <Loading>{S.nav.loading}</Loading>;
75+
76+ const counts = data.data?.counts;
77+ const FILTERS: { key: StatusFilter; label: string; n?: number }[] = [
78+ { key: "all", label: S.mapping.filterAll },
79+ { key: "proposed", label: S.mapping.filterProposed, n: counts?.proposed },
80+ {
81+ key: "confirmed",
82+ label: S.mapping.filterConfirmed,
83+ n: counts?.confirmed,
84+ },
85+ { key: "rejected", label: S.mapping.filterRejected, n: counts?.rejected },
86+ ];
87+
88+ return (
89+ <div className="p-6 max-w-4xl mx-auto space-y-4">
90+ <div>
91+ <PageTitle>{S.mapping.title}</PageTitle>
92+ <p className="mt-1 text-xs text-neutral-500">{S.mapping.hint}</p>
93+ </div>
94+
95+ <div className="flex gap-1.5">
96+ {(["definitions", "sources"] as const).map((t) => (
97+ <button
98+ key={t}
99+ className={cn(
100+ "u-btn px-3 py-1 text-xs",
101+ tab === t && "u-btn-primary",
102+ )}
103+ onClick={() => setTab(t)}
104+ >
105+ {t === "definitions"
106+ ? S.mapping.tabDefinitions
107+ : S.mapping.tabSources}
108+ </button>
109+ ))}
110+ </div>
111+
112+ {tab === "sources" ? (
113+ <DataSources kbId={kb.id} onExplored={refresh} />
114+ ) : (
115+ <>
116+ <div className="flex items-center gap-2 flex-wrap">
117+ {FILTERS.map((f) => (
118+ <button
119+ key={f.key}
120+ className={cn(
121+ "u-btn px-2.5 py-1 text-xs",
122+ status === f.key && "u-btn-primary",
123+ )}
124+ onClick={() => {
125+ setStatus(f.key);
126+ setPage(0);
127+ }}
128+ >
129+ {f.label}
130+ {f.n != null && <span className="u-num ml-1.5">{f.n}</span>}
131+ </button>
132+ ))}
133+ <input
134+ className="u-input flex-1 min-w-40 px-3 py-1 text-xs"
135+ placeholder={S.mapping.searchPlaceholder}
136+ value={q}
137+ onChange={(e) => {
138+ setQ(e.target.value);
139+ setPage(0);
140+ }}
141+ />
142+ </div>
143+
144+ {status === "rejected" && (
145+ <p className="text-xs text-neutral-600">{S.mapping.rejectedHint}</p>
146+ )}
147+
148+ {data.isPending ? (
149+ <Loading>{S.nav.loading}</Loading>
150+ ) : data.data && data.data.items.length === 0 ? (
151+ <div className="py-12">
152+ <EmptyState icon={<Database size={20} />}>
153+ {q || status !== "all"
154+ ? S.mapping.emptyFiltered
155+ : S.mapping.empty}
156+ </EmptyState>
157+ </div>
158+ ) : (
159+ <div className="space-y-2">
160+ {data.data?.items.map((m) => (
161+ <MappingCard
162+ key={m.id}
163+ kbId={kb.id}
164+ mapping={m}
165+ onChanged={refresh}
166+ />
167+ ))}
168+ </div>
169+ )}
170+ <Pager
171+ total={data.data?.total ?? 0}
172+ pageSize={PAGE}
173+ page={page}
174+ onPage={setPage}
175+ />
176+ </>
177+ )}
178+ </div>
179+ );
180+}
181+
182+/** 一条口径。**未表态的才给确认/拒绝两个按钮**——已表过态的给「编辑」,
183+ * 因为改口径和第一次拍板是两件事:前者要留痕(revisions),后者不用。 */
184+function MappingCard({
185+ kbId,
186+ mapping: m,
187+ onChanged,
188+}: {
189+ kbId: string;
190+ mapping: ConceptMapping;
191+ onChanged: () => void;
192+}) {
193+ const [editing, setEditing] = useState(false);
194+ const [showHistory, setShowHistory] = useState(false);
195+
196+ const decide = useMutation({
197+ mutationFn: (s: "confirmed" | "rejected") =>
198+ api.decideMapping(kbId, m.id, s),
199+ onSuccess: onChanged,
200+ onError: (e: unknown) => toast.error((e as Error).message),
201+ });
202+
203+ const how = howComputed(m);
204+ return (
205+ <div className="glass rounded-xl p-3">
206+ <div className="flex items-baseline gap-2 flex-wrap">
207+ <span className="text-sm text-neutral-200">{m.concept_name}</span>
208+ <span className="text-[11px] text-neutral-500">{m.source}</span>
209+ {m.unit && (
210+ <span className="text-[11px] text-neutral-500">[{m.unit}]</span>
211+ )}
212+ {m.derived && (
213+ <Chip tone="warn" className="text-[11px]">
214+ {S.mapping.derivedBadge}
215+ </Chip>
216+ )}
217+ <span className="flex-1" />
218+ <Chip tone={TONE[m.status]} className="text-[11px]">
219+ {statusLabel(m.status)}
220+ </Chip>
221+ </div>
222+
223+ <div
224+ className={cn(
225+ "mt-1 u-num text-xs break-all",
226+ how ? "text-neutral-400" : "text-neutral-600",
227+ )}
228+ >
229+ {how ?? S.mapping.noDefinition}
230+ </div>
231+ {m.summary && (
232+ <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>
233+ )}
234+
235+ {editing ? (
236+ <EditForm
237+ kbId={kbId}
238+ mapping={m}
239+ onDone={() => {
240+ setEditing(false);
241+ onChanged();
242+ }}
243+ onCancel={() => setEditing(false)}
244+ />
245+ ) : (
246+ <div className="mt-2 flex items-center gap-1.5 flex-wrap">
247+ {m.status === "proposed" && (
248+ <>
249+ <button
250+ className="u-btn text-xs"
251+ disabled={decide.isPending}
252+ onClick={() => decide.mutate("rejected")}
253+ >
254+ {S.mapping.reject}
255+ </button>
256+ <button
257+ className="u-btn u-btn-primary text-xs"
258+ disabled={decide.isPending}
259+ onClick={() => decide.mutate("confirmed")}
260+ >
261+ {S.mapping.approve}
262+ </button>
263+ </>
264+ )}
265+ <button
266+ className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"
267+ onClick={() => setEditing(true)}
268+ >
269+ <Pencil size={11} />
270+ {S.mapping.edit}
271+ </button>
272+ <button
273+ className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"
274+ onClick={() => setShowHistory((v) => !v)}
275+ >
276+ <History size={11} />
277+ {S.mapping.history}
278+ </button>
279+ </div>
280+ )}
281+
282+ {showHistory && <RevisionList kbId={kbId} mappingId={m.id} />}
283+ </div>
284+ );
285+}
286+
287+function EditForm({
288+ kbId,
289+ mapping: m,
290+ onDone,
291+ onCancel,
292+}: {
293+ kbId: string;
294+ mapping: ConceptMapping;
295+ onDone: () => void;
296+ onCancel: () => void;
297+}) {
298+ const [table, setTable] = useState(m.table_name ?? "");
299+ const [expr, setExpr] = useState(m.expr ?? "");
300+ const [sql, setSql] = useState(m.sql ?? "");
301+ const [unit, setUnit] = useState(m.unit ?? "");
302+ const [summary, setSummary] = useState(m.summary ?? "");
303+ const [derived, setDerived] = useState(m.derived);
304+
305+ const save = useMutation({
306+ mutationFn: () =>
307+ api.reviseMapping(kbId, m.id, {
308+ table_name: table,
309+ expr,
310+ sql,
311+ unit,
312+ summary,
313+ derived,
314+ }),
315+ onSuccess: onDone,
316+ onError: (e: unknown) => toast.error((e as Error).message),
317+ });
318+
319+ const nothing = !table.trim() && !expr.trim() && !sql.trim();
320+ const field = (
321+ label: string,
322+ value: string,
323+ set: (v: string) => void,
324+ mono = false,
325+ ) => (
326+ <label className="block">
327+ <span className="text-[11px] text-neutral-500">{label}</span>
328+ <input
329+ className={cn(
330+ "u-input w-full px-2 py-1 text-xs mt-0.5",
331+ mono && "u-num",
332+ )}
333+ value={value}
334+ onChange={(e) => set(e.target.value)}
335+ />
336+ </label>
337+ );
338+
339+ return (
340+ <div className="mt-3 space-y-2 border-t border-white/5 pt-3">
341+ <p className="text-[11px] text-neutral-500">{S.mapping.editTitle}</p>
342+ <div className="grid grid-cols-2 gap-2">
343+ {field(S.mapping.fieldTable, table, setTable, true)}
344+ {field(S.mapping.fieldUnit, unit, setUnit)}
345+ </div>
346+ {field(S.mapping.fieldExpr, expr, setExpr, true)}
347+ {field(S.mapping.fieldSql, sql, setSql, true)}
348+ {field(S.mapping.fieldSummary, summary, setSummary)}
349+ <label className="flex items-center gap-2 text-xs text-neutral-400">
350+ <input
351+ type="checkbox"
352+ checked={derived}
353+ onChange={(e) => setDerived(e.target.checked)}
354+ />
355+ {S.mapping.fieldDerived}
356+ </label>
357+ {nothing && (
358+ <p className="text-xs text-[var(--u-danger)]">{S.mapping.needOne}</p>
359+ )}
360+ <div className="flex gap-1.5">
361+ <button className="u-btn text-xs" onClick={onCancel}>
362+ {S.mapping.cancel}
363+ </button>
364+ <button
365+ className="u-btn u-btn-primary text-xs"
366+ disabled={nothing || save.isPending}
367+ onClick={() => save.mutate()}
368+ >
369+ {S.mapping.save}
370+ </button>
371+ </div>
372+ </div>
373+ );
374+}
375+
376+/** 改版历史。**留痕表从建表起就没人读过**——0006 说留它是为了答得出
377+ * 「上季度这个数是怎么算的」,这里是那句话的兑现处。 */
378+function RevisionList({
379+ kbId,
380+ mappingId,
381+}: {
382+ kbId: string;
383+ mappingId: string;
384+}) {
385+ const revs = useQuery({
386+ queryKey: ["mappingRevisions", kbId, mappingId],
387+ queryFn: () => api.mappingRevisions(kbId, mappingId),
388+ });
389+
390+ if (revs.isPending) return <Loading>{S.nav.loading}</Loading>;
391+ // **取失败要说取失败。** `?? []` 会把一次 500 画成「还没改过」——
392+ // 一条改过口径的记录被说成从没改过,比报错难查得多
393+ if (revs.isError)
394+ return (
395+ <div className="mt-3 border-t border-white/5 pt-3">
396+ <ErrorText>{(revs.error as Error).message}</ErrorText>
397+ </div>
398+ );
399+ const list = revs.data?.revisions ?? [];
400+ return (
401+ <div className="mt-3 border-t border-white/5 pt-3 space-y-2">
402+ <p className="text-[11px] text-neutral-500">{S.mapping.historyHint}</p>
403+ {list.length === 0 ? (
404+ <p className="text-xs text-neutral-600">{S.mapping.historyEmpty}</p>
405+ ) : (
406+ list.map((r) => {
407+ const b = r.before;
408+ const was = (b.sql ?? b.expr ?? b.table_name) as string | null;
409+ return (
410+ <div key={r.id} className="text-xs">
411+ <div className="text-neutral-500">
412+ {S.mapping.historyBy(
413+ r.changed_by_name ?? S.mapping.historyUnknown,
414+ )}
415+ <span className="u-num ml-2 text-neutral-600">
416+ {r.changed_at.slice(0, 16).replace("T", " ")}
417+ </span>
418+ </div>
419+ <div className="u-num text-neutral-400 break-all">
420+ {was ?? S.mapping.noDefinition}
421+ </div>
422+ </div>
423+ );
424+ })
425+ )}
426+ </div>
427+ );
428+}
429+
430+/** 知识库层的数据源挂载。**从 KB 设置搬来的**——挂哪个库和口径怎么定,
431+ * 是同一件事的两半:不知道有哪些表,就判断不了口径对不对。
432+ * 注册新连接仍是部署级动作,管理员给直达入口,其他人指路找管理员。 */
433+function DataSources({
434+ kbId,
435+ onExplored,
436+}: {
437+ kbId: string;
438+ onExplored: () => void;
439+}) {
440+ const queryClient = useQueryClient();
441+ const navigate = useNavigate();
442+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
443+ const mounted = useQuery({
444+ queryKey: ["kbDataSources", kbId],
445+ queryFn: () => api.kbDataSources(kbId),
446+ });
447+ const available = useQuery({
448+ queryKey: ["kbDataSourcesAvail", kbId],
449+ queryFn: () => api.kbDataSourcesAvailable(kbId),
450+ });
451+ const [picked, setPicked] = useState("");
452+ const [notice, setNotice] = useState<string | null>(null);
453+ const invalidate = () =>
454+ queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
455+
456+ const mount = useMutation({
457+ mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
458+ onSuccess: (r) => {
459+ setPicked("");
460+ setNotice(S.mapping.schemaSynced(r.schema_tables));
461+ invalidate();
462+ },
463+ onError: (e: unknown) => toast.error((e as Error).message),
464+ });
465+ const unmount = useMutation({
466+ mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),
467+ onSettled: invalidate,
468+ });
469+ const sync = useMutation({
470+ mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),
471+ onSuccess: (r) => setNotice(S.mapping.schemaSynced(r.schema_tables)),
472+ onError: (e: unknown) => toast.error((e as Error).message),
473+ });
474+ const explore = useMutation({
475+ mutationFn: () => api.exploreMappings(kbId),
476+ onSuccess: () => {
477+ setNotice(S.mapping.exploreQueued);
478+ onExplored();
479+ },
480+ onError: (e: unknown) => toast.error((e as Error).message),
481+ });
482+
483+ const mountedIds = new Set(
484+ (mounted.data?.data_sources ?? []).map((d) => d.id),
485+ );
486+ const mountable = (available.data?.data_sources ?? []).filter(
487+ (d) => !mountedIds.has(d.id),
488+ );
489+ const hasMounted = (mounted.data?.data_sources.length ?? 0) > 0;
490+
491+ return (
492+ <div className="space-y-4">
493+ <p className="text-xs text-neutral-500">{S.mapping.sourcesHint}</p>
494+
495+ <div className="glass rounded-xl divide-y divide-white/5">
496+ {(mounted.data?.data_sources ?? []).map((d) => (
497+ <div key={d.id} className="px-4 py-3 flex items-center gap-3">
498+ <div className="min-w-0 flex-1">
499+ <div className="text-sm text-neutral-200">{d.name}</div>
500+ <div className="text-xs text-neutral-500 u-num truncate">
501+ {d.summary}
502+ </div>
503+ </div>
504+ <button
505+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
506+ disabled={sync.isPending}
507+ onClick={() => sync.mutate(d.id)}
508+ >
509+ {S.mapping.syncSchema}
510+ </button>
511+ <button
512+ className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
513+ disabled={unmount.isPending}
514+ onClick={() => unmount.mutate(d.id)}
515+ >
516+ {S.mapping.unmount}
517+ </button>
518+ </div>
519+ ))}
520+ {!hasMounted && (
521+ <p className="px-4 py-6 text-sm text-neutral-500">
522+ {S.mapping.sourcesEmpty}
523+ </p>
524+ )}
525+ </div>
526+
527+ {mountable.length > 0 && (
528+ <div className="flex items-center gap-2">
529+ <SearchSelect
530+ className="flex-1"
531+ value={picked}
532+ options={mountable.map((d) => ({
533+ value: d.id,
534+ label: d.name,
535+ hint: d.summary,
536+ }))}
537+ onChange={setPicked}
538+ placeholder={S.mapping.mount + "…"}
539+ />
540+ <button
541+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"
542+ disabled={!picked || mount.isPending}
543+ onClick={() => mount.mutate(picked)}
544+ >
545+ {S.mapping.mount}
546+ </button>
547+ </div>
548+ )}
549+
550+ {me.data?.is_admin ? (
551+ <button
552+ className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
553+ onClick={() =>
554+ navigate({ to: "/admin", search: { tab: "datasources" } })
555+ }
556+ >
557+ <Plus size={12} />
558+ {S.mapping.newConn}
559+ </button>
560+ ) : (
561+ mountable.length === 0 &&
562+ available.data &&
563+ !hasMounted && (
564+ <p className="text-xs text-neutral-600">
565+ {S.mapping.sourcesNoneAvailable}
566+ </p>
567+ )
568+ )}
569+
570+ {hasMounted && (
571+ <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
572+ <p className="text-xs text-neutral-500 flex-1">
573+ {S.mapping.exploreHint}
574+ </p>
575+ <button
576+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
577+ disabled={explore.isPending}
578+ onClick={() => explore.mutate()}
579+ >
580+ {S.mapping.explore}
581+ </button>
582+ </div>
583+ )}
584+ {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}
585+ </div>
586+ );
587+}
modified web/src/pages/Review.tsx +101 −164
@@ -1,11 +1,12 @@
11 import { useEffect, useState } from "react";
22 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3+import { useNavigate } from "@tanstack/react-router";
4+import { ArrowUpRight } from "lucide-react";
35 import {
46 api,
57 type AxiomViolation,
68 type ReviewQueue,
79 type OntologyDefect,
8- type ConceptMapping,
910 type ConflictItem,
1011 type FactReviewItem,
1112 type MergeLog,
@@ -55,7 +56,8 @@
5556 )}
5657 </div>
5758 <div className="text-xs text-neutral-500 mb-2">
58- {side.type_label ?? S.graph.untyped} · {S.review.factsCount(side.degree)}
59+ {side.type_label ?? S.graph.untyped} ·{" "}
60+ {S.review.factsCount(side.degree)}
5961 </div>
6062 {side.top_facts.length > 0 ? (
6163 <ul className="space-y-1">
@@ -145,7 +147,13 @@
145147 </span>
146148 <span className="text-xs text-neutral-500">
147149 —{" "}
148- <span className={fact.predicate_label === null ? "italic text-neutral-600" : undefined}>
150+ <span
151+ className={
152+ fact.predicate_label === null
153+ ? "italic text-neutral-600"
154+ : undefined
155+ }
156+ >
149157 {fact.predicate_label ?? S.graph.unknownPredicate}
150158 </span>{" "}
151159 →
@@ -299,7 +307,13 @@
299307 </span>
300308 <span className="text-xs text-neutral-500">
301309 —{" "}
302- <span className={fact.predicate_label === null ? "italic text-neutral-600" : undefined}>
310+ <span
311+ className={
312+ fact.predicate_label === null
313+ ? "italic text-neutral-600"
314+ : undefined
315+ }
316+ >
303317 {fact.predicate_label ?? S.graph.unknownPredicate}
304318 </span>{" "}
305319 →
@@ -441,8 +455,7 @@
441455 );
442456 }
443457
444-
445-/** 一条待表态的语义层映射(0011)。
458+/** 一条待表态的数据映射口径(0011)。
446459 *
447460 * 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,
448461 * 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
@@ -578,53 +591,6 @@
578591 );
579592 }
580593
581-function MappingRow({
582- mapping: m,
583- busy,
584- onDecide,
585-}: {
586- mapping: ConceptMapping;
587- busy: boolean;
588- onDecide: (status: "confirmed" | "rejected") => void;
589-}) {
590- const how = m.sql ?? m.expr ?? m.table_name ?? "—";
591- return (
592- <div className="glass rounded-xl p-3">
593- <div className="flex items-baseline gap-2 flex-wrap">
594- <span className="text-sm text-neutral-200">{m.concept_name}</span>
595- <span className="text-[11px] text-neutral-500">{m.source}</span>
596- {m.unit && (
597- <span className="text-[11px] text-neutral-500">[{m.unit}]</span>
598- )}
599- {m.derived && (
600- <span className="text-[11px] text-[var(--u-warn)]">
601- {S.review.mappingDerived}
602- </span>
603- )}
604- </div>
605- <div className="mt-1 u-num text-xs text-neutral-400 break-all">{how}</div>
606- {m.summary && (
607- <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>
608- )}
609- <div className="mt-2 flex gap-1.5">
610- <button
611- className="u-btn text-xs"
612- disabled={busy}
613- onClick={() => onDecide("rejected")}
614- >
615- {S.review.reject}
616- </button>
617- <button
618- className="u-btn u-btn-primary text-xs"
619- disabled={busy}
620- onClick={() => onDecide("confirmed")}
621- >
622- {S.review.confirm}
623- </button>
624- </div>
625- </div>
626- );
627-}
628594 /* ---------- 页面:左栏分类 + 单类内容区 ---------- */
629595
630596 type Sel =
@@ -632,9 +598,6 @@
632598 | "conflicts"
633599 | "unconfirmed"
634600 | "lowconf"
635- // 语义层的待表态映射(0011)。从前它借「低置信事实」那一档露面——
636- // 靠 0.6 的置信度混进去,而它根本不是一条关于世界的断言
637- | "mappings"
638601 // 公理违规(0002 R0)。**与 conflicts 分开**:那一档问「哪条对」,
639602 // 这一档还可能答「公理写错了」——出路不同
640603 | "violations"
@@ -649,7 +612,6 @@
649612 "conflicts",
650613 "unconfirmed",
651614 "lowconf",
652- "mappings",
653615 "violations",
654616 "defects",
655617 "merges",
@@ -660,7 +622,6 @@
660622 "conflicts",
661623 "unconfirmed",
662624 "lowconf",
663- "mappings",
664625 "violations",
665626 "defects",
666627 ];
@@ -669,7 +630,6 @@
669630 conflicts: CONFLICT_PAGE,
670631 unconfirmed: FACT_PAGE,
671632 lowconf: FACT_PAGE,
672- mappings: FACT_PAGE,
673633 violations: FACT_PAGE,
674634 defects: FACT_PAGE,
675635 merges: MERGE_PAGE,
@@ -689,11 +649,14 @@
689649 label,
690650 count,
691651 onClick,
652+ external,
692653 }: {
693654 active: boolean;
694655 label: string;
695656 count: number | null;
696657 onClick: () => void;
658+ /** 这一档不在本页办——加个去向记号,免得点下去以为页面没反应 */
659+ external?: boolean;
697660 }) {
698661 return (
699662 <button
@@ -706,6 +669,7 @@
706669 )}
707670 >
708671 <span className="truncate">{label}</span>
672+ {external && <ArrowUpRight size={11} className="shrink-0 opacity-50" />}
709673 {count !== null && (
710674 <span
711675 className={cn(
@@ -723,6 +687,7 @@
723687 export function Review() {
724688 const { kb } = useKb();
725689 const queryClient = useQueryClient();
690+ const navigate = useNavigate();
726691 const [sel, setSel] = useState<Sel | null>(null);
727692 const [page, setPage] = useState(0);
728693
@@ -738,7 +703,13 @@
738703 : "duplicates";
739704 const review = useQuery({
740705 queryKey: ["review", kb?.id, queueSel, page],
741- queryFn: () => api.review(kb!.id, queueSel, PAGE_SIZE[queueSel], page * PAGE_SIZE[queueSel]),
706+ queryFn: () =>
707+ api.review(
708+ kb!.id,
709+ queueSel,
710+ PAGE_SIZE[queueSel as Sel],
711+ page * PAGE_SIZE[queueSel as Sel],
712+ ),
742713 enabled: !!kb,
743714 // 翻页时别把上一页闪成空白——计数与骨架都还在,只有条目在换
744715 placeholderData: (prev) => prev,
@@ -774,16 +745,6 @@
774745 : api.rejectFact(kb!.id, id),
775746 onSettled: invalidate,
776747 });
777- const mappingAction = useMutation({
778- mutationFn: ({
779- id,
780- status,
781- }: {
782- id: string;
783- status: "confirmed" | "rejected";
784- }) => api.decideMapping(kb!.id, id, status),
785- onSettled: invalidate,
786- });
787748 const defectAction = useMutation({
788749 mutationFn: ({
789750 id,
@@ -836,7 +797,9 @@
836797 // **徽标读服务端的 COUNT,不读列表长度。** 这是从前那个「库里 164、界面写
837798 // 100」的根源:数组长度反映的是一页多少条,不是库里有多少条。
838799 const c = review.data?.counts;
839- const counts: Record<Sel, number> = {
800+ // mappings 不是本页的一档(审批在「数据映射」页),但计数照收:
801+ // 收件箱该说「有几条等你」
802+ const counts: Record<Sel | "mappings", number> = {
840803 duplicates: c?.duplicates ?? 0,
841804 conflicts: c?.conflicts ?? 0,
842805 unconfirmed: c?.unconfirmed ?? 0,
@@ -853,7 +816,6 @@
853816 const asDuplicates = () => rows as ReviewItem[];
854817 const asFacts = () => rows as FactReviewItem[];
855818 const asConflicts = () => rows as ConflictItem[];
856- const asMappings = () => rows as ConceptMapping[];
857819 const asViolations = () => rows as AxiomViolation[];
858820 const asDefects = () => rows as OntologyDefect[];
859821 const asMerges = () => rows as MergeLog[];
@@ -885,7 +847,6 @@
885847 title: S.review.lowConfidence,
886848 hint: S.review.lowConfidenceHint,
887849 },
888- mappings: { title: S.review.mappings, hint: S.review.mappingsHint },
889850 violations: {
890851 title: S.review.violations,
891852 hint: S.review.violationsHint,
@@ -925,11 +886,15 @@
925886 count={counts.lowconf}
926887 onClick={() => select("lowconf")}
927888 />
889+ {/* 口径审批搬去了「数据映射」页:判断一条口径对不对要看得见表结构,
890+ 而那在那一页。**计数留在这里**——收件箱该说「有几条等你」,
891+ 但活要在有上下文的地方干 */}
928892 <RailItem
929- active={active === "mappings"}
893+ active={false}
930894 label={S.review.railMappings}
931895 count={counts.mappings}
932- onClick={() => select("mappings")}
896+ onClick={() => navigate({ to: "/mappings" })}
897+ external
933898 />
934899 <RailItem
935900 active={active === "violations"}
@@ -989,10 +954,10 @@
989954 active !== "violations" &&
990955 active !== "defects" &&
991956 counts[active] === 0 && (
992- <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
993- {queueEmpty ? S.review.empty : S.review.categoryEmpty}
994- </div>
995- )}
957+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
958+ {queueEmpty ? S.review.empty : S.review.categoryEmpty}
959+ </div>
960+ )}
996961
997962 {active === "duplicates" && counts.duplicates > 0 && (
998963 <div className="space-y-3">
@@ -1013,46 +978,42 @@
1013978
1014979 {active === "conflicts" && counts.conflicts > 0 && (
1015980 <div className="space-y-3">
1016- {asConflicts().map(
1017- (c) => (
1018- <ConflictRow
1019- key={c.id}
1020- conflict={c}
1021- busy={
1022- conflictAction.isPending &&
1023- conflictAction.variables?.id === c.id
1024- }
1025- onResolve={(action, closeAt) =>
1026- conflictAction.mutate({ id: c.id, action, closeAt })
1027- }
1028- />
1029- ),
1030- )}
981+ {asConflicts().map((c) => (
982+ <ConflictRow
983+ key={c.id}
984+ conflict={c}
985+ busy={
986+ conflictAction.isPending &&
987+ conflictAction.variables?.id === c.id
988+ }
989+ onResolve={(action, closeAt) =>
990+ conflictAction.mutate({ id: c.id, action, closeAt })
991+ }
992+ />
993+ ))}
1031994 </div>
1032995 )}
1033996
1034997 {active === "unconfirmed" && counts.unconfirmed > 0 && (
1035998 <div className="space-y-3">
1036- {asFacts().map(
1037- (fact) => (
1038- <UnconfirmedRow
1039- key={fact.id}
1040- fact={fact}
1041- busy={
1042- (factAction.isPending &&
1043- factAction.variables?.id === fact.id) ||
1044- (closeFactAction.isPending &&
1045- closeFactAction.variables?.id === fact.id)
1046- }
1047- onReject={() =>
1048- factAction.mutate({ id: fact.id, action: "reject" })
1049- }
1050- onClose={(validTo) =>
1051- closeFactAction.mutate({ id: fact.id, validTo })
1052- }
1053- />
1054- ),
1055- )}
999+ {asFacts().map((fact) => (
1000+ <UnconfirmedRow
1001+ key={fact.id}
1002+ fact={fact}
1003+ busy={
1004+ (factAction.isPending &&
1005+ factAction.variables?.id === fact.id) ||
1006+ (closeFactAction.isPending &&
1007+ closeFactAction.variables?.id === fact.id)
1008+ }
1009+ onReject={() =>
1010+ factAction.mutate({ id: fact.id, action: "reject" })
1011+ }
1012+ onClose={(validTo) =>
1013+ closeFactAction.mutate({ id: fact.id, validTo })
1014+ }
1015+ />
1016+ ))}
10561017 </div>
10571018 )}
10581019
@@ -1077,26 +1038,6 @@
10771038 </div>
10781039 )}
10791040
1080- {active === "mappings" && counts.mappings > 0 && (
1081- <div className="space-y-3">
1082- {asMappings().map(
1083- (m) => (
1084- <MappingRow
1085- key={m.id}
1086- mapping={m}
1087- busy={
1088- mappingAction.isPending &&
1089- mappingAction.variables?.id === m.id
1090- }
1091- onDecide={(status) =>
1092- mappingAction.mutate({ id: m.id, status })
1093- }
1094- />
1095- ),
1096- )}
1097- </div>
1098- )}
1099-
11001041 {active === "defects" && (
11011042 <div className="space-y-3">
11021043 {counts.defects === 0 && (
@@ -1104,21 +1045,19 @@
11041045 {S.review.categoryEmpty}
11051046 </div>
11061047 )}
1107- {asDefects().map(
1108- (d) => (
1109- <DefectRow
1110- key={d.id}
1111- defect={d}
1112- busy={
1113- defectAction.isPending &&
1114- defectAction.variables?.id === d.id
1115- }
1116- onDecide={(resolution) =>
1117- defectAction.mutate({ id: d.id, resolution })
1118- }
1119- />
1120- ),
1121- )}
1048+ {asDefects().map((d) => (
1049+ <DefectRow
1050+ key={d.id}
1051+ defect={d}
1052+ busy={
1053+ defectAction.isPending &&
1054+ defectAction.variables?.id === d.id
1055+ }
1056+ onDecide={(resolution) =>
1057+ defectAction.mutate({ id: d.id, resolution })
1058+ }
1059+ />
1060+ ))}
11221061 </div>
11231062 )}
11241063
@@ -1156,21 +1095,19 @@
11561095 {S.review.checkNeverRun}
11571096 </div>
11581097 )}
1159- {asViolations().map(
1160- (v) => (
1161- <ViolationRow
1162- key={v.id}
1163- violation={v}
1164- busy={
1165- violationAction.isPending &&
1166- violationAction.variables?.id === v.id
1167- }
1168- onDecide={(resolution) =>
1169- violationAction.mutate({ id: v.id, resolution })
1170- }
1171- />
1172- ),
1173- )}
1098+ {asViolations().map((v) => (
1099+ <ViolationRow
1100+ key={v.id}
1101+ violation={v}
1102+ busy={
1103+ violationAction.isPending &&
1104+ violationAction.variables?.id === v.id
1105+ }
1106+ onDecide={(resolution) =>
1107+ violationAction.mutate({ id: v.id, resolution })
1108+ }
1109+ />
1110+ ))}
11741111 </div>
11751112 )}
11761113
modified web/src/pages/Shell.tsx +17 −4
@@ -1,8 +1,14 @@
11 import { useEffect } from "react";
22 import { useQuery } from "@tanstack/react-query";
3-import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
3+import {
4+ Link,
5+ Outlet,
6+ useNavigate,
7+ useRouterState,
8+} from "@tanstack/react-router";
49 import {
510 BookMarked,
11+ Database,
612 Library as LibraryIcon,
713 ListChecks,
814 MessagesSquare,
@@ -30,6 +36,8 @@
3036 { to: "/library", label: S.nav.library, Icon: LibraryIcon },
3137 { to: "/review", label: S.review.title, Icon: ListChecks },
3238 { to: "/ontology", label: S.ontology.title, Icon: Shapes },
39+ // 本体说「世界上有什么」,数据映射说「这个数在库里怎么算」——挨着放
40+ { to: "/mappings", label: S.mapping.title, Icon: Database },
3341 // 库设置与其它 tab 同为"当前知识库作用域",并列于内容导航
3442 { to: "/kb-settings", label: S.nav.settings, Icon: SettingsIcon },
3543 ] as const;
@@ -38,7 +46,11 @@
3846 const navigate = useNavigate();
3947
4048 const me = useQuery({ queryKey: ["me"], queryFn: api.me });
41- const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });
49+ const health = useQuery({
50+ queryKey: ["health"],
51+ queryFn: api.health,
52+ staleTime: Infinity,
53+ });
4254 const { kb, kbs, setKb } = useKb();
4355 // 标题跟随当前 tab:`Graph · Utopia`;文档查看页归入 Library
4456 const pathname = useRouterState({ select: (s) => s.location.pathname });
@@ -122,7 +134,9 @@
122134 >
123135 <GithubMark size={13} />
124136 {health.data && (
125- <span className="u-num text-[11px]">v{health.data.version}</span>
137+ <span className="u-num text-[11px]">
138+ v{health.data.version}
139+ </span>
126140 )}
127141 </a>
128142 </div>
@@ -158,4 +172,3 @@
158172 </div>
159173 );
160174 }
161-
modified web/src/router.tsx +8 −0
@@ -17,6 +17,7 @@
1717 import { MyKbs } from "./pages/MyKbs";
1818 import { NotFound } from "./pages/ServerDown";
1919 import { Ontology } from "./pages/Ontology";
20+import { Mappings } from "./pages/Mappings";
2021 import { Review } from "./pages/Review";
2122 import { Search } from "./pages/Search";
2223 import { Settings } from "./pages/Settings";
@@ -111,6 +112,12 @@
111112 component: Ontology,
112113 });
113114
115+const mappingsRoute = createRoute({
116+ getParentRoute: () => appRoute,
117+ path: "/mappings",
118+ component: Mappings,
119+});
120+
114121 const reviewRoute = createRoute({
115122 getParentRoute: () => appRoute,
116123 path: "/review",
@@ -205,6 +212,7 @@
205212 libraryRoute,
206213 reviewRoute,
207214 ontologyRoute,
215+ mappingsRoute,
208216 kbSettingsRoute,
209217 ]),
210218 ]);