specOps.ts 12.2 KB
/**
 * 流程卡定义的纯函数操作:画布和表单视图共用同一套,保证「改名 / 删除 / 换类型 / 连线」
 * 之后所有引用都是对的 —— 以前改个步骤编号、删个步骤,别的步骤还指着旧编号,流程就断了。
 *
 * 全部返回新对象,不改入参,方便做撤销 / 重做。
 */
import type { SopSpec, SopStep } from "@/lib/onto";

export type StepType = SopStep["type"];

export const STEP_COLOR: Record<string, string> = {
  function: "#0ea5e9", skill: "#8b5cf6", decision: "#f59e0b", human_task: "#ec4899",
  action: "#ef4444", foreach: "#f97316", subprocess: "#14b8a6", end: "#64748b",
};
export const STEP_LABEL: Record<string, string> = {
  function: "取数 / 计算", skill: "AI 分析", decision: "判断", human_task: "人工任务",
  action: "动作(需审批)", foreach: "逐行处理", subprocess: "子流程", end: "结束",
};
export const STEP_HINT: Record<string, string> = {
  function: "调用指标、规则、决策表等只读函数取数或计算",
  skill: "让 AI 分析一段数据,结果仅供参考",
  decision: "按条件走不同分支,都不满足时走默认",
  human_task: "派给某个角色去做,填完表单后流程继续",
  action: "发起一个业务动作,审批通过才执行",
  foreach: "对上一步取到的每一行各发起一次动作(如每条缺货各提一张补货单)",
  subprocess: "调用另一张流程卡",
  end: "流程结束,写一句结果说明",
};

/** 出口:每条出边从哪个「口」出去,连到哪一步。画布上的连接点就是这些口。 */
export interface Exit { handle: string; to: string; label: string }

export function exits(st: SopStep): Exit[] {
  if (st.type === "end") return [];
  if (st.type === "decision") {
    return [
      ...(st.branches || []).map((b, i) => ({ handle: `b${i}`, to: b.next, label: b.label || b.when || `分支 ${i + 1}` })),
      { handle: "default", to: st.default || "", label: "默认" },
    ];
  }
  const out: Exit[] = [{ handle: "next", to: st.next || "", label: st.type === "action" ? "批准" : "" }];
  if (st.type === "action") out.push({ handle: "reject", to: st.on_reject || "", label: "驳回" });
  return out;
}

export function successors(st: SopStep): { to: string; label: string }[] {
  return exits(st).filter((e) => e.to).map((e) => ({ to: e.to, label: e.label }));
}

export function newId(spec: SopSpec, prefix = "s"): string {
  let i = spec.steps.length + 1;
  while (spec.steps.some((s) => s.id === `${prefix}${i}`)) i++;
  return `${prefix}${i}`;
}

/** 新步骤:只带这一类型需要的字段。 */
export function blankStep(id: string, type: StepType): SopStep {
  const base: SopStep = { id, type, title: STEP_LABEL[type] || type, description: "", lane: "", next: "", output: "" };
  switch (type) {
    case "function": return { ...base, function: "", args: {} };
    case "skill": return { ...base, skill: "", inputs: {} };
    case "decision": return { ...base, branches: [{ when: "", next: "", label: "是" }], default: "" };
    case "human_task": return { ...base, role: "", instructions: "", form: [], checklist: [], sla_hours: 24 };
    case "action": return { ...base, action: "", params: {}, object_key: "", on_reject: "" };
    case "foreach": return { ...base, items: "", action: "", params: {}, object_key: "", limit: 20 };
    case "subprocess": return { ...base, sop: "", params: {} };
    case "end": return { ...base, outcome: "" };
    default: return base;
  }
}

export function addStep(spec: SopSpec, type: StepType, opts: { after?: string; pos?: { x: number; y: number } } = {}): { spec: SopSpec; id: string } {
  const id = newId(spec);
  const step = blankStep(id, type);
  let steps = [...spec.steps, step];
  // 接在某一步后面:如果那一步的「下一步」还空着,顺手连上
  if (opts.after) {
    steps = steps.map((s) => (s.id === opts.after && s.type !== "decision" && s.type !== "end" && !s.next ? { ...s, next: id } : s));
  }
  const layout = { ...(spec.layout || {}) };
  if (opts.pos) layout[id] = opts.pos;
  return { spec: { ...spec, steps, start: spec.start || id, layout }, id };
}

