BindingEditor.tsx
9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { Database, Play, Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Badge, Field, Spinner } from "@/components/ui";
import { api } from "@/lib/api";
import { errText, onto, type Binding, type Concept } from "@/lib/onto";
import type { DataSource, SmModel } from "@/lib/types";
import { promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
import { DataTable } from "../ask/AskAnswer";
// 只有对象、关系、聚合函数需要绑定数据
const TARGET: Record<string, string> = { object_type: "table", function: "metric_expr", link_type: "join" };
/**
* 数据绑定:把概念落到某个数据源的表/列/表达式上。一个概念可以在多个数据源各绑一条。
* 下拉里的表和列来自数据源内省结果,不用手敲物理名。
*/
export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concept; canEdit: boolean; onChanged: () => void }) {
const kind = TARGET[concept.kind];
const [dss, setDss] = useState<DataSource[]>([]);
const [dsId, setDsId] = useState<number>(concept.bindings[0]?.ds_id || 0);
const [models, setModels] = useState<SmModel[]>([]);
const existing = concept.bindings.find((b) => b.ds_id === dsId && b.target_kind === kind);
const [ref, setRef] = useState<any>(existing?.ref || {});
const [busy, setBusy] = useState(false);
const [test, setTest] = useState<any>(null);
useEffect(() => {
void api.datasources().then((d) => { setDss(d); if (!dsId && d[0]) setDsId(d[0].id); }).catch(() => setDss([]));
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!dsId) return;
void api.sqlModels(dsId, true).then(setModels).catch(() => setModels([]));
}, [dsId]);
useEffect(() => {
setRef(concept.bindings.find((b) => b.ds_id === dsId && b.target_kind === kind)?.ref || {});
setTest(null);
}, [concept.id, dsId]); // eslint-disable-line react-hooks/exhaustive-deps
const tableName = (m: SmModel) => m.physical_table || m.name;
const table = kind === "table" ? ref.table : ref.base_table;
const cols = useMemo(() => models.find((m) => tableName(m) === table)?.columns?.map((c: any) => c.physical_column || c.name) || [],
[models, table]);
if (!kind) return null;
const save = async () => {
setBusy(true);
try {
await onto.setBinding(concept.id, { ds_id: dsId, target_kind: kind, ref });
toast("ok", "绑定已保存", "进入草稿,发布本体后生效");
onChanged();
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
};
const remove = async (b: Binding) => {
await onto.deleteBinding(b.id);
onChanged();
};
const colSelect = (key: string, label: string, hint?: string) => (
<Field label={label} hint={hint}>
<select className="input" value={ref[key] || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, [key]: e.target.value })}>
<option value="">(不设置)</option>
{cols.map((c: string) => <option key={c}>{c}</option>)}
</select>
</Field>
);
const props: string[] = (concept.spec?.properties || []).map((p: any) => p.name);
return (
<div className="space-y-3">
<div className="flex flex-wrap items-end gap-3">
<Field label="数据源" className="w-56">
<select className="input" value={dsId} onChange={(e) => setDsId(Number(e.target.value))}>
{!dss.length && <option value={0}>还没有接入数据源</option>}
{dss.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
</select>
</Field>
{concept.bindings.map((b) => (
<Badge key={b.id} tone="bg-ok/10 text-ok">
<Database className="h-3 w-3" /> 数据源 {b.ds_id}:{b.ref.table || b.ref.base_table || `${b.ref.from_column}→${b.ref.to_column}`}
{canEdit && <button onClick={() => void remove(b)} title="删除绑定"><Trash2 className="h-3 w-3" /></button>}
</Badge>
))}
</div>
{kind !== "join" && (
<Field label={kind === "table" ? "对应的表" : "基表"}>
<select className="input" value={table || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, [kind === "table" ? "table" : "base_table"]: e.target.value })}>
<option value="">选择表</option>
{models.map((m) => <option key={m.id} value={tableName(m)}>{tableName(m)}{m.description ? ` · ${m.description.slice(0, 20)}` : ""}</option>)}
</select>
</Field>
)}
{kind === "table" && table && (
<>
<div className="grid grid-cols-2 gap-3">
{colSelect("key_column", "主键列", "对象唯一标识")}
{colSelect("label_column", "显示列", "问句里用它识别对象,如名称")}
</div>
<Field label="属性 → 列" hint="只读属性映射到列;可写属性可以不映射,修改记在本系统写回层">
<div className="grid gap-1.5 sm:grid-cols-2">
{props.map((p) => (
<div key={p} className="flex items-center gap-2">
<span className="w-24 shrink-0 truncate text-[12.5px]">{p}</span>
<select className="input h-8" value={ref.columns?.[p] || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, columns: { ...(ref.columns || {}), [p]: e.target.value } })}>
<option value="">(不映射)</option>
{cols.map((c: string) => <option key={c}>{c}</option>)}
</select>
</div>
))}
{!props.length && <p className="text-[12px] text-muted">先在上方定义属性</p>}
</div>
</Field>
</>
)}
{kind === "metric_expr" && table && (
<>
<Field label="取数表达式" hint="聚合表达式,如 SUM(amount) 或 SUM(a)/NULLIF(SUM(b),0)。系统会据此确定性生成 SQL,不让模型自由发挥">
<input className="input font-mono" value={ref.expression || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, expression: e.target.value })} />
</Field>
<div className="grid grid-cols-2 gap-3">
{colSelect("time_column", "时间列", "按统计周期过滤用")}
{colSelect("object_key_column", "对象键列", "按单个对象取值用")}
</div>
<Field label="固定过滤条件(每行一条 SQL 条件)">
<textarea className="input min-h-[48px] font-mono text-[12px]" value={(ref.filters || []).join("\n")} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, filters: e.target.value.split("\n").filter((x) => x.trim()) })} />
</Field>
<Field label="可拆分维度(维度名 → 列)">
<div className="space-y-1.5">
{Object.entries(ref.dimensions || {}).map(([k, v]) => (
<div key={k} className="flex items-center gap-2">
<input className="input h-8 w-32" value={k} disabled />
<select className="input h-8" value={v as string} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, dimensions: { ...ref.dimensions, [k]: e.target.value } })}>
{cols.map((c: string) => <option key={c}>{c}</option>)}
</select>
{canEdit && <button className="btn btn-ghost btn-sm" onClick={() => {
const d = { ...ref.dimensions }; delete d[k]; setRef({ ...ref, dimensions: d });
}}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{canEdit && <button className="btn btn-sm" onClick={async () => {
const name = await promptText("维度名", { desc: "问句里怎么说这个维度,如 区域、品牌" });
if (name) setRef({ ...ref, dimensions: { ...(ref.dimensions || {}), [name]: cols[0] || "" } });
}}><Plus className="h-3.5 w-3.5" />加维度</button>}
</div>
</Field>
</>
)}
{kind === "join" && (
<div className="grid grid-cols-2 gap-3">
<Field label="起点对象的列"><input className="input" value={ref.from_column || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, from_column: e.target.value })} /></Field>
<Field label="终点对象的列"><input className="input" value={ref.to_column || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, to_column: e.target.value })} /></Field>
</div>
)}
<div className="flex flex-wrap gap-2">
{canEdit && <button className="btn btn-primary btn-sm" disabled={busy || !dsId} onClick={() => void save()}>
{busy && <Spinner className="h-3.5 w-3.5" />}保存绑定</button>}
{concept.kind === "object_type" && (
<button className="btn btn-sm" onClick={async () => {
try { const r = await onto.objects(concept.id, "", 20); setTest({ columns: ["主键", "名称"], rows: r.items.map((o) => [o.key, o.label]) }); }
catch (e) { toast("error", "读取失败(对象要先发布)", errText(e)); }
}}><Play className="h-3.5 w-3.5" />预览对象实例</button>
)}
</div>
{test && (
<div className="space-y-2">
{test.sql && <pre className="rounded bg-ink/5 p-2 font-mono text-[11px]">{test.sql}</pre>}
<DataTable columns={test.columns} rows={test.rows} max={20} />
</div>
)}
</div>
);
}