InboxPage.tsx
36.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
import { ParamInput } from "@/features/sop/RunParts";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
AlarmClock, Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, Radar, RefreshCw, ShieldCheck, Undo2, User, Workflow,
XCircle,
} from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { useDemoMode } from "@/lib/env";
import { go, useHashParams } from "@/lib/nav";
import {
errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type ActionRun, type InboxCounts, type NotificationRec,
type ReviewItem, type TaskRec,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
import { confirmDialog, promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
import { Desc, TraceChain, Select } from "@/components/kit";
import { PreviewView } from "@/features/actions/ActionParts";
import { fmtAgo, fmtAny } from "@/lib/format";
const PRIORITY_LABEL: Record<string, string> = { P0: "特急", P1: "紧急", P2: "普通", P3: "低" };
type Tab = "approvals" | "tasks" | "reviews" | "runs" | "notifications";
/** 演示模式下收起的页签:AI 草案审核属于搭建期内容,不在对外汇报的主线里。 */
const DEMO_HIDE_TABS: Tab[] = ["reviews"];
export function InboxPage({ onChanged }: { onChanged?: () => void }) {
const params = useHashParams();
const demo = useDemoMode();
const [tab, setTab] = useState<Tab>((params.get("tab") as Tab) || (params.get("task") ? "tasks" : "approvals"));
const [counts, setCounts] = useState<InboxCounts | null>(null);
const refreshCounts = useCallback(() => {
void onto.inbox().then(setCounts).catch(() => undefined);
onChanged?.();
}, [onChanged]);
useEffect(refreshCounts, [refreshCounts, tab]);
useEffect(() => { const t = params.get("tab") as Tab; if (t) setTab(t); }, [params]);
const badge = (n?: number) => (n ? <Badge tone="bg-bad/10 text-bad">{n}</Badge> : undefined);
// 演示模式下若从旧链接带着被收起的页签进来,回落到待审批动作
const cur: Tab = demo && DEMO_HIDE_TABS.includes(tab) ? "approvals" : tab;
const tabs: { key: Tab; label: string; badge?: ReactNode }[] = [
{ key: "approvals", label: "待我审批", badge: badge(counts?.approvals) },
{ key: "tasks", label: "我的待办", badge: badge(counts?.tasks) },
{ key: "runs", label: "全部审批单" },
{ key: "reviews", label: "草案审核", badge: badge(counts?.reviews) },
{ key: "notifications", label: "通知", badge: badge(counts?.notifications) },
];
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<Segmented value={cur} onChange={setTab}
options={tabs.filter((o) => !demo || !DEMO_HIDE_TABS.includes(o.key))} />
{!demo && (counts?.releases || 0) > 0 && (
<button className="chip border-warn/40 text-warn" onClick={() => go("publish")}>
有 {counts?.releases} 份本体变更提案等审批 →
</button>
)}
</div>
{cur === "approvals" && <Approvals focus={params.get("run") || ""} onChanged={refreshCounts} />}
{cur === "tasks" && <Tasks focus={params.get("task") || ""} onChanged={refreshCounts} />}
{cur === "reviews" && <Reviews onChanged={refreshCounts} />}
{cur === "runs" && <Runs focus={params.get("run") || ""} onChanged={refreshCounts} />}
{cur === "notifications" && <Notifications onChanged={refreshCounts} />}
</div>
);
}
// ---------------------------------------------------------------- 审批
const INITIATOR: Record<string, { label: string; icon: React.ReactNode }> = {
ai: { label: "提问里的建议", icon: <Bot className="h-3 w-3" /> },
sop: { label: "流程卡发起", icon: <Workflow className="h-3 w-3" /> },
watch: { label: "监控发起", icon: <AlarmClock className="h-3 w-3" /> },
user: { label: "人工发起", icon: <User className="h-3 w-3" /> },
};
const EVIDENCE_KIND: Record<string, string> = { data: "数据", rule: "规则", doc: "原文", note: "说明", ask: "提问", sop: "流程", watch: "监控" };
export function RunDetail({ run, onDone }: { run: ActionRun; onDone: () => void }) {
const [comment, setComment] = useState("");
const [busy, setBusy] = useState(false);
const decide = async (approve: boolean) => {
setBusy(true);
try {
const r = await onto.decideAction(run.id, approve, comment);
const msg = !approve ? "已驳回" : r.status === "done" ? "已批准并执行" : r.status === "pending_approval" ? "已批准,转下一个审批环节"
: r.status === "failed" ? "已批准,但执行失败" : "已批准";
toast(r.status === "failed" ? "error" : "ok", msg, r.error || undefined);
setComment("");
onDone();
} catch (e) { toast("error", "操作失败", errText(e)); } finally { setBusy(false); }
};
const revert = async () => {
const reason = await promptText("为什么要撤销", { desc: "撤销也要审批,批准后才会恢复原样" });
if (!reason) return;
try { await onto.revertAction(run.id, reason); toast("ok", "撤销申请已提交"); onDone(); }
catch (e) { toast("error", "撤销失败", errText(e)); }
};
const ini = INITIATOR[run.initiator_kind] || INITIATOR.user;
const pv = run.preview;
const params = Object.entries(run.params || {}).filter(([k]) => k !== "obj_key" && pv.param_labels?.[k]);
const evidence = (run.evidence || []).filter((e) => e.kind !== "watch" && e.ref !== "approval.auto" && e.text);
const failed = (run.result?.effects || []).filter((e: any) => !e.ok);
const rejected = run.approvals.find((a) => a.status === "rejected");
const stageNow = pv.stages && pv.stage_index != null ? pv.stages[pv.stage_index] : null;
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center gap-2 text-label text-muted">
<Badge tone={STATUS_TONE[run.status]}>{STATUS_LABEL[run.status] || run.status}</Badge>
<Badge tone={PRIORITY_TONE[run.priority] || PRIORITY_TONE.P2}>{PRIORITY_LABEL[run.priority] || run.priority}</Badge>
{run.kind === "revert" && <Badge variant="warn"><Undo2 className="h-3 w-3" />撤销申请</Badge>}
<span className="inline-flex items-center gap-1">{ini.icon}{ini.label}</span>
<span>{run.submitted_name || run.submitted_by || run.initiator_id}</span>
<span title={fmtTime(run.created_at)}>{fmtAgo(run.created_at)}</span>
</div>
{(pv.target_label || params.length > 0 || run.reason) && (
<Desc cols={2} items={[
...(pv.target_label ? [{ label: "对象", value: (
<button className="text-left text-brand hover:underline" onClick={() => {
const [, type, ...rest] = run.target_ref.split(":");
go("objects", { type, key: rest.join(":") });
}}>{pv.target_label}</button>) }] : []),
...params.map(([k, v]) => ({ label: pv.param_labels?.[k] || k, value: pv.param_values?.[k] ?? (v === true ? "是" : v === false ? "否" : fmtAny(v)) })),
...(run.reason ? [{ label: "备注", value: run.reason, wide: true }] : []),
]} />
)}
{rejected && (
<div className="rounded-lg border border-bad/30 bg-bad/5 px-3 py-2.5 text-body">
<span className="font-medium text-bad">{rejected.decided_name || rejected.decided_by} 驳回:</span>{rejected.comment}
</div>
)}
{run.status === "failed" && (
<div className="rounded-lg border border-bad/30 bg-bad/5 px-3 py-2.5 text-body">
<p className="font-medium text-bad">执行失败</p>
<p className="mt-0.5">{failed[0]?.error || run.error}</p>
</div>
)}
<PreviewView preview={pv} approvals={run.approvals} status={run.status} />
{evidence.length > 0 && (
<div>
<p className="mb-1.5 text-caption text-muted">依据</p>
<ul className="space-y-1">{evidence.map((e, i) => (
<li key={i} className="flex items-start gap-2 text-label">
<span className="mt-0.5 shrink-0 rounded bg-ink/[0.06] px-1.5 py-0.5 text-caption text-muted">{EVIDENCE_KIND[e.kind] || "说明"}</span>
<span className="min-w-0 flex-1 whitespace-pre-wrap break-words">{e.text}</span>
</li>
))}</ul>
</div>
)}
<TraceChain kind="action_run" id={run.id} refreshKey={run.status} />
{run.status === "failed" && run.kind === "normal" && (
<div className="flex items-center justify-end gap-3 border-t border-line pt-4">
<span className="mr-auto text-label text-muted">已经做成的部分不会重复做</span>
<button className="btn" disabled={busy} onClick={async () => {
setBusy(true);
try { const r = await onto.retryAction(run.id); toast(r.status === "done" ? "ok" : "error", r.status === "done" ? "重试成功" : "仍然失败", r.error || undefined); onDone(); }
catch (e) { toast("error", "重试失败", errText(e)); } finally { setBusy(false); }
}}><RefreshCw className="h-3.5 w-3.5" />重试</button>
</div>
)}
{run.status === "pending_approval" && (
run.can_approve === false ? (
<div className="flex flex-wrap items-center gap-3 border-t border-line pt-4">
<p className="min-w-0 flex-1 text-label text-muted">{run.cannot_reason}</p>
{run.can_cancel && (
<button className="btn" disabled={busy} onClick={async () => {
const why = await promptText("撤回这张审批单?", { placeholder: "原因(可以不填)" });
if (why === null) return;
setBusy(true);
try { await onto.cancelAction(run.id, why || "发起人撤回"); toast("ok", "已撤回"); onDone(); }
catch (e) { toast("error", "撤回失败", errText(e)); } finally { setBusy(false); }
}}><Undo2 className="h-3.5 w-3.5" />撤回</button>
)}
</div>
) : (
<div className="space-y-3 border-t border-line pt-4">
<Field label={stageNow ? `审批意见(${stageNow.name})` : "审批意见"} hint="驳回时必须写原因">
<textarea className="input min-h-[64px]" value={comment} onChange={(e) => setComment(e.target.value)} />
</Field>
<div className="flex justify-end gap-2">
<button className="btn" disabled={busy || !comment.trim()} title={comment.trim() ? "" : "先写驳回原因"} onClick={() => void decide(false)}>驳回</button>
<button className="btn btn-primary" disabled={busy} onClick={() => void decide(true)}>
{busy && <Spinner className="h-3.5 w-3.5" />}批准
</button>
</div>
</div>
)
)}
{run.status === "done" && run.kind === "normal" && pv.action.reversible && (
<div className="flex justify-end border-t border-line pt-4">
<button className="btn" onClick={() => void revert()}><Undo2 className="h-3.5 w-3.5" />申请撤销</button>
</div>
)}
</div>
);
}
function RunList({ runs, focus, onDone, empty, batch }: {
runs: ActionRun[]; focus: string; onDone: () => void; empty: string;
/** 待审批列表:可以勾选多张一起批准 */
batch?: boolean;
}) {
const [sel, setSel] = useState<string>(focus);
const [picked, setPicked] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
useEffect(() => { if (focus) setSel(focus); }, [focus]);
useEffect(() => { setPicked((p) => p.filter((id) => runs.some((r) => r.id === id))); }, [runs]);
// 没选的时候默认打开第一张:右边不留一块空白
useEffect(() => { if (runs.length && !runs.some((r) => r.id === sel)) setSel(runs[0].id); }, [runs]); // eslint-disable-line react-hooks/exhaustive-deps
const cur = runs.find((r) => r.id === sel) || null;
if (!runs.length) return <Card><Empty icon={<ShieldCheck className="h-10 w-10" />} title={empty} /></Card>;
const can = (r: ActionRun) => r.status === "pending_approval" && r.can_approve !== false;
const approveAll = async () => {
if (!(await confirmDialog(`批准这 ${picked.length} 张审批单?`, { desc: "批准后立刻执行。紧急的单子建议逐张看过再批。" }))) return;
setBusy(true);
let ok = 0;
const failed: string[] = [];
for (const id of picked) {
try { const r = await onto.decideAction(id, true, "批量批准"); if (r.status === "done") ok += 1; else failed.push(r.error || r.status); }
catch (e) { failed.push(errText(e)); }
}
setBusy(false);
setPicked([]);
toast(failed.length ? "error" : "ok", `批准并执行了 ${ok} 张${failed.length ? `,${failed.length} 张没成功` : ""}`, failed[0]);
onDone();
};
return (
<div className="grid items-start gap-4 lg:grid-cols-[minmax(320px,2fr)_minmax(0,3fr)]">
<Card className="divide-y divide-line overflow-hidden">
{batch && runs.some(can) && (
<div className="flex items-center gap-2 px-3 py-2 text-label">
<label className="flex items-center gap-1.5 text-muted">
<input type="checkbox" checked={picked.length > 0 && picked.length === runs.filter(can).length}
onChange={(e) => setPicked(e.target.checked ? runs.filter(can).map((r) => r.id) : [])} />全选
</label>
<span className="flex-1" />
<button className="btn btn-primary btn-sm" disabled={busy || !picked.length} onClick={() => void approveAll()}>
{busy && <Spinner className="h-3.5 w-3.5" />}{picked.length ? `批准选中的 ${picked.length} 张` : "批准选中的"}
</button>
</div>
)}
{runs.map((r) => (
<button key={r.id} onClick={() => setSel(r.id)}
className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === r.id && "bg-brand/5")}>
<div className="flex items-center gap-2">
{batch && can(r) && (
<input type="checkbox" checked={picked.includes(r.id)} onClick={(e) => e.stopPropagation()}
onChange={(e) => setPicked((p) => (e.target.checked ? [...p, r.id] : p.filter((x) => x !== r.id)))} />
)}
<span className="min-w-0 flex-1 truncate text-body font-medium">{r.action_name}</span>
{["P0", "P1"].includes(r.priority) && <Badge tone={PRIORITY_TONE[r.priority]}>{PRIORITY_LABEL[r.priority]}</Badge>}
<Badge tone={STATUS_TONE[r.status]}>{STATUS_LABEL[r.status] || r.status}</Badge>
</div>
<p className="mt-1 truncate text-label text-muted">{r.preview.target_label || r.preview.summary}</p>
<p className="mt-1 text-caption text-muted">
{r.submitted_name || r.submitted_by || r.initiator_id} · {(INITIATOR[r.initiator_kind] || INITIATOR.user).label} · {fmtAgo(r.created_at)}
</p>
</button>
))}
</Card>
<Card>
{cur ? (
<>
<CardHeader title={cur.action_name} />
<div className="p-5"><RunDetail run={cur} onDone={onDone} /></div>
</>
) : <Empty title="在左边选一张" />}
</Card>
</div>
);
}
function Approvals({ focus, onChanged }: { focus: string; onChanged: () => void }) {
const [runs, setRuns] = useState<ActionRun[] | null>(null);
const load = useCallback(() => { void onto.approvals().then(setRuns).catch((e) => toast("error", errText(e))); }, []);
useEffect(load, [load]);
if (!runs) return <Spinner />;
// 这一页只放轮到我批的;等别人批的在「全部审批单」里看
const mine = runs.filter((r) => r.can_approve !== false || r.id === focus);
return <RunList runs={mine} focus={focus} empty="没有等你审批的" batch
onDone={() => { load(); onChanged(); }} />;
}
function Runs({ focus, onChanged }: { focus: string; onChanged: () => void }) {
const [runs, setRuns] = useState<ActionRun[] | null>(null);
const [status, setStatus] = useState("");
const load = useCallback(() => {
void onto.actionRuns({ status, limit: 200 }).then(async (rs) => {
if (focus && !rs.find((r) => r.id === focus)) {
try { rs = [await onto.actionRun(focus), ...rs]; } catch { /* ignore */ }
}
setRuns(rs);
});
}, [status, focus]);
useEffect(load, [load]);
return (
<div className="space-y-3">
<Select className="input w-40" value={status} onChange={(e) => setStatus(e.target.value)}>
<option value="">全部状态</option>
{["pending_approval", "done", "failed", "rejected", "cancelled", "reverted"].map((s) =>
<option key={s} value={s}>{STATUS_LABEL[s]}</option>)}
</Select>
{runs ? <RunList runs={runs} focus={focus} empty="还没有审批单" onDone={() => { load(); onChanged(); }} /> : <Spinner />}
</div>
);
}
// ---------------------------------------------------------------- 任务
function Tasks({ focus, onChanged }: { focus: string; onChanged: () => void }) {
const [scope, setScope] = useState<"mine" | "all">("mine");
const [status, setStatus] = useState("open");
const [items, setItems] = useState<TaskRec[] | null>(null);
const [sel, setSel] = useState(focus);
const load = useCallback(() => {
void onto.tasks({ scope, status }).then(async (ts) => {
if (focus && !ts.find((t) => t.id === focus)) {
try { ts = [await onto.task(focus), ...ts]; } catch { /* ignore */ }
}
setItems(ts);
});
}, [scope, status, focus]);
useEffect(load, [load]);
const cur = items?.find((t) => t.id === sel) || null;
return (
<div className="space-y-3">
<div className="flex gap-2">
<Segmented value={scope} onChange={setScope} options={[{ key: "mine", label: "派给我的" }, { key: "all", label: "全部" }]} />
<Segmented value={status} onChange={setStatus} options={[
{ key: "open", label: "待办" }, { key: "done", label: "已完成" }, { key: "cancelled", label: "已取消" }]} />
</div>
{!items ? <Spinner /> : !items.length ? (
<Card><Empty icon={<ClipboardList className="h-10 w-10" />} title="没有待办"
/></Card>
) : (
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)]">
<Card className="divide-y divide-line">
{items.map((t) => (
<button key={t.id} onClick={() => setSel(t.id)}
className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === t.id && "bg-brand/5")}>
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-body font-medium">{t.title}</span>
{t.overdue && <Badge tone="bg-bad/10 text-bad">已超时</Badge>}
<Badge tone={STATUS_TONE[t.status]}>{STATUS_LABEL[t.status]}</Badge>
</div>
<p className="mt-0.5 text-caption text-muted">
派给 {t.assignee || `角色「${t.role}」`} · {({ sop: "来自流程卡", watch: "来自监控", action: "来自动作" } as Record<string, string>)[t.source_type] || "手工创建"} · 截止 {fmtTime(t.due_at)}
</p>
</button>
))}
</Card>
<Card>{cur ? <TaskDetail t={cur} onDone={() => { load(); onChanged(); }} /> : <Empty title="选择一项任务" />}</Card>
</div>
)}
</div>
);
}
function TaskDetail({ t, onDone }: { t: TaskRec; onDone: () => void }) {
const [vals, setVals] = useState<Record<string, any>>({});
const [checks, setChecks] = useState<Record<number, boolean>>({});
const [busy, setBusy] = useState(false);
useEffect(() => { setVals({}); setChecks({}); }, [t.id]);
const allChecked = t.checklist.every((_, i) => checks[i]);
const missing = t.form.filter((f) => f.required && (vals[f.name] === undefined || vals[f.name] === ""));
const submit = async () => {
setBusy(true);
try {
await onto.completeTask(t.id, { ...vals, _checklist: t.checklist.filter((_, i) => checks[i]) });
toast("ok", "任务已完成", t.source_type === "sop" ? "流程会自动进入下一步" : undefined);
onDone();
} catch (e) { toast("error", "提交失败", errText(e)); } finally { setBusy(false); }
};
const sopRun = t.context?.sop_run;
return (
<>
<CardHeader title={t.title}
right={<div className="flex gap-1.5">
{t.status === "open" && (
<button className="btn btn-sm" title="把待办内容带到提问页,让 AI 查数、算量、生成动作审批卡"
onClick={() => go("ask", { q: `帮我处理这个待办:${t.title}\n${(t.description || "").slice(0, 1500)}` })}>
让 AI 帮我处理</button>
)}
{sopRun && <button className="btn btn-sm" onClick={() => go("sop", { run: sopRun })}>查看流程 <ExternalLink className="h-3 w-3" /></button>}
</div>} />
<div className="space-y-3 p-4 text-body">
{t.description && (
<div className="prose-sm max-w-none text-label [&_table]:my-1 [&_table]:text-label [&_td]:border [&_td]:border-line [&_td]:px-1.5 [&_th]:border [&_th]:border-line [&_th]:px-1.5">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{t.description}</ReactMarkdown>
</div>
)}
<TraceChain kind="task" id={t.id} />
{t.status === "open" ? (
<>
{t.checklist.length > 0 && (
<div className="space-y-1">
<p className="text-label font-medium text-muted">检查清单</p>
{t.checklist.map((c, i) => (
<label key={i} className="flex items-center gap-2">
<input type="checkbox" checked={!!checks[i]} onChange={(e) => setChecks({ ...checks, [i]: e.target.checked })} />
{c}
</label>
))}
</div>
)}
{t.form.map((f) => (
<Field key={f.name} label={f.label} required={f.required}>
{f.type === "text" || !f.type ? (
<textarea className="input min-h-[60px]" value={vals[f.name] || ""}
onChange={(e) => setVals({ ...vals, [f.name]: e.target.value })} />
) : (
<ParamInput p={{ name: f.name, label: f.label, type: f.type, object_type: (f as any).object_type || "", calendar: "",
options: f.options, required: f.required }} value={vals[f.name]} onChange={(v) => setVals((x) => ({ ...x, [f.name]: v }))} />
)}
</Field>
))}
<div className="flex justify-end gap-2">
{!t.assignee && <button className="btn" onClick={() => void onto.claimTask(t.id).then(onDone)}>认领</button>}
<button className="btn btn-primary" disabled={busy || !allChecked || missing.length > 0} onClick={() => void submit()}
title={!allChecked ? "请先勾完检查清单" : missing.length ? `还没填:${missing.map((f) => f.label).join("、")}` : ""}>
{busy && <Spinner className="h-3.5 w-3.5" />}完成任务
</button>
</div>
</>
) : (
<div>
<p className="text-muted">{STATUS_LABEL[t.status]} · {t.completed_by} · {fmtTime(t.completed_at)}</p>
<dl className="mt-2 space-y-1 rounded bg-ink/5 p-2 text-label">
{Object.entries(t.result || {}).filter(([k]) => !k.startsWith("_")).map(([k, v]) => (
<div key={k} className="flex gap-2">
<dt className="shrink-0 text-muted">{t.form.find((f) => f.name === k)?.label || k}</dt>
<dd className="min-w-0 whitespace-pre-wrap break-words">{typeof v === "boolean" ? (v ? "是" : "否") : typeof v === "object" ? JSON.stringify(v) : String(v ?? "")}</dd>
</div>
))}
</dl>
</div>
)}
</div>
</>
);
}
// ---------------------------------------------------------------- 审核队列
const SOURCE_LABEL: Record<string, string> = {
extract: "文档提议", introspect: "数据源提议", ai: "AI", user: "用户", feedback: "答案反馈", template: "模板",
};
function Reviews({ onChanged }: { onChanged: () => void }) {
const [kind, setKind] = useState("");
const [status, setStatus] = useState("pending");
const [data, setData] = useState<{ total: number; items: ReviewItem[] } | null>(null);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [open, setOpen] = useState<ReviewItem | null>(null);
const load = useCallback(() => {
void onto.reviews({ kind, status, limit: 300 }).then(setData).catch((e) => toast("error", errText(e)));
setPicked(new Set());
}, [kind, status]);
useEffect(load, [load]);
const batch = async (accept: boolean) => {
const comment = accept ? "" : (await promptText("驳回意见") || "");
if (!accept && !comment) return;
const r = await onto.batchReview([...picked], accept, comment);
toast(r.failed.length ? "warn" : "ok", `处理 ${r.ok.length} 条${r.failed.length ? `,失败 ${r.failed.length} 条` : ""}`,
r.failed.slice(0, 3).map((f) => f.error).join(";"));
load(); onChanged();
};
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
<Select className="input w-36" value={kind} onChange={(e) => setKind(e.target.value)}>
<option value="">全部类型</option>
{[["concept_create", "新概念"], ["concept_update", "概念修改"], ["conflict", "知识冲突"], ["sop_publish", "流程卡发布"],
["feedback", "答案反馈"], ["binding", "数据绑定"], ["memory_fact", "经验沉淀"], ["release", "变更提案"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}
</Select>
<Segmented value={status} onChange={setStatus} options={[
{ key: "pending", label: "待处理" }, { key: "accepted", label: "已采纳" }, { key: "rejected", label: "已驳回" }]} />
{status === "pending" && picked.size > 0 && (
<>
<button className="btn btn-primary btn-sm" onClick={() => void batch(true)}>批量采纳 {picked.size}</button>
<button className="btn btn-sm" onClick={() => void batch(false)}>批量驳回</button>
</>
)}
<span className="ml-auto text-label text-muted">共 {data?.total ?? 0} 条</span>
</div>
{!data ? <Spinner /> : !data.items.length ? (
<Card><Empty icon={<GitPullRequest className="h-10 w-10" />} title="没有要审核的草案"
/></Card>
) : (
<Card className="divide-y divide-line">
{status === "pending" && (
<label className="flex items-center gap-2 px-3 py-2 text-label text-muted">
<input type="checkbox" checked={picked.size === data.items.length}
onChange={(e) => setPicked(e.target.checked ? new Set(data.items.map((i) => i.id)) : new Set())} />
全选
</label>
)}
{data.items.map((it) => (
<div key={it.id} className="flex items-center gap-2 px-3 py-2">
{status === "pending" && (
<input type="checkbox" checked={picked.has(it.id)} onChange={(e) => {
const n = new Set(picked); if (e.target.checked) n.add(it.id); else n.delete(it.id); setPicked(n);
}} />
)}
<button className="min-w-0 flex-1 text-left" onClick={() => setOpen(it)}>
<div className="flex items-center gap-2">
<Badge tone={it.kind === "conflict" ? "bg-bad/10 text-bad" : "bg-brand/10 text-brand"}>{it.kind_label}</Badge>
<span className="truncate text-body font-medium">{it.title}</span>
</div>
<p className="mt-0.5 truncate text-label text-muted">
{SOURCE_LABEL[it.source] || it.source}
{it.confidence ? ` · 置信度 ${(it.confidence * 100).toFixed(0)}%` : ""}
{it.payload?.description ? ` · ${it.payload.description}` : ""}
{it.comment ? ` · 意见:${it.comment}` : ""}
</p>
</button>
<span className="text-caption text-muted">{fmtTime(it.created_at)}</span>
</div>
))}
</Card>
)}
{open && <ReviewModal item={open} onClose={() => setOpen(null)} onDone={() => { setOpen(null); load(); onChanged(); }} />}
</div>
);
}
function ReviewModal({ item, onClose, onDone }: { item: ReviewItem; onClose: () => void; onDone: () => void }) {
const [payload, setPayload] = useState<any>(item.payload);
const [comment, setComment] = useState("");
const [busy, setBusy] = useState(false);
const pending = item.status === "pending";
const decide = async (accept: boolean) => {
setBusy(true);
try {
await onto.decideReview(item.id, { accept, comment, payload: accept ? payload : undefined });
toast("ok", accept ? "已采纳" : "已驳回");
onDone();
} catch (e) { toast("error", "处理失败", errText(e)); } finally { setBusy(false); }
};
return (
<Modal open onClose={onClose} title={item.title} desc={`${item.kind_label} · ${SOURCE_LABEL[item.source] || item.source}`}
width="max-w-2xl"
footer={pending ? <>
<input className="input mr-auto h-8 max-w-xs" placeholder="意见(驳回必填)" value={comment} onChange={(e) => setComment(e.target.value)} />
<button className="btn" disabled={busy || !comment.trim()} onClick={() => void decide(false)}>驳回</button>
<button className="btn btn-primary" disabled={busy} onClick={() => void decide(true)}>
{item.kind === "conflict" ? "采用提议的定义" : "采纳"}
</button>
</> : undefined}>
<div className="space-y-3 text-body">
{item.kind === "concept_create" && (
<>
<div className="grid grid-cols-2 gap-3">
<Field label="名称"><input className="input" value={payload.name} disabled={!pending}
onChange={(e) => setPayload({ ...payload, name: e.target.value })} /></Field>
<Field label="类别"><input className="input" value={payload.kind} disabled /></Field>
</div>
<Field label="定义"><textarea className="input min-h-[56px]" value={payload.description || ""} disabled={!pending}
onChange={(e) => setPayload({ ...payload, description: e.target.value })} /></Field>
<Field label="别名(逗号分隔)"><input className="input" value={(payload.synonyms || []).join(",")} disabled={!pending}
onChange={(e) => setPayload({ ...payload, synonyms: e.target.value.split(/[,,、]/).map((s) => s.trim()).filter(Boolean) })} /></Field>
<Field label="结构定义(spec)"><pre className="max-h-40 overflow-auto rounded bg-ink/5 p-2 text-label">{JSON.stringify(payload.spec, null, 2)}</pre></Field>
{payload.bindings?.length > 0 && <p className="text-muted">附带 {payload.bindings.length} 条数据绑定,采纳后一并创建</p>}
<Evidence items={payload.evidence} />
</>
)}
{item.kind === "conflict" && (
<>
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-lg border border-line p-2.5">
<p className="mb-1 text-label font-medium text-muted">当前定义</p>
<p>{payload.current?.description}</p>
<pre className="mt-1 text-label">{JSON.stringify(payload.current?.spec, null, 2)}</pre>
</div>
<div className="rounded-lg border border-warn/40 bg-warn/5 p-2.5">
<p className="mb-1 text-label font-medium text-warn">文档里的新说法</p>
<p>{payload.proposed?.description}</p>
<pre className="mt-1 text-label">{JSON.stringify(payload.proposed?.spec, null, 2)}</pre>
</div>
</div>
<Evidence items={payload.evidence} />
<p className="text-label text-muted">采纳:换成新的说法,发布后生效。驳回:保留现在的。</p>
</>
)}
{item.kind === "concept_update" && <pre className="rounded bg-ink/5 p-2 text-label">{JSON.stringify(payload, null, 2)}</pre>}
{item.kind === "sop_publish" && (
<>
{payload.note && <p>这次改了什么:{payload.note}</p>}
{payload.changes?.length > 0 && (
<div>
<p className="font-medium">相对线上版本的改动</p>
<ul className="mt-1 space-y-0.5">
{payload.changes.map((c: any) => (
<li key={c.id + c.change}>
<Badge variant={c.change === "removed" ? "danger" : c.change === "added" ? "ok" : "info"}>
{c.change === "removed" ? "删除" : c.change === "added" ? "新增" : "修改"}</Badge> {c.title}
</li>
))}
</ul>
</div>
)}
{payload.outline?.length > 0 && (
<div>
<p className="font-medium">发布后的流程</p>
<ol className="mt-1 space-y-0.5 text-label">
{payload.outline.map((o: any, i: number) => (
<li key={i} style={{ paddingLeft: `${(o.depth || 0) * 14}px` }} className={o.kind === "case" ? "text-muted" : ""}>
{o.title}{o.kind_label ? <span className="ml-1.5 text-caption text-muted">{o.kind_label}</span> : null}
</li>
))}
</ol>
</div>
)}
<p className="text-muted">试运行:{payload.dry_run?.ok && payload.dry_run?.hash === payload.hash ? `通过(${fmtTime(payload.dry_run?.at)})` : "这一版没有试运行通过的记录"}</p>
{payload.warnings?.length > 0 && <ul className="list-disc pl-5 text-warn">{payload.warnings.map((w: string) => <li key={w}>{w}</li>)}</ul>}
<button className="btn btn-sm" onClick={() => go("sop", { id: payload.def_id })}>打开流程卡查看 <ExternalLink className="h-3 w-3" /></button>
</>
)}
{item.kind === "feedback" && (
<>
<p><b>问题:</b>{payload.question}</p>
<div className="max-h-40 overflow-auto rounded bg-ink/5 p-2 text-label whitespace-pre-wrap">{payload.answer}</div>
<p><b>用户意见:</b>{payload.comment}</p>
<Field label="正确答案要点(采纳后成为评测用例)">
<textarea className="input min-h-[56px]" value={payload.correction || ""} disabled={!pending}
onChange={(e) => setPayload({ ...payload, correction: e.target.value })} />
</Field>
</>
)}
{!pending && <p className="text-muted">{STATUS_LABEL[item.status]} · {item.decided_by} · {fmtTime(item.decided_at)} {item.comment}</p>}
</div>
</Modal>
);
}
function Evidence({ items }: { items?: any[] }) {
if (!items?.length) return null;
return (
<div>
<p className="mb-1 text-label font-medium text-muted">文档出处</p>
<ul className="space-y-1">
{items.slice(0, 5).map((e: any, i: number) => (
<li key={i} className="rounded bg-ink/[0.03] p-2 text-label"><b>{e.heading || e.chunk_id}</b> {e.snippet}</li>
))}
</ul>
</div>
);
}
// ---------------------------------------------------------------- 通知
function Notifications({ onChanged }: { onChanged: () => void }) {
const [items, setItems] = useState<NotificationRec[]>([]);
const load = useCallback(() => { void onto.notifications().then((r) => setItems(r.items)); }, []);
useEffect(load, [load]);
return (
<Card>
<CardHeader title="通知" right={<button className="btn btn-sm" onClick={() => void onto.readNotifications().then(() => { load(); onChanged(); })}>全部已读</button>} />
{!items.length ? <Empty icon={<Bell className="h-10 w-10" />} title="没有通知" /> : (
<div className="divide-y divide-line">
{items.map((n) => (
<button key={n.id} className="block w-full px-4 py-2.5 text-left hover:bg-ink/[0.03]"
onClick={() => {
void onto.readNotifications([n.id]).then(onChanged);
if (n.link) window.location.hash = n.link.replace(/^#/, "#");
}}>
<div className="flex items-center gap-2">
{!n.read && <i className="h-2 w-2 rounded-full bg-brand" />}
<span className={cn("text-body", !n.read && "font-medium")}>{n.title}</span>
<span className="ml-auto text-caption text-muted">{fmtTime(n.created_at)}</span>
</div>
{n.body && <p className="mt-0.5 truncate text-label text-muted">{n.body}</p>}
</button>
))}
</div>
)}
</Card>
);
}