DataSourcePanel.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
import {
  AlertTriangle, Database, FileSpreadsheet, FileUp, Globe, Loader2, Plug, RefreshCw, ShieldCheck, Trash2,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { api, ApiError } from "@/lib/api";
import { cn, formatTime } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import {
  Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Field, Modal, Progress, Spinner,
} from "@/components/ui";
import type { DataSource, JobItem } from "@/lib/types";

const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "", schema: "public", tables: "", writeback: false };

/** 新建连接时可选的类型。键是后端的 ds_type(= SQL 方言);MariaDB 走 MySQL 协议。 */
const KINDS: { key: string; ds_type: string; label: string; desc: string; port: number; group: string; soon?: boolean }[] = [
  { key: "mysql", ds_type: "mysql", label: "MySQL", desc: "5.7 / 8.x", port: 3306, group: "关系型数据库" },
  { key: "mariadb", ds_type: "mysql", label: "MariaDB", desc: "10.x / 11.x", port: 3306, group: "关系型数据库" },
  { key: "postgres", ds_type: "postgres", label: "PostgreSQL", desc: "13 / 14 / 15 / 16", port: 5432, group: "关系型数据库" },
  { key: "api", ds_type: "", label: "REST API", desc: "HTTP GET / POST · JSON 响应", port: 0, group: "API" },
  { key: "file", ds_type: "sqlite", label: "本地文件", desc: "CSV · Excel · JSON", port: 0, group: "文件" },
  { key: "nosql", ds_type: "", label: "MongoDB · Redis · ClickHouse · Elasticsearch", desc: "非关系型数据库", port: 0, group: "即将上线", soon: true },
];
const TYPE_LABEL: Record<string, string> = { mysql: "MySQL", postgres: "PostgreSQL", sqlite: "本地文件" };

