ObjectEditor.tsx
21.2 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
/**
* 对象的属性表单:从数据表来的属性(怎么叫、怎么显示、值类型、能不能改、记不记历史)、算出来的属性(公式)、
* 状态机(状态怎么流转、每一步由哪个动作完成),以及接口(多类对象共有的形状)。
*/
import { Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { FormSection, Select } from "@/components/kit";
import { Field } from "@/components/ui";
import { onto, type ConceptBrief, type ValueTypeDef } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { readable, VarInput, type VarDef } from "./ActionEditor";
const TYPES: [string, string][] = [["string", "文字"], ["number", "数字"], ["integer", "整数"], ["boolean", "是 / 否"],
["date", "日期"], ["datetime", "日期时间"], ["text", "多行文字"]];
const FORMATS: [string, string][] = [["", "默认"], ["money", "金额"], ["quantity", "数量"], ["percent", "百分比"], ["status", "状态标签"]];
const TONES: [string, string, string][] = [["neutral", "灰", "bg-ink/10"], ["info", "蓝", "bg-brand/30"], ["ok", "绿", "bg-ok/40"],
["warn", "橙", "bg-warn/50"], ["danger", "红", "bg-bad/50"]];
/** 状态的每个取值用什么颜色。 */
function TonesEditor({ value, onChange, disabled, bool }: { value: Record<string, string>; onChange: (v: Record<string, string>) => void; disabled: boolean; bool?: boolean }) {
const entries = bool ? [["1", value["1"] || "neutral"], ["0", value["0"] || "neutral"]] : Object.entries(value || {});
return (
<div className="flex flex-wrap items-center gap-2">
{entries.map(([k, tone]) => (
<span key={k} className="inline-flex items-center gap-1 rounded-md border border-line py-0.5 pl-2 pr-1 text-label">
<span>{bool ? (k === "1" ? "是" : "否") : k}</span>
{TONES.map(([t, name, cls]) => (
<button key={t} type="button" disabled={disabled} title={name} onClick={() => onChange({ ...value, [k]: t })}
className={cn("h-4 w-4 rounded-full border", cls, tone === t ? "border-ink ring-1 ring-ink/40" : "border-transparent")} />
))}
{!bool && !disabled && <button className="px-0.5 text-muted hover:text-bad" title="去掉" onClick={() => { const n = { ...value }; delete n[k]; onChange(n); }}>×</button>}
</span>
))}
{!bool && !disabled && (
<input className="input h-7 w-28 text-label" placeholder="加一个取值,回车"
onKeyDown={(e) => {
const v = (e.target as HTMLInputElement).value.trim();
if (e.key === "Enter" && v) { onChange({ ...value, [v]: "neutral" }); (e.target as HTMLInputElement).value = ""; }
}} />
)}
</div>
);
}
export function ObjectEditor({ spec, set, canEdit, all }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; all: ConceptBrief[] }) {
const disabled = !canEdit;
const props: any[] = spec.properties || [];
const [vts, setVts] = useState<ValueTypeDef[]>([]);
useEffect(() => { void onto.valueTypes().then(setVts).catch(() => undefined); }, []);
const interfaces = all.filter((x) => x.kind === "object_type" && x.abstract);
const actionNames = all.filter((x) => x.kind === "action").map((x) => x.display_name || x.name);
const base = props.map((p, i) => ({ p, i })).filter(({ p }) => !p.expression && !p._derived);
const derived = props.map((p, i) => ({ p, i })).filter(({ p }) => p.expression || p._derived);
const up = (i: number, patch: any) => set("properties", props.map((p, j) => (j === i ? { ...p, ...patch } : p)));
const del = (i: number) => set("properties", props.filter((_, j) => j !== i));
const vars: VarDef[] = useMemo(() => [
...props.filter((p) => p.name).map((p) => ({ expr: p.name, label: p.display_name || p.name, group: "这个对象的属性" })),
...["share", "total"].map((f) => ({ expr: `${f}(`, label: f === "share" ? "占同组合计的比例 share(数量, 按什么分组)" : "同组合计 total(数量, 按什么分组)", group: "函数" })),
{ expr: "days_between(", label: "相隔几天 days_between(开始, 结束)", group: "函数" }, { expr: "today()", label: "今天 today()", group: "函数" },
{ expr: "max(", label: "取大 max(a, b)", group: "函数" }, { expr: "min(", label: "取小 min(a, b)", group: "函数" },
{ expr: "round(", label: "四舍五入 round(数, 位数)", group: "函数" }, { expr: "floor(", label: "向下取整 floor(数)", group: "函数" },
{ expr: "safe_div(", label: "相除(除数为 0 时不报错)safe_div(a, b)", group: "函数" }, { expr: "coalesce(", label: "取第一个不为空的 coalesce(a, b)", group: "函数" },
], [props]); // eslint-disable-line react-hooks/exhaustive-deps
const others = all.filter((x) => x.kind === "object_type").map((x) => x.name);
return (
<>
<FormSection title="接口" desc="接口只规定一组属性的形状;几类对象实现同一个接口后,函数、动作、预警可以写在接口上,一次覆盖它们">
<label className="flex items-center gap-2 text-label">
<input type="checkbox" checked={!!spec.abstract} disabled={disabled}
onChange={(e) => { set("abstract", e.target.checked); if (e.target.checked) set("implements", []); }} />
这是一个接口(没有自己的数据来源,数据来自实现它的对象)
</label>
{!spec.abstract && (
<ImplementsEditor value={spec.implements || []} interfaces={interfaces} props={props} disabled={disabled}
onChange={(v) => set("implements", v)} />
)}
</FormSection>
<FormSection title="属性" desc="来自数据表的每一列。改「显示名」和「显示成」不影响数据;值类型统一单位、格式和写入校验"
right={canEdit && <button className="btn btn-sm" onClick={() => set("properties", [...props, { name: "", data_type: "string" }])}><Plus className="h-3.5 w-3.5" />加属性</button>}>
<div className="overflow-auto rounded-lg border border-line">
<table className="tbl">
<thead><tr>
<th>显示名</th><th>字段</th><th className="w-28">类型</th><th className="w-28">值类型</th><th className="w-28">显示成</th><th className="w-20">单位</th>
<th className="w-14 text-center">主键</th><th className="w-16 text-center" title="允许动作修改这个属性">可修改</th>
<th className="w-16 text-center" title="每次同步记一个点,变化记进变化记录:预警可以和历史比">记历史</th><th className="w-10" />
</tr></thead>
<tbody>
{base.map(({ p, i }) => (
<tr key={i} className="align-top">
<td><input className="input h-8" value={p.display_name || ""} disabled={disabled} placeholder={p.name} onChange={(e) => up(i, { display_name: e.target.value })} /></td>
<td><input className="input h-8 font-mono text-[13px]" value={p.name} disabled={disabled} onChange={(e) => up(i, { name: e.target.value })} /></td>
<td><Select className="input h-8" value={p.data_type === "enum" ? "string" : p.data_type} disabled={disabled} onChange={(e) => up(i, { data_type: e.target.value })}>
{TYPES.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select></td>
<td>
<Select className="input h-8" value={p.value_type || ""} disabled={disabled} onChange={(e) => up(i, { value_type: e.target.value })}>
<option value="">不用</option>
{vts.map((v) => <option key={v.name} value={v.name}>{v.name}{v.unit ? `(${v.unit})` : ""}</option>)}
</Select>
</td>
<td>
<Select className="input h-8" value={p.format || ""} disabled={disabled} onChange={(e) => up(i, { format: e.target.value })}>
{FORMATS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select>
</td>
<td><input className="input h-8" value={p.unit || ""} disabled={disabled} onChange={(e) => up(i, { unit: e.target.value })} /></td>
<td className="text-center"><input type="radio" name="obj-key" checked={!!p.is_key} disabled={disabled}
onChange={() => set("properties", props.map((x, j) => ({ ...x, is_key: j === i })))} /></td>
<td className="text-center"><input type="checkbox" checked={!!p.is_writable && !p.lifecycle} disabled={disabled || !!p.lifecycle}
title={p.lifecycle ? "状态机属性只能经由动作流转" : undefined}
onChange={(e) => up(i, { is_writable: e.target.checked })} /></td>
<td className="text-center"><input type="checkbox" checked={!!p.track || !!p.lifecycle} disabled={disabled || !!p.lifecycle}
onChange={(e) => up(i, { track: e.target.checked })} /></td>
<td>{canEdit && <button className="rounded p-1 text-muted hover:text-bad" title="删除" onClick={() => del(i)}><Trash2 className="h-3.5 w-3.5" /></button>}</td>
</tr>
))}
</tbody>
</table>
</div>
{base.filter(({ p }) => p.format === "status").length > 0 && (
<div className="space-y-2">
<p className="text-label font-medium">状态标签的颜色</p>
{base.filter(({ p }) => p.format === "status").map(({ p, i }) => (
<div key={i} className="grid grid-cols-[7rem_minmax(0,1fr)] items-start gap-3">
<span className="pt-1 text-label text-muted">{p.display_name || p.name}</span>
<TonesEditor value={p.tones || {}} disabled={disabled} bool={p.data_type === "boolean"} onChange={(v) => up(i, { tones: v })} />
</div>
))}
</div>
)}
</FormSection>
<FormSection title="算出来的属性" desc="用公式从别的属性算出来,可以像普通属性一样筛选、排序、进指标"
right={canEdit && <button className="btn btn-sm" onClick={() => {
let n = 1; while (props.some((p) => p.name === `calc${n}`)) n += 1;
set("properties", [...props, { name: `calc${n}`, display_name: "", data_type: "number", expression: "", _derived: true, format: "" }]);
}}><Plus className="h-3.5 w-3.5" />加一个</button>}>
{!derived.length && <p className="text-label text-muted">还没有。例如「可用库存 = 在库 − 预留 + 在途」。</p>}
<div className="space-y-3">
{derived.map(({ p, i }) => (
<div key={i} className="relative rounded-lg border border-line p-4 pr-11">
<div className="grid gap-3 sm:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_7rem_7rem_5rem]">
<Field label="显示名" required><input className="input" value={p.display_name || ""} disabled={disabled} onChange={(e) => up(i, { display_name: e.target.value })} /></Field>
<Field label="字段"><input className="input font-mono text-[13px]" value={p.name} disabled={disabled} onChange={(e) => up(i, { name: e.target.value })} /></Field>
<Field label="结果是">
<Select className="input" value={p.data_type} disabled={disabled} onChange={(e) => up(i, { data_type: e.target.value })}>
<option value="number">数字</option><option value="boolean">是 / 否</option><option value="string">文字</option><option value="date">日期</option>
</Select>
</Field>
<Field label="显示成">
<Select className="input" value={p.format || ""} disabled={disabled} onChange={(e) => up(i, { format: e.target.value })}>
{FORMATS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</Select>
</Field>
<Field label="单位"><input className="input" value={p.unit || ""} disabled={disabled} onChange={(e) => up(i, { unit: e.target.value })} /></Field>
</div>
<Field label="公式" className="mt-3" hint={others.length ? `指向别的对象时可以写「对象名.属性」,如 ${others[0]}.某属性` : undefined}>
<VarInput mode="expr" vars={vars.filter((v) => v.expr !== p.name)} value={p.expression || ""} disabled={disabled} read={false}
onChange={(v) => up(i, { expression: v, _derived: true })} />
{p.expression && <p className="hint">{readable(p.expression, vars.filter((v) => v.group !== "函数"))}</p>}
</Field>
{p.format === "status" && (
<div className="mt-3"><TonesEditor value={p.tones || {}} disabled={disabled} bool={p.data_type === "boolean"} onChange={(v) => up(i, { tones: v })} /></div>
)}
{canEdit && <button className="absolute right-2 top-2 rounded p-1.5 text-muted hover:bg-bad/10 hover:text-bad" title="删除" onClick={() => del(i)}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
</div>
</FormSection>
<LifecycleEditor props={props} up={up} disabled={disabled} actionNames={actionNames} />
<FormSection title="标题" desc="列表和链接里怎么称呼一个对象">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="用哪个属性当名称">
<Select className="input" value={spec.label_property || ""} disabled={disabled || !!spec.title_template} onChange={(e) => set("label_property", e.target.value)}>
<option value="">用主键</option>
{base.map(({ p }) => <option key={p.name} value={p.name}>{p.display_name || p.name}</option>)}
</Select>
</Field>
<Field label="或者自己拼一个" hint="用 {字段} 引用属性,如 {po_no} {part_id} ×{qty}">
<input className="input" value={spec.title_template || ""} disabled={disabled} onChange={(e) => set("title_template", e.target.value)} />
</Field>
</div>
</FormSection>
</>
);
}
/** 实现了哪些接口:接口的每个属性对上这类对象的哪个属性(同名可以不写)。 */
function ImplementsEditor({ value, onChange, interfaces, props, disabled }: {
value: { interface: string; mapping: Record<string, string> }[]; onChange: (v: any[]) => void;
interfaces: ConceptBrief[]; props: any[]; disabled: boolean;
}) {
const up = (i: number, patch: any) => onChange(value.map((x, j) => (j === i ? { ...x, ...patch } : x)));
return (
<div className="space-y-2">
{value.map((it, i) => (
<div key={i} className="flex flex-wrap items-center gap-2 rounded-lg border border-line p-2">
<span className="text-label text-muted">实现接口</span>
<Select className="input h-8 w-44" value={it.interface} disabled={disabled} onChange={(e) => up(i, { interface: e.target.value })}>
<option value="">选择接口</option>
{interfaces.map((x) => <option key={x.id} value={x.name}>{x.name}</option>)}
</Select>
<span className="text-label text-muted">属性对应</span>
<input className="input h-8 min-w-[16rem] flex-1 font-mono text-[13px]" disabled={disabled}
placeholder="接口属性=我的属性,逗号隔开;同名不用写"
value={Object.entries(it.mapping || {}).map(([k, v]) => `${k}=${v}`).join(",")}
onChange={(e) => up(i, { mapping: Object.fromEntries(e.target.value.split(/[,,]/).map((x) => x.split("="))
.filter((x) => x.length === 2 && x[0].trim() && x[1].trim()).map(([k, v]) => [k.trim(), v.trim()])) })} />
{!disabled && <button className="rounded p-1 text-muted hover:text-bad" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{!disabled && interfaces.length > 0 && (
<button className="btn btn-sm" onClick={() => onChange([...value, { interface: "", mapping: {} }])}><Plus className="h-3.5 w-3.5" />实现一个接口</button>
)}
{!interfaces.length && <p className="hint">还没有接口。新建一个对象并勾上「这是一个接口」,再回来选。</p>}
{props.length > 0 && value.some((x) => x.interface) && <p className="hint">我的属性:{props.map((p) => p.name).join("、")}</p>}
</div>
);
}
/** 状态机:状态属性有哪些状态、允许怎样流转、每条流转由哪个动作完成。状态只能经由动作改变。 */
function LifecycleEditor({ props, up, disabled, actionNames }: {
props: any[]; up: (i: number, patch: any) => void; disabled: boolean; actionNames: string[];
}) {
const candidates = props.map((p, i) => ({ p, i })).filter(({ p }) => !p.expression);
const withLc = candidates.filter(({ p }) => p.lifecycle);
const [pick, setPick] = useState("");
return (
<FormSection title="状态机" desc="单据、事项的状态只能按这里定义的流转走,每一步由指定的动作完成(直接改状态会被拒绝)">
{withLc.map(({ p, i }) => {
const lc = p.lifecycle;
const states: string[] = (lc.states || []).map((s: any) => (typeof s === "string" ? s : s.value));
const setLc = (patch: any) => up(i, { lifecycle: { ...lc, ...patch } });
return (
<div key={i} className="space-y-2 rounded-lg border border-line p-3">
<div className="flex flex-wrap items-center gap-2">
<b className="text-body">{p.display_name || p.name}</b>
<span className="text-label text-muted">状态(逗号隔开,第一个是初始状态)</span>
<input className="input h-8 min-w-[16rem] flex-1" disabled={disabled} value={states.join(",")}
onChange={(e) => setLc({ states: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean).map((v) => ({ value: v })),
initial: e.target.value.split(/[,,]/)[0]?.trim() || "" })} />
{!disabled && <button className="btn btn-ghost btn-sm text-bad" onClick={() => up(i, { lifecycle: undefined })}>去掉状态机</button>}
</div>
<div className="space-y-1.5">
{(lc.transitions || []).map((t: any, k: number) => {
const setT = (patch: any) => setLc({ transitions: lc.transitions.map((x: any, j: number) => (j === k ? { ...x, ...patch } : x)) });
return (
<div key={k} className="flex flex-wrap items-center gap-2 text-label">
<span className="text-muted">从</span>
<input className="input h-8 w-44" disabled={disabled} placeholder="哪些状态(逗号隔开)" value={(t.from || []).join(",")}
onChange={(e) => setT({ from: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean) })} />
<span className="text-muted">到</span>
<Select className="input h-8 w-32" value={t.to || ""} disabled={disabled} onChange={(e) => setT({ to: e.target.value })}>
<option value="">选择</option>{states.map((x) => <option key={x} value={x}>{x}</option>)}
</Select>
<span className="text-muted">由动作</span>
<Select className="input h-8 w-44" value={t.action || ""} disabled={disabled} onChange={(e) => setT({ action: e.target.value })}>
<option value="">任何声明了它的动作</option>{actionNames.map((x) => <option key={x} value={x}>{x}</option>)}
</Select>
{!disabled && <button className="rounded p-1 text-muted hover:text-bad" onClick={() => setLc({ transitions: lc.transitions.filter((_: any, j: number) => j !== k) })}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
);
})}
{!disabled && <button className="btn btn-sm" onClick={() => setLc({ transitions: [...(lc.transitions || []), { from: [], to: "", action: "" }] })}><Plus className="h-3.5 w-3.5" />加一条流转</button>}
</div>
</div>
);
})}
{!disabled && (
<div className="flex items-center gap-2">
<Select className="input h-8 w-48" value={pick} onChange={(e) => setPick(e.target.value)}>
<option value="">给哪个属性加状态机</option>
{candidates.filter(({ p }) => !p.lifecycle).map(({ p, i }) => <option key={i} value={String(i)}>{p.display_name || p.name}</option>)}
</Select>
<button className="btn btn-sm" disabled={!pick} onClick={() => {
const i = Number(pick); const p = props[i];
const states = (p.enum_values?.length ? p.enum_values : ["待处理", "处理中", "已完成"]).map((v: string) => ({ value: v }));
up(i, { lifecycle: { states, transitions: [], initial: states[0].value } }); setPick("");
}}><Plus className="h-3.5 w-3.5" />加状态机</button>
</div>
)}
{!withLc.length && disabled && <p className="text-label text-muted">没有状态机。</p>}
</FormSection>
);
}