ModelingPanel.tsx 22.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
import {
  CheckCircle2, Download, GitBranch, Layers, Loader2, Search, Sparkles, Table2, 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, Empty, ErrorNote, Field, Progress, Spinner } from "@/components/ui";
import type { JobItem, SmColumn, SmModel, SmRelation, SqlRelationRec } from "@/lib/types";

/**
 * 语义建模页。左边选表,右边看这张表的结构 —— 表和列是两级信息,
 * 以前塞在一个手风琴列表里:展开一张表,列表被顶到屏幕外,想比较两张表得来回折叠。
 * 分成两栏之后,左边的选择状态一直在,右边换内容,比较和编辑都不用来回滚。
 */
export function ModelingPanel({ dsId }: { dsId: number }) {
  const [models, setModels] = useState<SmModel[] | null>(null);
  const [relations, setRelations] = useState<SmRelation[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [keyword, setKeyword] = useState("");
  const [activeId, setActiveId] = useState<number | null>(null);
  const [onlyEnabled, setOnlyEnabled] = useState(false);
  const [job, setJob] = useState<JobItem | null>(null);

  const load = useCallback(() => {
    Promise.all([api.sqlModels(dsId), api.sqlRelations(dsId)])
      .then(([m, r]) => { setModels(m); setRelations(r); setError(null); })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
  }, [dsId]);

  useEffect(load, [load]);

  // 起草是后台任务,轮询进度。跑完刷新一次表格,让新写的同义词立刻可见。
  useEffect(() => {
    if (!job || job.status === "done" || job.status === "failed") return;
    const t = window.setTimeout(async () => {
      try {
        const j = await api.job(job.id);
        setJob(j);
        if (j.status === "done" || j.status === "failed") {
          toast(j.status === "done" ? "ok" : "error",
                j.status === "done" ? "起草完成" : "起草失败", j.message);
          load();
        }
      } catch { /* 下一轮再试 */ }
    }, 1500);
    return () => window.clearTimeout(t);
  }, [job, load]);

  const draft = async () => {
    try {
      const { job_id } = await api.describeSchema(dsId);
      setJob(await api.job(job_id));
      toast("ok", "已开始起草", "给已启用的表补业务描述与同义词,十几张表要几分钟");
    } catch (e) {
      toast("error", "启动失败", e instanceof Error ? e.message : String(e));
    }
  };

  const shown = useMemo(() => {
    const kw = keyword.trim().toLowerCase();
    return (models ?? []).filter((m) => {
      if (onlyEnabled && !m.enabled) return false;
      if (!kw) return true;
      return m.physical_table.toLowerCase().includes(kw)
        || m.description.toLowerCase().includes(kw)
        || m.columns.some((c) => c.name.toLowerCase().includes(kw)
          || c.description.toLowerCase().includes(kw));
    });
  }, [models, keyword, onlyEnabled]);

  // 选中的表被筛掉了就顺势跳到第一条,右栏不要留一片空白
  useEffect(() => {
    if (shown.length === 0) return;
    if (activeId === null || !shown.some((m) => m.id === activeId)) setActiveId(shown[0].id);
  }, [shown, activeId]);

  const enabledCount = (models ?? []).filter((m) => m.enabled).length;
  const active = (models ?? []).find((m) => m.id === activeId) ?? null;
  const busy = !!job && job.status !== "done" && job.status !== "failed";

  const toggle = async (m: SmModel) => {
    try {
      await api.enableSqlModels(dsId, [m.id], !m.enabled);
      setModels((s) => s?.map((x) => (x.id === m.id ? { ...x, enabled: !x.enabled } : x)) ?? null);
    } catch (e) {
      toast("error", "操作失败", e instanceof Error ? e.message : String(e));
    }
  };

  const bulk = async (enabled: boolean) => {
    const ids = shown.map((m) => m.id);
    if (!ids.length) return;
    try {
      await api.enableSqlModels(dsId, ids, enabled);
      load();
      toast("ok", enabled ? `已启用 ${ids.length} 张表` : `已停用 ${ids.length} 张表`,
            keyword ? "只作用于当前筛选出的表" : undefined);
    } catch (e) {
      toast("error", "操作失败", e instanceof Error ? e.message : String(e));
    }
  };

  const onColumnSaved = (modelId: number, col: SmColumn) =>
    setModels((s) => s?.map((x) => x.id === modelId
      ? { ...x, columns: x.columns.map((c) => (c.id === col.id ? col : c)) }
      : x) ?? null);

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

  if (models.length === 0) {
    return (
      <Card>
        <Empty icon={<Table2 className="h-6 w-6" />} title="还没有表结构"
               desc="先回到「数据源」页,对这个数据源做一次内省。" />
      </Card>
    );
  }

  return (
    <div className="space-y-3">
      <Card className="overflow-hidden">
        <CardHeader
          title="语义模型"
          desc="启用的表才会参与问答 —— 停用等于收回查询授权,生成的 SQL 碰不到它。"
          right={
            <div className="flex flex-wrap items-center justify-end gap-1.5">
              <button className="btn btn-sm" disabled={busy} onClick={draft}
                      title="让大模型给已启用的表补业务描述与同义词。同义词决定用户随口问能不能命中">
                {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                      : <Wand2 className="h-3.5 w-3.5" />}
                AI 起草描述
              </button>
              <a className="btn btn-ghost btn-sm" href={api.mdlUrl(dsId)} target="_blank" rel="noreferrer">
                <Download className="h-3.5 w-3.5" /> 导出 MDL
              </a>
            </div>
          } />

        <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 pb-3">
          <div className="relative min-w-[180px] 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="搜表名、列名或描述"
                   value={keyword} onChange={(e) => setKeyword(e.target.value)} />
          </div>
          <label className="flex shrink-0 cursor-pointer items-center gap-1.5 text-[12.5px] text-muted">
            <input type="checkbox" checked={onlyEnabled}
                   onChange={(e) => setOnlyEnabled(e.target.checked)} />
            只看已启用
          </label>
          <Badge tone={enabledCount ? "bg-ok/10 text-ok" : "bg-warn/10 text-warn"}>
            已启用 {enabledCount} / {models.length}
          </Badge>
          <span className="h-4 w-px bg-line" />
          <button className="btn btn-ghost btn-sm" onClick={() => bulk(true)}>
            {keyword || onlyEnabled ? "启用筛选结果" : "全部启用"}
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => bulk(false)}>
            {keyword || onlyEnabled ? "停用筛选结果" : "全部停用"}
          </button>
        </div>

        {busy && job && (
          <div className="border-b border-line px-4 py-2">
            <Progress value={job.progress} />
            <p className="mt-1 text-[11.5px] text-muted">{job.message || "起草中…"}</p>
          </div>
        )}

        {enabledCount === 0 && (
          <p className="border-b border-line bg-warn/5 px-4 py-2 text-[12.5px] text-warn">
            一张表都没启用,现在还问不了。勾选几张真正要查的表再去「问答」页。
          </p>
        )}

        {/* 左栏选表、右栏看结构。两边各自滚动,比较两张表时左边的位置不会丢 */}
        <div className="grid h-[min(62vh,620px)] grid-cols-1 md:grid-cols-[minmax(0,280px)_minmax(0,1fr)]">
          <div className="min-h-0 overflow-auto border-b border-line md:border-b-0 md:border-r">
            {shown.length === 0 ? (
              <p className="px-4 py-6 text-center text-[13px] text-muted">没有匹配的表</p>
            ) : (
              shown.map((m) => (
                <div key={m.id}
                     className={cn("flex items-center gap-2 border-b border-line px-3 py-2 last:border-0",
                       activeId === m.id ? "bg-brand/[0.06]" : "hover:bg-ink/[0.02]",
                       !m.enabled && "opacity-60")}>
                  <input type="checkbox" checked={m.enabled} onChange={() => toggle(m)}
                         className="shrink-0"
                         title={m.enabled ? "停用后不再参与问答" : "启用后才能被查询"} />
                  <button className="min-w-0 flex-1 text-left" onClick={() => setActiveId(m.id)}>
                    <span className="flex items-center gap-1.5">
                      <span className="truncate font-mono text-[12.5px]">{m.physical_table}</span>
                      {m.kind === "view" && <Badge>视图</Badge>}
                    </span>
                    <span className="mt-0.5 block truncate text-[11px] text-muted">
                      {m.description || "(无表说明)"}
                    </span>
                  </button>
                  <span className="shrink-0 text-[11px] tabular-nums text-muted">{m.columns.length}</span>
                </div>
              ))
            )}
          </div>

          <div className="min-h-0 overflow-auto">
            {active ? (
              <ModelDetail model={active}
                           onColumnSaved={(c) => onColumnSaved(active.id, c)} />
            ) : (
              <Empty icon={<Layers className="h-6 w-6" />} title="从左边选一张表"
                     desc="右边会显示它的全部列、业务说明、取值样例和空值比例。" />
            )}
          </div>
        </div>
      </Card>

      <RelationCard dsId={dsId} models={models} relations={relations} onChanged={load} />
    </div>
  );
}

