ModelingPanel.tsx 22.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 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
import {
  GitBranch, Layers, Link2, Loader2, Network, Search, Sparkles, Table2, Trash2, Wand2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { go } from "@/lib/nav";
import { onto } from "@/lib/onto";
import { FromTableModal } from "../ontology/BindTools";
import { RelationGraph } from "./RelationGraph";
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, dsName = "", canEdit = false }: { dsId: number; dsName?: string; canEdit?: boolean }) {
  const [map, setMap] = useState<Record<string, { concept_id: string; name: string }[]>>({});
  const [toObject, setToObject] = useState("");
  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 [job, setJob] = useState<JobItem | null>(null);
  const [graph, setGraph] = useState(false);

  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)));
    void onto.mappings(dsId).then(setMap).catch(() => setMap({}));
  }, [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));
    }
  };

  // 一步把这个数据源的表都起草成对象和关系:建一次只含这个数据库的 AI 建模,草案在建模页里逐条采纳
  const [proposing, setProposing] = useState(false);
  const toOntology = async () => {
    setProposing(true);
    try {
      const fd = new FormData();
      fd.append("title", `数据库:${dsName || `#${dsId}`}`);
      fd.append("doc_ids", "[]");
      fd.append("ds_ids", JSON.stringify([dsId]));
      const r = await onto.createModelingRun(fd);
      toast("info", "已开始 AI 建模", "表和关联会变成对象与关系草案");
      go("modeling", { run: r.id });
    } catch (e) {
      toast("error", "生成失败", e instanceof Error ? e.message : String(e));
    } finally { setProposing(false); }
  };

  const shown = useMemo(() => {
    const kw = keyword.trim().toLowerCase();
    return (models ?? []).filter((m) => !kw
      || 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]);

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

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

  const patchModel = (modelId: number, patch: Partial<SmModel>) =>
    setModels((s) => s?.map((x) => (x.id === modelId ? { ...x, ...patch } : x)) ?? null);
  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">
      {toObject && <FromTableModal dsId={dsId} table={toObject} onClose={() => setToObject("")} onDone={load} />}
      {graph && <RelationGraph dsId={dsId} models={models} relations={relations} onChanged={load}
                               onOpenTable={(id) => { setActiveId(id); setKeyword(""); setGraph(false); }}
                               onClose={() => setGraph(false)} />}
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2.5">
          <h3 className="text-title font-semibold">表与字段</h3>
          <span className="text-label text-muted">{models.length} 张表 · {relations.length} 条关联</span>
          <div className="relative ml-2 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 py-1.5 pl-8" placeholder="搜表名、字段或说明"
                   value={keyword} onChange={(e) => setKeyword(e.target.value)} />
          </div>
          <button className="btn btn-sm" onClick={() => setGraph(true)}>
            <Network className="h-3.5 w-3.5" /> 关系图
          </button>
          {canEdit && (
            <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>
          )}
          {canEdit && (
            <button className="btn btn-primary btn-sm" disabled={proposing} onClick={() => void toOntology()}>
              {proposing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Layers className="h-3.5 w-3.5" />}
              生成对象和关系
            </button>
          )}
        </div>

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

        {/* 左栏选表、右栏看结构。两边各自滚动 */}
        <div className="grid h-[min(66vh,660px)] grid-cols-1 md:grid-cols-[minmax(0,340px)_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-body text-muted">没有匹配的表</p>
            ) : shown.map((m) => {
              const obj = (map[m.physical_table] || [])[0];
              return (
                <div key={m.id} onClick={() => setActiveId(m.id)} title={m.description || m.physical_table}
                     className={cn("grid h-10 cursor-pointer grid-cols-[minmax(0,1fr)_2rem_6rem] items-center gap-2 border-b border-line px-3",
                       activeId === m.id ? "bg-brand/[0.06]" : "hover:bg-ink/[0.02]")}>
                  <span className="flex min-w-0 items-center gap-1.5">
                    <span className="truncate font-mono text-label">{m.physical_table}</span>
                    {m.kind === "view" && <Badge>视图</Badge>}
                  </span>
                  <span className="text-right text-caption tabular-nums text-muted">{m.columns.length}</span>
                  {obj ? (
                    <button className="chip w-full justify-center truncate text-caption text-ok" title={`已建成对象「${obj.name}」,点击查看`}
                            onClick={(e) => { e.stopPropagation(); go("b_object", { id: obj.concept_id }); }}>
                      <Link2 className="h-3 w-3 shrink-0" /><span className="truncate">{obj.name}</span>
                    </button>
                  ) : canEdit ? (
                    <button className="btn btn-ghost btn-sm w-full justify-center text-brand" title="把这张表建成一个对象(字段成属性)"
                            onClick={(e) => { e.stopPropagation(); setToObject(m.physical_table); }}>建成对象</button>
                  ) : <span />}
                </div>
              );
            })}
          </div>

          <div className="min-h-0 overflow-auto">
            {active ? (
              <ModelDetail model={active} onModelSaved={(p) => patchModel(active.id, p)}
                           onColumnSaved={(c) => onColumnSaved(active.id, c)} />
            ) : (
              <Empty icon={<Layers className="h-6 w-6" />} title="从左边选一张表" />
            )}
          </div>
        </div>
      </Card>

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

function ModelDetail({ model, onModelSaved, onColumnSaved }: {
  model: SmModel; onModelSaved: (p: Partial<SmModel>) => void; onColumnSaved: (c: SmColumn) => void;
}) {
  const [filter, setFilter] = useState("");
  const [desc, setDesc] = useState(model.description);
  useEffect(() => setDesc(model.description), [model.id, model.description]);
  const empties = model.columns.filter((c) => c.null_ratio >= 0.9999).length;

  const saveDesc = async () => {
    if (desc === model.description) return;
    try { await api.updateSqlModel(model.id, { description: desc }); onModelSaved({ description: desc }); }
    catch (e) { toast("error", "保存失败", e instanceof Error ? e.message : String(e)); setDesc(model.description); }
  };

  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 space-y-1.5 border-b border-line bg-surface px-4 py-2.5">
        <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
          <span className="font-mono text-body font-medium">{model.physical_table}</span>
          <span className="text-caption text-muted">
            {model.columns.length} 列
            {model.row_count_est > 0 && ` · 约 ${model.row_count_est.toLocaleString()} 行`}
            {model.primary_key && ` · 主键 ${model.primary_key}`}
          </span>
          {empties > 0 && <span className="text-caption text-bad">{empties} 列全空</span>}
          <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-label" placeholder="筛选字段"
                   value={filter} onChange={(e) => setFilter(e.target.value)} />
          </div>
        </div>
        <input className="input py-1 text-label" value={desc} placeholder="这张表是做什么的(业务说明)"
               onChange={(e) => setDesc(e.target.value)} onBlur={() => void saveDesc()}
               onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} />
      </div>

      <table className="w-full table-fixed text-label">
        <thead>
          <tr className="text-left text-muted [&>th]:whitespace-nowrap [&>th]:py-1.5 [&>th]:font-medium">
            <th className="w-[20%] px-4">字段</th>
            <th className="w-[14%] pr-3">类型</th>
            <th className="w-[34%] pr-3">业务说明</th>
            <th className="w-[24%] pr-3">取值样例</th>
            <th className="w-[8%] 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-middle", !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-label" 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="block truncate text-muted" title={column.sample_values.map(String).join("、")}>
            {column.sample_values.slice(0, 8).map(String).join("、")}
          </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="表间关联"
       
        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-label 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-label">
                  {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-body 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-label">
                {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-label 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>
  );
}