Prechádzať zdrojové kódy

feat(cockpit): 防护目标详情接入字典单一来源与风险因素键值网格

- 字典分层落地:内存(domain/dictLabels)→ 持久化快照(domain/dictSnapshot,带版本)→ 原码;services/cockpitDict 负责取数与启动编排,启动先用快照顶上再并发刷新,单类失败不牵连其它类,localStorage 不可用时退化为内存。
- 防护目标风险等级与颜色改走 risk_level / risk_color 字典,不再出现「未定义(原值:N)」;字典没取到时回原码,不内置第二份可漂移词表。
- 抬头徽标文案「风险等级」,按 risk_color 红橙黄蓝着色;摘要删掉风险等级卡、业务明细删掉风险等级与风险颜色行,全程只出现一次。
- 风险因素 JSON 排成两列键值网格(键弱化、值强调);非法 JSON 原样展示,不吞内容也不假装解析成功。
- 关联管网按业务引用显示「名称(编码)」并提供聚焦入口;复用现有设施定位入口(resolveFacilityPoint 已按 sourceId/networkId 支持 PIPE_NETWORK),只有内部 id 时显示「未提供」,不渲染 id。
- mock 补齐六类字典与防护目标详情样例,联调前可在 mock 场景验收。
ChenJZ 1 hodinu pred
rodič
commit
860befef51

+ 17 - 1
src/modules/cockpit/CockpitShell.vue

@@ -377,7 +377,7 @@
                 -->
                 <PipeColorLegend :counts="pipeColorCountsView" />
                 <!-- 实体详情只占中央一张图;按来源栏靠近对应侧边,绝不覆盖侧栏。 -->
-                <EntityDetailDrawer v-if="!introVisible && !facilityDetailOpen" :side="entityDetailSide" @locate-device="locateDeviceFromDetail" />
+                <EntityDetailDrawer v-if="!introVisible && !facilityDetailOpen" :side="entityDetailSide" @locate-device="locateDeviceFromDetail" @focus-network="focusNetworkFromDetail" />
             </section>
 
             <PipeEnhancement
@@ -502,6 +502,7 @@
                     :location-hint="facilityPointStore.selectedPoint?.locationHint || ''"
                     :underground-ready="facilityUndergroundReady"
                     @locate-device="locateDeviceFromDetail"
+                    @focus-network="focusNetworkFromDetail"
                     @open-underground="openFacilityUnderground"
                 />
                 <PointDetailCard v-else :location-reason="fixedLocationReason" @locate-device="locateDeviceFromDetail" />
@@ -628,6 +629,7 @@ import { useRefreshStore } from './stores/refreshStore.js'
 import { MAP_OBJECT_KIND, MAP_SUMMARY_PHASE } from './domain/mapSummary.js'
 import { getCockpitConfigState, loadCockpitConfig, withUrlDataSourceOverride } from './services/cockpitConfig.js'
 import { fetchPumpStationTypeDict } from './services/facilityDictApi.js'
