WatchPage.tsx
51.8 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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
import {
ArrowLeft, BellOff, CheckCircle2, ChevronRight, Play, Plus, RefreshCw, Trash2, TriangleAlert, Zap,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Ago, Desc, FormSection, ResultGrid, Tabs, TraceItem, Value, Select } from "@/components/kit";
import { fmtDuration } from "@/lib/format";
import { Badge, Card, Empty, Field, ListState, Segmented, Spinner } from "@/components/ui";
import { ConditionEditor } from "@/features/sop/canvas/ConditionEditor";
import { ScopeCtx } from "@/features/sop/canvas/data";
import { confirmDialog } from "@/lib/dialog";
import { go, useHashParams } from "@/lib/nav";
import {
errText, fmtTime, onto,
type AlertEvent, type AlertStats, type CapDef, type ConceptBrief, type Me, type SopBrief, type SopDef, type WatchDef,
type WatchDetector, type WatchField, type WatchMeta, type WatchRunRec, type WatchScanResult,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast, loadFailed } from "@/store/useAppStore";
import { actionParamSchema, SchemaForm, sopParamSchema } from "../ontology/common";
import { RefMulti, RefSelect } from "../ontology/RefSelect";
const BLANK = {
title: "", description: "", enabled: true, owner_role: "",
schedule: { kind: "daily" as const, at: "08:00", weekday: 1, day: 1, every_minutes: 60, cron: "*/30 * * * *" },
trigger: { kind: "schedule" as const, properties: [] as string[] },
source: { kind: "metric" as const, metric: "", dimensions: [] as string[], time: "", object_type: "", set: "", sop: "" },
detectors: [] as WatchDetector[],
condition: "value > 0",
severity: { mode: "fixed" as const, level: "中", rules: [] as { when: string; level: string }[] },
strategies: [] as any[],
dedup: { key: "$key", cooldown_hours: 24 },
recovery: { mode: "auto" as const, reopen_days: 7 },
};
const SEV_TONE: Record<string, "danger" | "warn" | "info"> = { 高: "danger", 中: "warn", 低: "info" };
/**
* 监控与定时(预警规则):看什么 → 怎么算异常(检测量 + 条件)→ 多严重 → 什么时候看 → 命中了做什么 → 怎样算恢复。
* 每一次命中开一条预警事件,事件从「新发现」走到「已恢复 / 已忽略」,效果统计在预警页和系统对象「预警事件」上。
*/
export function WatchPage({ me }: { me: Me | null }) {
const params = useHashParams();
const canEdit = !!me?.permissions.includes("build");
const [list, setList] = useState<WatchDef[] | null>(null);
const [err, setErr] = useState("");
const [meta, setMeta] = useState<WatchMeta | null>(null);
const [typeNames, setTypeNames] = useState<Record<string, string>>({});
const [sel, setSel] = useState(params.get("id") || "");
const [creating, setCreating] = useState(false);
const [firing, setFiring] = useState<Record<string, number>>({});
const narrow = !!(sel || creating);
const toggle = async (w: WatchDef) => {
try { await onto.setWatchEnabled(w.id, !w.enabled); load(); } catch (e) { toast("error", "操作失败", errText(e)); }
};
const load = useCallback(() => {
setErr("");
void onto.watches().then(setList).catch((e) => { setErr(errText(e)); setList([]); });
}, []);
useEffect(() => {
load();
void onto.watchAlerts("open").then((a) => {
const n: Record<string, number> = {};
for (const x of a) n[x.watch_id] = (n[x.watch_id] || 0) + 1;
setFiring(n);
}).catch(() => undefined);
void onto.watchMeta().then(setMeta).catch(() => undefined);
void onto.concepts({ kind: "object_type" })
.then((xs) => setTypeNames(Object.fromEntries(xs.map((x) => [x.id, x.name])))).catch(() => undefined);
}, [load]);
useEffect(() => { setSel(params.get("id") || ""); }, [params]);
const open = (id: string) => { setCreating(false); go("watch", id ? { id } : {}); };
if (narrow && meta) {
return <WatchEditor key={sel || "new"} id={sel} meta={meta} canEdit={canEdit}
onClose={() => { setCreating(false); go("watch"); load(); }}
onSaved={(id) => { setCreating(false); load(); go("watch", id ? { id } : {}); }} />;
}
return (
<div className="flex h-full min-h-0 flex-col gap-3">
<div className="flex items-center gap-2">
<button className="btn btn-sm" onClick={() => go("alerts")}><TriangleAlert className="h-3.5 w-3.5" />看当前的预警</button>
<span className="flex-1" />
<button className="btn btn-ghost btn-sm" onClick={load} aria-label="刷新"><RefreshCw className="h-3.5 w-3.5" /></button>
{canEdit && (
<button className="btn btn-primary" onClick={() => { setCreating(true); go("watch"); }}>
<Plus className="h-4 w-4" />新建监控
</button>
)}
</div>
<Card className="min-h-0 flex-1 overflow-auto">
<ListState loading={list === null} error={err} onRetry={load} empty={!!list && !list.length}
emptyTitle="还没有监控"
emptyAction={canEdit && <button className="btn btn-primary" onClick={() => setCreating(true)}>新建监控</button>}>
<table className="tbl">
<thead>
<tr><th>名称</th><th>盯什么</th><th>多久看一次</th><th className="w-32">下次</th><th className="w-40">最近一次</th>
<th className="w-28">当前命中</th><th className="w-20">启用</th></tr>
</thead>
<tbody>
{(list || []).map((w) => (
<tr key={w.id} className="row-link" tabIndex={0} onClick={() => open(w.id)}
onKeyDown={(e) => { if (e.key === "Enter") open(w.id); }}>
<td>
<p className="font-medium">{w.title}</p>
{w.description && <p className="mt-0.5 line-clamp-1 max-w-md text-label text-muted">{w.description}</p>}
</td>
<td className="text-label">{sourceText(w, typeNames)}</td>
<td className="whitespace-nowrap text-label text-muted">{w.trigger?.kind === "change" ? "对象一变就看" : w.schedule_text}</td>
<td className="whitespace-nowrap text-label text-muted">{w.enabled && w.next_fire_at ? <Ago at={w.next_fire_at} /> : "—"}</td>
<td className="whitespace-nowrap text-label">{lastText(w)}</td>
<td>{firing[w.id] ? <button className="hover:underline" onClick={(e) => { e.stopPropagation(); go("alerts", { watch: w.id }); }}>
<Badge variant="warn">{firing[w.id]} 条</Badge></button> : <span className="text-label text-muted">—</span>}</td>
<td onClick={(e) => e.stopPropagation()}>
<button role="switch" aria-checked={w.enabled} disabled={!canEdit} onClick={() => void toggle(w)}
className={cn("relative h-5 w-9 rounded-full transition-colors", w.enabled ? "bg-brand" : "bg-ink/15")}>
<span className={cn("absolute top-0.5 h-4 w-4 rounded-full bg-white shadow transition-all", w.enabled ? "left-[18px]" : "left-0.5")} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</ListState>
</Card>
</div>
);
}
function sourceText(w: WatchDef, names: Record<string, string> = {}) {
const s = w.source;
if (s.kind === "metric") return `指标「${s.metric}」${s.dimensions?.length ? `,按${s.dimensions.join("、")}` : ""}`;
if (s.kind === "object") return `每一个「${names[s.object_type || ""] || s.object_type}」`;
if (s.kind === "object_set") return `对象集「${s.set}」里的每一个`;
return "到点跑流程卡";
}
function lastText(w: WatchDef) {
if (!w.last_fired_at) return <span className="text-muted">还没跑过</span>;
if (w.last_status === "error") {
return <span className="text-bad" title={w.last_error}><Ago at={w.last_fired_at} /> 失败</span>;
}
return <span className="text-muted"><Ago at={w.last_fired_at} /> 正常</span>;
}
// ---------------------------------------------------------------- 编辑器
function WatchEditor({ id, meta, canEdit, onClose, onSaved }: {
id: string; meta: WatchMeta; canEdit: boolean; onClose: () => void; onSaved: (id: string) => void;
}) {
const [d, setD] = useState<any>(id ? null : { ...BLANK });
const [tab, setTab] = useState<"edit" | "runs">("edit");
const [busy, setBusy] = useState("");
const [scan, setScan] = useState<WatchScanResult | null>(null);
const [preview, setPreview] = useState<{ ok: boolean; error?: string; text: string; next: string[] } | null>(null);
const [objects, setObjects] = useState<ConceptBrief[]>([]);
const [actions, setActions] = useState<CapDef[]>([]);
const [sops, setSops] = useState<SopBrief[]>([]);
const [fns, setFns] = useState<ConceptBrief[]>([]);
const [runs, setRuns] = useState<WatchRunRec[] | null>(null);
const [rowFields, setRowFields] = useState<WatchField[]>([]);
useEffect(() => {
if (id) void onto.watch(id).then(setD).catch((e) => toast("error", errText(e)));
void onto.concepts({ kind: "object_type", status: "published" }).then(setObjects).catch(() => undefined);
// 动作带上 spec:命中后提议动作时,参数按动作的定义生成表单(以前是一个手写 JSON 的输入框,还打不进字)
void onto.capDefs("action", true).then(setActions).catch(() => undefined);
void onto.sops({ status: "published" }).then(setSops).catch(() => undefined);
void onto.concepts({ kind: "function", status: "published" }).then(setFns).catch(() => undefined);
}, [id]);
// 排程一改就告诉人「下五次分别什么时候跑」—— 比让人脑补 cron 靠谱得多
useEffect(() => {
if (!d?.schedule) return;
const h = window.setTimeout(() => {
void onto.previewSchedule(d.schedule).then(setPreview).catch(() => setPreview(null));
}, 250);
return () => window.clearTimeout(h);
}, [d?.schedule]);
useEffect(() => {
if (tab === "runs" && id) void onto.watchRuns(id).then(setRuns).catch((e) => { setRuns([]); loadFailed(e); });
}, [tab, id]);
const srcKey = d ? JSON.stringify([d.source.kind, d.source.metric, d.source.object_type, d.source.set, d.source.dimensions,
(d.detectors || []).map((x: WatchDetector) => [x.name, x.fn, x.field])]) : "";
useEffect(() => {
if (!d || d.source.kind === "sop") { setRowFields([]); return; }
const h = window.setTimeout(() => {
void onto.watchFields(d.source, (d.detectors || []).filter((x: WatchDetector) => x.fn && x.name))
.then(setRowFields).catch(() => setRowFields([]));
}, 300);
return () => window.clearTimeout(h);
}, [srcKey]); // eslint-disable-line react-hooks/exhaustive-deps
if (!d) return <div className="grid h-full place-items-center"><Spinner /></div>;
const set = (k: string, v: any) => setD({ ...d, [k]: v });
const setSched = (patch: any) => setD({ ...d, schedule: { ...d.schedule, ...patch } });
const setSource = (patch: any) => setD({ ...d, source: { ...d.source, ...patch } });
const save = async () => {
setBusy("save");
try {
const saved = id ? await onto.saveWatch(id, d) : await onto.createWatch(d);
toast("ok", id ? "已保存" : "已创建", `下次执行:${saved.next_fire_at ? fmtTime(saved.next_fire_at) : "已停用"}`);
onSaved(saved.id);
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(""); }
};
const doScan = async (dry: boolean) => {
if (!id) { toast("warn", "先保存,再试扫描"); return; }
setBusy(dry ? "scan" : "run");
try {
const r = await onto.scanWatch(id, dry);
setScan(r);
if (!dry) toast("ok", `触发了 ${r.fired.filter((f) => f.ok).length} 条`, `命中 ${r.hit_count},抑制 ${r.suppressed}`);
} catch (e) { toast("error", "扫描失败", errText(e)); } finally { setBusy(""); }
};
return (
<div className="flex h-full flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<button className="btn btn-ghost btn-sm -ml-2" onClick={onClose}><ArrowLeft className="h-4 w-4" />监控</button>
<h2 className="min-w-0 flex-1 truncate text-section font-semibold">{d.title || "新建监控"}</h2>
<label className="flex items-center gap-2 text-label">
<button role="switch" aria-checked={d.enabled} disabled={!canEdit} onClick={() => set("enabled", !d.enabled)}
className={cn("relative h-5 w-9 rounded-full transition-colors", d.enabled ? "bg-brand" : "bg-ink/15")}>
<span className={cn("absolute top-0.5 h-4 w-4 rounded-full bg-white shadow transition-all", d.enabled ? "left-[18px]" : "left-0.5")} />
</button>{d.enabled ? "已启用" : "已停用"}
</label>
</div>
{id && <Tabs<"edit" | "runs"> value={tab} onChange={setTab} options={[{ key: "edit", label: "设置" }, { key: "runs", label: "运行记录" }]} />}
<Card className="flex min-h-0 flex-1 flex-col overflow-hidden">
{tab === "runs" ? <RunsView runs={runs} /> : (
<div className="min-h-0 flex-1 space-y-6 overflow-auto p-6">
<FormSection title="基本信息">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="名称" required><input className="input" value={d.title} disabled={!canEdit} onChange={(e) => set("title", e.target.value)} /></Field>
<Field label="负责角色"><RefSelect refKind="role" value={d.owner_role || ""} disabled={!canEdit} allowCustom={false}
placeholder="不指定" onChange={(v) => set("owner_role", String(v || ""))} /></Field>
</div>
<Field label="说明"><input className="input" value={d.description || ""} disabled={!canEdit} onChange={(e) => set("description", e.target.value)} /></Field>
</FormSection>
<FormSection title="盯什么">
<Segmented value={d.source.kind}
onChange={(k) => setD({ ...d, source: { ...d.source, kind: k, cond: null }, condition: "" })}
options={meta.source_kinds.map((s) => ({ key: s.key, label: s.label }))} />
{d.source.kind === "metric" && (
<div className="grid gap-4 sm:grid-cols-2">
<Field label="指标" required>
<RefSelect refKind="metric" value={d.source.metric} disabled={!canEdit} allowCustom={false}
onChange={(v) => setSource({ metric: String(v || ""), dimensions: [], cond: null })} />
</Field>
<Field label="按什么拆开" hint="不选就只看总数">
<RefMulti refKind="dimension:metric" of={d.source.metric} value={d.source.dimensions || []} disabled={!canEdit}
onChange={(v) => setSource({ dimensions: v })} />
</Field>
</div>
)}
{d.source.kind === "object_set" && (
<Field label="哪个对象集" required className="sm:max-w-sm">
<Select className="input" value={d.source.set || ""} disabled={!canEdit}
onChange={(e) => setSource({ set: e.target.value, cond: null })}>
<option value="">选择</option>
{fns.filter((x) => x.category === "object_set").map((o) => <option key={o.id} value={o.name}>{o.name}</option>)}
</Select>
</Field>
)}
{d.source.kind === "object" && (
<Field label="哪一类对象" required className="sm:max-w-sm">
<Select className="input" value={d.source.object_type} disabled={!canEdit}
onChange={(e) => setSource({ object_type: e.target.value, cond: null })}>
<option value="">选择</option>
{objects.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
</Select>
</Field>
)}
{d.source.kind === "sop" && (
<Field label="流程卡" required className="sm:max-w-sm">
<Select className={cn("input", d.source.sop && !sops.some((x) => x.id === d.source.sop) && "border-bad")} value={d.source.sop} disabled={!canEdit}
onChange={(e) => setSource({ sop: e.target.value })}>
<option value="">请选择</option>
{sops.map((x) => <option key={x.id} value={x.id}>{x.title}</option>)}
</Select>
{d.source.sop && !sops.some((x) => x.id === d.source.sop) && <p className="hint text-bad">原来选的流程卡已经归档或删除,请重新选一张</p>}
</Field>
)}
{d.source.kind !== "sop" && (
<Field label="检测量" hint="先算好再判断:变化率、偏离近 N 期均值几倍、连涨几期、状态变没变、多少天没动……算出来的值在条件里直接用名字">
<DetectorList value={d.detectors || []} meta={meta} fields={rowFields} canEdit={canEdit}
onChange={(v) => set("detectors", v)} />
</Field>
)}
{d.source.kind !== "sop" && (
<Field label="满足什么条件算命中" required>
{d.source.cond || !d.condition ? (
<ScopeCtx.Provider value={{ meta: null, outputs: [{ id: "row", var: "item", title: "命中的这一行", kind: "item", scope: "",
schema: { type: "object", fields: rowFields.map((f) => ({ name: f.path, label: f.label, type: f.type === "number" ? "number" : "string", options: f.enum })) } }] }}>
<ConditionEditor value={(d.source.cond as any) || null} disabled={!canEdit}
emptyHint="还没有条件" onChange={(v) => {
if (v && "expr" in v) setD({ ...d, source: { ...d.source, cond: null }, condition: v.expr || " " });
else setSource({ cond: v as any });
}} />
</ScopeCtx.Provider>
) : (
<div className="space-y-1">
<input className="input font-mono" value={d.condition} disabled={!canEdit} onChange={(e) => set("condition", e.target.value)} />
{canEdit && <button className="text-caption text-brand hover:underline" onClick={() => setD({ ...d, condition: "", source: { ...d.source, cond: null } })}>改用点选的方式</button>}
</div>
)}
</Field>
)}
</FormSection>
{d.source.kind !== "sop" && (
<FormSection title="多严重">
<SeverityEditor value={d.severity || { mode: "fixed", level: "中" }} meta={meta} canEdit={canEdit}
decisions={fns.filter((x) => x.category === "decision")} onChange={(v) => set("severity", v)} />
</FormSection>
)}
{(d.source.kind === "object" || d.source.kind === "object_set") && (
<FormSection title="什么时候看">
<Segmented value={d.trigger?.kind || "schedule"} onChange={(k) => set("trigger", { ...(d.trigger || {}), kind: k })}
options={meta.trigger_kinds.map((s) => ({ key: s.key, label: s.label }))} />
{d.trigger?.kind === "change" && (
<Field label="只看这几个属性的变化" hint="不选 = 任何属性变了都看;动作写入、数据同步发现变化后马上判,不用等排程">
<div className="flex flex-wrap gap-1.5">
{rowFields.filter((f) => !f.detector && !["key", "label"].includes(f.path)).map((f) => {
const on = (d.trigger.properties || []).includes(f.path);
return <button key={f.path} disabled={!canEdit} onClick={() => set("trigger", { ...d.trigger,
properties: on ? d.trigger.properties.filter((x: string) => x !== f.path) : [...(d.trigger.properties || []), f.path] })}
className={cn("rounded-full border px-2.5 py-0.5 text-label", on ? "border-brand bg-brand/10 text-brand" : "border-line")}>{f.label}</button>;
})}
</div>
</Field>
)}
</FormSection>
)}
<FormSection title={d.trigger?.kind === "change" ? "另外再定时全量看一次" : "多久看一次"}>
<Segmented value={d.schedule.kind}
onChange={(k) => setSched({ kind: k })}
options={meta.schedule_kinds.map((s) => ({ key: s.key, label: s.label }))} />
<div className="flex flex-wrap items-start gap-4">
{d.schedule.kind === "interval" && (
<Field label="每隔多少分钟"><input className="input w-32" type="number" min={1}
value={d.schedule.every_minutes} disabled={!canEdit}
onChange={(e) => setSched({ every_minutes: Number(e.target.value) })} /></Field>
)}
{d.schedule.kind === "cron" && (
<Field label="cron 表达式" hint="分 时 日 月 周" className="min-w-[240px] flex-1">
<input className="input font-mono" value={d.schedule.cron} disabled={!canEdit}
onChange={(e) => setSched({ cron: e.target.value })} /></Field>
)}
{["daily", "weekly", "monthly"].includes(d.schedule.kind) && (
<Field label="时刻"><input className="input w-28" value={d.schedule.at} disabled={!canEdit}
onChange={(e) => setSched({ at: e.target.value })} /></Field>
)}
{d.schedule.kind === "weekly" && (
<Field label="周几"><Select className="input w-28" value={d.schedule.weekday} disabled={!canEdit}
onChange={(e) => setSched({ weekday: Number(e.target.value) })}>
{[1, 2, 3, 4, 5, 6, 7].map((n) => <option key={n} value={n}>{"周" + "一二三四五六日"[n - 1]}</option>)}
</Select></Field>
)}
{d.schedule.kind === "monthly" && (
<Field label="几号" hint="1 到 28">
<input className="input w-24" type="number" min={1} max={28} value={d.schedule.day}
disabled={!canEdit} onChange={(e) => setSched({ day: Number(e.target.value) })} /></Field>
)}
{d.schedule.kind !== "interval" && (
<Field label="时区">
<Select className="input w-44" value={d.schedule.tz || "Asia/Shanghai"} disabled={!canEdit}
onChange={(e) => setSched({ tz: e.target.value })}>
{[["Asia/Shanghai", "北京时间"], ["Asia/Tokyo", "东京"], ["Asia/Singapore", "新加坡"], ["Europe/London", "伦敦"],
["Europe/Berlin", "柏林"], ["America/New_York", "纽约"], ["America/Los_Angeles", "洛杉矶"], ["UTC", "UTC"]]
.map(([k, v]) => <option key={k} value={k}>{v}({k})</option>)}
{d.schedule.tz && !["Asia/Shanghai", "Asia/Tokyo", "Asia/Singapore", "Europe/London", "Europe/Berlin", "America/New_York", "America/Los_Angeles", "UTC"].includes(d.schedule.tz)
&& <option value={d.schedule.tz}>{d.schedule.tz}</option>}
</Select></Field>
)}
<Field label="停机错过了" hint="系统恢复后怎么办">
<Select className="input w-32" value={d.schedule.misfire || "skip"} disabled={!canEdit}
onChange={(e) => setSched({ misfire: e.target.value })}>
<option value="skip">跳过</option><option value="run_once">补跑一次</option>
</Select></Field>
</div>
{preview && (
<p className={cn("hint", !preview.ok && "text-bad")}>
{preview.ok ? `${preview.text}。接下来三次:${preview.next.slice(0, 3).join("、")}` : preview.error}
</p>
)}
</FormSection>
<FormSection title={d.source.kind === "sop" ? "到点做什么" : "命中后做什么"}>
<StrategyList value={d.strategies} onChange={(v) => set("strategies", v)} canEdit={canEdit}
meta={meta} actions={actions} sops={sops}
rowVars={d.source.kind === "metric"
? ["$key", "$value", ...(d.source.dimensions || []).map((x: string) => `$${x}`)]
: d.source.kind === "object" ? ["$key", "$label", ...Object.keys(scan?.hits?.[0] || {})
.filter((k) => !["key", "label", "value"].includes(k)).map((k) => `$${k}`)] : []} />
{d.source.kind !== "sop" && (
<Field label="同一条多久内不重复提醒" hint="一直命中的那一条,过了这么久才会再提醒一次;恢复后再命中会立刻提醒" className="sm:max-w-xs">
<div className="flex items-center gap-2">
<input className="input w-24" type="number" min={0} value={d.dedup.cooldown_hours} disabled={!canEdit}
onChange={(e) => set("dedup", { ...d.dedup, cooldown_hours: Number(e.target.value) })} />
<span className="text-label text-muted">小时</span>
</div>
</Field>
)}
</FormSection>
{d.source.kind !== "sop" && (
<FormSection title="怎样算恢复">
<div className="flex flex-wrap items-start gap-4">
<Field label="恢复方式">
<Segmented value={d.recovery?.mode || "auto"} onChange={(k) => set("recovery", { ...(d.recovery || {}), mode: k })}
options={[{ key: "auto", label: "条件不成立就自动恢复" }, { key: "manual", label: "要人确认恢复" }]} />
</Field>
<Field label="恢复后几天内再命中算复发" hint="0 = 不算复发">
<input className="input w-24" type="number" min={0} max={365} value={d.recovery?.reopen_days ?? 7} disabled={!canEdit}
onChange={(e) => set("recovery", { ...(d.recovery || {}), reopen_days: Number(e.target.value) })} />
</Field>
</div>
</FormSection>
)}
{scan && <ScanResult r={scan} fields={rowFields} />}
</div>
)}
{canEdit && tab === "edit" && (
<div className="flex flex-wrap items-center gap-2 border-t border-line bg-elevated px-6 py-3">
<button className="btn btn-primary" disabled={!!busy} onClick={() => void save()}>
{busy === "save" && <Spinner className="h-3.5 w-3.5" />}{id ? "保存" : "创建"}
</button>
{id && <>
<button className="btn" disabled={!!busy} title="只看现在会命中哪些,不做任何事" onClick={() => void doScan(true)}>
{busy === "scan" ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}看看现在会命中哪些
</button>
<button className="btn" disabled={!!busy} onClick={async () => {
if (!(await confirmDialog("现在就跑一次?", {
desc: "命中的会真的触发:提交审批、启动流程卡、派待办或发通知。", danger: true }))) return;
void doScan(false);
}}><Zap className="h-3.5 w-3.5" />现在跑一次</button>
<button className="btn btn-ghost ml-auto text-bad" onClick={async () => {
if (!(await confirmDialog(`删除监控「${d.title}」?`, { danger: true }))) return;
try { await onto.deleteWatch(id); toast("ok", "已删除"); onClose(); onSaved(""); }
catch (e) { toast("error", errText(e)); }
}}><Trash2 className="h-3.5 w-3.5" />删除</button>
</>}
</div>
)}
</Card>
</div>
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function Step({ n, title, desc, children }: { n: number; title: string; desc: string; children: React.ReactNode }) {
return (
<section>
<div className="mb-2 flex items-baseline gap-2">
<span className="grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand/10 text-caption font-semibold text-brand">{n}</span>
<h3 className="text-title font-semibold">{title}</h3>
<span className="text-caption text-muted">{desc}</span>
</div>
<div className="rounded-xl border border-line p-3">{children}</div>
</section>
);
}
/** 检测量:给每一行先算好「变化率 / 偏离倍数 / 连涨期数……」,条件里直接用名字。 */
function DetectorList({ value, onChange, meta, fields, canEdit }: {
value: WatchDetector[]; onChange: (v: WatchDetector[]) => void; meta: WatchMeta; fields: WatchField[]; canEdit: boolean;
}) {
const up = (i: number, patch: Partial<WatchDetector>) => onChange(value.map((x, j) => (j === i ? { ...x, ...patch } : x)));
const base = fields.filter((f) => !f.detector && !["key", "label"].includes(f.path));
const desc = (fn: string) => meta.detectors.find((x) => x.key === fn)?.desc || "";
return (
<div className="space-y-2">
{value.map((x, i) => (
<div key={i} className="flex flex-wrap items-center gap-2">
<input className="input h-8 w-32" placeholder="叫什么" value={x.name} disabled={!canEdit} onChange={(e) => up(i, { name: e.target.value })} />
<span className="text-label text-muted">=</span>
<Select className="input h-8 w-32" value={x.fn} disabled={!canEdit} title={desc(x.fn)} onChange={(e) => up(i, { fn: e.target.value })}>
{meta.detectors.map((k) => <option key={k.key} value={k.key}>{k.label}</option>)}
</Select>
<span className="text-label text-muted">看</span>
<Select className="input h-8 w-36" value={x.field} disabled={!canEdit} onChange={(e) => up(i, { field: e.target.value })}>
<option value="value">指标值</option>
{base.filter((f) => f.path !== "value").map((f) => <option key={f.path} value={f.path}>{f.label}</option>)}
</Select>
{["avg", "std", "zscore", "streak_up", "streak_down"].includes(x.fn) && <>
<span className="text-label text-muted">近</span>
<input className="input h-8 w-16" type="number" min={2} max={90} value={x.window} disabled={!canEdit}
onChange={(e) => up(i, { window: Number(e.target.value) })} />
<span className="text-label text-muted">期</span>
</>}
{x.fn === "changed" && <>
<input className="input h-8 w-28" placeholder="从(逗号隔开)" value={(x.from || []).join(",")} disabled={!canEdit}
onChange={(e) => up(i, { from: e.target.value.split(/[,,]/).map((v) => v.trim()).filter(Boolean) })} />
<input className="input h-8 w-28" placeholder="变成" value={(x.to || []).join(",")} disabled={!canEdit}
onChange={(e) => up(i, { to: e.target.value.split(/[,,]/).map((v) => v.trim()).filter(Boolean) })} />
</>}
<span className="min-w-0 flex-1 truncate text-caption text-muted">{desc(x.fn)}</span>
{canEdit && <button className="btn btn-ghost btn-sm" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{canEdit && <button className="btn btn-sm" onClick={() => onChange([...value, { name: `检测${value.length + 1}`, fn: "pct_change", field: "value", window: 7 }])}>
<Plus className="h-3.5 w-3.5" />加一个检测量</button>}
</div>
);
}
/** 严重度:固定一个级别 / 按条件分级(从上往下第一条成立的)/ 用本体里的决策表定。 */
function SeverityEditor({ value: v, onChange, meta, canEdit, decisions }: {
value: any; onChange: (v: any) => void; meta: WatchMeta; canEdit: boolean; decisions: ConceptBrief[];
}) {
const rules: { when: string; level: string }[] = v.rules || [];
return (
<div className="space-y-3">
<Segmented value={v.mode || "fixed"} onChange={(k) => onChange({ ...v, mode: k })}
options={meta.severity_modes.map((s) => ({ key: s.key, label: s.label }))} />
<div className="flex flex-wrap items-start gap-4">
<Field label={v.mode === "fixed" ? "级别" : "都不成立时"}>
<Select className="input w-24" value={v.level || "中"} disabled={!canEdit} onChange={(e) => onChange({ ...v, level: e.target.value })}>
{meta.severities.map((x) => <option key={x} value={x}>{x}</option>)}</Select>
</Field>
{v.mode === "decision" && (
<Field label="决策表" hint="命中行的字段按同名传给决策表;它的第一个输出是高 / 中 / 低">
<Select className="input w-56" value={v.function || ""} disabled={!canEdit} onChange={(e) => onChange({ ...v, function: e.target.value })}>
<option value="">选择</option>{decisions.map((x) => <option key={x.id} value={x.name}>{x.name}</option>)}</Select>
</Field>
)}
</div>
{v.mode === "rules" && (
<div className="space-y-2">
{rules.map((r, i) => (
<div key={i} className="flex items-center gap-2">
<span className="text-label text-muted">如果</span>
<input className="input h-8 min-w-0 flex-1 font-mono" placeholder="如 涨幅 > 0.5" value={r.when} disabled={!canEdit}
onChange={(e) => onChange({ ...v, rules: rules.map((x, j) => (j === i ? { ...x, when: e.target.value } : x)) })} />
<span className="text-label text-muted">就是</span>
<Select className="input h-8 w-20" value={r.level} disabled={!canEdit}
onChange={(e) => onChange({ ...v, rules: rules.map((x, j) => (j === i ? { ...x, level: e.target.value } : x)) })}>
{meta.severities.map((x) => <option key={x} value={x}>{x}</option>)}</Select>
{canEdit && <button className="btn btn-ghost btn-sm" onClick={() => onChange({ ...v, rules: rules.filter((_, j) => j !== i) })}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
))}
{canEdit && <button className="btn btn-sm" onClick={() => onChange({ ...v, rules: [...rules, { when: "", level: "高" }] })}>
<Plus className="h-3.5 w-3.5" />加一条分级条件</button>}
</div>
)}
</div>
);
}
function StrategyList({ value, onChange, canEdit, meta, actions, sops, rowVars }: {
value: any[]; onChange: (v: any[]) => void; canEdit: boolean; meta: WatchMeta;
actions: CapDef[]; sops: SopBrief[];
/** 命中的每一行里可以引用的字段:$key、$value、各维度 / 属性 */
rowVars: string[];
}) {
const up = (i: number, patch: any) => onChange(value.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const [sopDefs, setSopDefs] = useState<Record<string, SopDef>>({});
useEffect(() => {
for (const s of value) {
if (s.kind === "run_sop" && s.sop && !sopDefs[s.sop]) {
void onto.sop(s.sop).then((x) => setSopDefs((m) => ({ ...m, [s.sop]: x }))).catch(() => undefined);
}
}
}, [value]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="space-y-2">
{value.map((s, i) => (
<div key={i} className="rounded-lg border border-line p-2">
<div className="flex flex-wrap items-center gap-2">
<Select className="input h-8 w-36" value={s.kind} disabled={!canEdit}
onChange={(e) => up(i, { kind: e.target.value })}>
{meta.strategy_kinds.map((k) => <option key={k.key} value={k.key}>{k.label}</option>)}
</Select>
{s.kind === "propose_action" && (
<Select className="input h-8 w-44" value={s.action || ""} disabled={!canEdit}
onChange={(e) => up(i, { action: e.target.value })}>
<option value="">选动作</option>
{actions.map((a) => <option key={a.id} value={a.name}>{a.display_name || a.name}{a.status !== "published" ? "(草稿)" : ""}</option>)}
</Select>
)}
{s.kind === "run_sop" && (
<Select className="input h-8 w-44" value={s.sop || ""} disabled={!canEdit}
onChange={(e) => up(i, { sop: e.target.value })}>
<option value="">选流程卡</option>
{sops.map((x) => <option key={x.id} value={x.id}>{x.title}</option>)}
</Select>
)}
{s.kind === "task" && (
<>
<RefSelect refKind="role" className="w-40" value={s.role || ""} disabled={!canEdit} placeholder="派给哪个角色"
onChange={(v) => up(i, { role: String(v || "") })} />
<input className="input h-8 min-w-[10rem] flex-1" placeholder="待办的标题" value={s.title || ""}
disabled={!canEdit} onChange={(e) => up(i, { title: e.target.value })} />
</>
)}
{s.kind === "notify" && (
<>
<RefSelect refKind="role" className="w-40" value={s.role || ""} disabled={!canEdit} placeholder="通知哪个角色"
onChange={(v) => up(i, { role: String(v || "") })} />
<input className="input h-8 min-w-[10rem] flex-1" placeholder="通知的标题" value={s.subject || ""}
disabled={!canEdit} onChange={(e) => up(i, { subject: e.target.value })} />
</>
)}
<Select className="input h-8 w-32" value={s.min_severity || ""} disabled={!canEdit} title="严重度到这一级才做这一项"
onChange={(e) => up(i, { min_severity: e.target.value || undefined })}>
<option value="">任何级别都做</option>
{meta.severities.map((x) => <option key={x} value={x}>{x === "低" ? "低及以上" : `${x}${x === "高" ? "" : "及以上"}才做`}</option>)}
</Select>
{canEdit && <button className="btn btn-ghost btn-sm ml-auto"
onClick={() => onChange(value.filter((_, j) => j !== i))}>
<Trash2 className="h-3.5 w-3.5" /></button>}
</div>
{(s.kind === "task" || s.kind === "notify") && (
<div className="mt-2">
<textarea className="input min-h-[52px] text-label" disabled={!canEdit}
placeholder={s.kind === "task" ? "要对方做什么" : "通知内容"}
value={(s.kind === "task" ? s.instructions : s.body) || ""}
onChange={(e) => up(i, s.kind === "task" ? { instructions: e.target.value } : { body: e.target.value })} />
<p className="hint">标题和内容里可以用 $label(命中的是谁)、$severity(严重度)、$event_id(预警事件){rowVars.length > 2 ? ",以及这一行的其他字段" : ""}。</p>
</div>
)}
{s.kind === "propose_action" && (() => {
const a = actions.find((x) => x.name === s.action);
if (!a) return null;
return (
<div className="mt-2 space-y-2">
{a.spec?.target_type && (
<Field label="对哪个对象做" hint="不选就自动对上命中的那一个">
<RefSelect refKind="" value={s.object_key || ""} disabled={!canEdit} vars={rowVars} placeholder="自动"
onChange={(v) => up(i, { object_key: String(v || "") })} />
</Field>
)}
<SchemaForm compact disabled={!canEdit} schema={actionParamSchema(a.spec)} value={s.params || {}} vars={rowVars}
onChange={(v) => up(i, { params: v })} />
</div>
);
})()}
{s.kind === "run_sop" && sopDefs[s.sop] && (sopDefs[s.sop].spec.params || []).length > 0 && (
<div className="mt-2">
<SchemaForm compact disabled={!canEdit} schema={sopParamSchema(sopDefs[s.sop].spec.params)} value={s.params || {}}
vars={rowVars} onChange={(v) => up(i, { params: v })} />
</div>
)}
</div>
))}
{canEdit && (
<button className="btn btn-sm" onClick={() => onChange([...value, { kind: "propose_action", params: {}, object_key: "" }])}>
<Plus className="h-3.5 w-3.5" />再加一件事
</button>
)}
</div>
);
}
type RowField = { path: string; label: string; type: string; enum?: string[]; format?: string; unit?: string };
/** 命中的行,按字段的名称显示。 */
export function HitTable({ hits, fields }: { hits: Record<string, any>[]; fields: RowField[] }) {
if (!hits.length) return null;
const known = fields.filter((f) => hits.some((h) => h[f.path] !== undefined)).slice(0, 8);
const data = known.length
? { columns: ["命中的是谁", ...known.map((f) => f.label)], rows: hits.map((h) => [h.label ?? h.key, ...known.map((f) => h[f.path])]) }
: { columns: Object.keys(hits[0]).slice(0, 8), rows: hits.map((h) => Object.keys(hits[0]).slice(0, 8).map((k) => h[k])) };
return <ResultGrid data={data} max={20} />;
}
function FiredList({ fired }: { fired: WatchRunRec["fired"] }) {
if (!fired.length) return null;
const link = (f: any) => (f.ref_kind === "action_run" ? `#/inbox?run=${f.ref}` : f.ref_kind === "sop_run" ? `#/sop?run=${f.ref}`
: f.ref_kind === "task" ? `#/inbox?tab=tasks&task=${f.ref}` : "");
return (
<ul className="space-y-1">
{fired.slice(0, 12).map((f: any, i) => (
<li key={i} className={cn("flex items-center gap-2 text-label", !f.ok && "text-bad")}>
<span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", f.ok ? "bg-ok" : "bg-bad")} />
{f.label && <span className="shrink-0 font-medium">{f.label}</span>}
<span className="min-w-0 truncate text-muted">{f.text}</span>
{f.ok && link(f) && <a className="shrink-0 text-brand hover:underline" href={link(f)}>查看</a>}
</li>
))}
{fired.length > 12 && <li className="text-caption text-muted">还有 {fired.length - 12} 条</li>}
</ul>
);
}
function ScanResult({ r, fields }: { r: WatchScanResult; fields: RowField[] }) {
return (
<FormSection title={r.run_id ? "这一次的结果" : "现在会命中这些"}>
<p className="text-body">
看了 <b>{r.scanned}</b> 条,命中 <b className={r.hit_count ? "text-warn" : ""}>{r.hit_count}</b> 条
{r.suppressed > 0 && <>,其中 {r.suppressed} 条不久前提醒过,这次没有重复提醒</>}
{(r.opened || 0) > 0 && <>,新开 {r.opened} 条预警事件</>}
{(r.recovered || 0) > 0 && <span className="text-ok">,{r.recovered} 条已恢复</span>}
{r.over_limit > 0 && <span className="text-bad">,还有 {r.over_limit} 条超出单次上限没处理</span>}
{(r.unscanned || 0) > 0 && <span className="text-bad">,数据太多,还有 {r.unscanned} 条没看</span>}
</p>
<FiredList fired={r.fired} />
<HitTable hits={r.hits} fields={fields} />
</FormSection>
);
}
function RunsView({ runs }: { runs: WatchRunRec[] | null }) {
if (runs === null) return <div className="grid flex-1 place-items-center"><Spinner /></div>;
if (!runs.length) return <div className="flex-1"><Empty title="还没有运行过" /></div>;
return (
<div className="min-h-0 flex-1 overflow-auto">
<ul className="divide-y divide-line/70">
{runs.map((r) => (
<li key={r.id} className="px-6 py-3.5">
<div className="flex flex-wrap items-center gap-3">
<Badge variant={r.status === "done" ? (r.hit_count ? "warn" : "ok") : r.status === "failed" ? "danger" : "info"}>
{r.status === "done" ? (r.hit_count ? `命中 ${r.hit_count} 条` : "没有命中") : r.status === "failed" ? "失败" : "进行中"}
</Badge>
<span className="text-label text-muted"><Ago at={r.started_at} /> · {{ schedule: "定时", change: "对象变化", manual: "手动" }[r.trigger] || r.trigger}</span>
{(r.opened || 0) > 0 && <Badge variant="warn">新开 {r.opened} 条事件</Badge>}
{(r.recovered || 0) > 0 && <Badge variant="ok">恢复 {r.recovered} 条</Badge>}
<span className="ml-auto text-label text-muted">看了 {r.scanned} 条{r.suppressed > 0 ? `,${r.suppressed} 条没有重复提醒` : ""}</span>
</div>
{r.error && <p className="mt-1.5 text-label text-bad">{r.error}</p>}
{r.fired.length > 0 && <div className="mt-2"><FiredList fired={r.fired} /></div>}
</li>
))}
</ul>
</div>
);
}
/**
* 预警:每一条是一个预警事件 —— 从「新发现」到「已恢复 / 已忽略」的一整轮,带严重度、偏离基线多少、系统做了什么。
* 上面是近 30 天的效果:自动处理率、平均恢复用时、复发率、误报率(和系统对象上的效果指标是同一个口径)。
*/
export function AlertsPage() {
const params = useHashParams();
const watchId = params.get("watch") || "";
const [state, setState] = useState<"open" | "closed">("open");
const [items, setItems] = useState<AlertEvent[] | null>(null);
const [stats, setStats] = useState<AlertStats | null>(null);
const [err, setErr] = useState("");
const [open, setOpen] = useState("");
const load = useCallback(() => {
void onto.watchAlerts(state, watchId).then((r) => { setItems(r); setErr(""); }).catch((e) => { setErr(errText(e)); setItems([]); });
void onto.alertStats(watchId, 30).then(setStats).catch(() => setStats(null));
}, [state, watchId]);
useEffect(() => { setItems(null); load(); }, [load]);
const groups = useMemo(() => {
const m = new Map<string, AlertEvent[]>();
for (const a of items || []) m.set(a.watch_id, [...(m.get(a.watch_id) || []), a]);
return [...m.values()];
}, [items]);
const pct = (v: number | null | undefined) => (v === null || v === undefined ? "—" : `${Math.round(v * 100)}%`);
const ignore = async (a: AlertEvent) => {
const reason = window.prompt("为什么忽略(误报原因)?", "");
if (reason === null) return;
const days = Number(window.prompt("同一条静默几天?0 = 不静默", "7") || 0);
try { await onto.ignoreAlert(a.id, reason, days); toast("ok", "已标为忽略"); load(); } catch (e) { toast("error", errText(e)); }
};
const close = async (a: AlertEvent) => {
try { await onto.closeAlert(a.id, "人工确认恢复"); toast("ok", "已确认恢复"); load(); } catch (e) { toast("error", errText(e)); }
};
return (
<div className="flex flex-col gap-4">
{stats && (
<Card className="grid grid-cols-2 gap-4 p-4 sm:grid-cols-6">
{[["近 30 天预警", String(stats.total)], ["还没结束", String(stats.open)], ["自动处理率", pct(stats.auto_rate)],
["平均恢复用时", stats.avg_recover_hours === null ? "—" : `${stats.avg_recover_hours} 小时`],
["复发率", pct(stats.recurrence_rate)], ["误报率", pct(stats.false_alarm_rate)]].map(([k, v]) => (
<div key={k}><p className="text-caption text-muted">{k}</p><p className="text-section font-semibold">{v}</p></div>
))}
</Card>
)}
<div className="flex flex-wrap items-center gap-2">
<Tabs<"open" | "closed"> className="flex-1" value={state} onChange={setState}
options={[{ key: "open", label: "还没结束", count: state === "open" ? items?.length : null }, { key: "closed", label: "已恢复 / 已忽略" }]} />
{watchId && <button className="btn btn-sm" onClick={() => go("alerts")}>看全部规则的</button>}
<button className="btn btn-ghost btn-sm" onClick={load} aria-label="刷新"><RefreshCw className="h-3.5 w-3.5" /></button>
</div>
{err && <Card className="p-4 text-label text-bad">{err}</Card>}
{items === null ? <div className="grid place-items-center p-16"><Spinner /></div> : !groups.length ? (
<Card><Empty icon={<CheckCircle2 className="h-9 w-9" />} title={state === "open" ? "现在没有预警" : "没有已结束的记录"} /></Card>
) : groups.map((g) => (
<Card key={g[0].watch_id} className="overflow-hidden">
<div className="flex items-center gap-2 border-b border-line px-5 py-3">
<h3 className="text-title font-semibold">{g[0].rule}</h3>
<Badge variant={state === "open" ? "warn" : "neutral"}>{g.length} 条</Badge>
<span className="flex-1" />
<button className="btn btn-ghost btn-sm" onClick={() => go("watch", { id: g[0].watch_id })}>看这条规则</button>
</div>
<ul className="divide-y divide-line/70">
{g.map((a) => {
const row = a.detail?.row || {};
const dets = a.detail?.detectors || {};
const shown = Object.entries(row).filter(([k, v]) => !["key", "label"].includes(k) && v !== null && v !== undefined && v !== "");
return (
<li key={a.id}>
<button className="flex w-full items-center gap-3 px-5 py-3 text-left hover:bg-ink/[0.03]" onClick={() => setOpen(open === a.id ? "" : a.id)}>
<ChevronRight className={cn("h-4 w-4 shrink-0 text-muted transition-transform", open === a.id && "rotate-90")} />
<Badge variant={SEV_TONE[a.severity] || "neutral"}>{a.severity}</Badge>
<span className="min-w-0 flex-1 truncate text-body font-medium">{a.title}</span>
{a.is_recurrence && <Badge variant="danger">复发</Badge>}
<Badge variant={a.status === "已恢复" ? "ok" : a.status === "已忽略" ? "neutral" : "warn"}>{a.status}</Badge>
<span className="shrink-0 text-label text-muted">
{state === "open" ? <>已持续 {fmtDuration(a.first_seen_at) || "不到 1 分钟"}</>
: a.recovered_at ? <>恢复于 <Ago at={a.recovered_at} />{a.recover_hours !== null ? `(用了 ${a.recover_hours} 小时)` : ""}</> : a.note}
</span>
</button>
{open === a.id && (
<div className="space-y-4 bg-ink/[0.015] px-12 py-4">
{(a.value !== null || a.baseline !== null) && (
<p className="text-label">现在 <b>{a.value ?? "—"}</b>
{a.baseline !== null && <>,基线 <b>{a.baseline}</b></>}
{a.deviation !== null && <>,偏离 <b className="text-warn">{a.deviation}</b></>}
{a.handling && <span className="text-muted"> · 处置:{a.handling}{a.auto_handled ? "(自动)" : ""}</span>}</p>
)}
<Desc cols={4} items={[...shown.slice(0, 12).map(([k, v]) => ({ label: k, value: <Value v={v} /> })),
...Object.entries(dets).map(([k, v]) => ({ label: `${k}(检测量)`, value: <Value v={v} /> }))]} />
{a.fired.length > 0 && (
<div>
<p className="mb-1.5 text-caption text-muted">系统已经做了</p>
<FiredList fired={a.fired as any} />
</div>
)}
{a.object?.type_id && a.object.key && (
<TraceItem n={{ kind: "object", kind_label: a.object.type_name || "对象", id: a.object.key, title: a.object.label || a.title,
status: "", note: "", link: `#/objects?type=${a.object.type_id}&key=${a.object.key}`, at: "" }} />
)}
{state === "open" && (
<div className="flex gap-2">
<button className="btn btn-sm" onClick={() => void close(a)}><CheckCircle2 className="h-3.5 w-3.5" />确认已恢复</button>
<button className="btn btn-ghost btn-sm" onClick={() => void ignore(a)}><BellOff className="h-3.5 w-3.5" />误报,忽略</button>
</div>
)}
</div>
)}
</li>
);
})}
</ul>
</Card>
))}
</div>
);
}