function ModelDetail({ model, onColumnSaved }: {
  model: SmModel; onColumnSaved: (c: SmColumn) => void;
}) {
  const [filter, setFilter] = useState("");
  const sampled = model.columns.filter((c) => c.sample_values.length > 0).length;
  const empties = model.columns.filter((c) => c.null_ratio >= 0.9999).length;

  const cols = useMemo(() => {
    const kw = filter.trim().toLowerCase();
    if (!kw) return model.columns;
    return model.columns.filter((c) => c.name.toLowerCase().includes(kw)
      || c.description.toLowerCase().includes(kw));
  }, [model.columns, filter]);

  return (
    <div>
      <div className="sticky top-0 z-10 border-b border-line bg-surface px-4 py-2.5">
        <div className="flex flex-wrap items-center gap-1.5">
          <span className="font-mono text-[13px] font-medium">{model.physical_table}</span>
          {model.enabled
            ? <Badge tone="bg-ok/10 text-ok"><CheckCircle2 className="h-3 w-3" />参与问答</Badge>
            : <Badge tone="bg-ink/5 text-muted">已停用</Badge>}
          <span className="flex-1" />
          <div className="relative w-40">
            <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted" />
            <input className="input py-1 pl-7 text-[12px]" placeholder="筛选列"
                   value={filter} onChange={(e) => setFilter(e.target.value)} />
          </div>
        </div>
        <p className="mt-1 text-[11.5px] text-muted">
          {model.description || "(还没写表说明,AI 起草或手填都行)"}
        </p>
        <p className="mt-0.5 text-[11px] text-muted">
          「业务说明」可以直接改,它会原样进提示词,是这一页里对准确率影响最大的东西。
        </p>
        <p className="mt-0.5 flex flex-wrap gap-x-3 text-[11px] text-muted">
          <span>{model.columns.length} 列</span>
          {sampled > 0 && <span>{sampled} 个枚举列有取值样例</span>}
          {empties > 0 && <span className="text-bad">{empties} 个整列全空,已自动停用</span>}
          {model.row_count_est > 0 && <span>约 {model.row_count_est.toLocaleString()} 行</span>}
          {model.primary_key && <span>主键 {model.primary_key}</span>}
        </p>
      </div>

      {/* 表头一律不换行并给死宽度:右栏本来就窄,让「说明(可编辑,直接影响…)」
          这种长表头自由换行,四个字的列名会被挤成三行 */}
      <table className="w-full table-fixed text-[12.5px]">
        <thead>
          <tr className="text-left text-muted [&>th]:whitespace-nowrap [&>th]:py-1.5 [&>th]:font-medium">
            <th className="w-[18%] px-4">列</th>
            <th className="w-[12%] pr-3">类型</th>
            <th className="w-[34%] pr-3">业务说明</th>
            <th className="w-[26%] pr-3">取值样例</th>
            <th className="w-[10%] pr-4">空值</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-line">
          {cols.map((c) => (
            <ColumnRow key={c.id} column={c} onSaved={onColumnSaved} />
          ))}
          {cols.length === 0 && (
            <tr><td colSpan={5} className="px-4 py-6 text-center text-muted">没有匹配的列</td></tr>
          )}
        </tbody>
      </table>
    </div>
  );
}

