feat(alarms): 完成 M06 报警中心与人工处理

落地正式异常创建/合并、三状态人工处置与控制台,关闭 M06 DONE_LOCAL(含 D40 认领文案「处理」)。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-19 15:27:06 +08:00
1 parent df991417d7
commit 47d3b85a4b
88 files changed
+12658 -30

No files matched your search

+375
View File
@@ -0,0 +1,375 @@
/**
* Demo walkthrough screenshots for M06. Route-mocked so Casdoor is not required.
* Output: docs/evidence/M06/demo/
*/
import { expect, test, type Page, type Route } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const demoDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M06/demo",
);
fs.mkdirSync(demoDir, { recursive: true });
const SUBJECT = "demo-operator";
const OTHER = "demo-lin";
const PENDING = "11111111-1111-4111-8111-111111111111";
const PROCESSING = "22222222-2222-4222-8222-222222222222";
const CLOSED = "33333333-3333-4333-8333-333333333333";
const OBJECT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
type Alarm = {
id: string;
status: string;
current_handler: string | null;
claimed_at: string | null;
closed_at: string | null;
close_result: string | null;
occurrence_count: number;
first_occurred_at: string;
last_occurred_at: string;
previous_alarm_id: string | null;
mapped_input_id: string;
identity_key: string;
module_key: string;
scenario_key: string;
scenario_name: string;
snapshot_id: string;
snapshot_version_no: number;
cycle_key: string;
event_key: string;
opened_at: string;
updated_at: string;
};
type HistoryItem = {
id: string;
seq: number;
command: string;
actor_subject: string;
actor_role: string;
handler_subject: string;
from_status: string;
to_status: string;
note: string | null;
close_result: string | null;
evidence_ref: string | null;
recorded_at: string;
};
type Mock = {
alarms: Alarm[];
history: Record<string, HistoryItem[]>;
};
function ok(data: unknown): string {
return JSON.stringify({ success: true, data, request_id: "demo-alarm" });
}
function seedAlarm(overrides: Partial<Alarm> & Pick<Alarm, "id" | "status" | "scenario_name">): Alarm {
return {
current_handler: null,
claimed_at: null,
closed_at: null,
close_result: null,
occurrence_count: 1,
first_occurred_at: "2026-11-19T01:00:00.000Z",
last_occurred_at: "2026-11-19T02:00:00.000Z",
previous_alarm_id: null,
mapped_input_id: OBJECT,
identity_key: "furnace-01",
module_key: "furnace",
scenario_key: "furnace-overtemp",
snapshot_id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
snapshot_version_no: 3,
cycle_key: "cycle-1",
event_key: "event-1",
opened_at: "2026-11-19T01:00:00.000Z",
updated_at: "2026-11-19T02:00:00.000Z",
...overrides,
};
}
function seedAlarms(): Alarm[] {
return [
seedAlarm({ id: PENDING, status: "pending", scenario_name: "炉温超限", identity_key: "furnace-01" }),
seedAlarm({
id: PROCESSING,
status: "processing",
scenario_name: "气压偏低",
identity_key: "comp-02",
module_key: "utility",
scenario_key: "air-pressure",
current_handler: OTHER,
claimed_at: "2026-11-19T01:30:00.000Z",
mapped_input_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
}),
seedAlarm({
id: CLOSED,
status: "closed",
scenario_name: "尺寸超差",
identity_key: "part-09",
module_key: "quality",
scenario_key: "dimension",
current_handler: OTHER,
claimed_at: "2026-11-19T01:10:00.000Z",
closed_at: "2026-11-19T03:00:00.000Z",
close_result: "resolved",
occurrence_count: 2,
mapped_input_id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
}),
];
}
async function signIn(page: Page, roles: string[]): Promise<void> {
await page.route(
(url) => url.pathname === "/auth/me",
async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ subject: SUBJECT, display_name: "演示操作员", roles }),
});
},
);
}
function pushHistory(
mock: Mock,
alarm: Alarm,
command: string,
note: string | null,
result: string | null = null,
): void {
const items = mock.history[alarm.id] ?? [];
items.push({
id: `h-${items.length + 1}`,
seq: items.length + 1,
command,
actor_subject: SUBJECT,
actor_role: "watchman-operator",
handler_subject: alarm.current_handler ?? SUBJECT,
from_status: command === "claim" ? "pending" : "processing",
to_status: command === "close" ? "closed" : "processing",
note,
close_result: result,
evidence_ref: null,
recorded_at: "2026-11-19T05:00:00.000Z",
});
mock.history[alarm.id] = items;
}
async function mockAlarms(page: Page): Promise<Mock> {
const mock: Mock = {
alarms: seedAlarms(),
history: {
[CLOSED]: [
{
id: "h1",
seq: 1,
command: "claim",
actor_subject: OTHER,
actor_role: "watchman-operator",
handler_subject: OTHER,
from_status: "pending",
to_status: "processing",
note: null,
close_result: null,
evidence_ref: null,
recorded_at: "2026-11-19T01:10:00.000Z",
},
{
id: "h2",
seq: 2,
command: "close",
actor_subject: OTHER,
actor_role: "watchman-operator",
handler_subject: OTHER,
from_status: "processing",
to_status: "closed",
note: "已核对量具并复测通过",
close_result: "resolved",
evidence_ref: null,
recorded_at: "2026-11-19T03:00:00.000Z",
},
],
},
};
const matcher = (url: URL) =>
/^\/alarms(\/[^/]+(\/(occurrences|evidence|history|claim|progress|close))?)?$/.test(url.pathname);
await page.route(matcher, async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const method = request.method();
const parts = url.pathname.split("/").filter(Boolean);
const json = (status: number, text: string) =>
route.fulfill({ status, contentType: "application/json", body: text });
if (parts.length === 1 && method === "GET") {
return json(
200,
ok({ items: mock.alarms, total: mock.alarms.length, page: 1, page_size: 20 }),
);
}
const id = parts[1];
const alarm = mock.alarms.find((item) => item.id === id);
if (!alarm) {
return json(404, ok(null));
}
if (parts.length === 2 && method === "GET") {
return json(200, ok(alarm));
}
const action = parts[2];
if (method === "GET" && action === "occurrences") {
return json(
200,
ok({
alarm_id: id,
items: [
{
id: `${id}-occ-0`,
mapped_input_revision_id: OBJECT,
mapping_version_id: OBJECT,
rule_version_id: OBJECT,
snapshot_id: alarm.snapshot_id,
snapshot_version_no: alarm.snapshot_version_no,
module_key: alarm.module_key,
scenario_key: alarm.scenario_key,
scenario_name: alarm.scenario_name,
cycle_key: alarm.cycle_key,
event_key: alarm.event_key,
observed_at: alarm.first_occurred_at,
received_at: alarm.first_occurred_at,
created_at: alarm.opened_at,
},
],
}),
);
}
if (method === "GET" && action === "evidence") {
return json(200, ok({ alarm_id: id, revision_evidence: [], closed_basis: [] }));
}
if (method === "GET" && action === "history") {
return json(200, ok({ alarm_id: id, items: mock.history[id] ?? [] }));
}
if (method === "POST" && action === "claim") {
alarm.status = "processing";
alarm.current_handler = SUBJECT;
alarm.claimed_at = "2026-11-19T02:10:00.000Z";
pushHistory(mock, alarm, "claim", null);
return json(
200,
ok({
alarm_id: id,
event_id: "evt-1",
command: "claim",
status: alarm.status,
current_handler: alarm.current_handler,
close_result: null,
replayed: false,
}),
);
}
if (method === "POST" && action === "progress") {
const body = request.postDataJSON() as { note?: string };
pushHistory(mock, alarm, "progress", body.note ?? null);
return json(
200,
ok({
alarm_id: id,
event_id: "evt-2",
command: "progress",
status: alarm.status,
current_handler: alarm.current_handler,
close_result: null,
replayed: false,
}),
);
}
if (method === "POST" && action === "close") {
const body = request.postDataJSON() as { result?: string; note?: string };
alarm.status = "closed";
alarm.close_result = body.result ?? "resolved";
alarm.closed_at = "2026-11-19T05:00:00.000Z";
pushHistory(mock, alarm, "close", body.note ?? null, alarm.close_result);
return json(
200,
ok({
alarm_id: id,
event_id: "evt-3",
command: "close",
status: alarm.status,
current_handler: alarm.current_handler,
close_result: alarm.close_result,
replayed: false,
}),
);
}
return json(404, ok(null));
});
return mock;
}
async function shot(page: Page, name: string): Promise<void> {
await page.screenshot({ path: path.join(demoDir, name), fullPage: true });
}
test.describe("alarm center demo", () => {
test("walk through list, claim, progress, close, history, viewer", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await signIn(page, ["watchman-operator"]);
await mockAlarms(page);
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-table")).toBeVisible();
await expect(page.getByTestId("alarm-table")).toContainText("炉温超限");
await expect(page.getByTestId("alarm-table")).toContainText("气压偏低");
await expect(page.getByTestId("alarm-table")).toContainText("尺寸超差");
await shot(page, "01-list-three-alarms.png");
await page.getByTestId(`alarm-row-${PENDING}`).getByTestId("alarm-open").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("待处理");
await shot(page, "02-detail-pending.png");
await page.getByTestId("footer-claim").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("处理中");
await shot(page, "03-after-claim.png");
await page.getByTestId("footer-progress").click();
await page.getByTestId("progress-note").locator("textarea").fill("已到现场核对温度曲线");
await page.getByTestId("progress-submit").click();
await expect(page.getByTestId("alarm-history")).toContainText("已到现场核对温度曲线");
await shot(page, "04-after-progress.png");
await page.getByTestId("footer-close").click();
await page.getByTestId("close-result").click();
await page.getByRole("option", { name: "已处理" }).click();
await page.getByTestId("close-note").locator("textarea").fill("调整冷却参数后恢复正常");
await page.getByTestId("close-submit").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
await shot(page, "05-after-close.png");
await page.goto(`/#/alarms/${CLOSED}`);
await expect(page.getByTestId("alarm-history")).toContainText("已核对量具并复测通过");
await shot(page, "06-closed-history.png");
});
test("viewer sees detail without handling buttons", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await signIn(page, ["watchman-viewer"]);
await mockAlarms(page);
await page.goto(`/#/alarms/${PENDING}`);
await expect(page.getByTestId("alarm-detail")).toBeVisible();
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await expect(page.getByTestId("footer-close")).toHaveCount(0);
await shot(page, "07-viewer-no-actions.png");
});
});
+596
View File
@@ -0,0 +1,596 @@
/**
* U06 alarm center. The API is mocked. Copy must not echo a server message,
* and the three desktop viewports keep the list pager and detail footer in view.
*/
import { expect, test, type Page, type Route } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const evidenceDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M06/ui",
);
fs.mkdirSync(evidenceDir, { recursive: true });
const SERVER_SECRET = "HANDLER_STOLEN_SECRET sql password leaked";
const SUBJECT = "subj-chen";
const OTHER = "subj-lin";
const PENDING = "11111111-1111-4111-8111-111111111111";
const PROCESSING = "22222222-2222-4222-8222-222222222222";
const CLOSED = "33333333-3333-4333-8333-333333333333";
const OBJECT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
type Alarm = {
id: string;
status: string;
current_handler: string | null;
claimed_at: string | null;
closed_at: string | null;
close_result: string | null;
occurrence_count: number;
first_occurred_at: string;
last_occurred_at: string;
previous_alarm_id: string | null;
mapped_input_id: string;
identity_key: string;
module_key: string;
scenario_key: string;
scenario_name: string;
snapshot_id: string;
snapshot_version_no: number;
cycle_key: string;
event_key: string;
opened_at: string;
updated_at: string;
};
type HistoryItem = {
id: string;
seq: number;
command: string;
actor_subject: string;
actor_role: string;
handler_subject: string;
from_status: string;
to_status: string;
note: string | null;
close_result: string | null;
evidence_ref: string | null;
recorded_at: string;
};
type Mock = {
alarms: Alarm[];
history: Record<string, HistoryItem[]>;
requests: { method: string; pathname: string; search: string; key: string | null }[];
claimConflict: boolean;
listStatus: number;
listFailuresLeft: number;
};
function ok(data: unknown): string {
return JSON.stringify({ success: true, data, request_id: "pw-alarm" });
}
function fail(code: number, message: string, details: Record<string, unknown> = {}): string {
return JSON.stringify({
success: false,
error: { code, message, details, retryable: false },
request_id: "pw-alarm",
});
}
function seedAlarm(overrides: Partial<Alarm> & Pick<Alarm, "id" | "status" | "scenario_name">): Alarm {
return {
current_handler: null,
claimed_at: null,
closed_at: null,
close_result: null,
occurrence_count: 1,
first_occurred_at: "2026-11-18T01:00:00.000Z",
last_occurred_at: "2026-11-18T02:00:00.000Z",
previous_alarm_id: null,
mapped_input_id: OBJECT,
identity_key: "furnace-01",
module_key: "furnace",
scenario_key: "furnace-overtemp",
snapshot_id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
snapshot_version_no: 3,
cycle_key: "cycle-1",
event_key: "event-1",
opened_at: "2026-11-18T01:00:00.000Z",
updated_at: "2026-11-18T02:00:00.000Z",
...overrides,
};
}
function seedAlarms(): Alarm[] {
return [
seedAlarm({ id: PENDING, status: "pending", scenario_name: "炉温超限", identity_key: "furnace-01" }),
seedAlarm({
id: PROCESSING,
status: "processing",
scenario_name: "气压偏低",
identity_key: "comp-02",
module_key: "utility",
scenario_key: "air-pressure",
current_handler: OTHER,
claimed_at: "2026-11-18T01:30:00.000Z",
mapped_input_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
}),
seedAlarm({
id: CLOSED,
status: "closed",
scenario_name: "尺寸超差",
identity_key: "part-09",
module_key: "quality",
scenario_key: "dimension",
current_handler: OTHER,
claimed_at: "2026-11-18T01:10:00.000Z",
closed_at: "2026-11-18T03:00:00.000Z",
close_result: "resolved",
occurrence_count: 2,
mapped_input_id: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
}),
];
}
function occurrence(alarm: Alarm, index: number) {
return {
id: `${alarm.id}-occ-${index}`,
mapped_input_revision_id: OBJECT,
mapping_version_id: OBJECT,
rule_version_id: OBJECT,
snapshot_id: alarm.snapshot_id,
snapshot_version_no: alarm.snapshot_version_no,
module_key: alarm.module_key,
scenario_key: alarm.scenario_key,
scenario_name: alarm.scenario_name,
cycle_key: alarm.cycle_key,
event_key: `${alarm.event_key}-${index}`,
observed_at: "2026-11-18T01:00:00.000Z",
received_at: "2026-11-18T01:05:00.000Z",
created_at: "2026-11-18T01:06:00.000Z",
};
}
async function signIn(page: Page, roles: string[], subject = SUBJECT): Promise<void> {
await page.route(
(url) => url.pathname === "/auth/me",
async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: ok({ subject, display_name: "Chen", roles }),
});
},
);
}
async function mockAlarms(
page: Page,
options: { alarms?: Alarm[]; claimConflict?: boolean; listFailuresLeft?: number } = {},
): Promise<Mock> {
const mock: Mock = {
alarms: options.alarms ?? seedAlarms(),
history: {
[CLOSED]: [
{
id: "h1",
seq: 1,
command: "claim",
actor_subject: OTHER,
actor_role: "watchman-operator",
handler_subject: OTHER,
from_status: "pending",
to_status: "processing",
note: null,
close_result: null,
evidence_ref: null,
recorded_at: "2026-11-18T01:10:00.000Z",
},
{
id: "h2",
seq: 2,
command: "close",
actor_subject: OTHER,
actor_role: "watchman-operator",
handler_subject: OTHER,
from_status: "processing",
to_status: "closed",
note: "已核对尺寸",
close_result: "resolved",
evidence_ref: "lot-100",
recorded_at: "2026-11-18T03:00:00.000Z",
},
],
},
requests: [],
claimConflict: options.claimConflict ?? false,
listStatus: 200,
listFailuresLeft: options.listFailuresLeft ?? 0,
};
const matcher = (url: URL) =>
/^\/alarms(\/[^/]+(\/(occurrences|evidence|history|claim|progress|close))?)?$/.test(url.pathname);
await page.route(matcher, async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const method = request.method();
const key = request.headers()["x-idempotency-key"] ?? null;
mock.requests.push({ method, pathname: url.pathname, search: url.search, key });
const json = (status: number, text: string) =>
route.fulfill({ status, contentType: "application/json", body: text });
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length === 1 && method === "GET") {
if (mock.listFailuresLeft > 0) {
mock.listFailuresLeft -= 1;
return json(500, fail(50000, SERVER_SECRET));
}
return json(200, ok(listBody(mock, url)));
}
const id = parts[1];
const alarm = mock.alarms.find((item) => item.id === id);
if (!alarm) {
return json(404, fail(40000, SERVER_SECRET, { reason: "not_found" }));
}
if (parts.length === 2 && method === "GET") {
return json(200, ok(alarm));
}
const action = parts[2];
if (method === "GET" && action === "occurrences") {
const count = alarm.id === CLOSED ? 4 : 1;
return json(200, ok({ alarm_id: id, items: Array.from({ length: count }, (_v, index) => occurrence(alarm, index)) }));
}
if (method === "GET" && action === "evidence") {
return json(
200,
ok({
alarm_id: id,
revision_evidence:
alarm.id === CLOSED
? [
{
id: "rev-1",
occurrence_id: `${id}-occ-0`,
mapped_input_revision_id: OBJECT,
mapping_version_id: OBJECT,
rule_version_id: OBJECT,
snapshot_id: alarm.snapshot_id,
snapshot_version_no: 3,
received_at: "2026-11-18T01:05:00.000Z",
recorded_at: "2026-11-18T01:06:00.000Z",
},
]
: [],
closed_basis:
alarm.id === CLOSED
? [
{
id: "basis-1",
original_occurrence_id: `${id}-occ-0`,
mapped_input_revision_id: OBJECT,
mapping_version_id: OBJECT,
rule_version_id: OBJECT,
snapshot_id: alarm.snapshot_id,
snapshot_version_no: 4,
cycle_key: alarm.cycle_key,
event_key: alarm.event_key,
observed_at: "2026-11-18T04:00:00.000Z",
received_at: "2026-11-18T04:01:00.000Z",
recorded_at: "2026-11-18T04:02:00.000Z",
},
]
: [],
}),
);
}
if (method === "GET" && action === "history") {
return json(200, ok({ alarm_id: id, items: mock.history[id] ?? [] }));
}
if (method === "POST" && action === "claim") {
if (mock.claimConflict) {
alarm.status = "processing";
alarm.current_handler = OTHER;
return json(409, fail(40000, SERVER_SECRET, { reason: "already_claimed" }));
}
alarm.status = "processing";
alarm.current_handler = SUBJECT;
alarm.claimed_at = "2026-11-18T02:10:00.000Z";
pushHistory(mock, alarm, "claim", null, null);
return json(200, ok(commandBody(alarm, "claim")));
}
if (method === "POST" && action === "progress") {
const body = request.postDataJSON() as { note?: string; evidence_ref?: string };
pushHistory(mock, alarm, "progress", body.note ?? null, body.evidence_ref ?? null);
return json(200, ok(commandBody(alarm, "progress")));
}
if (method === "POST" && action === "close") {
const body = request.postDataJSON() as { result?: string; note?: string; evidence_ref?: string };
alarm.status = "closed";
alarm.close_result = body.result ?? "resolved";
alarm.closed_at = "2026-11-18T05:00:00.000Z";
pushHistory(mock, alarm, "close", body.note ?? null, body.evidence_ref ?? null, alarm.close_result);
return json(200, ok(commandBody(alarm, "close")));
}
return json(404, fail(40000, SERVER_SECRET, { reason: "not_found" }));
});
return mock;
}
function pushHistory(
mock: Mock,
alarm: Alarm,
command: string,
note: string | null,
evidence: string | null,
result: string | null = null,
): void {
const items = mock.history[alarm.id] ?? [];
items.push({
id: `h-${items.length + 1}`,
seq: items.length + 1,
command,
actor_subject: SUBJECT,
actor_role: "watchman-operator",
handler_subject: alarm.current_handler ?? SUBJECT,
from_status: command === "claim" ? "pending" : "processing",
to_status: command === "close" ? "closed" : "processing",
note,
close_result: result,
evidence_ref: evidence,
recorded_at: "2026-11-18T05:00:00.000Z",
});
mock.history[alarm.id] = items;
}
function commandBody(alarm: Alarm, command: string) {
return {
alarm_id: alarm.id,
event_id: "evt-1",
command,
status: alarm.status,
current_handler: alarm.current_handler,
close_result: alarm.close_result,
replayed: false,
};
}
function listBody(mock: Mock, url: URL) {
let rows = [...mock.alarms];
const moduleKey = url.searchParams.get("module_key");
const scenario = (url.searchParams.get("scenario_name") ?? "").trim().toLowerCase();
const status = url.searchParams.get("status");
const objectId = url.searchParams.get("mapped_input_id");
if (moduleKey) {
rows = rows.filter((item) => item.module_key === moduleKey);
}
if (scenario) {
rows = rows.filter((item) => item.scenario_name.toLowerCase().includes(scenario));
}
if (status) {
rows = rows.filter((item) => item.status === status);
}
if (objectId) {
rows = rows.filter((item) => item.mapped_input_id === objectId);
}
const sortBy = url.searchParams.get("sort_by") || "last_occurred_at";
const dir = url.searchParams.get("sort_order") === "asc" ? 1 : -1;
rows.sort((a, b) => {
const av = String((a as Record<string, unknown>)[sortBy] ?? "");
const bv = String((b as Record<string, unknown>)[sortBy] ?? "");
return av < bv ? -dir : av > bv ? dir : 0;
});
const page = Number(url.searchParams.get("page") || "1");
const pageSize = Number(url.searchParams.get("page_size") || "20");
const start = Math.max(0, (page - 1) * pageSize);
return { items: rows.slice(start, start + pageSize), total: rows.length, page, page_size: pageSize };
}
function listGets(mock: Mock) {
return mock.requests.filter((item) => item.method === "GET" && item.pathname === "/alarms");
}
async function noPageScroll(page: Page): Promise<void> {
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow).toBeLessThanOrEqual(1);
}
async function expectInsideViewport(page: Page, testId: string): Promise<void> {
const box = await page.getByTestId(testId).boundingBox();
const viewport = page.viewportSize();
expect(box).toBeTruthy();
expect(viewport).toBeTruthy();
expect(box!.y).toBeGreaterThanOrEqual(-1);
expect(box!.y + box!.height).toBeLessThanOrEqual(viewport!.height + 1);
}
test.describe("alarm center", () => {
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
});
test("filters on search, then claim, progress, and close", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
const mock = await mockAlarms(page);
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-table")).toBeVisible();
await expect(page.getByTestId("alarm-table")).toContainText("待处理");
await expect(page.getByTestId("alarm-table")).toContainText("处理中");
await expect(page.getByTestId("alarm-table")).toContainText("已关闭");
await expect(page.getByRole("columnheader", { name: "等级" })).toHaveCount(0);
await expect(page.getByTestId("alarm-list-toolbar")).not.toContainText("等级");
await expect(page.locator("body")).not.toContainText("已恢复");
expect(listGets(mock)).toHaveLength(1);
expect(listGets(mock)[0].search).toContain("page=1");
expect(listGets(mock)[0].search).toContain("page_size=20");
expect(listGets(mock)[0].search).toContain("sort_by=last_occurred_at");
await page.getByTestId("alarm-filter-scenario").locator("input").fill("不会命中");
expect(listGets(mock)).toHaveLength(1);
await page.getByTestId("alarm-filter-search").click();
await expect(page.getByTestId("alarm-no-match")).toContainText("没有符合条件的报警");
expect(listGets(mock).at(-1)?.search).toContain("scenario_name=");
await page.screenshot({ path: path.join(evidenceDir, "U06-no-match-1440x900.png") });
await page.getByTestId("alarm-filter-reset").click();
await expect(page.getByTestId("alarm-table")).toBeVisible();
await page.getByRole("columnheader", { name: "模块" }).click();
await expect.poll(() => listGets(mock).at(-1)?.search ?? "").toContain("sort_by=module_key");
await expect.poll(() => listGets(mock).at(-1)?.search ?? "").toContain("sort_order=asc");
await page.getByTestId(`alarm-row-${PENDING}`).getByTestId("alarm-open").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("待处理");
await expect(page.getByTestId("footer-claim")).toBeVisible();
await expect(page.getByTestId("footer-close")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await expect(page.locator("body")).not.toContainText("计划时间");
await expect(page.locator("body")).not.toContainText("规则原文");
await page.getByTestId("footer-claim").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("处理中");
await expect(page.getByTestId("alarm-handler")).toContainText(SUBJECT);
const claim = mock.requests.find((item) => item.pathname.endsWith("/claim"));
expect(claim?.key).toBeTruthy();
await page.getByTestId("footer-progress").click();
await page.getByTestId("progress-submit").click();
await expect(page.getByTestId("alarm-progress-dialog")).toBeVisible();
await expect(page.getByText("请填写说明")).toBeVisible();
await page.getByTestId("progress-note").locator("textarea").fill("已现场核对");
await page.getByTestId("progress-submit").click();
await expect(page.getByTestId("alarm-history")).toContainText("已现场核对");
await page.getByTestId("footer-close").click();
await page.getByTestId("close-submit").click();
await expect(page.getByTestId("alarm-close-dialog")).toBeVisible();
await expect(page.getByText("请选择关闭结果")).toBeVisible();
await page.getByTestId("close-result").click();
await page.getByRole("option", { name: "已处理" }).click();
await page.getByTestId("close-note").locator("textarea").fill("可以关闭");
await page.getByTestId("close-submit").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await expect(page.getByTestId("footer-close")).toHaveCount(0);
await expect(page.getByTestId("alarm-close-dialog")).toBeHidden();
await expect(page.locator("body")).not.toContainText("已恢复");
await expect(page.locator("body")).not.toContainText(SERVER_SECRET);
await page.screenshot({ path: path.join(evidenceDir, "U06-closed-1440x900.png") });
});
test("a viewer does not see handling buttons", async ({ page }) => {
await signIn(page, ["watchman-viewer"]);
await mockAlarms(page);
await page.goto(`/#/alarms/${PENDING}`);
await expect(page.getByTestId("alarm-summary")).toBeVisible();
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await expect(page.getByTestId("footer-close")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "U06-viewer-1440x900.png") });
});
test("an admin can close another handler's alarm and cannot take it or write progress", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockAlarms(page);
await page.goto(`/#/alarms/${PROCESSING}`);
await expect(page.getByTestId("alarm-handler")).toContainText(OTHER);
await expect(page.getByTestId("footer-close")).toBeVisible();
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await page.getByTestId("footer-close").click();
await page.getByTestId("close-result").click();
await page.getByRole("option", { name: "误报" }).click();
await page.getByTestId("close-note").locator("textarea").fill("管理者关闭");
await page.getByTestId("close-submit").click();
await expect(page.getByTestId("alarm-detail-status")).toContainText("已关闭");
await expect(page.getByTestId("alarm-handler")).toContainText(OTHER);
await expect(page.getByTestId("footer-close")).toHaveCount(0);
});
test("a claim conflict refreshes and hides the server message", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
await mockAlarms(page, { claimConflict: true });
await page.goto(`/#/alarms/${PENDING}`);
await page.getByTestId("footer-claim").click();
await expect(page.getByTestId("alarm-command-error")).toContainText("已经有处理人");
await expect(page.getByTestId("alarm-command-error")).toContainText("页面已按最新状态刷新");
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.locator("body")).not.toContainText(SERVER_SECRET);
await page.screenshot({ path: path.join(evidenceDir, "U06-conflict-1440x900.png") });
});
test("a missing subject says there is no handling scope", async ({ page }) => {
await signIn(page, ["watchman-operator"], "");
await mockAlarms(page);
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-no-scope")).toContainText("没有处理范围,所以看不到报警");
await expect(page.getByTestId("alarm-empty")).toHaveCount(0);
await page.screenshot({ path: path.join(evidenceDir, "U06-no-scope-1440x900.png") });
});
test("an empty page is different from a filter miss", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
await mockAlarms(page, { alarms: [] });
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-empty")).toContainText("还没有报警");
await page.screenshot({ path: path.join(evidenceDir, "U06-empty-1440x900.png") });
});
test("a failed list can be retried without showing the server message", async ({ page }) => {
await signIn(page, ["watchman-operator"]);
await mockAlarms(page, { listFailuresLeft: 1 });
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-load-error")).toBeVisible();
await expect(page.getByTestId("alarm-load-error")).not.toContainText(SERVER_SECRET);
await page.screenshot({ path: path.join(evidenceDir, "U06-load-failed-1440x900.png") });
await page.getByTestId("alarm-retry").click();
await expect(page.getByTestId("alarm-table")).toBeVisible();
});
test("a closed alarm keeps the basis and only the back button", async ({ page }) => {
await signIn(page, ["watchman-admin"]);
await mockAlarms(page);
await page.goto(`/#/alarms/${CLOSED}`);
await expect(page.getByTestId("alarm-closed-basis-hint")).toContainText("报警保持关闭");
await expect(page.getByTestId("alarm-history")).toContainText("已核对尺寸");
await expect(page.getByTestId("footer-back")).toBeVisible();
await expect(page.getByTestId("footer-claim")).toHaveCount(0);
await expect(page.getByTestId("footer-progress")).toHaveCount(0);
await expect(page.getByTestId("footer-close")).toHaveCount(0);
await expect(page.locator("body")).not.toContainText("已恢复");
});
});
for (const viewport of [
{ name: "1440x900", width: 1440, height: 900 },
{ name: "1280x800", width: 1280, height: 800 },
{ name: "1920x1080", width: 1920, height: 1080 },
]) {
test(`list and detail stay in view at ${viewport.name}`, async ({ page }) => {
await page.setViewportSize({ width: viewport.width, height: viewport.height });
await signIn(page, ["watchman-operator"]);
await mockAlarms(page);
await page.goto("/#/alarms");
await expect(page.getByTestId("alarm-table")).toBeVisible();
await expect(page.getByTestId("alarm-pagination")).toBeVisible();
await expectInsideViewport(page, "alarm-pagination");
await noPageScroll(page);
await page.screenshot({ path: path.join(evidenceDir, `U06-list-${viewport.name}.png`) });
await page.getByTestId(`alarm-row-${CLOSED}`).getByTestId("alarm-open").click();
await expect(page.getByTestId("alarm-footer")).toBeVisible();
await page.getByTestId("alarm-scroll").evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
await expectInsideViewport(page, "alarm-footer");
await expect(page.getByTestId("alarm-summary")).toBeVisible();
await noPageScroll(page);
await page.screenshot({ path: path.join(evidenceDir, `U06-detail-${viewport.name}.png`) });
});
}
+167
View File
@@ -38,6 +38,7 @@
"datasources": "Data sources",
"queries": "Queries",
"mappings": "Mappings & Rules",
"alarms": "Alarms",
"create": "New",
"detail": "Details",
"version": "Version v{no}"
@@ -453,5 +454,171 @@
"unsupported_engine": "This data source engine is not supported yet",
"unsupported_datasource": "This data source type is not supported yet"
}
},
"alarm": {
"list": {
"filterModule": "Module",
"filterScenario": "Scenario name",
"filterObject": "Object id",
"filterStatus": "Status",
"filterFrom": "Last seen from",
"filterTo": "Last seen to",
"filterSearch": "Search",
"filterReset": "Reset",
"loadFailed": "The alarm list could not be loaded",
"retry": "Retry",
"empty": "No alarms yet",
"emptyHint": "There are no alarms in the current handling scope.",
"noMatch": "No alarms match these filters",
"noMatchHint": "Change the filters, or reset them.",
"noScope": "No handling scope, so alarms stay hidden",
"noScopeHint": "This account has no subject that can see alarms. That does not mean the tenant has none.",
"forbidden": "No permission to view alarms",
"objectInvalid": "The object id must be a full id",
"timeOrder": "The start time cannot be later than the end time",
"resultSep": " · "
},
"columns": {
"module": "Module",
"scenario": "Scenario",
"object": "Object",
"lastOccurred": "Last seen",
"status": "Status",
"actions": "Actions"
},
"status": {
"pending": "Pending",
"processing": "In progress",
"closed": "Closed"
},
"closeResult": {
"resolved": "Handled",
"false_positive": "False positive"
},
"actions": {
"open": "Open",
"back": "Back to list",
"claim": "Handle",
"progress": "Add progress",
"close": "Close",
"submitting": "Submitting"
},
"role": {
"watchman-admin": "Admin",
"watchman-operator": "Operator",
"watchman-viewer": "Viewer"
},
"detail": {
"loading": "Loading alarm",
"loadFailed": "The alarm could not be loaded",
"sectionFailed": "Some sections did not load",
"notFound": "This alarm was not found",
"summary": "Summary",
"occurrences": "Observations",
"occurrencesHint": "Each observation shows only the time, cycle, and event returned by the API.",
"occurrencesEmpty": "No observations yet",
"evidence": "Basis",
"revisionEvidence": "Same-cycle revision basis",
"revisionEmpty": "No revision basis",
"closedBasis": "Basis after close",
"closedBasisEmpty": "No basis after close",
"closedBasisHint": "These records were kept after the alarm was closed. The alarm stays closed, and the last-seen time and observation count do not change because of them.",
"history": "Handling history",
"historyEmpty": "No handling history yet",
"fields": {
"status": "Status",
"scenario": "Scenario",
"module": "Module",
"scenarioKey": "Scenario key",
"object": "Object",
"count": "Observations",
"firstOccurred": "First seen",
"lastOccurred": "Last seen",
"handler": "Current handler",
"claimedAt": "Handling started at",
"closedAt": "Closed at",
"cycle": "Cycle",
"event": "Event",
"openedAt": "Opened at",
"updatedAt": "Updated at",
"previous": "Previous linked alarm",
"none": "None"
}
},
"occurrence": {
"observedAt": "Observed at",
"receivedAt": "Received at",
"cycle": "Cycle",
"event": "Event"
},
"evidenceCols": {
"receivedAt": "Received at",
"recordedAt": "Recorded at",
"observedAt": "Observed at",
"snapshotVersion": "Snapshot version",
"cycle": "Cycle",
"event": "Event"
},
"historyCols": {
"seq": "Seq",
"command": "Action",
"actor": "Actor",
"handler": "Handler",
"note": "Note",
"result": "Result",
"evidence": "Evidence ref",
"at": "Time"
},
"commandName": {
"claim": "Handle",
"progress": "Progress",
"close": "Close"
},
"progressDialog": {
"title": "Add progress",
"note": "Note",
"notePlaceholder": "What was done this time",
"evidence": "Evidence ref",
"evidencePlaceholder": "Optional",
"required": "A note is required",
"cancel": "Cancel",
"submit": "Save progress"
},
"closeDialog": {
"title": "Close alarm",
"result": "Close result",
"resultPlaceholder": "Choose a result",
"note": "Note",
"notePlaceholder": "Why it is being closed this way",
"evidence": "Evidence ref",
"evidencePlaceholder": "Optional",
"resultRequired": "Choose a close result",
"noteRequired": "A note is required",
"cancel": "Cancel",
"submit": "Confirm close"
},
"command": {
"claimed": "Handling started",
"progressSaved": "Progress saved",
"closed": "Closed",
"failed": "The action did not finish",
"conflictRefreshed": "The page was refreshed to the latest state"
},
"errors": {
"already_claimed": "This alarm already has a handler",
"not_current_handler": "Only the current handler can do this",
"illegal_transition": "This action is not available in the current state",
"already_closed": "This alarm is already closed",
"idempotency_payload_mismatch": "This submit id was already used for different content",
"handling_history_missing": "The handling record is incomplete. Refresh and try again",
"idempotency_key_required": "A submit id is missing. Try again",
"idempotency_key_too_long": "The submit id is too long",
"note_invalid": "The note is not valid",
"evidence_ref_invalid": "The evidence ref is not valid",
"close_result_invalid": "The close result is not valid",
"not_found": "This alarm was not found",
"forbidden": "Not allowed ({node})",
"forbiddenPlain": "Not allowed to finish this action"
}
}
}
+167
View File
@@ -38,6 +38,7 @@
"datasources": "แหล่งข้อมูล",
"queries": "คิวรี",
"mappings": "การแมปและกฎ",
"alarms": "การแจ้งเตือน",
"create": "สร้างใหม่",
"detail": "รายละเอียด",
"version": "เวอร์ชัน v{no}"
@@ -453,5 +454,171 @@
"unsupported_engine": "ยังไม่รองรับเอนจินของแหล่งข้อมูลนี้",
"unsupported_datasource": "ยังไม่รองรับแหล่งข้อมูลประเภทนี้"
}
},
"alarm": {
"list": {
"filterModule": "โมดูล",
"filterScenario": "ชื่อสถานการณ์",
"filterObject": "รหัสวัตถุ",
"filterStatus": "สถานะ",
"filterFrom": "เกิดล่าสุดตั้งแต่",
"filterTo": "เกิดล่าสุดถึง",
"filterSearch": "ค้นหา",
"filterReset": "ล้าง",
"loadFailed": "โหลดรายการแจ้งเตือนไม่สำเร็จ",
"retry": "ลองใหม่",
"empty": "ยังไม่มีการแจ้งเตือน",
"emptyHint": "ในช่วงการจัดการปัจจุบันยังไม่มีการแจ้งเตือน",
"noMatch": "ไม่มีการแจ้งเตือนที่ตรงเงื่อนไข",
"noMatchHint": "ลองเปลี่ยนตัวกรอง หรือกดล้าง",
"noScope": "ไม่มีขอบเขตการจัดการ จึงไม่เห็นการแจ้งเตือน",
"noScopeHint": "บัญชีนี้ไม่มีตัวตนที่ใช้ดูการแจ้งเตือน นี่ไม่ได้แปลว่าทั้งผู้เช่าไม่มีการแจ้งเตือน",
"forbidden": "ไม่มีสิทธิ์ดูการแจ้งเตือน",
"objectInvalid": "รหัสวัตถุต้องเป็นรหัสเต็ม",
"timeOrder": "เวลาเริ่มต้องไม่ช้ากว่าเวลาสิ้นสุด",
"resultSep": " · "
},
"columns": {
"module": "โมดูล",
"scenario": "สถานการณ์",
"object": "วัตถุ",
"lastOccurred": "เกิดล่าสุด",
"status": "สถานะ",
"actions": "การทำงาน"
},
"status": {
"pending": "รอดำเนินการ",
"processing": "กำลังดำเนินการ",
"closed": "ปิดแล้ว"
},
"closeResult": {
"resolved": "จัดการแล้ว",
"false_positive": "แจ้งผิด"
},
"actions": {
"open": "เปิด",
"back": "กลับรายการ",
"claim": "ดำเนินการ",
"progress": "เพิ่มความคืบหน้า",
"close": "ปิด",
"submitting": "กำลังส่ง"
},
"role": {
"watchman-admin": "ผู้ดูแล",
"watchman-operator": "ผู้ปฏิบัติ",
"watchman-viewer": "ผู้ดู"
},
"detail": {
"loading": "กำลังโหลดรายละเอียด",
"loadFailed": "โหลดรายละเอียดไม่สำเร็จ",
"sectionFailed": "บางส่วนโหลดไม่สำเร็จ",
"notFound": "ไม่พบการแจ้งเตือนนี้",
"summary": "สรุป",
"occurrences": "การสังเกต",
"occurrencesHint": "แต่ละรายการแสดงเฉพาะเวลา รอบ และเหตุการณ์ที่ส่วนต่อประสานส่งมา",
"occurrencesEmpty": "ยังไม่มีบันทึกการสังเกต",
"evidence": "หลักฐานประกอบ",
"revisionEvidence": "หลักฐานการแก้ไขในรอบเดียวกัน",
"revisionEmpty": "ไม่มีหลักฐานการแก้ไข",
"closedBasis": "หลักฐานหลังปิด",
"closedBasisEmpty": "ไม่มีหลักฐานหลังปิด",
"closedBasisHint": "บันทึกเหล่านี้เกิดหลังปิดรายการ การแจ้งเตือนยังคงปิดอยู่ เวลาที่เกิดล่าสุดและจำนวนการสังเกตไม่เปลี่ยนเพราะบันทึกเหล่านี้",
"history": "ประวัติการจัดการ",
"historyEmpty": "ยังไม่มีประวัติการจัดการ",
"fields": {
"status": "สถานะ",
"scenario": "สถานการณ์",
"module": "โมดูล",
"scenarioKey": "คีย์สถานการณ์",
"object": "วัตถุ",
"count": "จำนวนการสังเกต",
"firstOccurred": "เกิดครั้งแรก",
"lastOccurred": "เกิดล่าสุด",
"handler": "ผู้ดูแลปัจจุบัน",
"claimedAt": "เวลาเริ่มดำเนินการ",
"closedAt": "เวลาปิด",
"cycle": "รอบ",
"event": "เหตุการณ์",
"openedAt": "เวลาเปิด",
"updatedAt": "เวลาอัปเดต",
"previous": "การแจ้งเตือนที่เชื่อมไว้ก่อนหน้า",
"none": "ไม่มี"
}
},
"occurrence": {
"observedAt": "เวลาสังเกต",
"receivedAt": "เวลารับ",
"cycle": "รอบ",
"event": "เหตุการณ์"
},
"evidenceCols": {
"receivedAt": "เวลารับ",
"recordedAt": "เวลาบันทึก",
"observedAt": "เวลาสังเกต",
"snapshotVersion": "เวอร์ชันสแนปช็อต",
"cycle": "รอบ",
"event": "เหตุการณ์"
},
"historyCols": {
"seq": "ลำดับ",
"command": "การกระทำ",
"actor": "ผู้ทำ",
"handler": "ผู้ดูแล",
"note": "คำอธิบาย",
"result": "ผล",
"evidence": "อ้างอิงหลักฐาน",
"at": "เวลา"
},
"commandName": {
"claim": "ดำเนินการ",
"progress": "ความคืบหน้า",
"close": "ปิด"
},
"progressDialog": {
"title": "เพิ่มความคืบหน้า",
"note": "คำอธิบาย",
"notePlaceholder": "รอบนี้ทำอะไรไป",
"evidence": "อ้างอิงหลักฐาน",
"evidencePlaceholder": "ไม่บังคับ",
"required": "ต้องใส่คำอธิบาย",
"cancel": "ยกเลิก",
"submit": "บันทึกความคืบหน้า"
},
"closeDialog": {
"title": "ปิดการแจ้งเตือน",
"result": "ผลการปิด",
"resultPlaceholder": "เลือกผล",
"note": "คำอธิบาย",
"notePlaceholder": "ทำไมจึงปิดแบบนี้",
"evidence": "อ้างอิงหลักฐาน",
"evidencePlaceholder": "ไม่บังคับ",
"resultRequired": "กรุณาเลือกผลการปิด",
"noteRequired": "ต้องใส่คำอธิบาย",
"cancel": "ยกเลิก",
"submit": "ยืนยันการปิด"
},
"command": {
"claimed": "เริ่มดำเนินการแล้ว",
"progressSaved": "บันทึกความคืบหน้าแล้ว",
"closed": "ปิดแล้ว",
"failed": "การทำงานไม่เสร็จ",
"conflictRefreshed": "หน้านี้รีเฟรชเป็นสถานะล่าสุดแล้ว"
},
"errors": {
"already_claimed": "การแจ้งเตือนนี้มีผู้ดูแลแล้ว ดำเนินการซ้ำไม่ได้",
"not_current_handler": "ไม่ใช่ผู้ดูแลปัจจุบัน จึงทำรายการนี้ไม่ได้",
"illegal_transition": "สถานะปัจจุบันทำรายการนี้ไม่ได้",
"already_closed": "การแจ้งเตือนนี้ปิดแล้ว",
"idempotency_payload_mismatch": "รหัสส่งนี้ถูกใช้กับเนื้อหาอื่นแล้ว",
"handling_history_missing": "ประวัติการจัดการไม่ครบ โปรดรีเฟรชแล้วลองใหม่",
"idempotency_key_required": "ไม่มีรหัสส่ง โปรดลองใหม่",
"idempotency_key_too_long": "รหัสส่งยาวเกินไป",
"note_invalid": "คำอธิบายไม่ถูกต้อง",
"evidence_ref_invalid": "การอ้างอิงหลักฐานไม่ถูกต้อง",
"close_result_invalid": "ผลการปิดไม่ถูกต้อง",
"not_found": "ไม่พบการแจ้งเตือนนี้",
"forbidden": "ไม่มีสิทธิ์ ({node})",
"forbiddenPlain": "ไม่มีสิทธิ์ทำการนี้ให้เสร็จ"
}
}
}
+167
View File
@@ -39,6 +39,7 @@
"datasources": "数据源",
"queries": "查询",
"mappings": "映射与规则",
"alarms": "报警",
"create": "新建",
"detail": "详情",
"version": "版本 v{no}"
@@ -454,5 +455,171 @@
"unsupported_engine": "该数据源引擎暂不支持",
"unsupported_datasource": "该数据源类型暂不支持"
}
},
"alarm": {
"list": {
"filterModule": "模块",
"filterScenario": "场景名称",
"filterObject": "对象编号",
"filterStatus": "状态",
"filterFrom": "最近发生起",
"filterTo": "最近发生止",
"filterSearch": "查询",
"filterReset": "重置",
"loadFailed": "报警列表加载失败",
"retry": "重试",
"empty": "还没有报警",
"emptyHint": "当前处理范围内还没有报警。",
"noMatch": "没有符合条件的报警",
"noMatchHint": "试试改筛选条件,或点重置。",
"noScope": "没有处理范围,所以看不到报警",
"noScopeHint": "当前账号没有可用来查看报警的主体。这不是租户里没有报警。",
"forbidden": "没有查看报警的权限",
"objectInvalid": "对象编号需要是完整的编号",
"timeOrder": "开始时间不能晚于结束时间",
"resultSep": " · "
},
"columns": {
"module": "模块",
"scenario": "场景",
"object": "对象",
"lastOccurred": "最近发生",
"status": "状态",
"actions": "操作"
},
"status": {
"pending": "待处理",
"processing": "处理中",
"closed": "已关闭"
},
"closeResult": {
"resolved": "已处理",
"false_positive": "误报"
},
"actions": {
"open": "打开",
"back": "返回列表",
"claim": "处理",
"progress": "追加进展",
"close": "关闭",
"submitting": "提交中"
},
"role": {
"watchman-admin": "管理者",
"watchman-operator": "处理者",
"watchman-viewer": "查看者"
},
"detail": {
"loading": "报警详情加载中",
"loadFailed": "报警详情加载失败",
"sectionFailed": "部分内容没有载入",
"notFound": "没有找到这条报警",
"summary": "摘要",
"occurrences": "观测",
"occurrencesHint": "每条观测只显示接口里的时间、周期和事件。",
"occurrencesEmpty": "还没有观测记录",
"evidence": "依据",
"revisionEvidence": "同周期修订依据",
"revisionEmpty": "没有修订依据",
"closedBasis": "关闭后依据",
"closedBasisEmpty": "没有关闭后依据",
"closedBasisHint": "这些记录出现在关闭之后。报警保持关闭,最近发生时间和观测次数不会因此改变。",
"history": "处理历史",
"historyEmpty": "还没有处理记录",
"fields": {
"status": "状态",
"scenario": "场景",
"module": "模块",
"scenarioKey": "场景键",
"object": "对象",
"count": "观测次数",
"firstOccurred": "首次发生",
"lastOccurred": "最近发生",
"handler": "当前处理人",
"claimedAt": "开始处理时间",
"closedAt": "关闭时间",
"cycle": "周期",
"event": "事件",
"openedAt": "打开时间",
"updatedAt": "更新时间",
"previous": "关联的上一条报警",
"none": "无"
}
},
"occurrence": {
"observedAt": "观测时间",
"receivedAt": "接收时间",
"cycle": "周期",
"event": "事件"
},
"evidenceCols": {
"receivedAt": "接收时间",
"recordedAt": "记录时间",
"observedAt": "观测时间",
"snapshotVersion": "快照版本",
"cycle": "周期",
"event": "事件"
},
"historyCols": {
"seq": "序号",
"command": "动作",
"actor": "操作者",
"handler": "处理人",
"note": "说明",
"result": "结果",
"evidence": "证据引用",
"at": "时间"
},
"commandName": {
"claim": "处理",
"progress": "进展",
"close": "关闭"
},
"progressDialog": {
"title": "追加进展",
"note": "说明",
"notePlaceholder": "写这次处理做了什么",
"evidence": "证据引用",
"evidencePlaceholder": "选填",
"required": "请填写说明",
"cancel": "取消",
"submit": "保存进展"
},
"closeDialog": {
"title": "关闭报警",
"result": "关闭结果",
"resultPlaceholder": "选择结果",
"note": "说明",
"notePlaceholder": "说明为什么这样关闭",
"evidence": "证据引用",
"evidencePlaceholder": "选填",
"resultRequired": "请选择关闭结果",
"noteRequired": "请填写说明",
"cancel": "取消",
"submit": "确认关闭"
},
"command": {
"claimed": "已开始处理",
"progressSaved": "进展已保存",
"closed": "已关闭",
"failed": "操作未完成",
"conflictRefreshed": "页面已按最新状态刷新"
},
"errors": {
"already_claimed": "这条报警已经有处理人,不能再处理",
"not_current_handler": "不是当前处理人,不能完成这个操作",
"illegal_transition": "当前状态不能做这个操作",
"already_closed": "这条报警已经关闭",
"idempotency_payload_mismatch": "同一个提交编号被用在了不同的内容上",
"handling_history_missing": "处理记录不完整,请刷新后再试",
"idempotency_key_required": "缺少提交编号,请重试",
"idempotency_key_too_long": "提交编号过长",
"note_invalid": "说明不合法",
"evidence_ref_invalid": "证据引用不合法",
"close_result_invalid": "关闭结果不合法",
"not_found": "没有找到这条报警",
"forbidden": "没有权限({node})",
"forbiddenPlain": "没有权限完成这个操作"
}
}
}
+167
View File
@@ -38,6 +38,7 @@
"datasources": "資料來源",
"queries": "查詢",
"mappings": "映射與規則",
"alarms": "警報",
"create": "新增",
"detail": "詳情",
"version": "版本 v{no}"
@@ -453,5 +454,171 @@
"unsupported_engine": "該資料來源引擎暫不支援",
"unsupported_datasource": "該資料來源類型暫不支援"
}
},
"alarm": {
"list": {
"filterModule": "模組",
"filterScenario": "場景名稱",
"filterObject": "物件編號",
"filterStatus": "狀態",
"filterFrom": "最近發生起",
"filterTo": "最近發生止",
"filterSearch": "查詢",
"filterReset": "重設",
"loadFailed": "警報清單載入失敗",
"retry": "重試",
"empty": "還沒有警報",
"emptyHint": "目前處理範圍內還沒有警報。",
"noMatch": "沒有符合條件的警報",
"noMatchHint": "試試改篩選條件,或點重設。",
"noScope": "沒有處理範圍,所以看不到警報",
"noScopeHint": "目前帳號沒有可用來查看警報的主體。這不是租戶裡沒有警報。",
"forbidden": "沒有查看警報的權限",
"objectInvalid": "物件編號需要是完整的編號",
"timeOrder": "開始時間不能晚於結束時間",
"resultSep": " · "
},
"columns": {
"module": "模組",
"scenario": "場景",
"object": "物件",
"lastOccurred": "最近發生",
"status": "狀態",
"actions": "操作"
},
"status": {
"pending": "待處理",
"processing": "處理中",
"closed": "已關閉"
},
"closeResult": {
"resolved": "已處理",
"false_positive": "誤報"
},
"actions": {
"open": "打開",
"back": "返回清單",
"claim": "處理",
"progress": "追加進展",
"close": "關閉",
"submitting": "提交中"
},
"role": {
"watchman-admin": "管理者",
"watchman-operator": "處理者",
"watchman-viewer": "查看者"
},
"detail": {
"loading": "警報詳情載入中",
"loadFailed": "警報詳情載入失敗",
"sectionFailed": "部分內容沒有載入",
"notFound": "沒有找到這條警報",
"summary": "摘要",
"occurrences": "觀測",
"occurrencesHint": "每條觀測只顯示介面裡的時間、週期和事件。",
"occurrencesEmpty": "還沒有觀測記錄",
"evidence": "依據",
"revisionEvidence": "同週期修訂依據",
"revisionEmpty": "沒有修訂依據",
"closedBasis": "關閉後依據",
"closedBasisEmpty": "沒有關閉後依據",
"closedBasisHint": "這些記錄出現在關閉之後。警報保持關閉,最近發生時間和觀測次數不會因此改變。",
"history": "處理歷史",
"historyEmpty": "還沒有處理記錄",
"fields": {
"status": "狀態",
"scenario": "場景",
"module": "模組",
"scenarioKey": "場景鍵",
"object": "物件",
"count": "觀測次數",
"firstOccurred": "首次發生",
"lastOccurred": "最近發生",
"handler": "目前處理人",
"claimedAt": "開始處理時間",
"closedAt": "關閉時間",
"cycle": "週期",
"event": "事件",
"openedAt": "打開時間",
"updatedAt": "更新時間",
"previous": "關聯的上一條警報",
"none": "無"
}
},
"occurrence": {
"observedAt": "觀測時間",
"receivedAt": "接收時間",
"cycle": "週期",
"event": "事件"
},
"evidenceCols": {
"receivedAt": "接收時間",
"recordedAt": "記錄時間",
"observedAt": "觀測時間",
"snapshotVersion": "快照版本",
"cycle": "週期",
"event": "事件"
},
"historyCols": {
"seq": "序號",
"command": "動作",
"actor": "操作者",
"handler": "處理人",
"note": "說明",
"result": "結果",
"evidence": "證據引用",
"at": "時間"
},
"commandName": {
"claim": "處理",
"progress": "進展",
"close": "關閉"
},
"progressDialog": {
"title": "追加進展",
"note": "說明",
"notePlaceholder": "寫這次處理做了什麼",
"evidence": "證據引用",
"evidencePlaceholder": "選填",
"required": "請填寫說明",
"cancel": "取消",
"submit": "儲存進展"
},
"closeDialog": {
"title": "關閉警報",
"result": "關閉結果",
"resultPlaceholder": "選擇結果",
"note": "說明",
"notePlaceholder": "說明為什麼這樣關閉",
"evidence": "證據引用",
"evidencePlaceholder": "選填",
"resultRequired": "請選擇關閉結果",
"noteRequired": "請填寫說明",
"cancel": "取消",
"submit": "確認關閉"
},
"command": {
"claimed": "已開始處理",
"progressSaved": "進展已儲存",
"closed": "已關閉",
"failed": "操作未完成",
"conflictRefreshed": "頁面已按最新狀態重新整理"
},
"errors": {
"already_claimed": "這條警報已經有處理人,不能再處理",
"not_current_handler": "不是目前處理人,不能完成這個操作",
"illegal_transition": "目前狀態不能做這個操作",
"already_closed": "這條警報已經關閉",
"idempotency_payload_mismatch": "同一個提交編號被用在了不同的內容上",
"handling_history_missing": "處理記錄不完整,請重新整理後再試",
"idempotency_key_required": "缺少提交編號,請重試",
"idempotency_key_too_long": "提交編號過長",
"note_invalid": "說明不合法",
"evidence_ref_invalid": "證據引用不合法",
"close_result_invalid": "關閉結果不合法",
"not_found": "沒有找到這條警報",
"forbidden": "沒有權限({node})",
"forbiddenPlain": "沒有權限完成這個操作"
}
}
}
+9 -1
View File
@@ -18,7 +18,12 @@ const { t } = useI18n();
const route = useRoute();
const auth = useAuthStore();
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries", mappings: "/mappings" };
const CRUMB_LINKS: Record<string, string> = {
datasources: "/datasources",
queries: "/queries",
mappings: "/mappings",
alarms: "/alarms",
};
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
function crumbLink(key: string): string | undefined {
@@ -95,6 +100,9 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
<RouterLink to="/mappings" :class="linkClass" :active-class="activeClass" data-testid="nav-mappings">
{{ t("nav.mappings") }}
</RouterLink>
<RouterLink to="/alarms" :class="linkClass" :active-class="activeClass" data-testid="nav-alarms">
{{ t("nav.alarms") }}
</RouterLink>
</nav>
<div
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
+706
View File
@@ -0,0 +1,706 @@
<script setup lang="ts">
/**
* Alarm detail: summary, observations, evidence, and handling history.
* Boundary: footer commands follow the role rules. A closed alarm keeps only
* 返回. Server error text is not rendered. Closed basis is not a recovery.
* Depends on the alarm read APIs and the three command routes.
*/
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElMessage,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
type FormInstance,
type FormRules,
} from "element-plus";
import { useAuthStore } from "../stores/auth";
import {
ALARM_PERMISSION,
alarmCommandVisibility,
clearIdempotencyKey,
holdIdempotencyKey,
type IdempotencyHold,
} from "./actions";
import { appendProgress, claimAlarm, closeAlarm, getAlarm, listEvidence, listHistory, listOccurrences } from "./client";
import { describeAlarmError, isAlarmConflict, isAlarmForbidden, isAlarmNotFound } from "./errors";
import { formatDateTime } from "./format";
import type { AlarmRecord, ClosedBasis, EvidenceBundle, HistoryEvent, OccurrenceList } from "./types";
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const alarm = ref<AlarmRecord | null>(null);
const occurrences = ref<OccurrenceList["items"]>([]);
const evidence = ref<EvidenceBundle | null>(null);
const history = ref<HistoryEvent[]>([]);
const phase = ref<"loading" | "ready" | "error" | "forbidden" | "missing">("loading");
const loadError = ref("");
const sectionError = ref("");
const commandError = ref("");
const commandConflict = ref(false);
const commandBusy = ref(false);
const progressOpen = ref(false);
const closeOpen = ref(false);
const progressModel = reactive({ note: "", evidence: "" });
const closeModel = reactive({ result: "", note: "", evidence: "" });
const progressForm = ref<FormInstance>();
const closeForm = ref<FormInstance>();
const claimHold = ref<IdempotencyHold>(clearIdempotencyKey());
const progressHold = ref<IdempotencyHold>(clearIdempotencyKey());
const closeHold = ref<IdempotencyHold>(clearIdempotencyKey());
let loadSeq = 0;
const commands = computed(() =>
alarmCommandVisibility({
roles: auth.user?.roles ?? [],
subject: auth.user?.subject,
status: alarm.value?.status ?? "",
currentHandler: alarm.value?.current_handler ?? null,
}),
);
const progressRules = computed<FormRules>(() => ({
note: [{ required: true, whitespace: true, message: t("alarm.progressDialog.required"), trigger: "blur" }],
}));
const closeRules = computed<FormRules>(() => ({
result: [{ required: true, message: t("alarm.closeDialog.resultRequired"), trigger: "change" }],
note: [{ required: true, whitespace: true, message: t("alarm.closeDialog.noteRequired"), trigger: "blur" }],
}));
function newKey(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `alarm-${Date.now()}`;
}
function textOrNone(value: string | null | undefined): string {
if (value === null || value === undefined || value.trim() === "") {
return t("alarm.detail.fields.none");
}
return value;
}
function statusText(status: string): string {
const key = `alarm.status.${status}`;
return te(key) ? t(key) : status;
}
function statusTag(status: string): "warning" | "primary" | "info" {
if (status === "pending") {
return "warning";
}
if (status === "processing") {
return "primary";
}
return "info";
}
function named(group: string, value: string | null | undefined): string {
if (!value) {
return t("alarm.detail.fields.none");
}
const key = `alarm.${group}.${value}`;
return te(key) ? t(key) : value;
}
function roleText(role: string): string {
const key = `alarm.role.${role}`;
return te(key) ? t(key) : role;
}
function backToList(): void {
void router.push({ name: "alarm-list" });
}
function openPrevious(): void {
const id = alarm.value?.previous_alarm_id;
if (!id) {
return;
}
void router.push({ name: "alarm-detail", params: { id } });
}
async function load(): Promise<void> {
const id = String(route.params.id ?? "");
const seq = ++loadSeq;
phase.value = "loading";
loadError.value = "";
sectionError.value = "";
alarm.value = null;
occurrences.value = [];
evidence.value = null;
history.value = [];
if (!id) {
phase.value = "missing";
return;
}
const [alarmResult, occurrenceResult, evidenceResult, historyResult] = await Promise.allSettled([
getAlarm(id),
listOccurrences(id),
listEvidence(id),
listHistory(id),
]);
if (seq !== loadSeq) {
return;
}
if (alarmResult.status === "rejected") {
if (isAlarmNotFound(alarmResult.reason)) {
phase.value = "missing";
return;
}
phase.value = isAlarmForbidden(alarmResult.reason) ? "forbidden" : "error";
loadError.value = describeAlarmError(
alarmResult.reason,
t,
te,
"alarm.detail.loadFailed",
ALARM_PERMISSION.read,
);
return;
}
alarm.value = alarmResult.value;
if (occurrenceResult.status === "fulfilled") {
occurrences.value = occurrenceResult.value.items;
}
if (evidenceResult.status === "fulfilled") {
evidence.value = evidenceResult.value;
}
if (historyResult.status === "fulfilled") {
history.value = historyResult.value.items;
}
if (
occurrenceResult.status === "rejected" ||
evidenceResult.status === "rejected" ||
historyResult.status === "rejected"
) {
const reason =
(occurrenceResult.status === "rejected" && occurrenceResult.reason) ||
(evidenceResult.status === "rejected" && evidenceResult.reason) ||
(historyResult.status === "rejected" && historyResult.reason);
sectionError.value = describeAlarmError(reason, t, te, "alarm.detail.sectionFailed", ALARM_PERMISSION.read);
}
phase.value = "ready";
}
function permissionFor(command: "claim" | "progress" | "close"): string {
if (command === "claim") {
return ALARM_PERMISSION.take;
}
if (command === "progress") {
return ALARM_PERMISSION.progress;
}
return ALARM_PERMISSION.close;
}
async function runCommand(
command: "claim" | "progress" | "close",
send: () => Promise<unknown>,
): Promise<boolean> {
if (commandBusy.value) {
return false;
}
commandBusy.value = true;
commandError.value = "";
commandConflict.value = false;
try {
await send();
return true;
} catch (error) {
commandConflict.value = isAlarmConflict(error);
commandError.value = describeAlarmError(
error,
t,
te,
"alarm.command.failed",
permissionFor(command),
);
return false;
} finally {
commandBusy.value = false;
}
}
async function finishCommand(ok: boolean, successKey: string, closeDialog: () => void): Promise<void> {
if (ok) {
closeDialog();
ElMessage.success(t(successKey));
} else if (commandConflict.value) {
closeDialog();
}
await load();
}
async function onClaim(): Promise<void> {
const id = alarm.value?.id;
if (!id || !commands.value.claim) {
return;
}
claimHold.value = holdIdempotencyKey(claimHold.value, "claim", newKey);
const key = claimHold.value.key;
const ok = await runCommand("claim", () => claimAlarm(id, key));
if (ok) {
claimHold.value = clearIdempotencyKey();
}
await finishCommand(ok, "alarm.command.claimed", () => undefined);
}
async function openProgress(): Promise<void> {
progressModel.note = "";
progressModel.evidence = "";
commandError.value = "";
commandConflict.value = false;
progressOpen.value = true;
await nextTick();
progressForm.value?.clearValidate();
}
async function submitProgress(): Promise<void> {
const id = alarm.value?.id;
if (!id || !commands.value.progress || commandBusy.value) {
return;
}
const valid = await progressForm.value?.validate().catch(() => false);
if (!valid) {
return;
}
const note = progressModel.note.trim();
const evidenceRef = progressModel.evidence.trim();
const payload = JSON.stringify({ note, evidence_ref: evidenceRef });
progressHold.value = holdIdempotencyKey(progressHold.value, payload, newKey);
const body = evidenceRef ? { note, evidence_ref: evidenceRef } : { note };
const ok = await runCommand("progress", () => appendProgress(id, progressHold.value.key, body));
if (ok) {
progressHold.value = clearIdempotencyKey();
}
await finishCommand(ok, "alarm.command.progressSaved", () => {
progressOpen.value = false;
});
}
async function openClose(): Promise<void> {
closeModel.result = "";
closeModel.note = "";
closeModel.evidence = "";
commandError.value = "";
commandConflict.value = false;
closeOpen.value = true;
await nextTick();
closeForm.value?.clearValidate();
}
async function submitClose(): Promise<void> {
const id = alarm.value?.id;
if (!id || !commands.value.close || commandBusy.value) {
return;
}
const valid = await closeForm.value?.validate().catch(() => false);
if (!valid) {
return;
}
const note = closeModel.note.trim();
const evidenceRef = closeModel.evidence.trim();
const payload = JSON.stringify({ result: closeModel.result, note, evidence_ref: evidenceRef });
closeHold.value = holdIdempotencyKey(closeHold.value, payload, newKey);
const body = evidenceRef
? { result: closeModel.result, note, evidence_ref: evidenceRef }
: { result: closeModel.result, note };
const ok = await runCommand("close", () => closeAlarm(id, closeHold.value.key, body));
if (ok) {
closeHold.value = clearIdempotencyKey();
}
await finishCommand(ok, "alarm.command.closed", () => {
closeOpen.value = false;
});
}
function keepDialog(done: () => void): void {
if (commandBusy.value) {
return;
}
done();
}
watch(
() => route.params.id,
() => {
void load();
},
);
onMounted(() => {
void load();
});
</script>
<template>
<div class="flex h-full min-h-0 flex-col" data-testid="alarm-detail">
<div class="min-h-0 flex-1 overflow-y-auto p-5" data-testid="alarm-scroll">
<p v-if="phase === 'loading'" data-testid="alarm-detail-loading">{{ t("alarm.detail.loading") }}</p>
<ElAlert
v-else-if="phase === 'missing'"
type="warning"
data-testid="alarm-missing"
:title="t('alarm.detail.notFound')"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="phase === 'forbidden' || phase === 'error'"
type="error"
data-testid="alarm-detail-error"
:title="loadError || t('alarm.detail.loadFailed')"
show-icon
:closable="false"
/>
<template v-else-if="alarm">
<ElAlert
v-if="commandError"
class="mb-3.5"
:type="commandConflict ? 'warning' : 'error'"
data-testid="alarm-command-error"
:title="commandError"
:description="commandConflict ? t('alarm.command.conflictRefreshed') : undefined"
show-icon
:closable="false"
/>
<ElAlert
v-if="sectionError"
class="mb-3.5"
type="error"
data-testid="alarm-section-error"
:title="sectionError"
show-icon
:closable="false"
/>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-summary">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.summary") }}</h3>
<dl class="grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.status") }}</dt>
<dd>
<ElTag :type="statusTag(alarm.status)" effect="light" data-testid="alarm-detail-status">
{{ statusText(alarm.status) }}
</ElTag>
<span v-if="alarm.close_result">
{{ t("alarm.list.resultSep") }}{{ named("closeResult", alarm.close_result) }}
</span>
</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.scenario") }}</dt>
<dd>{{ alarm.scenario_name }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.module") }}</dt>
<dd>{{ alarm.module_key }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.scenarioKey") }}</dt>
<dd>{{ alarm.scenario_key }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.object") }}</dt>
<dd data-testid="alarm-identity">{{ alarm.identity_key }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.count") }}</dt>
<dd>{{ alarm.occurrence_count }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.firstOccurred") }}</dt>
<dd>{{ formatDateTime(alarm.first_occurred_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.lastOccurred") }}</dt>
<dd>{{ formatDateTime(alarm.last_occurred_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.handler") }}</dt>
<dd data-testid="alarm-handler">{{ textOrNone(alarm.current_handler) }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.claimedAt") }}</dt>
<dd>{{ formatDateTime(alarm.claimed_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.closedAt") }}</dt>
<dd>{{ formatDateTime(alarm.closed_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.cycle") }}</dt>
<dd>{{ textOrNone(alarm.cycle_key) }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.event") }}</dt>
<dd>{{ textOrNone(alarm.event_key) }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.openedAt") }}</dt>
<dd>{{ formatDateTime(alarm.opened_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.updatedAt") }}</dt>
<dd>{{ formatDateTime(alarm.updated_at) || t("alarm.detail.fields.none") }}</dd>
</div>
<div>
<dt class="text-[var(--text-muted)]">{{ t("alarm.detail.fields.previous") }}</dt>
<dd>
<ElButton
v-if="alarm.previous_alarm_id"
link
type="primary"
data-testid="alarm-previous"
@click="openPrevious"
>
{{ alarm.previous_alarm_id }}
</ElButton>
<span v-else>{{ t("alarm.detail.fields.none") }}</span>
</dd>
</div>
</dl>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-occurrences">
<h3 class="mb-1 text-[14.5px] font-semibold">{{ t("alarm.detail.occurrences") }}</h3>
<p class="mb-2.5 text-[var(--text-muted)]">{{ t("alarm.detail.occurrencesHint") }}</p>
<ElTable :data="occurrences" row-key="id" :empty-text="t('alarm.detail.occurrencesEmpty')">
<ElTableColumn :label="t('alarm.occurrence.observedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.observed_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.occurrence.receivedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="cycle_key" :label="t('alarm.occurrence.cycle')" min-width="120" />
<ElTableColumn prop="event_key" :label="t('alarm.occurrence.event')" min-width="120" />
</ElTable>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-evidence">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.evidence") }}</h3>
<h4 class="mb-2 font-semibold">{{ t("alarm.detail.revisionEvidence") }}</h4>
<ElTable
:data="evidence?.revision_evidence ?? []"
row-key="id"
:empty-text="t('alarm.detail.revisionEmpty')"
>
<ElTableColumn :label="t('alarm.evidenceCols.receivedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.evidenceCols.recordedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.recorded_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="snapshot_version_no" :label="t('alarm.evidenceCols.snapshotVersion')" min-width="110" />
</ElTable>
<h4 class="mb-1 mt-4 font-semibold">{{ t("alarm.detail.closedBasis") }}</h4>
<p class="mb-2.5 text-[var(--text-muted)]" data-testid="alarm-closed-basis-hint">
{{ t("alarm.detail.closedBasisHint") }}
</p>
<ElTable :data="evidence?.closed_basis ?? []" row-key="id" :empty-text="t('alarm.detail.closedBasisEmpty')">
<ElTableColumn :label="t('alarm.evidenceCols.observedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime((row as ClosedBasis).observed_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.evidenceCols.receivedAt')" min-width="160">
<template #default="{ row }">{{ formatDateTime(row.received_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="cycle_key" :label="t('alarm.evidenceCols.cycle')" min-width="120" />
<ElTableColumn prop="event_key" :label="t('alarm.evidenceCols.event')" min-width="120" />
</ElTable>
</section>
<section class="mb-4 rounded-lg border border-[var(--border-subtle)] bg-white px-[18px] py-4" data-testid="alarm-history">
<h3 class="mb-3 text-[14.5px] font-semibold">{{ t("alarm.detail.history") }}</h3>
<ElTable :data="history" row-key="id" :empty-text="t('alarm.detail.historyEmpty')">
<ElTableColumn prop="seq" :label="t('alarm.historyCols.seq')" width="72" />
<ElTableColumn :label="t('alarm.historyCols.command')" min-width="100">
<template #default="{ row }">{{ named("commandName", (row as HistoryEvent).command) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.historyCols.actor')" min-width="140">
<template #default="{ row }">
{{ (row as HistoryEvent).actor_subject }}
{{ roleText((row as HistoryEvent).actor_role) }}
</template>
</ElTableColumn>
<ElTableColumn prop="handler_subject" :label="t('alarm.historyCols.handler')" min-width="120" />
<ElTableColumn :label="t('alarm.historyCols.note')" min-width="180">
<template #default="{ row }">{{ textOrNone((row as HistoryEvent).note) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.historyCols.result')" min-width="100">
<template #default="{ row }">{{ named("closeResult", (row as HistoryEvent).close_result) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.historyCols.evidence')" min-width="140">
<template #default="{ row }">{{ textOrNone((row as HistoryEvent).evidence_ref) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.historyCols.at')" min-width="160">
<template #default="{ row }">{{ formatDateTime((row as HistoryEvent).recorded_at) }}</template>
</ElTableColumn>
</ElTable>
</section>
</template>
</div>
<footer
data-testid="alarm-footer"
class="flex shrink-0 flex-wrap items-center justify-center gap-2 border-t border-[var(--border-subtle)] bg-white px-5 py-3"
>
<ElButton data-testid="footer-back" :disabled="commandBusy" @click="backToList">
{{ t("alarm.actions.back") }}
</ElButton>
<template v-if="phase === 'ready' && alarm && alarm.status !== 'closed'">
<ElButton
v-if="commands.claim"
type="primary"
data-testid="footer-claim"
:loading="commandBusy"
@click="onClaim"
>
{{ t("alarm.actions.claim") }}
</ElButton>
<ElButton
v-if="commands.progress"
data-testid="footer-progress"
:disabled="commandBusy"
@click="openProgress"
>
{{ t("alarm.actions.progress") }}
</ElButton>
<ElButton
v-if="commands.close"
type="primary"
data-testid="footer-close"
:disabled="commandBusy"
@click="openClose"
>
{{ t("alarm.actions.close") }}
</ElButton>
</template>
</footer>
<ElDialog
v-model="progressOpen"
align-center
append-to-body
:close-on-click-modal="false"
:before-close="keepDialog"
:title="t('alarm.progressDialog.title')"
width="480px"
data-testid="alarm-progress-dialog"
>
<ElAlert
v-if="commandError && progressOpen"
class="mb-3"
type="error"
:title="commandError"
show-icon
:closable="false"
/>
<ElForm
ref="progressForm"
:model="progressModel"
:rules="progressRules"
label-position="top"
@submit.prevent
>
<ElFormItem :label="t('alarm.progressDialog.note')" prop="note" data-testid="progress-note">
<ElInput
v-model="progressModel.note"
type="textarea"
:rows="4"
maxlength="2000"
:placeholder="t('alarm.progressDialog.notePlaceholder')"
/>
</ElFormItem>
<ElFormItem :label="t('alarm.progressDialog.evidence')" data-testid="progress-evidence">
<ElInput
v-model="progressModel.evidence"
maxlength="512"
:placeholder="t('alarm.progressDialog.evidencePlaceholder')"
/>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="commandBusy" @click="progressOpen = false">
{{ t("alarm.progressDialog.cancel") }}
</ElButton>
<ElButton type="primary" data-testid="progress-submit" :loading="commandBusy" @click="submitProgress">
{{ commandBusy ? t("alarm.actions.submitting") : t("alarm.progressDialog.submit") }}
</ElButton>
</template>
</ElDialog>
<ElDialog
v-model="closeOpen"
align-center
append-to-body
:close-on-click-modal="false"
:before-close="keepDialog"
:title="t('alarm.closeDialog.title')"
width="480px"
data-testid="alarm-close-dialog"
>
<ElAlert
v-if="commandError && closeOpen"
class="mb-3"
type="error"
:title="commandError"
show-icon
:closable="false"
/>
<ElForm
ref="closeForm"
:model="closeModel"
:rules="closeRules"
label-position="top"
@submit.prevent
>
<ElFormItem :label="t('alarm.closeDialog.result')" prop="result" data-testid="close-result">
<ElSelect v-model="closeModel.result" class="w-full" :placeholder="t('alarm.closeDialog.resultPlaceholder')">
<ElOption :label="t('alarm.closeResult.resolved')" value="resolved" />
<ElOption :label="t('alarm.closeResult.false_positive')" value="false_positive" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('alarm.closeDialog.note')" prop="note" data-testid="close-note">
<ElInput
v-model="closeModel.note"
type="textarea"
:rows="4"
maxlength="2000"
:placeholder="t('alarm.closeDialog.notePlaceholder')"
/>
</ElFormItem>
<ElFormItem :label="t('alarm.closeDialog.evidence')" data-testid="close-evidence">
<ElInput
v-model="closeModel.evidence"
maxlength="512"
:placeholder="t('alarm.closeDialog.evidencePlaceholder')"
/>
</ElFormItem>
</ElForm>
<template #footer>
<ElButton :disabled="commandBusy" @click="closeOpen = false">
{{ t("alarm.closeDialog.cancel") }}
</ElButton>
<ElButton type="primary" data-testid="close-submit" :loading="commandBusy" @click="submitClose">
{{ commandBusy ? t("alarm.actions.submitting") : t("alarm.closeDialog.submit") }}
</ElButton>
</template>
</ElDialog>
</div>
</template>
+362
View File
@@ -0,0 +1,362 @@
<script setup lang="ts">
/**
* Alarm list. Filters stay local until 查询. Sort and page are server-side.
* Boundary: no severity filter or column (D39). Empty copy distinguishes no
* alarms, no match, and no handling subject. Row action is 打开 only.
* Depends on the alarm list API and the signed-in subject.
*/
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import {
ElAlert,
ElButton,
ElDatePicker,
ElInput,
ElOption,
ElPagination,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
vLoading,
} from "element-plus";
import { LIST_DEFAULT_PAGE_SIZE, LIST_PAGE_SIZES, actionsColumnWidth } from "../tableLayout";
import { useAuthStore } from "../stores/auth";
import { ALARM_PERMISSION, alarmListEmptyKind, hasAlarmSubject } from "./actions";
import { listAlarms } from "./client";
import { describeAlarmError, isAlarmForbidden } from "./errors";
import {
alarmFilterIssue,
alarmFiltersActive,
alarmListParams,
emptyAlarmFilters,
type AlarmFilterDraft,
} from "./filters";
import { formatDateTime } from "./format";
import type { AlarmRecord } from "./types";
const { t, te } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const items = ref<AlarmRecord[]>([]);
const total = ref(0);
const phase = ref<"loading" | "ready" | "error" | "forbidden">("loading");
const loadError = ref("");
const filterIssue = ref<"object" | "time-order" | null>(null);
const draft = reactive<AlarmFilterDraft>(emptyAlarmFilters());
const applied = reactive<AlarmFilterDraft>(emptyAlarmFilters());
const page = ref(1);
const pageSize = ref(LIST_DEFAULT_PAGE_SIZE);
const sortBy = ref("last_occurred_at");
const sortOrder = ref<"asc" | "desc">("desc");
const actionsWidth = actionsColumnWidth(1);
const hasSubject = computed(() => hasAlarmSubject(auth.user?.subject));
const hasFilters = computed(() => alarmFiltersActive(applied));
const emptyKind = computed(() =>
alarmListEmptyKind({
phase: phase.value,
total: total.value,
hasSubject: hasSubject.value,
hasFilters: hasFilters.value,
}),
);
const showTable = computed(() => phase.value === "loading" || (phase.value === "ready" && total.value > 0));
const showPager = computed(
() => emptyKind.value === "none" && (phase.value === "loading" || total.value > 0),
);
function copyFilters(target: AlarmFilterDraft, source: AlarmFilterDraft): void {
target.moduleKey = source.moduleKey;
target.scenarioName = source.scenarioName;
target.objectId = source.objectId;
target.status = source.status;
target.from = source.from;
target.to = source.to;
}
async function load(): Promise<void> {
phase.value = "loading";
loadError.value = "";
try {
const result = await listAlarms(
alarmListParams(applied, {
sortBy: sortBy.value,
sortOrder: sortOrder.value,
page: page.value,
pageSize: pageSize.value,
}),
);
items.value = result.items;
total.value = result.total;
phase.value = "ready";
} catch (error) {
items.value = [];
total.value = 0;
if (isAlarmForbidden(error)) {
phase.value = "forbidden";
loadError.value = describeAlarmError(error, t, te, "alarm.list.loadFailed", ALARM_PERMISSION.read);
return;
}
phase.value = "error";
loadError.value = describeAlarmError(error, t, te, "alarm.list.loadFailed", ALARM_PERMISSION.read);
}
}
function applyFilters(): void {
const issue = alarmFilterIssue(draft);
filterIssue.value = issue;
if (issue) {
return;
}
copyFilters(applied, draft);
page.value = 1;
void load();
}
function resetFilters(): void {
const blank = emptyAlarmFilters();
copyFilters(draft, blank);
copyFilters(applied, blank);
filterIssue.value = null;
page.value = 1;
void load();
}
function onSortChange(payload: { prop: string | null; order: string | null }): void {
const sortable = new Set(["module_key", "scenario_name", "last_occurred_at", "status"]);
if (!payload.prop || !payload.order || !sortable.has(payload.prop)) {
sortBy.value = "last_occurred_at";
sortOrder.value = "desc";
} else {
sortBy.value = payload.prop;
sortOrder.value = payload.order === "ascending" ? "asc" : "desc";
}
page.value = 1;
void load();
}
function onPageChange(next: number): void {
page.value = next;
void load();
}
function onSizeChange(next: number): void {
pageSize.value = next;
page.value = 1;
void load();
}
function statusText(status: string): string {
const key = `alarm.status.${status}`;
return te(key) ? t(key) : status;
}
function statusTag(status: string): "warning" | "primary" | "info" {
if (status === "pending") {
return "warning";
}
if (status === "processing") {
return "primary";
}
return "info";
}
function closeResultText(value: string | null): string {
if (!value) {
return "";
}
const key = `alarm.closeResult.${value}`;
return te(key) ? t(key) : value;
}
function openDetail(source: unknown): void {
const row = source as AlarmRecord;
void router.push({ name: "alarm-detail", params: { id: row.id } });
}
onMounted(() => {
void load();
});
</script>
<template>
<div class="flex h-full min-h-0 flex-col overflow-hidden" data-testid="alarm-list">
<div class="flex shrink-0 flex-wrap items-center gap-2 px-5 pb-3 pt-5" data-testid="alarm-list-toolbar">
<div class="w-[140px]" data-testid="alarm-filter-module">
<ElInput v-model="draft.moduleKey" clearable :placeholder="t('alarm.list.filterModule')" />
</div>
<div class="w-[180px]" data-testid="alarm-filter-scenario">
<ElInput v-model="draft.scenarioName" clearable :placeholder="t('alarm.list.filterScenario')" />
</div>
<div class="w-[220px]" data-testid="alarm-filter-object">
<ElInput v-model="draft.objectId" clearable :placeholder="t('alarm.list.filterObject')" />
</div>
<div class="w-[200px]" data-testid="alarm-filter-from">
<ElDatePicker
v-model="draft.from"
style="width: 100%"
type="datetime"
:placeholder="t('alarm.list.filterFrom')"
/>
</div>
<div class="w-[200px]" data-testid="alarm-filter-to">
<ElDatePicker
v-model="draft.to"
style="width: 100%"
type="datetime"
:placeholder="t('alarm.list.filterTo')"
/>
</div>
<div class="w-[120px]" data-testid="alarm-filter-status">
<ElSelect v-model="draft.status" clearable class="w-full" :placeholder="t('alarm.list.filterStatus')">
<ElOption :label="t('alarm.status.pending')" value="pending" />
<ElOption :label="t('alarm.status.processing')" value="processing" />
<ElOption :label="t('alarm.status.closed')" value="closed" />
</ElSelect>
</div>
<ElButton type="primary" data-testid="alarm-filter-search" @click="applyFilters">
{{ t("alarm.list.filterSearch") }}
</ElButton>
<ElButton data-testid="alarm-filter-reset" @click="resetFilters">
{{ t("alarm.list.filterReset") }}
</ElButton>
</div>
<div class="flex min-h-0 flex-1 flex-col px-5">
<ElAlert
v-if="filterIssue"
class="mb-3"
type="warning"
data-testid="alarm-filter-issue"
:title="filterIssue === 'object' ? t('alarm.list.objectInvalid') : t('alarm.list.timeOrder')"
show-icon
:closable="false"
/>
<ElAlert
v-if="phase === 'error'"
type="error"
data-testid="alarm-load-error"
:title="loadError"
show-icon
:closable="false"
/>
<div v-if="phase === 'error'" class="mt-3">
<ElButton data-testid="alarm-retry" @click="load">{{ t("alarm.list.retry") }}</ElButton>
</div>
<div
v-else-if="phase === 'forbidden'"
data-testid="alarm-forbidden"
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<div>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.forbidden") }}</h3>
<p class="text-[var(--text-secondary)]">{{ loadError }}</p>
</div>
</div>
<div
v-else-if="emptyKind === 'no-scope'"
data-testid="alarm-no-scope"
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<div>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.noScope") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.noScopeHint") }}</p>
</div>
</div>
<div
v-else-if="emptyKind === 'empty'"
data-testid="alarm-empty"
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<div>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.empty") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.emptyHint") }}</p>
</div>
</div>
<div
v-else-if="emptyKind === 'no-match'"
data-testid="alarm-no-match"
class="flex flex-1 items-center justify-center rounded-lg border border-dashed border-[var(--border-default)] bg-white px-5 py-14 text-center"
>
<div>
<h3 class="mb-1.5 text-[15px] font-semibold">{{ t("alarm.list.noMatch") }}</h3>
<p class="text-[var(--text-secondary)]">{{ t("alarm.list.noMatchHint") }}</p>
</div>
</div>
<div v-else-if="showTable" class="min-h-0 flex-1" data-testid="alarm-table-wrap">
<ElTable
v-loading="phase === 'loading'"
height="100%"
:data="items"
row-key="id"
data-testid="alarm-table"
:default-sort="{ prop: 'last_occurred_at', order: 'descending' }"
@sort-change="onSortChange"
>
<ElTableColumn
prop="module_key"
:label="t('alarm.columns.module')"
min-width="120"
sortable="custom"
/>
<ElTableColumn
prop="scenario_name"
:label="t('alarm.columns.scenario')"
min-width="160"
sortable="custom"
/>
<ElTableColumn prop="identity_key" :label="t('alarm.columns.object')" min-width="140" />
<ElTableColumn
prop="last_occurred_at"
:label="t('alarm.columns.lastOccurred')"
min-width="160"
sortable="custom"
>
<template #default="{ row }">{{ formatDateTime(row.last_occurred_at) }}</template>
</ElTableColumn>
<ElTableColumn prop="status" :label="t('alarm.columns.status')" min-width="140" sortable="custom">
<template #default="{ row }">
<ElTag :type="statusTag(row.status)" effect="light" data-testid="alarm-status">
{{ statusText(row.status) }}
</ElTag>
<span v-if="row.status === 'closed' && row.close_result">
{{ t("alarm.list.resultSep") }}{{ closeResultText(row.close_result) }}
</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('alarm.columns.actions')" :width="actionsWidth" align="right" fixed="right">
<template #default="{ row }">
<div class="whitespace-nowrap" :data-testid="`alarm-row-${row.id}`">
<ElButton link type="primary" data-testid="alarm-open" @click="openDetail(row)">
{{ t("alarm.actions.open") }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
</div>
</div>
<footer
v-if="showPager"
data-testid="alarm-pagination"
class="flex shrink-0 items-center justify-end border-t border-[var(--border-subtle)] bg-white px-5 py-3"
>
<ElPagination
background
layout="total, sizes, prev, pager, next"
:total="total"
:page-size="pageSize"
:page-sizes="[...LIST_PAGE_SIZES]"
:current-page="page"
@current-change="onPageChange"
@size-change="onSizeChange"
/>
</footer>
</div>
</template>
+143
View File
@@ -0,0 +1,143 @@
/**
* Command visibility, empty-state choice, and idempotency reuse.
* Covers D39: viewer hides commands, admin cannot steal a handler or write for them.
*/
import { describe, expect, it } from "vitest";
import {
alarmCommandVisibility,
alarmListEmptyKind,
clearIdempotencyKey,
hasAlarmSubject,
holdIdempotencyKey,
} from "./actions";
const admin = ["watchman-admin"];
const operator = ["watchman-operator"];
const viewer = ["watchman-viewer"];
describe("alarm command visibility", () => {
it("hides every command from a viewer, including a pending alarm", () => {
expect(
alarmCommandVisibility({
roles: viewer,
subject: "subj-chen",
status: "pending",
currentHandler: null,
}),
).toEqual({ claim: false, progress: false, close: false });
});
it("lets an operator claim a pending alarm and nothing else", () => {
expect(
alarmCommandVisibility({
roles: operator,
subject: "subj-chen",
status: "pending",
currentHandler: null,
}),
).toEqual({ claim: true, progress: false, close: false });
});
it("lets the current handler add progress and close, and hides claim", () => {
expect(
alarmCommandVisibility({
roles: operator,
subject: "subj-chen",
status: "processing",
currentHandler: "subj-chen",
}),
).toEqual({ claim: false, progress: true, close: true });
});
it("hides claim, progress, and close when someone else is the handler", () => {
expect(
alarmCommandVisibility({
roles: operator,
subject: "subj-zhao",
status: "processing",
currentHandler: "subj-lin",
}),
).toEqual({ claim: false, progress: false, close: false });
});
it("lets an admin close another handler's alarm without taking it or writing progress", () => {
expect(
alarmCommandVisibility({
roles: admin,
subject: "subj-chen",
status: "processing",
currentHandler: "subj-lin",
}),
).toEqual({ claim: false, progress: false, close: true });
});
it("lets an admin who is the handler write progress and close", () => {
expect(
alarmCommandVisibility({
roles: [...admin, ...viewer],
subject: "subj-chen",
status: "processing",
currentHandler: "subj-chen",
}),
).toEqual({ claim: false, progress: true, close: true });
});
it("leaves only the back action after close, including for an admin", () => {
expect(
alarmCommandVisibility({
roles: admin,
subject: "subj-chen",
status: "closed",
currentHandler: "subj-lin",
}),
).toEqual({ claim: false, progress: false, close: false });
});
it("hides commands when the session has no handling subject", () => {
expect(hasAlarmSubject(" ")).toBe(false);
expect(hasAlarmSubject("a\nb")).toBe(false);
expect(hasAlarmSubject("subj-chen")).toBe(true);
expect(
alarmCommandVisibility({
roles: admin,
subject: "",
status: "processing",
currentHandler: "subj-lin",
}),
).toEqual({ claim: false, progress: false, close: false });
});
});
describe("alarm list empty kind", () => {
it("uses no-scope before the other empty copies", () => {
expect(
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: false, hasFilters: true }),
).toBe("no-scope");
expect(
alarmListEmptyKind({ phase: "ready", total: 3, hasSubject: false, hasFilters: false }),
).toBe("no-scope");
expect(
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: true, hasFilters: false }),
).toBe("empty");
expect(
alarmListEmptyKind({ phase: "ready", total: 0, hasSubject: true, hasFilters: true }),
).toBe("no-match");
expect(
alarmListEmptyKind({ phase: "ready", total: 2, hasSubject: true, hasFilters: false }),
).toBe("none");
expect(
alarmListEmptyKind({ phase: "forbidden", total: 0, hasSubject: false, hasFilters: false }),
).toBe("none");
});
});
describe("idempotency hold", () => {
it("reuses the key until the payload changes", () => {
const first = holdIdempotencyKey(clearIdempotencyKey(), "note-a", () => "k1");
const again = holdIdempotencyKey(first, "note-a", () => "k2");
const edited = holdIdempotencyKey(again, "note-b", () => "k3");
expect(again).toEqual({ key: "k1", payload: "note-a" });
expect(edited).toEqual({ key: "k3", payload: "note-b" });
});
});
+115
View File
@@ -0,0 +1,115 @@
/**
* Which handling buttons the signed-in role may see.
* Boundary: presentation only. The API still accepts or rejects the command.
* Depends on the session role, the snapshot subject, and the alarm status.
*/
export const ALARM_PERMISSION = {
read: "perm:data:emp:watchman.alarm.read",
take: "perm:data:emp:watchman.alarm.take",
progress: "perm:data:emp:watchman.alarm.progress",
close: "perm:data:emp:watchman.alarm.close",
} as const;
const ROLE_ADMIN = "watchman-admin";
const ROLE_OPERATOR = "watchman-operator";
export type AlarmCommandVisibility = {
claim: boolean;
progress: boolean;
close: boolean;
};
const HIDDEN: AlarmCommandVisibility = { claim: false, progress: false, close: false };
/**
* A blank subject has no handling scope. Newlines match the read API, which
* treats that session as having no subject. This does not grant access.
*/
export function hasAlarmSubject(subject: string | null | undefined): boolean {
if (typeof subject !== "string") {
return false;
}
const cleaned = subject.trim();
if (!cleaned || /[\r\n\u0000]/.test(cleaned)) {
return false;
}
return true;
}
/**
* Hide commands the role cannot complete.
* A viewer never sees claim, progress, or close.
* An admin may close another person's alarm, but cannot take over the handler
* or write progress for them. A closed alarm has no command buttons.
*/
export function alarmCommandVisibility(input: {
roles: readonly string[];
subject: string | null | undefined;
status: string;
currentHandler: string | null;
}): AlarmCommandVisibility {
if (!hasAlarmSubject(input.subject)) {
return HIDDEN;
}
const admin = input.roles.includes(ROLE_ADMIN);
const operator = input.roles.includes(ROLE_OPERATOR);
if (!admin && !operator) {
return HIDDEN;
}
const subject = input.subject!.trim();
const self = input.currentHandler !== null && input.currentHandler === subject;
if (input.status === "pending") {
return { claim: true, progress: false, close: false };
}
if (input.status === "processing") {
return { claim: false, progress: self, close: admin || self };
}
return HIDDEN;
}
export type AlarmListPhase = "loading" | "ready" | "error" | "forbidden";
export type AlarmListEmptyKind = "none" | "no-scope" | "empty" | "no-match";
/** Pick the empty copy. No subject wins over rows, "no alarms", and "no match". */
export function alarmListEmptyKind(input: {
phase: AlarmListPhase;
total: number;
hasSubject: boolean;
hasFilters: boolean;
}): AlarmListEmptyKind {
if (input.phase !== "ready") {
return "none";
}
if (!input.hasSubject) {
return "no-scope";
}
if (input.total > 0) {
return "none";
}
if (input.hasFilters) {
return "no-match";
}
return "empty";
}
export type IdempotencyHold = { key: string; payload: string };
/**
* Reuse the key while the payload is unchanged so a retry does not append a
* second progress note when the first response was lost.
*/
export function holdIdempotencyKey(
hold: IdempotencyHold,
payload: string,
makeKey: () => string,
): IdempotencyHold {
if (hold.key !== "" && hold.payload === payload) {
return hold;
}
return { key: makeKey(), payload };
}
export function clearIdempotencyKey(): IdempotencyHold {
return { key: "", payload: "" };
}
@@ -0,0 +1,63 @@
/**
* Alarm HTTP calls. Reads are GET. Commands send x-idempotency-key and a JSON body.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@watchman/api", async () => {
const actual = await vi.importActual<typeof import("@watchman/api")>("@watchman/api");
return { ...actual, requestJson: vi.fn() };
});
import { requestJson } from "@watchman/api";
import { appendProgress, claimAlarm, closeAlarm, getAlarm, listAlarms, listHistory } from "./client";
import { alarmListParams, emptyAlarmFilters } from "./filters";
const mocked = vi.mocked(requestJson);
function lastCall(): { url: string; init: RequestInit } {
const call = mocked.mock.calls[mocked.mock.calls.length - 1];
return { url: String(call[0]), init: (call[1] ?? {}) as RequestInit };
}
describe("alarm client", () => {
beforeEach(() => {
mocked.mockReset();
mocked.mockResolvedValue({});
});
it("lists and reads under /alarms", async () => {
await listAlarms(
alarmListParams(emptyAlarmFilters(), {
sortBy: "last_occurred_at",
sortOrder: "desc",
page: 1,
pageSize: 20,
}),
);
expect(lastCall().url).toContain("/alarms?");
expect(lastCall().init.method).toBeUndefined();
await getAlarm("alarm id");
expect(lastCall().url).toBe("/alarms/alarm%20id");
await listHistory("a1");
expect(lastCall().url).toBe("/alarms/a1/history");
});
it("sends the idempotency key and does not put a handler on the command body", async () => {
await claimAlarm("a1", "key-1");
const claim = lastCall();
expect(claim.url).toBe("/alarms/a1/claim");
expect(claim.init.method).toBe("POST");
expect(new Headers(claim.init.headers).get("x-idempotency-key")).toBe("key-1");
expect(JSON.parse(String(claim.init.body))).toEqual({});
await appendProgress("a1", "key-2", { note: "checked" });
expect(JSON.parse(String(lastCall().init.body))).toEqual({ note: "checked" });
await closeAlarm("a1", "key-3", { result: "resolved", note: "done" });
const close = lastCall();
expect(close.url).toBe("/alarms/a1/close");
expect(JSON.parse(String(close.init.body))).toEqual({ result: "resolved", note: "done" });
expect(String(close.init.body)).not.toContain("current_handler");
});
});
+70
View File
@@ -0,0 +1,70 @@
/**
* Alarm list, detail, and the three handling commands.
* Boundary: unwraps the success envelope. It does not decide who may press a button.
* Depends on the console session client and the /alarms routes.
*/
import { api } from "../api";
import { alarmListQuery, type AlarmListParams } from "./filters";
import type {
AlarmList,
AlarmRecord,
CommandResult,
EvidenceBundle,
HistoryList,
OccurrenceList,
} from "./types";
const JSON_HEADERS = { "Content-Type": "application/json" };
function base(id: string): string {
return `/alarms/${encodeURIComponent(id)}`;
}
function commandInit(idempotencyKey: string, body: unknown): RequestInit {
return {
method: "POST",
headers: { ...JSON_HEADERS, "x-idempotency-key": idempotencyKey },
body: JSON.stringify(body),
};
}
export function listAlarms(params: AlarmListParams): Promise<AlarmList> {
return api<AlarmList>(`/alarms${alarmListQuery(params)}`);
}
export function getAlarm(id: string): Promise<AlarmRecord> {
return api<AlarmRecord>(base(id));
}
export function listOccurrences(id: string): Promise<OccurrenceList> {
return api<OccurrenceList>(`${base(id)}/occurrences`);
}
export function listEvidence(id: string): Promise<EvidenceBundle> {
return api<EvidenceBundle>(`${base(id)}/evidence`);
}
export function listHistory(id: string): Promise<HistoryList> {
return api<HistoryList>(`${base(id)}/history`);
}
export function claimAlarm(id: string, idempotencyKey: string): Promise<CommandResult> {
return api<CommandResult>(`${base(id)}/claim`, commandInit(idempotencyKey, {}));
}
export function appendProgress(
id: string,
idempotencyKey: string,
body: { note: string; evidence_ref?: string },
): Promise<CommandResult> {
return api<CommandResult>(`${base(id)}/progress`, commandInit(idempotencyKey, body));
}
export function closeAlarm(
id: string,
idempotencyKey: string,
body: { result: string; note: string; evidence_ref?: string },
): Promise<CommandResult> {
return api<CommandResult>(`${base(id)}/close`, commandInit(idempotencyKey, body));
}
@@ -0,0 +1,79 @@
/**
* Envelope errors stay on stable reasons. Server message text must not surface.
*/
import { describe, expect, it } from "vitest";
import { BusinessError } from "@watchman/api";
import { describeAlarmError, isAlarmConflict, isAlarmNotFound } from "./errors";
const MESSAGES: Record<string, string> = {
"alarm.errors.already_claimed": "已经有处理人",
"alarm.errors.forbidden": "没有权限({node})",
"alarm.errors.forbiddenPlain": "没有权限完成这个操作",
"codes.40000": "参数错误",
"codes.42000": "权限不足",
"alarm.list.loadFailed": "报警列表加载失败",
};
const t = (key: string, named?: Record<string, unknown>) => {
const template = MESSAGES[key] ?? key;
if (!named) {
return template;
}
return template.replace(/\{(\w+)\}/g, (_match, name: string) => String(named[name] ?? ""));
};
const te = (key: string) => key in MESSAGES;
function business(
code: number,
status: number,
details: Record<string, unknown> = {},
message = "SECRET server text",
): BusinessError {
return new BusinessError({ code, message, details, status, requestId: "r" });
}
describe("describeAlarmError", () => {
it("uses the stable reason and hides the server message", () => {
const text = describeAlarmError(
business(40000, 409, { reason: "already_claimed" }),
t,
te,
"alarm.list.loadFailed",
);
expect(text).toBe("已经有处理人");
expect(text).not.toContain("SECRET");
});
it("shows the permission node we already know, not the server message", () => {
const text = describeAlarmError(
business(42000, 403, {}, "raw denial"),
t,
te,
"alarm.list.loadFailed",
"perm:data:emp:watchman.alarm.take",
);
expect(text).toBe("没有权限(perm:data:emp:watchman.alarm.take)");
expect(text).not.toContain("raw denial");
});
it("falls back to the numeric code, then to the fallback, without the thrown text", () => {
expect(describeAlarmError(business(40000, 400, { reason: "unheard" }), t, te, "alarm.list.loadFailed")).toBe(
"参数错误 (40000)",
);
expect(describeAlarmError(business(50000, 500), t, te, "alarm.list.loadFailed")).toBe(
"报警列表加载失败 (50000)",
);
expect(describeAlarmError(new Error("SECRET network"), t, te, "alarm.list.loadFailed")).toBe(
"报警列表加载失败",
);
});
});
describe("alarm error status", () => {
it("treats HTTP 404 as not found and HTTP 409 as conflict", () => {
expect(isAlarmNotFound(business(40000, 404, { reason: "not_found" }))).toBe(true);
expect(isAlarmNotFound(business(40000, 400))).toBe(false);
expect(isAlarmConflict(business(40000, 409, { reason: "already_claimed" }))).toBe(true);
expect(isAlarmConflict(business(40000, 400))).toBe(false);
});
});
+48
View File
@@ -0,0 +1,48 @@
/**
* Alarm API failures as fixed copy. The server message is never shown.
* Boundary: reason codes and the numeric envelope code only.
* Depends on BusinessError from the shared API client.
*/
import { BusinessError } from "@watchman/api";
type Translate = (key: string, named?: Record<string, unknown>) => string;
type Exists = (key: string) => boolean;
export function describeAlarmError(
error: unknown,
t: Translate,
te: Exists,
fallbackKey: string,
permissionNode?: string,
): string {
if (!(error instanceof BusinessError)) {
return t(fallbackKey);
}
if (error.status === 403 || error.code === 42000) {
if (permissionNode) {
return t("alarm.errors.forbidden", { node: permissionNode });
}
return t("alarm.errors.forbiddenPlain");
}
const reason = error.details.reason;
if (typeof reason === "string" && te(`alarm.errors.${reason}`)) {
return t(`alarm.errors.${reason}`);
}
if (te(`codes.${error.code}`)) {
return `${t(`codes.${error.code}`)} (${error.code})`;
}
return `${t(fallbackKey)} (${error.code})`;
}
export function isAlarmNotFound(error: unknown): boolean {
return error instanceof BusinessError && error.status === 404;
}
export function isAlarmConflict(error: unknown): boolean {
return error instanceof BusinessError && error.status === 409;
}
export function isAlarmForbidden(error: unknown): boolean {
return error instanceof BusinessError && (error.status === 403 || error.code === 42000);
}
@@ -0,0 +1,62 @@
/**
* Filter drafts stay local until they become a server query.
* Covers: no severity param, timezone on time filters, invalid object id blocked.
*/
import { describe, expect, it } from "vitest";
import {
alarmFilterIssue,
alarmFiltersActive,
alarmListParams,
alarmListQuery,
emptyAlarmFilters,
} from "./filters";
const query = { sortBy: "last_occurred_at", sortOrder: "desc" as const, page: 1, pageSize: 20 };
describe("alarm list filters", () => {
it("omits empty filters and never sends a severity field", () => {
const params = alarmListParams(emptyAlarmFilters(), query);
const text = alarmListQuery(params);
expect(text).toContain("sort_by=last_occurred_at");
expect(text).toContain("sort_order=desc");
expect(text).toContain("page=1");
expect(text).toContain("page_size=20");
expect(text).not.toContain("module_key");
expect(text).not.toContain("severity");
expect(text).not.toContain("level");
expect(alarmFiltersActive(emptyAlarmFilters())).toBe(false);
});
it("sends a timezone-aware range and the object id", () => {
const draft = {
...emptyAlarmFilters(),
moduleKey: " furnace ",
scenarioName: "炉温",
objectId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
status: "pending",
from: new Date("2026-11-18T01:00:00.000Z"),
to: new Date("2026-11-18T02:00:00.000Z"),
};
const text = alarmListQuery(alarmListParams(draft, { ...query, page: 2 }));
expect(text).toContain("module_key=furnace");
expect(text).toContain("scenario_name=");
expect(text).toContain("mapped_input_id=aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
expect(text).toContain("status=pending");
expect(text).toContain("occurred_from=2026-11-18T01%3A00%3A00.000Z");
expect(text).toContain("page=2");
expect(alarmFiltersActive(draft)).toBe(true);
expect(alarmFilterIssue(draft)).toBeNull();
});
it("rejects an object id that is not a uuid and a reversed time range", () => {
expect(alarmFilterIssue({ ...emptyAlarmFilters(), objectId: "furnace-01" })).toBe("object");
expect(
alarmFilterIssue({
...emptyAlarmFilters(),
from: new Date("2026-11-18T02:00:00.000Z"),
to: new Date("2026-11-18T01:00:00.000Z"),
}),
).toBe("time-order");
});
});
+105
View File
@@ -0,0 +1,105 @@
/**
* List filter draft turned into the alarm query string.
* Boundary: sends only supported query params, and only after 查询.
* Depends on the list route's page, sort, and filter names.
*/
const OBJECT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export type AlarmFilterDraft = {
moduleKey: string;
scenarioName: string;
objectId: string;
status: string;
from: Date | null;
to: Date | null;
};
export type AlarmFilterIssue = "object" | "time-order" | null;
export type AlarmListParams = {
module_key?: string;
scenario_name?: string;
mapped_input_id?: string;
status?: string;
occurred_from?: string;
occurred_to?: string;
sort_by: string;
sort_order: "asc" | "desc";
page: number;
page_size: number;
};
export function emptyAlarmFilters(): AlarmFilterDraft {
return {
moduleKey: "",
scenarioName: "",
objectId: "",
status: "",
from: null,
to: null,
};
}
export function alarmFiltersActive(draft: AlarmFilterDraft): boolean {
return (
draft.moduleKey.trim() !== "" ||
draft.scenarioName.trim() !== "" ||
draft.objectId.trim() !== "" ||
draft.status !== "" ||
draft.from !== null ||
draft.to !== null
);
}
/** Block a request the API would reject, without showing the server sentence. */
export function alarmFilterIssue(draft: AlarmFilterDraft): AlarmFilterIssue {
const objectId = draft.objectId.trim();
if (objectId !== "" && !OBJECT_ID.test(objectId)) {
return "object";
}
if (draft.from && draft.to && draft.from.getTime() > draft.to.getTime()) {
return "time-order";
}
return null;
}
export function alarmListParams(
draft: AlarmFilterDraft,
query: { sortBy: string; sortOrder: "asc" | "desc"; page: number; pageSize: number },
): AlarmListParams {
return {
module_key: draft.moduleKey.trim() || undefined,
scenario_name: draft.scenarioName.trim() || undefined,
mapped_input_id: draft.objectId.trim() || undefined,
status: draft.status || undefined,
occurred_from: draft.from ? draft.from.toISOString() : undefined,
occurred_to: draft.to ? draft.to.toISOString() : undefined,
sort_by: query.sortBy,
sort_order: query.sortOrder,
page: query.page,
page_size: query.pageSize,
};
}
export function alarmListQuery(params: AlarmListParams): string {
const q = new URLSearchParams();
const set = (key: string, value: string | number | undefined) => {
if (value === undefined || value === "") {
return;
}
q.set(key, String(value));
};
set("module_key", params.module_key);
set("scenario_name", params.scenario_name);
set("mapped_input_id", params.mapped_input_id);
set("status", params.status);
set("occurred_from", params.occurred_from);
set("occurred_to", params.occurred_to);
set("sort_by", params.sort_by);
set("sort_order", params.sort_order);
set("page", params.page);
set("page_size", params.page_size);
const text = q.toString();
return text ? `?${text}` : "";
}
+21
View File
@@ -0,0 +1,21 @@
/**
* Alarm timestamps for tables. Empty or invalid values stay blank.
* Boundary: display only. It does not parse filter input.
* Depends on the browser time zone.
*/
function pad(value: number): string {
return String(value).padStart(2, "0");
}
/** "2026-11-17 09:12" in the browser's time zone, or "" when unset or invalid. */
export function formatDateTime(iso: string | null | undefined): string {
if (!iso) {
return "";
}
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return "";
}
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
@@ -0,0 +1,72 @@
/**
* Alarm copy is present in all four languages and does not say the alarm recovered.
*/
import { describe, expect, it } from "vitest";
import zhCN from "../../locales/zh-CN/common.json";
import zhTW from "../../locales/zh-TW/common.json";
import en from "../../locales/en/common.json";
import th from "../../locales/th/common.json";
function leafKeys(value: unknown, prefix = ""): string[] {
if (value === null || typeof value !== "object") {
return [prefix];
}
return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>
leafKeys(child, prefix ? `${prefix}.${key}` : key),
);
}
function texts(value: unknown): string[] {
if (typeof value === "string") {
return [value];
}
if (value && typeof value === "object") {
return Object.values(value as Record<string, unknown>).flatMap(texts);
}
return [];
}
const BANNED = ["已恢复", "已恢復", "recovered", "Recovered"];
describe("alarm locale keys", () => {
const base = leafKeys((zhCN as { alarm: unknown }).alarm).sort();
it.each([
["zh-TW", zhTW],
["en", en],
["th", th],
])("%s has the same alarm keys as zh-CN", (_name, messages) => {
expect(leafKeys((messages as { alarm: unknown }).alarm).sort()).toEqual(base);
});
it.each([
["zh-CN", zhCN],
["zh-TW", zhTW],
["en", en],
["th", th],
])("%s fills every alarm string and does not say recovered", (_name, messages) => {
const alarm = (messages as { alarm: unknown }).alarm;
const nav = (messages as { nav: Record<string, string> }).nav;
expect(nav.alarms).toBeTruthy();
expect(texts(alarm).every((text) => text.trim() !== "")).toBe(true);
const joined = texts(alarm).join("\n");
for (const word of BANNED) {
expect(joined).not.toContain(word);
}
});
it("names the handling reasons the page can show", () => {
for (const reason of [
"already_claimed",
"not_current_handler",
"illegal_transition",
"already_closed",
"idempotency_payload_mismatch",
"forbidden",
"forbiddenPlain",
]) {
expect(leafKeys(zhCN)).toContain(`alarm.errors.${reason}`);
}
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* Alarm console types matched to the S3 read and command payloads.
* Boundary: fields the alarm API already returns. No severity, planned time, or rule text.
* Depends on the list, detail, occurrence, evidence, and history responses.
*/
export type AlarmStatus = "pending" | "processing" | "closed";
export type CloseResult = "resolved" | "false_positive";
export type AlarmRecord = {
id: string;
status: string;
current_handler: string | null;
claimed_at: string | null;
closed_at: string | null;
close_result: string | null;
occurrence_count: number;
first_occurred_at: string | null;
last_occurred_at: string | null;
previous_alarm_id: string | null;
mapped_input_id: string;
identity_key: string;
module_key: string;
scenario_key: string;
scenario_name: string;
snapshot_id: string;
snapshot_version_no: number;
cycle_key: string;
event_key: string;
opened_at: string;
updated_at: string;
};
export type AlarmList = {
items: AlarmRecord[];
total: number;
page: number;
page_size: number;
};
export type AlarmOccurrence = {
id: string;
mapped_input_revision_id: string;
mapping_version_id: string;
rule_version_id: string;
snapshot_id: string;
snapshot_version_no: number;
module_key: string;
scenario_key: string;
scenario_name: string;
cycle_key: string;
event_key: string;
observed_at: string;
received_at: string;
created_at: string;
};
export type OccurrenceList = {
alarm_id: string;
items: AlarmOccurrence[];
};
export type RevisionEvidence = {
id: string;
occurrence_id: string;
mapped_input_revision_id: string;
mapping_version_id: string;
rule_version_id: string;
snapshot_id: string;
snapshot_version_no: number;
received_at: string;
recorded_at: string;
};
export type ClosedBasis = {
id: string;
original_occurrence_id: string;
mapped_input_revision_id: string;
mapping_version_id: string;
rule_version_id: string;
snapshot_id: string;
snapshot_version_no: number;
cycle_key: string;
event_key: string;
observed_at: string;
received_at: string;
recorded_at: string;
};
export type EvidenceBundle = {
alarm_id: string;
revision_evidence: RevisionEvidence[];
closed_basis: ClosedBasis[];
};
export type HistoryEvent = {
id: string;
seq: number;
command: string;
actor_subject: string;
actor_role: string;
handler_subject: string;
from_status: string;
to_status: string;
note: string | null;
close_result: string | null;
evidence_ref: string | null;
recorded_at: string;
};
export type HistoryList = {
alarm_id: string;
items: HistoryEvent[];
};
export type CommandResult = {
alarm_id: string;
event_id: string;
command: string;
status: string;
current_handler: string | null;
close_result: string | null;
replayed: boolean;
};
+4
View File
@@ -15,6 +15,8 @@ import QueryList from "./queries/QueryList.vue";
import QueryVersionView from "./queries/QueryVersionView.vue";
import MappingList from "./mappings/MappingList.vue";
import MappingEdit from "./mappings/MappingEdit.vue";
import AlarmList from "./alarms/AlarmList.vue";
import AlarmDetail from "./alarms/AlarmDetail.vue";
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
return createRouter({
@@ -77,6 +79,8 @@ export function createAppRouter(history: RouterHistory = createWebHashHistory())
},
{ path: "/mappings", name: "mapping-list", component: MappingList, meta: { crumbs: ["mappings"] } },
{ path: "/mappings/:id", name: "mapping-detail", component: MappingEdit, meta: { crumbs: ["mappings", "detail"] } },
{ path: "/alarms", name: "alarm-list", component: AlarmList, meta: { crumbs: ["alarms"] } },
{ path: "/alarms/:id", name: "alarm-detail", component: AlarmDetail, meta: { crumbs: ["alarms", "detail"] } },
{ path: "/:pathMatch(.*)*", redirect: "/" },
],
});
+1
View File
@@ -14,6 +14,7 @@ export default defineConfig({
"/datasources": "http://127.0.0.1:8000",
"/queries": "http://127.0.0.1:8000",
"/mappings": "http://127.0.0.1:8000",
"/alarms": "http://127.0.0.1:8000",
},
},
});