+import { loadDictionaries } from './services/cockpitDict.js'
 import { setPumpTypeLabels } from './domain/facilityTypeDict.js'
 import {
     atHome,
@@ -1040,6 +1042,17 @@ function locateDeviceFromDetail(deviceCode) {
     return pointLocateStore.locateTarget({ kind: 'map-object', code: deviceCode })
 }
 
+/**
+ * 详情里的「关联管网聚焦」:复用设施定位入口 ——
+ * `resolveFacilityPoint` 对 PIPE_NETWORK 已按 sourceId/networkId 从管线图层解析位置,
+ * 所以管网走的就是同一条飞行与高亮链;解析不到时由统一反馈如实说明原因,不静默。
+ */
+function focusNetworkFromDetail(networkCode) {
+    if (!networkCode) return false
+    if (facilityDetailOpen.value) entityDetailStore.close()
+    return pointLocateStore.locateTarget({ kind: 'facility', code: networkCode, category: 'PIPE_NETWORK' })
+}
+
 function openLedgerCard(pointCode) {
     return monitoringStore.openLedgerPoint(pointCode)
 }
@@ -2445,6 +2458,9 @@ onMounted(() => {
         fetchPumpStationTypeDict({ config: result.config }).then((section) => {
             if (section.state === 'success') setPumpTypeLabels(section.data)
         })
+        // 票 07:六类业务字典 —— 先用持久化快照顶上,再并发刷新并覆盖快照。
+        // 单类失败不牵连其它类;全部失败时保留快照与内存,界面继续用上一次可用标签。
+        loadDictionaries({ config: result.config }).catch(() => {})
         lifecycleReady.value = true
         // 首屏只取当前模式;其它模式在第一次切过去时再取(筛选变化会清缓存)。
         ensureModePanelsLoaded(mode.value)

+ 15 - 3
src/modules/cockpit/components/EntityDetailDrawer.vue

@@ -11,14 +11,17 @@
             <!-- 维护者 2026-10-29:等级不在这里重复 —— 它作为带色的指标卡出现在摘要区。 -->
             <div v-if="view.status || view.categoryText" class="entity-drawer__badges">
                 <span v-if="view.categoryText" class="entity-drawer__badge" data-entity-category>{{ view.categoryText }}</span>
-                <span v-if="view.status" class="entity-drawer__badge entity-drawer__status" :data-tone="view.tone" data-entity-status>{{ view.status }}</span>
+                <!-- 防护目标的「状态」就是风险等级:抬头写「风险等级」,颜色跟 risk_color,文字始终可读。 -->
+                <span v-if="view.status" class="entity-drawer__badge entity-drawer__status" :data-tone="view.tone" data-entity-status>
+                    <em v-if="view.statusCaption" class="entity-drawer__status-caption">{{ view.statusCaption }}</em>{{ view.status }}
+                </span>
             </div>
             <p v-if="store.loading" class="entity-drawer__hint" data-entity-detail-loading>正在更新详情…</p>
             <p v-if="store.error" class="entity-drawer__hint is-error" data-entity-detail-error>
                 详情暂未取到,已保留列表摘要。
                 <button type="button" @click="store.retry">重试</button>
             </p>
-            <div class="entity-drawer__body"><EntityDetailSections :detail="store.detail" @locate-device="(code) => emit('locate-device', code)" /></div>
+            <div class="entity-drawer__body"><EntityDetailSections :detail="store.detail" @locate-device="(code) => emit('locate-device', code)" @focus-network="(code) => emit('focus-network', code)" /></div>
         </aside>
     </Transition>
 </template>
@@ -28,7 +31,7 @@ import { entityDetailView } from '../domain/entityDetail.js'
 import { useEntityDetailStore } from '../stores/entityDetailStore.js'
 import EntityDetailSections from './EntityDetailSections.vue'
 defineProps({ side: { type: String, default: 'right' } })
-const emit = defineEmits(['locate-device'])
+const emit = defineEmits(['locate-device', 'focus-network'])
 const store = useEntityDetailStore()
 const view = computed(() => entityDetailView(store.detail))
 </script>
@@ -141,6 +144,15 @@ const view = computed(() => entityDetailView(store.detail))
 .entity-drawer__level[data-tone='lv4'],
 .entity-drawer__status[data-tone='lv4'] { border-color: rgba(53, 219, 146, 0.5); color: #b8f2d4; }
 /* 已处置=紫(与列表卡同一套状态色)、未知=中性灰;等级四档不含这两档。 */
+/* 风险颜色(risk_color 字典):红 / 橙 / 黄 / 蓝四档。文字仍是中文,颜色不是唯一线索。 */
+.entity-drawer__status[data-tone='risk-1'] { border-color: rgba(255, 59, 82, 0.6); color: #ffc2c9; background: rgba(255, 59, 82, 0.12); }
+.entity-drawer__status[data-tone='risk-2'] { border-color: rgba(255, 138, 32, 0.6); color: #ffd8a8; background: rgba(255, 138, 32, 0.12); }
+.entity-drawer__status[data-tone='risk-3'] { border-color: rgba(255, 214, 32, 0.6); color: #ffeeb0; background: rgba(255, 214, 32, 0.12); }
+.entity-drawer__status[data-tone='risk-4'] { border-color: rgba(1, 171, 234, 0.6); color: #b7e4ff; background: rgba(1, 171, 234, 0.12); }
+
+/* 徽标抬头(「风险等级」):小一号、弱化,不抢风险等级本身。 */
+.entity-drawer__status-caption { margin-right: 4px; font-style: normal; font-weight: 400; opacity: 0.72; }
+
 .entity-drawer__status[data-tone='handled'] { border-color: rgba(169, 112, 255, 0.6); color: #dcc9ff; }
 .entity-drawer__status[data-tone='neutral'] { border-color: rgba(86, 128, 176, 0.5); color: #c4d5e8; }
 

+ 24 - 2
src/modules/cockpit/components/EntityDetailSections.vue

@@ -22,7 +22,16 @@
             <dl class="entity-sections__grid">
                 <div v-for="item in group.fields" :key="item.label" :class="{ 'is-wide': item.wide }">
                     <dt>{{ item.label }}</dt>
-                    <dd>{{ item.value }}<small v-if="item.note" class="entity-sections__note">{{ item.note }}</small></dd>
+                    <dd>
+                        <!-- 键值网格(风险因素):键弱化、值强调,长值折行(规格 §8)。 -->
+                        <div v-if="item.pairs" class="entity-sections__pairs">
+                            <div v-for="(pair, index) in item.pairs" :key="index" class="entity-sections__pair"><span>{{ pair[0] }}</span><b>{{ pair[1] }}</b></div>
+                        </div>
+                        <template v-else>
+                            {{ item.value }}<button v-if="item.action" type="button" class="entity-sections__locate entity-sections__action" :data-action="item.action.kind" @click.stop="runAction(item.action)">{{ ACTION_TEXT[item.action.kind] || '查看' }}</button>
+                        </template>
+                        <small v-if="item.note" class="entity-sections__note">{{ item.note }}</small>
+                    </dd>
                 </div>
             </dl>
         </section>
@@ -84,7 +93,10 @@ import { entityDetailView } from '../domain/entityDetail.js'
 import WorkOrderTimeline from './WorkOrderTimeline.vue'
 import ImageGallery from './ImageGallery.vue'
 const props = defineProps({ detail: { type: Object, default: null }, presentation: { type: String, default: 'entity' } })
-const emit = defineEmits(['locate-device'])
+const emit = defineEmits(['locate-device', 'focus-network'])
+
+/** 明细里的联动按钮文案;认不出的动作不渲染按钮。 */
+const ACTION_TEXT = { 'focus-network': '聚焦管网' }
 const view = computed(() => entityDetailView(props.detail))
 
 // 分区图标:静态内联 SVG(不引第三方图标库),统一当前色 14px。
@@ -125,6 +137,11 @@ const showRelated = computed(() => activeTab.value === 'related')
 const showAlarms = computed(() => activeTab.value === 'alarms')
 
 /** 关联设备定位:沿用运行监测「设备台账」的定位方法(由外壳转给 monitoringStore)。 */
+/** 明细里的联动出口(目前只有管网聚焦):组件不认识地图,交给外壳。 */
+function runAction(action) {
+    if (action && action.kind === 'focus-network' && action.code) emit('focus-network', action.code)
+}
+
 function locateDevice(code) {
     if (!code) return
     emit('locate-device', code)
@@ -184,6 +201,11 @@ function locateDevice(code) {
 /* 所有详情消费方共用:字段值在任意位置折行,长编码不会把容器撑出横向滚动。 */
 .entity-sections dd { margin: 1px 0 0; color: var(--text); font-size: calc(12.5 * var(--u, 1px)); line-height: 1.45; overflow-wrap: anywhere; }
 .entity-sections__note { display: block; margin-top: 1px; color: var(--muted); font-size: calc(10 * var(--u, 1px)); }
+/* 风险因素键值网格:两列,键弱化、值强调;长值折行不横向溢出。 */
+.entity-sections__pairs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 12px; margin-top: 2px; }
+.entity-sections__pair { display: flex; gap: 6px; min-width: 0; }
+.entity-sections__pair span { flex: none; color: var(--muted); font-size: calc(10.5 * var(--u, 1px)); }
+.entity-sections__pair b { min-width: 0; color: var(--text); font-weight: 600; overflow-wrap: anywhere; }
 
 /* 相关人员:按处置顺序横向排列,箭头表达先后关系。 */
 .entity-sections__people { display: flex; align-items: stretch; flex-wrap: wrap; margin: 0; padding: 0; list-style: none; }

+ 2 - 2
src/modules/cockpit/components/FacilityDetailCard.vue

@@ -19,7 +19,7 @@
                 设施详情未取到,已保留现有信息。
                 <button type="button" class="facility-detail__action" @click="store.retry()">重试</button>
             </p>
-            <EntityDetailSections :detail="store.detail" presentation="device" @locate-device="code => emit('locate-device', code)">
+            <EntityDetailSections :detail="store.detail" presentation="device" @locate-device="code => emit('locate-device', code)" @focus-network="code => emit('focus-network', code)">
                 <!-- 维护者 2026-11-16:「查看详情」放在「基本信息/业务信息/关联信息」TAB 行右侧。 -->
                 <template #tabs-action>
                     <button
@@ -48,7 +48,7 @@ const props = defineProps({
     // 面板只负责画按钮,不自己再算一遍下钻条件。
     undergroundReady: { type: Boolean, default: false },
 })
-const emit = defineEmits(['locate-device', 'open-underground'])
+const emit = defineEmits(['locate-device', 'focus-network', 'open-underground'])
 const store = useEntityDetailStore()
 const view = computed(() => entityDetailView(store.detail))
 const code = computed(() => store.detail?.displayCode || '未提供')

+ 85 - 0
src/modules/cockpit/domain/dictLabels.js

@@ -0,0 +1,85 @@
+/**
+ * 业务字典的唯一内存权威(票 07)。
+ *
+ * 分层(规格 §4):内存 → 持久化快照 → 原码。这里只管内存这一层与翻译:
+ * 快照的编解码在 `dictSnapshot.js`,读写 localStorage 在 `services/cockpitDict.js`。
+ * **不内置第二份可漂移词表** —— 命中就出中文,没命中由调用方决定回原码。
+ *
+ * 既有设施词表(泵站类型等)不在此列,迁移另票。
+ */
+
+export const DICT_TYPES = Object.freeze({
+    riskLevel: 'risk_level',
+    riskColor: 'risk_color',
+    hazardType: 'hazard_type',
+    hazardLevel: 'hazard_level',
+    hazardSource: 'hazard_source',
+    hazardStatus: 'hazard_status',
+})
+
+export const DICT_TYPE_LIST = Object.freeze(Object.values(DICT_TYPES))
+
+const field = (row, camel, snake) => {
+    if (!row || typeof row !== 'object') return ''
+    const value = row[camel] !== undefined ? row[camel] : row[snake]
+    return value === null || value === undefined ? '' : String(value).trim()
+}
+
+/** 字典端点的行 → `{ dictValue: dictLabel }`;缺值行不收,一行都收不出就回 null。 */
+export function toDictLabels(raw) {
+    const rows = Array.isArray(raw) ? raw
+        : (raw && Array.isArray(raw.rows) ? raw.rows : (raw && Array.isArray(raw.data) ? raw.data : []))
+    const result = {}
+    for (const row of rows) {
+        const value = field(row, 'dictValue', 'dict_value')
+        const label = field(row, 'dictLabel', 'dict_label')
+        if (value && label) result[value] = label
+    }
+    return Object.keys(result).length ? result : null
+}
+
+/** 纯标签表(键非空、值为非空字符串),避免把任意对象当字典。 */
+export function isLabelMap(value) {
+    if (!value || typeof value !== 'object' || Array.isArray(value)) return false
+    const entries = Object.entries(value)
+    return entries.length > 0 && entries.every(([key, label]) => key !== '' && typeof label === 'string' && label !== '')
+}
+
+/** 已注入的字典;冻结后整体替换,避免调用方原地改内存。 */
+let memory = Object.freeze({})
+
+/**
+ * 注入一类字典(行数组或已解析的标签表都收)。
+ *
+ * 空表**不**覆盖已有值:接口某次返回空列表时,应当继续用上一份可用字典
+ * (规格「接口失败保留快照」的同一口径),而不是把界面打回原码。
+ */
+export function setDictLabels(type, value) {
+    if (!DICT_TYPE_LIST.includes(type)) return false
+    const map = toDictLabels(value) || (isLabelMap(value) ? { ...value } : null)
+    if (!map) return false
+    memory = { ...memory, [type]: map }
+    return true
+}
+
+/** 当前已注入的字典表(快照写入用;回的是浅拷贝)。 */
+export function dictSnapshotSource() {
+    return { ...memory }
+}
+
+/** 仅测试用:回到「字典未取到」。 */
+export function resetDictLabelsForTest() {
+    memory = Object.freeze({})
+}
+
+export function hasDictLabels(type) {
+    return !!memory[type]
+}
+
+/** 码 → 中文;这类字典没取到、或没有这个码,一律回空串,由调用方决定回什么原码。 */
+export function dictLabel(type, value) {
+    const code = value === null || value === undefined ? '' : String(value).trim()
+    if (!code) return ''
+    const map = memory[type]
+    return map && Object.hasOwn(map, code) ? map[code] : ''
+}

+ 43 - 0
src/modules/cockpit/domain/dictSnapshot.js

@@ -0,0 +1,43 @@
+/**
+ * 字典持久化快照(票 07):只做编解码与版本校验,**不碰 localStorage**。
+ *
+ * 为什么带版本:标签口径改过之后,旧快照应当整份丢弃,而不是继续拿旧标签渲染
+ * (规格 §4「持久化按字典类型分区并带版本与加载时间」)。
+ * 版本不符、结构损坏都当作「没有快照」→ 界面回原码,而不是回半份字典。
+ */
+import { DICT_TYPE_LIST, isLabelMap } from './dictLabels.js'
+
+export const DICT_SNAPSHOT_VERSION = 1
+
+/** 当前字典表 → 快照对象;一类都没有时回 null(不写空快照,免得下次误判「有快照」)。 */
+export function buildDictSnapshot(types, savedAt = 0) {
+    const clean = {}
+    for (const type of DICT_TYPE_LIST) {
+        const map = types && types[type]
+        if (isLabelMap(map)) clean[type] = { ...map }
+    }
+    if (!Object.keys(clean).length) return null
+    return { version: DICT_SNAPSHOT_VERSION, savedAt: Number(savedAt) || 0, types: clean }
+}
+
+/** 快照文本/对象 → 可用的字典表;版本不符或结构损坏一律回 null。 */
+export function parseDictSnapshot(raw) {
+    let value = raw
+    if (typeof raw === 'string') {
+        try {
+            value = JSON.parse(raw)
+        } catch {
+            return null
+        }
+    }
+    if (!value || typeof value !== 'object' || Array.isArray(value)) return null
+    if (Number(value.version) !== DICT_SNAPSHOT_VERSION) return null
+    if (!value.types || typeof value.types !== 'object' || Array.isArray(value.types)) return null
+    const types = {}
+    for (const type of DICT_TYPE_LIST) {
+        const map = value.types[type]
+        if (isLabelMap(map)) types[type] = { ...map }
+    }
+    if (!Object.keys(types).length) return null
+    return { version: DICT_SNAPSHOT_VERSION, savedAt: Number(value.savedAt) || 0, types }
+}

+ 93 - 12
src/modules/cockpit/domain/entityDetail.js

@@ -11,6 +11,7 @@ import { toWorkOrder, toWorkOrderTimeline, workOrderStateName } from './workOrde
 import { trackOf } from './workOrderTimeline.js'
 import { facilityStatusTone } from './facilityStatus.js'
 import { pumpStationTypeText } from './facilityTypeDict.js'
+import { DICT_TYPES, dictLabel } from './dictLabels.js'
 export { facilityStatusTone } from './facilityStatus.js'
 
 export const ENTITY_DETAIL_KIND = Object.freeze({
@@ -101,6 +102,8 @@ export function entityDetailView(detail) {
         subtitle: current.subtitle || assetSubtitle(current.kindLabel, current.displayCode),
         tone: current.tone || 'neutral',
         status: current.statusText || '',
+        // 徽标的抬头:防护目标写「风险等级」,其它对象的状态不加抬头。
+        statusCaption: current.statusCaption || '',
         // 等级与状态各有自己的语义色:等级沿用卡片那张四级词表,不与状态色混用。
         levelLabel: current.levelLabel || '',
         levelTone: current.levelTone || '',
@@ -134,7 +137,10 @@ function normalizeAsset(identity, source) {
     const name = text(source.name || source.facilityName || source.resourceName || source.title) || (emergency ? '应急对象名称未提供' : '设施名称未提供')
     // 状态是码值时翻成中文(设施:0 正常 / 1 异常;后端若直接给人话则原样用)。
     const statusRaw = source.status ?? source.state ?? source.statusName ?? source.stateName
-    const status = (category === 'PROTECTION_TARGET' ? riskLevelText(statusRaw) : emergency ? undefinedEnumText(statusRaw) : facilityStatusText(statusRaw)) || '状态未发布'
+    const isRiskTarget = category === 'PROTECTION_TARGET'
+    const status = (isRiskTarget ? riskLevelText(statusRaw) : emergency ? undefinedEnumText(statusRaw) : facilityStatusText(statusRaw)) || '状态未发布'
+    // 防护目标的「状态」就是风险等级(规格 §5):抬头只留一个「风险等级」徽标,配色跟 risk_color。
+    const riskColorRaw = isRiskTarget ? attributes.riskColor ?? statusRaw : ''
     const location = text(source.address || source.location || source.position)
     const fields = assetFields(category, attributes)
     const kindLabel = emergency ? '应急对象' : '设施'
@@ -144,7 +150,9 @@ function normalizeAsset(identity, source) {
         kindLabel,
         // 抬头只拼接真实存在的业务编码;没有编码列时不留「编码未提供」。
         subtitle: assetSubtitle(kindLabel, displayCode, hasCodeColumn),
-        statusText: status, tone: emergency ? 'neutral' : facilityStatusTone(source.status), raw: source,
+        statusText: status, statusCaption: isRiskTarget ? '风险等级' : '',
+        tone: isRiskTarget ? riskTone(riskColorRaw) : emergency ? 'neutral' : facilityStatusTone(source.status),
+        raw: source,
         categoryText: facilityCategoryText(category),
         coordinates: source.coordinates || null,
         summary: assetSummary(category, attributes, location),
@@ -276,7 +284,8 @@ function assetSummary(category, attributes, location) {
         PIPE_NETWORK: ['lengthMeters', 'diameterMillimeters', 'material'],
         MANHOLE: ['manholeDepth', 'manholeShape', 'material', 'ownershipUnit'],
         HAZARD: ['level', 'rectifyDeadline', 'rectifyPerson'],
-        PROTECTION_TARGET: ['riskLevel', 'riskScore', 'assessmentTime'],
+        // 风险等级由抬头徽标承担,摘要不再重复同一个词(票面「只出现一次」)。
+        PROTECTION_TARGET: ['riskScore', 'assessmentTime'],
         EMERGENCY_RESOURCE: ['model', 'specification', 'maintainer'],
     }
     const labels = { ...SUMMARY_LABELS, ...SUMMARY_LABELS_BY_CATEGORY[category] }
@@ -522,14 +531,14 @@ const ASSET_FIELD_ROWS = {
         { label: '隐患图片', key: 'images', wide: true },
         { label: '备注', key: 'remark', wide: true },
     ],
+    // 风险等级与风险颜色不再进明细:已由抬头那一个「风险等级」徽标承担(规格 §5)。
+    // 风险因素改成键值网格,不再把一整串 JSON 打在页面上。
     PROTECTION_TARGET: [
         { label: '关联管网', key: 'networkId' },
-        { label: '风险等级', key: 'riskLevel' },
         { label: '风险分值', key: 'riskScore' },
-        { label: '风险颜色', key: 'riskColor' },
         { label: '评估模型', key: 'assessmentModel' },
         { label: '评估时间', key: 'assessmentTime' },
-        { label: '风险因素', key: 'riskFactors', wide: true },
+        { label: '风险因素', key: 'riskFactors', wide: true, pairs: true },
         { label: '危险源', key: 'hazardSources', wide: true },
         { label: '备注', key: 'remark', wide: true },
     ],
@@ -547,11 +556,71 @@ function undefinedEnumText(raw) {
     return /^[+-]?\d+(?:\.\d+)?$/.test(value) ? `未定义(原值:${value})` : '未知'
 }
 
-/** RiskAssessmentServiceImpl 发布 high/medium/low;历史数字码无定义,不套易积水点字典。 */
+/**
+ * 风险等级:业务库 risk_level 字典是唯一权威(0 重大 / 1 较大 / 2 一般 / 3 低)。
+ *
+ * 字典没取到时回**原码**,不再写「未定义(原值:N)」——那是把「字典还没到」
+ * 说成「后端给了个没定义的枚举」。high/medium/low 是风险评估服务的历史发布形状,
+ * 保留映射(它不是数字码,字典里没有对应行);已发布中文原样透传。
+ */
+const RISK_LEVEL_LEGACY_TEXT = { high: '高风险', medium: '中风险', low: '低风险' }
 function riskLevelText(raw) {
     const value = text(raw)
-    const names = { high: '高风险', medium: '中风险', low: '低风险' }
-    return Object.hasOwn(names, value) ? names[value] : undefinedEnumText(raw)
+    if (!value) return ''
+    return dictLabel(DICT_TYPES.riskLevel, value) || RISK_LEVEL_LEGACY_TEXT[value] || value
+}
+
+/** 风险颜色码 → 中文(红/橙/黄/蓝);字典没取到就回原码。 */
+function riskColorText(raw) {
+    const value = text(raw)
+    if (!value) return ''
+    return dictLabel(DICT_TYPES.riskColor, value) || value
+}
+
+/** 风险颜色码 → 语义色键(0 红 / 1 橙 / 2 黄 / 3 蓝);认不出回中性。 */
+const RISK_TONE_BY_CODE = { 0: 'risk-1', 1: 'risk-2', 2: 'risk-3', 3: 'risk-4' }
+function riskTone(value) {
+    return RISK_TONE_BY_CODE[text(value)] || 'neutral'
+}
+
+/**
+ * 风险因素 → 键值对(规格 §2「风险因素从字符串改为键值组结构」)。
+ *
+ * 后端既可能下发对象,也可能下发 JSON 字符串;解析失败(非法 JSON、纯文本)回 null,
+ * 由调用方原样展示 —— 不吞掉内容,也不假装解析成功。
+ */
+function riskFactorPairs(value) {
+    if (value === null || value === undefined || value === '') return null
+    let source = value
+    if (typeof source === 'string') {
+        try {
+            source = JSON.parse(source)
+        } catch {
+            return null
+        }
+    }
+    if (Array.isArray(source)) {
+        const pairs = source.map((item, index) => [`${index + 1}`, text(item)]).filter(([, label]) => label)
+        return pairs.length ? pairs : null
+    }
+    if (source && typeof source === 'object') {
+        const pairs = Object.entries(source).map(([key, item]) => [key, text(item)]).filter(([, label]) => label)
+        return pairs.length ? pairs : null
+    }
+    return null
+}
+
+/**
+ * 关联管网的业务引用(规格 §5):只认后端下发的 name + code。
+ * 只有内部 id 时不渲染 id —— 字段表据此显示「未提供」。
+ */
+function networkReference(a) {
+    const network = a.network
+    if (!network || typeof network !== 'object') return null
+    const code = text(network.code)
+    const name = text(network.name)
+    if (!code && !name) return null
+    return { label: name && code ? `${name}(${code})` : name || code, code }
 }
 
 /** 详情里按完整时间戳展示的字段。 */
@@ -572,7 +641,7 @@ function assetFieldValue(key, a) {
     }
     if (['networkId', 'workOrderId', 'equipmentTypeId'].includes(key)) return '未提供'
     if (key === 'riskLevel') return riskLevelText(a[key])
-    if (key === 'riskColor') return undefinedEnumText(a[key])
+    if (key === 'riskColor') return riskColorText(a[key])
     if (ASSET_TIMESTAMP_KEYS.has(key)) return formatEventTime(a[key])
     if (ASSET_DATE_KEYS.has(key)) return formatAssetDate(a[key])
     return a[key]
@@ -581,6 +650,17 @@ function assetFieldValue(key, a) {
 function assetFields(category, a) {
     const rows = category === 'PIPE_NETWORK' ? pipesFields(a) : ASSET_FIELD_ROWS[category] || []
     return rows.map((row) => {
+        // 关联管网:后端下发 name + code 时显示「名称(编码)」并给聚焦入口;否则如实「未提供」。
+        if (row.key === 'networkId' && category === 'PROTECTION_TARGET') {
+            const ref = networkReference(a)
+            if (!ref) return field(row.label, '未提供')
+            return field(row.label, ref.label, false, { action: ref.code ? { kind: 'focus-network', code: ref.code } : null })
+        }
+        // 风险因素:能解析成键值就出网格;非法 JSON / 纯文本原样展示。
+        if (row.pairs) {
+            const pairs = riskFactorPairs(a[row.key])
+            return pairs ? field(row.label, '', row.wide === true, { pairs }) : field(row.label, a[row.key], row.wide === true)
+        }
         // 单位一律由 `unitOf(category, key)` 给:同一字段名在不同设施里量纲可能不同。
         const raw = row.format ? row.format(a[row.key]) : withUnitText(assetFieldValue(row.key, a), unitOf(category, row.key))
         // always 行(如非排水管的二级分类)保留占位;其余缺值由 compactSections 剔除。
@@ -871,11 +951,12 @@ function timelineAttachments(records) { return (Array.isArray(records) ? records
  */
 function compactSections(sections) {
     return sections
-        .map((group) => ({ ...group, fields: group.fields.filter((item) => item.always || item.value !== PLACEHOLDER) }))
+        // 键值网格行(风险因素)没有单值文本,但它本身有内容,不能按占位符剔掉。
+        .map((group) => ({ ...group, fields: group.fields.filter((item) => item.always || item.pairs || item.value !== PLACEHOLDER) }))
         .filter((group) => group.fields.length)
 }
 function section(title, fields) { return { title, fields } }
-function field(label, value, wide = false) { return { label, value: display(value), wide, always: false, note: '' } }
+function field(label, value, wide = false, extra = {}) { return { label, value: display(value), wide, always: false, note: '', ...extra } }
 function display(value) { return value === null || value === undefined || String(value).trim() === '' ? PLACEHOLDER : String(value) }
 function text(value) { return value === null || value === undefined ? '' : String(value).trim() }
 /**

+ 31 - 1
src/modules/cockpit/mocks/contractMocks.js

@@ -2003,6 +2003,26 @@ const FACILITY_ENTITY_FIXTURES = {
         location: '沅陵县城东',
         coordinates: { longitude: 110.392, latitude: 28.437, endLongitude: null, endLatitude: null },
     },
+    // 票 07:防护目标没有业务编码列(code 空);风险等级/颜色以字典码下发;
+    // 关联管网给业务引用 name+code(后端票 06 的契约,联调前用这份 mock 验收)。
+    'PROTECTION_TARGET|PT-DR-001': {
+        category: 'PROTECTION_TARGET',
+        id: 'PT-DR-001',
+        code: '',
+        name: '污水处理厂防护目标',
+        status: 1,
+        location: '城北污水处理厂',
+        coordinates: { longitude: 110.383, latitude: 28.447, endLongitude: null, endLatitude: null },
+        attributes: {
+            riskLevel: 1,
+            riskColor: 1,
+            riskScore: 72.5,
+            assessmentModel: '易损性评估 v2',
+            assessmentTime: '2026-11-20T10:30:00+08:00',
+            riskFactors: '{"管材":"钢管","周边":"学校","埋深":"1.8 米"}',
+            network: { code: 'YS-P-004', name: '城北污水干管' },
+        },
+    },
     'PUMP_STATION|2': {
         category: 'PUMP_STATION',
         id: '2',
@@ -2036,7 +2056,7 @@ function facilityEntityDetailPayload(scenario, requested, query = {}) {
         district: null,
         districtName: '未分区',
         coordinates: fixture.coordinates,
-        attributes: {},
+        attributes: fixture.attributes || {},
         updatedAt: '2026-09-02T09:59:50+08:00',
     }
 }
@@ -2946,6 +2966,16 @@ const PAYLOADS = {
         { dictType: 'pump_station_type', dictValue: '0', dictLabel: '供水泵站' },
         { dictType: 'pump_station_type', dictValue: '1', dictLabel: '排水泵站' },
     ]),
+    // 票 07:六类业务字典(与票 04 的后端透传同形,值与业务库一致)。
+    // 改库标签不需要改这里 —— 这只是 mock 场景的固定样例。
+    ...Object.fromEntries([
+        ['risk_level', [['0', '重大风险'], ['1', '较大风险'], ['2', '一般风险'], ['3', '低风险']]],
+        ['risk_color', [['0', '红'], ['1', '橙'], ['2', '黄'], ['3', '蓝']]],
+        ['hazard_type', [['0', '腐蚀'], ['1', '第三方破坏'], ['2', '占压'], ['3', '泄漏']]],
+        ['hazard_level', [['1', '一级'], ['2', '二级'], ['3', '三级'], ['4', '四级隐患']]],
+        ['hazard_source', [['0', '巡检'], ['1', '政府检查'], ['2', '企业上报'], ['3', '模型辨识']]],
+        ['hazard_status', [['0', '整改中'], ['1', '已整改'], ['2', '待核查'], ['3', '已闭环']]],
+    ].map(([type, rows]) => [`/dict/${type}`, (s) => (s === 'empty' ? [] : rows.map(([dictValue, dictLabel]) => ({ dictType: type, dictValue, dictLabel })))])),
     '/infrastructure/base-archives': (s, _requested, context) => baseArchivesPayload(s, context.query),
     '/infrastructure/operating-information': (s, _requested, context) => operatingInformationPayload(s, context.query),
     '/infrastructure/management-information': (s, _requested, context) => managementInformationPayload(s, context.query),

+ 92 - 0
src/modules/cockpit/services/cockpitDict.js

@@ -0,0 +1,92 @@
+/**
+ * 字典的取数与持久化(票 07)。
+ *
+ * 分层(规格 §4):启动先读快照即时渲染 → 再用接口刷新并覆盖快照;
+ * 接口失败保留快照;快照也没有才回原码(域层 `dictLabels.js` 回空串即是这条退路)。
+ *
+ * localStorage 不可用(隐私模式、配额、被禁用)时全部函数静默退化为内存:
+ * 渲染仍然正确,只是下次启动没有快照可用。
+ */
+import { fetchSection } from './domainRequest.js'
+import { DICT_TYPE_LIST, dictSnapshotSource, setDictLabels, toDictLabels } from '../domain/dictLabels.js'
+import { buildDictSnapshot, parseDictSnapshot } from '../domain/dictSnapshot.js'
+
+export const DICT_STORAGE_KEY = 'cockpit.dict'
+
+/** 六类字典同形:`/dict/{type}` 回 `[{ dictValue, dictLabel }]`。 */
+export function dictPath(type) {
+    return `/dict/${type}`
+}
+
+function storageOf(options = {}) {
+    if (options.storage !== undefined) return options.storage
+    try {
+        return typeof localStorage !== 'undefined' ? localStorage : null
+    } catch {
+        // 隐私模式下访问 localStorage 会抛异常。
+        return null
+    }
+}
+
+/** 读快照并注入内存;没有可用快照回 null。 */
+export function loadDictSnapshot(options = {}) {
+    const storage = storageOf(options)
+    if (!storage || typeof storage.getItem !== 'function') return null
+    let raw = ''
+    try {
+        raw = storage.getItem(DICT_STORAGE_KEY)
+    } catch {
+        return null
+    }
+    const snapshot = parseDictSnapshot(raw)
+    if (!snapshot) return null
+    for (const [type, map] of Object.entries(snapshot.types)) setDictLabels(type, map)
+    return snapshot
+}
+
+/** 把当前字典写成快照;storage 不可用或没有字典时静默跳过。 */
+export function saveDictSnapshot(options = {}) {
+    const storage = storageOf(options)
+    if (!storage || typeof storage.setItem !== 'function') return null
+    const at = typeof options.now === 'function' ? options.now() : Date.now()
+    const snapshot = buildDictSnapshot(dictSnapshotSource(), at)
+    if (!snapshot) return null
+    try {
+        storage.setItem(DICT_STORAGE_KEY, JSON.stringify(snapshot))
+    } catch {
+        return null
+    }
+    return snapshot
+}
+
+export function fetchDict(type, options = {}) {
+    return fetchSection(dictPath(type), {
+        toData: toDictLabels,
+        isEmpty: (payload) => toDictLabels(payload) === null,
+        config: options.config,
+        fetchImpl: options.fetchImpl,
+    })
+}
+
+/**
+ * 启动链唯一的字典入口:先用快照顶上,再并发刷新六类。
+ *
+ * 单类失败不牵连其它类;刷新成功的类覆盖内存并写回快照。
+ * 全部失败时内存与快照都保持原样 —— 界面继续用上一次可用标签,不是打回原码。
+ */
+export async function loadDictionaries(options = {}) {
+    const request = typeof options.fetchDict === 'function' ? options.fetchDict : (type) => fetchDict(type, options)
+    const snapshot = loadDictSnapshot(options)
+    const sections = await Promise.all(DICT_TYPE_LIST.map((type) => request(type).catch(() => null)))
+    const refreshed = []
+    DICT_TYPE_LIST.forEach((type, index) => {
+        const section = sections[index]
+        if (!section || section.state !== 'success') return
+        const map = toDictLabels(section.data)
+        if (!map) return
+        setDictLabels(type, map)
+        refreshed.push(type)
+    })
+    if (refreshed.length) saveDictSnapshot(options)
+    return { snapshot: !!snapshot, refreshed }
+}

+ 89 - 0
tests/cockpitDict.test.js

@@ -0,0 +1,89 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+import { DICT_TYPES, dictLabel, resetDictLabelsForTest } from '../src/modules/cockpit/domain/dictLabels.js'
+import { DICT_SNAPSHOT_VERSION, parseDictSnapshot } from '../src/modules/cockpit/domain/dictSnapshot.js'
+import {
+    DICT_STORAGE_KEY,
+    loadDictSnapshot,
+    loadDictionaries,
+    saveDictSnapshot,
+} from '../src/modules/cockpit/services/cockpitDict.js'
+
+/** 最小 localStorage 替身:只实现 getItem/setItem。 */
+function memoryStorage(seed = {}) {
+    const data = { ...seed }
+    return {
+        getItem: (key) => (Object.hasOwn(data, key) ? data[key] : null),
+        setItem: (key, value) => { data[key] = String(value) },
+        data,
+    }
+}
+
+const snapshotOf = (types) => JSON.stringify({ version: DICT_SNAPSHOT_VERSION, savedAt: 1, types })
+
+test('启动先读快照顶上:接口还没回来时就能出中文', async () => {
+    resetDictLabelsForTest()
+    const storage = memoryStorage({
+        [DICT_STORAGE_KEY]: snapshotOf({ [DICT_TYPES.riskLevel]: { 1: '较大风险' } }),
+    })
+    const snapshot = loadDictSnapshot({ storage })
+    assert.equal(snapshot.savedAt, 1)
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '1'), '较大风险')
+})
+
+test('接口刷新成功后覆盖内存并写回快照', async () => {
+    resetDictLabelsForTest()
+    const storage = memoryStorage()
+    const result = await loadDictionaries({
+        storage,
+        now: () => 42,
+        fetchDict: async (type) => (type === DICT_TYPES.riskLevel
+            ? { state: 'success', data: [{ dictValue: '2', dictLabel: '一般风险' }] }
+            : { state: 'failed', data: null }),
+    })
+    assert.deepEqual(result.refreshed, [DICT_TYPES.riskLevel])
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '2'), '一般风险')
+    const saved = parseDictSnapshot(storage.getItem(DICT_STORAGE_KEY))
+    assert.equal(saved.savedAt, 42)
+    assert.deepEqual(saved.types[DICT_TYPES.riskLevel], { 2: '一般风险' })
+})
+
+test('接口失败时保留快照里的字典,不改写、不清空', async () => {
+    resetDictLabelsForTest()
+    const storage = memoryStorage({
+        [DICT_STORAGE_KEY]: snapshotOf({ [DICT_TYPES.riskColor]: { 1: '橙' } }),
+    })
+    const before = storage.getItem(DICT_STORAGE_KEY)
+    const result = await loadDictionaries({
+        storage,
+        fetchDict: async () => { throw new Error('network down') },
+    })
+    assert.deepEqual(result.refreshed, [])
+    assert.equal(dictLabel(DICT_TYPES.riskColor, '1'), '橙')
+    assert.equal(storage.getItem(DICT_STORAGE_KEY), before)
+})
+
+test('快照损坏或版本不符时当作没有快照,界面回原码(字典为空)', () => {
+    resetDictLabelsForTest()
+    const broken = memoryStorage({ [DICT_STORAGE_KEY]: '{oops' })
+    assert.equal(loadDictSnapshot({ storage: broken }), null)
+    const stale = memoryStorage({
+        [DICT_STORAGE_KEY]: JSON.stringify({ version: DICT_SNAPSHOT_VERSION - 1, types: { [DICT_TYPES.riskLevel]: { 1: '较大风险' } } }),
+    })
+    assert.equal(loadDictSnapshot({ storage: stale }), null)
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '1'), '')
+})
+
+test('localStorage 不可用(隐私模式)时退化为内存,不抛错', async () => {
+    resetDictLabelsForTest()
+    const result = await loadDictionaries({
+        storage: null,
+        fetchDict: async (type) => (type === DICT_TYPES.riskLevel
+            ? { state: 'success', data: [{ dictValue: '3', dictLabel: '低风险' }] }
+            : { state: 'failed', data: null }),
+    })
+    assert.deepEqual(result.refreshed, [DICT_TYPES.riskLevel])
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '3'), '低风险')
+    assert.equal(saveDictSnapshot({ storage: null }), null)
+})

+ 49 - 0
tests/dictLabels.test.js

@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+import {
+    DICT_TYPES,
+    dictLabel,
+    hasDictLabels,
+    resetDictLabelsForTest,
+    setDictLabels,
+    toDictLabels,
+} from '../src/modules/cockpit/domain/dictLabels.js'
+
+test('字典行归一化成 value→label,缺值行不收', () => {
+    const map = toDictLabels([
+        { dictValue: '0', dictLabel: '重大风险' },
+        { dictValue: '1', dictLabel: '较大风险' },
+        { dictValue: '', dictLabel: '空值丢掉' },
+        { dict_value: '2', dict_label: '一般风险' },
+    ])
+    assert.deepEqual(map, { 0: '重大风险', 1: '较大风险', 2: '一般风险' })
+    assert.equal(toDictLabels([]), null)
+    assert.equal(toDictLabels(null), null)
+})
+
+test('注入后按类型翻译;没有这类字典或没有这个码都回空串', () => {
+    resetDictLabelsForTest()
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '1'), '')
+    setDictLabels(DICT_TYPES.riskLevel, [{ dictValue: '1', dictLabel: '较大风险' }])
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '1'), '较大风险')
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, 1), '较大风险')
+    assert.equal(dictLabel(DICT_TYPES.riskLevel, '9'), '')
+    assert.equal(dictLabel(DICT_TYPES.riskColor, '1'), '')
+    assert.equal(hasDictLabels(DICT_TYPES.riskLevel), true)
+    resetDictLabelsForTest()
+    assert.equal(hasDictLabels(DICT_TYPES.riskLevel), false)
+})
+
+test('空表不覆盖已有字典:接口返回空时继续用上一份', () => {
+    resetDictLabelsForTest()
+    setDictLabels(DICT_TYPES.riskColor, { 0: '红', 1: '橙' })
+    assert.equal(setDictLabels(DICT_TYPES.riskColor, []), false)
+    assert.equal(dictLabel(DICT_TYPES.riskColor, '1'), '橙')
+})
+
+test('未知字典类型不接收', () => {
+    resetDictLabelsForTest()
+    assert.equal(setDictLabels('pump_station_type', { 0: '供水泵站' }), false)
+    assert.equal(hasDictLabels('pump_station_type'), false)
+})

+ 51 - 0
tests/dictSnapshot.test.js

@@ -0,0 +1,51 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+import { DICT_TYPES } from '../src/modules/cockpit/domain/dictLabels.js'
+import {
+    DICT_SNAPSHOT_VERSION,
+    buildDictSnapshot,
+    parseDictSnapshot,
+} from '../src/modules/cockpit/domain/dictSnapshot.js'
+
+const sample = () => ({
+    [DICT_TYPES.riskLevel]: { 0: '重大风险', 1: '较大风险' },
+    [DICT_TYPES.riskColor]: { 0: '红', 1: '橙' },
+})
+
+test('快照带版本、保存时间与按类型的字典表', () => {
+    const snapshot = buildDictSnapshot(sample(), 1700000000000)
+    assert.equal(snapshot.version, DICT_SNAPSHOT_VERSION)
+    assert.equal(snapshot.savedAt, 1700000000000)
+    assert.deepEqual(snapshot.types[DICT_TYPES.riskLevel], { 0: '重大风险', 1: '较大风险' })
+})
+
+test('没有任何字典时不出空快照', () => {
+    assert.equal(buildDictSnapshot({}), null)
+    assert.equal(buildDictSnapshot(null), null)
+    assert.equal(buildDictSnapshot({ [DICT_TYPES.riskLevel]: {} }), null)
+})
+
+test('往返:序列化后能解析回同一份字典', () => {
+    const snapshot = buildDictSnapshot(sample(), 1)
+    const parsed = parseDictSnapshot(JSON.stringify(snapshot))
+    assert.deepEqual(parsed.types, snapshot.types)
+})
+
+test('版本不符、结构损坏、非法 JSON 都当作没有快照', () => {
+    const snapshot = buildDictSnapshot(sample(), 1)
+    assert.equal(parseDictSnapshot(JSON.stringify({ ...snapshot, version: 0 })), null)
+    assert.equal(parseDictSnapshot('{not json'), null)
+    assert.equal(parseDictSnapshot(JSON.stringify({ version: DICT_SNAPSHOT_VERSION })), null)
+    assert.equal(parseDictSnapshot(JSON.stringify({ version: DICT_SNAPSHOT_VERSION, types: [] })), null)
+    assert.equal(parseDictSnapshot(null), null)
+})
+
+test('快照里认不出的类型被丢弃,其余保留', () => {
+    const parsed = parseDictSnapshot({
+        version: DICT_SNAPSHOT_VERSION,
+        savedAt: 5,
+        types: { [DICT_TYPES.riskLevel]: { 0: '重大风险' }, pump_station_type: { 0: '供水泵站' } },
+    })
+    assert.deepEqual(Object.keys(parsed.types), [DICT_TYPES.riskLevel])
+})

+ 122 - 0
tests/entityDetailProtectionTarget.test.js

@@ -0,0 +1,122 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+import { normalizeEntityDetail, entityDetailView } from '../src/modules/cockpit/domain/entityDetail.js'
+import { DICT_TYPES, resetDictLabelsForTest, setDictLabels } from '../src/modules/cockpit/domain/dictLabels.js'
+
+const RISK_LEVEL = { 0: '重大风险', 1: '较大风险', 2: '一般风险', 3: '低风险' }
+const RISK_COLOR = { 0: '红', 1: '橙', 2: '黄', 3: '蓝' }
+
+function useDictionaries() {
+    resetDictLabelsForTest()
+    setDictLabels(DICT_TYPES.riskLevel, RISK_LEVEL)
+    setDictLabels(DICT_TYPES.riskColor, RISK_COLOR)
+}
+
+function targetView(attributes = {}, source = {}) {
+    const raw = {
+        category: 'PROTECTION_TARGET',
+        id: 'r1',
+        name: '污水处理厂防护目标',
+        status: 1,
+        attributes: { riskLevel: 1, riskColor: 1, riskScore: 72.5, assessmentTime: '2026-11-13T17:57:10', ...attributes },
+        ...source,
+    }
+    return entityDetailView(normalizeEntityDetail({ kind: 'emergency', id: 'r1', category: 'PROTECTION_TARGET' }, raw))
+}
+
+const businessRows = (view) => view.sections.find((group) => group.title === '业务详情').fields
+const rowOf = (view, label) => businessRows(view).find((row) => row.label === label)
+
+test('风险等级按 risk_level 字典显示中文,徽标抬头写「风险等级」并按风险颜色着色', () => {
+    useDictionaries()
+    const view = targetView()
+    assert.equal(view.status, '较大风险')
+    assert.equal(view.statusCaption, '风险等级')
+    assert.equal(view.tone, 'risk-2')
+})
+
+test('不再出现「未定义(原值:N)」', () => {
+    useDictionaries()
+    for (const code of [0, 1, 2, 3]) {
+        const view = targetView({ riskLevel: code, riskColor: code }, { status: code })
+        assert.ok(!JSON.stringify(view.sections).includes('未定义'), 'code ' + code + ' 仍出现了未定义')
+        assert.ok(!view.status.includes('未定义'))
+    }
+})
+
+test('风险等级与风险颜色不再进业务明细(改由抬头徽标承担)', () => {
+    useDictionaries()
+    const view = targetView()
+    assert.equal(rowOf(view, '风险等级'), undefined)
+    assert.equal(rowOf(view, '风险颜色'), undefined)
+    assert.equal(rowOf(view, '风险分值').value, '72.5 分')
+})
+
+test('「风险等级」在整份视图里只出现一次(徽标),摘要不再重复', () => {
+    useDictionaries()
+    const view = targetView()
+    const seen = []
+    for (const item of view.summary) if (item.label === '风险等级') seen.push('summary')
+    if (view.statusCaption === '风险等级') seen.push('badge')
+    for (const group of view.sections) for (const item of group.fields) if (item.label === '风险等级') seen.push('section')
+    assert.deepEqual(seen, ['badge'])
+})
+
+test('风险因素 JSON 串排成键值网格', () => {
+    useDictionaries()
+    const view = targetView({ riskFactors: '{"管材":"钢管","埋深":"1.8 米"}' })
+    const row = rowOf(view, '风险因素')
+    assert.deepEqual(row.pairs, [['管材', '钢管'], ['埋深', '1.8 米']])
+    assert.equal(row.wide, true)
+})
+
+test('风险因素本身就是对象时同样成网格', () => {
+    useDictionaries()
+    const view = targetView({ riskFactors: { 周边: '学校', 距离: '30 米' } })
+    assert.deepEqual(rowOf(view, '风险因素').pairs, [['周边', '学校'], ['距离', '30 米']])
+})
+
+test('风险因素不是合法 JSON 时原样展示,不当成网格', () => {
+    useDictionaries()
+    const view = targetView({ riskFactors: '管材钢管,埋深不明' })
+    const row = rowOf(view, '风险因素')
+    assert.equal(row.pairs, undefined)
+    assert.equal(row.value, '管材钢管,埋深不明')
+})
+
+test('关联管网下发 name+code 时显示「名称(编码)」并给出聚焦入口', () => {
+    useDictionaries()
+    const view = targetView({ network: { code: 'PS-N-001', name: '滨江污水干管' } })
+    const row = rowOf(view, '关联管网')
+    assert.equal(row.value, '滨江污水干管(PS-N-001)')
+    assert.deepEqual(row.action, { kind: 'focus-network', code: 'PS-N-001' })
+})
+
+test('关联管网只有内部 id 时显示「未提供」,不把 id 渲染出来', () => {
+    useDictionaries()
+    const withId = targetView({ networkId: 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4' })
+    assert.equal(rowOf(withId, '关联管网').value, '未提供')
+    assert.equal(rowOf(withId, '关联管网').action, undefined)
+    assert.ok(!JSON.stringify(withId.sections).includes('a1b2c3d4e5f6'))
+})
+
+test('字典没取到时回原码,而不是编一个「未定义」', () => {
+    resetDictLabelsForTest()
+    const view = targetView()
+    assert.equal(view.status, '1')
+    assert.equal(view.tone, 'risk-2')
+    const row = rowOf(view, '风险分值')
+    assert.equal(row.value, '72.5 分')
+})
+
+test('后端已发布的中文风险等级原样透传', () => {
+    useDictionaries()
+    const view = targetView({ riskLevel: '待核查' }, { status: '待核查' })
+    assert.equal(view.status, '待核查')
+})
+
+test('历史 high/medium/low 仍能翻译(风险评估服务的老形状,不是数字码)', () => {
+    useDictionaries()
+    assert.equal(targetView({}, { status: 'high' }).status, '高风险')
+})