ObjectsPage.tsx 14.4 KB
/**
 * 对象:选一类对象看表格,点一行看这个对象的全貌 —— 属性、指标、关联对象、发生过的事,以及能对它做什么。
 */
import { ArrowLeft, Boxes, Radar, Search, Zap } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Ago, Desc, isNumeric, Tabs, Value } from "@/components/kit";
import { Badge, Card, Empty, ErrorNote, Spinner, type BadgeVariant } from "@/components/ui";
import { ProposeActionModal } from "@/features/actions/ActionParts";
import { fmtValue, type FieldMeta } from "@/lib/format";
import { go, useHashParams } from "@/lib/nav";
import { errText, onto, STATUS_LABEL, type CapDef, type ConceptBrief, type ImpactResult, type Me, type ObjectRec } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { ObjectTable } from "./ObjectTable";

const RUN_VARIANT: Record<string, BadgeVariant> = {
  done: "ok", failed: "danger", rejected: "danger", pending_approval: "warn", waiting: "warn", running: "info",
  executing: "info", cancelled: "neutral", reverted: "neutral",
};

export function ObjectsPage({ me }: { me: Me | null }) {
  const params = useHashParams();
  const [types, setTypes] = useState<ConceptBrief[] | null>(null);
  const [err, setErr] = useState("");
  const [q, setQ] = useState("");
  const type = params.get("type") || types?.[0]?.id || "";
  const key = params.get("key") || "";

  useEffect(() => {
    void onto.concepts({ kind: "object_type", status: "published" }).then(setTypes).catch((e) => { setErr(errText(e)); setTypes([]); });
  }, []);
  useEffect(() => { setQ(""); }, [type]);

  if (err) return <ErrorNote>{err}</ErrorNote>;
  if (types === null) return <div className="grid place-items-center p-16"><Spinner /></div>;
  if (!types.length) {
    return <Card><Empty icon={<Boxes className="h-10 w-10" />} title="还没有可以看的对象"
                        desc="对象建好并发布后,会出现在这里。"
                        action={me?.permissions.includes("build") ? <button className="btn" onClick={() => go("b_object")}>去建对象</button> : undefined} /></Card>;
  }
  if (key) return <ObjectDetail key={`${type}:${key}`} type={type} objKey={key} me={me} />;
  return (
    <div className="flex h-full min-h-0 flex-col gap-3">
      <div className="flex flex-wrap items-center gap-2">
        <div className="flex flex-wrap gap-1.5">
          {types.map((t) => (
            <button key={t.id} onClick={() => go("objects", { type: t.id })}
                    className={cn("rounded-lg border px-3 py-1.5 text-body transition-colors",
                      t.id === type ? "border-brand bg-brand/5 font-medium text-brand" : "border-line bg-surface hover:border-brand/40")}>
              {t.name}
            </button>
          ))}
        </div>
        <span className="flex-1" />
        <div className="relative w-64">
          <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={q} onChange={(e) => setQ(e.target.value)} />
        </div>
      </div>
      <ObjectTable type={type} q={q} onOpen={(k) => go("objects", { type, key: k })} />
    </div>
  );
}

type Tab = "overview" | "links" | "activity" | "docs";