export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: {
  selectedId: number | null;
  onSelect: (id: number) => void;
  onChanged: () => void;
  /** 选了 REST API:跳到「外部系统 / API」页签登记端点 */
  onOpenApi?: () => void;
}) {
  const [items, setItems] = useState<DataSource[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [cryptoReady, setCryptoReady] = useState(true);
  const [editing, setEditing] = useState<DataSource | null>(null);
  const [creating, setCreating] = useState(false);
  const [picking, setPicking] = useState(false);
  const [fileDs, setFileDs] = useState<DataSource | "new" | null>(null);
  const [confirmDel, setConfirmDel] = useState<DataSource | null>(null);
  const [busy, setBusy] = useState<number | null>(null);
  const [job, setJob] = useState<{ dsId: number; item: JobItem | null } | null>(null);

  const load = useCallback(() => {
    api.datasources().then((d) => { setItems(d); setError(null); })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
    api.sqlMeta().then((m) => setCryptoReady(m.crypto_ready)).catch(() => undefined);
  }, []);

  useEffect(load, [load]);

  // 内省是后台任务,轮询它的进度。也可以走 /api/jobs/{id}/events 的 SSE,
  // 但这里只需要一个进度条,轮询代码短得多。
  const jobId = job?.item?.id ?? null;
  const timer = useRef<number>();
  useEffect(() => {
    if (jobId === null) return;
    const tick = async () => {
      try {
        const j = await api.job(jobId);
        setJob((s) => (s ? { ...s, item: j } : s));
        if (j.status === "done" || j.status === "failed") {
          toast(j.status === "done" ? "ok" : "error",
                j.status === "done" ? "内省完成" : "内省失败", j.message);
          setJob(null);
          load();
          onChanged();
          return;     // 不再排下一次
        }
      } catch { /* 任务还没落库,下一轮再看 */ }
      timer.current = window.setTimeout(tick, 1200);
    };
    timer.current = window.setTimeout(tick, 800);
    return () => window.clearTimeout(timer.current);
  }, [jobId, load, onChanged]);

  const test = async (ds: DataSource) => {
    setBusy(ds.id);
    try {
      const info = await api.testDatasource(ds.id);
      toast(info.warning ? "warn" : "ok", `连接成功:${info.database}`,
            info.warning ?? `${info.version},${info.table_count} 张表`);
      load();
    } catch (e) {
      toast("error", "连接失败", e instanceof Error ? e.message : String(e));
      load();
    } finally { setBusy(null); }
  };

  const introspect = async (ds: DataSource, resample = false) => {
    setBusy(ds.id);
    try {
      const { job_id } = await api.introspect(ds.id, resample);
      const j = await api.job(job_id);
      setJob({ dsId: ds.id, item: j });
      toast("ok", "已开始内省", "抓表结构 + 采样枚举列,几百张表可能要几分钟");
    } catch (e) {
      toast("error", "内省启动失败", e instanceof Error ? e.message : String(e));
    } finally { setBusy(null); }
  };

  const remove = async (ds: DataSource) => {
    try {
      await api.deleteDatasource(ds.id);
      toast("ok", `已删除数据源「${ds.name}」`);
      load();
      onChanged();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
    setConfirmDel(null);
  };

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

  return (
    <div className="space-y-3">
      {!cryptoReady && (
        <div className="card flex items-start gap-2.5 border-warn/40 bg-warn/5 p-3">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" />
          <div className="text-body leading-relaxed">
            <p className="font-medium">未配置 SECRET_KEY,暂时不能添加数据源。</p>
            <p className="mt-0.5 text-muted">
              业务库口令必须加密存储。请在 <code className="rounded bg-ink/[0.07] px-1">.env</code> 里加一行
              <code className="mx-1 rounded bg-ink/[0.07] px-1">SECRET_KEY=(一串足够长的随机字符)</code>
              后重启服务。
            </p>
          </div>
        </div>
      )}

      <Card>
        <CardHeader
          title="数据源"
          desc="建议使用只读账号连接业务库。口令加密存储,不会明文落库,也不会回显。"
          right={
            <button className="btn btn-primary btn-sm" onClick={() => setPicking(true)}>
              <Database className="h-3.5 w-3.5" /> 新建连接
            </button>
          } />

        {items.length === 0 ? (
          <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
                 desc="接一个业务库(MySQL / PostgreSQL)或上传 CSV / Excel,做一次内省,就能映射对象、开始提问了。" />
        ) : (
          <div className="divide-y divide-line">
            {items.map((ds) => (
              <div key={ds.id}
                   className={cn("px-4 py-3 transition-colors",
                     selectedId === ds.id ? "bg-brand/[0.04]" : "hover:bg-ink/[0.015]")}>
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
                  <button className="min-w-0 flex-1 text-left" onClick={() => onSelect(ds.id)}>
                    <span className="flex flex-wrap items-center gap-1.5">
                      <span className="truncate text-body font-medium">{ds.name}</span>
                      {selectedId === ds.id && <Badge tone="bg-brand/10 text-brand">当前</Badge>}
                      {ds.status === "ok" && <Badge tone="bg-ok/10 text-ok">已连通</Badge>}
                      {ds.status === "error" && <Badge tone="bg-bad/10 text-bad">连接异常</Badge>}
                      {ds.status === "new" && <Badge tone="bg-warn/10 text-warn">未测试</Badge>}
                      {ds.read_only && (
                        <span title="按只读方式使用"><ShieldCheck className="h-3.5 w-3.5 text-ok" /></span>
                      )}
                    </span>
                    <span className="mt-0.5 block truncate font-mono text-label text-muted">
                      <Badge className="mr-1.5 font-sans">{TYPE_LABEL[ds.ds_type] || ds.ds_type}</Badge>
                      {ds.ds_type === "sqlite" ? "上传文件导入的只读库" : `${ds.username}@${ds.host}:${ds.port}/${ds.db_name}`}
                    </span>
                    <span className="mt-0.5 block text-label text-muted">
                      {ds.last_introspect_at
                        ? `上次内省 ${formatTime(ds.last_introspect_at)}`
                        : "还没有内省过 —— 内省一次才能开始提问"}
                    </span>
                    {ds.status === "error" && ds.last_error && (
                      <span className="mt-0.5 block truncate text-label text-bad" title={ds.last_error}>
                        {ds.last_error}
                      </span>
                    )}
                  </button>

                  {/* 按钮成组靠右,小屏换行到下一行整体左对齐,不跟文字挤在一起 */}
                  <div className="flex shrink-0 flex-wrap items-center gap-1 sm:justify-end">
                    <button className="btn btn-sm" disabled={busy === ds.id}
                            onClick={() => test(ds)} title="测试连接是否可用">
                      {busy === ds.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                      : <Plug className="h-3.5 w-3.5" />}
                      测试
                    </button>
                    <button className={cn("btn btn-sm", !ds.last_introspect_at && "btn-primary")}
                            disabled={busy === ds.id || !!job}
                            onClick={() => introspect(ds)} title="抓取表结构并采样枚举列">
                      <RefreshCw className="h-3.5 w-3.5" /> 内省
                    </button>
                    {ds.ds_type === "sqlite"
                      ? <button className="btn btn-ghost btn-sm" onClick={() => setFileDs(ds)}><FileUp className="h-3.5 w-3.5" />追加文件</button>
                      : <button className="btn btn-ghost btn-sm"
                                onClick={() => { setEditing(ds); setCreating(false); }}>编辑</button>}
                    <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(ds)}
                            title="删除数据源及其全部建模">
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                </div>

                {job?.dsId === ds.id && job.item && (
                  <div className="mt-2.5">
                    <Progress value={job.item.progress} />
                    <p className="mt-1 text-label text-muted">{job.item.message || "处理中…"}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </Card>

      <Modal open={picking} onClose={() => setPicking(false)} title="新建连接" width="max-w-2xl"
             desc="关系型数据库直接连;API 在「外部系统 / API」登记;表格文件导入成只读库。">
        <div className="space-y-3">
          {[...new Set(KINDS.map((k) => k.group))].map((g) => (
            <div key={g}>
              <p className="mb-1.5 text-label font-medium text-muted">{g}</p>
              <div className="grid gap-2 sm:grid-cols-2">
                {KINDS.filter((k) => k.group === g).map((k) => (
                  <button key={k.key} disabled={k.soon || (!cryptoReady && !!k.port)}
                          className="flex items-center gap-2.5 rounded-lg border border-line p-2.5 text-left hover:border-brand/40 disabled:opacity-50"
                          onClick={() => {
                            setPicking(false);
                            if (k.key === "api") { onOpenApi?.(); return; }
                            if (k.key === "file") { setFileDs("new"); return; }
                            setEditing({ ...BLANK, ds_type: k.ds_type, port: k.port } as unknown as DataSource); setCreating(true);
                          }}>
                    <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">
                      {k.key === "api" ? <Globe className="h-4 w-4" /> : k.key === "file" ? <FileSpreadsheet className="h-4 w-4" /> : <Database className="h-4 w-4" />}</span>
                    <span className="min-w-0"><span className="block text-body font-medium">{k.label}</span>
                      <span className="block text-label text-muted">{k.desc}{k.port ? ` · 默认端口 ${k.port}` : ""}</span></span>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </Modal>

      {fileDs && <FileSourceForm ds={fileDs === "new" ? null : fileDs} onClose={() => setFileDs(null)}
                                 onSaved={(id) => { setFileDs(null); load(); onChanged(); onSelect(id); }} />}

      <DataSourceForm
        open={!!editing} creating={creating} initial={editing}
        onClose={() => setEditing(null)}
        onSaved={() => { setEditing(null); load(); onChanged(); }} />

      <Confirm
        open={!!confirmDel} danger title="删除数据源?"
        body={`将同时删除「${confirmDel?.name ?? ""}」下的全部建模、关系与指标定义。沉淀的问答对也会失去关联。此操作不可撤销。`}
        confirmText="删除" onConfirm={() => confirmDel && remove(confirmDel)}
        onClose={() => setConfirmDel(null)} />
    </div>
  );
}

function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
  open: boolean; creating: boolean; initial: DataSource | null;
  onClose: () => void; onSaved: () => void;
}) {
  const [form, setForm] = useState({ ...BLANK });
  const [password, setPassword] = useState("");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");

  useEffect(() => {
    if (!initial) return;
    setForm({
      name: initial.name ?? "", ds_type: initial.ds_type ?? "mysql", host: initial.host ?? "",
      port: initial.port ?? 3306, db_name: initial.db_name ?? "",
      username: initial.username ?? "", password: "",
      schema: String((initial.extra as any)?.schema || "public"),
      tables: String((initial.extra as any)?.tables || ""),
      writeback: !!(initial.extra as any)?.writeback,
    });
    setPassword("");
    setErr("");
  }, [initial]);

  const set = (k: string, v: string | number | boolean) => setForm((f) => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    setErr("");
    try {
      const { schema, tables, writeback, ...rest } = form;
      const extra: Record<string, string | boolean> = form.ds_type === "postgres" ? { schema: schema || "public" } : {};
      if (tables.trim()) extra.tables = tables.trim();
      if (writeback) extra.writeback = true;
      if (creating) {
        const ds = await api.createDatasource({ ...rest, password, extra });
        // 建完直接测连通、连通就内省:用户不必再回列表点两下
        try {
          await api.testDatasource(ds.id);
          await api.introspect(ds.id);
          toast("ok", "数据源已创建,连接成功", "正在读取表结构,完成后到「实体映射」把表建成对象");
        } catch (e) {
          toast("error", "数据源已保存,但连接失败", e instanceof Error ? e.message : String(e));
        }
        onSaved();
        return;
      } else if (initial) {
        const body: Record<string, unknown> = { ...rest, extra };
        delete body.ds_type;
        // 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过"
        if (password) body.password = password;
        else delete body.password;
        await api.updateDatasource(initial.id, body);
      }
      toast("ok", creating ? "数据源已创建" : "数据源已更新");
      onSaved();
    } catch (e) {
      setErr(e instanceof ApiError ? e.message : e instanceof Error ? e.message : String(e));
    } finally { setSaving(false); }
  };

  const ok = form.name.trim() && form.host.trim() && form.db_name.trim() && form.username.trim();

  return (
    <Modal
      open={open} onClose={onClose} width="max-w-xl"
      title={`${creating ? "新建" : "编辑"}${TYPE_LABEL[form.ds_type] || ""}数据源`}
      desc="保存后自动测试连接、读取表结构;接着到「业务建模」让 AI 按业务文档起草本体。"
      footer={
        <>
          {err && <p className="mr-auto min-w-0 flex-1 text-label text-bad">{err}</p>}
          <button className="btn btn-sm" onClick={onClose}>取消</button>
          <button className="btn btn-primary btn-sm" disabled={!ok || saving} onClick={save}>
            {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
            保存
          </button>
        </>
      }>
      <div className="space-y-4">
        <Field label="名称" required
               hint="给人看的名字,问答页的数据源下拉里显示的就是它。">
          <input className="input" value={form.name} placeholder="如:门店运营库(只读)"
                 onChange={(e) => set("name", e.target.value)} />
        </Field>

        <div className="space-y-3 rounded-lg border border-line bg-elevated/50 p-3">
          <p className="text-label font-medium text-muted">连接信息</p>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
            <Field label="主机" required>
              <input className="input" value={form.host} placeholder="192.168.x.x"
                     onChange={(e) => set("host", e.target.value)} />
            </Field>
            <Field label="端口" required>
              <input className="input" type="number" value={form.port}
                     onChange={(e) => set("port", Number(e.target.value) || 3306)} />
            </Field>
          </div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            {form.ds_type === "postgres" && (
              <Field label="Schema" hint="只内省这个 schema 下的表">
                <input className="input" value={form.schema} onChange={(e) => set("schema", e.target.value)} />
              </Field>
            )}
            <Field label="数据库" required>
              <input className="input" value={form.db_name} placeholder="库名"
                     onChange={(e) => set("db_name", e.target.value)} />
            </Field>
            <Field label="用户名" required>
              <input className="input" value={form.username} autoComplete="off"
                     onChange={(e) => set("username", e.target.value)} />
            </Field>
          </div>
          <Field
            label={<>口令{!creating && <span className="ml-1 font-normal">(留空表示不修改)</span>}</>}
            required={creating}
            hint="加密后存库,任何接口都不会把它回显出来。强烈建议使用只读账号。">
            <input className="input" type="password" value={password} autoComplete="new-password"
                   placeholder={creating ? "" : "••••••••"}
                   onChange={(e) => setPassword(e.target.value)} />
          </Field>
        </div>

        <Field label="表范围" hint="只接入这些表,逗号分隔,支持通配符,如 otlgt3_dm_*;留空 = 整个库。圈定的表会直接启用。">
          <input className="input" value={form.tables} placeholder="otlgt3_dm_*"
                 onChange={(e) => set("tables", e.target.value)} />
        </Field>

        <label className="flex items-start gap-2 rounded-lg border border-line p-3 text-label">
          <input type="checkbox" className="mt-0.5" checked={form.writeback} onChange={(e) => set("writeback", e.target.checked)} />
          <span><span className="font-medium">允许审批通过的动作写回业务库</span>
            <span className="block text-label text-muted">打开后,「新建采购单」「改状态」这类动作在人工审批通过后直接写进业务表(只限已绑定的表和列,可撤销);
              关闭时只写在本系统的写回层,业务库不动。需要账号有写权限。</span></span>
        </label>

        <p className="text-label leading-relaxed text-muted">
          保存后会自动测试连接并读取表结构。PostgreSQL 需要服务器装有 psycopg2 驱动。
        </p>
      </div>
    </Modal>
  );
}

/** 本地文件:CSV / Excel(每个工作表一张表)/ JSON 导入成只读库,之后和数据库一样内省、映射、提问。 */
function FileSourceForm({ ds, onClose, onSaved }: { ds: DataSource | null; onClose: () => void; onSaved: (id: number) => void }) {
  const [name, setName] = useState(ds?.name || "");
  const [files, setFiles] = useState<File[]>([]);
  const [busy, setBusy] = useState(false);
  const save = async () => {
    setBusy(true);
    try {
      const r = await api.createFileDatasource(name || files[0]?.name || "本地文件", files, ds?.id || 0);
      toast("ok", `已导入 ${r.imported.length} 张表`, r.imported.map((t) => `${t.table}(${t.rows} 行)`).join("、"));
      await api.introspect(r.id).catch(() => undefined);
      onSaved(r.id);
    } catch (e) { toast("error", "导入失败", e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title={ds ? `向「${ds.name}」追加文件` : "本地文件数据源"}
           desc="同名文件再次上传会覆盖原来那张表。导入后自动内省。"
           footer={<><button className="btn btn-sm" onClick={onClose}>取消</button>
             <button className="btn btn-primary btn-sm" disabled={busy || !files.length} onClick={() => void save()}>
               {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}导入</button></>}>
      <div className="space-y-3">
        {!ds && <Field label="名称"><input className="input" placeholder="如:产线日报(Excel)" value={name} onChange={(e) => setName(e.target.value)} /></Field>}
        <Field label="文件" hint="支持 .csv .tsv .xlsx .xlsm .json;第一行是表头">
          <input type="file" multiple accept=".csv,.tsv,.xlsx,.xlsm,.json" className="input"
                 onChange={(e) => setFiles(Array.from(e.target.files || []))} />
        </Field>
        {files.map((f) => <p key={f.name} className="text-label text-muted">{f.name} · {Math.ceil(f.size / 1024)} KB</p>)}
      </div>
    </Modal>
  );
}