SopFlow.tsx 4.21 KB
import { Background, Controls, MarkerType, ReactFlow, type Edge, type Node } from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { useMemo } from "react";
import type { SopSpec, SopStep, SopStepRun } from "@/lib/onto";

export const STEP_COLOR: Record<string, string> = {
  function: "#0ea5e9", skill: "#8b5cf6", decision: "#f59e0b", human_task: "#ec4899",
  action: "#ef4444", subprocess: "#14b8a6", end: "#64748b",
};
export const STEP_LABEL: Record<string, string> = {
  function: "取数/求值", skill: "AI 分析", decision: "判断", human_task: "人工任务",
  action: "动作·需审批", subprocess: "子流程", end: "结束",
};

export function successors(st: SopStep): { to: string; label: string }[] {
  if (st.type === "end") return [];
  if (st.type === "decision") {
    return [...(st.branches || []).filter((b) => b.next).map((b) => ({ to: b.next, label: b.label || b.when })),
            ...(st.default ? [{ to: st.default, label: "默认" }] : [])];
  }
  const out = st.next ? [{ to: st.next, label: st.type === "action" ? "批准" : "" }] : [];
  if (st.type === "action" && st.on_reject) out.push({ to: st.on_reject, label: "驳回" });
  return out;
}

/** 流程图:按从开始步骤的层级自动布局,不用手摆坐标。运行视图里按步骤状态着色。 */
export function SopFlow({ spec, runSteps, selected, onSelect, height = 460 }: {
  spec: SopSpec; runSteps?: SopStepRun[]; selected?: string; onSelect?: (id: string) => void; height?: number;
}) {
  const { nodes, edges } = useMemo(() => {
    const byId = new Map(spec.steps.map((s) => [s.id, s]));
    const level = new Map<string, number>();
    const queue = [spec.start];
    level.set(spec.start, 0);
    while (queue.length) {
      const id = queue.shift()!;
      const st = byId.get(id);
      if (!st) continue;
      for (const s of successors(st)) {
        if (!level.has(s.to) && byId.has(s.to)) { level.set(s.to, level.get(id)! + 1); queue.push(s.to); }
      }
    }
    spec.steps.forEach((s) => { if (!level.has(s.id)) level.set(s.id, Math.max(0, ...level.values()) + 1); });
    const rows = new Map<number, string[]>();
    spec.steps.forEach((s) => { const l = level.get(s.id)!; rows.set(l, [...(rows.get(l) || []), s.id]); });
    const status = new Map((runSteps || []).map((r) => [r.step_id, r.status]));
    const nodes: Node[] = spec.steps.map((s) => {
      const l = level.get(s.id)!;
      const row = rows.get(l)!;
      const idx = row.indexOf(s.id);
      const st = status.get(s.id);
      const color = STEP_COLOR[s.type];
      return {
        id: s.id, position: { x: (idx - (row.length - 1) / 2) * 250, y: l * 110 },
        data: { label: (
          <div className="text-left">
            <div className="text-[10px] font-medium" style={{ color }}>{STEP_LABEL[s.type]}{s.lane || s.role ? ` · ${s.role || s.lane}` : ""}</div>
            <div className="text-[12px] font-medium leading-snug">{s.title}</div>
            {st && <div className="mt-0.5 text-[10px] text-muted">{st}</div>}
          </div>) },
        style: {
          width: 200, borderRadius: 10, padding: 8, fontSize: 12,
          border: `${selected === s.id ? 2.5 : 1.5}px solid ${color}`,
          background: st === "done" ? "rgba(16,185,129,.10)" : st?.startsWith("waiting") ? "rgba(245,158,11,.14)"
            : st === "failed" ? "rgba(239,68,68,.12)" : st === "suggested" ? "rgba(99,102,241,.12)" : "rgb(var(--surface))",
          color: "rgb(var(--ink))",
        },
      };
    });
    const edges: Edge[] = spec.steps.flatMap((s) => successors(s).filter((x) => byId.has(x.to)).map((x, i) => ({
      id: `${s.id}-${x.to}-${i}`, source: s.id, target: x.to, label: x.label || undefined,
      markerEnd: { type: MarkerType.ArrowClosed }, style: { strokeWidth: 1.5 },
      labelStyle: { fontSize: 11 },
    })));
    return { nodes, edges };
  }, [spec, runSteps, selected]);

  return (
    <div style={{ height }} className="rounded-lg border border-line">
      <ReactFlow nodes={nodes} edges={edges} fitView nodesDraggable={false} nodesConnectable={false}
                 onNodeClick={(_, n) => onSelect?.(n.id)} proOptions={{ hideAttribution: true }}>
        <Background gap={16} />
        <Controls showInteractive={false} />
      </ReactFlow>
    </div>
  );
}