Elffuss BraidHub

kikocis/utopia public

dev · 19.8 KiBRawPermalink
1// 数据映射:业务概念在数据库里对应什么、怎么算。
2//
3// **这一页在此之前不存在**,而它管的东西一直都在:口径由探查任务提出、在
4// 「审阅」里被确认,然后沉进问数的 system prompt——人再也看不见它,也改不动。
5// `mappings::revise` 连同它的留痕表从建表起就是零调用的。
6//
7// 审批留在同一个端点上(`review/mappings/{id}`,那里已经在写审计流水),
8// 搬的是界面不是逻辑:判断一条口径对不对要看得见表结构,而那在这一页。
9import { useState } from "react";
10import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
11import { Database, History, Pencil, Plus } from "lucide-react";
12import { useNavigate } from "@tanstack/react-router";
13import { api, type ConceptMapping } from "../api";
14import { S } from "../i18n";
15import { useKb } from "../kb";
16import { toast } from "../toast";
17import {
18 Chip,
19 type ChipTone,
20 EmptyState,
21 ErrorText,
22 Loading,
23 Pager,
24 PageTitle,
25 SearchSelect,
26 cn,
27} from "../ui";
28
29const PAGE = 25;
30
31type StatusFilter = "all" | "proposed" | "confirmed" | "rejected";
32
33const TONE: Record<string, ChipTone> = {
34 proposed: "warn",
35 confirmed: "success",
36 rejected: "neutral",
37};
38
39/** 「这个数怎么算」。SQL / 表达式 / 表名按这个优先级取一个——
40 * 三者都在回答同一个问题,而 SQL 最具体、表名最粗 */
41const howComputed = (m: ConceptMapping) =>
42 m.sql ?? m.expr ?? m.table_name ?? null;
43
44const statusLabel = (s: string) =>
45 s === "proposed"
46 ? S.mapping.filterProposed
47 : s === "confirmed"
48 ? S.mapping.filterConfirmed
49 : S.mapping.filterRejected;
50
51export 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 {/* 分段控件用全站那一套(`bg-white/10` 选中 + 静默的未选中),
96 不是 `u-btn-primary`——那是主操作的实心白,用在这里每个标签都像
97 一个行动号召 */}
98 <div className="flex w-fit rounded-lg overflow-hidden border border-white/10">
99 {(["definitions", "sources"] as const).map((t) => (
100 <button
101 key={t}
102 className={cn(
103 "px-3 py-1.5 text-xs transition-colors",
104 tab === t
105 ? "bg-white/10 text-neutral-100"
106 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300",
107 )}
108 onClick={() => setTab(t)}
109 >
110 {t === "definitions"
111 ? S.mapping.tabDefinitions
112 : S.mapping.tabSources}
113 </button>
114 ))}
115 </div>
116
117 {tab === "sources" ? (
118 <DataSources kbId={kb.id} onExplored={refresh} />
119 ) : (
120 <>
121 <div className="flex items-center gap-2 flex-wrap">
122 <div className="flex rounded-lg overflow-hidden border border-white/10">
123 {FILTERS.map((f) => (
124 <button
125 key={f.key}
126 className={cn(
127 "px-2.5 py-1.5 text-xs transition-colors flex items-center gap-1.5",
128 status === f.key
129 ? "bg-white/10 text-neutral-100"
130 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300",
131 )}
132 onClick={() => {
133 setStatus(f.key);
134 setPage(0);
135 }}
136 >
137 {f.label}
138 {f.n != null && (
139 <span
140 className={cn(
141 "u-num",
142 status === f.key
143 ? "text-neutral-300"
144 : "text-neutral-600",
145 )}
146 >
147 {f.n}
148 </span>
149 )}
150 </button>
151 ))}
152 </div>
153 <input
154 className="u-input flex-1 min-w-40 px-3 py-1 text-xs"
155 placeholder={S.mapping.searchPlaceholder}
156 value={q}
157 onChange={(e) => {
158 setQ(e.target.value);
159 setPage(0);
160 }}
161 />
162 </div>
163
164 {status === "rejected" && (
165 <p className="text-xs text-neutral-600">{S.mapping.rejectedHint}</p>
166 )}
167
168 {data.isPending ? (
169 <Loading>{S.nav.loading}</Loading>
170 ) : data.data && data.data.items.length === 0 ? (
171 <div className="py-12">
172 <EmptyState icon={<Database size={20} />}>
173 {q || status !== "all"
174 ? S.mapping.emptyFiltered
175 : S.mapping.empty}
176 </EmptyState>
177 </div>
178 ) : (
179 <div className="space-y-2">
180 {data.data?.items.map((m) => (
181 <MappingCard
182 key={m.id}
183 kbId={kb.id}
184 mapping={m}
185 onChanged={refresh}
186 />
187 ))}
188 </div>
189 )}
190 <Pager
191 total={data.data?.total ?? 0}
192 pageSize={PAGE}
193 page={page}
194 onPage={setPage}
195 />
196 </>
197 )}
198 </div>
199 );
200}
201
202/** 一条口径。**未表态的才给确认/拒绝两个按钮**——已表过态的给「编辑」,
203 * 因为改口径和第一次拍板是两件事:前者要留痕(revisions),后者不用。 */
204function MappingCard({
205 kbId,
206 mapping: m,
207 onChanged,
208}: {
209 kbId: string;
210 mapping: ConceptMapping;
211 onChanged: () => void;
212}) {
213 const [editing, setEditing] = useState(false);
214 const [showHistory, setShowHistory] = useState(false);
215
216 const decide = useMutation({
217 mutationFn: (s: "confirmed" | "rejected") =>
218 api.decideMapping(kbId, m.id, s),
219 onSuccess: onChanged,
220 onError: (e: unknown) => toast.error((e as Error).message),
221 });
222
223 const how = howComputed(m);
224 return (
225 <div className="glass rounded-xl p-3">
226 <div className="flex items-baseline gap-2 flex-wrap">
227 <span className="text-sm text-neutral-200">{m.concept_name}</span>
228 <span className="text-[11px] text-neutral-500">{m.source}</span>
229 {m.unit && (
230 <span className="text-[11px] text-neutral-500">[{m.unit}]</span>
231 )}
232 {m.derived && (
233 <Chip tone="warn" className="text-[11px]">
234 {S.mapping.derivedBadge}
235 </Chip>
236 )}
237 <span className="flex-1" />
238 <Chip tone={TONE[m.status]} className="text-[11px]">
239 {statusLabel(m.status)}
240 </Chip>
241 </div>
242
243 <div
244 className={cn(
245 "mt-1 u-num text-xs break-all",
246 how ? "text-neutral-400" : "text-neutral-600",
247 )}
248 >
249 {how ?? S.mapping.noDefinition}
250 </div>
251 {m.summary && (
252 <p className="mt-1 text-xs text-neutral-500">{m.summary}</p>
253 )}
254
255 {editing ? (
256 <EditForm
257 kbId={kbId}
258 mapping={m}
259 onDone={() => {
260 setEditing(false);
261 onChanged();
262 }}
263 onCancel={() => setEditing(false)}
264 />
265 ) : (
266 <div className="mt-2 flex items-center gap-1.5 flex-wrap">
267 {m.status === "proposed" && (
268 <>
269 <button
270 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
271 disabled={decide.isPending}
272 onClick={() => decide.mutate("rejected")}
273 >
274 {S.mapping.reject}
275 </button>
276 <button
277 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
278 disabled={decide.isPending}
279 onClick={() => decide.mutate("confirmed")}
280 >
281 {S.mapping.approve}
282 </button>
283 </>
284 )}
285 <button
286 className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"
287 onClick={() => setEditing(true)}
288 >
289 <Pencil size={11} />
290 {S.mapping.edit}
291 </button>
292 <button
293 className="u-btn u-btn-ghost px-2 py-1 text-xs flex items-center gap-1"
294 onClick={() => setShowHistory((v) => !v)}
295 >
296 <History size={11} />
297 {S.mapping.history}
298 </button>
299 </div>
300 )}
301
302 {showHistory && <RevisionList kbId={kbId} mappingId={m.id} />}
303 </div>
304 );
305}
306
307function EditForm({
308 kbId,
309 mapping: m,
310 onDone,
311 onCancel,
312}: {
313 kbId: string;
314 mapping: ConceptMapping;
315 onDone: () => void;
316 onCancel: () => void;
317}) {
318 const [table, setTable] = useState(m.table_name ?? "");
319 const [expr, setExpr] = useState(m.expr ?? "");
320 const [sql, setSql] = useState(m.sql ?? "");
321 const [unit, setUnit] = useState(m.unit ?? "");
322 const [summary, setSummary] = useState(m.summary ?? "");
323 const [derived, setDerived] = useState(m.derived);
324
325 const save = useMutation({
326 mutationFn: () =>
327 api.reviseMapping(kbId, m.id, {
328 table_name: table,
329 expr,
330 sql,
331 unit,
332 summary,
333 derived,
334 }),
335 onSuccess: onDone,
336 onError: (e: unknown) => toast.error((e as Error).message),
337 });
338
339 const nothing = !table.trim() && !expr.trim() && !sql.trim();
340 const field = (
341 label: string,
342 value: string,
343 set: (v: string) => void,
344 mono = false,
345 ) => (
346 <label className="block">
347 <span className="text-[11px] text-neutral-500">{label}</span>
348 <input
349 className={cn(
350 "u-input w-full px-2 py-1 text-xs mt-0.5",
351 mono && "u-num",
352 )}
353 value={value}
354 onChange={(e) => set(e.target.value)}
355 />
356 </label>
357 );
358
359 return (
360 <div className="mt-3 space-y-2 border-t border-white/5 pt-3">
361 <p className="text-[11px] text-neutral-500">{S.mapping.editTitle}</p>
362 <div className="grid grid-cols-2 gap-2">
363 {field(S.mapping.fieldTable, table, setTable, true)}
364 {field(S.mapping.fieldUnit, unit, setUnit)}
365 </div>
366 {field(S.mapping.fieldExpr, expr, setExpr, true)}
367 {field(S.mapping.fieldSql, sql, setSql, true)}
368 {field(S.mapping.fieldSummary, summary, setSummary)}
369 <label className="flex items-center gap-2 text-xs text-neutral-400">
370 <input
371 type="checkbox"
372 checked={derived}
373 onChange={(e) => setDerived(e.target.checked)}
374 />
375 {S.mapping.fieldDerived}
376 </label>
377 {nothing && (
378 <p className="text-xs text-[var(--u-danger)]">{S.mapping.needOne}</p>
379 )}
380 <div className="flex gap-1.5">
381 <button
382 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
383 onClick={onCancel}
384 >
385 {S.mapping.cancel}
386 </button>
387 <button
388 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
389 disabled={nothing || save.isPending}
390 onClick={() => save.mutate()}
391 >
392 {S.mapping.save}
393 </button>
394 </div>
395 </div>
396 );
397}
398
399/** 改版历史。**留痕表从建表起就没人读过**——0006 说留它是为了答得出
400 * 「上季度这个数是怎么算的」,这里是那句话的兑现处。 */
401function RevisionList({
402 kbId,
403 mappingId,
404}: {
405 kbId: string;
406 mappingId: string;
407}) {
408 const revs = useQuery({
409 queryKey: ["mappingRevisions", kbId, mappingId],
410 queryFn: () => api.mappingRevisions(kbId, mappingId),
411 });
412
413 if (revs.isPending) return <Loading>{S.nav.loading}</Loading>;
414 // **取失败要说取失败。** `?? []` 会把一次 500 画成「还没改过」——
415 // 一条改过口径的记录被说成从没改过,比报错难查得多
416 if (revs.isError)
417 return (
418 <div className="mt-3 border-t border-white/5 pt-3">
419 <ErrorText>{(revs.error as Error).message}</ErrorText>
420 </div>
421 );
422 const list = revs.data?.revisions ?? [];
423 return (
424 <div className="mt-3 border-t border-white/5 pt-3 space-y-2">
425 <p className="text-[11px] text-neutral-500">{S.mapping.historyHint}</p>
426 {list.length === 0 ? (
427 <p className="text-xs text-neutral-600">{S.mapping.historyEmpty}</p>
428 ) : (
429 list.map((r) => {
430 const b = r.before;
431 const was = (b.sql ?? b.expr ?? b.table_name) as string | null;
432 return (
433 <div key={r.id} className="text-xs">
434 <div className="text-neutral-500">
435 {S.mapping.historyBy(
436 r.changed_by_name ?? S.mapping.historyUnknown,
437 )}
438 <span className="u-num ml-2 text-neutral-600">
439 {r.changed_at.slice(0, 16).replace("T", " ")}
440 </span>
441 </div>
442 <div className="u-num text-neutral-400 break-all">
443 {was ?? S.mapping.noDefinition}
444 </div>
445 </div>
446 );
447 })
448 )}
449 </div>
450 );
451}
452
453/** 知识库层的数据源挂载。**从 KB 设置搬来的**——挂哪个库和口径怎么定,
454 * 是同一件事的两半:不知道有哪些表,就判断不了口径对不对。
455 * 注册新连接仍是部署级动作,管理员给直达入口,其他人指路找管理员。 */
456function DataSources({
457 kbId,
458 onExplored,
459}: {
460 kbId: string;
461 onExplored: () => void;
462}) {
463 const queryClient = useQueryClient();
464 const navigate = useNavigate();
465 const me = useQuery({ queryKey: ["me"], queryFn: api.me });
466 const mounted = useQuery({
467 queryKey: ["kbDataSources", kbId],
468 queryFn: () => api.kbDataSources(kbId),
469 });
470 const available = useQuery({
471 queryKey: ["kbDataSourcesAvail", kbId],
472 queryFn: () => api.kbDataSourcesAvailable(kbId),
473 });
474 const [picked, setPicked] = useState("");
475 const [notice, setNotice] = useState<string | null>(null);
476 // 与 notice 分开:一个是「成了」,一个是「成了一半」,配色也不同
477 const [warning, setWarning] = useState<string | null>(null);
478 const invalidate = () =>
479 queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
480
481 const mount = useMutation({
482 mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
483 // **挂载成了、schema 没成,是两件事。** 服务端此时回的是 ok(源确实挂上了),
484 // 所以不能照着 `schema_tables: 0` 说「已摄入 0 张表」——那等于说成功了。
485 // 说清楚半成的是哪一半,同一件事也进了告警中心
486 onSuccess: (r) => {
487 setPicked("");
488 setNotice(null);
489 setWarning(r.schema_error ? S.mapping.schemaFailed : null);
490 if (!r.schema_error) setNotice(S.mapping.schemaSynced(r.schema_tables));
491 invalidate();
492 },
493 onError: (e: unknown) => toast.error((e as Error).message),
494 });
495 const unmount = useMutation({
496 mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),
497 onSettled: invalidate,
498 });
499 const sync = useMutation({
500 mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),
501 onSuccess: (r) => setNotice(S.mapping.schemaSynced(r.schema_tables)),
502 onError: (e: unknown) => toast.error((e as Error).message),
503 });
504 const explore = useMutation({
505 mutationFn: () => api.exploreMappings(kbId),
506 onSuccess: () => {
507 setNotice(S.mapping.exploreQueued);
508 onExplored();
509 },
510 onError: (e: unknown) => toast.error((e as Error).message),
511 });
512
513 const mountedIds = new Set(
514 (mounted.data?.data_sources ?? []).map((d) => d.id),
515 );
516 const mountable = (available.data?.data_sources ?? []).filter(
517 (d) => !mountedIds.has(d.id),
518 );
519 const hasMounted = (mounted.data?.data_sources.length ?? 0) > 0;
520
521 return (
522 <div className="space-y-4">
523 <p className="text-xs text-neutral-500">{S.mapping.sourcesHint}</p>
524
525 <div className="glass rounded-xl divide-y divide-white/5">
526 {(mounted.data?.data_sources ?? []).map((d) => (
527 <div key={d.id} className="px-4 py-3 flex items-center gap-3">
528 <div className="min-w-0 flex-1">
529 <div className="text-sm text-neutral-200">{d.name}</div>
530 <div className="text-xs text-neutral-500 u-num truncate">
531 {d.summary}
532 </div>
533 </div>
534 <button
535 className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
536 disabled={sync.isPending}
537 onClick={() => sync.mutate(d.id)}
538 >
539 {S.mapping.syncSchema}
540 </button>
541 <button
542 className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
543 disabled={unmount.isPending}
544 onClick={() => unmount.mutate(d.id)}
545 >
546 {S.mapping.unmount}
547 </button>
548 </div>
549 ))}
550 {!hasMounted && (
551 <p className="px-4 py-6 text-sm text-neutral-500">
552 {S.mapping.sourcesEmpty}
553 </p>
554 )}
555 </div>
556
557 {mountable.length > 0 && (
558 <div className="flex items-center gap-2">
559 <SearchSelect
560 className="flex-1"
561 value={picked}
562 options={mountable.map((d) => ({
563 value: d.id,
564 label: d.name,
565 hint: d.summary,
566 }))}
567 onChange={setPicked}
568 placeholder={S.mapping.mount + "…"}
569 />
570 <button
571 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"
572 disabled={!picked || mount.isPending}
573 onClick={() => mount.mutate(picked)}
574 >
575 {S.mapping.mount}
576 </button>
577 </div>
578 )}
579
580 {me.data?.is_admin ? (
581 <button
582 className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
583 onClick={() =>
584 navigate({ to: "/admin", search: { tab: "datasources" } })
585 }
586 >
587 <Plus size={12} />
588 {S.mapping.newConn}
589 </button>
590 ) : (
591 mountable.length === 0 &&
592 available.data &&
593 !hasMounted && (
594 <p className="text-xs text-neutral-600">
595 {S.mapping.sourcesNoneAvailable}
596 </p>
597 )
598 )}
599
600 {hasMounted && (
601 <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
602 <p className="text-xs text-neutral-500 flex-1">
603 {S.mapping.exploreHint}
604 </p>
605 <button
606 className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
607 disabled={explore.isPending}
608 onClick={() => explore.mutate()}
609 >
610 {S.mapping.explore}
611 </button>
612 </div>
613 )}
614 {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}
615 {warning && <p className="text-xs text-[var(--u-warn)]">{warning}</p>}
616 </div>
617 );
618}