ConceptEditor.tsx
18.4 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { Archive, FileText, Network, Play, Plus, Save, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import { Badge, Card, CardHeader, Collapse, Field, Pill, Spinner } from "@/components/ui";
import { go } from "@/lib/nav";
import {
errText, fmtTime, KIND_COLOR, onto, STATUS_LABEL, STATUS_TONE, type Concept, type ConceptBrief, type KernelMeta,
} from "@/lib/onto";
import { confirmDialog, promptText } from "@/lib/dialog";
import { useAppStore, toast } from "@/store/useAppStore";
import { BindingEditor } from "./BindingEditor";
/** 概念详情 + 编辑。按 kind 渲染不同的结构化表单,而不是让人手写 JSON。 */
export function ConceptEditor({ id, meta, all, canEdit, onChanged }: {
id: string; meta: KernelMeta; all: ConceptBrief[]; canEdit: boolean; onChanged: () => void;
}) {
const [c, setC] = useState<Concept | null>(null);
const [draft, setDraft] = useState<any>(null);
const [busy, setBusy] = useState(false);
const [usage, setUsage] = useState<any[] | null>(null);
const [lineage, setLineage] = useState<any | null>(null);
const [sec, setSec] = useState<Record<string, boolean>>({ binding: true });
const focusGraph = useAppStore((s) => s.requestGraphFocus);
const load = async () => {
try {
const x = await onto.concept(id);
setC(x);
setDraft({ name: x.name, display_name: x.display_name, description: x.description,
synonyms: x.synonyms.join(","), spec: structuredClone(x.spec || {}) });
setUsage(null); setLineage(null);
} catch (e) { toast("error", "加载失败", errText(e)); }
};
useEffect(() => { void load(); }, [id]); // eslint-disable-line react-hooks/exhaustive-deps
if (!c || !draft) return <Card className="p-6"><Spinner /></Card>;
const set = (k: string, v: any) => setDraft({ ...draft, spec: { ...draft.spec, [k]: v } });
const byKind = (k: string) => all.filter((x) => x.kind === k);
const conceptSelect = (key: string, kind: string, label: string) => (
<Field label={label}>
<select className="input" value={draft.spec[key] || ""} disabled={!canEdit} onChange={(e) => set(key, e.target.value)}>
<option value="">(未设置)</option>
{byKind(kind).map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
</select>
</Field>
);
const save = async () => {
setBusy(true);
try {
await onto.updateConcept(c.id, { ...draft, synonyms: draft.synonyms });
toast("ok", "已保存到草稿", "发布本体后,问答与取数才会用到新定义");
await load(); onChanged();
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
};
return (
<Card>
<CardHeader
title={<span className="flex items-center gap-2">
<i className="h-2.5 w-2.5 rounded-full" style={{ background: KIND_COLOR[c.kind] }} />{c.name}
<Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge>
{c.dirty && c.published && <Badge tone="bg-warn/10 text-warn">有未发布的修改</Badge>}
</span>}
desc={`${c.kind_label} · v${c.version} · 来源 ${c.origin} · 更新于 ${fmtTime(c.updated_at)}`}
right={canEdit && <>
{c.published
? c.status !== "deprecated" && <button className="btn btn-sm" onClick={async () => {
const r = await promptText("废弃原因", { desc: "已发布过的概念不能删除,只能废弃(保证历史答案可追溯)" });
if (r === null) return;
await onto.deprecateConcept(c.id, r); await load(); onChanged();
}}><Archive className="h-3.5 w-3.5" />废弃</button>
: <button className="btn btn-sm" onClick={async () => {
if (!(await confirmDialog("删除这个草稿概念?", { danger: true }))) return;
await onto.deleteConcept(c.id); onChanged();
}}><Trash2 className="h-3.5 w-3.5" />删除</button>}
<button className="btn btn-primary btn-sm" disabled={busy} onClick={() => void save()}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Save className="h-3.5 w-3.5" />}保存
</button>
</>} />
<div className="space-y-4 p-4">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="名称" required><input className="input" value={draft.name} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, name: e.target.value })} /></Field>
<Field label="别名 / 同义词" hint="逗号分隔。问句里出现这些词都会链接到它">
<input className="input" value={draft.synonyms} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, synonyms: e.target.value })} />
</Field>
</div>
<Field label="定义"><textarea className="input min-h-[56px]" value={draft.description} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, description: e.target.value })} /></Field>
{c.kind === "object_type" && (
<Field label="属性" hint="标「主键」的属性唯一识别对象;标「可写」的属性才允许被审批过的动作修改">
<div className="space-y-1.5">
{(draft.spec.properties || []).map((p: any, i: number) => (
<div key={i} className="flex flex-wrap items-center gap-2">
<input className="input h-8 w-32" value={p.name} disabled={!canEdit} placeholder="属性名"
onChange={(e) => { const ps = [...draft.spec.properties]; ps[i] = { ...p, name: e.target.value }; set("properties", ps); }} />
<select className="input h-8 w-24" value={p.data_type} disabled={!canEdit}
onChange={(e) => { const ps = [...draft.spec.properties]; ps[i] = { ...p, data_type: e.target.value }; set("properties", ps); }}>
{meta.data_types.map((t) => <option key={t}>{t}</option>)}
</select>
{p.data_type === "enum" && (
<input className="input h-8 w-44" value={(p.enum_values || []).join(",")} disabled={!canEdit} placeholder="可选值,逗号分隔"
onChange={(e) => { const ps = [...draft.spec.properties]; ps[i] = { ...p, enum_values: e.target.value.split(/[,,、]/).map((s) => s.trim()).filter(Boolean) }; set("properties", ps); }} />
)}
{(["is_key", "is_time", "is_writable"] as const).map((k) => (
<label key={k} className="flex items-center gap-1 text-[12px]">
<input type="checkbox" checked={!!p[k]} disabled={!canEdit}
onChange={(e) => { const ps = [...draft.spec.properties]; ps[i] = { ...p, [k]: e.target.checked }; set("properties", ps); }} />
{{ is_key: "主键", is_time: "时间", is_writable: "可写" }[k]}
</label>
))}
{canEdit && <button className="btn btn-ghost btn-sm" onClick={() => set("properties", draft.spec.properties.filter((_: any, j: number) => j !== i))}>
<Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{canEdit && <button className="btn btn-sm" onClick={() => set("properties", [...(draft.spec.properties || []), { name: "", data_type: "string" }])}>
<Plus className="h-3.5 w-3.5" />加属性</button>}
<Field label="显示属性" className="mt-2 w-56">
<select className="input" value={draft.spec.label_property || ""} disabled={!canEdit} onChange={(e) => set("label_property", e.target.value)}>
<option value="">(主键)</option>
{(draft.spec.properties || []).map((p: any) => <option key={p.name}>{p.name}</option>)}
</select>
</Field>
</div>
</Field>
)}
{c.kind === "link_type" && (
<div className="grid gap-3 sm:grid-cols-3">
{conceptSelect("from_type", "object_type", "起点对象")}
{conceptSelect("to_type", "object_type", "终点对象")}
<Field label="基数"><select className="input" value={draft.spec.cardinality} disabled={!canEdit} onChange={(e) => set("cardinality", e.target.value)}>
{meta.cardinality.map((x) => <option key={x}>{x}</option>)}</select></Field>
</div>
)}
{c.kind === "metric" && (
<div className="grid gap-3 sm:grid-cols-3">
{conceptSelect("object_type", "object_type", "所属对象")}
{conceptSelect("calibre_rule", "rule", "口径规则")}
{conceptSelect("calendar", "calendar", "默认统计周期")}
<Field label="单位"><input className="input" value={draft.spec.unit || ""} disabled={!canEdit} onChange={(e) => set("unit", e.target.value)} /></Field>
<Field label="方向"><select className="input" value={draft.spec.direction} disabled={!canEdit} onChange={(e) => set("direction", e.target.value)}>
<option value="higher_better">越高越好</option><option value="lower_better">越低越好</option><option value="neutral">中性</option></select></Field>
<Field label="文字公式" className="sm:col-span-3"><input className="input" value={draft.spec.formula_text || ""} disabled={!canEdit}
onChange={(e) => set("formula_text", e.target.value)} /></Field>
</div>
)}
{c.kind === "dimension" && (
<div className="grid gap-3 sm:grid-cols-2">
{conceptSelect("object_type", "object_type", "所属对象")}
<Field label="对应属性"><input className="input" value={draft.spec.property || ""} disabled={!canEdit} onChange={(e) => set("property", e.target.value)} /></Field>
</div>
)}
{c.kind === "rule" && <RuleFields draft={draft} set={set} canEdit={canEdit} meta={meta} />}
{c.kind === "calendar" && <CalendarFields draft={draft} set={set} canEdit={canEdit} />}
{c.kind === "role" && <Field label="职责"><textarea className="input" value={draft.spec.responsibilities || ""} disabled={!canEdit} onChange={(e) => set("responsibilities", e.target.value)} /></Field>}
{c.kind === "process" && (
<Field label="参与角色(逗号分隔)"><input className="input" value={(draft.spec.roles || []).join(",")} disabled={!canEdit}
onChange={(e) => set("roles", e.target.value.split(/[,,、]/).map((s) => s.trim()).filter(Boolean))} /></Field>
)}
{c.kind === "term" && (
<Field label="指向的概念"><select className="input" value={draft.spec.refers_to || ""} disabled={!canEdit} onChange={(e) => set("refers_to", e.target.value)}>
<option value="">(未设置)</option>{all.filter((x) => x.kind !== "term").map((x) => <option key={x.id} value={x.id}>{x.name}({x.kind_label})</option>)}
</select></Field>
)}
{["object_type", "metric", "link_type"].includes(c.kind) && (
<Collapse open={!!sec.binding} onToggle={() => setSec({ ...sec, binding: !sec.binding })} title="数据绑定"
summary={c.bindings.length ? `${c.bindings.length} 条绑定` : "未绑定:问答里不能取数"}>
<BindingEditor concept={c} canEdit={canEdit} onChanged={() => { void load(); onChanged(); }} />
</Collapse>
)}
<Collapse open={!!sec.ev} onToggle={() => setSec({ ...sec, ev: !sec.ev })} icon={<FileText className="h-3.5 w-3.5" />}
title="出处与知识" summary={`${c.evidence.length} 条文档出处 · ${c.graph_entities?.length || 0} 个图谱实体`}>
<div className="space-y-2">
{c.evidence.map((e, i) => (
<div key={i} className="rounded bg-ink/[0.03] p-2 text-[12px]"><b>{e.heading || e.chunk_id}</b> {e.snippet}</div>
))}
{!!c.graph_entities?.length && (
<div className="flex flex-wrap gap-1.5">
{c.graph_entities.map((g) => <Pill key={g.id} onClick={() => focusGraph(g.id)}>{g.label}</Pill>)}
</div>
)}
{!c.evidence.length && !c.graph_entities?.length && <p className="text-[12px] text-muted">暂无。可在本体目录顶部「关联图谱」把文档图谱实体挂到概念上。</p>}
</div>
</Collapse>
<Collapse open={!!sec.usage} onToggle={() => {
setSec({ ...sec, usage: !sec.usage });
if (!usage) void onto.usage(c.id).then(setUsage);
}} icon={<Network className="h-3.5 w-3.5" />} title="被谁引用(影响分析)" summary="修改前看看会波及哪些指标、动作、SOP">
{!usage ? <Spinner /> : !usage.length ? <p className="text-[12px] text-muted">没有被引用,可以放心修改</p> : (
<div className="flex flex-wrap gap-1.5">
{usage.map((u) => (
<Pill key={u.id} color={u.type === "concept" ? KIND_COLOR[u.kind] : u.type === "sop" ? "#ef4444" : "#8b5cf6"}
onClick={() => u.type === "concept" ? go("kernel", { id: u.id }) : u.type === "sop" ? go("sop", { id: u.id }) : go("capability", { id: u.id })}>
{u.type === "concept" ? "概念" : u.type === "sop" ? "SOP" : "能力"}:{u.name}
</Pill>
))}
</div>
)}
</Collapse>
<Collapse open={!!sec.lineage} onToggle={() => {
setSec({ ...sec, lineage: !sec.lineage });
if (!lineage) void onto.lineage(c.id).then(setLineage);
}} title="血缘" summary="概念 → 引用的概念 → 表 / 列 → 数据源,以及文档出处">
{!lineage ? <Spinner /> : <LineageView data={lineage} />}
</Collapse>
</div>
</Card>
);
}
function RuleFields({ draft, set, canEdit, meta }: { draft: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta }) {
const [vars, setVars] = useState("{}");
const [out, setOut] = useState<string>("");
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-3">
<Field label="规则类型"><select className="input" value={draft.spec.rule_kind} disabled={!canEdit} onChange={(e) => set("rule_kind", e.target.value)}>
<option value="judgement">判定</option><option value="calibre">口径</option><option value="calculation">计算</option></select></Field>
<Field label="表达式" className="sm:col-span-2" hint={`可用函数:${meta.functions.join(" ")}`}>
<input className="input font-mono" value={draft.spec.expression || ""} disabled={!canEdit} placeholder="如 actual >= target"
onChange={(e) => set("expression", e.target.value)} />
</Field>
</div>
<Field label="规则原文要点"><textarea className="input min-h-[48px]" value={draft.spec.text || ""} disabled={!canEdit} onChange={(e) => set("text", e.target.value)} /></Field>
{draft.spec.expression && (
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-line p-2">
<span className="text-[12px] text-muted">试算:</span>
<input className="input h-8 flex-1 font-mono text-[12px]" value={vars} onChange={(e) => setVars(e.target.value)}
placeholder={`{${(draft.spec.params || []).map((p: string) => `"${p}": 1`).join(", ")}}`} />
<button className="btn btn-sm" onClick={async () => {
try { const r = await onto.evalRule({ expression: draft.spec.expression, vars: JSON.parse(vars || "{}") }); setOut(JSON.stringify(r.result)); }
catch (e) { setOut(`错误:${errText(e)}`); }
}}><Play className="h-3.5 w-3.5" />运行</button>
{out && <code className="text-[12px]">= {out}</code>}
</div>
)}
</div>
);
}
function CalendarFields({ draft, set, canEdit }: { draft: any; set: (k: string, v: any) => void; canEdit: boolean }) {
const [pv, setPv] = useState<string>("");
const s = draft.spec;
useEffect(() => {
void Promise.all([onto.resolveCalendar({ spec: s, ref: "current" }), onto.resolveCalendar({ spec: s, ref: "last" })])
.then(([a, b]) => setPv(`本期 ${a.period}:${a.start} ~ ${a.end};上期 ${b.period}:${b.start} ~ ${b.end}`))
.catch((e) => setPv(errText(e)));
}, [s.start_day, s.start_month_offset, s.end_day, s.end_month_offset]); // eslint-disable-line react-hooks/exhaustive-deps
const num = (k: string, label: string, hint?: string) => (
<Field label={label} hint={hint}><input className="input" value={s[k] ?? ""} disabled={!canEdit}
onChange={(e) => set(k, e.target.value)} /></Field>
);
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-4">
{num("start_day", "起始日", "1~31")}
{num("start_month_offset", "起始月偏移", "-1 = 上月")}
{num("end_day", "截止日", "1~31 或 last")}
{num("end_month_offset", "截止月偏移", "0 = 本月")}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="适用条件"><input className="input" value={s.applies_when || ""} disabled={!canEdit} onChange={(e) => set("applies_when", e.target.value)} /></Field>
<Field label="原文说明"><input className="input" value={s.text || ""} disabled={!canEdit} onChange={(e) => set("text", e.target.value)} /></Field>
</div>
<p className="rounded-md bg-ok/10 px-2 py-1.5 text-[12px] text-ok">预览:{pv}</p>
</div>
);
}
function LineageView({ data }: { data: { nodes: any[]; edges: any[] } }) {
const groups: [string, string][] = [["metric", "指标"], ["object_type", "对象"], ["rule", "规则"], ["calendar", "周期"],
["table", "表"], ["column", "列"], ["datasource", "数据源"], ["document", "文档"]];
return (
<div className="flex flex-wrap gap-4">
{groups.map(([k, label]) => {
const ns = data.nodes.filter((n) => n.kind === k);
if (!ns.length) return null;
return (
<div key={k} className="min-w-[120px]">
<p className="mb-1 text-[11px] font-medium text-muted">{label}</p>
<div className="flex flex-col gap-1">
{ns.map((n) => <Pill key={n.id} color={KIND_COLOR[k] || "#64748b"}>{n.label}</Pill>)}
</div>
</div>
);
})}
<p className="w-full text-[11px] text-muted">{data.edges.length} 条血缘关系</p>
</div>
);
}