RunParts.tsx 23.5 KB
/**
 * 运行相关的界面:运行参数弹窗、运行时间线、运行详情页。
 * 详情页里轮到谁办,就直接在那一步的卡片上办(填任务、批准 / 驳回、重试),不用再去待办里找。
 */
import { ArrowLeft, Ban, Check, ChevronDown, ChevronRight, CircleDashed, Clock, Loader2, Play, RotateCcw, X, XCircle } from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Desc, ObjectPicker, TraceChain, Select } from "@/components/kit";
import { Badge, Card, ErrorNote, Field, Modal, Spinner, type BadgeVariant } from "@/components/ui";
import { fmtAgo, fmtDateTime, fmtDuration } from "@/lib/format";
import { ResultView } from "@/features/ontology/common";
import { errText, onto, type SopParam, type SopRun, type SopStepRun, type TaskRec } from "@/lib/onto";
import { go } from "@/lib/nav";
import { toast } from "@/store/useAppStore";
import { cn } from "@/lib/utils";

export const RUN_STATUS: Record<string, { label: string; variant: BadgeVariant }> = {
  running: { label: "运行中", variant: "info" }, waiting: { label: "等人处理", variant: "warn" },
  cancelling: { label: "取消中", variant: "warn" }, done: { label: "已完成", variant: "ok" },
  failed: { label: "失败", variant: "danger" }, rejected: { label: "被驳回", variant: "danger" },
  cancelled: { label: "已取消", variant: "neutral" }, paused: { label: "已暂停", variant: "neutral" },
};
const STEP_STATUS: Record<string, string> = {
  running: "进行中", done: "完成", failed: "失败", cancelled: "已取消", suggested: "建议",
  waiting_human: "等人处理", waiting_approval: "等审批", waiting_child: "处理中",
};
export const isActive = (s: string) => ["running", "waiting", "cancelling"].includes(s);

export function triggerText(run: { trigger: string; started_by: string; mode?: string }): string {
  const t = run.trigger || "";
  if (run.mode === "dry_run" || t === "dry_run") return "试运行";
  if (t === "ask") return `${run.started_by} 在提问里确认发起`;
  if (t.startsWith("watch")) return `监控与定时触发(以 ${run.started_by} 的名义)`;
  if (t.startsWith("subprocess")) return "被另一张流程卡调起";
  if (t === "playbook") return "提问时按流程诊断";
  return `${run.started_by || "有人"} 手动发起`;
}

const duration = fmtDuration;

/** 一个流程参数的输入框:对象用搜索选择,是否 / 单选 / 日期各用对应的控件。 */
export function ParamInput({ p, value, onChange }: { p: SopParam; value: any; onChange: (v: any) => void }) {
  if (p.type === "list") return <ListParamInput p={p} value={value} onChange={onChange} />;
  if (p.type === "object" && p.object_type) {
    return <ObjectPicker type={p.object_type} value={value} onChange={(k) => onChange(k)} />;
  }
  if (p.type === "period") {
    return (
      <Select className="input h-8" value={value ?? ""} onChange={(e) => onChange(e.target.value)}>
        <option value="">请选择</option><option value="current">本期</option><option value="last">上期</option>
        {Array.from({ length: 6 }, (_, i) => { const d = new Date(); d.setMonth(d.getMonth() - i); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; })
          .map((m) => <option key={m} value={m}>{m}</option>)}
      </Select>
    );
  }
  if (p.type === "boolean") {
    return (
      <Select className="input h-8" value={value === undefined || value === "" ? "" : String(value)}
              onChange={(e) => onChange(e.target.value === "" ? undefined : e.target.value === "true")}>
        <option value="">请选择</option><option value="true">是</option><option value="false">否</option>
      </Select>
    );
  }
  if (p.type === "choice") {
    return (
      <Select className="input h-8" value={value ?? ""} onChange={(e) => onChange(e.target.value)}>
        <option value="">请选择</option>{(p.options || []).map((o) => <option key={o} value={o}>{o}</option>)}
      </Select>
    );
  }
  if (p.type === "date") return <input className="input h-8" type="date" value={value ?? ""} onChange={(e) => onChange(e.target.value)} />;
  if (p.type === "number") return <input className="input h-8" type="number" value={value ?? ""} onChange={(e) => onChange(e.target.value === "" ? "" : Number(e.target.value))} />;
  return <input className="input h-8" value={value ?? ""} onChange={(e) => onChange(e.target.value)} />;
}

