MetricsPanel.tsx 25.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
import {
  AlertTriangle, Gauge, Loader2, Plus, ScrollText, Search, Sparkles, Trash2, Wand2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import {
  Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Field, Modal, Segmented, Spinner,
} from "@/components/ui";
import type { SmInstruction, SmMetric, SmMetricIssue, SmModel } from "@/lib/types";

/**
 * 指标与业务规则。
 *
 * 这两样是这套系统相对「纯 text-to-sql」的差异所在:
 * 指标把口径固定下来(渗透率的分母到底取交付数还是触客数),
 * 规则把 schema 表达不了的约定固定下来(品牌有两种写法、日期是字符串、
 * 不许悄悄丢掉筛选条件)。两者每次提问都会进提示词。
 *
 * 页面按分类分组:十几个指标、十七条规则平铺成两条长列表,第一次用的人
 * 只会觉得"乱",既看不出边界在哪,也不知道该从哪一条改起。
 */
const UNCATEGORIZED = "未分类";

const METRIC_CATEGORIES = ["规模", "渗透与转化", "单品成交", "目标达成", "其他"];
const RULE_CATEGORIES = ["时间口径", "口径与算法", "选表", "关联", "取值与写法", "结果呈现", "其他"];

/** 每个分类一句人话。新人看分类名往往还是不知道这堆东西管什么 */
const CATEGORY_HINT: Record<string, string> = {
  "规模": "有多少 —— 产值、交付、触客、订单这类总量",
  "渗透与转化": "占比 —— 分母取哪个决定了结果,口径最容易错",
  "单品成交": "单个商品的成交数与金额",
  "目标达成": "实际对目标的完成情况",
  "时间口径": "「最近」「本月」到底指哪一段",
  "口径与算法": "同一个词该怎么算,分母怎么取、怎么防除零",
  "选表": "同样的问题优先用哪张表回答",
  "关联": "哪些表能连、怎么连才不会把数字放大",
  "取值与写法": "库里实际存的是什么值,过滤条件该怎么写",
  "结果呈现": "返回哪些列、怎么排序、别名怎么起",
  [UNCATEGORIZED]: "还没归类,点上面的「自动归类」或逐条编辑",
};

type Tab = "metrics" | "rules";

function groupBy<T>(items: T[], key: (x: T) => string, order: string[]): [string, T[]][] {
  const map = new Map<string, T[]>();
  for (const it of items) {
    const k = key(it).trim() || UNCATEGORIZED;
    (map.get(k) ?? map.set(k, []).get(k)!).push(it);
  }
  const rank = (k: string) => {
    const i = order.indexOf(k);
    return i === -1 ? (k === UNCATEGORIZED ? order.length + 1 : order.length) : i;
  };
  return [...map.entries()].sort((a, b) => rank(a[0]) - rank(b[0]) || a[0].localeCompare(b[0]));
}

export function MetricsPanel({ dsId }: { dsId: number }) {
  const [tab, setTab] = useState<Tab>("metrics");
  const [metrics, setMetrics] = useState<SmMetric[] | null>(null);
  const [issues, setIssues] = useState<SmMetricIssue[]>([]);
  const [instructions, setInstructions] = useState<SmInstruction[]>([]);
  const [models, setModels] = useState<SmModel[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [keyword, setKeyword] = useState("");
  const [editing, setEditing] = useState<Partial<SmMetric> | null>(null);
  const [editingRule, setEditingRule] = useState<Partial<SmInstruction> | null>(null);
  const [del, setDel] = useState<{ kind: "metric" | "rule"; id: number; label: string } | null>(null);
  const [sorting, setSorting] = useState(false);

  const load = useCallback(() => {
    Promise.all([
      api.sqlMetrics(dsId), api.metricIssues(dsId),
      api.sqlInstructions(dsId), api.sqlModels(dsId, true),
    ]).then(([m, i, ins, mo]) => {
      setMetrics(m); setIssues(i); setInstructions(ins); setModels(mo); setError(null);
    }).catch((e) => setError(e instanceof Error ? e.message : String(e)));
  }, [dsId]);

  useEffect(load, [load]);

  const issueOf = (id: number) => issues.find((i) => i.metric_id === id);
  const tableOf = (id: number) => models.find((m) => m.id === id)?.physical_table ?? "—";

  const remove = async () => {
    if (!del) return;
    try {
      if (del.kind === "metric") await api.deleteMetric(del.id);
      else await api.deleteInstruction(del.id);
      toast("ok", "已删除");
      load();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
    setDel(null);
  };

  const autoSort = async () => {
    setSorting(true);
    try {
      const r = await api.categorize(dsId);
      toast("ok", "已自动归类", `指标 ${r.metrics} 个、规则 ${r.instructions} 条。归类只影响展示,不影响生成`);
      load();
    } catch (e) {
      toast("error", "归类失败", e instanceof Error ? e.message : String(e));
    } finally { setSorting(false); }
  };

  const kw = keyword.trim().toLowerCase();
  const shownMetrics = useMemo(() => (metrics ?? []).filter((m) =>
    !kw || m.name.toLowerCase().includes(kw) || (m.display_name ?? "").toLowerCase().includes(kw)
    || (m.calibre_note ?? "").toLowerCase().includes(kw)
    || m.synonyms.some((s) => s.toLowerCase().includes(kw))), [metrics, kw]);
  const shownRules = useMemo(() => (instructions ?? []).filter((i) =>
    !kw || i.content.toLowerCase().includes(kw)), [instructions, kw]);

  if (error) return <ErrorNote onRetry={load}>{error}</ErrorNote>;
  if (!metrics) return <Card className="p-4"><Spinner /></Card>;

  const broken = issues.filter((i) => i.level === "error");
  const unsorted = metrics.filter((m) => !m.category?.trim()).length
    + instructions.filter((i) => !i.category?.trim()).length;

  return (
    <div className="space-y-3">
      {/* 先说清这两样各是什么。不解释的话,"指标"和"规则"对新人就是两个同义的抽象名词 */}
      <div className="grid gap-2 sm:grid-cols-2">
        <button onClick={() => setTab("metrics")}
                className={cn("card flex items-start gap-2.5 p-3 text-left transition-colors",
                  tab === "metrics" ? "border-brand/40 bg-brand/[0.04]" : "hover:border-brand/30")}>
          <Gauge className="mt-0.5 h-4 w-4 shrink-0 text-brand" />
          <div className="min-w-0">
            <p className="text-[13px] font-medium">业务指标 · {metrics.length} 个</p>
            <p className="mt-0.5 text-[11.5px] leading-relaxed text-muted">
              把「渗透率怎么算、分母取哪个」这类口径固定下来。问到这些词,模型必须照着算,
              不许自己另起一套。
            </p>
          </div>
        </button>
        <button onClick={() => setTab("rules")}
                className={cn("card flex items-start gap-2.5 p-3 text-left transition-colors",
                  tab === "rules" ? "border-brand/40 bg-brand/[0.04]" : "hover:border-brand/30")}>
          <ScrollText className="mt-0.5 h-4 w-4 shrink-0 text-brand2" />
          <div className="min-w-0">
            <p className="text-[13px] font-medium">业务规则 · {instructions.length} 条</p>
            <p className="mt-0.5 text-[11.5px] leading-relaxed text-muted">
              表结构表达不了的约定:品牌名有几种写法、日期其实是字符串、哪两张表不能直接 JOIN。
              一条写对能少错很多。
            </p>
          </div>
        </button>
      </div>

      <Card>
        <CardHeader
          title={tab === "metrics" ? "业务指标" : "业务规则"}
          desc={tab === "metrics"
            ? "按业务分类分组。带「口径」标记的那几条最值钱,也最容易出错。"
            : "标了「默认注入」的每次提问都会进提示词;其余的按触发词匹配。"}
          right={
            <div className="flex flex-wrap items-center justify-end gap-1.5">
              {unsorted > 0 && (
                <button className="btn btn-sm" disabled={sorting} onClick={autoSort}
                        title="按关键词给还没分类的条目补一个分类。只填空,不动你改过的">
                  {sorting ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                           : <Wand2 className="h-3.5 w-3.5" />}
                  自动归类 {unsorted} 条
                </button>
              )}
              {tab === "metrics" ? (
                <button className="btn btn-primary btn-sm"
                        onClick={() => setEditing({ enabled: true, status: "verified" })}>
                  <Plus className="h-3.5 w-3.5" /> 新建指标
                </button>
              ) : (
                <button className="btn btn-primary btn-sm"
                        onClick={() => setEditingRule({ is_default: true, enabled: true, scope: "sql", priority: 50 })}>
                  <Plus className="h-3.5 w-3.5" /> 新建规则
                </button>
              )}
            </div>
          } />

        <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 pb-3">
          <div className="relative min-w-[200px] flex-1">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
            <input className="input pl-8"
                   placeholder={tab === "metrics" ? "搜指标名、同义词或口径" : "搜规则内容"}
                   value={keyword} onChange={(e) => setKeyword(e.target.value)} />
          </div>
          <Segmented<Tab> value={tab} onChange={setTab} options={[
            { key: "metrics", label: "指标", badge: <Badge>{shownMetrics.length}</Badge> },
            { key: "rules", label: "规则", badge: <Badge>{shownRules.length}</Badge> },
          ]} />
        </div>

        {tab === "metrics" && broken.length > 0 && (
          <div className="flex items-start gap-2 border-b border-line bg-bad/5 px-4 py-2.5">
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-bad" />
            <div className="text-[12.5px]">
              <p className="font-medium text-bad">{broken.length} 个指标当前不可用,已被排除在提示词之外</p>
              {broken.map((b) => (
                <p key={b.metric_id} className="mt-0.5 text-muted">{b.name}:{b.reason}</p>
              ))}
            </div>
          </div>
        )}

        {tab === "metrics" ? (
          shownMetrics.length === 0 ? (
            <Empty icon={<Gauge className="h-6 w-6" />}
                   title={kw ? "没有匹配的指标" : "还没有指标"}
                   desc={kw ? undefined : "定义一个指标,把「渗透率该怎么算、分母取哪个」这类口径固定下来。"} />
          ) : (
            groupBy(shownMetrics, (m) => m.category ?? "", METRIC_CATEGORIES).map(([cat, list]) => (
              <Group key={cat} name={cat} count={list.length}>
                {list.map((m) => {
                  const bad = issueOf(m.id);
                  return (
                    <div key={m.id}
                         className={cn("px-4 py-2.5", bad?.level === "error" && "bg-bad/[0.03]")}>
                      <div className="flex flex-wrap items-center gap-1.5">
                        <button className="min-w-0 flex-1 truncate text-left text-[13.5px] font-medium hover:text-brand"
                                onClick={() => setEditing(m)}>
                          {m.display_name || m.name}
                        </button>
                        {!m.enabled && <Badge>已停用</Badge>}
                        {bad && (
                          <Badge tone={bad.level === "error" ? "bg-bad/10 text-bad" : "bg-warn/10 text-warn"}>
                            {bad.level === "error" ? "不可用" : "有告警"}
                          </Badge>
                        )}
                        {m.calibre_note && <Badge tone="bg-brand/10 text-brand">有口径</Badge>}
                        <Badge tone="bg-ink/5 text-muted">{tableOf(m.base_model_id)}</Badge>
                        <button className="btn btn-ghost btn-sm text-bad"
                                onClick={() => setDel({ kind: "metric", id: m.id, label: m.name })}>
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                      <pre className="mt-1 overflow-x-auto rounded bg-ink/[0.05] px-2 py-1 font-mono text-[11.5px]">
                        {m.expression}
                      </pre>
                      {m.synonyms.length > 0 && (
                        <p className="mt-1 flex flex-wrap gap-1">
                          {m.synonyms.map((s) => (
                            <span key={s} className="chip px-1.5 py-0 text-[11px]">{s}</span>
                          ))}
                        </p>
                      )}
                      {m.calibre_note && (
                        // 口径单独高亮 —— 这是这套业务最容易出错、也最值钱的一段信息
                        <p className="mt-1.5 rounded-md border border-brand/30 bg-brand/5 px-2 py-1
                                      text-[12px] leading-relaxed text-brand">
                          口径:{m.calibre_note}
                        </p>
                      )}
                    </div>
                  );
                })}
              </Group>
            ))
          )
        ) : shownRules.length === 0 ? (
          <Empty icon={<ScrollText className="h-6 w-6" />}
                 title={kw ? "没有匹配的规则" : "还没有规则"}
                 desc={kw ? undefined : "比如「品牌名有多种写法,过滤要用 LIKE」这类,写一条能少错很多。"} />
        ) : (
          groupBy(shownRules, (i) => i.category ?? "", RULE_CATEGORIES).map(([cat, list]) => (
            <Group key={cat} name={cat} count={list.length}>
              {[...list].sort((a, b) => b.priority - a.priority).map((i) => (
                <div key={i.id} className={cn("flex items-start gap-2 px-4 py-2.5", !i.enabled && "opacity-50")}>
                  <div className="min-w-0 flex-1">
                    <p className="whitespace-pre-wrap text-[12.5px] leading-relaxed">{i.content}</p>
                    <p className="mt-1 flex flex-wrap items-center gap-1.5">
                      {i.is_default
                        ? <Badge tone="bg-ok/10 text-ok">默认注入</Badge>
                        : <Badge tone="bg-warn/10 text-warn">按条件匹配</Badge>}
                      {i.ds_id === 0 && <Badge>全局</Badge>}
                      <span className="text-[11px] text-muted">优先级 {i.priority}</span>
                      {i.condition_text && (
                        <span className="text-[11px] text-muted">触发词:{i.condition_text}</span>
                      )}
                    </p>
                  </div>
                  <button className="btn btn-ghost btn-sm shrink-0"
                          onClick={() => setEditingRule(i)}>编辑</button>
                  <button className="btn btn-ghost btn-sm shrink-0 text-bad"
                          onClick={() => setDel({ kind: "rule", id: i.id, label: i.content.slice(0, 40) })}>
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              ))}
            </Group>
          ))
        )}
      </Card>

      <MetricForm dsId={dsId} models={models} value={editing}
                  onClose={() => setEditing(null)}
                  onSaved={() => { setEditing(null); load(); }} />
      <RuleForm dsId={dsId} value={editingRule}
                onClose={() => setEditingRule(null)}
                onSaved={() => { setEditingRule(null); load(); }} />
      <Confirm open={!!del} danger title="确认删除?" body={del?.label ?? ""} confirmText="删除"
               onConfirm={remove} onClose={() => setDel(null)} />
    </div>
  );
}

/** 分组头。粘在顶上,长列表滚到一半也知道现在看的是哪一类 */
function Group({ name, count, children }: { name: string; count: number; children: React.ReactNode }) {
  return (
    <div>
      <div className="sticky top-0 z-10 flex items-baseline gap-2 border-y border-line bg-elevated px-4 py-1.5">
        <span className="text-[12px] font-semibold">{name}</span>
        <span className="text-[11px] tabular-nums text-muted">{count}</span>
        {CATEGORY_HINT[name] && (
          <span className="min-w-0 truncate text-[11px] text-muted">· {CATEGORY_HINT[name]}</span>
        )}
      </div>
      <div className="divide-y divide-line">{children}</div>
    </div>
  );
}

function MetricForm({ dsId, models, value, onClose, onSaved }: {
  dsId: number; models: SmModel[]; value: Partial<SmMetric> | null;
  onClose: () => void; onSaved: () => void;
}) {
  const [f, setF] = useState<Partial<SmMetric>>({});
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");
  useEffect(() => { setF(value ?? {}); setErr(""); }, [value]);

  const set = (k: keyof SmMetric, v: unknown) => setF((p) => ({ ...p, [k]: v }));

  const save = async () => {
    setSaving(true); setErr("");
    try {
      await api.upsertMetric(dsId, {
        id: f.id ?? null, name: f.name ?? "", display_name: f.display_name ?? "",
        category: f.category ?? "", description: f.description ?? "",
        base_model_id: f.base_model_id ?? 0,
        expression: f.expression ?? "", time_column: f.time_column ?? "",
        calibre_note: f.calibre_note ?? "", synonyms: f.synonyms ?? [],
        status: f.status ?? "verified", enabled: f.enabled ?? true,
      });
      toast("ok", "指标已保存");
      onSaved();
    } catch (e) {
      setErr(e instanceof Error ? e.message : String(e));
    } finally { setSaving(false); }
  };

  return (
    <Modal open={!!value} onClose={onClose} width="max-w-2xl"
           title={f.id ? "编辑指标" : "新建指标"}
           desc="指标 = 一个业务词 + 它唯一正确的算法。问到这个词,模型只能照这里算。"
           footer={
             <>
               {err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>}
               <button className="btn btn-sm" onClick={onClose}>取消</button>
               <button className="btn btn-primary btn-sm" disabled={saving || !f.name || !f.expression}
                       onClick={save}>
                 {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />} 保存
               </button>
             </>
           }>
      <div className="space-y-4">
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <Field label="指标名" required hint="模型按它匹配用户的问句">
            <input className="input" value={f.name ?? ""} placeholder="整车延保渗透率"
                   onChange={(e) => set("name", e.target.value)} />
          </Field>
          <Field label="展示名" hint="页面和结果里显示的名字,可以写得更完整">
            <input className="input" value={f.display_name ?? ""} placeholder="整车延保渗透率(交付口径)"
                   onChange={(e) => set("display_name", e.target.value)} />
          </Field>
        </div>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <Field label="分类" hint="只影响页面分组,不进提示词">
            <select className="input" value={f.category ?? ""}
                    onChange={(e) => set("category", e.target.value)}>
              <option value="">未分类</option>
              {METRIC_CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>
          <Field label="基表" required>
            <select className="input" value={f.base_model_id ?? 0}
                    onChange={(e) => set("base_model_id", Number(e.target.value))}>
              <option value={0}>选择…</option>
              {models.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
            </select>
          </Field>
        </div>
        <Field label="SQL 表达式" required
               hint="保存后系统会自动校验:表达式里引用了整列为空的列,这个指标会被标成不可用并排除出提示词。">
          <textarea className="input min-h-[64px] font-mono text-[12.5px]" value={f.expression ?? ""}
                    placeholder="ROUND(SUM(total_extended_warranty) / NULLIF(SUM(total_delivery_count), 0), 4)"
                    onChange={(e) => set("expression", e.target.value)} />
        </Field>
        <Field label="同义词" hint="逗号分隔。决定用户随口怎么问能命中这个指标 —— 漏了同义词,指标等于没定义">
          <input className="input" value={(f.synonyms ?? []).join(",")}
                 placeholder="延保渗透率,延保成交率,延保占比"
                 onChange={(e) => set("synonyms", e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean))} />
        </Field>
        <Field label="业务口径说明"
               hint="写清楚「什么情况下换哪个分母」。这段会原样进提示词,是整套系统最值钱的一块信息。">
          <textarea className="input min-h-[64px]" value={f.calibre_note ?? ""}
                    placeholder="分母取决于兜底类型:交付口径用总交付数,触客口径改用触客数。"
                    onChange={(e) => set("calibre_note", e.target.value)} />
        </Field>
      </div>
    </Modal>
  );
}

function RuleForm({ dsId, value, onClose, onSaved }: {
  dsId: number; value: Partial<SmInstruction> | null; onClose: () => void; onSaved: () => void;
}) {
  const [f, setF] = useState<Partial<SmInstruction>>({});
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");
  useEffect(() => { setF(value ?? {}); setErr(""); }, [value]);

  const save = async () => {
    setSaving(true); setErr("");
    try {
      await api.upsertInstruction({
        id: f.id ?? null, ds_id: f.ds_id ?? dsId, scope: "sql",
        category: f.category ?? "",
        is_default: f.is_default ?? true, condition_text: f.condition_text ?? "",
        content: f.content ?? "", priority: f.priority ?? 50, enabled: f.enabled ?? true,
      });
      toast("ok", "规则已保存");
      onSaved();
    } catch (e) {
      setErr(e instanceof Error ? e.message : String(e));
    } finally { setSaving(false); }
  };

  return (
    <Modal open={!!value} onClose={onClose} width="max-w-2xl"
           title={f.id ? "编辑业务规则" : "新建业务规则"}
           desc="只写你对着真实数据验证过的事实。写错一条会主动把模型带偏,比不写更糟。"
           footer={
             <>
               {err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>}
               <button className="btn btn-sm" onClick={onClose}>取消</button>
               <button className="btn btn-primary btn-sm" disabled={saving || !f.content} onClick={save}>
                 {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />} 保存
               </button>
             </>
           }>
      <div className="space-y-4">
        <Field label="规则内容" required>
          <textarea className="input min-h-[120px] leading-relaxed" value={f.content ?? ""}
                    placeholder="品牌名有多种写法,过滤品牌一律用 LIKE 模糊匹配,用等号会漏数据。"
                    onChange={(e) => setF((p) => ({ ...p, content: e.target.value }))} />
        </Field>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <Field label="分类" hint="只影响页面分组,不进提示词">
            <select className="input" value={f.category ?? ""}
                    onChange={(e) => setF((p) => ({ ...p, category: e.target.value }))}>
              <option value="">未分类</option>
              {RULE_CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>
          <Field label="优先级" hint="数字大的排前面,也更先进提示词">
            <input className="input" type="number" value={f.priority ?? 50}
                   onChange={(e) => setF((p) => ({ ...p, priority: Number(e.target.value) || 0 }))} />
          </Field>
        </div>
        <div className="space-y-2 rounded-lg border border-line bg-elevated/50 p-3">
          <label className="flex cursor-pointer items-start gap-2 text-[12.5px]">
            <input type="checkbox" className="mt-0.5" checked={f.is_default ?? true}
                   onChange={(e) => setF((p) => ({ ...p, is_default: e.target.checked }))} />
            <span>
              每次提问都注入
              <span className="block text-[11.5px] text-muted">
                关掉之后只有问句里出现下面的触发词才会用上,适合只对某类问题成立的规则
              </span>
            </span>
          </label>
          <label className="flex cursor-pointer items-start gap-2 text-[12.5px]">
            <input type="checkbox" className="mt-0.5" checked={f.ds_id === 0}
                   onChange={(e) => setF((p) => ({ ...p, ds_id: e.target.checked ? 0 : dsId }))} />
            <span>
              对所有数据源生效
              <span className="block text-[11.5px] text-muted">
                写法类的通用约定可以开;带具体表名列名的规则别开,换个库就是错的
              </span>
            </span>
          </label>
        </div>
        {!(f.is_default ?? true) && (
          <Field label="触发词" hint="空格分隔。问题里出现其中任意一个才注入这条规则">
            <input className="input" value={f.condition_text ?? ""} placeholder="渗透率 兜底 赔付"
                   onChange={(e) => setF((p) => ({ ...p, condition_text: e.target.value }))} />
          </Field>
        )}
      </div>
    </Modal>
  );
}