function ObjectDetail({ type, objKey, me }: { type: string; objKey: string; me: Me | null }) {
  const [d, setD] = useState<any>(null);
  const [err, setErr] = useState("");
  const [tab, setTab] = useState<Tab>("overview");
  const [act, setAct] = useState<CapDef | null>(null);
  const load = () => { void onto.object360(type, objKey).then((x) => { setD(x); setErr(""); }).catch((e) => setErr(errText(e))); };
  useEffect(() => { load(); }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const back = <button className="btn btn-ghost btn-sm -ml-2 w-fit" onClick={() => go("objects", { type })}><ArrowLeft className="h-4 w-4" />返回列表</button>;
  if (err) return <div className="space-y-3">{back}<ErrorNote onRetry={load}>{err}</ErrorNote></div>;
  if (!d) return <div className="grid place-items-center p-16"><Spinner /></div>;

  const o: ObjectRec = d.object;
  const fields: FieldMeta[] = d.fields || [];
  const actions: CapDef[] = d.actions || [];
  const links: any[] = d.links || [];
  const many = links.filter((g) => !g.single);
  const activity = buildActivity(d);
  const base = fields.filter((f) => !f.derived);
  const derived = fields.filter((f) => f.derived);
  const item = (f: FieldMeta) => ({
    label: <span title={f.description || undefined}>{f.label}</span>,
    value: <Value v={o.properties[f.name]} field={f} refInfo={o.refs?.[f.name]} />,
  });

  return (
    <div className="flex flex-col gap-4">
      {back}
      <div className="flex flex-wrap items-start gap-3">
        <div className="min-w-0 flex-1">
          <p className="text-label text-muted">{d.object_type.name}</p>
          <h2 className="mt-0.5 break-words text-page font-semibold">{o.label}</h2>
          {o.label !== o.key && <p className="mt-0.5 text-label text-muted">编号 {o.key}</p>}
        </div>
        {me?.permissions.includes("operate") && actions.length > 0 && (
          <div className="flex flex-wrap justify-end gap-2">
            {actions.map((a) => (
              <button key={a.id} className="btn" title={a.description} onClick={() => setAct(a)}><Zap className="h-3.5 w-3.5 text-brand" />{a.display_name || a.name}</button>
            ))}
          </div>
        )}
      </div>

      <Tabs<Tab> value={tab} onChange={setTab} options={[
        { key: "overview", label: "概览" },
        { key: "links", label: "关联", count: many.reduce((n, g) => n + (g.total || g.items.length), 0) },
        { key: "activity", label: "动态", count: activity.length },
        { key: "docs", label: "相关文档", count: (d.documents || []).length },
      ]} />

      {tab === "overview" && (
        <div className="space-y-4">
          {(d.metrics || []).length > 0 && (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
              {d.metrics.map((m: any) => (
                <Card key={m.metric.id} className="px-4 py-3">
                  <p className="text-label text-muted">{m.metric.name}</p>
                  <p className="mt-1 text-page font-semibold tabular-nums">
                    {m.error ? "—" : fmtValue(m.value, { format: m.metric.format, unit: "" })}
                    {!m.error && m.metric.unit && m.metric.format !== "money" && <span className="ml-1 text-label font-normal text-muted">{m.metric.unit}</span>}
                  </p>
                  {m.error && <p className="mt-0.5 truncate text-caption text-bad" title={m.error}>{m.error}</p>}
                </Card>
              ))}
            </div>
          )}
          <Card className="p-5">
            <h3 className="mb-4 text-title font-semibold">基本信息</h3>
            <Desc items={base.map(item)} />
          </Card>
          {derived.length > 0 && (
            <Card className="p-5">
              <h3 className="mb-4 text-title font-semibold">计算值</h3>
              <Desc items={derived.map(item)} cols={4} />
            </Card>
          )}
          <ImpactPanel type={type} objKey={objKey} />
        </div>
      )}

      {tab === "links" && (
        <div className="space-y-4">
          {!many.length && <Card><Empty title="没有关联的记录" /></Card>}
          {many.map((g) => <LinkTable key={g.link_id + g.direction} g={g} />)}
        </div>
      )}

      {tab === "activity" && (
        <Card>
          {!activity.length ? <Empty title="还没有发生过什么" /> : (
            <ul className="divide-y divide-line/70">
              {activity.map((a, i) => (
                <li key={i} className={cn("flex items-start gap-3 px-5 py-3", a.link && "cursor-pointer hover:bg-ink/[0.03]")}
                    onClick={() => a.link && (window.location.hash = a.link)}>
                  <span className="mt-0.5 w-16 shrink-0 rounded bg-ink/[0.06] px-1.5 py-0.5 text-center text-caption text-muted">{a.kind}</span>
                  <div className="min-w-0 flex-1">
                    <p className="text-body">{a.title}</p>
                    {a.detail && <p className="mt-0.5 line-clamp-2 text-label text-muted">{a.detail}</p>}
                  </div>
                  {a.status && <Badge variant={RUN_VARIANT[a.status] || "neutral"}>{STATUS_LABEL[a.status] || a.status}</Badge>}
                  <span className="w-28 shrink-0 text-right text-label text-muted">{a.who && <span className="mr-2">{a.who}</span>}<Ago at={a.at} /></span>
                </li>
              ))}
            </ul>
          )}
        </Card>
      )}

      {tab === "docs" && (
        <Card>
          {!(d.documents || []).length ? <Empty title="文档里没有提到它" /> : (
            <ul className="divide-y divide-line/70">
              {d.documents.map((c: any) => (
                <li key={c.id} className="px-5 py-3">
                  <p className="text-body font-medium">{c.heading || "正文"}</p>
                  <p className="mt-1 line-clamp-3 text-label text-muted">{String(c.snippet || "").replace(/[*#>`]/g, "")}</p>
                </li>
              ))}
            </ul>
          )}
        </Card>
      )}

      {act && <ProposeActionModal action={act} objKey={objKey} objLabel={o.label} onClose={() => setAct(null)}
                                  onDone={(rid) => { setAct(null); load(); go("inbox", { run: rid }); }} />}
    </div>
  );
}

function LinkTable({ g }: { g: any }) {
  const fields: FieldMeta[] = (g.fields || []).slice(0, 8);
  const items: ObjectRec[] = g.items || [];
  return (
    <Card className="overflow-hidden">
      <div className="flex items-center gap-2 border-b border-line px-5 py-3">
        <h3 className="text-title font-semibold">{g.object_type}</h3>
        <span className="text-label text-muted">{g.total ?? items.length} 条</span>
        <span className="flex-1" />
        <button className="btn btn-ghost btn-sm" onClick={() => go("objects", { type: g.object_type_id })}>查看全部</button>
      </div>
      {!items.length ? <p className="px-5 py-4 text-label text-muted">没有</p> : (
        <div className="overflow-auto">
          <table className="tbl">
            <thead><tr><th>名称</th>{fields.map((f) => <th key={f.name} className={cn(isNumeric(f) && "text-right")}>{f.label}</th>)}</tr></thead>
            <tbody>
              {items.map((x) => (
                <tr key={x.key} className="row-link" onClick={() => go("objects", { type: g.object_type_id, key: x.key })}>
                  <td className="max-w-[16rem] truncate whitespace-nowrap font-medium">{x.label}</td>
                  {fields.map((f) => (
                    <td key={f.name} className={cn("max-w-[14rem] truncate whitespace-nowrap", isNumeric(f) && "num")}>
                      <Value v={x.properties?.[f.name]} field={f} refInfo={x.refs?.[f.name]} />
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      {(g.total ?? 0) > items.length && <p className="border-t border-line px-5 py-2 text-caption text-muted">只列出前 {items.length} 条</p>}
    </Card>
  );
}

interface Act { kind: string; title: string; detail?: string; status?: string; who?: string; at: string; link?: string }

/** 把动作、流程运行、属性修改合成一条时间线。 */
function buildActivity(d: any): Act[] {
  const out: Act[] = [];
  for (const r of d.action_runs || []) {
    out.push({ kind: "动作", title: r.action_name, detail: r.preview?.summary, status: r.status, at: r.created_at, link: `#/inbox?run=${r.id}` });
  }
  for (const r of d.sop_runs || []) {
    out.push({ kind: "流程", title: r.title, detail: r.outcome || r.error, status: r.status, at: r.created_at, link: `#/sop?run=${r.id}` });
  }
  const seen = new Set((d.action_runs || []).map((r: any) => r.id));
  for (const a of d.audit || []) {
    if (a.target_type === "action_run" && seen.has(a.target_id)) continue;
    out.push({ kind: "修改", title: a.summary, who: a.actor_name, at: a.ts });
  }
  return out.sort((a, b) => (a.at < b.at ? 1 : -1)).slice(0, 60);
}

/** 影响分析:顺着关系往外推,这个对象出了问题会波及谁。 */
function ImpactPanel({ type, objKey }: { type: string; objKey: string }) {
  const [depth, setDepth] = useState(2);
  const [r, setR] = useState<ImpactResult | null>(null);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const run = async () => {
    setBusy(true); setErr("");
    try { setR(await onto.impactObject(type, objKey, depth)); } catch (e) { setR(null); setErr(errText(e)); } finally { setBusy(false); }
  };
  const groups = useMemo(() => (r?.layers || []).flatMap((l) => l.groups.map((g) => ({ ...g, depth: l.depth }))), [r]);
  return (
    <Card className="p-5">
      <div className="flex flex-wrap items-center gap-3">
        <h3 className="flex-1 text-title font-semibold">影响分析</h3>
        <select className="input h-8 w-28" value={depth} onChange={(e) => setDepth(Number(e.target.value))}>
          {[1, 2, 3].map((x) => <option key={x} value={x}>往外 {x} 层</option>)}
        </select>
        <button className="btn btn-sm" disabled={busy} onClick={() => void run()}>
          {busy ? <Spinner className="h-3.5 w-3.5" /> : <Radar className="h-3.5 w-3.5" />}看看会影响谁
        </button>
      </div>
      {err && <p className="mt-3 rounded-md bg-warn/10 px-3 py-2 text-label text-warn">{err}</p>}
      {r && (
        <div className="mt-4 space-y-3">
          {!groups.length && <p className="text-label text-muted">没有找到会受影响的对象。</p>}
          {groups.map((g) => (
            <div key={`${g.depth}:${g.type_name}`}>
              <p className="mb-1.5 text-label"><span className="font-medium">{g.type_name}</span><span className="ml-1.5 text-muted">{g.count} 个 · 第 {g.depth} 层</span></p>
              <div className="flex flex-wrap gap-1.5">
                {g.items.slice(0, 24).map((n) => (
                  <button key={n.id} className="chip" title={n.via ? `经「${n.via.link}」` : ""}
                          onClick={() => go("objects", { type: n.type_id, key: n.key })}>{n.label}</button>
                ))}
                {g.items.length > 24 && <span className="self-center text-caption text-muted">等 {g.count} 个</span>}
              </div>
            </div>
          ))}
          {r.truncated && <p className="text-caption text-muted">结果太多,只列出了一部分。</p>}
        </div>
      )}
    </Card>
  );
}