/** 多行数据(明细)参数:按定义的列填一张小表。 */
export function ListParamInput({ p, value, onChange }: { p: Pick<SopParam, "columns">; value: any; onChange: (v: any) => void }) {
  const rows: Record<string, any>[] = Array.isArray(value) ? value : [];
  const cols = p.columns || [];
  const set = (i: number, k: string, v: any) => onChange(rows.map((r, j) => (j === i ? { ...r, [k]: v } : r)));
  return (
    <div className="overflow-x-auto rounded-md border border-line">
      <table className="w-full text-label">
        <thead className="bg-ink/[0.03] text-caption text-muted">
          <tr>{cols.map((c) => <th key={c.name} className="whitespace-nowrap px-2 py-1 text-left font-normal">{c.label || c.name}{c.required && <span className="text-bad"> *</span>}</th>)}<th className="w-8" /></tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} className="border-t border-line">
              {cols.map((c) => (
                <td key={c.name} className="min-w-[7rem] px-1 py-1">
                  {c.type === "object" && c.object_type
                    ? <ObjectPicker type={c.object_type} value={r[c.name] ?? ""} onChange={(k) => set(i, c.name, k)} />
                    : <input className="input h-7 w-full" type={c.type === "number" ? "number" : c.type === "date" ? "date" : "text"} value={r[c.name] ?? ""}
                             onChange={(e) => set(i, c.name, c.type === "number" && e.target.value !== "" ? Number(e.target.value) : e.target.value)} />}
                </td>
              ))}
              <td className="px-1"><button className="btn btn-ghost btn-sm px-1" title="删掉这一行" onClick={() => onChange(rows.filter((_, j) => j !== i))}><X className="h-3.5 w-3.5" /></button></td>
            </tr>
          ))}
        </tbody>
      </table>
      <button className="btn btn-ghost btn-sm m-1" onClick={() => onChange([...rows, {}])}>+ 加一行</button>
    </div>
  );
}