function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColumn) => void }) {
  const [desc, setDesc] = useState(column.description);
  const [saving, setSaving] = useState(false);
  useEffect(() => setDesc(column.description), [column.description]);

  const save = async () => {
    if (desc === column.description) return;
    setSaving(true);
    try {
      await api.updateSqlColumn(column.id, { description: desc });
      onSaved({ ...column, description: desc });
    } catch (e) {
      toast("error", "保存失败", e instanceof Error ? e.message : String(e));
      setDesc(column.description);
    } finally { setSaving(false); }
  };

  return (
    <tr className={cn("align-top", !column.enabled && "opacity-50")}>
      <td className="truncate px-4 py-1.5 font-mono" title={column.name}>{column.name}</td>
      <td className="truncate py-1.5 pr-3 text-muted" title={column.data_type}>{column.data_type}</td>
      <td className="w-[36%] py-1.5 pr-3">
        <div className="flex items-center gap-1.5">
          <input className="input py-1 text-[12.5px]" value={desc} placeholder="补一句业务含义"
                 onChange={(e) => setDesc(e.target.value)} onBlur={save}
                 onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} />
          {saving && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted" />}
        </div>
      </td>
      <td className="py-1.5 pr-3">
        {column.sample_values.length > 0 ? (
          <span className="flex flex-wrap gap-1">
            {column.sample_values.slice(0, 6).map((v, i) => (
              <span key={i} className="chip max-w-full truncate px-1.5 py-0 text-[11px]"
                    title={String(v)}>{String(v)}</span>
            ))}
          </span>
        ) : (
          <span className="text-muted">—</span>
        )}
      </td>
      <td className="py-1.5 pr-4">
        {column.null_ratio >= 0.9999 ? (
          <span className="text-bad" title="整列全空,已自动停用">全空</span>
        ) : column.null_ratio >= 0.5 ? (
          <span className="text-warn">{Math.round(column.null_ratio * 100)}%</span>
        ) : (
          <span className="text-muted">—</span>
        )}
      </td>
    </tr>
  );
}

