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

+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;
};