/** 运行 / 试运行前填参数。没有参数时调用方可以直接跑,不必弹这个窗。 */
export function RunDialog({ title, params, mode, preset, source, defId, onClose, onDone }: {
  title: string; params: SopParam[]; mode: "live" | "dry_run"; preset?: Record<string, any>;
  /** ask = 提问里 AI 建议的,本人确认后发起 */
  source?: string; defId: string; onClose: () => void; onDone: (run: SopRun) => void;
}) {
  const [vals, setVals] = useState<Record<string, any>>(() => {
    const init: Record<string, any> = {};
    for (const p of params) { const v = preset?.[p.name] ?? p.default; if (v !== undefined && v !== null && v !== "") init[p.name] = v; }
    return init;
  });
  const [busy, setBusy] = useState(false);
  const missing = mode === "live" ? params.filter((p) => p.required && (vals[p.name] === undefined || vals[p.name] === "")) : [];
  const submit = async () => {
    setBusy(true);
    try {
      const run = mode === "dry_run" ? await onto.dryRunSop(defId, vals) : await onto.runSop(defId, vals, source || "");
      onDone(run);
    } catch (e) { toast("error", mode === "dry_run" ? "试运行失败" : "发起失败", errText(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title={mode === "dry_run" ? `试运行「${title}」` : `运行「${title}」`}
           width={params.some((p) => p.type === "list") ? "max-w-2xl" : undefined}
           desc={mode === "dry_run" ? "试运行不会改数据、不发通知" : undefined}
           footer={<><button className="btn" onClick={onClose}>取消</button>
             <button className="btn btn-primary" disabled={busy || missing.length > 0}
                     title={missing.length ? `还没填:${missing.map((p) => p.label).join("、")}` : ""} onClick={submit}>
               {busy ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}
               {mode === "dry_run" ? "开始试运行" : source === "ask" ? "确认并发起" : "运行"}</button></>}>
      <div className="space-y-3">
        {params.length === 0 && <p className="text-label text-muted">这张流程卡不需要参数。</p>}
        {params.map((p) => (
          <Field key={p.name} label={p.label || p.name} required={p.required && mode === "live"} hint={p.description}>
            <ParamInput p={p} value={vals[p.name]} onChange={(v) => setVals((s) => ({ ...s, [p.name]: v }))} />
          </Field>
        ))}
      </div>
    </Modal>
  );
}

function StepIcon({ status }: { status: string }) {
  if (status === "done") return <Check className="h-3.5 w-3.5 text-ok" />;
  if (status === "failed") return <XCircle className="h-3.5 w-3.5 text-bad" />;
  if (status === "cancelled") return <Ban className="h-3.5 w-3.5 text-muted" />;
  if (status === "running") return <Loader2 className="h-3.5 w-3.5 animate-spin text-brand" />;
  if (status.startsWith("waiting")) return <Clock className="h-3.5 w-3.5 text-warn" />;
  return <CircleDashed className="h-3.5 w-3.5 text-muted" />;
}

/** 一步的结果,尽量说人话:取数出表格,任务出填写内容,动作出结果摘要。 */
function StepOutput({ step }: { step: SopStepRun }) {
  const o = step.output;
  if (o == null) return null;
  if (step.step_type === "human_task" && typeof o === "object") {
    const labels: Record<string, string> = Object.fromEntries(((step.task?.form || []) as any[]).map((f) => [f.name, f.label]));
    return (
      <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-label">
        {Object.entries(o).filter(([k]) => !k.startsWith("_")).map(([k, v]) => <div key={k} className="contents"><dt className="text-muted">{labels[k] || k}</dt><dd>{v === true ? "是" : v === false ? "否" : String(v ?? "")}</dd></div>)}
      </dl>
    );
  }
  if (step.step_type === "function" && typeof o === "object" && (Array.isArray(o.rows) || Array.isArray(o.items))) {
    return <ResultView data={{ ...o, summary: undefined }} />;
  }
  if (step.step_type === "function" && typeof o === "object" && o.value !== undefined && o.value !== null) {
    return <p className="text-body"><span className="text-muted">{o.value_label || "结果"}:</span><b className="tabular-nums">{String(o.value)}</b></p>;
  }
  if (step.step_type === "skill" && o?.output) {
    return (
      <div className="text-label">
        <p>{o.output.conclusion}</p>
        {Array.isArray(o.output.points) && <ul className="mt-1 list-disc pl-4 text-muted">{o.output.points.map((x: string, i: number) => <li key={i}>{x}</li>)}</ul>}
      </div>
    );
  }
  return null;
}

/** 在这一步的卡片上直接填任务。 */
function TaskInline({ task, onDone }: { task: TaskRec & { can_handle: boolean }; onDone: () => void }) {
  const [vals, setVals] = useState<Record<string, any>>({});
  const [busy, setBusy] = useState(false);
  if (!task.can_handle) {
    return <p className="text-caption text-muted">等 {task.assignee || task.role} 处理{task.overdue ? "(已超时)" : ""}</p>;
  }
  const missing = task.form.filter((f) => f.required && (vals[f.name] === undefined || vals[f.name] === ""));
  return (
    <div className="mt-2 space-y-2 rounded-md border border-warn/30 bg-warn/5 p-2.5">
      {task.description && <p className="whitespace-pre-wrap text-label">{task.description}</p>}
      {task.form.map((f) => (
        <Field key={f.name} label={f.label} required={f.required}>
          <ParamInput p={{ name: f.name, label: f.label, type: f.type === "text" ? "string" : f.type, object_type: "", calendar: "",
            options: f.options, required: f.required }} value={vals[f.name]} onChange={(v) => setVals((s) => ({ ...s, [f.name]: v }))} />
        </Field>
      ))}
      <button className="btn btn-primary btn-sm" disabled={busy || missing.length > 0}
              title={missing.length ? `还没填:${missing.map((f) => f.label).join("、")}` : ""}
              onClick={async () => {
                setBusy(true);
                try { await onto.completeTask(task.id, vals); toast("ok", "已完成"); onDone(); }
                catch (e) { toast("error", "提交失败", errText(e)); } finally { setBusy(false); }
              }}>{busy && <Spinner className="h-3.5 w-3.5" />}填好了,完成</button>
    </div>
  );
}

function ActionInline({ action, onDone }: { action: NonNullable<SopStepRun["action"]>; onDone: () => void }) {
  const [comment, setComment] = useState("");
  const [busy, setBusy] = useState(false);
  const act = async (fn: () => Promise<unknown>, ok: string) => {
    setBusy(true);
    try { await fn(); toast("ok", ok); onDone(); } catch (e) { toast("error", "操作失败", errText(e)); } finally { setBusy(false); }
  };
  if (action.status === "failed") {
    return (
      <div className="mt-2 flex items-center gap-2 rounded-md border border-bad/30 bg-bad/5 p-2.5">
        <p className="min-w-0 flex-1 text-label text-bad">执行失败:{action.error}</p>
        {action.can_retry && <button className="btn btn-sm" disabled={busy} onClick={() => act(() => onto.retryAction(action.id), "已重试")}><RotateCcw className="h-3.5 w-3.5" />重试</button>}
      </div>
    );
  }
  if (!action.can_decide) {
    return <p className="text-caption text-muted">等审批{action.approver_roles.length ? `(${action.approver_roles.join("、")})` : ""}
      <button className="ml-2 text-brand hover:underline" onClick={() => go("inbox", { run: action.id })}>查看审批单</button></p>;
  }
  return (
    <div className="mt-2 space-y-2 rounded-md border border-warn/30 bg-warn/5 p-2.5">
      <p className="text-label">{action.summary}{action.priority && <Badge className="ml-2" variant="warn">{action.priority}</Badge>}</p>
      <input className="input h-8 w-full" placeholder="审批意见(驳回必须填原因)" value={comment} onChange={(e) => setComment(e.target.value)} />
      <div className="flex gap-2">
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={() => act(() => onto.decideAction(action.id, true, comment), "已批准")}><Check className="h-3.5 w-3.5" />批准</button>
        <button className="btn btn-sm" disabled={busy || !comment.trim()} title={comment.trim() ? "" : "先写驳回原因"}
                onClick={() => act(() => onto.decideAction(action.id, false, comment), "已驳回")}><X className="h-3.5 w-3.5" />驳回</button>
        <button className="btn btn-ghost btn-sm" onClick={() => go("inbox", { run: action.id })}>看完整依据</button>
      </div>
    </div>
  );
}

function RowsBlock({ step, onChanged }: { step: SopStepRun; onChanged: () => void }) {
  const [open, setOpen] = useState<number | null>(null);
  const rows = step.rows || [];
  const o = step.output || {};
  return (
    <div className="mt-2">
      <div className="flex flex-wrap gap-1.5 text-caption">
        {o.ok > 0 && <Badge variant="ok">完成 {o.ok}</Badge>}
        {o.pending > 0 && <Badge variant="warn">处理中 {o.pending}</Badge>}
        {o.rejected > 0 && <Badge variant="danger">被驳回 {o.rejected}</Badge>}
        {o.failed > 0 && <Badge variant="danger">失败 {o.failed}</Badge>}
        {o.cancelled > 0 && <Badge variant="neutral">已取消 {o.cancelled}</Badge>}
      </div>
      {rows.map((r) => {
        const st = RUN_STATUS[r.status] || { label: r.status, variant: "neutral" as BadgeVariant };
        const item = r.params?.item || {};
        const head = item.label ? String(item.label)
          : Object.entries(item).filter(([k]) => k !== "value").slice(0, 3).map(([, v]) => String(v)).join(" · ");
        return (
          <div key={r.id} className="mt-1.5 rounded-md border border-line">
            <button className="flex w-full items-center gap-2 px-2 py-1.5 text-left text-label hover:bg-ink/[0.03]"
                    onClick={() => setOpen(open === r.row_index ? null : r.row_index ?? null)}>
              {open === r.row_index ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
              <span className="text-muted">第 {r.row_index} 条</span>
              <span className="min-w-0 flex-1 truncate">{head}{item.value !== undefined && !item.label ? `(${item.value})` : ""}</span>
              {r.status === "failed" && r.error && <span className="hidden max-w-[50%] truncate text-caption text-bad sm:inline" title={r.error}>{r.error}</span>}
              <Badge variant={st.variant}>{st.label}</Badge>
            </button>
            {open === r.row_index && <div className="border-t border-line p-2"><RunTimeline run={r} onChanged={onChanged} nested /></div>}
          </div>
        );
      })}
    </div>
  );
}

/** 一次运行每一步的情况,从上往下。 */
export function RunTimeline({ run, onChanged, nested }: { run: SopRun; onChanged: () => void; nested?: boolean }) {
  const steps = run.steps || [];
  if (!steps.length) return <p className="text-label text-muted">还没有执行任何步骤。</p>;
  return (
    <ol className={cn("space-y-2", nested && "space-y-1.5")}>
      {steps.map((s) => (
        <li key={s.id} className={cn("rounded-lg border bg-surface px-4 py-3",
          s.status.startsWith("waiting") ? "border-warn/50" : s.status === "failed" ? "border-bad/40" : "border-line")}>
          <div className="flex items-center gap-2">
            <StepIcon status={s.status} />
            <span className="min-w-0 flex-1 truncate text-body font-medium">{s.title}</span>
            <span className="shrink-0 text-caption text-muted">{STEP_STATUS[s.status] || s.status}
              {s.finished_at ? ` · ${duration(s.started_at, s.finished_at)}` : ""}</span>
          </div>
          {/* 取数步骤的说明和结果摘要是同一句话,结果里已经有了就不重复 */}
          {s.note && !(s.status === "done" && s.output && typeof s.output === "object" && s.output.summary === s.note)
            && <p className="mt-1 text-label text-muted">{s.note}</p>}
          {s.error && s.status !== "waiting_approval" && <p className="mt-1 text-label text-bad">{s.error}</p>}
          {s.status === "done" && <div className="mt-1.5"><StepOutput step={s} /></div>}
          {s.action_brief && s.action_brief.summary && (
            <p className="mt-1.5 text-label">
              {s.action_brief.summary}
              <button className="ml-2 text-brand hover:underline" onClick={() => go("inbox", { run: s.action_brief!.id })}>查看审批单</button>
            </p>
          )}
          {s.task && <TaskInline task={s.task} onDone={onChanged} />}
          {s.action && <ActionInline action={s.action} onDone={onChanged} />}
          {s.step_type === "foreach" && (s.rows || []).length > 0 && <RowsBlock step={s} onChanged={onChanged} />}
          {s.child_run_id && s.step_type === "subprocess" && (
            <button className="mt-1 text-caption text-brand hover:underline" onClick={() => go("sop", { run: s.child_run_id })}>查看子流程的运行</button>
          )}
        </li>
      ))}
    </ol>
  );
}



/** 运行详情页。 */
export function RunView({ runId, onBack }: { runId: string; onBack: () => void }) {
  const [run, setRun] = useState<SopRun | null>(null);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const [asking, setAsking] = useState(false);
  const [reason, setReason] = useState("");
  const load = useCallback(() => {
    void onto.sopRun(runId).then((r) => { setRun(r); setErr(""); }).catch((e) => setErr(errText(e)));
  }, [runId]);
  useEffect(() => { setRun(null); load(); }, [load]);
  const active = !!run && isActive(run.status);
  useEffect(() => {
    if (!active) return undefined;
    const h = window.setInterval(load, 3000);
    return () => window.clearInterval(h);
  }, [active, load]);
  if (err) return <ErrorNote onRetry={load}>{err}</ErrorNote>;
  if (!run) return <Card className="p-4"><Spinner /></Card>;
  const st = RUN_STATUS[run.status] || { label: run.status, variant: "neutral" as BadgeVariant };
  const head: ReactNode = (
    <div className="flex flex-wrap items-center gap-2">
      <button className="btn btn-ghost btn-sm" onClick={onBack}><ArrowLeft className="h-4 w-4" />返回</button>
      <h2 className="text-title font-semibold">{run.title}</h2>
      {run.version > 0 && <span className="text-label text-muted">v{run.version}</span>}
      <Badge variant={st.variant}>{st.label}</Badge>
      <span className="flex-1" />
      {run.mode === "live" && !active && (
        <button className="btn btn-sm" disabled={busy} onClick={async () => {
          setBusy(true);
          try {
            const params = Object.fromEntries(Object.entries(run.params || {}).filter(([k]) => !k.startsWith("__")));
            const r = await onto.runSop(run.def_id, params); toast("ok", "已按相同参数重新发起"); go("sop", { run: r.id });
          } catch (e) { toast("error", "发起失败", errText(e)); } finally { setBusy(false); }
        }}><RotateCcw className="h-3.5 w-3.5" />按相同参数再跑一次</button>
      )}
      {active && run.status !== "cancelling" && <button className="btn btn-sm" onClick={() => setAsking(true)}><Ban className="h-3.5 w-3.5" />取消这次运行</button>}
      <button className="btn btn-sm" onClick={() => go("sop", { id: run.def_id })}>打开流程卡</button>
    </div>
  );
  return (
    <div className="flex h-full min-h-0 flex-col gap-3">
      {head}
      <div className="min-h-0 flex-1 overflow-auto">
        <div className="space-y-4">
          <Card className="space-y-4 p-5">
            <Desc cols={4} items={[
              { label: "怎么发起的", value: triggerText({ ...run, started_by: run.started_by_name || run.started_by }) },
              { label: "开始时间", value: <span title={fmtDateTime(run.created_at)}>{fmtAgo(run.created_at)}</span> },
              { label: active ? "已运行" : "用时", value: duration(run.created_at, run.finished_at) || "—" },
              ...(run.params_view || []).map((p) => ({ label: p.label, value: p.object_type && p.raw
                ? <button className="text-left text-brand hover:underline" onClick={() => go("objects", { type: p.object_type, key: String(p.raw) })}>{p.value}</button>
                : (p.value || "—") })),
            ]} />
            {(run.outcome || run.error) && (
              <p className={cn("rounded-md px-3 py-2 text-body", run.status === "done" ? "bg-ok/5 text-ok" : run.status === "cancelled" ? "bg-ink/[0.03] text-muted" : "bg-bad/5 text-bad")}>
                {run.outcome || run.error}
              </p>
            )}
            <TraceChain kind="sop_run" id={run.id} refreshKey={run.status} />
          </Card>
          <RunTimeline run={run} onChanged={load} />
        </div>
      </div>
      <Modal open={asking} onClose={() => setAsking(false)} title="取消这次运行"
             desc="没办的待办和没批的审批单会一起撤掉;已经做完的不会撤回"
             footer={<><button className="btn" onClick={() => setAsking(false)}>不取消了</button>
               <button className="btn btn-danger" disabled={busy || !reason.trim()} onClick={async () => {
                 setBusy(true);
                 try { await onto.cancelSopRun(run.id, reason.trim()); setAsking(false); setReason(""); load(); }
                 catch (e) { toast("error", "取消失败", errText(e)); } finally { setBusy(false); }
               }}>确认取消</button></>}>
        <Field label="为什么取消" required><input className="input h-8" value={reason} onChange={(e) => setReason(e.target.value)} autoFocus /></Field>
      </Modal>
    </div>
  );
}