/** 把所有指向 from 的引用改成 to(to 为空就是断开)。 */
function retarget(st: SopStep, from: string, to: string): SopStep {
  const r = (v?: string) => (v === from ? to : v || "");
  const out: SopStep = { ...st, next: r(st.next) };
  if (st.type === "decision") {
    out.branches = (st.branches || []).map((b) => ({ ...b, next: r(b.next) }));
    out.default = r(st.default);
  }
  if (st.type === "action") out.on_reject = r(st.on_reject);
  return out;
}

export function deleteStep(spec: SopSpec, id: string): SopSpec {
  const steps = spec.steps.filter((s) => s.id !== id).map((s) => retarget(s, id, ""));
  const layout = { ...(spec.layout || {}) };
  delete layout[id];
  const start = spec.start === id ? (steps[0]?.id || "") : spec.start;
  return { ...spec, steps, start, layout };
}

export function renameStep(spec: SopSpec, from: string, to: string): SopSpec {
  const clean = to.replace(/[^\w-]/g, "");
  if (!clean || clean === from || spec.steps.some((s) => s.id === clean)) return spec;
  const steps = spec.steps.map((s) => retarget(s.id === from ? { ...s, id: clean } : s, from, clean));
  const layout = { ...(spec.layout || {}) };
  if (layout[from]) { layout[clean] = layout[from]; delete layout[from]; }
  return { ...spec, steps, start: spec.start === from ? clean : spec.start, layout };
}

/** 换类型:保留通用字段和已有的下一步,丢掉旧类型特有的字段,补上新类型需要的。 */
export function changeType(spec: SopSpec, id: string, type: StepType): SopSpec {
  return {
    ...spec,
    steps: spec.steps.map((s) => {
      if (s.id !== id || s.type === type) return s;
      const fresh = blankStep(s.id, type);
      const keepTitle = s.title && s.title !== STEP_LABEL[s.type];
      const out: SopStep = { ...fresh, title: keepTitle ? s.title : fresh.title, description: s.description, lane: s.lane,
                             output: type === "decision" || type === "end" ? "" : s.output };
      if (type !== "decision" && type !== "end") out.next = s.type === "decision" ? (s.default || "") : s.next;
      if (type === "decision") out.default = s.next;
      return out;
    }),
  };
}

export function updateStep(spec: SopSpec, id: string, patch: Partial<SopStep>): SopSpec {
  return { ...spec, steps: spec.steps.map((s) => (s.id === id ? { ...s, ...patch } : s)) };
}

/** 连线:从 source 的某个出口连到 target。 */
export function connect(spec: SopSpec, source: string, handle: string, target: string): SopSpec {
  if (source === target) return spec;
  return {
    ...spec,
    steps: spec.steps.map((s) => {
      if (s.id !== source) return s;
      if (handle === "default") return { ...s, default: target };
      if (handle === "reject") return { ...s, on_reject: target };
      if (handle.startsWith("b")) {
        const i = Number(handle.slice(1));
        const bs = [...(s.branches || [])];
        if (bs[i]) bs[i] = { ...bs[i], next: target };
        return { ...s, branches: bs };
      }
      return { ...s, next: target };
    }),
  };
}

export function disconnect(spec: SopSpec, source: string, handle: string): SopSpec {
  return connect(spec, source, handle, "");
}

/** 「逐行处理」「动作」等步骤里能引用的变量:参数 + 所有上游步骤的输出。 */
/** 一个步骤的输出里有哪些字段可以引用($变量.字段)。以前只告诉人有个 $shortage,至于该写 .value 还是 .rows 全靠猜。 */
export function outputFields(st: SopStep): string[] {
  if (st.type === "function") {
    const f = st.function || "";
    if (f === "metric.query") return ["value", "rows", "summary"];
    if (f === "data.ask") return ["value", "rows", "summary"];
    if (f === "decision.eval") return ["result", "matched"];
    if (f === "rule.eval" || f === "function.eval") return ["result"];
    if (f === "object.get") return ["key", "label", "properties"];
    if (f === "object.search") return ["items"];
    return ["summary"];
  }
  if (st.type === "human_task") return (st.form || []).map((x) => x.name).filter(Boolean);
  if (st.type === "action") return ["status", "result"];
  if (st.type === "foreach") return ["total", "ok"];
  if (st.type === "skill") return ["summary"];
  return [];
}

