RulesPanel.tsx 13.9 KB
import { AlertTriangle, FunctionSquare, Loader2, Plus, ScrollText, Search, Trash2, Wand2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { go } from "@/lib/nav";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Field, Modal, Spinner } from "@/components/ui";
import type { SmInstruction, SmMetric, SmMetricIssue } from "@/lib/types";

/**
 * 问数的「取数规则」:表结构表达不了的约定(品牌名有几种写法、日期其实是字符串、哪两张表不能直接 JOIN)。
 * 按条件注入问数 Agent 的 SQL 提示词。
 *
 * 指标不在这里定义 —— 它是本体里的「聚合函数」,只定义一次;这里只读展示问数实际拿到的那份,方便排查。
 */
const UNCATEGORIZED = "未分类";
const RULE_CATEGORIES = ["时间口径", "口径与算法", "选表", "关联", "取值与写法", "结果呈现", "其他"];
const CATEGORY_HINT: Record<string, string> = {
  "时间口径": "「最近」「本月」到底指哪一段",
  "口径与算法": "同一个词该怎么算,分母怎么取、怎么防除零",
  "选表": "同样的问题优先用哪张表回答",
  "关联": "哪些表能连、怎么连才不会把数字放大",
  "取值与写法": "库里实际存的是什么值,过滤条件该怎么写",
  "结果呈现": "返回哪些列、怎么排序、别名怎么起",
  [UNCATEGORIZED]: "还没归类,点上面的「自动归类」或逐条编辑",
};

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 RulesPanel({ dsId }: { dsId: number }) {
  const [metrics, setMetrics] = useState<SmMetric[] | null>(null);
  const [issues, setIssues] = useState<SmMetricIssue[]>([]);
  const [instructions, setInstructions] = useState<SmInstruction[]>([]);
  const [keyword, setKeyword] = useState("");
  const [editingRule, setEditingRule] = useState<Partial<SmInstruction> | null>(null);
  const [del, setDel] = useState<{ id: number; label: string } | null>(null);
  const [sorting, setSorting] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const remove = async () => {
    if (!del) return;
    try { 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.instructions} 条。归类只影响展示`); load(); }
    catch (e) { toast("error", "归类失败", e instanceof Error ? e.message : String(e)); } finally { setSorting(false); }
  };

  const kw = keyword.trim().toLowerCase();
  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 = instructions.filter((i) => !i.category?.trim()).length;

  return (
    <div className="space-y-3">
      <Card>
        <CardHeader title={<span className="flex items-center gap-2"><FunctionSquare className="h-4 w-4 text-brand" />问数看到的指标 · {metrics.length}</span>}
                    desc="来自本体:已发布、并在这个数据源上绑定了取数表达式的聚合函数。要改请去「函数类型」。"
                    right={<button className="btn btn-sm" onClick={() => go("b_function")}>去函数类型</button>} />
        {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>
        )}
        <div className="flex flex-wrap gap-1.5 p-3">
          {metrics.map((m) => (
            <button key={m.id} className="chip" title={m.calibre_note ? `${m.expression}\n口径:${m.calibre_note}` : m.expression}
                    onClick={() => go("b_function", { id: String(m.id) })}>{m.display_name || m.name}</button>
          ))}
          {!metrics.length && <p className="text-[12px] text-muted">还没有绑定到这个数据源的聚合函数。问数会直接生成 SQL。</p>}
        </div>
      </Card>

      <Card>
        <CardHeader title={<span className="flex items-center gap-2"><ScrollText className="h-4 w-4 text-brand2" />取数规则 · {instructions.length}</span>}
                    desc="标了「默认注入」的每次取数都会进提示词;其余的按触发词匹配。只写对着真实数据验证过的事实。"
                    right={<>
                      {unsorted > 0 && (
                        <button className="btn btn-sm" disabled={sorting} onClick={autoSort}>
                          {sorting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Wand2 className="h-3.5 w-3.5" />}自动归类 {unsorted} 条
                        </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 className="border-b border-line px-4 py-2">
          <div className="relative">
            <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="搜规则内容" value={keyword} onChange={(e) => setKeyword(e.target.value)} />
          </div>
        </div>
        {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({ id: i.id, label: i.content.slice(0, 40) })}>
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </div>
            ))}
          </Group>
        ))}
      </Card>

      <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 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>
  );
}