MetricBuilder.tsx
8.44 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
/** 指标怎么算:选「怎么聚合 + 哪一列」,不用手写表达式。写不进这几种的(复杂公式)切到「自己写」。 */
import { Plus, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import { Segmented } from "@/components/ui";
import { Select } from "@/components/kit";
type Agg = "sum" | "count" | "count_distinct" | "avg" | "max" | "min" | "ratio" | "custom";
const AGGS: { key: Agg; label: string }[] = [
{ key: "sum", label: "求和" }, { key: "count", label: "数个数" }, { key: "count_distinct", label: "去重计数" },
{ key: "avg", label: "平均" }, { key: "max", label: "最大" }, { key: "min", label: "最小" },
{ key: "ratio", label: "两数相除" }, { key: "custom", label: "自己写" },
];
const FN: Record<string, string> = { sum: "SUM", avg: "AVG", max: "MAX", min: "MIN" };
const OPS: [string, string][] = [["=", "等于"], ["<>", "不等于"], [">", "大于"], [">=", "不小于"], ["<", "小于"], ["<=", "不大于"]];
interface Parsed { agg: Agg; a: string; b: string }
/** 把表达式认回构建器能表示的形状;认不出来就是「自己写」。 */
export function parseExpr(expr: string): Parsed {
const e = (expr || "").trim();
let m = /^(SUM|AVG|MAX|MIN)\(\s*`?(\w+)`?\s*\)$/i.exec(e);
if (m) return { agg: m[1].toLowerCase() as Agg, a: m[2], b: "" };
if (/^COUNT\(\s*\*\s*\)$/i.test(e)) return { agg: "count", a: "", b: "" };
m = /^COUNT\(\s*DISTINCT\s+`?(\w+)`?\s*\)$/i.exec(e);
if (m) return { agg: "count_distinct", a: m[1], b: "" };
m = /^SUM\(\s*`?(\w+)`?\s*\)\s*\/\s*NULLIF\(\s*SUM\(\s*`?(\w+)`?\s*\)\s*,\s*0\s*\)$/i.exec(e);
if (m) return { agg: "ratio", a: m[1], b: m[2] };
return { agg: e ? "custom" : "sum", a: "", b: "" };
}
export function buildExpr(p: Parsed): string {
if (p.agg === "count") return "COUNT(*)";
if (p.agg === "count_distinct") return p.a ? `COUNT(DISTINCT ${p.a})` : "";
if (p.agg === "ratio") return p.a && p.b ? `SUM(${p.a}) / NULLIF(SUM(${p.b}), 0)` : "";
if (p.agg === "custom") return "";
return p.a ? `${FN[p.agg]}(${p.a})` : "";
}
export function ExprBuilder({ value, cols, disabled, onChange, labels = {} }: {
value: string; cols: string[]; disabled?: boolean; onChange: (expr: string) => void;
/** 列 / 属性的中文名,下拉里显示它 */
labels?: Record<string, string>;
}) {
const [p, setP] = useState<Parsed>(() => parseExpr(value));
// 外面换了一个指标 / 重新载入时跟上
useEffect(() => { if (buildExpr(p) !== value && p.agg !== "custom") setP(parseExpr(value)); }, [value]); // eslint-disable-line react-hooks/exhaustive-deps
const set = (patch: Partial<Parsed>) => {
const next = { ...p, ...patch };
setP(next);
if (next.agg !== "custom") onChange(buildExpr(next));
};
const col = (key: "a" | "b", placeholder: string) => (
<Select className="input w-48" value={p[key]} disabled={disabled} onChange={(e) => set({ [key]: e.target.value })}>
<option value="">{placeholder}</option>
{cols.map((c) => <option key={c} value={c}>{labels[c] || c}</option>)}
</Select>
);
return (
<div className="space-y-2">
<Segmented value={p.agg} onChange={(k) => !disabled && set({ agg: k })} options={AGGS} />
{p.agg === "custom" ? (
<input className="input font-mono" value={value} disabled={disabled} placeholder="例如 SUM(a) - SUM(b)"
onChange={(e) => onChange(e.target.value)} />
) : (
<div className="flex flex-wrap items-center gap-2 text-label">
{p.agg === "count" ? <span className="text-muted">数一共有多少个(配合下面的「只算哪些」用)</span>
: p.agg === "ratio" ? <>{col("a", "分子:哪一项求和")}<span className="text-muted">除以</span>{col("b", "分母:哪一项求和")}</>
: col("a", "选一项")}
</div>
)}
</div>
);
}
/** 固定过滤条件:选列、比较、值,拼成一条条件;老的手写条件原样保留。 */
export function FilterList({ value, cols, disabled, onChange, labels = {} }: {
value: string[]; cols: string[]; disabled?: boolean; onChange: (v: string[]) => void; labels?: Record<string, string>;
}) {
const pretty = (f: string) => {
const m = /^(\w+)\s*(=|<>|>=|<=|>|<)\s*(.+)$/.exec(f);
if (!m) return f;
const v = m[3].replace(/^'|'$/g, "");
return `${labels[m[1]] || m[1]} ${OPS.find(([k]) => k === m[2])?.[1] || m[2]} ${v === "1" && labels[m[1]] ? "是" : v}`;
};
const [c, setC] = useState("");
const [op, setOp] = useState("=");
const [v, setV] = useState("");
const add = () => {
if (!c || v === "") return;
const lit = /^-?\d+(\.\d+)?$/.test(v.trim()) ? v.trim() : `'${v.replace(/'/g, "''")}'`;
onChange([...value, `${c} ${op} ${lit}`]);
setV("");
};
return (
<div className="space-y-1.5">
{value.map((f, i) => (
<div key={i} className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate rounded-md bg-ink/5 px-2.5 py-1.5 text-label" title={f}>{pretty(f)}</span>
{!disabled && <button className="btn btn-ghost btn-sm" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{!disabled && (
<div className="flex flex-wrap items-center gap-1.5">
<Select className="input h-8 w-40" value={c} onChange={(e) => setC(e.target.value)}>
<option value="">选一项</option>{cols.map((x) => <option key={x} value={x}>{labels[x] || x}</option>)}
</Select>
<Select className="input h-8 w-28" value={op} onChange={(e) => setOp(e.target.value)}>
{OPS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}
</Select>
<input className="input h-8 w-36" placeholder="值" value={v} onChange={(e) => setV(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") add(); }} />
<button className="btn btn-sm" disabled={!c || v === ""} onClick={add}><Plus className="h-3.5 w-3.5" />加条件</button>
</div>
)}
</div>
);
}
/** 可拆分维度:叫什么、对应哪一列、它是不是某个对象(是的话取数时自动带出名称)。 */
export function DimensionList({ dims, types, cols, objects, disabled, onChange }: {
dims: Record<string, string>; types: Record<string, string>; cols: string[];
objects: { id: string; name: string }[]; disabled?: boolean;
onChange: (dims: Record<string, string>, types: Record<string, string>) => void;
}) {
const [name, setName] = useState("");
const rows = Object.entries(dims || {});
return (
<div className="space-y-1.5">
{rows.map(([k, v]) => (
<div key={k} className="flex flex-wrap items-center gap-2">
<input className="input h-8 w-28" value={k} disabled title="维度名:问句里怎么说它" />
<Select className="input h-8 w-40" value={v} disabled={disabled} onChange={(e) => onChange({ ...dims, [k]: e.target.value }, types)}>
{!cols.includes(v) && <option value={v}>{v}</option>}
{cols.map((c) => <option key={c}>{c}</option>)}
</Select>
<Select className="input h-8 w-40" value={types?.[k] || ""} disabled={disabled} title="这一列存的是哪个对象的主键"
onChange={(e) => { const t = { ...(types || {}) }; if (e.target.value) t[k] = e.target.value; else delete t[k]; onChange(dims, t); }}>
<option value="">不是对象(普通分类)</option>
{objects.map((o) => <option key={o.id} value={o.id}>是「{o.name}」</option>)}
</Select>
{!disabled && <button className="btn btn-ghost btn-sm" onClick={() => {
const d = { ...dims }; delete d[k]; const t = { ...(types || {}) }; delete t[k]; onChange(d, t);
}}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{!disabled && (
<div className="flex items-center gap-1.5">
<input className="input h-8 w-44" placeholder="维度名,如 仓库、品牌" value={name} onChange={(e) => setName(e.target.value)} />
<button className="btn btn-sm" disabled={!name.trim() || name.trim() in (dims || {})} onClick={() => {
const n = name.trim();
const guess = objects.find((o) => o.name === n);
onChange({ ...(dims || {}), [n]: cols[0] || "" }, guess ? { ...(types || {}), [n]: guess.id } : types);
setName("");
}}><Plus className="h-3.5 w-3.5" />加维度</button>
</div>
)}
</div>
);
}