function RelationCard({ dsId, models, relations, onChanged }: {
  dsId: number; models: SmModel[]; relations: SmRelation[]; onChanged: () => void;
}) {
  const nameOf = (id: number) =>
    models.find((m) => m.id === id)?.physical_table ?? `#${id}`;
  const [adding, setAdding] = useState(false);
  const [recs, setRecs] = useState<SqlRelationRec[] | null>(null);
  const [scanning, setScanning] = useState(false);
  const [form, setForm] = useState({ from_model_id: 0, from_column: "", to_model_id: 0, to_column: "" });

  const recommend = async () => {
    setScanning(true);
    try {
      const r = await api.recommendRelations(dsId);
      setRecs(r);
      toast(r.length ? "ok" : "warn",
            r.length ? `找到 ${r.length} 条候选关联` : "没有找到可靠的关联路径",
            r.length ? "已按取值重叠率排序,确认后再采纳" : "列名或取值都对不上");
    } catch (e) {
      toast("error", "推荐失败", e instanceof Error ? e.message : String(e));
    } finally { setScanning(false); }
  };

  const accept = async (r: SqlRelationRec) => {
    try {
      await api.upsertSqlRelation(dsId, {
        from_model_id: r.from_model_id, from_column: r.from_column,
        to_model_id: r.to_model_id, to_column: r.to_column,
        join_type: "left", cardinality: r.cardinality,
        description: `按列名与取值推导(重叠率 ${r.overlap},目标唯一度 ${r.target_uniqueness})`,
      });
      setRecs((s) => s?.filter((x) => x !== r) ?? null);
      onChanged();
    } catch (e) {
      toast("error", "采纳失败", e instanceof Error ? e.message : String(e));
    }
  };

  const fromCols = models.find((m) => m.id === form.from_model_id)?.columns ?? [];
  const toCols = models.find((m) => m.id === form.to_model_id)?.columns ?? [];

  const add = async () => {
    try {
      await api.upsertSqlRelation(dsId, { ...form, join_type: "inner", cardinality: "N:1" });
      toast("ok", "已新增关联路径");
      setAdding(false);
      setForm({ from_model_id: 0, from_column: "", to_model_id: 0, to_column: "" });
      onChanged();
    } catch (e) {
      toast("error", "新增失败", e instanceof Error ? e.message : String(e));
    }
  };

  const remove = async (r: SmRelation) => {
    try {
      await api.deleteSqlRelation(r.id);
      onChanged();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
  };

  const ok = form.from_model_id && form.to_model_id && form.from_column && form.to_column;

  return (
    <Card>
      <CardHeader
        title="表间关联"
        desc="生成的 SQL 只能走这里声明过的关联路径,写别的 JOIN 条件会被直接拒掉。"
        right={
          <div className="flex items-center gap-1.5">
            <button className="btn btn-sm" disabled={scanning} onClick={recommend}
                    title="这个库没有外键,按列名 + 真实取值重叠率扫一遍候选关联">
              {scanning ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        : <Sparkles className="h-3.5 w-3.5" />}
              推荐关联
            </button>
            <button className="btn btn-sm" onClick={() => setAdding(!adding)}>
              <GitBranch className="h-3.5 w-3.5" /> {adding ? "取消" : "新增"}
            </button>
          </div>
        } />

      {recs && recs.length > 0 && (
        <div className="border-b border-line bg-brand/[0.03] px-4 py-2.5">
          <p className="mb-1.5 text-[12px] font-medium">
            候选关联(按取值重叠率排序,确认无误再采纳)
          </p>
          <div className="space-y-1">
            {recs.map((r, i) => (
              <div key={i} className="flex flex-wrap items-center gap-2">
                <code className="min-w-0 flex-1 truncate text-[12px]">
                  {r.from_table}.{r.from_column} = {r.to_table}.{r.to_column}
                </code>
                <Badge tone="bg-ok/10 text-ok">重叠 {(r.overlap * 100).toFixed(1)}%</Badge>
                <Badge tone="bg-ink/5 text-muted">目标唯一度 {(r.target_uniqueness * 100).toFixed(0)}%</Badge>
                <button className="btn btn-sm" onClick={() => accept(r)}>采纳</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {adding && (
        <div className="grid grid-cols-2 items-end gap-2 border-b border-line px-4 pb-3
                        sm:grid-cols-[1fr_1fr_auto_1fr_1fr_auto]">
          <Field label="从表">
            <select className="input" value={form.from_model_id}
                    onChange={(e) => setForm({ ...form, from_model_id: Number(e.target.value), from_column: "" })}>
              <option value={0}>选择…</option>
              {models.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
            </select>
          </Field>
          <Field label="列">
            <select className="input" value={form.from_column}
                    onChange={(e) => setForm({ ...form, from_column: e.target.value })}>
              <option value="">选择…</option>
              {fromCols.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
            </select>
          </Field>
          <span className="hidden pb-2 text-muted sm:block">=</span>
          <Field label="到表">
            <select className="input" value={form.to_model_id}
                    onChange={(e) => setForm({ ...form, to_model_id: Number(e.target.value), to_column: "" })}>
              <option value={0}>选择…</option>
              {models.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
            </select>
          </Field>
          <Field label="列">
            <select className="input" value={form.to_column}
                    onChange={(e) => setForm({ ...form, to_column: e.target.value })}>
              <option value="">选择…</option>
              {toCols.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
            </select>
          </Field>
          <button className="btn btn-primary btn-sm" disabled={!ok} onClick={add}>添加</button>
        </div>
      )}

      {relations.length === 0 ? (
        <p className="px-4 py-5 text-center text-[13px] text-muted">
          还没有关联路径。有外键的话内省会自动带出来;没有就在这里手动声明。
        </p>
      ) : (
        <div className="divide-y divide-line">
          {relations.map((r) => (
            <div key={r.id} className="flex flex-wrap items-center gap-2 px-4 py-2">
              <code className="min-w-0 flex-1 truncate text-[12.5px]">
                {nameOf(r.from_model_id)}.{r.from_column} = {nameOf(r.to_model_id)}.{r.to_column}
              </code>
              <Badge>{r.cardinality}</Badge>
              {r.description && (
                <span className="max-w-[40%] truncate text-[11.5px] text-muted" title={r.description}>
                  {r.description}
                </span>
              )}
              <button className="btn btn-ghost btn-sm text-bad" onClick={() => remove(r)}>
                <Trash2 className="h-3.5 w-3.5" />
              </button>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}