/** 逐行处理时 $item 有哪些列:数据来自「指标取数」且按维度拆分时,列就是各维度 + value。 */
export function itemColumns(spec: SopSpec, st: SopStep): string[] {
  const src = String(st.items || "").replace(/^\$/, "").split(".")[0];
  const from = spec.steps.find((s) => s.output === src);
  if (from?.type === "function" && from.function === "metric.query") {
    const dims = Array.isArray(from.args?.dimensions) ? from.args!.dimensions.map(String) : [];
    return [...dims, "value"];
  }
  return [];
}

export function upstreamVars(spec: SopSpec, id: string): { name: string; from: string; fields?: string[] }[] {
  const byId = new Map(spec.steps.map((s) => [s.id, s]));
  const preds = new Map<string, string[]>();
  for (const s of spec.steps) for (const e of successors(s)) preds.set(e.to, [...(preds.get(e.to) || []), s.id]);
  const seen = new Set<string>();
  const stack = [...(preds.get(id) || [])];
  const out: { name: string; from: string; fields?: string[] }[] = spec.params.map((p) => ({
    name: p.name, from: `参数:${p.label || p.name}`, fields: p.type === "object" ? ["key", "label"] : undefined }));
  while (stack.length) {
    const cur = stack.pop()!;
    if (seen.has(cur)) continue;
    seen.add(cur);
    const st = byId.get(cur);
    if (st?.output) out.push({ name: st.output, from: `步骤:${st.title}`, fields: outputFields(st) });
    stack.push(...(preds.get(cur) || []));
  }
  const self = byId.get(id);
  if (self?.type === "foreach") {
    const cols = itemColumns(spec, self);
    out.push({ name: "item", from: "当前行", fields: cols.length ? cols : undefined });
  }
  return out;
}

/** 变量 + 字段展开成可直接引用的写法:$shortage、$shortage.value、$item.仓库…… */
export function varPaths(vars: { name: string; fields?: string[] }[]): string[] {
  return vars.flatMap((v) => [`$${v.name}`, ...(v.fields || []).map((f) => `$${v.name}.${f}`)]);
}

/**
 * 自动布局:按从开始步骤的最长路径分层,同层按上层父节点的平均位置排序(减少交叉),
 * 从不到的步骤排在最右边一列。不引第三方布局库,二三十个步骤足够用。
 */
export function autoLayout(spec: SopSpec, gapX = 250, gapY = 130): Record<string, { x: number; y: number }> {
  const byId = new Map(spec.steps.map((s) => [s.id, s]));
  const level = new Map<string, number>();
  if (byId.has(spec.start)) {
    level.set(spec.start, 0);
    // 最长路径分层(流程无环,最多迭代步骤数次)
    for (let round = 0; round < spec.steps.length; round++) {
      let changed = false;
      for (const s of spec.steps) {
        const l = level.get(s.id);
        if (l === undefined) continue;
        for (const e of successors(s)) {
          if (!byId.has(e.to)) continue;
          if ((level.get(e.to) ?? -1) < l + 1) { level.set(e.to, l + 1); changed = true; }
        }
      }
      if (!changed) break;
    }
  }
  const rows = new Map<number, string[]>();
  for (const s of spec.steps) {
    const l = level.get(s.id);
    if (l !== undefined) rows.set(l, [...(rows.get(l) || []), s.id]);
  }
  const pos: Record<string, { x: number; y: number }> = {};
  const order = [...rows.keys()].sort((a, b) => a - b);
  const xOf = new Map<string, number>();
  for (const l of order) {
    const ids = rows.get(l)!;
    if (l > 0) {
      const parentsX = (id: string) => {
        const xs = spec.steps.filter((p) => successors(p).some((e) => e.to === id) && xOf.has(p.id)).map((p) => xOf.get(p.id)!);
        return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0;
      };
      ids.sort((a, b) => parentsX(a) - parentsX(b));
    }
    ids.forEach((id, i) => {
      const x = (i - (ids.length - 1) / 2) * gapX;
      xOf.set(id, x);
      pos[id] = { x, y: l * gapY };
    });
  }
  const orphans = spec.steps.filter((s) => !level.has(s.id));
  const maxX = Math.max(0, ...Object.values(pos).map((p) => p.x));
  orphans.forEach((s, i) => { pos[s.id] = { x: maxX + gapX * 1.3, y: i * gapY }; });
  return pos;
}