DocumentsPage.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
import {
  AlertTriangle, ArrowDown, ArrowUp, ArrowUpDown, CheckCircle2, ChevronLeft, ChevronRight,
  FileText, Play, RefreshCw, Search, Trash2, Upload, X, XCircle,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, ApiError } from "@/lib/api";
import { cn, formatBytes, formatTime, shortHeading, STATUS_TEXT, STATUS_TONE } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Modal, Progress, Skeleton } from "@/components/ui";
import type { ChunkRecord, DocumentItem } from "@/lib/types";
import { useJobStream } from "./useJobStream";

const ACCEPT = ".md,.markdown,.txt,.csv,.tsv,.html,.htm,.pdf,.docx,.xlsx,.xlsm,.pptx";

type SortKey = "filename" | "status" | "chunk_count" | "entity_count" | "relation_count" | "updated_at";
const PAGE_SIZE = 10;

export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
  const [docs, setDocs] = useState<DocumentItem[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [activeJob, setActiveJob] = useState<number | null>(null);
  const [activeDoc, setActiveDoc] = useState<DocumentItem | null>(null);
  const [confirmDel, setConfirmDel] = useState<DocumentItem | null>(null);
  const [detail, setDetail] = useState<DocumentItem | null>(null);
  const [showUpload, setShowUpload] = useState(false);

  const [query, setQuery] = useState("");
  const [sortKey, setSortKey] = useState<SortKey>("updated_at");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
  const [page, setPage] = useState(1);

  const load = useCallback(async () => {
    setError(null);
    try {
      const list = await api.documents();
      setDocs(list);
      // 页面刚打开就自动挂上仍在跑的任务 —— 刷新不丢进度
      const running = list.find((d) => d.active_job);
      if (running?.active_job && activeJob == null) {
        setActiveJob(running.active_job.id);
        setActiveDoc(running);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "加载失败");
    }
  }, [activeJob]);

  useEffect(() => { void load(); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, []);

  const job = useJobStream(activeJob, () => { void load(); onExtracted?.(); });

  const startExtract = async (d: DocumentItem) => {
    try {
      const r = await api.startExtract(d.id);
      setActiveJob(r.job_id);
      setActiveDoc(d);
      toast(r.already_running ? "info" : "ok",
            r.already_running ? "该文档已在抽取中,已切到它的进度" : `已提交抽取任务 #${r.job_id}`);
      void load();
    } catch (e) {
      toast("error", "提交失败", e instanceof Error ? e.message : undefined);
    }
  };

  const remove = async (d: DocumentItem) => {
    try {
      const r = await api.deleteDocument(d.id);
      toast("ok", `已删除「${d.filename}」`,
            `回收实体 ${r.removed_entities} 个、关系 ${r.removed_relations} 条、原文片段 ${r.removed_chunks} 个`);
      if (activeDoc?.id === d.id) { setActiveJob(null); setActiveDoc(null); }
      void load();
      onExtracted?.();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : undefined);
    }
  };

  const filtered = useMemo(() => {
    if (!docs) return null;
    const q = query.trim().toLowerCase();
    const list = q ? docs.filter((d) => d.filename.toLowerCase().includes(q)) : docs;
    const dir = sortDir === "asc" ? 1 : -1;
    return [...list].sort((a, b) => {
      const av = a[sortKey] ?? "", bv = b[sortKey] ?? "";
      if (typeof av === "number" && typeof bv === "number") return (av - bv) * dir;
      return String(av).localeCompare(String(bv), "zh-CN") * dir;
    });
  }, [docs, query, sortKey, sortDir]);

  const pageCount = Math.max(1, Math.ceil((filtered?.length ?? 0) / PAGE_SIZE));
  const pageSafe = Math.min(page, pageCount);
  const pageItems = filtered?.slice((pageSafe - 1) * PAGE_SIZE, pageSafe * PAGE_SIZE) ?? null;

  useEffect(() => { setPage(1); }, [query, sortKey, sortDir]);

  const toggleSort = (key: SortKey) => {
    if (sortKey === key) setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    else { setSortKey(key); setSortDir(key === "filename" ? "asc" : "desc"); }
  };

  return (
    <div className="space-y-3">
      {activeJob != null && activeDoc && (
        <JobCard doc={activeDoc} job={job} onClose={() => { setActiveJob(null); setActiveDoc(null); }} />
      )}

      <Card>
        <CardHeader
          title="文档列表"
          desc={docs ? `共 ${docs.length} 份;删除文档会连同它独有的实体、关系和原文索引一起回收` : undefined}
          right={<>
            <button className="btn btn-sm" onClick={() => void load()}>
              <RefreshCw className="h-3.5 w-3.5" />刷新</button>
            <button className="btn btn-primary btn-sm" onClick={() => setShowUpload(true)}>
              <Upload className="h-3.5 w-3.5" />上传文档</button>
          </>}
        />

        {docs && docs.length > 0 && (
          <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2">
            <div className="relative w-full max-w-[16rem]">
              <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 h-8 pl-8 text-[12.5px]" placeholder="按文件名检索…"
                     value={query} onChange={(e) => setQuery(e.target.value)} />
            </div>
            <span className="ml-auto text-[11.5px] text-muted">
              {filtered?.length ?? 0} 条结果
            </span>
          </div>
        )}

        {error && <div className="p-3"><ErrorNote onRetry={load}>{error}</ErrorNote></div>}
        {!docs && !error && (
          <div className="space-y-2 p-3">
            {Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-12 w-full" />)}
          </div>
        )}
        {docs?.length === 0 && (
          <Empty icon={<FileText className="h-8 w-8" />} title="还没有文档"
                 desc="上传一份业务文档(md / txt / pdf / docx / xlsx / pptx / csv / html),系统会抽取实体与关系并建成图谱。"
                 action={<button className="btn btn-primary btn-sm" onClick={() => setShowUpload(true)}>
                   <Upload className="h-3.5 w-3.5" />上传文档</button>} />
        )}
        {docs && docs.length > 0 && filtered?.length === 0 && (
          <Empty icon={<Search className="h-7 w-7" />} title="没有匹配的文档" desc={`没有文件名包含「${query}」的文档`} />
        )}
        {pageItems && pageItems.length > 0 && (
          <div className="overflow-x-auto">
            <table className="w-full text-[13px]">
              <thead>
                <tr className="border-b border-line text-left text-xs text-muted">
                  <SortableTh label="文件名" sortKey="filename" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-4 py-2" />
                  <SortableTh label="状态" sortKey="status" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-3 py-2" />
                  <SortableTh label="片段" sortKey="chunk_count" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-3 py-2" align="right" />
                  <SortableTh label="实体" sortKey="entity_count" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-3 py-2" align="right" />
                  <SortableTh label="关系" sortKey="relation_count" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-3 py-2" align="right" />
                  <SortableTh label="更新" sortKey="updated_at" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-3 py-2" />
                  <th className="px-4 py-2 text-right font-medium">操作</th>
                </tr>
              </thead>
              <tbody>
                {pageItems.map((d) => (
                  <tr key={d.id} className="border-b border-line/60 last:border-0 hover:bg-ink/[0.02]">
                    <td className="max-w-[22rem] px-4 py-2">
                      <button className="block w-full truncate text-left font-medium hover:text-brand"
                              onClick={() => setDetail(d)} title={d.filename}>
                        {d.filename}
                      </button>
                      <span className="flex flex-wrap items-center gap-1.5 text-[11px] text-muted">
                        {formatBytes(d.size_bytes)}
                        {d.encoding && <Badge>{d.encoding}</Badge>}
                        {d.parse_warning && (
                          <Badge tone="bg-warn/10 text-warn" >
                            <AlertTriangle className="h-3 w-3" />{shortHeading(d.parse_warning, 1)}
                          </Badge>
                        )}
                      </span>
                    </td>
                    <td className="px-3 py-2">
                      <Badge tone={STATUS_TONE[d.status]}>{STATUS_TEXT[d.status] ?? d.status}</Badge>
                      {d.error && (
                        <p className="mt-0.5 max-w-[16rem] truncate text-[11px] text-bad" title={d.error}>{d.error}</p>
                      )}
                    </td>
                    <td className="px-3 py-2 text-right tabular-nums">{d.chunk_count || "—"}</td>
                    <td className="px-3 py-2 text-right tabular-nums">{d.entity_count || "—"}</td>
                    <td className="px-3 py-2 text-right tabular-nums">{d.relation_count || "—"}</td>
                    <td className="px-3 py-2 text-[11.5px] text-muted">{formatTime(d.updated_at)}</td>
                    <td className="px-4 py-2">
                      <div className="flex items-center justify-end gap-1">
                        {d.active_job ? (
                          <button className="btn btn-sm"
                                  onClick={() => { setActiveJob(d.active_job!.id); setActiveDoc(d); }}>
                            查看进度
                          </button>
                        ) : (
                          <button className="btn btn-sm" onClick={() => void startExtract(d)}>
                            <Play className="h-3.5 w-3.5" />{d.status === "done" ? "重抽" : "抽取"}
                          </button>
                        )}
                        <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(d)}
                                disabled={!!d.active_job} title="删除">
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {filtered && filtered.length > PAGE_SIZE && (
          <div className="flex items-center justify-between border-t border-line px-4 py-2 text-[12.5px] text-muted">
            <span>第 {pageSafe} / {pageCount} 页</span>
            <div className="flex items-center gap-1">
              <button className="btn btn-ghost btn-sm" disabled={pageSafe <= 1} onClick={() => setPage((p) => p - 1)}>
                <ChevronLeft className="h-3.5 w-3.5" /></button>
              <button className="btn btn-ghost btn-sm" disabled={pageSafe >= pageCount} onClick={() => setPage((p) => p + 1)}>
                <ChevronRight className="h-3.5 w-3.5" /></button>
            </div>
          </div>
        )}
      </Card>

      <Confirm
        open={!!confirmDel} onClose={() => setConfirmDel(null)} danger confirmText="删除"
        title={`删除「${confirmDel?.filename ?? ""}」?`}
        body={<>
          会同时回收该文档**独有**的实体与关系,以及它的原文片段索引。
          被其他文档共同支撑的实体会保留。此操作不可撤销。
        </>}
        onConfirm={() => confirmDel && void remove(confirmDel)}
      />

      <DocDetailModal doc={detail} onClose={() => setDetail(null)} />

      <Modal open={showUpload} onClose={() => setShowUpload(false)} title="上传文档" width="max-w-xl"
             bodyClass="p-0">
        <UploadZone onUploaded={(d) => { void load(); void startExtract(d); }} />
      </Modal>
    </div>
  );
}

// ---------------- 可排序表头 ----------------
function SortableTh({ label, sortKey, active, dir, onSort, className, align }: {
  label: string; sortKey: SortKey; active: SortKey; dir: "asc" | "desc";
  onSort: (k: SortKey) => void; className?: string; align?: "right";
}) {
  const isActive = active === sortKey;
  const Icon = isActive ? (dir === "asc" ? ArrowUp : ArrowDown) : ArrowUpDown;
  return (
    <th className={cn(className, "font-medium select-none", align === "right" && "text-right")}>
      <button className={cn("inline-flex items-center gap-1 hover:text-ink", align === "right" && "flex-row-reverse",
        isActive && "text-ink")} onClick={() => onSort(sortKey)}>
        {label}<Icon className="h-3 w-3" />
      </button>
    </th>
  );
}

// ---------------- 上传(弹层里的内容:拖拽 + 多选 + 进度) ----------------
function UploadZone({ onUploaded }: { onUploaded: (d: DocumentItem) => void }) {
  const [drag, setDrag] = useState(false);
  const [queue, setQueue] = useState<{ name: string; pct: number; error?: string }[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);

  const upload = async (files: FileList | File[]) => {
    const list = Array.from(files);
    if (!list.length) return;
    setQueue(list.map((f) => ({ name: f.name, pct: 0 })));
    for (let i = 0; i < list.length; i++) {
      const f = list[i];
      try {
        const d = await api.upload(f, (pct) =>
          setQueue((q) => q.map((x, j) => (j === i ? { ...x, pct } : x))));
        setQueue((q) => q.map((x, j) => (j === i ? { ...x, pct: 100 } : x)));
        if (d.duplicate) toast("warn", d.message ?? "文件已存在");
        else { toast("ok", `已上传:${d.filename}`); onUploaded(d); }
      } catch (e) {
        const msg = e instanceof ApiError ? e.message : "上传失败";
        setQueue((q) => q.map((x, j) => (j === i ? { ...x, error: msg } : x)));
        toast("error", `「${f.name}」上传失败`, msg);
      }
    }
  };

  return (
    <div className="p-4">
      <div
        className={cn("rounded-xl border-2 border-dashed p-6 transition-colors",
          drag ? "border-brand bg-brand/5" : "border-line")}
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); void upload(e.dataTransfer.files); }}
      >
        <input ref={inputRef} type="file" hidden multiple accept={ACCEPT}
               onChange={(e) => { if (e.target.files) void upload(e.target.files); e.target.value = ""; }} />
        <div className="flex flex-col items-center gap-2 text-center">
          <div className="grid h-11 w-11 place-items-center rounded-xl bg-brand/10">
            <Upload className="h-5 w-5 text-brand" />
          </div>
          <p className="text-[14px] font-medium">拖拽文件到此,或
            <button className="ml-1 text-brand underline underline-offset-2"
                    onClick={() => inputRef.current?.click()}>选择文件</button>
          </p>
          <p className="text-xs text-muted">
            支持 md / txt / csv / html / pdf / docx / xlsx / pptx,可一次多选多个文件。
            中文文件名与 GBK 编码都会自动识别修复。
          </p>
        </div>
      </div>
      {queue.length > 0 && (
        <div className="mt-4 space-y-1.5">
          {queue.map((q, i) => (
            <div key={i} className="flex items-center gap-2 text-xs">
              <span className="min-w-0 flex-1 truncate">{q.name}</span>
              {q.error ? <span className="shrink-0 text-bad">{q.error}</span> : (
                <>
                  <Progress value={q.pct} className="w-28 shrink-0" />
                  <span className="w-9 shrink-0 text-right tabular-nums text-muted">{q.pct}%</span>
                </>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------------- 任务进度 ----------------
function JobCard({ doc, job, onClose }: {
  doc: DocumentItem; job: ReturnType<typeof useJobStream>; onClose: () => void;
}) {
  const logRef = useRef<HTMLDivElement>(null);
  useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight }); }, [job.events.length]);

  const last = job.events[job.events.length - 1];
  const quality = job.events.find((e) => e.stage === "done")?.quality as Record<string, any> | undefined;

  return (
    <Card>
      <CardHeader
        title={<span className="flex items-center gap-2">
          抽取进度
          {job.finished && !job.error && <CheckCircle2 className="h-4 w-4 text-ok" />}
          {job.error && <XCircle className="h-4 w-4 text-bad" />}
        </span>}
        desc={doc.filename}
        right={<button className="btn btn-ghost btn-sm" onClick={onClose}><X className="h-3.5 w-3.5" /></button>}
      />
      <div className="space-y-2 p-3">
        <div className="flex items-center gap-2">
          <Progress value={job.progress} />
          <span className="w-10 shrink-0 text-right text-xs tabular-nums text-muted">{job.progress}%</span>
        </div>
        <p className="text-xs text-muted">
          {job.error ? <span className="text-bad">{job.error}</span>
            : job.finished ? "抽取完成"
            : last?.message ?? (last?.stage === "extract" ? `正在抽取第 ${last.i}/${last.total} 个片段` : "准备中…")}
        </p>

        {quality && (
          <div className="grid grid-cols-2 gap-2 rounded-lg border border-line bg-elevated p-2.5 text-xs sm:grid-cols-4">
            <QualityStat label="片段数" value={quality.chunks} hint={`平均 ${quality.avg_chunk_tokens} token`} />
            <QualityStat label="LLM 调用" value={quality.llm_calls} />
            <QualityStat label="过滤噪声实体" value={quality.dropped_noise} />
            <QualityStat label="消歧合并" value={quality.resolve?.merged ?? 0}
                          hint={`候选 ${quality.resolve?.candidates ?? 0} 组`} />
          </div>
        )}

        <div ref={logRef}
             className="max-h-56 overflow-auto rounded-lg bg-[#0f1420] p-2.5 font-mono text-[11.5px] leading-5 text-slate-300">
          {job.events.map((e, i) => <LogLine key={i} ev={e} />)}
          {job.events.length === 0 && <p className="text-slate-500">等待任务开始…</p>}
        </div>
      </div>
    </Card>
  );
}

function QualityStat({ label, value, hint }: { label: string; value: unknown; hint?: string }) {
  return (
    <div>
      <p className="text-[10.5px] uppercase tracking-wide text-muted">{label}</p>
      <p className="text-[15px] font-semibold tabular-nums">{String(value ?? "—")}</p>
      {hint && <p className="text-[10.5px] text-muted">{hint}</p>}
    </div>
  );
}

function LogLine({ ev }: { ev: import("@/lib/types").ExtractEvent }) {
  if (ev.stage === "error" || ev.error) {
    return <p className="whitespace-pre-wrap text-rose-300">× {ev.error}</p>;
  }
  if (ev.stage === "extract" && ev.i) {
    return (
      <p className="whitespace-pre-wrap text-emerald-300">
        ✓ [{ev.i}/{ev.total}] {shortHeading(ev.heading)} · +实体 {ev.new_entities} / +关系 {ev.new_relations}
        <span className="text-slate-500"> · 累计 {ev.cum_entities}/{ev.cum_relations}</span>
      </p>
    );
  }
  if (ev.stage === "done") return <p className="text-emerald-300">✔ {ev.message}</p>;
  return <p className={cn("whitespace-pre-wrap", ev.level === "warn" ? "text-amber-300" : "text-slate-300")}>
    · {ev.message ?? ev.stage}
  </p>;
}

// ---------------- 文档详情 ----------------
function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: () => void }) {
  const [tab, setTab] = useState<"chunks" | "entities">("chunks");
  const [chunks, setChunks] = useState<ChunkRecord[] | null>(null);
  const [entities, setEntities] = useState<{ total: number; items: any[] } | null>(null);

  useEffect(() => {
    if (!doc) { setChunks(null); setEntities(null); return; }
    setTab("chunks");
    void api.documentChunks(doc.id).then((r) => setChunks(r.chunks)).catch(() => setChunks([]));
    void api.documentEntities(doc.id).then(setEntities).catch(() => undefined);
  }, [doc]);

  if (!doc) return null;
  return (
    <Modal open onClose={onClose} title={doc.filename} width="max-w-3xl" bodyClass="p-0">
      <div className="flex border-b border-line px-2">
        {([["chunks", `分块(${chunks?.length ?? "…"})`], ["entities", `实体(${entities?.total ?? "…"})`]] as const)
          .map(([k, label]) => (
            <button key={k}
                    className={cn("px-3 py-2 text-[13px]",
                      tab === k ? "border-b-2 border-brand font-medium text-brand" : "text-muted")}
                    onClick={() => setTab(k)}>{label}</button>
          ))}
      </div>
      <div className="max-h-[60vh] space-y-2 overflow-auto p-3">
        {tab === "chunks" && (chunks?.length
          ? chunks.map((c) => (
            <div key={c.id} className="rounded-lg border border-line p-2.5">
              <div className="mb-1 flex flex-wrap items-center gap-1.5">
                <code className="rounded bg-ink/5 px-1.5 py-0.5 font-mono text-[10.5px] text-muted">{c.id}</code>
                <Badge>{c.tokens} token</Badge>
                <span className="min-w-0 truncate text-[11.5px] text-muted">{c.heading}</span>
              </div>
              <p className="whitespace-pre-wrap text-[12.5px] leading-6 text-muted line-clamp-4">{c.text}</p>
            </div>
          ))
          : <p className="py-8 text-center text-xs text-muted">尚未抽取,没有分块记录。</p>)}
        {tab === "entities" && (entities?.items.length
          ? entities.items.map((e) => (
            <div key={e.id} className="flex items-center gap-2 rounded-lg border border-line px-2.5 py-1.5">
              <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{e.label}</span>
              <Badge>{e.type}</Badge>
              <span className="shrink-0 text-[11px] tabular-nums text-muted">{e.degree} 度</span>
            </div>
          ))
          : <p className="py-8 text-center text-xs text-muted">该文档还没有抽出实体。</p>)}
      </div>
    </Modal>
  );
}