WorkbenchPage.tsx 10.4 KB
import { ArrowRight, CheckCircle2, ClipboardList, MessageSquareText, Play, Send, ShieldCheck, Sparkles, TrendingDown, TrendingUp } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Spinner } from "@/components/ui";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, PRIORITY_TONE, type Workbench } from "@/lib/onto";
import { toast } from "@/store/useAppStore";

const RUN_STATUS: Record<string, [string, string]> = {
  pending_approval: ["待审批", "bg-warn/10 text-warn"], done: ["已执行", "bg-ok/10 text-ok"],
  rejected: ["已驳回", "bg-bad/10 text-bad"], failed: ["执行失败", "bg-bad/10 text-bad"],
  cancelled: ["已撤回", "bg-ink/5 text-muted"], reverted: ["已撤销", "bg-ink/5 text-muted"],
};

function fmtValue(v: any, unit: string) {
  if (v === null || v === undefined || v === "") return "—";
  const n = Number(v);
  if (Number.isNaN(n)) return String(v);
  const s = Math.abs(n) >= 1000 ? n.toLocaleString("zh-CN", { maximumFractionDigits: 0 })
    : n.toLocaleString("zh-CN", { maximumFractionDigits: 1 });
  return unit === "%" ? `${s}%` : s;
}

/**
 * 工作台:老板和员工每天打开系统的第一页。不讲本体、积木、管道这些搭建期的概念,
 * 只回答「数字怎么样、有什么等我处理、我提交的办得怎样、常用的事一点就做」。
 */
