BlockEditor.tsx
47.5 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
import { Archive, ArrowLeft, Play, Plus, Save, Trash2, Undo2 } from "lucide-react";
import { useEffect, useState } from "react";
import { FormSection, ObjectPicker, Tabs, Select } from "@/components/kit";
import { Badge, Card, Field, GLOSSARY, Pill, Spinner, Term } from "@/components/ui";
import { ResultGrid } from "@/components/kit";
import { ParamInput, PreviewView } from "@/features/actions/ActionParts";
import { ActionEditor } from "./ActionEditor";
import { ObjectEditor } from "./ObjectEditor";
import { go } from "@/lib/nav";
import {
errText, fmtTime, KIND_COLOR, onto, STATUS_LABEL, STATUS_TONE, TYPE_LABEL, typeKey,
type Concept, type ConceptBrief, type KernelMeta,
} from "@/lib/onto";
import { confirmDialog, promptText } from "@/lib/dialog";
import { cn } from "@/lib/utils";
import { toast, loadFailed } from "@/store/useAppStore";
import { BindingEditor } from "../kernel/BindingEditor";
import { ResultView, Rows, TypeBadge } from "./common";
import { DecisionCheck, fnInputNames, InputsEditor, TestCases } from "./FnParts";
import { invalidateRefOptions } from "./RefSelect";
import { pageOfKind } from "./routes";
const DIR = [["higher_better", "越高越好"], ["lower_better", "越低越好"], ["neutral", "中性"]];
type EdTab = "define" | "data" | "try" | "tests" | "refs";
const KIND_NOUN: Record<string, string> = { object_type: "对象", link_type: "关系", function: "函数", action: "动作", value_type: "值类型" };
const CARD_CN: Record<string, string> = { "n:1": "多对一", "1:n": "一对多", "1:1": "一对一", "n:n": "多对多" };
/**
* 一个元素的编辑页。顶部是名称、状态和保存;下面按页签分:定义 / 数据 / 试一试 / 引用关系。
* 改的是草稿,发布后才生效;「试一试」直接用当前表单里的内容,不用先保存。
*/
export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose, backText = "" }: {
id: string; meta: KernelMeta; all: ConceptBrief[]; canEdit: boolean;
onChanged: () => void; onClose?: () => void;
/** 从别的页面(如 AI 建模)跳来时,返回按钮写明回哪里 */
backText?: string;
}) {
const [c, setC] = useState<Concept | null>(null);
const [draft, setDraft] = useState<any>(null);
const [busy, setBusy] = useState(false);
const [tab, setTab] = useState<EdTab>("define");
const [usage, setUsage] = useState<any[] | null>(null);
const [lineage, setLineage] = useState<any | null>(null);
const [saved, setSaved] = useState("");
/** keepDraft=true 只刷新服务端状态,不覆盖正在编辑的表单(保存数据绑定时用,免得把没保存的修改冲掉)。 */
const load = async (keepDraft = false) => {
try {
const x = await onto.concept(id);
setC(x);
if (!keepDraft) {
const d = { name: x.name, display_name: x.display_name, description: x.description,
synonyms: x.synonyms.join(","), spec: structuredClone(x.spec || {}) };
setDraft(d); setSaved(JSON.stringify(d));
}
setUsage(null); setLineage(null);
} catch (e) { toast("error", "加载失败", errText(e)); }
};
useEffect(() => { void load(); }, [id]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (tab !== "refs" || !c) return;
if (!usage) void onto.usage(c.id).then(setUsage).catch((e) => { setUsage([]); loadFailed(e); });
if (!lineage) void onto.lineage(c.id).then(setLineage).catch(() => setLineage({ nodes: [], edges: [] }));
}, [tab, c?.id]); // eslint-disable-line react-hooks/exhaustive-deps
if (!c || !draft) return <div className="grid h-full place-items-center"><Spinner /></div>;
const tk = typeKey({ kind: c.kind, category: draft.spec.category });
const set = (k: string, v: any) => setDraft((d: any) => ({ ...d, spec: { ...d.spec, [k]: v } }));
const objects = all.filter((x) => x.kind === "object_type");
const fns = (cat: string) => all.filter((x) => x.kind === "function" && x.category === cat);
const dirty = JSON.stringify(draft) !== saved;
const conceptSelect = (key: string, items: ConceptBrief[], label: string, hint?: string) => {
// 存的可能是 id 也可能是名称(AI 建模、模板导入存名称):两种都要认
const raw = draft.spec[key] || "";
const hit = items.find((x) => x.id === raw || x.name === raw);
return (
<Field label={label} hint={raw && !hit ? <span className="text-bad">原来填的「{String(raw).slice(0, 20)}」已经不存在,请重新选</span> : hint}>
<Select className={cn("input", raw && !hit && "border-bad")} value={hit ? hit.id : ""} disabled={!canEdit} onChange={(e) => set(key, e.target.value)}>
<option value="">不选</option>
{items.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
</Select>
</Field>
);
};
const save = async () => {
setBusy(true);
try {
const spec = { ...draft.spec };
if (Array.isArray(spec.properties)) spec.properties = spec.properties.map(({ _derived, ...p }: any) => p);
await onto.updateConcept(c.id, { ...draft, spec, synonyms: draft.synonyms });
invalidateRefOptions();
toast("ok", "已保存", c.published ? "发布后才会生效" : undefined);
await load(); onChanged();
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
};
const hasData = (c.kind === "object_type" && !draft.spec.abstract) || c.kind === "link_type" || draft.spec.category === "aggregate";
const hasTry = c.kind === "function" || c.kind === "action";
const tabs: { key: EdTab; label: string }[] = [
{ key: "define", label: "定义" },
...(hasData ? [{ key: "data" as EdTab, label: c.kind === "function" ? "怎么取数" : "数据来源" }] : []),
...(hasTry ? [{ key: "try" as EdTab, label: "试一试" }] : []),
...(c.kind === "function" && draft.spec.category !== "ai" ? [{ key: "tests" as EdTab, label: `测试用例${(draft.spec.tests || []).length ? `(${draft.spec.tests.length})` : ""}` }] : []),
{ key: "refs", label: "引用关系" },
];
return (
<div className="flex h-full flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
{onClose && <button className="btn btn-ghost btn-sm -ml-2" onClick={onClose}><ArrowLeft className="h-4 w-4" />{backText || KIND_NOUN[c.kind]}</button>}
<h2 className="min-w-0 break-words text-section font-semibold">{draft.display_name || draft.name}</h2>
<TypeBadge t={tk} />
<Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge>
{c.dirty && c.published && <Badge variant="warn">有修改没发布</Badge>}
<span className="flex-1" />
{canEdit && <>
{c.status === "deprecated"
? <button className="btn" onClick={async () => {
try { await onto.restoreConcept(c.id); toast("ok", "已恢复为草稿"); await load(); onChanged(); }
catch (e) { toast("error", errText(e)); }
}}><Undo2 className="h-3.5 w-3.5" />恢复</button>
: c.published
? <button className="btn btn-ghost text-muted" title="停用这个元素" onClick={async () => {
const uses = await onto.conceptUsage(c.id).catch(() => []);
const desc = uses.length
? `${uses.slice(0, 5).map((u) => `「${u.name}」`).join("、")}${uses.length > 5 ? " 等" : ""} ${uses.length} 处还在用它,停用后它们会失效。`
: "发布过的元素不能删除,只能停用。";
const r = await promptText("为什么停用", { desc });
if (r === null) return;
try { await onto.deprecateConcept(c.id, r, uses.length > 0); await load(); onChanged(); }
catch (e) { toast("error", "停用失败", errText(e)); }
}}><Archive className="h-3.5 w-3.5" />停用</button>
: <button className="btn btn-ghost text-muted" onClick={async () => {
if (!(await confirmDialog("删除这个草稿?", { danger: true }))) return;
await onto.deleteConcept(c.id); onChanged(); onClose?.();
}}><Trash2 className="h-3.5 w-3.5" />删除</button>}
<button className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Save className="h-3.5 w-3.5" />}{dirty ? "保存" : "已保存"}
</button>
</>}
</div>
<Tabs<EdTab> value={tab} onChange={setTab} options={tabs} />
<Card className="min-h-0 flex-1 overflow-auto p-6">
{tab === "define" && (
<div className="space-y-6">
<FormSection title="基本信息">
<div className="grid gap-4 sm:grid-cols-2">
{c.kind === "action" ? (
<Field label="名称" required>
<input className="input" value={draft.display_name || draft.name} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, display_name: e.target.value })} />
</Field>
) : (
<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={c.kind === "action" ? "这个动作是做什么的" : "业务定义"}>
<textarea className="input min-h-[64px]" value={draft.description} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, description: e.target.value })} />
</Field>
<Field label="分组" hint="同一组的元素在列表里排在一起" className="sm:max-w-xs">
<input className="input" value={draft.spec.domain || ""} disabled={!canEdit} onChange={(e) => set("domain", e.target.value)} />
</Field>
</FormSection>
{c.kind === "object_type" && <ObjectEditor spec={draft.spec} set={set} canEdit={canEdit} all={all} />}
{c.kind === "link_type" && (
<FormSection title="连接哪两类对象">
<div className="grid gap-4 sm:grid-cols-3">
{conceptSelect("from_type", objects, "从")}
{conceptSelect("to_type", objects, "到")}
<Field label={<Term tip={GLOSSARY["基数"]}>数量关系</Term>}><Select className="input" value={draft.spec.cardinality} disabled={!canEdit} onChange={(e) => set("cardinality", e.target.value)}>
{meta.cardinality.map((x) => <option key={x} value={x}>{CARD_CN[x] || x}</option>)}</Select></Field>
</div>
</FormSection>
)}
{c.kind === "function" && (
<FormSection title={TYPE_LABEL[draft.spec.category] || "函数"}>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="类别" hint={GLOSSARY[TYPE_LABEL[draft.spec.category] || ""]}>
<Select className="input" value={draft.spec.category} disabled={!canEdit} onChange={async (e) => {
const next = e.target.value;
const filled = Object.keys(draft.spec).filter((k) => !["category", "object_type", "domain"].includes(k)
&& draft.spec[k] !== "" && draft.spec[k] != null).length;
if (filled > 0 && !(await confirmDialog("换一个类别?", { desc: "不同类别的设置不通用,换了之后当前的设置会清空。", danger: true }))) return;
setDraft({ ...draft, spec: { category: next, object_type: draft.spec.object_type, domain: draft.spec.domain,
...(next === "decision" ? EMPTY_DECISION : {}), ...(next === "object_set" ? EMPTY_SET : {}), ...(next === "ai" ? EMPTY_AI : {}) } });
}}>
{meta.categories.map((x) => <option key={x.category} value={x.category}>{x.label}</option>)}
</Select>
</Field>
{conceptSelect("object_type", objects, "关于哪类对象")}
</div>
{draft.spec.category === "aggregate" && (
<div className="grid gap-4 sm:grid-cols-3">
<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.format || ""} disabled={!canEdit} onChange={(e) => set("format", e.target.value)}>
<option value="">默认</option><option value="money">金额</option><option value="quantity">数量</option><option value="percent">百分比</option></Select></Field>
<Field label="怎么算好"><Select className="input" value={draft.spec.direction} disabled={!canEdit} onChange={(e) => set("direction", e.target.value)}>
{DIR.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select></Field>
<Field label="同时算对比期" hint="结果里多出 对比期数值、变化量、变化率">
<Select className="input" value={draft.spec.compare || ""} disabled={!canEdit} onChange={(e) => set("compare", e.target.value)}>
<option value="">不算</option><option value="mom">环比(上一期)</option><option value="yoy">同比(去年同期)</option>
</Select>
</Field>
<Field label="记录走势" hint="没有时间列的时点数(库存、余额)要和历史比时打开:每天拍一次快照">
<label className="flex h-9 items-center gap-2 text-label">
<input type="checkbox" checked={!!draft.spec.history?.enabled} disabled={!canEdit}
onChange={(e) => set("history", { ...(draft.spec.history || {}), enabled: e.target.checked, every: draft.spec.history?.every || "daily" })} />
每天拍一次快照
</label>
</Field>
<Field label="参数化筛选" className="sm:col-span-3" hint="调用时可以传的筛选条件,如某个维度 = 输入的值">
<InputsEditor value={draft.spec.inputs || []} disabled={!canEdit} onChange={(v) => set("inputs", v)} addText="加一个筛选参数"
dimensions={Object.keys(c.bindings.find((b) => b.target_kind === "metric_expr")?.ref?.dimensions || {})} />
</Field>
<div className="sm:col-span-3"><PeriodFields period={draft.spec.period || {}} canEdit={canEdit}
onChange={(v) => set("period", v)} /></div>
</div>
)}
{draft.spec.category === "rule" && <RuleFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />}
{draft.spec.category === "object_set" && <ObjectSetFields spec={draft.spec} set={set} canEdit={canEdit} all={all} />}
{draft.spec.category === "decision" && <DecisionEditor spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} canEdit={canEdit} />}
{draft.spec.category === "ai" && <AiFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />}
</FormSection>
)}
{c.kind === "action" && <ActionEditor spec={draft.spec} set={set} canEdit={canEdit} meta={meta} all={all} />}
{c.kind === "value_type" && <ValueTypeFields spec={draft.spec} set={set} canEdit={canEdit} />}
</div>
)}
{tab === "data" && (
<FormSection title={c.kind === "function" ? "怎么取数" : c.kind === "link_type" ? "两边靠哪一列对上" : "数据来自哪张表"}>
<BindingEditor concept={{ ...c, spec: draft.spec }} canEdit={canEdit} onChanged={() => { void load(true); onChanged(); }} />
</FormSection>
)}
{tab === "tests" && (
<FormSection title="测试用例">
<TestCases conceptId={c.id} spec={draft.spec} disabled={!canEdit} onChange={(v) => set("tests", v)} />
</FormSection>
)}
{tab === "try" && (
<FormSection title="试一试" desc={c.kind === "action" ? "只看会做什么,不会真的执行" : "用现在表单里的内容算一次"}>
<TryPanel concept={c} kind={c.kind} spec={draft.spec} name={draft.name} />
</FormSection>
)}
{tab === "refs" && (
<div className="space-y-6">
<FormSection title="谁在用它" desc="改之前看看会影响到哪里">
{!usage ? <Spinner /> : !usage.length ? <p className="text-label text-muted">还没有被别的地方用到。</p> : (
<div className="flex flex-wrap gap-2">
{usage.map((u) => (
<button key={u.id} className="chip" onClick={() => u.type === "sop" ? go("sop", { id: u.id }) : go(pageOfKind(u.kind), { id: u.id })}>
<span className="text-muted">{u.type === "sop" ? "流程卡" : u.type === "watch" ? "监控" : TYPE_LABEL[u.kind] || "元素"}</span>{u.name}
</button>
))}
</div>
)}
</FormSection>
<FormSection title="它用到了什么">
{!lineage ? <Spinner /> : <LineageView data={lineage} />}
</FormSection>
{c.evidence.length > 0 && (
<FormSection title="文档出处">
{c.evidence.map((e, i) => (
<div key={i} className="rounded-lg bg-ink/[0.03] px-3 py-2 text-label"><b>{e.heading || "正文"}</b><span className="ml-2 text-muted">{e.snippet}</span></div>
))}
</FormSection>
)}
{!!c.implementations?.length && (
<FormSection title="实现这个接口的对象">
<div className="flex flex-wrap gap-1.5">
{c.implementations.map((x) => <Pill key={x.id} onClick={() => go("b_object", { id: x.id })}>{x.name}</Pill>)}
</div>
</FormSection>
)}
</div>
)}
</Card>
</div>
);
}
const EMPTY_DECISION = { inputs: [{ name: "x", label: "输入", type: "number" }], outputs: [{ name: "result", label: "结果" }],
rows: [{ when: { x: "> 0" }, then: { result: "" }, note: "" }], hit_policy: "first", default: {} };
const EMPTY_AI = { instructions: "", functions: ["data.ask", "knowledge.search"], inputs: [],
output_schema: { conclusion: "一句话结论", details: [] }, max_steps: 4 };
/** 公式里用到的变量名(粗略:去掉字符串和函数名)。保存后由后端精确补全。 */
function exprNames(expr: string, fnNames: string[]): string[] {
const body = String(expr || "").replace(/'[^']*'|"[^"]*"/g, " ");
const out: string[] = [];
for (const m of body.matchAll(/[A-Za-z_\u4e00-\u9fff][\w\u4e00-\u9fff]*/g)) {
const n = m[0];
const after = body.slice((m.index || 0) + n.length).trimStart();
const before = body.slice(0, m.index || 0).trimEnd();
if (after.startsWith("(") || before.endsWith(".") || fnNames.includes(n) || ["and", "or", "not", "in", "if", "else", "True", "False", "None", "true", "false", "null"].includes(n)) continue;
if (!out.includes(n)) out.push(n);
}
return out;
}
function RuleFields({ spec, set, canEdit, meta }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta }) {
const names = exprNames(spec.expression || "", meta.functions);
const typed = new Map<string, any>((spec.inputs || []).map((i: any) => [i.name, i]));
const inputs = names.map((n) => typed.get(n) || { name: n, label: "", type: "number", required: true });
const kind = spec.rule_kind || "judgement";
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<Field label="规则类型"><Select className="input" value={kind} disabled={!canEdit} onChange={(e) => set("rule_kind", e.target.value)}>
<option value="judgement">判定(得出 是 / 否)</option><option value="calculation">计算(得出一个数)</option><option value="calibre">口径</option></Select></Field>
<Field label="结果类型"><Select className="input" value={spec.output_type || ""} disabled={!canEdit} onChange={(e) => set("output_type", e.target.value)}>
<option value="">{kind === "judgement" ? "是否(默认)" : kind === "calculation" ? "数字(默认)" : "任意"}</option>
<option value="boolean">是否</option><option value="number">数字</option><option value="string">文字</option><option value="date">日期</option></Select></Field>
</div>
<Field label="公式" hint={<>直接写变量名,可以多行;条件分支用 <code>A if 条件 else B</code>。可用函数:{meta.functions.slice(0, 16).join("、")} 等</>}>
<textarea className="input min-h-[72px] font-mono text-label" value={spec.expression || ""} disabled={!canEdit} spellCheck={false}
placeholder={"如:\nactual >= target * 0.9\n and days_between(order_date, today()) <= 30"}
onChange={(e) => set("expression", e.target.value)} />
</Field>
<Field label="输入(从公式里认出来的变量)" hint="给每个变量定类型和中文名:调用时按类型校验,流程卡里按类型给输入框">
<InputsEditor fixedNames value={inputs} disabled={!canEdit}
onChange={(v) => { set("inputs", v); set("params", v.map((x) => x.name)); }} />
</Field>
{kind === "judgement" && (
<Field label="不通过时的提示" hint="可以写 $变量名 嵌入数值,如:完成率 $actual 低于目标">
<input className="input" value={spec.message || ""} disabled={!canEdit} onChange={(e) => set("message", e.target.value)} />
</Field>
)}
<Field label="规则原文"><textarea className="input min-h-[48px]" value={spec.text || ""} disabled={!canEdit} onChange={(e) => set("text", e.target.value)} /></Field>
</div>
);
}
/** 指标的统计周期口径:按什么切、一期从哪天到哪天(「上月 26 日到本月 25 日」这类业务月也在这里写)。 */
function PeriodFields({ period: s, onChange, canEdit }: { period: any; onChange: (v: any) => void; canEdit: boolean }) {
const [pv, setPv] = useState<string>("");
const set = (k: string, v: any) => onChange({ ...s, [k]: v });
useEffect(() => {
void Promise.all([onto.resolvePeriod({ period: s, ref: "current" }), onto.resolvePeriod({ period: s, ref: "last" })])
.then(([a, b]) => setPv(`${a.label}:本期 ${a.period}(${a.start} ~ ${a.end}),上期 ${b.period}(${b.start} ~ ${b.end})`))
.catch((e) => setPv(errText(e)));
}, [s.grain, s.week_start, s.start_month, 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>
);
const grain = s.grain || "month";
return (
<div className="space-y-3 rounded-lg border border-line p-3">
<p className="text-label font-medium">统计周期口径 <span className="font-normal text-muted">问「本期 / 上期 / 某月」时按它算</span></p>
<div className="grid gap-3 sm:grid-cols-4">
<Field label="按什么切"><Select className="input" value={grain} disabled={!canEdit} onChange={(e) => set("grain", e.target.value)}>
<option value="day">日</option><option value="week">周</option><option value="month">月</option><option value="quarter">季度</option><option value="year">年</option>
</Select></Field>
{grain === "week" && (
<Field label="一周从周几开始"><Select className="input" value={String(s.week_start || 1)} disabled={!canEdit} onChange={(e) => set("week_start", Number(e.target.value))}>
{["一", "二", "三", "四", "五", "六", "日"].map((d, i) => <option key={d} value={String(i + 1)}>周{d}</option>)}
</Select></Field>
)}
{(grain === "quarter" || grain === "year") && (
<Field label={grain === "year" ? "财年从几月开始" : "第一季度从几月开始"} hint="自然年填 1">
<Select className="input" value={String(s.start_month || 1)} disabled={!canEdit} onChange={(e) => set("start_month", Number(e.target.value))}>
{Array.from({ length: 12 }, (_, i) => <option key={i} value={String(i + 1)}>{i + 1} 月</option>)}
</Select>
</Field>
)}
</div>
{grain === "month" && (
<div className="grid gap-3 sm:grid-cols-4">
{num("start_day", "从几号开始", "1 到 31")}
{num("start_month_offset", "开始在哪个月", "0 本月,-1 上月")}
{num("end_day", "到几号结束", "1 到 31,月底填 last")}
{num("end_month_offset", "结束在哪个月", "0 本月,-1 上月")}
</div>
)}
<Field label="这个口径叫什么" hint="如 业务月、财年;不填按规则自动起名" className="sm:max-w-xs">
<input className="input" value={s.label || ""} disabled={!canEdit} onChange={(e) => set("label", e.target.value)} />
</Field>
<p className="rounded-md bg-ink/[0.03] px-3 py-2 text-label">{pv}</p>
</div>
);
}
const EMPTY_SET = { base: "", where: { mode: "all", items: [] }, around: [], combine: [], sort: [], limit: 0, inputs: [] };
const SET_OPS: Record<string, string> = { eq: "等于", ne: "不等于", gt: "大于", ge: "大于等于", lt: "小于", le: "小于等于",
contains: "包含", in: "属于", empty: "为空", not_empty: "不为空" };
/** 对象集:从哪类对象(或哪个对象集)出发 → 按条件筛 → 沿关系走到别的对象 → 和别的对象集并 / 交 / 差。条件右边可以写 $参数名。 */
function ObjectSetFields({ spec, set, canEdit, all }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; all: ConceptBrief[] }) {
const bases = all.filter((x) => x.kind === "object_type" || (x.kind === "function" && x.category === "object_set"));
const sets = all.filter((x) => x.kind === "function" && x.category === "object_set");
const items: any[] = spec.where?.items || [];
const [pv, setPv] = useState<any>(null);
const setItems = (v: any[]) => set("where", { mode: spec.where?.mode || "all", items: v });
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-3">
<Field label="从哪来" required>
<Select className="input" value={spec.base || ""} disabled={!canEdit} onChange={(e) => set("base", e.target.value)}>
<option value="">选对象(或对象集)</option>
{bases.map((x) => <option key={x.id} value={x.name}>{x.kind === "function" ? `对象集 · ${x.name}` : x.name}</option>)}
</Select>
</Field>
<Field label="条件之间">
<Select className="input" value={spec.where?.mode || "all"} disabled={!canEdit} onChange={(e) => set("where", { ...(spec.where || {}), mode: e.target.value, items })}>
<option value="all">都要满足</option><option value="any">满足一个就行</option></Select>
</Field>
<Field label="只要前几个" hint="0 = 不限"><input className="input" type="number" min={0} value={spec.limit || 0} disabled={!canEdit} onChange={(e) => set("limit", Number(e.target.value) || 0)} /></Field>
</div>
<Field label="筛选条件" hint="右边可以写 $参数名,调用时再给值">
<Rows items={items} disabled={!canEdit} onChange={setItems} addText="加一个条件" empty={{ left: "", op: "eq", right: "" }}
render={(it: any, up) => (<>
<input className="input h-8 w-40" placeholder="属性" value={it.left || ""} onChange={(e) => up({ ...it, left: e.target.value })} />
<Select className="input h-8 w-28" value={it.op || "eq"} onChange={(e) => up({ ...it, op: e.target.value })}>
{Object.entries(SET_OPS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select>
<input className="input h-8 min-w-0 flex-1" placeholder="值 或 $参数" value={it.right ?? ""} onChange={(e) => up({ ...it, right: e.target.value })} />
</>)} />
</Field>
<Field label="再沿关系走到" hint="一步一步走;最后得到的是最后一步那头的对象">
<Rows items={spec.around || []} disabled={!canEdit} onChange={(v) => set("around", v)} addText="走一步" empty={{ link: "" }}
render={(it: any, up) => <input className="input h-8 flex-1" placeholder="关系名或对方对象名" value={it.link || ""} onChange={(e) => up({ ...it, link: e.target.value })} />} />
</Field>
<Field label="和别的对象集" hint="要同一类对象">
<Rows items={spec.combine || []} disabled={!canEdit} onChange={(v) => set("combine", v)} addText="加一个集合运算" empty={{ op: "intersect", set: "" }}
render={(it: any, up) => (<>
<Select className="input h-8 w-28" value={it.op} onChange={(e) => up({ ...it, op: e.target.value })}>
<option value="union">并上</option><option value="intersect">交上</option><option value="subtract">去掉</option></Select>
<Select className="input h-8 flex-1" value={it.set || ""} onChange={(e) => up({ ...it, set: e.target.value })}>
<option value="">选对象集</option>{sets.map((x) => <option key={x.id} value={x.name}>{x.name}</option>)}</Select>
</>)} />
</Field>
<Field label="参数"><InputsEditor value={spec.inputs || []} disabled={!canEdit} onChange={(v) => set("inputs", v)} addText="加一个参数" /></Field>
<div className="space-y-2">
<button className="btn btn-sm" disabled={!spec.base} onClick={async () => {
try { setPv(await onto.evalObjectSet({ spec, limit: 10 })); } catch (e) { setPv({ error: errText(e) }); }
}}><Play className="h-3.5 w-3.5" />看看现在有哪些</button>
{pv && (pv.error ? <p className="text-label text-bad">{pv.error}</p> : (
<div className="space-y-1">
<p className="text-label">现在一共 <b>{pv.total}</b> 个{pv.type_name}</p>
<ResultGrid data={{ columns: ["主键", "名称"], rows: (pv.items || []).map((o: any) => [o.key, o.label]) }} max={10} />
</div>
))}
</div>
</div>
);
}
/** 值类型:基础类型 + 单位 / 格式 / 范围 / 小数位 / 格式(正则)/ 可选值,引用它的属性写入时统一按它校验。 */
function ValueTypeFields({ spec, set, canEdit }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean }) {
return (
<FormSection title="值类型" desc="属性引用它之后,单位、显示格式和写入时的校验都按这里来">
<div className="grid gap-3 sm:grid-cols-4">
<Field label="基础类型"><Select className="input" value={spec.base_type || "string"} disabled={!canEdit} onChange={(e) => set("base_type", e.target.value)}>
<option value="string">文字</option><option value="number">数字</option><option value="integer">整数</option>
<option value="boolean">是 / 否</option><option value="date">日期</option><option value="datetime">日期时间</option><option value="text">多行文字</option>
</Select></Field>
<Field label="单位"><input className="input" value={spec.unit || ""} disabled={!canEdit} onChange={(e) => set("unit", e.target.value)} /></Field>
<Field label="显示成"><Select className="input" value={spec.format || ""} disabled={!canEdit} onChange={(e) => set("format", e.target.value)}>
<option value="">默认</option><option value="money">金额</option><option value="quantity">数量</option><option value="percent">百分比</option><option value="status">状态标签</option>
</Select></Field>
<Field label="小数位"><input className="input" value={spec.precision ?? ""} disabled={!canEdit} onChange={(e) => set("precision", e.target.value)} /></Field>
<Field label="最小值"><input className="input" value={spec.min ?? ""} disabled={!canEdit} onChange={(e) => set("min", e.target.value)} /></Field>
<Field label="最大值"><input className="input" value={spec.max ?? ""} disabled={!canEdit} onChange={(e) => set("max", e.target.value)} /></Field>
<Field label="格式(正则)" className="sm:col-span-2"><input className="input font-mono" value={spec.pattern || ""} disabled={!canEdit} onChange={(e) => set("pattern", e.target.value)} /></Field>
<Field label="可选值" hint="逗号隔开" className="sm:col-span-2"><input className="input" value={(spec.enum_values || []).join(",")} disabled={!canEdit}
onChange={(e) => set("enum_values", e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean))} /></Field>
<Field label="不通过时的提示" className="sm:col-span-2"><input className="input" value={spec.message || ""} disabled={!canEdit} onChange={(e) => set("message", e.target.value)} /></Field>
</div>
</FormSection>
);
}
/** 决策表:一行一条规则。条件格写「> 3」「[0, 3]」「'A'」「-」(任意),输出格写值,以 = 开头则按表达式算。 */
export function DecisionEditor({ spec, onChange, canEdit }: { spec: any; onChange: (s: any) => void; canEdit: boolean }) {
const inputs: any[] = spec.inputs || [];
const outputs: any[] = spec.outputs || [];
const rows: any[] = spec.rows || [];
const set = (k: string, v: any) => onChange({ ...spec, [k]: v });
const cell = (i: number, side: "when" | "then", k: string, v: string) => {
const rs = rows.map((r) => ({ ...r, when: { ...(r.when || {}) }, then: { ...(r.then || {}) } }));
rs[i][side][k] = v;
set("rows", rs);
};
const cols = (items: any[], key: "inputs" | "outputs", title: string) => (
<Field label={title}>
<Rows items={items} disabled={!canEdit} onChange={(v) => set(key, v)} addText={`加${key === "inputs" ? "输入" : "输出"}`}
empty={{ name: "", label: "", type: key === "inputs" ? "number" : "string" }}
render={(it: any, up) => (<>
<input className="input h-8 min-w-0 flex-1" placeholder="名称" value={it.label} onChange={(e) => up({ ...it, label: e.target.value })} />
<input className="input h-8 w-32 font-mono text-[13px]" placeholder="字段" value={it.name} onChange={(e) => up({ ...it, name: e.target.value })} />
<Select className="input h-8 w-20" value={it.type || (key === "inputs" ? "number" : "string")} onChange={(e) => up({ ...it, type: e.target.value })}>
<option value="number">数字</option><option value="string">文字</option><option value="boolean">是否</option>{key === "inputs" && <option value="date">日期</option>}
</Select>
</>)} />
</Field>
);
const prio = spec.hit_policy === "priority";
return (
<div className="space-y-3">
<div className="grid gap-3 lg:grid-cols-2">
{cols(inputs, "inputs", "看哪些条件")}
{cols(outputs, "outputs", "得出什么")}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="多行都满足时" hint={prio ? "表格里多一列「优先级」,数大的优先" : spec.hit_policy === "unique" ? "同时命中多行会报错,适合要求互斥的规则" : undefined}>
<Select className="input" value={spec.hit_policy || "first"} disabled={!canEdit} onChange={(e) => set("hit_policy", e.target.value)}>
<option value="first">取最上面那一行</option><option value="unique">只能命中一行(多行命中算错)</option>
<option value="priority">取优先级最高的</option><option value="collect">满足的都要(列表)</option>
</Select>
</Field>
</div>
<div className="overflow-auto rounded-lg border border-line">
<table className="w-full text-label">
<thead className="bg-ink/[0.03] text-muted">
<tr>
<th className="w-8 px-1">#</th>
{inputs.map((x) => <th key={`i${x.name}`} className="px-1 py-1 text-left">当 {x.label || x.name}</th>)}
{outputs.map((x) => <th key={`o${x.name}`} className="bg-brand/5 px-1 py-1 text-left">则 {x.label || x.name}</th>)}
{prio && <th className="w-20 px-1 text-left">优先级</th>}
<th className="px-1 text-left">说明</th><th />
</tr>
</thead>
<tbody>
{rows.map((r, i) => (
<tr key={i} className="border-t border-line/60">
<td className="px-1 text-center text-muted">{i + 1}</td>
{inputs.map((x) => <td key={x.name} className="px-1 py-0.5"><input className="input h-7 font-mono text-label" disabled={!canEdit}
value={r.when?.[x.name] ?? ""} placeholder="-" onChange={(e) => cell(i, "when", x.name, e.target.value)} /></td>)}
{outputs.map((x) => <td key={x.name} className="bg-brand/[0.03] px-1"><input className="input h-7 text-label" disabled={!canEdit}
value={r.then?.[x.name] ?? ""} onChange={(e) => cell(i, "then", x.name, e.target.value)} /></td>)}
{prio && <td className="px-1"><input className="input h-7 text-label" type="number" disabled={!canEdit} value={r.priority ?? ""}
onChange={(e) => { const rs = [...rows]; rs[i] = { ...r, priority: e.target.value }; set("rows", rs); }} /></td>}
<td className="px-1"><input className="input h-7 text-label" disabled={!canEdit} value={r.note || ""}
onChange={(e) => { const rs = [...rows]; rs[i] = { ...r, note: e.target.value }; set("rows", rs); }} /></td>
<td>{canEdit && <button className="btn btn-ghost btn-sm" onClick={() => set("rows", rows.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}</td>
</tr>
))}
<tr className="border-t border-line bg-ink/[0.02]">
<td className="px-1 text-center text-muted">其他</td>
<td colSpan={inputs.length} className="px-1 text-label text-muted">上面都不满足时</td>
{outputs.map((x) => <td key={x.name} className="px-1 py-0.5"><input className="input h-7 text-label" disabled={!canEdit}
value={spec.default?.[x.name] ?? ""} onChange={(e) => set("default", { ...(spec.default || {}), [x.name]: e.target.value })} /></td>)}
<td colSpan={prio ? 3 : 2} />
</tr>
</tbody>
</table>
</div>
<div className="flex flex-wrap items-start gap-2">
{canEdit && <button className="btn btn-sm" onClick={() => set("rows", [...rows, { when: {}, then: {}, note: "" }])}><Plus className="h-3.5 w-3.5" />加一行</button>}
<DecisionCheck spec={spec} />
</div>
<p className="hint">条件格的写法:<code>>= 5000</code>、<code>[0, 3]</code>(0 到 3)、<code>'紧急'</code>(等于);留空表示不限。</p>
</div>
);
}
function AiFields({ spec, set, canEdit, meta }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta }) {
const fs: string[] = spec.functions || [];
return (
<div className="space-y-3">
<Field label="分析指令" required><textarea className="input min-h-[90px]" value={spec.instructions || ""} disabled={!canEdit} onChange={(e) => set("instructions", e.target.value)} /></Field>
<Field label="它可以查什么" hint="只能查,不能改数据">
<div className="flex flex-wrap gap-1.5">
{meta.readonly_functions.map((f) => (
<label key={f.name} className={cn("chip cursor-pointer", fs.includes(f.name) && "border-brand text-brand")} title={f.description}>
<input type="checkbox" className="hidden" disabled={!canEdit} checked={fs.includes(f.name)}
onChange={(e) => set("functions", e.target.checked ? [...fs, f.name] : fs.filter((x) => x !== f.name))} />
{f.title}
</label>
))}
</div>
</Field>
<Field label="输入"><InputsEditor value={spec.inputs || []} disabled={!canEdit} onChange={(v) => set("inputs", v)} /></Field>
<Field label="按哪些字段回答" hint="定义了字段,流程卡就能按 AI 的回答分支(标「由 AI 判断」)">
<Rows items={spec.output_fields || []} disabled={!canEdit} onChange={(v) => set("output_fields", v)} empty={{ name: "", label: "", type: "string", options: [] }} addText="加一个字段"
render={(it: any, up) => (<>
<input className="input h-7 w-28 font-mono text-label" placeholder="英文名" value={it.name} onChange={(e) => up({ ...it, name: e.target.value })} />
<input className="input h-7 w-32" placeholder="中文名" value={it.label} onChange={(e) => up({ ...it, label: e.target.value })} />
<Select className="input h-7 w-24" value={it.type || "string"} onChange={(e) => up({ ...it, type: e.target.value })}>
<option value="string">文字</option><option value="number">数字</option><option value="boolean">是否</option><option value="list">列表</option>
</Select>
{it.type === "string" && <input className="input h-7 flex-1" placeholder="可选值(逗号隔开,做分类用)" value={(it.options || []).join(",")}
onChange={(e) => up({ ...it, options: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean) })} />}
</>)} />
</Field>
</div>
);
}
/** 试跑:规则、决策表、周期、动作用当前表单里的定义;聚合与 AI 分析用已保存的工作副本(要查数据/调模型)。 */
export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kind: string; spec: any; name: string }) {
const cat = spec.category;
const init = () => {
if (kind === "action") return Object.fromEntries((spec.params || []).map((p: any) => [p.name, p.default ?? ""]));
if (cat === "aggregate") return {};
return Object.fromEntries(fnInputNames(spec).map((p) => [p.name, p.default ?? ""]));
};
const [vals, setVals] = useState<Record<string, any>>(init);
const [objKey, setObjKey] = useState("");
const [aggArgs, setAggArgs] = useState<any>({ dimensions: [], time: "" });
const [out, setOut] = useState<any>(null);
const [busy, setBusy] = useState(false);
useEffect(() => { setVals(init()); setOut(null); }, [cat, kind, JSON.stringify(spec.params), JSON.stringify(spec.inputs)]); // eslint-disable-line react-hooks/exhaustive-deps
const num = (v: any) => (v !== "" && !Number.isNaN(Number(v)) ? Number(v) : v);
const run = async () => {
setBusy(true); setOut(null);
try {
const clean = Object.fromEntries(Object.entries(vals).filter(([, v]) => v !== "").map(([k, v]) => [k, num(v)]));
let args: any = cat === "ai" ? vals : clean; // 函数一律收扁平的输入
if (cat === "aggregate") args = { ...clean, dimensions: aggArgs.dimensions, time: aggArgs.time || undefined, object_key: objKey || undefined };
const needSaved = cat === "aggregate" || cat === "ai";
if (needSaved && !concept) throw new Error("先保存成草稿,才能试跑聚合函数与 AI 分析");
const r = needSaved ? await onto.tryConcept(concept!.id, args, objKey)
: await onto.trySpec(kind, spec, args, objKey, name);
setOut(r);
} catch (e) { setOut({ error: errText(e) }); } finally { setBusy(false); }
};
const dims = Object.keys(concept?.bindings.find((b) => b.target_kind === "metric_expr")?.ref?.dimensions || {});
const labelOf = (k: string) => {
const defs: any[] = kind === "action" ? spec.params || [] : fnInputNames(spec);
return defs.find((p) => (typeof p === "string" ? p : p.name) === k)?.label || k;
};
const paramOf = (k: string) => (kind === "action" ? (spec.params || []).find((p: any) => p.name === k) : null);
return (
<div className="space-y-2">
{cat === "aggregate" ? (
<div className="flex flex-wrap items-end gap-2">
<Field label="按维度拆分">
<div className="flex flex-wrap gap-1">
{dims.map((d) => (
<button key={d} className={cn("chip", aggArgs.dimensions.includes(d) && "border-brand text-brand")}
onClick={() => setAggArgs({ ...aggArgs, dimensions: aggArgs.dimensions.includes(d) ? aggArgs.dimensions.filter((x: string) => x !== d) : [...aggArgs.dimensions, d] })}>{d}</button>
))}
{!dims.length && <span className="text-label text-muted">不拆分</span>}
</div>
</Field>
<Field label="统计时间"><Select className="input w-32" value={aggArgs.time} onChange={(e) => setAggArgs({ ...aggArgs, time: e.target.value })}>
<option value="">不限</option><option value="current">本期</option><option value="last">上期</option></Select></Field>
</div>
) : (
<div className="flex flex-wrap items-end gap-2">
{Object.keys(vals).map((k) => (
<Field key={k} label={labelOf(k)}>
{paramOf(k) ? <div className="w-48"><ParamInput p={paramOf(k)} value={vals[k]} onChange={(v) => setVals({ ...vals, [k]: v })} /></div>
: <input className="input w-40" value={vals[k]} onChange={(e) => setVals({ ...vals, [k]: e.target.value })} />}
</Field>
))}
{kind === "action" && spec.target_type && (
<Field label="对哪一个试"><ObjectPicker className="w-64" type={spec.target_type} value={objKey} onChange={setObjKey} /></Field>
)}
{!Object.keys(vals).length && kind !== "action" && <span className="text-label text-muted">不需要填什么,直接试。</span>}
</div>
)}
<button className="btn" disabled={busy} onClick={() => void run()}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}{kind === "action" ? "看看会做什么" : "算一次"}
</button>
{out && (kind === "action" && !out.error ? (
<div className="rounded-lg border border-line p-4"><PreviewView preview={out} /></div>
) : <ResultView data={out} />)}
</div>
);
}
function LineageView({ data }: { data: { nodes: any[]; edges: any[] } }) {
const groups: [string, string][] = [["object_type", "对象"], ["function", "函数"], ["link_type", "关系"], ["action", "动作"],
["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-caption 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>
);
})}
</div>
);
}