/** * 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; 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 { return JSON.stringify({ success: false, error: { code, message, details, retryable: false }, request_id: "pw-alarm", }); } function seedAlarm(overrides: Partial & Pick): 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 { 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 { 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)[sortBy] ?? ""); const bv = String((b as Record)[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 { const overflow = await page.evaluate( () => document.documentElement.scrollWidth - document.documentElement.clientWidth, ); expect(overflow).toBeLessThanOrEqual(1); } async function expectInsideViewport(page: Page, testId: string): Promise { 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`) }); }); }