export function WorkbenchPage() {
  const [w, setW] = useState<Workbench | null>(null);
  const [q, setQ] = useState("");
  const [running, setRunning] = useState("");
  const load = useCallback(() => { void onto.workbench().then(setW).catch((e) => toast("error", "加载失败", errText(e))); }, []);
  useEffect(load, [load]);
  if (!w) return <div className="p-8"><Spinner /></div>;

  const askNow = (text: string) => { if (text.trim()) go("ask", { q: text.trim() }); };
  const runSop = async (id: string, title: string) => {
    setRunning(id);
    try {
      const r = await onto.runSop(id, {});
      toast("ok", `已启动「${title}」`, "取数会自动跑完,需要人处理的步骤会出现在待办里");
      go("sop", { id, run: r.id });
    } catch (e) { toast("error", "启动失败", errText(e)); } finally { setRunning(""); }
  };
  const today = new Date().toLocaleDateString("zh-CN", { month: "long", day: "numeric", weekday: "long" });
  const todoCount = w.todo.approvals_total + w.todo.releases.length + w.todo.tasks.length;

  return (
    <div className="mx-auto max-w-6xl space-y-4">
      <Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.08), transparent 60%)" }}>
        <p className="text-[16px] font-semibold">{w.user.name},你好</p>
        <p className="mt-0.5 text-[12.5px] text-muted">
          {today}{w.user.biz_roles.length ? ` · ${w.user.biz_roles.join("、")}` : ""}
          {todoCount ? ` · 有 ${todoCount} 件事等你处理` : " · 暂时没有等你处理的事"}
        </p>
        <div className="mt-3 flex gap-2">
          <div className="relative min-w-0 flex-1">
            <MessageSquareText className="absolute left-2.5 top-2.5 h-4 w-4 text-muted" />
            <input className="input h-10 pl-8 text-[13.5px]" value={q} placeholder="直接问:哪些商品快缺货了?帮我给上海仓补抽纸……"
                   onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") askNow(q); }} />
          </div>
          <button className="btn btn-primary h-10" disabled={!q.trim()} onClick={() => askNow(q)}><Send className="h-4 w-4" />提问</button>
        </div>
        {w.questions.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-1.5">
            {w.questions.map((x) => (
              <button key={x} className="chip hover:border-brand/50 hover:text-brand" onClick={() => askNow(x)}><Sparkles className="h-3 w-3" />{x}</button>
            ))}
          </div>
        )}
      </Card>

      {w.kpis.length > 0 ? (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {w.kpis.map((k) => (
            <button key={k.name} className="card p-3 text-left hover:border-brand/40" title={k.formula}
                    onClick={() => askNow(k.dimensions[0] ? `${k.name}按${k.dimensions[0]}拆开看` : `${k.name}是怎么算出来的?`)}>
              <p className="flex items-center gap-1 text-[12px] text-muted">{k.name}
                {k.direction === "higher_better" && <TrendingUp className="h-3 w-3" />}
                {k.direction === "lower_better" && <TrendingDown className="h-3 w-3" />}</p>
              <p className="mt-1 text-[24px] font-semibold tabular-nums">{fmtValue(k.value, k.unit)}
                {k.unit && k.unit !== "%" && <span className="ml-1 text-[12px] font-normal text-muted">{k.unit}</span>}</p>
              <p className="mt-0.5 truncate text-[11px] text-muted">{k.formula || "点击查看明细"}</p>
            </button>
          ))}
        </div>
      ) : (
        <Card className="p-4 text-[12.5px] text-muted">还没有可展示的指标。实施人员在「业务建模」里发布带取数口径的指标后,这里会显示当天的数字。</Card>
      )}

      <div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
        <Card>
          <CardHeader title={<span className="flex items-center gap-1.5"><ShieldCheck className="h-4 w-4" />等我处理</span>}
                      right={todoCount > 0 && <button className="btn btn-ghost btn-sm" onClick={() => go("inbox")}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} />
          <div className="divide-y divide-line">
            {w.todo.approvals.map((r) => (
              <button key={r.id} className="flex w-full items-start gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]"
                      onClick={() => go("inbox", { tab: "approvals", run: r.id })}>
                <Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge>
                <span className="min-w-0 flex-1">
                  <span className="block text-[13px] font-medium">审批:{r.action_name}</span>
                  <span className="block truncate text-[11.5px] text-muted">{r.summary}</span>
                </span>
                <span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span>
              </button>
            ))}
            {w.todo.releases.map((r) => (
              <button key={r.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "releases" })}>
                <Badge>变更</Badge><span className="min-w-0 flex-1 truncate text-[13px]">{r.title}</span>
              </button>
            ))}
            {w.todo.tasks.map((t) => (
              <button key={t.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "tasks" })}>
                <ClipboardList className="h-4 w-4 text-brand" /><span className="min-w-0 flex-1 truncate text-[13px]">待办:{t.title}</span>
                {t.due_at && <span className="text-[11px] text-muted">截止 {fmtTime(t.due_at)}</span>}
              </button>
            ))}
            {!todoCount && <Empty icon={<CheckCircle2 className="h-8 w-8" />} title="都处理完了" desc="有新的审批和待办会出现在这里" />}
          </div>
        </Card>

        <Card>
          <CardHeader title="我提交的" desc="提交的动作走到哪一步了" />
          <div className="divide-y divide-line">
            {w.mine.map((r) => {
              const [label, tone] = RUN_STATUS[r.status] || [r.status, "bg-ink/5 text-muted"];
              return (
                <button key={r.id} className="flex w-full items-start gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]"
                        onClick={() => go("inbox", { tab: "runs", run: r.id })}>
                  <Badge tone={tone}>{label}</Badge>
                  <span className="min-w-0 flex-1">
                    <span className="block text-[13px] font-medium">{r.action_name}</span>
                    <span className="block truncate text-[11.5px] text-muted">{r.summary}</span>
                  </span>
                  <span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span>
                </button>
              );
            })}
            {!w.mine.length && <Empty title="还没有提交过动作" desc="在提问里让 AI 帮你发起,或在对象页上直接发起" />}
          </div>
        </Card>
      </div>

      <div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
        <Card>
          <CardHeader title="常用流程" desc="一点就跑:取数自动完成,需要人判断的步骤会派到待办" />
          <div className="divide-y divide-line">
            {w.sops.map((s) => (
              <div key={s.id} className="flex items-center gap-2 px-4 py-2.5">
                <span className="min-w-0 flex-1">
                  <span className="block text-[13px] font-medium">{s.title}</span>
                  <span className="block truncate text-[11.5px] text-muted">{s.description}</span>
                </span>
                <span className="text-[11px] text-muted">已运行 {s.run_count} 次</span>
                {w.user.can_run
                  ? <button className="btn btn-sm" disabled={!!running} onClick={() => void runSop(s.id, s.title)}>
                      {running === s.id ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}运行</button>
                  : <button className="btn btn-ghost btn-sm" onClick={() => go("sop", { id: s.id })}>查看</button>}
              </div>
            ))}
            {!w.sops.length && <Empty title="还没有发布的流程" />}
          </div>
        </Card>
        <Card>
          <CardHeader title="最近动态" right={<button className="btn btn-ghost btn-sm" onClick={() => go("audit")}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} />
          <div className="divide-y divide-line">
            {w.feed.map((f, i) => (
              <p key={i} className="flex gap-2 px-4 py-2 text-[12.5px]">
                <span className="w-24 shrink-0 text-[11px] text-muted">{fmtTime(f.ts)}</span>
                <span className="w-16 shrink-0 truncate text-muted">{f.actor}</span>
                <span className="min-w-0 flex-1 truncate">{f.summary}</span>
              </p>
            ))}
            {!w.feed.length && <Empty title="暂无动态" />}
          </div>
        </Card>
      </div>
    </div>
  );
}