Explorar o código

Merge remote-tracking branch 'origin/master'

zengy hai 2 meses
pai
achega
5c29504eec
Modificáronse 80 ficheiros con 7169 adicións e 27 borrados
  1. 99 0
      .scratch/cockpit-backend-read-contracts/spec.md
  2. 35 0
      .scratch/out-of-scope-tests/zksy-system/src/main/java/com/zksy/WaterSupply/MonitorAlarm/dto/out/AlarmDispatchOutDTO.java
  3. 92 0
      T6-water-device-handoff.md
  4. 140 0
      docs/cockpit/equipment-detail-aggregate-demo.html
  5. 121 0
      docs/cockpit/freshness-semantics-demo.html
  6. 267 0
      docs/cockpit/overview-infrastructure-demo.html
  7. 230 0
      docs/cockpit/overview-monitoring-demo.html
  8. 180 0
      docs/cockpit/websocket-scope-delta-demo.html
  9. 127 0
      docs/cockpit/work-order-seven-states-demo.html
  10. 99 0
      docs/superpowers/specs/2026-08-26-water-supply-alarm-work-order-acceptance-fixes.md
  11. 115 0
      docs/superpowers/specs/2026-08-27-water-supply-subsystem-e2e-delivery.md
  12. 62 0
      logs/pipe-network-service/spring.log
  13. 9 0
      pipe-network-service/docs/adr/0003-water-supply-subsystem-product-boundary.md
  14. 9 0
      pipe-network-service/docs/adr/0004-cross-system-unified-work-order-lifecycle.md
  15. 7 0
      pipe-network-service/docs/adr/0005-independent-frontend-backend-contract-gate.md
  16. 7 0
      pipe-network-service/docs/adr/0006-work-order-attachment-storage.md
  17. 16 0
      pipe-network-service/docs/adr/0007-shared-pump-station-by-type.md
  18. 42 0
      pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md
  19. 17 0
      pipe-network-service/docs/adr/0009-retain-parameter-names-and-explicit-mvc-binding-names.md
  20. 124 0
      pipe-network-service/docs/domain/work-order-lifecycle.md
  21. 54 0
      pipe-network-service/sql/migration_pump_station_shared.sql
  22. 56 0
      pipe-network-service/sql/rollback_pump_station_shared.sql
  23. 66 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitEquipmentDetailAggregateController.java
  24. 100 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitFreshnessController.java
  25. 49 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitOverviewInfrastructureController.java
  26. 60 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringController.java
  27. 103 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitWorkOrderReadController.java
  28. 73 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusDeltaTracker.java
  29. 122 25
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusRedisListener.java
  30. 39 1
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusWebSocketHandler.java
  31. 28 1
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/SubscriptionManager.java
  32. 349 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitEquipmentDetailAggregateControllerTest.java
  33. 213 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitFreshnessSemanticsControllerTest.java
  34. 282 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewInfrastructureControllerTest.java
  35. 167 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringControllerTest.java
  36. 202 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringServiceTest.java
  37. 272 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderReadControllerTest.java
  38. 317 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/websocket/DeviceStatusCockpitWebSocketHandlerTest.java
  39. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/event/DeviceStatusChangePublisher.java
  40. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/EquipmentStatusService.java
  41. 10 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentStatusServiceImpl.java
  42. 75 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitEquipmentDetailAggregateResponse.java
  43. 312 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitEquipmentDetailAggregateService.java
  44. 36 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitSectionResult.java
  45. 8 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitSectionState.java
  46. 1 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveResponse.java
  47. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessAdapter.java
  48. 68 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessResponse.java
  49. 24 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSection.java
  50. 40 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSectionData.java
  51. 9 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSectionState.java
  52. 169 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessService.java
  53. 17 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSource.java
  54. 9 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessStatus.java
  55. 11 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/EmptyCockpitFreshnessAdapter.java
  56. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureAdapter.java
  57. 185 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureResponse.java
  58. 251 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureService.java
  59. 100 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureSnapshot.java
  60. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringAdapter.java
  61. 24 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringDeviceStatusDelta.java
  62. 249 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringResponse.java
  63. 406 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringService.java
  64. 120 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringSnapshot.java
  65. 11 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/EmptyCockpitOverviewInfrastructureAdapter.java
  66. 20 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/EmptyCockpitOverviewMonitoringAdapter.java
  67. 151 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/BusinessCockpitWorkOrderReadAdapter.java
  68. 20 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderEventAssociation.java
  69. 9 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadAdapter.java
  70. 50 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadResponse.java
  71. 119 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadService.java
  72. 26 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadSnapshot.java
  73. 14 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderState.java
  74. 49 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderStateDictionary.java
  75. 60 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderSummary.java
  76. 40 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineEntry.java
  77. 38 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineResponse.java
  78. 18 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineSnapshot.java
  79. 21 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/EmptyCockpitWorkOrderReadAdapter.java
  80. 24 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/service/impl/WaterSupplyDeviceServiceImplTest.java

+ 99 - 0
.scratch/cockpit-backend-read-contracts/spec.md

@@ -0,0 +1,99 @@
+# 城市生命线驾驶舱系统:后端只读接口与实时状态契约
+
+Status: ready-for-agent
+
+## Problem Statement
+
+城市生命线驾驶舱系统面向指挥中心领导和值班人员,是一个只读展示大屏。UE 需要在进入程序后加载“一张图”,以监测点为首要地图对象,查看关联智能设备的基础档案、当前监测数据、预警、报警和工单处置状态。现有后端主要提供管理型接口,字段、分页和写入能力与驾驶舱展示边界不一致;预警接口仍处于向统一工单模型迁移的阶段,设备状态 WebSocket 也使用旧的驼峰设备字段。
+
+如果 UE 直接拼接管理接口,客户端将不得不推断监测点综合状态、复制事件关系和承担迁移兼容,导致状态口径不一致、地图分页重复、局部详情失败被空数据掩盖以及只读大屏误用业务写接口。因此后端需要提供稳定、版本化、只读的驾驶舱专用契约,并在内部复用现有表和服务。
+
+## Solution
+
+新增驾驶舱只读聚合服务和 DTO,统一挂载于 `/api/cockpit/v1/`。服务端负责从现有监测点、智能设备、设备类型、预警、报警、`alarm_warning_rel`、工单和指标数据中组合稳定响应;UE 不直接访问管理接口或数据库。
+
+地图摘要使用一个共享 `snapshotAt` 的分页快照,分别返回监测点摘要和未关联智能设备摘要。后端返回已解析的 `pointStatus`、状态原因、统计和坐标校验结果。监测点优先渲染;已关联设备不重复生成独立点位;未关联且坐标有效的设备才作为直接设备点位;无效坐标对象保留在列表和详情中但禁止地图渲染。
+
+设备详情采用基础档案、当前指标、预警、报警、工单、工单时间线和图片等独立只读分区。REST 首次提供权威快照,WebSocket 仅推送状态增量。现有 `/ws/deviceStatus` 增加 `cockpitSubscribe` 范围订阅,规范字段使用 `deviceCode`,迁移期可额外返回旧 `device_code`;UE 以 `serverUpdatedAt` 判断新旧消息,断线后自动重连和恢复订阅。
+
+## User Stories
+
+1. As a 指挥中心领导, I want the cockpit to load the map frame before data completes, so that the display never appears frozen during startup.
+2. As a 值班人员, I want paginated monitoring-point summaries, so that a large city dataset can load progressively.
+3. As a 地图使用者, I want one consistent snapshot across all map pages, so that points are not duplicated or omitted while data changes.
+4. As a 值班人员, I want unassociated intelligent equipment with valid coordinates to appear directly on the map, so that equipment is not lost when an association is absent.
+5. As a 数据负责人, I want invalid or unverified coordinates returned with a reason, so that the cockpit never guesses a spatial transform.
+6. As a 地图使用者, I want the server to return the resolved monitoring-point status, so that UE does not recompute status from a partial page.
+7. As a 值班人员, I want to click a monitoring point and see its summary and backend-ordered equipment cards, so that I can choose the relevant equipment.
+8. As a 值班人员, I want to open equipment details by stable equipment code, so that detail navigation does not depend on database primary IDs.
+9. As a 值班人员, I want equipment archive fields and the latest image, so that I can identify the physical equipment.
+10. As a 值班人员, I want type-specific current metrics, including sewage environmental metrics when supplied, so that the display reflects the equipment schema.
+11. As a 值班人员, I want warning and alarm events in separate sections, so that their distinct event families remain clear.
+12. As a 值班人员, I want current and historical event results with explicit empty and unavailable states, so that missing data is not mistaken for no events.
+13. As a 值班人员, I want every related work order and its complete nine-state timeline, so that handling progress is visible without merging records.
+14. As a 系统集成负责人, I want event and work-order relationships resolved by the backend, so that the cockpit does not infer relationships from names, coordinates or timestamps.
+15. As a 驾驶舱维护者, I want independent detail sections, so that one failed query does not erase successful sibling sections.
+16. As a 值班人员, I want a short-lived cached detail with an explicit stale marker, so that I retain context without being misled about freshness.
+17. As a 值班人员, I want scheduled summary refresh between three and ten minutes and a manual refresh, so that display freshness can match deployment needs.
+18. As a 系统运维人员, I want device-state calibration to start at sixty seconds and be extendable, so that device population does not overload the service.
+19. As a 值班人员, I want incremental WebSocket updates to identify the affected device, so that the map and open detail update promptly.
+20. As a 网络异常场景下的值班人员, I want automatic reconnect and subscription recovery, so that temporary disconnections do not permanently stop updates.
+21. As a 安全负责人, I want fixed display identity supplied outside UE assets, so that credentials are not exposed in packaged content.
+22. As a 安全负责人, I want all cockpit endpoints to be read-only, so that display interactions cannot mutate business records.
+23. As a 后端协作者, I want dedicated JSON fields to use camelCase, so that the contract is consistent with the existing Java stack while keeping database names internal.
+24. As a 后端协作者, I want `deviceCode` to be canonical and `device_code` to be a migration alias, so that old WebSocket clients remain compatible.
+25. As a 统计使用者, I want facility counts and intelligent-equipment counts separated, so that water plants and pump stations are not mixed with sensor equipment.
+26. As a 业务负责人, I want the formal scope limited to gas, supply water and drainage, so that unknown types are not silently counted in a formal industry total.
+27. As a 业务负责人, I want sensor-equipped manholes represented as intelligent equipment, so that manholes are not modeled as a separate industry or facility entity.
+28. As a 统计使用者, I want overview, infrastructure, monitoring and warning-disposal metrics to use one timezone and freshness vocabulary, so that dashboards are comparable.
+29. As a 后端协作者, I want contract handoff material before warning migration replacement, so that the adapter changes from evidence rather than guessed fields.
+30. As a 测试人员, I want the aggregate behavior observable through one public read model seam, so that contract tests verify user-visible behavior without coupling to database joins.
+
+## Implementation Decisions
+
+- Add a versioned read-only cockpit API surface under `/api/cockpit/v1/`; keep management endpoints as internal composition sources only.
+- Preserve the existing response envelope convention, while placing dedicated camelCase DTOs in the data payload.
+- Provide map-summary, monitoring-point-detail and equipment-detail contracts, plus read-only metric, warning, alarm, work-order, timeline and image sections.
+- Map summaries use `page`, `pageSize` and `snapshotAt`; default page size is 500 and maximum is 1000. The response includes total, batch update time and completion metadata.
+- Return monitoring points and unassociated equipment as separate collections. A valid published map coordinate is WGS84; missing, zero, out-of-range or unvalidated coordinates fail the render gate and include a reason.
+- Return `pointStatus` and a status reason from the backend. Fixed codes are `ALARM`, `WARNING`, `WORK_ORDER`, `NORMAL`, `OFFLINE` and `EMPTY`, each with a display label. The backend owns precedence.
+- Keep facility and intelligent-equipment statistics separate. Facilities include water plants, pump stations and pipelines; sensor-equipped manholes belong to intelligent equipment and are not an industry.
+- Use the database `equipment_base.equipment_code` as the preferred shared association key. Dedicated cockpit JSON exposes it as `deviceCode`; legacy data may retain `device_code` or other aliases inside the adapter boundary.
+- Keep warning and alarm event families distinct. Reuse backend authority for `alarm_warning_rel`, event cardinality and work-order uniqueness; the cockpit never creates or deduplicates work orders.
+- Preserve all nine work-order states and each work order's independent timeline. Do not merge timelines across events.
+- Use `Asia/Shanghai` for business date and statistic boundaries. Emit ISO-8601 timestamps with timezone information and return selected range, timezone and update time.
+- Extend `/ws/deviceStatus` with `cockpitSubscribe` and `scope=all`, while retaining existing device-code subscription compatibility. REST provides initial snapshots; WebSocket sends changed-device deltas only.
+- WebSocket payloads use canonical `deviceCode`, may include legacy `device_code`, and include current status, `statusTime` and `serverUpdatedAt`. No sequence field is added; newest `serverUpdatedAt` wins.
+- On reconnect, the client may resubscribe automatically. The service must not treat subscription, refresh or detail queries as business writes.
+- Enforce service identity at the deployment or gateway layer. Do not embed credentials in UE, DTOs or packaged assets. Use standard HTTP errors to distinguish empty data, invalid input, missing resources, authentication failure and server failure.
+- Implement the read model by composing existing tables and services first. Add indexes or a projection only after query and representative-scale measurements demonstrate the need.
+- Do not publish unverified CAD coordinates. Conversion from CGCS2000, Xi'an 80, Beijing 54 and elevation references happens before publication and requires later control-point validation.
+
+## Testing Decisions
+
+- Use one highest-level public seam: a fake read-only cockpit adapter feeds the aggregate presentation contract with deterministic map pages, details and WebSocket updates; assert only public DTO behavior, freshness, selection identity and update results.
+- Add controller/service contract tests for response envelopes, camelCase fields, status dictionaries, HTTP error categories, pagination snapshot consistency and facility/equipment count separation.
+- Add integration tests against representative database fixtures for monitoring-point association, unassociated equipment, invalid coordinates, event-family separation, `alarm_warning_rel` relationships and nine work-order states.
+- Add WebSocket tests for canonical and legacy device-code fields, delta-only pushes, `serverUpdatedAt` ordering, missing point status fallback, scope subscription, reconnect subscription and heartbeat behavior.
+- Add read-only safety tests using an adapter/request spy; all map loading, detail loading, refresh, retry and subscription operations must produce no business mutation request.
+- Add freshness tests for successful empty results, one missed cycle, two missed cycles, stale retention and independent section failure.
+- Add statistics tests for timezone boundaries, selected ranges, formal industry filtering, unknown-type exclusion and separate facility/equipment totals.
+- Reuse existing Spring controller/service test conventions and add dedicated contract fixtures rather than testing private SQL helpers or requiring a particular join implementation.
+
+## Out of Scope
+
+- No UE implementation, UMG changes, Actor implementation, Three.js migration or Pixel Streaming work.
+- No login page, role management, threshold configuration, publishing, upgrading, resolving, dispatching, accepting, processing, verifying, approving or other business write operation in the cockpit API.
+- No replacement of the existing management APIs or removal of their compatibility behavior.
+- No local UE aggregation of monitoring-point state, event relationships, coordinate transforms or work-order uniqueness.
+- No Flowable introduction or redesign of the existing work-order state machine.
+- No judgment of warning truthfulness or false positives.
+- No final GIS accuracy threshold, production-scale performance threshold or Galaxy Kylin certification; these remain later validation gates.
+
+## Further Notes
+
+- The backend working tree contains pre-existing uncommitted changes. This spec does not authorize reverting or mixing those changes into the cockpit implementation.
+- The warning lifecycle is expected to migrate to the same work-order model as alarms. The dedicated adapter must remain stable while the backend absorbs that migration.
+- Before replacing transitional warning mappings, backend handoff must include endpoint paths, request parameters, response examples, field and status dictionaries, relationship/cardinality rules, pagination and freshness semantics, and WebSocket samples.
+- The current repository has `/MonitorPoint`, `/EquipmentBase`, `/api/alarm` and `/ws/deviceStatus` management or transitional surfaces, but no completed `/api/cockpit/v1` contract. This spec defines the target seam without claiming those endpoints already exist.
+- Apply the `ready-for-agent` triage label when publishing this spec to Gogs Issues.

+ 35 - 0
.scratch/out-of-scope-tests/zksy-system/src/main/java/com/zksy/WaterSupply/MonitorAlarm/dto/out/AlarmDispatchOutDTO.java

@@ -0,0 +1,35 @@
+package com.zksy.WaterSupply.MonitorAlarm.dto.out;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 报警转工单结果。
+ */
+@Data
+@ApiModel(value = "报警转工单结果", description = "报警生成或复用的待派单故障维修工单摘要")
+public class AlarmDispatchOutDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    @ApiModelProperty(value = "工单ID")
+    private Long orderId;
+
+    @ApiModelProperty(value = "工单编号")
+    private String orderNo;
+
+    @ApiModelProperty(value = "工单类型,固定为1-故障维修")
+    private Integer orderType;
+
+    @ApiModelProperty(value = "工单状态;新建工单为1-待派单")
+    private Integer orderStatus;
+
+    @ApiModelProperty(value = "关联报警ID")
+    private String alarmId;
+
+    @ApiModelProperty(value = "关联设备编码")
+    private String deviceCode;
+}

+ 92 - 0
T6-water-device-handoff.md

@@ -0,0 +1,92 @@
+# T6 供水设备准入、台账与异常态势 · Handoff
+
+## 目标
+
+继续完成 Gogs Issue #10 / T6“供水设备准入、台账与异常态势”。当前对话已经完成后端与前端的主要实现,剩余工作集中在测试补齐、全量验证、两轴代码审查和提交。
+
+## 仓库与当前状态
+
+- 后端仓库:`E:\pipe-ner-server`
+  - 分支:`master`
+  - 状态:`ahead 1`
+  - T6 相关改动已暂存,另有多处无关脏文件;不要清理或覆盖。
+- 前端仓库:`E:\city-life-line`
+  - 分支:`master`
+  - 状态:`ahead 10`
+  - T6 相关改动仍在工作区,尚未暂存;同样存在无关脏文件,不要清理或覆盖。
+
+## 已完成的核心工作
+
+### 后端
+
+- `WaterSupplyDeviceServiceImpl`
+  - 通过 `equipmentBaseService.findByTopLevelType("供水")` 统一执行供水设备准入。
+  - 设备状态、在线状态、报警状态分别建模,不再互相替代。
+  - 异常原因来自有效报警或维修状态。
+  - 关联工单使用真实 `order_no`,并映射为 `relatedWorkOrderNo`、`relatedWorkOrderStatus`、`relatedWorkOrderPerson`。
+  - 异常页只关联“未结案的故障维修工单”。
+- `WaterSupplyDeviceService` / `WaterSupplyDeviceServiceImplTest`
+  - 补齐供水过滤、空数据、状态分离、异常原因、关联工单、报警等级筛选等测试。
+- 控制器与导出
+  - `DeviceLedgerController`、`DeviceAbnormalController` 已支持分页、筛选、Excel 导出。
+  - 新增 `WaterDeviceLedgerExportDTO`、`WaterDeviceAbnormalExportDTO`。
+  - 对应控制器测试已添加。
+- 测试数据
+  - 新增 `pipe-network-service/sql/water_supply_device_test_data.sql`,覆盖混合供水/非供水设备、正常/报警/维修/离线状态、异常原因和真实工单编号。
+
+### 前端
+
+- `src/views/subSystem/waterSupply/components/WaterDevicePage.vue`
+  - 台账页聚焦资产信息。
+  - 异常页聚焦异常态势、异常原因、处置状态、关联工单。
+  - 展示设备状态、在线状态、报警状态、报警等级、异常原因、关联工单号、工单状态、接单责任人。
+  - 详情使用右侧抽屉。
+  - 导出改为 Blob 下载并处理 JSON 错误。
+- `src/utils/waterSupplyUiModel.js`
+  - 统一设备行归一化,明确区分 `currentStatus`、`onlineStatus`、`alarmStatus`、`alertLevel`、`abnormalReason`、`relatedWorkOrderNo`、`relatedWorkOrderStatus`、`relatedWorkOrderPerson`。
+- `src/api/pipeNetwork/waterSupply.js`
+  - 设备台账和异常设备导出接口改为 `responseType: 'blob'`。
+- 测试
+  - 更新 `tests/waterSupplyUiModel.test.mjs`
+  - 新增 `tests/waterDeviceExport.test.mjs`
+
+## 剩余工作
+
+1. 补一个 `relatedWorkOrderPerson` 的测试,mock `ISysUserService`,确认多个接单人可映射为昵称并用“、”连接。
+2. 后端运行:
+   - `mvn -q -pl zksy-system "-Dtest=WaterSupplyDeviceServiceImplTest" test`
+   - `mvn -q test`
+3. 前端运行:
+   - `node --test tests`
+   - `npm run build:prod`
+4. 按两轴完成代码审查:
+   - Standards:检查是否符合 CONTEXT / ADR / 设计规范。
+   - Spec:检查 T6 验收标准是否完整覆盖。
+5. 只暂存 T6 相关文件,分别提交后端与前端仓库;不要推送、不要合并。
+
+## 参考文档
+
+- 交付规格:`E:\pipe-ner-server\docs\superpowers\specs\2026-08-27-water-supply-subsystem-e2e-delivery.md`
+- 后端上下文:`E:\pipe-ner-server\CONTEXT-MAP.md`
+- 后端领域文档:`E:\pipe-ner-server\pipe-network-service\CONTEXT.md`
+- 前端上下文:`E:\city-life-line\CONTEXT.md`
+- 前端设计规范:`E:\city-life-line\docs\design\2026-08-22-water-supply-work-order-ui.md`
+- ADR:
+  - `E:\pipe-ner-server\pipe-network-service\docs\adr\0003-water-supply-subsystem-product-boundary.md`
+  - `E:\pipe-ner-server\pipe-network-service\docs\adr\0004-cross-system-unified-work-order-lifecycle.md`
+  - `E:\pipe-ner-server\pipe-network-service\docs\adr\0005-independent-frontend-backend-contract-gate.md`
+  - `E:\pipe-ner-server\pipe-network-service\docs\adr\0006-work-order-attachment-storage.md`
+  - `E:\pipe-ner-server\pipe-network-service\docs\adr\0007-shared-pump-station-by-type.md`
+
+## 环境注意事项
+
+- 当前机器的 Windows 沙箱助手曾出现 `helper_unknown_error: setup refresh had errors`。
+- 使用 `require_escalated` 可以绕过该问题并正常执行命令。
+- 若再次遇到沙箱初始化失败,优先对命令使用提权执行,而不是清理工作区。
+
+## Suggested skills
+
+- `implement`
+- `tdd`
+- `code-review`
+- `verification-before-completion`

+ 140 - 0
docs/cockpit/equipment-detail-aggregate-demo.html

@@ -0,0 +1,140 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Equipment Detail Aggregate Demo</title>
+  <style>
+    body { margin:0; min-height:100vh; background:#08131f; color:#e8f1f8; font:15px/1.5 "Microsoft YaHei",sans-serif; }
+    main { width:min(1280px,calc(100vw - 32px)); margin:28px auto; display:grid; gap:16px; }
+    header, section { background:#0e1e2d; border:1px solid #21465f; padding:20px; }
+    h1,h2,h3 { margin:0 0 10px; } h1 { font-size:22px; } h2 { font-size:17px; } h3 { font-size:15px; }
+    .endpoint { color:#78a2b8; font-family:Consolas,monospace; margin:0; }
+    .toolbar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
+    button { border:1px solid #2f7098; background:#123247; color:#dff2ff; padding:8px 14px; cursor:pointer; }
+    button.active { outline:2px solid #61c2ff; }
+    .sections { display:grid; grid-template-columns:repeat(auto-fit,minmax(260px,1fr)); gap:12px; }
+    .section { border:1px solid #275b74; background:#0b1922; padding:12px; }
+    .section.success { border-color:#68d095; } .section.empty { border-color:#a9b7c0; }
+    .section.stale { border-color:#f2c94c; } .section.failed { border-color:#ff7a7a; }
+    .badge { display:inline-block; font-size:12px; padding:3px 8px; border:1px solid; margin-bottom:8px; }
+    .success .badge { color:#68d095; border-color:#68d095; } .empty .badge { color:#a9b7c0; border-color:#a9b7c0; }
+    .stale .badge { color:#f2c94c; border-color:#f2c94c; } .failed .badge { color:#ff7a7a; border-color:#ff7a7a; }
+    table { width:100%; border-collapse:collapse; } th,td { border:1px solid #275b74; padding:6px; text-align:left; } th { background:#123247; }
+    .mono { font-family:Consolas,monospace; overflow-wrap:anywhere; } pre { max-height:340px; overflow:auto; background:#071019; border:1px solid #275b74; padding:12px; }
+    .note { color:#8fb3c7; font-size:13px; } .missing { color:#a9b7c0; font-style:italic; }
+  </style>
+</head>
+<body>
+<main>
+  <header>
+    <h1>设备详情聚合与独立分区演示</h1>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/detail-aggregate</p>
+    <p class="endpoint">分区重试复用既有:/archive · /metrics/current · /events/current · /work-orders · /work-orders/{code}/timeline</p>
+  </header>
+  <section>
+    <div class="toolbar">
+      <button type="button" data-mode="full" class="active">完整详情</button>
+      <button type="button" data-mode="partial">局部失败</button>
+      <button type="button" data-mode="empty">成功空数据</button>
+    </div>
+    <div id="sections" class="sections"></div>
+  </section>
+  <section>
+    <h2>响应契约</h2>
+    <p class="note">每个 sectionResult 独立返回 SUCCESS / EMPTY / STALE / FAILED;FAILED 分区保留原因与提示,不覆盖成功兄弟分区。最新图片继承档案分区,档案失败时显示来源分区失败。</p>
+    <pre id="payload" class="mono"></pre>
+  </section>
+</main>
+<script>
+  const section = (state, reason, data, message) => ({ state, reason, message, data });
+  const image = { url:'https://cockpit.example/latest.jpg', capturedAt:'2026-08-30T10:20:00+08:00' };
+  const archive = {
+    deviceCode:'TC-PS-WS-202609020012', deviceName:'污水环境监测设备', deviceModel:'WS-PRO-2000',
+    deviceSpec:'悬浮物/COD/氨氮/电导率/PH', manufacturer:'沅陵专用仪表厂', deviceTypeName:'污水环境监测设备',
+    assetValue:128000, expectedServiceYears:10, equipmentLocation:'太常片区', ownershipUnit:'沅陵县排水管理所',
+    latestImage:image
+  };
+  const metric = { metricCode:'COD', metricName:'COD', value:18.2, unit:'mg/L', status:'WARNING', sampledAt:'2026-09-02T09:59:30+08:00', freshness:'CURRENT' };
+  const warning = { warningNo:'WRN-20260902-001', warningName:'污水COD预警', level:2, levelColor:'YELLOW', status:'PROCESSING', eventTime:'2026-09-02T09:59:30+08:00' };
+  const alarm = { alarmId:'ALM-20260902-001', warningName:'污水COD报警', level:1, levelColor:'RED', status:'UNHANDLED', eventTime:'2026-09-02T10:00:00+08:00' };
+  const relation = { relationId:'REL-001', warningNo:warning.warningNo, alarmId:alarm.alarmId, relatedAt:'2026-09-02T10:00:00+08:00' };
+  const workOrder = { workOrderCode:'WO-2026090200001', orderTypeName:'故障维修', stateCode:4, stateName:'处理中', orderDesc:'处理异常' };
+  const timeline = { workOrder:{ ...workOrder }, timelineEntries:[{ logId:1, operationName:'创建工单', operationDesc:'处理异常', operatorName:'系统', operatedAt:'2026-09-02T09:00:00+08:00' }] };
+  const metrics = { deviceCode:archive.deviceCode, state:'CURRENT', stateReason:'READY', metrics:[metric] };
+
+  const responses = {
+    full: {
+      aggregateState:'READY',
+      archive:section('SUCCESS','SUCCESS',archive), metrics:section('SUCCESS','SUCCESS',metrics),
+      warnings:section('SUCCESS','SUCCESS',[warning]), alarms:section('SUCCESS','SUCCESS',[alarm]),
+      alarmWarningRelations:section('SUCCESS','SUCCESS',[relation]),
+      workOrders:section('SUCCESS','SUCCESS',[workOrder]), timelines:section('SUCCESS','SUCCESS',[timeline]),
+      latestImage:section('SUCCESS','SUCCESS',image)
+    },
+    partial: {
+      aggregateState:'PARTIAL',
+      archive:section('FAILED','READ_FAILURE',null,'设备档案数据暂不可用'),
+      metrics:section('STALE','SAMPLE_OUTDATED',{ ...metrics, state:'STALE' }),
+      warnings:section('SUCCESS','SUCCESS',[warning]), alarms:section('SUCCESS','SUCCESS',[alarm]),
+      alarmWarningRelations:section('SUCCESS','SUCCESS',[relation]),
+      workOrders:section('FAILED','READ_FAILURE',null,'工单数据暂不可用'),
+      timelines:section('FAILED','SOURCE_SECTION_FAILED',null,'工单分区失败,时间线不可用'),
+      latestImage:section('FAILED','SOURCE_SECTION_FAILED',null,'设备档案失败,图片不可用')
+    },
+    empty: {
+      aggregateState:'EMPTY',
+      archive:section('EMPTY','NO_ARCHIVE',null), metrics:section('EMPTY','NO_METRICS',null),
+      warnings:section('EMPTY','NO_EVENTS',null), alarms:section('EMPTY','NO_EVENTS',null),
+      alarmWarningRelations:section('EMPTY','NO_EVENTS',null),
+      workOrders:section('EMPTY','NO_WORK_ORDERS',null), timelines:section('EMPTY','NO_WORK_ORDERS',null),
+      latestImage:section('EMPTY','NO_IMAGE',null)
+    }
+  };
+
+  function renderSection(name, result) {
+    const rows = [];
+    const data = result.data;
+    if (name === 'archive' && data) {
+      rows.push(['设备编码', data.deviceCode], ['设备名称', data.deviceName], ['设备型号', data.deviceModel], ['权属单位', data.ownershipUnit]);
+    } else if (name === 'metrics' && data) {
+      rows.push(['状态', `${data.state} / ${data.stateReason}`], ['最新COD', `${data.metrics[0].value} ${data.metrics[0].unit}`]);
+    } else if (name === 'warnings' && data) {
+      data.forEach(item => rows.push([item.warningNo, `${item.warningName} · ${item.status}`]));
+    } else if (name === 'alarms' && data) {
+      data.forEach(item => rows.push([item.alarmId, `${item.warningName} · ${item.status}`]));
+    } else if (name === 'alarmWarningRelations' && data) {
+      data.forEach(item => rows.push([item.relationId, `${item.warningNo} ⇄ ${item.alarmId}`]));
+    } else if (name === 'workOrders' && data) {
+      data.forEach(item => rows.push([item.workOrderCode, `${item.stateCode} ${item.stateName}`]));
+    } else if (name === 'timelines' && data) {
+      data.forEach(item => rows.push([item.workOrder.workOrderCode, `${item.timelineEntries.length} 条时间线`]));
+    } else if (name === 'latestImage' && data) {
+      rows.push(['图片地址', data.url], ['采集时间', data.capturedAt]);
+    }
+    const body = result.data
+      ? '<table><tbody>' + rows.map(row => `<tr><th>${row[0]}</th><td class="mono">${row[1]}</td></tr>`).join('') + '</tbody></table>'
+      : `<p class="missing">${result.message || '暂无数据'}</p>`;
+    return `<article class="section ${result.state.toLowerCase()}">
+      <span class="badge">${result.state}</span>
+      <h3>${name}</h3>
+      ${result.reason ? `<p class="note">reason:${result.reason}</p>` : ''}
+      ${body}
+    </article>`;
+  }
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
+    const payload = responses[mode];
+    document.getElementById('sections').innerHTML = Object.keys(payload)
+      .filter(key => key !== 'aggregateState')
+      .map(key => renderSection(key, payload[key])).join('');
+    document.getElementById('payload').textContent = JSON.stringify({
+      code:200, msg:'操作成功', data:{ requestId:'equipment-detail-demo', apiVersion:'v1', readOnly:true,
+        deviceCode:archive.deviceCode, aggregateState:payload.aggregateState, serverTime:'2026-09-02T10:00:00+08:00', ...payload }
+    }, null, 2);
+  }
+  document.querySelectorAll('button[data-mode]').forEach(button => button.addEventListener('click', () => render(button.dataset.mode)));
+  render('full');
+</script>
+</body>
+</html>

+ 121 - 0
docs/cockpit/freshness-semantics-demo.html

@@ -0,0 +1,121 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Freshness Semantics Demo</title>
+  <style>
+    body { margin:0; min-height:100vh; background:#08131f; color:#e8f1f8; font:15px/1.5 "Microsoft YaHei",sans-serif; }
+    main { width:min(1180px,calc(100vw - 32px)); margin:28px auto; display:grid; gap:16px; }
+    header, section { background:#0e1e2d; border:1px solid #21465f; padding:20px; }
+    h1,h2 { margin:0 0 10px; } h1 { font-size:22px; } h2 { font-size:17px; }
+    .endpoint { color:#78a2b8; font-family:Consolas,monospace; margin:0; }
+    .toolbar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
+    button { border:1px solid #2f7098; background:#123247; color:#dff2ff; padding:8px 14px; cursor:pointer; }
+    button.active { outline:2px solid #61c2ff; }
+    .timeline { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:10px; margin-bottom:18px; }
+    .phase { border:1px solid #275b74; background:#0b1922; padding:10px; }
+    .phase strong { display:block; font-size:16px; } .phase span { color:#8fb3c7; font-size:13px; }
+    .state-card { border:1px solid #275b74; background:#0b1922; padding:16px; }
+    .state-card.CURRENT { border-color:#68d095; } .state-card.STALE { border-color:#f2c94c; }
+    .state-card.EXPIRED { border-color:#ff7a7a; } .state-card.EMPTY { border-color:#a9b7c0; }
+    .state-card.NOT_FOUND { border-color:#ff7a7a; } .state-card.SERVER_ERROR { border-color:#ff7a7a; }
+    .badge { display:inline-block; font-size:12px; padding:4px 10px; border:1px solid; margin-bottom:10px; }
+    .CURRENT { color:#68d095; border-color:#68d095; } .STALE { color:#f2c94c; border-color:#f2c94c; }
+    .EXPIRED { color:#ff7a7a; border-color:#ff7a7a; } .EMPTY { color:#a9b7c0; border-color:#a9b7c0; }
+    .NOT_FOUND, .SERVER_ERROR { color:#ff7a7a; border-color:#ff7a7a; }
+    table { width:100%; border-collapse:collapse; } th,td { border:1px solid #275b74; padding:8px; text-align:left; } th { background:#123247; width:220px; }
+    .mono { font-family:Consolas,monospace; overflow-wrap:anywhere; } pre { max-height:320px; overflow:auto; background:#071019; border:1px solid #275b74; padding:12px; }
+    .note { color:#8fb3c7; font-size:13px; }
+  </style>
+</head>
+<body>
+<main>
+  <header>
+    <h1>驾驶舱新鲜度与过期语义演示</h1>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/freshness?calibrationPeriodSeconds=60</p>
+    <p class="endpoint">HTTP:空数据 200 · 非法参数 400 · 未认证 401 · 不存在 404 · 服务故障 500</p>
+  </header>
+  <section>
+    <div class="toolbar">
+      <button type="button" data-mode="current" class="active">当前</button>
+      <button type="button" data-mode="stale">一次未更新</button>
+      <button type="button" data-mode="expired">连续两次未更新</button>
+      <button type="button" data-mode="expired-cache">缓存过期保留</button>
+      <button type="button" data-mode="empty">成功空数据</button>
+      <button type="button" data-mode="not-found">404</button>
+      <button type="button" data-mode="server-error">500</button>
+    </div>
+    <div class="timeline">
+      <div class="phase"><strong>T0</strong><span>数据更新</span></div>
+      <div class="phase"><strong>T0 + 1 周期</strong><span>STALE,保留数据</span></div>
+      <div class="phase"><strong>T0 + 2 周期</strong><span>EXPIRED,数据暂不可用</span></div>
+    </div>
+    <div id="detail" class="state-card CURRENT">
+      <span id="badge" class="badge CURRENT">CURRENT</span>
+      <h2 id="message">数据为最新</h2>
+      <table><tbody id="fields"></tbody></table>
+    </div>
+  </section>
+  <section>
+    <h2>响应契约</h2>
+    <p class="note">服务端只取 updatedAt 与 statusTime 中最新者;连续两个可配置校准周期未成功更新时标记 EXPIRED,但保留最后一次数据并显式标记。</p>
+    <pre id="payload" class="mono"></pre>
+  </section>
+</main>
+<script>
+  const clock = '2026-09-02T10:00:00+08:00';
+  const section = (state, reason, message, data) => ({ state, reason, message, data });
+  const responses = {
+    current: { code:200, data:{ requestId:'freshness-current', apiVersion:'v1', readOnly:true, deviceCode:'TC-PS-WS-202609020012',
+      updatedAt:'2026-09-02T09:59:50+08:00', statusTime:'2026-09-02T09:59:55+08:00', serverUpdatedAt:clock,
+      freshness:'CURRENT', staleReason:null, calibrationPeriodSeconds:60, missedCycles:0, dataAgeSeconds:5, retained:false, message:null,
+      section:section('CURRENT','CURRENT',null,{ dataAgeSeconds:5 }) } },
+    stale: { code:200, data:{ requestId:'freshness-stale', apiVersion:'v1', readOnly:true, deviceCode:'TC-PS-WS-202609020012',
+      updatedAt:'2026-09-02T09:59:00+08:00', statusTime:null, serverUpdatedAt:clock,
+      freshness:'STALE', staleReason:'ONE_UPDATE_CYCLE_MISSED', calibrationPeriodSeconds:60, missedCycles:1, dataAgeSeconds:60, retained:true, message:null,
+      section:section('STALE','ONE_UPDATE_CYCLE_MISSED',null,{ dataAgeSeconds:60, retained:true }) } },
+    expired: { code:200, data:{ requestId:'freshness-expired', apiVersion:'v1', readOnly:true, deviceCode:'TC-PS-WS-202609020012',
+      updatedAt:'2026-09-02T09:58:00+08:00', statusTime:null, serverUpdatedAt:clock,
+      freshness:'EXPIRED', staleReason:'TWO_UPDATE_CYCLES_MISSED', calibrationPeriodSeconds:60, missedCycles:2, dataAgeSeconds:120, retained:true, message:'数据暂不可用/已过期',
+      section:section('EXPIRED','TWO_UPDATE_CYCLES_MISSED','数据暂不可用/已过期',{ dataAgeSeconds:120, retained:true }) } },
+    'expired-cache': { code:200, data:{ requestId:'freshness-expired-cache', apiVersion:'v1', readOnly:true, deviceCode:'TC-PS-WS-202609020012',
+      updatedAt:'2026-09-02T09:57:30+08:00', statusTime:null, serverUpdatedAt:clock,
+      freshness:'EXPIRED', staleReason:'TWO_UPDATE_CYCLES_MISSED', calibrationPeriodSeconds:60, missedCycles:3, dataAgeSeconds:150, retained:true, message:'数据暂不可用/已过期',
+      section:section('EXPIRED','TWO_UPDATE_CYCLES_MISSED','数据暂不可用/已过期',{ dataAgeSeconds:150, retained:true }) } },
+    empty: { code:200, data:{ requestId:'freshness-empty', apiVersion:'v1', readOnly:true, deviceCode:'TC-PS-WS-202609020012',
+      updatedAt:null, statusTime:null, serverUpdatedAt:clock, freshness:'EMPTY', staleReason:null,
+      calibrationPeriodSeconds:60, missedCycles:0, dataAgeSeconds:0, retained:false, message:null,
+      section:section('EMPTY','NO_SOURCE',null,null) } },
+    'not-found': { code:404, error:{ category:'NOT_FOUND', message:'驾驶舱新鲜度数据不存在', requestId:'freshness-404', serverTime:clock } },
+    'server-error': { code:500, error:{ category:'SERVER_ERROR', message:'驾驶舱新鲜度数据暂不可用', requestId:'freshness-500', serverTime:clock } }
+  };
+  const fields = [
+    ['updatedAt','数据更新时间'], ['statusTime','状态时间'], ['serverUpdatedAt','服务端时间'],
+    ['staleReason','过期原因'], ['calibrationPeriodSeconds','校准周期(秒)'], ['missedCycles','未更新周期'],
+    ['dataAgeSeconds','数据年龄(秒)'], ['retained','保留旧数据']
+  ];
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
+    const payload = responses[mode];
+    const data = payload.data;
+    const state = payload.error ? payload.error.category : data.freshness;
+    const card = document.getElementById('detail');
+    card.className = 'state-card ' + state;
+    const badge = document.getElementById('badge');
+    badge.className = 'badge ' + state;
+    badge.textContent = state;
+    document.getElementById('message').textContent = payload.error ? payload.error.message : (data.message || '数据为最新');
+    document.getElementById('fields').innerHTML = payload.error
+      ? `<tr><th>requestId</th><td class="mono">${payload.error.requestId}</td></tr><tr><th>serverTime</th><td class="mono">${payload.error.serverTime}</td></tr>`
+      : fields.map(field => {
+          const value = data[field[0]];
+          return `<tr><th>${field[1]}</th><td class="mono">${value === null || value === undefined ? '未提供' : value}</td></tr>`;
+        }).join('');
+    document.getElementById('payload').textContent = JSON.stringify(payload, null, 2);
+  }
+  document.querySelectorAll('button[data-mode]').forEach(button => button.addEventListener('click', () => render(button.dataset.mode)));
+  render('current');
+</script>
+</body>
+</html>

+ 267 - 0
docs/cockpit/overview-infrastructure-demo.html

@@ -0,0 +1,267 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <title>总体概览 / 基础设施</title>
+  <style>
+    :root {
+      --ink: #172033;
+      --muted: #667085;
+      --line: #d9dee7;
+      --panel: #ffffff;
+      --page: #f3f5f8;
+      --gas: #d92d20;
+      --water: #1570ef;
+      --drainage: #067647;
+    }
+
+    * { box-sizing: border-box; }
+    body {
+      margin: 0;
+      min-height: 100vh;
+      color: var(--ink);
+      font-family: "Microsoft YaHei", "Segoe UI", Arial, sans-serif;
+      background: var(--page);
+    }
+    header {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 16px;
+      align-items: center;
+      justify-content: space-between;
+      padding: 18px 28px;
+      background: var(--panel);
+      border-bottom: 1px solid var(--line);
+    }
+    h1 { margin: 0; font-size: 20px; font-weight: 600; }
+    .status { color: var(--muted); font-size: 13px; }
+    .status strong { color: #067647; font-weight: 600; }
+    .summary {
+      display: grid;
+      grid-template-columns: repeat(4, minmax(180px, 1fr));
+      gap: 1px;
+      background: var(--line);
+      border-bottom: 1px solid var(--line);
+    }
+    .summary div { background: var(--panel); padding: 18px 28px; }
+    .summary span { display: block; color: var(--muted); font-size: 13px; }
+    .summary strong { display: block; margin-top: 5px; font-size: 26px; font-weight: 600; }
+    .layout {
+      display: grid;
+      grid-template-columns: minmax(330px, 420px) minmax(0, 1fr);
+      min-height: calc(100vh - 173px);
+    }
+    aside {
+      border-right: 1px solid var(--line);
+      background: var(--panel);
+    }
+    .filter {
+      display: flex;
+      gap: 8px;
+      padding: 16px 20px;
+      border-bottom: 1px solid var(--line);
+    }
+    button {
+      min-width: 62px;
+      height: 32px;
+      padding: 0 12px;
+      border: 1px solid var(--line);
+      border-radius: 4px;
+      background: #fff;
+      color: var(--ink);
+      font-size: 13px;
+      cursor: pointer;
+    }
+    button.active { border-color: #1570ef; background: #eff6ff; color: #175cd3; font-weight: 600; }
+    .industries { padding: 16px 20px; }
+    .industry + .industry { margin-top: 12px; border-top: 1px solid var(--line); }
+    .industry { padding-top: 12px; }
+    .industry-head {
+      display: flex;
+      justify-content: space-between;
+      align-items: baseline;
+      font-size: 15px;
+      font-weight: 600;
+    }
+    .industry-head small { color: var(--muted); font-size: 12px; }
+    .bar {
+      display: grid;
+      grid-template-columns: 70px 1fr 36px;
+      gap: 8px;
+      align-items: center;
+      margin-top: 10px;
+      font-size: 12px;
+      color: var(--muted);
+    }
+    .track { height: 8px; background: #eef1f5; overflow: hidden; }
+    .fill { height: 100%; width: 0; }
+    .facility-gas { background: var(--gas); }
+    .facility-water { background: var(--water); }
+    .facility-drainage { background: var(--drainage); }
+    .types {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 6px;
+      margin-top: 10px;
+      font-size: 12px;
+      color: #475467;
+    }
+    .types span { padding: 3px 6px; background: #f7f8fa; border-radius: 3px; }
+    .map-panel {
+      display: grid;
+      grid-template-rows: auto minmax(0, 1fr);
+      background: #dfe5ec;
+    }
+    .map-tools {
+      display: flex;
+      justify-content: space-between;
+      gap: 12px;
+      padding: 14px 20px;
+      background: var(--panel);
+      border-bottom: 1px solid var(--line);
+      font-size: 13px;
+    }
+    .legend { display: flex; gap: 14px; color: var(--muted); align-items: center; }
+    .dot-label { display: inline-flex; align-items: center; gap: 5px; }
+    .shape { width: 9px; height: 9px; border-radius: 50%; }
+    .square { border-radius: 2px; }
+    .map {
+      position: relative;
+      overflow: hidden;
+      background:
+        linear-gradient(0deg, rgba(255, 255, 255, .48) 1px, transparent 1px),
+        linear-gradient(90deg, rgba(255, 255, 255, .48) 1px, transparent 1px),
+        #dfe5ec;
+      background-size: 80px 80px, 80px 80px;
+    }
+    .point { position: absolute; width: 13px; height: 13px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 1px 4px rgba(16, 24, 40, .24); }
+    .point.facility { border-radius: 2px; transform: rotate(45deg); }
+    .point.gas { background: var(--gas); }
+    .point.water { background: var(--water); }
+    .point.drainage { background: var(--drainage); }
+    .point-label {
+      position: absolute;
+      transform: translate(14px, -4px);
+      padding: 2px 5px;
+      background: rgba(255, 255, 255, .88);
+      font-size: 11px;
+      color: #344054;
+      border-radius: 3px;
+      white-space: nowrap;
+    }
+    @media (max-width: 900px) {
+      .summary { grid-template-columns: repeat(2, 1fr); }
+      .layout { grid-template-columns: 1fr; min-height: auto; }
+      aside { border-right: 0; border-bottom: 1px solid var(--line); }
+      .map { height: 460px; }
+    }
+  </style>
+</head>
+<body>
+  <header>
+    <h1>总体概览 / 基础设施</h1>
+    <div class="status">更新时间 <strong id="updated-at">2026-09-09 10:00:00 +08:00</strong> · 状态 <strong>CURRENT</strong></div>
+  </header>
+
+  <section class="summary">
+    <div><span>设施总数</span><strong id="facility-total">418</strong></div>
+    <div><span>智能设备总数</span><strong id="device-total">1126</strong></div>
+    <div><span>未知类型</span><strong>0</strong></div>
+    <div><span>类型错挂</span><strong>0</strong></div>
+  </section>
+
+  <main class="layout">
+    <aside>
+      <div class="filter" aria-label="行业筛选">
+        <button data-industry="ALL" class="active">全部</button>
+        <button data-industry="GAS">燃气</button>
+        <button data-industry="WATER_SUPPLY">供水</button>
+        <button data-industry="DRAINAGE">排水</button>
+      </div>
+      <div class="industries" id="industries"></div>
+    </aside>
+
+    <section class="map-panel">
+      <div class="map-tools">
+        <strong id="map-title">三行业基础设施一张图</strong>
+        <div class="legend">
+          <span class="dot-label"><i class="shape facility gas"></i>设施</span>
+          <span class="dot-label"><i class="shape gas"></i>智能设备</span>
+        </div>
+      </div>
+      <div class="map" id="map"></div>
+    </section>
+  </main>
+
+  <script>
+    const summary = {
+      updatedAt: "2026-09-09T10:00:00+08:00",
+      facilityCount: 418,
+      smartDeviceCount: 1126,
+      industries: [
+        { code: "GAS", label: "燃气", facilityCount: 126, smartDeviceCount: 402,
+          facilityTypes: [{ code: "PIPELINE", name: "燃气管线", count: 86 }, { code: "PUMP_STATION", name: "泵站", count: 40 }],
+          deviceTypes: [{ code: "GAS_SENSOR", name: "燃气浓度计", count: 402 }] },
+        { code: "WATER_SUPPLY", label: "供水", facilityCount: 158, smartDeviceCount: 368,
+          facilityTypes: [{ code: "WATER_PLANT", name: "水厂", count: 38 }, { code: "PIPELINE", name: "供水管线", count: 82 }, { code: "PUMP_STATION", name: "泵站", count: 38 }],
+          deviceTypes: [{ code: "WATER_SUPPLY_SENSOR", name: "供水压力计", count: 368 }] },
+        { code: "DRAINAGE", label: "排水", facilityCount: 134, smartDeviceCount: 356,
+          facilityTypes: [{ code: "PIPELINE", name: "排水管线", count: 96 }, { code: "PUMP_STATION", name: "泵站", count: 38 }],
+          deviceTypes: [{ code: "RAINWATER_SENSOR", name: "雨水流量计", count: 186 }, { code: "SEWAGE_ENVIRONMENT_SENSOR", name: "污水环境监测仪", count: 170 }] }
+      ]
+    };
+
+    const points = [
+      { industry: "GAS", kind: "FACILITY", label: "燃气管线 A", x: 14, y: 32 },
+      { industry: "GAS", kind: "SMART_DEVICE", label: "燃气浓度计-011", x: 26, y: 54 },
+      { industry: "GAS", kind: "SMART_DEVICE", label: "燃气浓度计-024", x: 42, y: 26 },
+      { industry: "WATER_SUPPLY", kind: "FACILITY", label: "第一水厂", x: 56, y: 40 },
+      { industry: "WATER_SUPPLY", kind: "FACILITY", label: "供水管线 B", x: 68, y: 61 },
+      { industry: "WATER_SUPPLY", kind: "SMART_DEVICE", label: "供水压力计-008", x: 47, y: 70 },
+      { industry: "DRAINAGE", kind: "FACILITY", label: "排水管线 C", x: 78, y: 28 },
+      { industry: "DRAINAGE", kind: "SMART_DEVICE", label: "雨水流量计-015", x: 84, y: 48 },
+      { industry: "DRAINAGE", kind: "SMART_DEVICE", label: "污水环境监测仪-006", x: 31, y: 80 }
+    ];
+
+    const colorKey = code => code === "WATER_SUPPLY" ? "water" : code.toLowerCase();
+    const maxCount = Math.max(...summary.industries.flatMap(item => [item.facilityCount, item.smartDeviceCount]));
+
+    document.getElementById("updated-at").textContent = summary.updatedAt.replace("T", " ");
+    document.getElementById("facility-total").textContent = summary.facilityCount.toLocaleString();
+    document.getElementById("device-total").textContent = summary.smartDeviceCount.toLocaleString();
+    document.getElementById("industries").innerHTML = summary.industries.map(industry => {
+      const key = colorKey(industry.code);
+      const types = [...industry.facilityTypes, ...industry.deviceTypes]
+        .map(item => `<span>${item.name} ${item.count}</span>`).join("");
+      return `
+        <section class="industry">
+          <div class="industry-head">${industry.label}<small>${industry.code}</small></div>
+          <div class="bar"><span>设施</span><div class="track"><div class="fill facility-${key}" style="width:${industry.facilityCount / maxCount * 100}%"></div></div><span>${industry.facilityCount}</span></div>
+          <div class="bar"><span>设备</span><div class="track"><div class="fill facility-${key}" style="width:${industry.smartDeviceCount / maxCount * 100}%"></div></div><span>${industry.smartDeviceCount}</span></div>
+          <div class="types">${types}</div>
+        </section>`;
+    }).join("");
+
+    function renderMap(industry) {
+      const selected = points.filter(item => industry === "ALL" || item.industry === industry);
+      document.getElementById("map-title").textContent = industry === "ALL"
+        ? "三行业基础设施一张图"
+        : `${summary.industries.find(item => item.code === industry).label}基础设施一张图`;
+      document.getElementById("map").innerHTML = selected.map(point => `
+        <div class="point ${point.kind === "FACILITY" ? "facility " : ""}${colorKey(point.industry)}" style="left:${point.x}%;top:${point.y}%"></div>
+        <div class="point-label" style="left:${point.x}%;top:${point.y}%">${point.label}</div>`).join("");
+    }
+
+    document.querySelectorAll("[data-industry]").forEach(button => {
+      button.addEventListener("click", () => {
+        document.querySelectorAll("[data-industry]").forEach(item => item.classList.remove("active"));
+        button.classList.add("active");
+        renderMap(button.dataset.industry);
+      });
+    });
+
+    renderMap("ALL");
+  </script>
+</body>
+</html>

+ 230 - 0
docs/cockpit/overview-monitoring-demo.html

@@ -0,0 +1,230 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width,initial-scale=1">
+  <title>驾驶舱总体概览:运行监测 Demo</title>
+  <style>
+    :root { color-scheme: dark; --panel:#0d1c30; --line:#234969; --cyan:#4dd5ff; --green:#49d17c; --yellow:#ffd166; --red:#ff5f6d; --muted:#8ba7bd; }
+    * { box-sizing:border-box; }
+    body { margin:0; font-family:"Microsoft YaHei",Arial,sans-serif; background:#071322; color:#eaf5ff; }
+    header { padding:18px 24px; border-bottom:1px solid var(--line); display:flex; align-items:center; justify-content:space-between; }
+    h1 { font-size:22px; margin:0; letter-spacing:2px; }
+    main { padding:20px; display:grid; grid-template-columns:minmax(310px,430px) 1fr; gap:18px; }
+    .panel { background:var(--panel); border:1px solid var(--line); border-radius:8px; overflow:hidden; }
+    .panel > h2 { margin:0; padding:12px 14px; font-size:15px; border-bottom:1px solid var(--line); }
+    .body { padding:14px; }
+    .kpis { display:grid; grid-template-columns:repeat(3,1fr); gap:10px; }
+    .kpi { background:#08182b; border:1px solid var(--line); border-radius:6px; padding:12px; }
+    .kpi b { display:block; font-size:24px; color:var(--cyan); }
+    .kpi span { color:var(--muted); font-size:12px; }
+    .filter { display:flex; gap:8px; margin:14px 0; }
+    .filter-label { align-self:center; color:var(--muted); font-size:12px; }
+    button { cursor:pointer; background:#102c44; color:#eaf5ff; border:1px solid var(--line); padding:7px 12px; border-radius:4px; }
+    button.active { background:#1a5f83; border-color:var(--cyan); }
+    .status { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:12px; }
+    .status div { text-align:center; padding:8px; border-radius:4px; background:#08182b; border:1px solid var(--line); }
+    .online b { color:var(--green); } .offline b { color:var(--red); } .stale b { color:var(--yellow); }
+    ul { padding-left:18px; margin:0; color:#d3e9f8; }
+    li { margin:5px 0; }
+    .map { position:relative; min-height:470px; background:#020b16; }
+    .map-grid { position:absolute; inset:0; background-image:linear-gradient(#12324c 1px,transparent 1px),linear-gradient(90deg,#12324c 1px,transparent 1px); background-size:50px 50px; opacity:.45; }
+    .point { position:absolute; width:26px; height:26px; margin:-13px; border-radius:50%; display:flex; align-items:center; justify-content:center; border:2px solid transparent; cursor:pointer; }
+    .point.ONLINE { background:#0e4b29; border-color:var(--green); }
+    .point.OFFLINE { background:#57232a; border-color:var(--red); }
+    .point.STALE { background:#55431a; border-color:var(--yellow); }
+    .point.UNKNOWN { background:#283642; border-color:#7e95a8; }
+    .point small { font-size:10px; font-weight:700; }
+    .legend, .events { padding:10px 14px; border-top:1px solid var(--line); font-size:12px; color:var(--muted); }
+    .events button { margin-left:8px; }
+    .toast { position:absolute; right:14px; bottom:14px; padding:9px 13px; border-radius:4px; background:#12324c; border:1px solid var(--cyan); min-width:220px; }
+    .hidden { display:none; }
+    code { color:var(--cyan); }
+  </style>
+</head>
+<body>
+  <header>
+  <h1>总体概览 / 运行监测</h1>
+  <div><span id="restState">REST:连接中</span> · <span id="updated">更新时间:--</span></div>
+</header>
+<main>
+  <section class="panel">
+    <h2>监管能力 KPI</h2>
+    <div class="body">
+      <div class="kpis">
+        <div class="kpi"><b id="deviceCount">--</b><span>监测设备</span></div>
+        <div class="kpi"><b id="pointCount">--</b><span>监测点</span></div>
+        <div class="kpi"><b id="facilityCount">--</b><span>监测设施</span></div>
+        <div class="kpi"><b id="onlineRate">--</b><span>设备在线率</span></div>
+        <div class="kpi"><b id="staleCount">--</b><span>STALE 设备</span></div>
+        <div class="kpi"><b id="freshness">--</b><span>汇总新鲜度</span></div>
+      </div>
+      <div class="filter" id="industries">
+        <span class="filter-label">行业:</span>
+        <button data-industry="" class="active">全部</button>
+        <button data-industry="GAS">燃气</button>
+        <button data-industry="WATER_SUPPLY">供水</button>
+        <button data-industry="DRAINAGE">排水</button>
+      </div>
+      <div class="filter" id="metrics">
+        <span class="filter-label">指标:</span>
+        <button data-metric="" class="active">全部</button>
+        <button data-metric="ONLINE">在线</button>
+        <button data-metric="OFFLINE">离线</button>
+        <button data-metric="STALE">过期</button>
+        <button data-metric="UNKNOWN">未知</button>
+      </div>
+      <div class="status">
+        <div class="online"><b id="online">--</b><span>在线</span></div>
+        <div class="offline"><b id="offline">--</b><span>离线</span></div>
+        <div class="stale"><b id="stale">--</b><span>过期</span></div>
+        <div><b id="unknown">--</b><span>未知</span></div>
+      </div>
+      <h3 style="font-size:14px;margin:14px 0 8px;">类型分布</h3>
+      <ul id="distribution"></ul>
+    </div>
+  </section>
+
+  <section class="panel">
+    <h2>中央一张图联动</h2>
+    <div class="map" id="map">
+      <div class="map-grid"></div>
+    </div>
+    <div class="legend">模拟点位:绿=ONLINE,红=OFFLINE,黄=STALE,灰=UNKNOWN;行业或指标筛选会过滤地图点位。</div>
+    <div class="events">
+      <span>模拟 WebSocket 设备增量:</span>
+      <button onclick="pushDelta('GAS-002','OFFLINE','2026-09-02T10:05:00+08:00')">GAS-002 离线</button>
+      <button onclick="pushDelta('GAS-002','ONLINE','2026-09-02T10:06:00+08:00')">GAS-002 在线</button>
+      <button onclick="pushDelta('WS-001','ONLINE','2026-09-02T10:07:00+08:00')">WS-001 恢复</button>
+      <button onclick="pushOldDelta()">发送旧消息</button>
+    </div>
+    <div class="toast hidden" id="toast"></div>
+  </section>
+</main>
+
+<script>
+  const devices = [
+    { code:'GAS-001', industry:'GAS', type:'GAS_SENSOR', state:'ONLINE', x:20, y:25 },
+    { code:'GAS-002', industry:'GAS', type:'GAS_SENSOR', state:'OFFLINE', x:33, y:41 },
+    { code:'WS-001', industry:'WATER_SUPPLY', type:'WATER_SUPPLY_SENSOR', state:'STALE', x:52, y:28 },
+    { code:'WS-002', industry:'WATER_SUPPLY', type:'WATER_SUPPLY_SENSOR', state:'UNKNOWN', x:63, y:47 },
+    { code:'RAIN-001', industry:'DRAINAGE', type:'RAINWATER_SENSOR', state:'ONLINE', x:76, y:31 },
+    { code:'SEW-001', industry:'DRAINAGE', type:'SEWAGE_ENVIRONMENT_SENSOR', state:'ONLINE', x:85, y:56 }
+  ];
+  const baseCounts = { monitoringPointCount:6, monitoringFacilityCount:9, infrastructureFacilityCount:99 };
+  let selectedIndustry = '';
+  let selectedMetric = '';
+  let latestServerUpdatedAt = '2026-09-02T09:59:50+08:00';
+
+  function filteredDevices() {
+    return devices.filter(device =>
+      (!selectedIndustry || device.industry === selectedIndustry)
+      && (!selectedMetric || device.state === selectedMetric));
+  }
+
+  function fmtRate(numerator, denominator) {
+    return denominator === 0 ? '0.0000' : (numerator / denominator).toFixed(4);
+  }
+
+  function render() {
+    const visible = filteredDevices();
+    const online = visible.filter(d => d.state === 'ONLINE').length;
+    const offline = visible.filter(d => d.state === 'OFFLINE').length;
+    const stale = visible.filter(d => d.state === 'STALE').length;
+    const unknown = visible.filter(d => d.state === 'UNKNOWN').length;
+    const denominator = online + offline + stale;
+    const freshness = visible.length === 0 ? 'EMPTY' : stale === 0 ? 'CURRENT' : 'STALE';
+
+    document.getElementById('deviceCount').textContent = visible.length;
+    document.getElementById('pointCount').textContent = selectedIndustry ? Math.round(baseCounts.monitoringPointCount / 2) : baseCounts.monitoringPointCount;
+    document.getElementById('facilityCount').textContent = selectedIndustry ? 3 : baseCounts.monitoringFacilityCount;
+    document.getElementById('onlineRate').textContent = fmtRate(online, denominator);
+    document.getElementById('staleCount').textContent = stale;
+    document.getElementById('freshness').textContent = freshness;
+    document.getElementById('online').textContent = online;
+    document.getElementById('offline').textContent = offline;
+    document.getElementById('stale').textContent = stale;
+    document.getElementById('unknown').textContent = unknown;
+    document.getElementById('updated').textContent = '更新时间:' + latestServerUpdatedAt;
+
+    const counts = new Map();
+    visible.forEach(d => counts.set(d.type, (counts.get(d.type) || 0) + 1));
+    document.getElementById('distribution').innerHTML = [...counts.entries()]
+      .map(([type, count]) => `<li><code>${type}</code>:${count} 台设备</li>`).join('');
+
+    const map = document.getElementById('map');
+    map.querySelectorAll('.point').forEach(node => node.remove());
+    visible.forEach(d => {
+      const point = document.createElement('div');
+      point.className = 'point ' + d.state;
+      point.style.left = d.x + '%';
+      point.style.top = d.y + '%';
+      point.title = `${d.code}\n${d.industry}\n${d.type}\n${d.state}`;
+      point.innerHTML = '<small>' + d.code.slice(0, 3) + '</small>';
+      point.onclick = () => show(d.code + ' / ' + d.state);
+      map.appendChild(point);
+    });
+  }
+
+  function show(message) {
+    const toast = document.getElementById('toast');
+    toast.textContent = message;
+    toast.classList.remove('hidden');
+    setTimeout(() => toast.classList.add('hidden'), 2200);
+  }
+
+  function pushDelta(deviceCode, state, serverUpdatedAt) {
+    if (serverUpdatedAt <= latestServerUpdatedAt) {
+      show('旧消息已忽略:' + serverUpdatedAt);
+      return;
+    }
+    const device = devices.find(d => d.code === deviceCode);
+    if (!device) return;
+    device.state = state;
+    latestServerUpdatedAt = serverUpdatedAt;
+    render();
+    show('已应用增量:' + deviceCode + ' → ' + state);
+  }
+
+  function pushOldDelta() {
+    pushDelta('GAS-002', 'ONLINE', '2026-09-02T09:00:00+08:00');
+  }
+
+  function bindFilter(containerId, apply) {
+    document.getElementById(containerId).addEventListener('click', event => {
+    const button = event.target.closest('button');
+    if (!button) return;
+      document.querySelectorAll('#' + containerId + ' button').forEach(node => node.classList.remove('active'));
+    button.classList.add('active');
+      apply(button.dataset);
+      render();
+    });
+  }
+
+  bindFilter('industries', dataset => { selectedIndustry = dataset.industry; });
+  bindFilter('metrics', dataset => { selectedMetric = dataset.metric; });
+
+  async function loadRestInitialSummary() {
+    try {
+      const response = await fetch('/api/cockpit/v1/overview/monitoring', {
+        headers: { 'Accept': 'application/json' }
+      });
+      if (!response.ok) throw new Error('HTTP ' + response.status);
+      const payload = await response.json();
+      if (payload && payload.data && payload.data.updatedAt) {
+        latestServerUpdatedAt = payload.data.updatedAt;
+        document.getElementById('restState').textContent = 'REST:已加载初始汇总';
+      } else {
+        throw new Error('INVALID_ENVELOPE');
+      }
+    } catch (error) {
+      document.getElementById('restState').textContent = 'REST:接口不可用,使用演示 fixture';
+    }
+    render();
+  }
+
+  loadRestInitialSummary();
+  render();
+</script>
+</body>
+</html>

+ 180 - 0
docs/cockpit/websocket-scope-delta-demo.html

@@ -0,0 +1,180 @@
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <title>Cockpit WebSocket Scope Delta Demo</title>
+  <style>
+    :root { color-scheme: light; font-family: Arial, sans-serif; }
+    * { box-sizing: border-box; }
+    body { margin: 0; background: #f4f7fb; color: #172b4d; }
+    header { background: #17324d; color: white; padding: 24px 32px; }
+    h1 { margin: 0; font-size: 22px; }
+    p { margin: 8px 0 0; opacity: .8; }
+    main { max-width: 1080px; margin: 0 auto; padding: 24px; }
+    .toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 20px; }
+    button { border: 1px solid #2557a7; background: white; color: #2557a7; padding: 8px 12px; cursor: pointer; }
+    button.primary { background: #2557a7; color: white; }
+    button:disabled { opacity: .5; cursor: not-allowed; }
+    .grid { display: grid; grid-template-columns: 1fr 360px; gap: 20px; }
+    .panel { background: white; border: 1px solid #d5dce6; padding: 16px; }
+    .panel h2 { margin-top: 0; font-size: 16px; }
+    #devices { display: grid; gap: 10px; }
+    .device { border: 1px solid #dde3ec; padding: 10px 12px; }
+    .device-name { font-weight: 700; }
+    .status { display: inline-block; min-width: 82px; text-align: center; padding: 2px 6px; color: white; font-size: 12px; }
+    .ALARM { background: #c53030; } .WORK_ORDER { background: #b7791f; } .OFFLINE { background: #4a5568; }
+    .NORMAL { background: #2f855a; } .EMPTY { background: #4a5568; }
+    .meta { color: #5d6b82; font-size: 12px; margin-top: 4px; }
+    #events { height: 320px; overflow: auto; font: 12px/1.5 Consolas, monospace; background: #f7f9fc; padding: 10px; }
+    .event-old { color: #b83280; } .event-push { color: #2c7a7b; } .event-state { color: #805ad5; }
+    @media (max-width: 860px) { .grid { grid-template-columns: 1fr; } }
+  </style>
+</head>
+<body>
+  <header>
+    <h1>Cockpit WebSocket Scope Delta Demo</h1>
+    <p>REST is the authoritative initial snapshot. WebSocket deltas are accepted only when serverUpdatedAt is newer.</p>
+  </header>
+  <main>
+    <div class="toolbar">
+      <button class="primary" id="load">1. Load REST snapshot</button>
+      <button id="replay" disabled>2. Replay pushes / reconnect</button>
+      <button id="live">Connect live WebSocket</button>
+    </div>
+    <div class="grid">
+      <section class="panel">
+        <h2>Devices</h2>
+        <div id="devices"></div>
+      </section>
+      <section class="panel">
+        <h2>Protocol events</h2>
+        <div id="events"></div>
+      </section>
+    </div>
+  </main>
+  <script>
+    const REST_URL = "http://localhost:8300/api/cockpit/v1/map-snapshot";
+    const WS_URL = "ws://localhost:8300/ws/deviceStatus";
+    let snapshotLoaded = false;
+    const latest = new Map();
+    const sampleDevices = [
+      { code: "TC-PS-WS-202609020001", name: "Pressure monitor 001", status: "NORMAL", statusTime: "2026-09-02T09:58:00+08:00", serverUpdatedAt: "2026-09-02T10:00:00+08:00" },
+      { code: "TC-PS-WS-202609020002", name: "Pressure monitor 002", status: "NORMAL", statusTime: "2026-09-02T09:58:00+08:00", serverUpdatedAt: "2026-09-02T10:00:00+08:00" }
+    ];
+    const scriptedMessages = [
+      { type: "cockpitDeviceStatusDelta", deviceCode: "TC-PS-WS-202609020001", device_code: "TC-PS-WS-202609020001",
+        data: { status: "ALARM", statusTime: "2026-09-02T10:01:00+08:00", serverUpdatedAt: "2026-09-02T10:01:00+08:00" } },
+      { type: "cockpitDeviceStatusDelta", deviceCode: "TC-PS-WS-202609020001", device_code: "TC-PS-WS-202609020001",
+        data: { status: "NORMAL", statusTime: "2026-09-02T10:00:30+08:00", serverUpdatedAt: "2026-09-02T10:00:30+08:00" } },
+      { type: "cockpitDeviceStatusDelta", deviceCode: "TC-PS-WS-202609020099", device_code: "TC-PS-WS-202609020099",
+        data: { status: "EMPTY", reason: "DEVICE_NOT_FOUND", statusTime: null, serverUpdatedAt: "2026-09-02T10:02:00+08:00" } },
+      { type: "__disconnect" },
+      { type: "__reconnect" },
+      { type: "cockpitDeviceStatusDelta", deviceCode: "TC-PS-WS-202609020001", device_code: "TC-PS-WS-202609020001",
+        data: { status: "NORMAL", statusTime: "2026-09-02T10:03:00+08:00", serverUpdatedAt: "2026-09-02T10:03:00+08:00" } }
+    ];
+
+    function time(value) {
+      return value ? value.replace("T", " ") : "-";
+    }
+    function log(message, className) {
+      const node = document.createElement("div");
+      node.textContent = message;
+      if (className) node.className = className;
+      document.getElementById("events").appendChild(node);
+      document.getElementById("events").scrollTop = document.getElementById("events").scrollHeight;
+    }
+    function render() {
+      const root = document.getElementById("devices");
+      root.replaceChildren();
+      sampleDevices.forEach((device, index) => {
+        const current = latest.get(device.code) || device;
+        const item = document.createElement("article");
+        item.className = "device";
+        item.innerHTML = `<div class="device-name">${device.name}</div>
+          <span class="status ${current.status}">${current.status}</span>
+          <div class="meta">${device.code}<br>statusTime: ${time(current.statusTime)}<br>serverUpdatedAt: ${time(current.serverUpdatedAt)}</div>`;
+        root.appendChild(item);
+      });
+      document.getElementById("replay").disabled = !snapshotLoaded;
+    }
+    function accept(message) {
+      if (!message || message.type !== "cockpitDeviceStatusDelta") return;
+      const code = message.deviceCode;
+      const data = message.data || {};
+      const previous = latest.get(code);
+      if (previous && data.serverUpdatedAt <= previous.serverUpdatedAt) {
+        log(`IGNORED OLD ${code} @ ${data.serverUpdatedAt}`, "event-old");
+        return;
+      }
+      latest.set(code, data);
+      render();
+      log(`DELTA ${code} -> ${data.status}${data.reason ? ` (${data.reason})` : ""}`, "event-push");
+    }
+    function loadSnapshot() {
+      log(`GET ${REST_URL}`);
+      fetch(REST_URL, { headers: { Accept: "application/json" } })
+        .then((response) => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`)))
+        .then((body) => {
+          const points = body.data?.monitoringPoints || [];
+          const unassociated = body.data?.unassociatedEquipment || [];
+          points.forEach((point, index) => {
+            const code = `${point.pointCode}-DEMO`;
+            latest.set(code, { status: point.pointStatus || "EMPTY", statusTime: body.data.snapshotAt, serverUpdatedAt: body.data.snapshotAt });
+            sampleDevices[index] = { code, name: point.pointName || code, status: point.pointStatus || "EMPTY", statusTime: body.data.snapshotAt, serverUpdatedAt: body.data.snapshotAt };
+          });
+          unassociated.forEach((device, index) => {
+            const offset = points.length + index;
+            const code = device.deviceCode;
+            latest.set(code, { status: "EMPTY", statusTime: null, serverUpdatedAt: body.data.snapshotAt });
+            sampleDevices[offset] = { code, name: device.deviceName || code, status: "EMPTY", statusTime: null, serverUpdatedAt: body.data.snapshotAt };
+          });
+          snapshotLoaded = true;
+          log(`SNAPSHOT ${body.data.snapshotAt}`, "event-state");
+          render();
+        })
+        .catch(() => {
+          sampleDevices.forEach((device) => latest.set(device.code, device));
+          snapshotLoaded = true;
+          log("SNAPSHOT fallback sample (REST unavailable)", "event-state");
+          render();
+        });
+    }
+    function replay() {
+      let index = 0;
+      const step = () => {
+        if (index >= scriptedMessages.length) return;
+        const message = scriptedMessages[index++];
+        if (message.type === "__disconnect") {
+          log("DISCONNECTED", "event-state");
+        } else if (message.type === "__reconnect") {
+          log("RECONNECT {\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}", "event-state");
+        } else {
+          accept(message);
+        }
+        setTimeout(step, 650);
+      };
+      step();
+    }
+    function connectLive() {
+      const socket = new WebSocket(WS_URL);
+      socket.onopen = () => {
+        log("WEBSOCKET OPEN", "event-state");
+        socket.send(JSON.stringify({ type: "cockpitSubscribe", scope: "all" }));
+      };
+      socket.onmessage = (event) => {
+        const message = JSON.parse(event.data);
+        log(`MESSAGE ${JSON.stringify(message)}`, message.type === "cockpitDeviceStatusDelta" ? "event-push" : "event-state");
+        accept(message);
+      };
+      socket.onclose = () => log("WEBSOCKET CLOSED", "event-state");
+      socket.onerror = () => log("WEBSOCKET UNAVAILABLE; use scripted replay", "event-old");
+    }
+    document.getElementById("load").addEventListener("click", loadSnapshot);
+    document.getElementById("replay").addEventListener("click", replay);
+    document.getElementById("live").addEventListener("click", connectLive);
+    render();
+  </script>
+</body>
+</html>

+ 127 - 0
docs/cockpit/work-order-seven-states-demo.html

@@ -0,0 +1,127 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Work Order Seven States Demo</title>
+  <style>
+    body { margin:0; min-height:100vh; background:#08131f; color:#e8f1f8; font:15px/1.5 "Microsoft YaHei",sans-serif; }
+    main { width:min(1280px,calc(100vw - 32px)); margin:28px auto; display:grid; gap:16px; }
+    header, section { background:#0e1e2d; border:1px solid #21465f; padding:20px; }
+    h1,h2,h3 { margin:0 0 10px; } h1 { font-size:22px; } h2 { font-size:17px; } h3 { font-size:15px; }
+    .endpoint { color:#78a2b8; font-family:Consolas,monospace; margin:0; }
+    .toolbar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
+    button { border:1px solid #2f7098; background:#123247; color:#dff2ff; padding:8px 14px; cursor:pointer; }
+    button.active { outline:2px solid #61c2ff; }
+    .layout { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; align-items:start; }
+    .orders { display:grid; gap:12px; }
+    .order { border:1px solid #275b74; background:#0b1922; padding:12px; }
+    .order.alarm { border-color:#ff7a7a; } .order.warning { border-color:#f2c94c; }
+    .title { display:flex; justify-content:space-between; gap:8px; align-items:flex-start; }
+    .code { color:#78a2b8; font-family:Consolas,monospace; font-size:12px; overflow-wrap:anywhere; }
+    .badge { font-size:12px; padding:3px 8px; border:1px solid; white-space:nowrap; }
+    .active { color:#68d095; border-color:#68d095; } .cancelled { color:#ff7a7a; border-color:#ff7a7a; } .finished { color:#a9b7c0; border-color:#a9b7c0; }
+    .timeline { margin-top:10px; display:grid; gap:8px; }
+    .entry { border-left:3px solid #61c2ff; background:#0e1e2d; padding:8px 10px; }
+    .entry.cancelled { border-left-color:#ff7a7a; } .entry.finished { border-left-color:#a9b7c0; }
+    .meta { color:#8fb3c7; font-size:13px; margin:6px 0 0; overflow-wrap:anywhere; }
+    .dictionary { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:8px; }
+    .state { border:1px solid #275b74; background:#0b1922; padding:8px; } .state.cancelled { border-color:#ff7a7a; }
+    .mono { font-family:Consolas,monospace; overflow-wrap:anywhere; } pre { max-height:340px; overflow:auto; background:#071019; border:1px solid #275b74; padding:12px; }
+    .note { color:#8fb3c7; font-size:13px; }
+  </style>
+</head>
+<body>
+<main>
+  <header>
+    <h1>驾驶舱事件关联工单七态演示</h1>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/work-orders</p>
+    <p class="endpoint">GET /api/cockpit/v1/events/{eventSource}/{eventCode}/work-orders</p>
+    <p class="endpoint">GET /api/cockpit/v1/work-orders/{workOrderCode}/timeline</p>
+  </header>
+  <section>
+    <div class="toolbar">
+      <button type="button" data-mode="all" class="active">七态总览</button>
+      <button type="button" data-mode="multi">同设备多类型报警</button>
+    </div>
+    <div class="layout">
+      <div>
+        <h2>工单列表</h2>
+        <div id="orders" class="orders"></div>
+      </div>
+      <div>
+        <h2>状态字典</h2>
+        <div id="dictionary" class="dictionary"></div>
+      </div>
+    </div>
+  </section>
+  <section>
+    <h2>响应契约</h2>
+    <p class="note">状态字典采用 ADR-0008 新七态:1 待派单、2 待接单、3 已接单、4 处理中、5 待验收、6 已结案、7 已取消;已废止状态不再输出。</p>
+    <pre id="payload" class="mono"></pre>
+  </section>
+</main>
+<script>
+  const stateDictionary = [
+    {code:1,name:'待派单'}, {code:2,name:'待接单'}, {code:3,name:'已接单'},
+    {code:4,name:'处理中'}, {code:5,name:'待验收'}, {code:6,name:'已结案'}, {code:7,name:'已取消'}
+  ];
+  const summary = (code, state, source, eventCode, desc) => {
+    const stateName = stateDictionary[state - 1].name;
+    return {
+      workOrderCode:code, deviceCode:'TC-PS-WS-202609020012', orderType:1, orderTypeName:'故障维修',
+      orderLevel:2, orderDesc:desc,
+      stateCode:state, stateName,
+      createTime:'2026-09-02T09:00:00+08:00', updateTime:'2026-09-02T10:00:00+08:00',
+      planFinishTime:'2026-09-03T09:00:00+08:00', realFinishTime:state === 6 ? '2026-09-02T10:00:00+08:00' : null,
+      eventAssociation:{ eventSource:source, eventCode, associatedAt:'2026-09-02T10:00:00+08:00' }
+    };
+  };
+  const allOrders = stateDictionary.map(state => summary(
+    'WO-202609020000' + state.code, state.code, 'ALARM', 'ALM-20260902-00' + state.code, '演示第 ' + state.code + ' 态'));
+  const multiOrders = [
+    summary('WO-2026090200101', 4, 'ALARM', 'ALM-WS_ENV_HIGH-001', '污水COD超标维修'),
+    summary('WO-2026090200102', 5, 'ALARM', 'ALM-WS_ENV_PH-002', '污水pH越界维修')
+  ];
+  const timelines = {
+    'WO-2026090200101': ['创建:待派单','派单:待接单','开始处置:处理中'],
+    'WO-2026090200102': ['创建:待派单','派单:待接单','提交验收:待验收']
+  };
+  function badgeClass(order) {
+    if (order.stateCode === 6) return 'finished';
+    if (order.stateCode === 7) return 'cancelled';
+    return 'active';
+  }
+  function renderOrder(order) {
+    const timeline = timelines[order.workOrderCode] || ['创建:' + order.stateName];
+    return `<article class="order ${order.eventAssociation.eventSource === 'ALARM' ? 'alarm' : 'warning'}">
+      <div class="title">
+        <div><h3>${order.orderDesc}</h3><div class="code">${order.workOrderCode}</div></div>
+        <span class="badge ${badgeClass(order)}">${order.stateCode} ${order.stateName}</span>
+      </div>
+      <p class="meta">事件:${order.eventAssociation.eventSource} ${order.eventAssociation.eventCode}</p>
+      <div class="timeline">${timeline.map(item => `<div class="entry ${badgeClass(order)}">${item}</div>`).join('')}</div>
+    </article>`;
+  }
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
+    const orders = mode === 'all' ? allOrders : multiOrders;
+    document.getElementById('orders').innerHTML = orders.map(renderOrder).join('');
+    document.getElementById('dictionary').innerHTML = stateDictionary.map(state => `
+      <div class="state ${state.code === 7 ? 'cancelled' : ''}"><strong>${state.code} ${state.name}</strong>
+        <p class="meta">${state.code === 7 ? '终态' : '中间态'}</p>
+      </div>`).join('');
+    document.getElementById('payload').textContent = JSON.stringify({
+      code:200, msg:'操作成功', data:{
+        requestId:'work-order-demo', apiVersion:'v1', readOnly:true,
+        deviceCode:'TC-PS-WS-202609020012', eventSource:mode === 'all' ? null : 'ALARM',
+        eventCode:mode === 'all' ? null : 'WS_ENV_MULTI', state:'READY', stateReason:'READY',
+        stateDictionary, workOrders:orders
+      }
+    }, null, 2);
+  }
+  document.querySelectorAll('button[data-mode]').forEach(button => button.addEventListener('click', () => render(button.dataset.mode)));
+  render('all');
+</script>
+</body>
+</html>

+ 99 - 0
docs/superpowers/specs/2026-08-26-water-supply-alarm-work-order-acceptance-fixes.md

@@ -0,0 +1,99 @@
+# 供水报警与工单验收问题修复规格
+
+> **2026-09-04 口径注记**:本规格写于旧状态编码期(现网 1-9)。工单状态以七态共识为权威:验收驳回是“待验收回退到处理中”的动作而非终态、新增任意中间态可进入的“已取消”终态、删除延期,见 [ADR-0008](../../../pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md) 与 [work-order-lifecycle.md](../../../pipe-network-service/docs/domain/work-order-lifecycle.md)。本文“申请延期”表述作废。
+
+## Problem Statement
+
+供水系统路由和菜单结构已经通过人工验收,但业务功能验收未通过。设备维修派单、设备异常管理、报警管理、报警审核和报警工单处置在数据准入、报警转工单、工单状态流转、详情可读性和页面职责方面仍不满足已确认的供水领域规则。部分页面无法产生可测试的待派单数据,报警编码或设备报警状态展示不准确,同一设备同一报警类型可重复生成未结束工单,审核驳回状态和处置图片输入也不符合实际闭环。
+
+本规格遵循 `pipe-network-service/docs/adr/0001-unify-device-work-under-work-orders.md` 与 `0002-runtime-owns-device-alarm-state.md`:维修请求和报警转入统一使用故障维修工单(类型 `1`);设备报警状态由运行系统及有效报警原因维护,工单结案只触发清警复核,不能无条件直接清警。
+
+## Solution
+
+修正供水后端 REST 契约和前端页面,使异常设备、报警记录和供水工单都能从真实数据进入可重复验证的闭环:
+
+- 仅展示供水类型监测设备,并明确异常设备的判定来源和筛选规则。
+- 报警记录先确保生成唯一的待派单故障维修工单,再由报警审核或其他允许入口完成责任人派发。
+- 以设备和报警编码限制未结束工单重复创建;报警编码缺失时回退到报警分类。
+- 报警审核提供工单状态数量、责任人派发、接单、开始处理、处理说明及前后置图片、提交验收、验收通过和驳回回处理中。
+- 报警管理只负责态势展示、详情和报警转工单,不承载后续处置。
+- 设备异常管理重做为异常态势与统计入口;设备维修派单聚焦没有适用未结束故障维修工单的异常设备。
+- 设备详情使用右侧抽屉,状态字段采用统一背景框;派单窗口使用左侧部门树和责任人、右侧工单类型/优先级/描述布局。
+- “报警工单处置”页面保留菜单名称兼容性,但页面标题和职责改为“供水工单总览”,承载全部供水工单检索与后续处置。
+
+## User Stories
+
+1. 作为供水运维人员,我想只看到供水类型的监测设备,以免误派其他系统设备。
+2. 作为供水运维人员,我想知道设备为什么进入设备异常清单,以便判断是否可以派发故障维修工单。
+3. 作为派单人员,我想在设备维修派单页看到当前设备状态、设备报警状态、在线状态、报警等级、关联工单编号和维修状态,以便选择正确的设备。
+4. 作为派单人员,我想对没有适用未结束故障维修工单的异常设备发起派单,以便异常设备具备可测试的待派单入口。
+5. 作为派单人员,我想看到真实的工单编号 `order_no`,而不是数据库随机 ID。
+6. 作为派单人员,我想在设备详情右侧抽屉查看列表和详情,以便不丢失上下文。
+7. 作为派单人员,我想用统一样式辨识设备当前状态、报警状态、在线状态、报警等级和维修状态。
+8. 作为派单人员,我想在派单窗口左侧选择部门和单一责任人,右侧填写工单类型、优先级和问题描述,以便快速完成派单。
+9. 作为系统,我想保证设备维修派单生成的工单类型固定为故障维修(`1`)。
+10. 作为异常管理人员,我想在设备异常管理看到异常设备数量、按报警等级/状态的统计和当前报警原因,以便先判断整体态势再进入单设备操作。
+11. 作为报警管理人员,我想看到报警编码、报警类型、报警等级、设备报警状态、报警记录状态和关联工单状态的独立字段。
+12. 作为报警管理人员,我想按红、橙、蓝、绿显示一级、二级、三级、四级报警,并同时显示文字。
+13. 作为报警管理人员,我想从报警记录触发“确保待派单工单存在”,而不是直接绕过待派单状态派发责任人。
+14. 作为系统,我想阻止同一设备同一报警编码同时创建多个未结束故障维修工单。
+15. 作为系统,当报警编码缺失时,我想按报警分类阻止同设备重复生成未结束工单。
+16. 作为系统,我想允许同一设备的不同报警编码分别生成故障维修工单。
+17. 作为报警审核人员,我想在进入页面时看到全部工单、待处理、处理中、待验收、已完成等状态数量。
+18. 作为报警审核人员,我想只在报警审核页处理供水设备故障维修工单。
+19. 作为责任人,我想先接单,再开始处理,并在处理前提交现场图片或说明。
+20. 作为责任人,我想在提交验收时填写简要处理说明并上传处置后图片,而不是填写验收意见。
+21. 作为派单或管理人员,我想在提交验收后看到处理前图片、处置后图片和完整工单信息,以便进行验收审核。
+22. 作为审核人员,我想验收通过后结案,并保留工单日志和图片证据。
+23. 作为审核人员,我想驳回验收后让工单返回处理中,以便责任人重新处置,而不是取消流程。
+24. 作为运行系统,我想在工单结案时触发清警复核,只有不存在其他有效报警原因时才将设备报警状态恢复正常。
+25. 作为运行系统,我想同一设备存在多个有效报警原因时保留设备报警状态,不因单个工单结案而直接清警。
+26. 作为工单管理人员,我想在供水工单总览查看全部供水类型工单,并按工单类型、来源、责任人和状态筛选。
+27. 作为供水责任人,即使巡检或保养工单由其他系统创建,只要工单派给我,我仍想在供水工单总览继续接单、处理和提交验收。
+28. 作为用户,我想刷新五个页面后仍保持正确路由、菜单和数据职责,不出现页面错位或重复菜单。
+29. 作为测试人员,我想通过 REST/真实数据库接缝验证建单去重、状态流转、图片保存、驳回回处理中和设备报警状态复核。
+30. 作为测试人员,我想通过浏览器页面接缝验证五个页面的数据范围、按钮集合、抽屉和派单窗口布局。
+
+## Implementation Decisions
+
+- 后端以设备类型树作为设备和工单查询的系统归属边界;供水页面只返回供水设备,工单仍使用跨系统统一业务流程并按关联设备类型过滤,不为供水单独复制一套生命周期。
+- `/api/work-order` 作为跨系统规范工单 API;供水、排水、燃气、窨井旧接口通过兼容适配接入,不复制平行工单生命周期。
+- 统一工单使用现有数据库状态机和事务服务;新日志采用统一操作语义,历史日志通过兼容映射展示。
+- 工单处理前和处置后图片统一使用现有 MinIO 保存对象、KingbaseES 保存附件元数据;现有 `work_order` 图片 URL 字段保留兼容,新上传附件按阶段记录并由后端提供受控访问地址。
+- 报警转工单接口负责幂等地创建待派单故障维修工单,并返回工单 ID、工单编号、工单类型、状态和关联报警信息。报警管理入口不得直接把责任人写入报警创建接口。
+- 未结束状态包括待派单、待接单、已接单、处理中、待验收以及其他未终止状态;同一设备与报警编码只能有一个。报警编码为空时使用报警分类作为去重键。
+- 维修派单入口只能对没有适用未结束故障维修工单的供水异常设备启用;已有工单时显示真实 `order_no`、责任人和当前状态,并提供查看入口。
+- 报警管理和报警审核分别使用设备报警状态与报警记录状态字段,不能互相替代;设备报警状态来源于设备状态表,报警记录状态仅作为辅助历史信息。
+- 报警审核页面聚焦供水故障维修工单,提供状态统计和完整工单操作;报警管理只提供详情、确保建单和跳转后续处置入口。
+- 工单状态机(本文沿用迁移前现网编码 1-6;目标七态编码 1-7 与独立“已取消”终态见 [ADR-0008](../../../pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md))保持:`1 待派单 -> 2 待接单 -> 3 已接单 -> 4 处理中 -> 5 待验收 -> 6 已结案`;验收驳回从 `5` 返回 `4`,不进入终止状态;任意中间态可由管理员取消进入终态“已取消”(迁移前取消暂落旧值,迁移后为目标编码 7),不存在“已驳回”终态与延期状态。
+- 处理操作支持处理说明和处理前图片;提交验收支持处置说明和处置后图片;图片和说明随工单详情及操作日志返回。
+- 工单结案只执行清警复核;复核检查该设备所有有效报警原因,存在任一原因时保持 `equipment_status.alarm_status=1`,全部恢复后才写入 `0`。
+- 设备异常管理采用异常指标带、筛选、设备异常表和右侧详情抽屉;设备维修派单采用待派单队列和突出派单动作;报警管理采用报警态势表和右侧详情抽屉;报警审核采用左列表右工作台;供水工单总览采用全部供水工单主从工作台。
+- 派单弹窗固定为左侧部门树/责任人、右侧工单类型/优先级/问题描述;只提交选中用户 ID,不允许前端手写权威姓名或电话。
+- 菜单名称“报警工单处置”保持兼容,但页面可见标题和说明使用“供水工单总览”。
+
+## Testing Decisions
+
+- 最高层公共 seam 采用真实登录态浏览器端的供水报警工单端到端业务流程:从五个供水页面进入真实后端 API 和真实数据库,以用户可观察结果验证整个闭环,不把私有 Java 方法或内部 Vue 实现作为独立测试目标。
+- 端到端流程必须覆盖供水设备过滤、报警数据加载、报警记录确保建单幂等、同设备同报警编码去重、不同报警编码可建单、故障维修类型、责任人派单、接单、开始处理、处理说明、处理前图片、提交验收、处置后图片、验收通过、驳回回处理中、再次处理和结案。
+- 端到端流程必须通过页面刷新和关联详情确认三类状态分别正确:设备报警状态来自设备状态表,报警记录状态来自报警记录,工单状态来自工单;同时验证工单日志和图片证据可回看。
+- 端到端流程必须验证同一设备存在多个有效报警原因时,单个工单结案只触发清警复核而不错误清警;所有有效原因恢复后才显示设备正常。
+- 端到端页面验收覆盖 1440px、1024px 和 390px:设备维修派单、设备异常管理、报警管理、报警审核、供水工单总览五页的加载、刷新、职责区分、状态统计、右侧抽屉、派单弹窗和工单操作。
+- 自动化回归作为该 seam 的支撑证据,包括前端已有 Node 测试、`npm run build:prod`、后端 Maven 测试、真实数据库迁移校验、`git diff --check`,以及浏览器控制台无应用级错误;测试断言外部行为和业务契约。
+- 采用现有燃气、窨井工单处置模块作为视觉和处置交互先例。
+- 图片验收除页面展示外,还需确认附件元数据中的工单关联、阶段、上传人和时间,以及历史 URL 兼容读取。
+
+## Out of Scope
+
+- 不在供水系统创建或首次派发日常巡检、设备保养工单。
+- 不修改门户、窨井和供水菜单名称及已通过验收的路由结构,除非修复本规格涉及的兼容跳转。
+- 不实现新的按钮级权限编码;沿用后端现有权限校验,待编码明确后另行配置。
+- 不改变报警等级的后端计算算法,只修正返回、展示和颜色表达。
+- 不将报警记录“已处理”改造成设备报警状态,不以工单结案直接覆盖运行系统的自动清警职责。
+- 不合并或推送执行者 worktree 的代码。
+
+## Further Notes
+
+- 当前人工验收结论为:路由回归通过;设备维修派单、设备异常管理、报警管理、报警审核、报警工单处置和写操作闭环不通过;设备报警闭环通过但需继续验证多报警原因场景。
+- 当前已知真实环境风险是同一设备存在多个报警原因时的清警复核,以及前端报警编码、设备报警状态字段映射不完整。
+- 已确认最高层公共 seam 为真实登录态浏览器端的供水报警工单端到端业务流程。spec 发布后再重新唤醒后端和前端执行者;执行者继续使用 `gpt-5.6-terra`、推理强度 `high`,从现有隔离 worktree 工作,不得合并或推送。

+ 115 - 0
docs/superpowers/specs/2026-08-27-water-supply-subsystem-e2e-delivery.md

@@ -0,0 +1,115 @@
+# 供水管网安全运行监测系统前后端整体交付规格
+
+> **2026-09-04 口径注记**:本规格写于旧状态编码期(现网 1-9)。工单状态以七态共识为权威:目标编码 1-7、验收驳回是“待验收回退到处理中”的动作而非终态、新增任意中间态可进入的“已取消”终态、删除延期,见 [ADR-0008](../../../pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md) 与 [work-order-lifecycle.md](../../../pipe-network-service/docs/domain/work-order-lifecycle.md)。
+
+## Problem Statement
+
+“城市地下管网及设施建设改造智能化系统项目”的软件平台由“地下管网管控平台”及其业务子系统组成。本规格针对其中的“供水管网安全运行监测系统”,要求 `pipe-ner-server` 后端与 `city-life-line` 前端形成可独立构建、可通过版本化 REST 契约集成验收的完整业务体验。
+
+当前系统的路由和菜单已经完成多轮人工修正,但供水业务仍需要以一个统一的外部行为标准验收:用户能从门户进入供水系统,查看供水设施、供水监测设备和报警态势,并将真实报警推进到统一工单生命周期。设备维修派单、设备异常管理、报警管理、报警审核和供水工单总览必须职责清晰、数据来源可追溯、页面刷新后状态一致。
+
+现有问题集中在跨前后端边界:供水设备过滤和异常判定不稳定,报警记录与设备报警状态容易混淆,报警转工单和责任人派发阶段混淆,同一设备同一报警类型可能重复建单,工单处置证据和状态流转不完整,且部分页面仍可能依赖模拟数据或返回无法解释的错误。测试必须以真实登录态、真实 REST API 和 KingbaseES 数据为依据,不能以 PostgreSQL、随机模拟数据或私有实现细节代替生产真相。
+
+## Solution
+
+交付一个完整的供水管网安全运行监测系统版本,前后端共同遵守已确认的领域模型、统一工单生命周期和 KingbaseES 数据契约:
+
+- 以门户到供水系统的真实浏览器流程作为最高层公共验收接缝。
+- 供水设施管理覆盖管网信息查询、水厂信息查询、泵站信息查询、水源地信息查询、用水户信息查询、管网数据统计分析和供水设施 GIS 一张图。
+- 监测设备管理覆盖供水设备台账、设备异常管理、设备维修派单、设备维修记录和监测设备 GIS 一张图;只展示设备类型树归属为供水的设备。
+- 运行监测覆盖流量监测、压力监测和漏失监测,展示真实监测数据及其查询、导出能力。
+- 监测报警覆盖报警管理、报警审核、阈值管理和监测报警一张图;报警管理偏重态势与报警转工单,报警审核偏重供水故障维修工单的完整处置。
+- 报警记录进入处置流程时幂等生成不指定责任人的 `1-故障维修` 待派单工单;后续由统一工单流程指定唯一接单责任人。
+- 统一工单视图作为“供水工单总览”使用,集中检索和处置全部供水类型工单,包括故障维修、日常巡检和设备保养;菜单兼容名称“报警工单处置”不擅自修改。
+- 工单结案只触发清警复核;运行系统确认设备不存在任何有效报警原因后,才将设备报警状态恢复为正常。
+
+## User Stories
+
+1. As a 项目用户, I want to 从门户进入供水管网安全运行监测系统首页, so that 我能在正确的业务系统上下文中工作。
+2. As a 项目用户, I want to 看到稳定的供水菜单层级和菜单图标, so that 我能按设施、设备、监测和报警职责定位功能。
+3. As a 供水设施管理人员, I want to 查询供水管线和管点, so that 我能按管材、管径、建设年代、所属区域和关键字定位资料。
+4. As a 供水设施管理人员, I want to 查询水源地、水厂、泵站和用水户, so that 我能维护完整的供水设施业务视图。
+5. As a 供水设施管理人员, I want to 将用水户按居民、工业、商业和行政事业等类型查询, so that 所有供水服务对象使用统一术语并可分类管理。
+6. As a 供水设施管理人员, I want to 批量导入和导出五类供水设施及其 WGS84 坐标, so that 我能批量初始化资料并进行线下分析、业务留档。
+7. As a 供水设施管理人员, I want to 在供水设施 GIS 一张图查看水源地、水厂、泵站、供水管线和用水户, so that 我能在统一空间视图中搜索、定位和查看详情。
+8. As a 供水设施管理人员, I want to 在列表页面与 GIS 一张图之间保持职责区分, so that 查询页面不会重复实现空间定位逻辑。
+9. As a 设备管理人员, I want to 只看到设备类型树归属为供水的监测设备, so that 其他系统设备不会混入供水台账或工单。
+10. As a 设备管理人员, I want to 查看设备分类统计、设备状态、在线状态和报警状态, so that 我能判断设备是否需要人工关注。
+11. As a 设备管理人员, I want to 知道设备进入异常清单的报警原因或维修原因, so that 我能选择正确的后续处置动作。
+12. As a 设备管理人员, I want to 在设备异常管理中查看异常态势、处置状态和关联工单, so that 该页面承担异常管理而不是重复设备维修派单页面。
+13. As a 派单人员, I want to 在设备维修派单中只看到已判定运行故障且没有适用未结束故障维修工单的设备, so that 我能创建可执行的维修工单。
+14. As a 派单人员, I want to 在已有关联工单的设备上看到真实工单编号 `order_no`, so that 我能追踪业务工单而不是辨认随机数据库 ID。
+15. As a 派单人员, I want to 在设备详情侧边栏查看设备当前状态、设备报警状态、在线状态、报警等级和维修状态, so that 详情不会遮挡列表且字段具有一致的辨识度。
+16. As a 派单人员, I want to 在派单窗口左侧选择部门树和唯一责任人、右侧填写工单类型、优先级和问题描述, so that 我能按统一布局完成派单。
+17. As a 派单人员, I want to 使设备维修派单生成的工单类型固定为 `1-故障维修`, so that 维修流程不会进入巡检或保养生命周期。
+18. As a 运行监测人员, I want to 查看流量、压力和漏失监测点位及查询结果, so that 我能发现供水运行趋势和异常。
+19. As a 报警管理人员, I want to 看到报警编码、报警类型、报警等级、设备报警状态、报警记录状态和关联工单状态的独立字段, so that 不同状态来源不会相互替代。
+20. As a 报警管理人员, I want to 看到一级红色、二级橙色、三级蓝色、四级绿色并同时显示文字, so that 报警等级具有明确且可访问的表达。
+21. As a 报警管理人员, I want to 从报警记录确保生成待派单故障维修工单, so that 报警事实先进入统一工单流程。
+22. As a 系统, I want to 对报警转工单执行幂等处理, so that 同一报警记录重复操作不会生成重复工单。
+23. As a 系统, I want to 限制同一设备同一报警编码同时只能存在一个未结束故障维修工单, so that 并发操作不会产生重复处置。
+24. As a 系统, I want to 在报警编码缺失时按报警分类执行同类工单去重, so that 缺少编码的数据仍具有稳定的幂等规则。
+25. As a 系统, I want to 允许同一设备的不同报警类型分别生成故障维修工单, so that 不同有效报警原因可以分别追踪。
+26. As a 报警审核人员, I want to 在页面上看到全部工单、待处理、处理中、待验收和已完成数量, so that 我能判断处置积压和审核工作量。
+27. As a 报警审核人员, I want to 只处理供水设备关联的故障维修工单, so that 报警审核不会承担其他系统或非故障类型工单。
+28. As a 接单责任人, I want to 接收待接单工单并开始处理, so that 工单状态能反映真实处置阶段。
+29. As a 接单责任人, I want to 在处理前提交简要说明和处理前图片, so that 验收人员能比较处置前现场状态。
+30. As a 接单责任人, I want to 在提交验收时提交处置说明和处置后图片, so that 工单具备可审计的完成证据。
+31. As a 派单或审核人员, I want to 验收通过后结案, so that 已完成工单保留完整日志、责任人和图片证据。
+32. As a 派单或审核人员, I want to 驳回验收后让工单回到处理中, so that 责任人可以继续修复而不是丢失闭环。
+33. As a 供水工单管理人员, I want to 在供水工单总览查看全部供水类型工单, so that 故障维修、日常巡检和设备保养均有统一查询入口。
+34. As a 供水责任人, I want to 继续处置其他系统派发给我的巡检或保养工单, so that 供水总览不会因工单类型而阻断授权处置。
+35. As a 运行系统, I want to 在工单结案后复核设备全部有效报警原因, so that 单个工单结案不会错误清除仍存在的其他报警。
+36. As a 运行系统, I want to 在所有有效报警原因恢复后自动清警, so that 设备状态最终反映真实运行情况。
+37. As a 业务用户, I want to 刷新供水页面后保持正确路由、菜单、筛选、状态和详情关系, so that 页面不会发生错位、重复菜单或状态丢失。
+38. As a 验收人员, I want to 在桌面和移动宽度下检查列表、抽屉、弹窗和工单工作台, so that 页面可读且不会发生溢出、重叠或空白渲染。
+39. As a 验收人员, I want to 通过真实登录态端到端流程核对页面、接口和数据库结果, so that 通过标准代表可交付版本而不是局部模拟成功。
+
+## Implementation Decisions
+
+- 前端和后端保持独立仓库、独立构建,通过版本化 REST 契约和真实登录态端到端流程集成;只有契约、页面和数据库验收同时通过,才视为同一系统版本。
+- KingbaseES 是生产和最终验收唯一数据库真相源。PostgreSQL 不作为本项目生产验收或主要集成测试数据库;只有在无法避免时才可用于非权威兼容性检查。
+- 供水系统只展示设备类型树稳定编码判定为供水的设备、报警和工单。工单跨供水、排水、燃气和窨井共用统一生命周期,系统归属由关联设备类型判定,不由页面名称或报警记录状态推断。
+- 既有统一工单 API 和数据库状态机继续作为工单契约;不引入新的平行维修任务、报警工单生命周期或 Flowable 工作流。
+- 工单类型固定为:`1-故障维修`、`2-日常巡检`、`3-设备保养`。报警转入和设备故障派单均使用类型 `1`;供水系统不负责首次创建或首次派发巡检、保养工单,但被派给供水责任人的巡检或保养工单可在供水工单总览继续处置。
+- 报警转工单是“生成待派单工单”,工单派发是“为待派单工单指定唯一接单责任人”,两者必须在契约、页面文案和状态上分开。报警创建接口不能接收责任人并越过待派单阶段。
+- 同一设备与同一报警编码只能有一个未结束同类故障维修工单;报警编码缺失时使用报警分类作为去重键;不同报警类型允许分别建单。并发重复请求必须返回既有工单或明确的业务冲突结果。
+- 设备报警状态来自设备状态表,由运行系统根据全部有效报警原因维护;报警记录状态只表示单条历史记录的人工处置辅助状态,工单状态只表示处置生命周期,三者不得互相替代。
+- 工单状态保持现有数据库状态机:待派单、待接单、已接单、处理中、待验收、已结案,另设任意中间态可进入的终态“已取消”;验收驳回从待验收回到处理中(非终态)。目标七态编码 1-7 与新旧编码对照见 [ADR-0008](../../../pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md),不存在“已驳回”终态,也不存在延期状态。工单结案只触发清警复核,不直接写正常状态。
+- 同一设备存在多个有效报警原因时,一项维修可以产生“随同修复”结果,但其他工单仍保留记录并完成各自验收;只有清警复核确认没有有效报警原因时,设备才恢复正常。
+- 处理前和处置后图片及说明是工单处置证据。附件使用既有 MinIO 与 KingbaseES 元数据方案,现有工单图片 URL 字段保留兼容,读取时不得丢失历史图片。
+- 页面职责固定:设备异常管理展示异常态势和处置跟踪;设备维修派单聚焦可派单故障设备;报警管理展示报警态势、详情和报警转工单/派发入口;报警审核承载供水故障维修工单完整流程;“报警工单处置”菜单兼容保留,页面职责为供水工单总览。
+- GIS 联动统一集中到供水设施 GIS 一张图、监测设备 GIS 一张图和监测报警一张图;供水设施 GIS 范围包括水源地、水厂、泵站、供水管线和用水户,不包含消火栓。
+- 报警等级由运行监测规则计算,前端只展示一级至四级及其红、橙、蓝、绿颜色,不在前端重新计算等级。
+- 页面采用已确认的蓝白运行指挥台视觉规范:状态文字与颜色同时表达,详情使用右侧抽屉,派单窗口采用部门/责任人与工单表单左右分栏,菜单项使用语义图标并提供缺失图标兜底。
+- 后端优先复用已有接口和服务,在不破坏旧入口的前提下通过兼容适配接入统一契约;新能力不得制造与现有统一工单流程相冲突的替代实现。
+
+## Testing Decisions
+
+- 最高层公共 seam 是真实登录态浏览器端的供水报警工单端到端业务流程:从门户进入供水系统,经真实前端页面、REST API 和 KingbaseES 数据完成可观察闭环。不得把私有 Java 方法、单个 Mapper、Vue 内部状态或随机模拟数据当成独立交付标准。
+- 端到端流程至少覆盖:门户路由、供水菜单、供水设备过滤、设施与监测页面加载、报警数据加载、报警转工单幂等、同设备同报警类型去重、不同报警类型建单、故障维修类型、唯一责任人派发、接单、开始处理、处理说明、处理前图片、提交验收、处置后图片、验收通过、驳回回处理中、再次处理、验收结案和清警复核。
+- 每个关键页面刷新后重新读取真实数据,确认路由不错位、不产生重复菜单、不回退随机数据;接口失败必须显示可解释的错误和重试状态。
+- 端到端断言必须区分三类状态来源:设备报警状态来自设备状态表,报警记录状态来自报警记录,工单处置状态来自工单;同时确认 `order_no`、责任人、日志和处置证据可回看。
+- 必须构造同一设备存在两个有效报警原因的场景:结案一个工单后设备仍报警,全部原因恢复后才显示正常;不得以单个工单结案直接覆盖设备状态。
+- 浏览器验收覆盖 1440px、1024px 和 390px,检查设备维修派单、设备异常管理、报警管理、报警审核和供水工单总览五页的职责区分、状态统计、右侧抽屉、派单弹窗、图片证据和工单工作台。
+- 自动化测试作为该公共 seam 的支撑证据:前端生产构建和已有 Node 测试、后端 Maven 编译/测试、KingbaseES SQL 迁移校验、接口冒烟测试、浏览器控制台无应用级错误、`git diff --check`。测试断言外部行为、REST 契约和数据库业务结果。
+- 现有燃气和窨井工单处置模块作为交互先例;图片验证除视觉展示外,还要核对工单、阶段、对象键/URL、上传人和时间等元数据关联。
+- 测试数据必须可重复初始化且与业务真实字段一致;生产验收不得依赖 PostgreSQL 或只在内存数据库中通过。
+
+## Out of Scope
+
+- 不改变已确认的门户、窨井和供水菜单名称及已通过验收的路由结构,除非为本规格的兼容跳转修复必要错误。
+- 不在供水系统首次创建或首次派发日常巡检、设备保养工单;不复制其他系统的工单生命周期。
+- 不改变报警等级计算算法、设备类型树编码体系或统一工单数据库状态机。
+- 不把报警记录状态改造成设备报警状态,不以工单结案无条件清警。
+- 不新增消火栓实体、消火栓 GIS 图层或消火栓专用业务流程。
+- 不新增未经确认的按钮级权限编码;权限沿用现有后端校验,待编码明确后另行配置。
+- 不将前后端合并为单仓库,不要求执行者合并、推送或发布代码。
+- 不把 UI 视觉重构扩展到本规格未覆盖的其他业务系统页面。
+
+## Further Notes
+
+- 当前已确认的最高层 seam 是真实登录态浏览器端供水报警工单端到端流程,前后端局部测试只提供证据,不替代该接缝验收。
+- 当前重点风险是供水设备准入判定、报警编码和关联工单映射、同类工单并发去重、状态字段来源、报警审核驳回回处理中,以及多报警原因下的清警复核。
+- 生产数据库变更和集成验收必须在 KingbaseES 环境完成;无法连接目标数据库时,应记录为环境阻塞,不得用其他数据库的通过结果替代。
+- 执行者从隔离 worktree 开始工作,默认使用 `gpt-5.6-terra`、推理强度 `high`,不得合并或推送;当前对话负责项目管理、代码审查和最终验收。

+ 62 - 0
logs/pipe-network-service/spring.log

@@ -5501,3 +5501,65 @@ com.zksy.common.exception.ServiceException: 设备不存在:dfbb32ef87a74fc353
 17:32:25:222  INFO 19692 --- [SpringApplicationShutdownHook] sys-user                                 : ====关闭后台任务任务线程池====
 17:32:25:236  INFO 19692 --- [SpringApplicationShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
 17:32:25:246  INFO 19692 --- [SpringApplicationShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed
+17:11:36:343  INFO 41920 --- [restartedMain] com.zksy.ZksyApplication                 : The following 1 profile is active: "dev"
+17:11:37:093  INFO 41920 --- [restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
+17:11:37:094  INFO 41920 --- [restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
+17:11:37:148  INFO 41920 --- [restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 44 ms. Found 0 Redis repository interfaces.
+17:11:37:366  INFO 41920 --- [restartedMain] o.s.cloud.context.scope.GenericScope     : BeanFactory id=0e5a4171-518d-3030-a3b9-b47de6434c0a
+17:11:38:071  INFO 41920 --- [restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8301 (http)
+17:11:38:083  INFO 41920 --- [restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
+17:11:38:084  INFO 41920 --- [restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.106]
+17:11:38:166  INFO 41920 --- [restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
+17:11:38:167  INFO 41920 --- [restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1817 ms
+17:11:38:503 DEBUG 41920 --- [restartedMain] c.z.f.s.f.JwtAuthenticationTokenFilter   : Filter 'jwtAuthenticationTokenFilter' configured for use
+17:11:38:894  INFO 41920 --- [restartedMain] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
+17:11:41:536  INFO 41920 --- [restartedMain] c.z.s.impl.MinioFileStorageServiceImpl   : 初始化MinIO成功
+17:11:43:269  INFO 41920 --- [restartedMain] c.a.c.sentinel.SentinelWebMvcConfigurer  : [Sentinel Starter] register SentinelWebInterceptor with urlPatterns: [/**].
+17:11:43:511  WARN 41920 --- [restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inspectTaskServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zksy.ops.mapper.InspectTaskMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
+17:11:43:512  INFO 41920 --- [restartedMain] sys-user                                 : ====关闭后台任务任务线程池====
+17:11:43:512  WARN 41920 --- [restartedMain] .s.c.a.CommonAnnotationBeanPostProcessor : Destroy method on bean with name 'shutdownManager' threw an exception: java.lang.ExceptionInInitializerError
+17:11:43:517  INFO 41920 --- [restartedMain] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
+17:11:43:518  INFO 41920 --- [restartedMain] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed
+17:11:43:657  INFO 41920 --- [restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
+17:11:43:683  INFO 41920 --- [restartedMain] ConditionEvaluationReportLoggingListener : 
+
+Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
+17:11:43:719 ERROR 41920 --- [restartedMain] o.s.boot.SpringApplication               : Application run failed
+
+org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inspectTaskServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zksy.ops.mapper.InspectTaskMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
+	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:408) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:336) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:334) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:209) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) ~[spring-context-5.3.39.jar:5.3.39]
+	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:591) ~[spring-context-5.3.39.jar:5.3.39]
+	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.12.jar:2.7.12]
+	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731) ~[spring-boot-2.7.12.jar:2.7.12]
+	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.12.jar:2.7.12]
+	at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.7.12.jar:2.7.12]
+	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.7.12.jar:2.7.12]
+	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.7.12.jar:2.7.12]
+	at com.zksy.ZksyApplication.main(ZksyApplication.java:19) ~[classes/:na]
+	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
+	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
+	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
+	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
+	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.7.12.jar:2.7.12]
+Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zksy.ops.mapper.InspectTaskMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
+	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1801) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1357) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311) ~[spring-beans-5.3.39.jar:5.3.39]
+	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:710) ~[spring-beans-5.3.39.jar:5.3.39]
+	... 25 common frames omitted
+
+17:11:44:645  WARN 41920 --- [Thread-8] c.a.nacos.common.notify.NotifyCenter     : [NotifyCenter] Start destroying Publisher
+17:11:44:646  WARN 41920 --- [Thread-8] c.a.nacos.common.notify.NotifyCenter     : [NotifyCenter] Destruction of the end
+17:11:44:645  WARN 41920 --- [Thread-4] c.a.n.common.http.HttpClientBeanHolder   : [HttpClientBeanHolder] Start destroying common HttpClient

+ 9 - 0
pipe-network-service/docs/adr/0003-water-supply-subsystem-product-boundary.md

@@ -0,0 +1,9 @@
+---
+status: accepted
+---
+
+# Water supply subsystem product boundary
+
+本项目软件平台的正式产品定位是“城市地下管网及设施建设改造智能化系统项目”中的“地下管网管控平台”;供水领域的交付单元是其“供水管网安全运行监测系统”,由 `pipe-network-service` 管理端后端和 `city-life-line` 前端共同组成完整业务体验。供水设施、监测设备、运行监测、监测报警和工单处置属于同一供水子系统,不能把当前交付缩减为单独的报警页面或单一工单功能。
+
+供水基础设施中的居民、工业、商业、行政事业等所有服务对象统一称为“用水户”;既有 `user`、`waterUser`、`WaterUserInfo` 和 `water_user_info` 等技术标识继续保留,仅作为兼容映射,不表示“大用水户”子集。

+ 9 - 0
pipe-network-service/docs/adr/0004-cross-system-unified-work-order-lifecycle.md

@@ -0,0 +1,9 @@
+---
+status: accepted
+---
+
+# Cross-system unified work-order lifecycle
+
+供水、排水、燃气、窨井等业务系统共用统一的工单业务流程和生命周期;工单所属系统由其关联设备类型树中的稳定业务编码确定,而不是为每个系统建立一套互不兼容的工单服务。现有 `/api/work-order` 作为规范 API,旧系统入口和接口保留兼容适配;统一工单继续采用数据库状态机和事务服务,不在本轮引入 Flowable 等工作流引擎。新工单使用统一的创建、派单、接单、开始处理、提交验收、验收通过、驳回、延期日志语义,历史日志通过兼容映射展示。
+
+> **2026-09-04 更新(部分被 ADR-0008 取代)**:上句“驳回、延期日志语义”及隐含的九态口径已被 [ADR-0008](0008-work-order-lifecycle-seven-states.md) 收敛为**七态**:驳回是“待验收→处理中”的回退动作而非独立终态;新增独立终态“已取消”;删除“延期审核/已延期”。跨系统共用统一工单、以设备类型树确定系统归属、数据库状态机、旧入口兼容等其余决策继续有效。权威流程见 [docs/domain/work-order-lifecycle.md](../domain/work-order-lifecycle.md)。

+ 7 - 0
pipe-network-service/docs/adr/0005-independent-frontend-backend-contract-gate.md

@@ -0,0 +1,7 @@
+---
+status: accepted
+---
+
+# Independent frontend and backend contract gate
+
+`city-life-line` 前端与 `pipe-ner-server` 后端保持独立构建和独立仓库边界,通过版本化 REST 契约、真实登录态端到端流程和 KingbaseES 集成验收作为集成门禁;不强制合并为单仓库或同步发布。前后端只有在接口契约和端到端验收均通过时,才视为同一供水管网安全运行监测系统版本。

+ 7 - 0
pipe-network-service/docs/adr/0006-work-order-attachment-storage.md

@@ -0,0 +1,7 @@
+---
+status: accepted
+---
+
+# Work-order attachment storage
+
+工单处理前和处置后的图片、后续扩展附件统一使用现有 MinIO 保存对象,KingbaseES 保存附件元数据(工单、阶段、对象键、类型、大小、校验值、上传人和时间),由后端提供受控访问地址。现有 `work_order` 表中的图片 URL 字段保留作为兼容字段,不删除或破坏历史数据;新上传附件以阶段化元数据为规范来源,读取时兼容既有 URL。这样既保留当前接口兼容性,又避免工单主表和数据库存储二进制文件持续膨胀。

+ 16 - 0
pipe-network-service/docs/adr/0007-shared-pump-station-by-type.md

@@ -0,0 +1,16 @@
+---
+status: accepted
+---
+
+# Shared pump station table discriminated by station_type
+
+泵站同时服务于供水与排水两个业务系统,历史上只有供水专用表 `app_user.water_pump_station`,而排水侧接口(`/api/drainage/pumpStation`)直接复用该表且没有归属过滤,两侧看到同一批数据。
+
+决策:将该表改名为公用表 `app_user.pump_station`,新增 `station_type varchar(16) NOT NULL DEFAULT 'water_supply'` 作为业务归属判别列,取值 `water_supply`(供水泵站)/`drainage`(排水泵站),并以 CHECK 约束限定取值域;存量数据全部回填为 `water_supply`。
+
+- 不建立第二张平行泵站表,不复制一套排水泵站实体;Java 类名(`WaterPumpStation`)、包路径与既有 REST 路径(`/api/water/pumpStation`、`/api/drainage/pumpStation`)为兼容前端全部保留,只改表映射,不做大规模重命名。
+- 每个入口必须显式限定本系统类型:供水侧的分页、回收站、GIS 一张图、统计分析、导入导出固定 `station_type='water_supply'`;排水侧固定 `station_type='drainage'`。新增记录的类型由后端按入口强制写入,更新接口不允许修改归属列。
+- 类型编码采用稳定英文业务编码(与设施类型 `source/plant/pumpStation` 风格一致),不使用易变的中文名,也不使用语义不自解释的数字。
+- 迁移与回滚脚本分别为 `sql/migration_pump_station_shared.sql`、`sql/rollback_pump_station_shared.sql`;回滚前若已存在排水记录必须先人工处置,回滚脚本内置护栏中止回滚。
+
+这样在不破坏现有接口和数据的前提下,让同一张物理表支撑两个业务系统,并从 SQL 与后端入口两层保证数据不串系统。

+ 42 - 0
pipe-network-service/docs/adr/0008-work-order-lifecycle-seven-states.md

@@ -0,0 +1,42 @@
+---
+status: accepted
+---
+
+# ADR-0008 工单生命周期收敛为七态
+
+日期:2026-09-04(状态编码 2026-09-05 调整为从 1 开始)
+取代(部分):[ADR-0004 跨系统统一工单生命周期](0004-cross-system-unified-work-order-lifecycle.md) 中“驳回、延期日志语义”及隐含的九态口径。
+领域共识全文:[docs/domain/work-order-lifecycle.md](../domain/work-order-lifecycle.md)
+
+## 背景(Context)
+
+统一工单此前在代码与文档中使用九态:`1 待派单 / 2 待接单 / 3 已接单 / 4 处理中 / 5 待验收 / 6 已结案 / 7 已驳回 / 8 延期审核 / 9 已延期`,并存在两处与实际业务闭环不符的问题:
+
+1. **“驳回”被建成独立终态,且只允许在待派单/待接单驳回**;但真实业务里,管理员是在“待验收”阶段对处置结果不满意,需要把工单**退回“处理中”让同一责任人继续整改**,而不是终止工单。旧实现缺失“待验收→处理中”这条回退边。
+2. **“取消”没有独立终态**:旧 `cancel` 与 `reject` 都写入状态 7,数据上无法区分“取消”和“驳回”;同时“延期审核/已延期”使状态机膨胀,而当前交付流程并不包含延期环节。
+
+前端 `CONTEXT.md`、UE 驾驶舱 `CONTEXT.md` 与 issue#10、供应商需求文档又分别写成“含已驳回的阶段”“完整保留九态”,三套口径互相不一致。
+
+## 决策(Decision)
+
+以新的**七态模型**作为跨三仓(后端、前端、UE)唯一领域权威,状态编码从 1 开始:
+
+- 状态:`1 待派单 / 2 待接单 / 3 已接单 / 4 处理中 / 5 待验收 / 6 已结案 / 7 已取消`,终态仅“已结案 / 已取消”。
+- **驳回是动作不是状态**:验收驳回 = `待验收(5) → 处理中(4)`,必须带驳回原因,交同一责任人继续处置。
+- **取消进入独立终态“已取消(7)”**:任意中间态(1–5)可由管理员取消,已结案不可取消;取消后需要继续处置的,另建新工单派给新责任人。
+- **删除延期**:移除“延期审核/已延期”两态及主流程中的申请/审核延期环节。
+- 巡检、维修等工单允许创建即下派,直接进入“待接单(2)”。
+- 继续使用数据库状态机与事务服务,不引入工作流引擎;附件仍按 ADR-0006 分阶段存储。
+
+## 编码与迁移
+
+- 领域文档以**状态名**为权威,目标编码为 1–7;现网 `work_order.order_status` 仍是旧 1–9。目标编码从 1 开始后,前六态(1–6)与现网旧编码**同值**,仅第 7 态语义不同。
+- **本次只确立领域共识与文档,不重排数据库、不改后端代码**;代码改造与存量数据编码迁移另开任务,按生命周期文档第 8 节对照表执行。
+- 迁移任务内容包括:把旧 7(“已驳回”/取消混用)重定义为独立“已取消(7)”、实现 5→4 验收驳回回退、下线延期状态(旧 8/9)/字段语义、统一工单操作日志类型,并同步前端与 UE 的状态字典;前六态编码与现网一致,无需整体重排。
+
+## 后果(Consequences)
+
+- 三仓对工单状态的表述统一为七态,消除“已驳回是状态还是动作”“是否保留九态/延期”的长期分歧。
+- UE 驾驶舱按七态**只读展示**工单当前状态与状态时间线,不提供任何处置写入口;原 issue#10“保留九态”按本决策改为七态。
+- 在后端迁移完成前存在“文档目标编码 1–7 / 现网编码 1–9(前六态同值,第 7 态语义不同)”的临时双轨期,所有接口、测试与 UI 以状态名和对照表换算,不得再新增依赖“已驳回终态/延期”的功能。
+- ADR-0004 中“跨系统共用统一工单、以设备类型树确定系统归属、数据库状态机、兼容旧入口”等仍然有效;仅其“驳回、延期日志语义”被本 ADR 取代。

+ 17 - 0
pipe-network-service/docs/adr/0009-retain-parameter-names-and-explicit-mvc-binding-names.md

@@ -0,0 +1,17 @@
+---
+status: accepted
+---
+
+# Retain parameter names at compile time and name MVC binding annotations explicitly
+
+供水 GIS 图层 `/waterSupply/gis/map/features`、流量监测分页 `/waterSupply/monitoring/flow/page` 等接口运行期返回 500:`Name for argument of type [java.lang.String/long] not specified, and parameter name information not found in class file either.`。
+
+根因(经 spring-webmvc 5.3.39 MockMvc 最小复现验证,与是否被 CGLIB 代理无关):Spring MVC 对未显式命名的 `@RequestParam/@PathVariable`,先靠 `-parameters` 保留的反射形参名,再靠调试局部变量表(`-g:vars`,Maven 默认开、裸 javac 默认不开)兜底;两条路都拿不到名字时,参数绑定直接抛异常。本工程两个 pom 都未开 `-parameters`,一旦运行时类未带局部变量表即必现。
+
+决策(A+B 双保险):
+
+- A(构建兜底):根 `pom.xml`、`pipe-network-service/pom.xml`、`zksy-system/pom.xml` 的 maven-compiler-plugin 统一开启 `<parameters>true</parameters>`;`pipe-network-service` 的编译器插件由不支持该选项的 3.1 升到与根一致的 3.8.1。实测开启后即使 `-g:none` 也能正常绑定。
+- B(代码规范):新增/在维护的控制器显式写 `@RequestParam(value="x")`/`@PathVariable("x")`,不依赖编译产物。本轮先覆盖供水(`web/controller/WaterSupply`,17 个)与排水(`web/controller/drainage`,8 个)共 25 个控制器、397 处;其余历史控制器由 `-parameters` 兜底,显式命名另行排期,避免跨团队大 diff。
+- 禁止 `@RequestParam Map/ MultiValueMap` 形式补名(Spring 对 Map 形参走整表注入,写名反而报错),脚本已内置跳过。
+
+新增控制器的评审检查项:绑定注解必须带显式名;CI 构建不得关闭 `-parameters`。

+ 124 - 0
pipe-network-service/docs/domain/work-order-lifecycle.md

@@ -0,0 +1,124 @@
+# 统一工单处置生命周期(七态共识)
+
+状态:accepted(跨后端 `pipe-ner-server`、前端 `city-life-line`、UE 驾驶舱 `Pipelines` 的统一领域共识)
+确立日期:2026-09-04(状态编码 2026-09-05 调整为从 1 开始)
+决策依据:[ADR-0008 工单生命周期收敛为七态](../adr/0008-work-order-lifecycle-seven-states.md)
+取代口径:旧“九态模型”(含“已驳回”终态、“延期审核/已延期”),以及 ADR-0004 中“驳回、延期日志语义”的旧表述。
+
+> 本文只定义**领域流程共识**(状态、角色、迁移动作、证据与边界),不规定具体类、接口或 SQL。后端代码与存量数据当前仍是旧编码,**编码迁移另开任务**,在迁移完成前以本文状态名为唯一业务权威,编码以对照表换算。
+
+## 1. 角色
+
+- **管理员(派单/验收者)**:派单下发、验收(审核通过 / 验收驳回 / 取消工单)。可在任意中间态取消工单。
+- **接单责任人**:接单确认、开始处置、多次追加处理流水、提交审核。一次派发指定唯一接单责任人。
+- **运行系统/设备**:产生设备预警、报警,是工单的来源之一,但不参与工单状态决策。
+
+## 2. 进入流程的两条入口
+
+1. **报警转工单**:由设备预警/报警创建工单,进入“待派单”,创建时不指定责任人。
+2. **直接下派**:巡检工单、维修工单等可在创建时直接派给责任人,跳过“待派单”,直接进入“待接单”。
+
+## 3. 七个状态(目标权威模型)
+
+状态编码从 1 开始:
+
+| 目标编码 | 状态 | 含义 | 是否终态 |
+| --- | --- | --- | --- |
+| 1 | 待派单 | 已创建、尚未指定接单责任人,等待管理员派单 | 否 |
+| 2 | 待接单 | 已派给责任人,等待责任人接单确认 | 否 |
+| 3 | 已接单 | 责任人已接单确认,尚未开始现场处置 | 否 |
+| 4 | 处理中 | 责任人已开始处置;可多次追加处理流水 | 否 |
+| 5 | 待验收 | 责任人已提交审核,等待管理员验收 | 否 |
+| 6 | 已结案 | 管理员审核通过,处置闭环 | 是 |
+| 7 | 已取消 | 管理员取消,强制终止;用于改派新责任人(另建新单) | 是 |
+
+终态只有“已结案(6)”和“已取消(7)”。除两个终态外,其余均为中间态(1–5)。
+
+## 4. 状态迁移(动作即事件)
+
+| 动作 | 角色 | 前置态 | 目标态 | 必填信息 |
+| --- | --- | --- | --- | --- |
+| 创建(报警转工单) | 系统/管理员 | — | 1 待派单 | 工单描述、来源报警/设备 |
+| 直接下派(巡检/维修等) | 管理员 | — | 2 待接单 | 唯一责任人 |
+| 派单/下发 | 管理员 | 1 | 2 待接单 | 唯一责任人 |
+| 接单确认 | 责任人 | 2 | 3 已接单 | — |
+| 开始处置 | 责任人 | 3 | 4 处理中 | **处理前照片 + 现场简述** |
+| 追加处理流水 | 责任人 | 4 | 4 处理中(自循环,可多次) | 处理描述,可含图片 |
+| 提交审核 | 责任人 | 4 | 5 待验收 | **处理后照片 + 处理描述** |
+| 审核通过 | 管理员 | 5 | 6 已结案(终态) | 审核评价/建议 |
+| 验收驳回 | 管理员 | 5 | 4 处理中(**回退**) | 驳回原因 |
+| 取消工单 | 管理员 | 1/2/3/4/5 任一中间态 | 7 已取消(终态) | 建议填取消原因 |
+
+约束:
+
+- “已结案(6)”不可再取消、驳回或回退。
+- “已取消(7)”是终态,不能复活;需要换责任人时,**另建一张新工单**重新派发。
+- “验收驳回”只发生在“待验收(5)”,回到“处理中(4)”交**同一责任人**继续处理,可再次走“提交审核→待验收”。
+
+### 状态机视图
+
+```mermaid
+stateDiagram-v2
+    [*] --> 待派单: 报警转工单创建
+    [*] --> 待接单: 巡检/维修直接下派
+    待派单 --> 待接单: 管理员派单
+    待接单 --> 已接单: 责任人接单确认
+    已接单 --> 处理中: 开始处置(处理前照片+简述)
+    处理中 --> 处理中: 追加处理流水(可多次)
+    处理中 --> 待验收: 提交审核(处理后照片+描述)
+    待验收 --> 处理中: 验收驳回(驳回原因)
+    待验收 --> 已结案: 审核通过(评价/建议)
+    待派单 --> 已取消: 管理员取消
+    待接单 --> 已取消: 管理员取消
+    已接单 --> 已取消: 管理员取消
+    处理中 --> 已取消: 管理员取消
+    待验收 --> 已取消: 管理员取消
+    已结案 --> [*]
+    已取消 --> [*]
+```
+
+## 5. “验收驳回”与“取消工单”的区别(重点,消除旧歧义)
+
+- **验收驳回**是一个**动作而非状态**:管理员对处置结果不满意时,把“待验收”工单退回“处理中”,由原责任人继续整改;工单不终止、不换单。
+- **取消工单**是一个**迁到终态“已取消”的动作**:用于不再继续本单(例如对该责任人处置不满、误报、停止处置)。取消后若仍需处置,应创建新工单并派给新责任人。
+- 旧模型中“已驳回”是独立终态、且只允许在待派单/待接单驳回;**该终态在七态模型中废止**:未开始即终止的情形统一走“取消→已取消”,验收不通过统一走“驳回→回处理中”。
+
+## 6. 处理流水与处置证据
+
+处置证据按阶段区分,遵循 [ADR-0006 工单附件存储](../adr/0006-work-order-attachment-storage.md)(MinIO 对象 + KingbaseES 阶段化元数据,旧 URL 字段兼容):
+
+- **处理前证据**:开始处置(3→4)时上传处理前照片与现场简述。
+- **处理流水**:处理中(4)可多次追加,每条可含图片与处理描述,并逐条写入工单操作日志,不改变状态。
+- **处理后证据**:提交审核(4→5)时上传处理后照片与处理描述。
+- **验收意见**:审核通过时记录评价/建议;验收驳回时记录驳回原因;取消时记录取消原因。
+
+## 7. 与设备预警/报警的关系
+
+- 工单来源于设备预警/报警,但**工单状态独立于设备报警状态**:工单结案/取消不直接清除报警;设备是否恢复由运行系统依据“有效报警原因”自动维护(见 ADR-0002)。
+- 同一设备同一报警类型,同一时间只能存在一张未结束(非 6/7 终态)的同类工单;不同报警类型可分别建单。
+- 一次维修同时消除其他异常属于“随同修复”,其他工单仍各自保留并完成验收,不静默结案。
+
+## 8. 目标编码与现网编码对照(迁移期)
+
+现网 `work_order.order_status` 仍是旧 1–9 编码;**对齐到目标 1–7 的代码与存量数据迁移另开任务**,迁移完成前按下表换算,业务讨论一律使用状态名。目标编码从 1 开始后,前六态与现网旧编码 1–6 **同值**,仅第 7 态语义不同。
+
+| 状态名 | 目标编码(权威) | 现网旧编码(迁移前) |
+| --- | --- | --- |
+| 待派单 | 1 | 1(同值) |
+| 待接单 | 2 | 2(同值) |
+| 已接单 | 3 | 3(同值) |
+| 处理中 | 4 | 4(同值) |
+| 待验收 | 5 | 5(同值) |
+| 已结案 | 6 | 6(同值) |
+| 已取消 | 7 | 旧实现无独立值(`cancel`/`reject` 都落到旧 7) |
+| ~~已驳回(废止)~~ | — | 7(旧终态,取消与驳回混用) |
+| ~~延期审核(废止)~~ | — | 8 |
+| ~~已延期(废止)~~ | — | 9 |
+
+迁移任务至少需要:把旧 7(“已驳回”/取消混用)重定义为独立“已取消(7)”、把“验收驳回”实现为 5→4 回退、下线延期状态(旧 8/9)与字段语义、同步工单操作日志类型与各前端/UE 状态字典;前六态编码与现网一致,无需整体重排。
+
+## 9. 本版明确删除/不纳入的内容
+
+- **删除“已驳回”终态**:驳回仅指“待验收→处理中”的回退动作。
+- **删除延期相关状态**:不再有“延期审核(旧 8)”“已延期(旧 9)”,工单主流程不含申请/审核延期环节;旧字段的下线随迁移任务处理。
+- 不引入 Flowable 等外部工作流引擎,继续使用数据库状态机 + 事务服务(沿用 ADR-0004 中仍有效的部分)。

+ 54 - 0
pipe-network-service/sql/migration_pump_station_shared.sql

@@ -0,0 +1,54 @@
+-- 泵站信息表公用化迁移(KingbaseES / PostgreSQL 兼容)
+-- 目标:
+--   1. app_user.water_pump_station 改名为 app_user.pump_station(公用泵站表)
+--   2. 新增 station_type 类型字段:water_supply-供水泵站,drainage-排水泵站
+--   3. 存量数据全部回填为供水泵站,并强制非空与取值域约束
+-- 可重复执行;不删除任何业务数据。
+-- 对应回滚脚本:rollback_pump_station_shared.sql
+
+-- 1. 表改名(重复执行时旧表已不存在,IF EXISTS 自动跳过;数据、主键、外键保持不变)
+ALTER TABLE IF EXISTS app_user.water_pump_station RENAME TO pump_station;
+
+-- 2. 新增泵站类型字段
+ALTER TABLE app_user.pump_station ADD COLUMN IF NOT EXISTS station_type varchar(16);
+
+-- 3. 存量数据回填为供水泵站(历史数据均来自供水子系统)
+UPDATE app_user.pump_station SET station_type = 'water_supply' WHERE station_type IS NULL;
+
+-- 4. 默认值与非空约束
+ALTER TABLE app_user.pump_station ALTER COLUMN station_type SET DEFAULT 'water_supply';
+ALTER TABLE app_user.pump_station ALTER COLUMN station_type SET NOT NULL;
+COMMENT ON COLUMN app_user.pump_station.station_type IS '泵站类型:water_supply-供水泵站,drainage-排水泵站';
+
+-- 5. 取值域 CHECK 约束(幂等)
+DO $$
+BEGIN
+    IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'ck_pump_station_type') THEN
+        ALTER TABLE app_user.pump_station
+            ADD CONSTRAINT ck_pump_station_type CHECK (station_type IN ('water_supply', 'drainage'));
+    END IF;
+END $$;
+
+-- 6. 坐标索引随表改名,并新增类型过滤索引(均幂等)
+ALTER INDEX IF EXISTS app_user.idx_water_pump_station_lon_lat RENAME TO idx_pump_station_lon_lat;
+CREATE INDEX IF NOT EXISTS idx_pump_station_type ON app_user.pump_station (station_type);
+
+-- 7. 主键序列改名(若沿用表名前缀默认命名则存在,幂等处理)
+DO $$
+BEGIN
+    IF EXISTS (SELECT 1
+                 FROM pg_class c
+                 JOIN pg_namespace n ON n.oid = c.relnamespace
+                WHERE n.nspname = 'app_user'
+                  AND c.relname = 'water_pump_station_id_seq') THEN
+        ALTER SEQUENCE app_user.water_pump_station_id_seq RENAME TO pump_station_id_seq;
+    END IF;
+END $$;
+
+-- 8. 表注释更新为公用泵站表
+COMMENT ON TABLE app_user.pump_station IS '公用泵站信息表,按 station_type 区分供水泵站(water_supply)与排水泵站(drainage)';
+
+-- 执行后校验(手动执行确认):
+-- SELECT station_type, COUNT(*) FROM app_user.pump_station GROUP BY station_type;
+-- SELECT column_name, data_type, is_nullable, column_default
+--   FROM information_schema.columns WHERE table_schema='app_user' AND table_name='pump_station' AND column_name='station_type';

+ 56 - 0
pipe-network-service/sql/rollback_pump_station_shared.sql

@@ -0,0 +1,56 @@
+-- 泵站信息表公用化迁移的回滚脚本(KingbaseES / PostgreSQL 兼容)
+-- 对应正向迁移:migration_pump_station_shared.sql
+--
+-- 回滚前置条件:
+--   回滚后表恢复为“供水专用”,不能携带排水泵站数据。
+--   默认安全策略:若存在 station_type='drainage' 的记录则中止回滚,
+--   由人工先导出/迁移这些数据;确认丢弃时再手动执行下方注释中的删除语句。
+--
+-- 警告:本脚本会删除 station_type 列并改回表名,请先完整备份后执行。
+
+-- 0. 安全护栏:存在排水泵站记录时中止回滚
+DO $$
+DECLARE
+    drainage_count integer;
+BEGIN
+    SELECT COUNT(*) INTO drainage_count
+      FROM app_user.pump_station WHERE station_type = 'drainage';
+    IF drainage_count > 0 THEN
+        RAISE EXCEPTION '回滚中止:pump_station 中存在 % 条排水泵站(drainage)记录,请先导出或确认删除后再回滚', drainage_count;
+    END IF;
+END $$;
+
+-- 如确认丢弃排水泵站数据,先手动执行(默认不执行):
+-- DELETE FROM app_user.pump_station WHERE station_type = 'drainage';
+
+-- 1. 删除取值域约束与类型索引
+ALTER TABLE app_user.pump_station DROP CONSTRAINT IF EXISTS ck_pump_station_type;
+DROP INDEX IF EXISTS app_user.idx_pump_station_type;
+
+-- 2. 删除类型字段(先移除默认值与非空,再删列)
+ALTER TABLE IF EXISTS app_user.pump_station ALTER COLUMN station_type DROP DEFAULT;
+ALTER TABLE IF EXISTS app_user.pump_station DROP COLUMN IF EXISTS station_type;
+
+-- 3. 坐标索引名改回
+ALTER INDEX IF EXISTS app_user.idx_pump_station_lon_lat RENAME TO idx_water_pump_station_lon_lat;
+
+-- 4. 主键序列名改回(幂等)
+DO $$
+BEGIN
+    IF EXISTS (SELECT 1
+                 FROM pg_class c
+                 JOIN pg_namespace n ON n.oid = c.relnamespace
+                WHERE n.nspname = 'app_user'
+                  AND c.relname = 'pump_station_id_seq') THEN
+        ALTER SEQUENCE app_user.pump_station_id_seq RENAME TO water_pump_station_id_seq;
+    END IF;
+END $$;
+
+-- 5. 表名改回
+ALTER TABLE IF EXISTS app_user.pump_station RENAME TO water_pump_station;
+COMMENT ON TABLE app_user.water_pump_station IS '供水泵站信息表';
+
+-- 回滚后校验:
+-- SELECT to_regclass('app_user.water_pump_station') AS old_table_back,
+--        to_regclass('app_user.pump_station')        AS new_table_gone;
+-- 代码层需同步 git 回退到本次迁移前的版本(实体 @TableName、Mapper XML、过滤逻辑等)。

+ 66 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitEquipmentDetailAggregateController.java

@@ -0,0 +1,66 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.detail.CockpitEquipmentDetailAggregateResponse;
+import com.zksy.cockpit.detail.CockpitEquipmentDetailAggregateService;
+import com.zksy.cockpit.foundation.CockpitErrorCategory;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.StringUtils;
+import com.zksy.common.utils.uuid.IdUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.util.UriUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+
+@RestController
+public class CockpitEquipmentDetailAggregateController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitEquipmentDetailAggregateService aggregateService;
+
+    public CockpitEquipmentDetailAggregateController(CockpitEquipmentDetailAggregateService aggregateService) {
+        this.aggregateService = aggregateService;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/detail-aggregate")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> equipmentDetailAggregate(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitEquipmentDetailAggregateResponse response = aggregateService.loadAggregate(
+                resolveRequestId(requestId), decodePathSegment(deviceCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        CockpitErrorPayload payload = new CockpitErrorPayload(
+                CockpitErrorCategory.INVALID_REQUEST,
+                "设备详情查询参数不合法",
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER)),
+                null);
+        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+                .body(new AjaxResult(HttpStatus.BAD_REQUEST.value(), payload.getMessage(), payload));
+    }
+
+    private String resolveRequestId(String requestId) {
+        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
+    }
+
+    private String decodePathSegment(String value) {
+        try {
+            return UriUtils.decode(value, StandardCharsets.UTF_8);
+        } catch (IllegalArgumentException exception) {
+            throw new CockpitInvalidRequestException("invalid device code encoding");
+        }
+    }
+}

+ 100 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitFreshnessController.java

@@ -0,0 +1,100 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitErrorCategory;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitFreshnessResponse;
+import com.zksy.cockpit.foundation.CockpitFreshnessService;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.StringUtils;
+import com.zksy.common.utils.uuid.IdUtils;
+import java.time.Clock;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.util.UriUtils;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+
+@RestController
+public class CockpitFreshnessController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private static final DateTimeFormatter BUSINESS_TIME = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+    private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
+
+    private final CockpitFreshnessService freshnessService;
+    private final Clock clock;
+
+    public CockpitFreshnessController(CockpitFreshnessService freshnessService, Clock clock) {
+        this.freshnessService = freshnessService;
+        this.clock = clock;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/freshness")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> freshness(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestParam(value = "calibrationPeriodSeconds", required = false) Integer calibrationPeriodSeconds,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitFreshnessResponse response = freshnessService.load(
+                resolveRequestId(requestId), decodePathSegment(deviceCode), calibrationPeriodSeconds);
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return badRequest(CockpitErrorCategory.INVALID_REQUEST, "驾驶舱新鲜度查询参数不合法", request);
+    }
+
+    @ExceptionHandler(CockpitDeviceNotFoundException.class)
+    public ResponseEntity<AjaxResult> handleNotFound(HttpServletRequest request) {
+        return error(HttpStatus.NOT_FOUND, CockpitErrorCategory.NOT_FOUND, "驾驶舱新鲜度数据不存在", request);
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, CockpitErrorCategory.SERVER_ERROR, "驾驶舱新鲜度数据暂不可用", request);
+    }
+
+    private ResponseEntity<AjaxResult> badRequest(CockpitErrorCategory category, String message, HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, category, message, request);
+    }
+
+    private ResponseEntity<AjaxResult> error(
+            HttpStatus status,
+            CockpitErrorCategory category,
+            String message,
+            HttpServletRequest request) {
+        CockpitErrorPayload payload = new CockpitErrorPayload(
+                category,
+                message,
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER)),
+                BUSINESS_TIME.format(clock.instant().atZone(BUSINESS_ZONE)));
+        return ResponseEntity.status(status)
+                .body(new AjaxResult(status.value(), payload.getMessage(), payload));
+    }
+
+    private String resolveRequestId(String requestId) {
+        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
+    }
+
+    private String decodePathSegment(String value) {
+        try {
+            return UriUtils.decode(value, StandardCharsets.UTF_8);
+        } catch (IllegalArgumentException exception) {
+            throw new CockpitInvalidRequestException("invalid device code encoding");
+        }
+    }
+}

+ 49 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitOverviewInfrastructureController.java

@@ -0,0 +1,49 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.overview.CockpitOverviewInfrastructureService;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.StringUtils;
+import com.zksy.common.utils.uuid.IdUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+
+@RestController
+public class CockpitOverviewInfrastructureController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitOverviewInfrastructureService overviewInfrastructureService;
+
+    public CockpitOverviewInfrastructureController(
+            CockpitOverviewInfrastructureService overviewInfrastructureService) {
+        this.overviewInfrastructureService = overviewInfrastructureService;
+    }
+
+    @GetMapping("/api/cockpit/v1/overview/infrastructure")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> overviewInfrastructure(
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        return ResponseEntity.ok(AjaxResult.success(
+                overviewInfrastructureService.load(resolveRequestId(requestId))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        CockpitErrorPayload payload = overviewInfrastructureService.serverError(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER)));
+        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
+                .body(new AjaxResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), payload.getMessage(), payload));
+    }
+
+    private String resolveRequestId(String requestId) {
+        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
+    }
+}

+ 60 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringController.java

@@ -0,0 +1,60 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringService;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.StringUtils;
+import com.zksy.common.utils.uuid.IdUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+
+@RestController
+public class CockpitOverviewMonitoringController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitOverviewMonitoringService overviewMonitoringService;
+
+    public CockpitOverviewMonitoringController(CockpitOverviewMonitoringService overviewMonitoringService) {
+        this.overviewMonitoringService = overviewMonitoringService;
+    }
+
+    @GetMapping("/api/cockpit/v1/overview/monitoring")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> overviewMonitoring(
+            @RequestParam(value = "industry", required = false) String industry,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        return ResponseEntity.ok(AjaxResult.success(
+                overviewMonitoringService.load(resolveRequestId(requestId), industry)));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, overviewMonitoringService.invalidRequest(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, overviewMonitoringService.serverError(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    private ResponseEntity<AjaxResult> error(HttpStatus status, CockpitErrorPayload payload) {
+        return ResponseEntity.status(status)
+                .body(new AjaxResult(status.value(), payload.getMessage(), payload));
+    }
+
+    private String resolveRequestId(String requestId) {
+        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
+    }
+}

+ 103 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitWorkOrderReadController.java

@@ -0,0 +1,103 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadResponse;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineResponse;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.StringUtils;
+import com.zksy.common.utils.uuid.IdUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.util.UriUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+
+@RestController
+public class CockpitWorkOrderReadController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitWorkOrderReadService workOrderService;
+
+    public CockpitWorkOrderReadController(CockpitWorkOrderReadService workOrderService) {
+        this.workOrderService = workOrderService;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/work-orders")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> deviceWorkOrders(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitWorkOrderReadResponse response = workOrderService.loadByDevice(
+                resolveRequestId(requestId), decodePathSegment(deviceCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @GetMapping("/api/cockpit/v1/events/{eventSource}/{eventCode}/work-orders")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> eventWorkOrders(
+            @PathVariable("eventSource") String eventSource,
+            @PathVariable("eventCode") String eventCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitWorkOrderReadResponse response = workOrderService.loadByEvent(
+                resolveRequestId(requestId),
+                decodePathSegment(eventSource),
+                decodePathSegment(eventCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @GetMapping("/api/cockpit/v1/work-orders/{workOrderCode}/timeline")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> workOrderTimeline(
+            @PathVariable("workOrderCode") String workOrderCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitWorkOrderTimelineResponse response = workOrderService.loadTimeline(
+                resolveRequestId(requestId), decodePathSegment(workOrderCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, workOrderService.invalidRequest(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitDeviceNotFoundException.class)
+    public ResponseEntity<AjaxResult> handleNotFound(HttpServletRequest request) {
+        return error(HttpStatus.NOT_FOUND, workOrderService.notFound(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, workOrderService.serverError(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    private ResponseEntity<AjaxResult> error(HttpStatus status, CockpitErrorPayload payload) {
+        return ResponseEntity.status(status)
+                .body(new AjaxResult(status.value(), payload.getMessage(), payload));
+    }
+
+    private String resolveRequestId(String requestId) {
+        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
+    }
+
+    private String decodePathSegment(String value) {
+        try {
+            return UriUtils.decode(value, StandardCharsets.UTF_8);
+        } catch (IllegalArgumentException exception) {
+            throw new CockpitInvalidRequestException("invalid path segment encoding");
+        }
+    }
+}

+ 73 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusDeltaTracker.java

@@ -0,0 +1,73 @@
+package com.zksy.web.websocket;
+
+import org.springframework.stereotype.Component;
+
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 以服务端更新时间为准过滤重放消息,只放行状态真正变化的设备。
+ */
+@Component
+public class DeviceStatusDeltaTracker {
+
+    private static final DateTimeFormatter BUSINESS_TIME =
+            DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+
+    private final Map<String, Delta> latestByDevice = new ConcurrentHashMap<>();
+
+    public boolean shouldPush(String deviceCode, OffsetDateTime serverUpdatedAt, String status, String statusTime) {
+        if (deviceCode == null || deviceCode.isEmpty()) {
+            return false;
+        }
+        Delta next = new Delta(serverUpdatedAt, status, statusTime);
+        boolean[] changed = {false};
+        latestByDevice.compute(deviceCode, (key, current) -> {
+            if (current != null && !next.serverUpdatedAt.isAfter(current.serverUpdatedAt)) {
+                return current;
+            }
+            if (current != null && current.isSameState(next)) {
+                return next;
+            }
+            changed[0] = true;
+            return next;
+        });
+        return changed[0];
+    }
+
+    public OffsetDateTime parseServerUpdatedAt(String value) {
+        if (value == null || value.isBlank()) {
+            return OffsetDateTime.now(ZoneOffset.ofHours(8));
+        }
+        try {
+            return OffsetDateTime.parse(value, BUSINESS_TIME);
+        } catch (DateTimeParseException ignored) {
+            return LocalDateTime.parse(value).atZone(ZoneOffset.ofHours(8)).toOffsetDateTime();
+        }
+    }
+
+    private static final class Delta {
+        private final OffsetDateTime serverUpdatedAt;
+        private final String status;
+        private final String statusTime;
+
+        private Delta(OffsetDateTime serverUpdatedAt, String status, String statusTime) {
+            this.serverUpdatedAt = serverUpdatedAt;
+            this.status = status;
+            this.statusTime = statusTime;
+        }
+
+        private boolean isSameState(Delta next) {
+            return status.equals(next.status) && safeEquals(statusTime, next.statusTime);
+        }
+
+        private boolean safeEquals(String left, String right) {
+            return left == null ? right == null : left.equals(right);
+        }
+    }
+}

+ 122 - 25
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusRedisListener.java

@@ -11,6 +11,11 @@ import org.springframework.stereotype.Component;
 import org.springframework.web.socket.WebSocketSession;
 
 import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.HashSet;
 import java.util.Set;
 
 /**
@@ -34,6 +39,9 @@ public class DeviceStatusRedisListener implements MessageListener {
     @Autowired
     private DeviceStatusWebSocketHandler webSocketHandler;
 
+    @Autowired
+    private DeviceStatusDeltaTracker deltaTracker;
+
     /**
      * Redis 频道名称
      */
@@ -47,64 +55,153 @@ public class DeviceStatusRedisListener implements MessageListener {
         try {
             JSONObject msgObj = JSONObject.parseObject(body);
             String deviceCode = msgObj.getString("deviceCode");
+            if (deviceCode == null || deviceCode.isEmpty()) {
+                deviceCode = msgObj.getString("device_code");
+            }
 
             if (deviceCode == null || deviceCode.isEmpty()) {
                 log.warn("Redis 消息缺少 deviceCode 字段: {}", body);
                 return;
             }
 
-            // 查找订阅了该设备的所有 WebSocket 会话
+            // 查找设备编码订阅和全量驾驶舱订阅的 WebSocket 会话。
             Set<String> sessionIds = subscriptionManager.getSubscribedSessions(deviceCode);
-            if (sessionIds.isEmpty()) {
+            Set<String> cockpitSessionIds = subscriptionManager.getAllScopeSessions();
+            if (sessionIds.isEmpty() && cockpitSessionIds.isEmpty()) {
                 log.debug("无会话订阅设备: deviceCode={}", deviceCode);
                 return;
             }
 
-            // 查询最新设备状态
-            EquipmentStatus status = equipmentStatusService.getByDeviceCode(deviceCode);
-            if (status == null) {
-                log.warn("未找到设备状态: deviceCode={}", deviceCode);
+            // 查询最新设备状态,缺失时不臆造状态,而是给出显式回退原因。
+            boolean deviceExists = equipmentStatusService.existsByDeviceCode(deviceCode);
+            EquipmentStatus latestStatus = null;
+            String status;
+            String statusTime = null;
+            String reason;
+            if (!deviceExists) {
+                status = "EMPTY";
+                reason = "DEVICE_NOT_FOUND";
+            } else {
+                latestStatus = equipmentStatusService.getByDeviceCode(deviceCode);
+                if (latestStatus == null) {
+                    status = "EMPTY";
+                    reason = "NO_STATUS";
+                } else {
+                    status = resolveStatus(latestStatus);
+                    statusTime = formatBusinessTime(latestStatus.getStatusUpdateTime());
+                    reason = null;
+                }
+            }
+            OffsetDateTime serverUpdatedAt = deltaTracker.parseServerUpdatedAt(serverUpdatedAtValue(msgObj));
+            if (!deltaTracker.shouldPush(deviceCode, serverUpdatedAt, status, statusTime)) {
+                log.debug("设备状态未变化或消息过期: deviceCode={}", deviceCode);
                 return;
             }
 
             // 构建推送消息
-            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(status));
-            // 客户端可能同时订阅多个设备,必须在推送中携带设备编码以便路由状态。
-            data.put("deviceCode", deviceCode);
-            if (msgObj.containsKey("eventId")) {
-                data.put("eventId", msgObj.getString("eventId"));
+            String pushPayload = null;
+            if (latestStatus != null) {
+                JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(latestStatus));
+                // 客户端可能同时订阅多个设备,必须在推送中携带设备编码以便路由状态。
+                data.put("deviceCode", deviceCode);
+                if (msgObj.containsKey("eventId")) {
+                    data.put("eventId", msgObj.getString("eventId"));
+                }
+                pushPayload = legacyPushMessage(deviceCode, data).toJSONString();
             }
-            JSONObject pushMsg = new JSONObject();
-            pushMsg.put("type", "deviceStatusPush");
-            pushMsg.put("deviceCode", deviceCode);
-            pushMsg.put("data", data);
+            String cockpitPayload = cockpitDeltaMessage(deviceCode, status, statusTime,
+                    serverUpdatedAt, reason).toJSONString();
 
-            String pushPayload = pushMsg.toJSONString();
-
-            // 推送到所有订阅了该设备的会话
             int successCount = 0;
             int failCount = 0;
-            for (String sessionId : sessionIds) {
-                WebSocketSession session = DeviceStatusWebSocketHandler.getSession(sessionId);
-                if (session != null && session.isOpen()) {
-                    if (webSocketHandler.sendText(session, pushPayload)) {
+            Set<String> allScopeSet = new HashSet<>(cockpitSessionIds);
+            if (pushPayload != null) {
+                for (String sessionId : sessionIds) {
+                    if (allScopeSet.contains(sessionId)) {
+                        continue;
+                    }
+                    if (send(sessionId, pushPayload)) {
                         successCount++;
                     } else {
                         failCount++;
                     }
+                }
+            }
+            for (String sessionId : allScopeSet) {
+                if (send(sessionId, cockpitPayload)) {
+                    successCount++;
                 } else {
-                    // 会话已失效,清理订阅
-                    subscriptionManager.removeSession(sessionId);
                     failCount++;
                 }
             }
 
             log.info("设备状态推送完成: deviceCode={}, 成功={}, 失败={}, 订阅会话数={}",
-                    deviceCode, successCount, failCount, sessionIds.size());
+                    deviceCode, successCount, failCount, sessionIds.size() + cockpitSessionIds.size());
 
         } catch (Exception e) {
             log.error("处理 Redis 设备状态变更消息异常: body={}", body, e);
         }
     }
 
+    private boolean send(String sessionId, String payload) {
+        WebSocketSession session = DeviceStatusWebSocketHandler.getSession(sessionId);
+        if (session != null && session.isOpen()) {
+            if (webSocketHandler.sendText(session, payload)) {
+                return true;
+            }
+        } else {
+            subscriptionManager.removeSession(sessionId);
+        }
+        return false;
+    }
+
+    private JSONObject legacyPushMessage(String deviceCode, JSONObject data) {
+        JSONObject pushMsg = new JSONObject();
+        pushMsg.put("type", "deviceStatusPush");
+        pushMsg.put("deviceCode", deviceCode);
+        pushMsg.put("data", data);
+        return pushMsg;
+    }
+
+    private String serverUpdatedAtValue(JSONObject msgObj) {
+        String value = msgObj.getString("serverUpdatedAt");
+        return value == null || value.isEmpty() ? msgObj.getString("changedAt") : value;
+    }
+
+    private JSONObject cockpitDeltaMessage(String deviceCode, String status, String statusTime,
+            OffsetDateTime serverUpdatedAt, String reason) {
+        String serverUpdatedAtText = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(serverUpdatedAt);
+        JSONObject delta = new JSONObject();
+        delta.put("type", "cockpitDeviceStatusDelta");
+        delta.put("deviceCode", deviceCode);
+        delta.put("device_code", deviceCode);
+        JSONObject data = new JSONObject();
+        data.put("status", status);
+        data.put("statusTime", statusTime);
+        data.put("serverUpdatedAt", serverUpdatedAtText);
+        data.put("reason", reason);
+        delta.put("data", data);
+        return delta;
+    }
+
+    private String resolveStatus(EquipmentStatus status) {
+        if (Integer.valueOf(1).equals(status.getAlarmStatus())) {
+            return "ALARM";
+        }
+        if (Integer.valueOf(0).equals(status.getOnlineStatus())) {
+            return "OFFLINE";
+        }
+        if (Integer.valueOf(3).equals(status.getCurrentStatus())) {
+            return "WORK_ORDER";
+        }
+        return "NORMAL";
+    }
+
+    private String formatBusinessTime(LocalDateTime value) {
+        if (value == null) {
+            return null;
+        }
+        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value.atZone(ZoneOffset.ofHours(8)).toOffsetDateTime());
+    }
+
 }

+ 39 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/DeviceStatusWebSocketHandler.java

@@ -19,6 +19,9 @@ import org.springframework.web.socket.WebSocketSession;
 import org.springframework.web.socket.handler.TextWebSocketHandler;
 
 import java.io.IOException;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
 import java.util.HashSet;
 import java.util.HashMap;
 import java.util.Collections;
@@ -36,6 +39,7 @@ import java.util.concurrent.ConcurrentHashMap;
  *   <li><b>authenticate</b> — 使用登录 JWT 鉴权(工单推送必需)</li>
  *   <li><b>subscribe</b> — 批量订阅设备,后端状态变更时主动推送</li>
  *   <li><b>unsubscribe</b> — 取消订阅设备</li>
+ *   <li><b>cockpitSubscribe</b> — 驾驶舱全量状态订阅(scope=all)</li>
  *   <li><b>deviceStatus</b> — 单次查询设备状态(兼容旧接口)</li>
  *   <li><b>workOrderReminder</b> — 查询当前用户可见的待处理/超时工单</li>
  *   <li><b>ping</b> — 心跳检测</li>
@@ -55,6 +59,10 @@ import java.util.concurrent.ConcurrentHashMap;
  * → {"type":"unsubscribe","deviceCodes":["DEV001"]}
  * ← {"type":"unsubscribed","deviceCodes":["DEV001"]}
  *
+ * // 驾驶舱全量订阅
+ * → {"type":"cockpitSubscribe","scope":"all"}
+ * ← {"type":"cockpitSubscribed","scope":"all","serverUpdatedAt":"2026-09-02T10:00:00+08:00"}
+ *
  * // 心跳
  * → {"type":"ping"}
  * ← {"type":"pong","timestamp":1690000000000}
@@ -66,6 +74,10 @@ import java.util.concurrent.ConcurrentHashMap;
  * // 设备状态变更推送(服务端主动推送)
  * ← {"type":"deviceStatusPush","deviceCode":"DEV001","data":{...}}
  *
+ * // 驾驶舱增量推送
+ * ← {"type":"cockpitDeviceStatusDelta","deviceCode":"DEV001","device_code":"DEV001",
+ *    "data":{"status":"ALARM","statusTime":"2026-09-02T09:59:50+08:00","serverUpdatedAt":"2026-09-02T10:00:00+08:00"}}
+ *
  * // 工单提醒推送(服务端每分钟扫描,有变化才推送)
  * ← {"type":"workOrderReminderPush","success":true,"data":{"items":[...],"total":1}}
  * </pre>
@@ -180,7 +192,10 @@ public class DeviceStatusWebSocketHandler extends TextWebSocketHandler {
                 case "unsubscribe":
                     handleUnsubscribe(session, request);
                     break;
-                    //查询设备状态(单次查询)
+                case "cockpitSubscribe":
+                    handleCockpitSubscribe(session, request);
+                    break;
+                //查询设备状态(单次查询)
                 case "deviceStatus":
                     handleDeviceStatus(session, request);
                     break;
@@ -324,6 +339,24 @@ public class DeviceStatusWebSocketHandler extends TextWebSocketHandler {
         log.info("取消订阅: sessionId={}, 取消设备={}, 剩余订阅={}", session.getId(), deviceCodes, remaining);
     }
 
+    /**
+     * 驾驶舱全量范围订阅;REST 仍是初始快照,这里只接收后续状态增量。
+     */
+    private void handleCockpitSubscribe(WebSocketSession session, JSONObject request) throws IOException {
+        String scope = request.getString("scope");
+        if (!"all".equals(scope)) {
+            sendError(session, "缺少 scope 参数或暂不支持该范围");
+            return;
+        }
+        subscriptionManager.subscribeAll(session.getId());
+
+        JSONObject response = new JSONObject();
+        response.put("type", "cockpitSubscribed");
+        response.put("scope", scope);
+        response.put("serverUpdatedAt", nowIso());
+        sendText(session, response.toJSONString());
+    }
+
     /**
      * 处理设备状态查询(兼容旧接口)
      */
@@ -354,6 +387,11 @@ public class DeviceStatusWebSocketHandler extends TextWebSocketHandler {
         sendText(session, response.toJSONString());
     }
 
+    private static String nowIso() {
+        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
+                OffsetDateTime.now(ZoneOffset.ofHours(8)));
+    }
+
     @Override
     public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
         String sessionId = session.getId();

+ 28 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/websocket/SubscriptionManager.java

@@ -34,6 +34,11 @@ public class SubscriptionManager {
      */
     private final ConcurrentHashMap<String, Set<String>> deviceToSessions = new ConcurrentHashMap<>();
 
+    /**
+     * 全量驾驶舱订阅会话ID集合。
+     */
+    private final Set<String> allScopeSessions = ConcurrentHashMap.newKeySet();
+
     /**
      * 批量订阅设备
      *
@@ -46,6 +51,8 @@ public class SubscriptionManager {
             return getSubscribedDevices(sessionId);
         }
 
+        allScopeSessions.remove(sessionId);
+
         // 更新正向映射
         sessionToDevices.compute(sessionId, (k, existing) -> {
             if (existing == null) {
@@ -102,12 +109,25 @@ public class SubscriptionManager {
         return getSubscribedDevices(sessionId);
     }
 
+    /**
+     * 订阅全部设备状态增量。
+     */
+    public void subscribeAll(String sessionId) {
+        clearDeviceSubscriptions(sessionId);
+        allScopeSessions.add(sessionId);
+    }
+
     /**
      * 移除会话的所有订阅(连接断开时调用)
      *
      * @param sessionId WebSocket 会话ID
      */
     public void removeSession(String sessionId) {
+        allScopeSessions.remove(sessionId);
+        clearDeviceSubscriptions(sessionId);
+    }
+
+    private void clearDeviceSubscriptions(String sessionId) {
         Set<String> deviceCodes = sessionToDevices.remove(sessionId);
         if (deviceCodes == null || deviceCodes.isEmpty()) {
             return;
@@ -134,6 +154,13 @@ public class SubscriptionManager {
         return sessions != null ? Collections.unmodifiableSet(sessions) : Collections.emptySet();
     }
 
+    /**
+     * 获取全量订阅的会话ID集合。
+     */
+    public Set<String> getAllScopeSessions() {
+        return Collections.unmodifiableSet(allScopeSessions);
+    }
+
     /**
      * 获取指定会话订阅的所有设备编码
      *
@@ -152,4 +179,4 @@ public class SubscriptionManager {
         return String.format("活跃会话数=%d, 被订阅设备数=%d",
                 sessionToDevices.size(), deviceToSessions.size());
     }
-}
+}

+ 349 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitEquipmentDetailAggregateControllerTest.java

@@ -0,0 +1,349 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.detail.CockpitEquipmentDetailAggregateService;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchive;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveResponse;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveService;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveSnapshot;
+import com.zksy.cockpit.equipment.CockpitEquipmentImage;
+import com.zksy.cockpit.event.CockpitAlarmWarningRelation;
+import com.zksy.cockpit.event.CockpitEventAlarm;
+import com.zksy.cockpit.event.CockpitEventReadResponse;
+import com.zksy.cockpit.event.CockpitEventReadService;
+import com.zksy.cockpit.event.CockpitEventSnapshot;
+import com.zksy.cockpit.event.CockpitEventWarning;
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.type.CockpitMetric;
+import com.zksy.cockpit.type.CockpitTypeMetricsResponse;
+import com.zksy.cockpit.type.CockpitTypeMetricsService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderEventAssociation;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadResponse;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderStateDictionary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderSummary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineEntry;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineResponse;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.lang.reflect.Method;
+import java.math.BigDecimal;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.hamcrest.Matchers.hasSize;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitEquipmentDetailAggregateControllerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+
+    private CockpitEquipmentArchiveService archiveService;
+    private CockpitTypeMetricsService metricsService;
+    private CockpitEventReadService eventService;
+    private CockpitWorkOrderReadService workOrderService;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        archiveService = mock(CockpitEquipmentArchiveService.class);
+        metricsService = mock(CockpitTypeMetricsService.class);
+        eventService = mock(CockpitEventReadService.class);
+        workOrderService = mock(CockpitWorkOrderReadService.class);
+        CockpitEquipmentDetailAggregateService service = new CockpitEquipmentDetailAggregateService(
+                archiveService,
+                metricsService,
+                eventService,
+                workOrderService,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitEquipmentDetailAggregateController(service))
+                .build();
+    }
+
+    @Test
+    void aggregateReturnsIndependentSuccessfulSections() throws Exception {
+        stubSuccessfulSections();
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate")
+                        .header("X-Request-Id", "detail-aggregate-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("detail-aggregate-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.aggregateState").value("READY"))
+                .andExpect(jsonPath("$.data.archive.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.archive.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.archive.data.deviceName").value("污水环境监测设备"))
+                .andExpect(jsonPath("$.data.metrics.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.metrics.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.metrics.data.state").value("CURRENT"))
+                .andExpect(jsonPath("$.data.metrics.data.metrics", hasSize(1)))
+                .andExpect(jsonPath("$.data.warnings.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.warnings.data", hasSize(1)))
+                .andExpect(jsonPath("$.data.alarms.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.alarms.data", hasSize(1)))
+                .andExpect(jsonPath("$.data.alarmWarningRelations.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.alarmWarningRelations.data", hasSize(1)))
+                .andExpect(jsonPath("$.data.workOrders.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.workOrders.data", hasSize(1)))
+                .andExpect(jsonPath("$.data.timelines.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.timelines.data", hasSize(1)))
+                .andExpect(jsonPath("$.data.timelines.data[0].timelineEntries", hasSize(1)))
+                .andExpect(jsonPath("$.data.latestImage.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.latestImage.data.url").value("https://cockpit.example/latest.jpg"));
+    }
+
+    @Test
+    void successfulEmptySectionsDoNotBecomeFailures() throws Exception {
+        stubEmptySections();
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.aggregateState").value("EMPTY"))
+                .andExpect(jsonPath("$.data.archive.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.metrics.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.warnings.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.alarms.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.alarmWarningRelations.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.workOrders.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.timelines.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.latestImage.state").value("EMPTY"));
+    }
+
+    @Test
+    void singleArchiveFailurePreservesSuccessfulSiblings() throws Exception {
+        when(archiveService.load("detail-aggregate-001", DEVICE_CODE))
+                .thenThrow(new CockpitReadException("archive read failed"));
+        stubSuccessfulSectionsExceptArchive();
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate")
+                        .header("X-Request-Id", "detail-aggregate-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.aggregateState").value("PARTIAL"))
+                .andExpect(jsonPath("$.data.archive.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.archive.reason").value("READ_FAILURE"))
+                .andExpect(jsonPath("$.data.metrics.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.warnings.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.alarms.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.workOrders.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.timelines.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.latestImage.state").value("FAILED"));
+    }
+
+    @Test
+    void multipleSectionFailuresAreReportedIndependently() throws Exception {
+        stubArchive();
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenThrow(new CockpitReadException("metrics failed"));
+        when(eventService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenThrow(new CockpitDeviceNotFoundException("events missing"));
+        when(workOrderService.loadByDevice("detail-aggregate-001", DEVICE_CODE))
+                .thenThrow(new CockpitReadException("work orders failed"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate")
+                        .header("X-Request-Id", "detail-aggregate-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.aggregateState").value("PARTIAL"))
+                .andExpect(jsonPath("$.data.archive.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.metrics.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.metrics.reason").value("READ_FAILURE"))
+                .andExpect(jsonPath("$.data.warnings.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.warnings.reason").value("NOT_FOUND"))
+                .andExpect(jsonPath("$.data.alarms.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.alarms.reason").value("NOT_FOUND"))
+                .andExpect(jsonPath("$.data.workOrders.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.workOrders.reason").value("READ_FAILURE"))
+                .andExpect(jsonPath("$.data.timelines.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.timelines.reason").value("SOURCE_SECTION_FAILED"))
+                .andExpect(jsonPath("$.data.latestImage.state").value("SUCCESS"));
+    }
+
+    @Test
+    void staleMetricsRemainVisibleWithIndependentStaleState() throws Exception {
+        stubArchive();
+        stubEventSection();
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(metricsResponse("STALE", "SAMPLE_OUTDATED"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate")
+                        .header("X-Request-Id", "detail-aggregate-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.aggregateState").value("PARTIAL"))
+                .andExpect(jsonPath("$.data.metrics.state").value("STALE"))
+                .andExpect(jsonPath("$.data.metrics.data.state").value("STALE"))
+                .andExpect(jsonPath("$.data.metrics.data.metrics", hasSize(1)));
+    }
+
+    @Test
+    void deviceCodeMismatchDoesNotLeakForeignSectionData() throws Exception {
+        stubArchive();
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(metricsResponse("CURRENT", "READY"));
+        when(eventService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(eventResponse("CN-GS-202609020099", "EMPTY", "NO_EVENTS",
+                        Collections.emptyList(), Collections.emptyList(), Collections.emptyList()));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate")
+                        .header("X-Request-Id", "detail-aggregate-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.metrics.state").value("SUCCESS"))
+                .andExpect(jsonPath("$.data.warnings.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.warnings.reason").value("DEVICE_CODE_MISMATCH"))
+                .andExpect(jsonPath("$.data.warnings.data").doesNotExist())
+                .andExpect(jsonPath("$.data.alarms.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.alarms.reason").value("DEVICE_CODE_MISMATCH"));
+    }
+
+    @Test
+    void controllerExposesReadOnlyMappedMethodsOnly() throws Exception {
+        Method[] methods = CockpitEquipmentDetailAggregateController.class.getDeclaredMethods();
+        for (Method method : methods) {
+            if (method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class)) {
+                assertTrue(!method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class));
+            }
+        }
+
+        stubSuccessfulSections();
+        mockMvc.perform(post("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/detail-aggregate"))
+                .andExpect(status().isMethodNotAllowed());
+    }
+
+    private void assertTrue(boolean condition) {
+        org.junit.jupiter.api.Assertions.assertTrue(condition);
+    }
+
+    private void stubSuccessfulSections() {
+        stubArchive();
+        stubSuccessfulSectionsExceptArchive();
+    }
+
+    private void stubSuccessfulSectionsExceptArchive() {
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(metricsResponse("CURRENT", "READY"));
+        stubEventSection();
+        stubWorkOrderSections();
+    }
+
+    private void stubEmptySections() {
+        when(archiveService.load("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(new CockpitEquipmentArchiveResponse(
+                        "detail-aggregate-001", "v1", true, new CockpitEquipmentArchive(null, "WGS84", null)));
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(metricsResponse("EMPTY", "NO_METRICS"));
+        when(eventService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(eventResponse(DEVICE_CODE, "EMPTY", "NO_EVENTS", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()));
+        when(workOrderService.loadByDevice("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(workOrderResponse(DEVICE_CODE, "EMPTY", "NO_WORK_ORDERS", Collections.emptyList()));
+    }
+
+    private void stubSuccessfulSectionsExceptWorkOrders() {
+        stubArchive();
+        when(metricsService.loadCurrent("detail-aggregate-001", DEVICE_CODE))
+                .thenReturn(metricsResponse("CURRENT", "READY"));
+        stubEventSection();
+    }
+
+    private void stubArchive() {
+        CockpitEquipmentImage image = new CockpitEquipmentImage(
+                "https://cockpit.example/latest.jpg", "2026-08-30T10:20:00+08:00");
+        CockpitEquipmentArchiveSnapshot snapshot = new CockpitEquipmentArchiveSnapshot(
+                DEVICE_CODE, "污水环境监测设备", "WS-PRO-2000", "悬浮物/COD/氨氮/电导率/PH",
+                "沅陵专用仪表厂", "2025-12-01", "ws_sewage_environment", "污水环境监测设备",
+                new BigDecimal("128000"), 10, new BigDecimal("110.141"), new BigDecimal("28.452"),
+                "太常片区", "2026-01-10 09:30:00", "张维护", "13800000000", "沅陵县排水管理所", "演示设备",
+                Collections.singletonList(image));
+        when(archiveService.load("detail-aggregate-001", DEVICE_CODE)).thenReturn(new CockpitEquipmentArchiveResponse(
+                "detail-aggregate-001", "v1", true, new CockpitEquipmentArchive(snapshot, "WGS84", image)));
+    }
+
+    private void stubEventSection() {
+        when(eventService.loadCurrent("detail-aggregate-001", DEVICE_CODE)).thenReturn(eventResponse(
+                DEVICE_CODE, "READY", "READY",
+                Collections.singletonList(warning("WRN-20260902-001")),
+                Collections.singletonList(alarm("ALM-20260902-001")),
+                Collections.singletonList(new CockpitAlarmWarningRelation(
+                        "REL-001", "WRN-20260902-001", "ALM-20260902-001", "2026-09-02T10:00:00+08:00"))));
+    }
+
+    private void stubWorkOrderSections() {
+        CockpitWorkOrderSummary summary = workOrderSummary();
+        when(workOrderService.loadByDevice("detail-aggregate-001", DEVICE_CODE)).thenReturn(workOrderResponse(
+                DEVICE_CODE, "READY", "READY", Collections.singletonList(summary)));
+        when(workOrderService.loadTimeline("detail-aggregate-001", "WO-2026090200001")).thenReturn(timelineResponse(summary));
+    }
+
+    private CockpitTypeMetricsResponse metricsResponse(String state, String stateReason) {
+        CockpitMetric metric = new CockpitMetric(
+                "COD", "COD", new BigDecimal("18.2"), "mg/L", "WARNING",
+                "2026-09-02T09:59:30+08:00", "CURRENT", Collections.emptyList());
+        return new CockpitTypeMetricsResponse(
+                "detail-aggregate-001", "v1", true, DEVICE_CODE, "ws_sewage_environment", "污水环境监测设备",
+                state, stateReason, Collections.singletonList(metric), null, null, "Asia/Shanghai", 1, 0, 1);
+    }
+
+    private CockpitEventReadResponse eventResponse(
+            String deviceCode, String state, String stateReason,
+            java.util.List<CockpitEventWarning> warnings,
+            java.util.List<CockpitEventAlarm> alarms,
+            java.util.List<CockpitAlarmWarningRelation> relations) {
+        return new CockpitEventReadResponse(
+                "detail-aggregate-001", "v1", true, deviceCode, "ws_sewage_environment", "污水环境监测设备",
+                state, stateReason, warnings, alarms, relations, null, null, "Asia/Shanghai", 1, 0, 2);
+    }
+
+    private CockpitWorkOrderReadResponse workOrderResponse(
+            String deviceCode, String state, String stateReason,
+            java.util.List<CockpitWorkOrderSummary> workOrders) {
+        return new CockpitWorkOrderReadResponse(
+                "detail-aggregate-001", "v1", true, deviceCode, null, null,
+                state, stateReason, CockpitWorkOrderStateDictionary.states(), workOrders);
+    }
+
+    private CockpitWorkOrderTimelineResponse timelineResponse(CockpitWorkOrderSummary summary) {
+        return new CockpitWorkOrderTimelineResponse(
+                "detail-aggregate-001", "v1", true, summary.getWorkOrderCode(),
+                CockpitWorkOrderStateDictionary.states(), summary,
+                Collections.singletonList(new CockpitWorkOrderTimelineEntry(
+                        1L, summary.getWorkOrderCode(), 4, "处理中", "创建工单", "处理异常", "系统",
+                        "2026-09-02T09:00:00+08:00")));
+    }
+
+    private CockpitWorkOrderSummary workOrderSummary() {
+        return new CockpitWorkOrderSummary(
+                "WO-2026090200001", DEVICE_CODE, 1, "故障维修", 1, "处理异常", 4, "处理中",
+                "2026-09-02T09:00:00+08:00", "2026-09-02T10:00:00+08:00",
+                "2026-09-03T09:00:00+08:00", null,
+                new CockpitWorkOrderEventAssociation("ALARM", "ALM-20260902-001", "2026-09-02T10:00:00+08:00"));
+    }
+
+    private CockpitEventWarning warning(String warningNo) {
+        return new CockpitEventWarning(
+                warningNo, "污水COD预警", "WS_ENV", 1, "RED", "PROCESSING",
+                "2026-09-02T09:59:30+08:00", new BigDecimal("18.2"), "mg/L",
+                DEVICE_CODE, "污水环境监测设备", "太常片区");
+    }
+
+    private CockpitEventAlarm alarm(String alarmId) {
+        return new CockpitEventAlarm(
+                alarmId, "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 1, "RED", "UNHANDLED",
+                "2026-09-02T10:00:00+08:00", new BigDecimal("42"), new BigDecimal("40"),
+                new BigDecimal("50"), "mg/L", DEVICE_CODE, "污水环境监测设备", "太常片区");
+    }
+}

+ 213 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitFreshnessSemanticsControllerTest.java

@@ -0,0 +1,213 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitFreshnessAdapter;
+import com.zksy.cockpit.foundation.CockpitFreshnessService;
+import com.zksy.cockpit.foundation.CockpitFreshnessSource;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitFreshnessSemanticsControllerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+    private static final String SERVER_TIME = "2026-09-02T10:00:00+08:00";
+
+    private CockpitFreshnessAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitFreshnessAdapter.class);
+        CockpitFreshnessService service = new CockpitFreshnessService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC),
+                60);
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitFreshnessController(service, Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC)))
+                .build();
+    }
+
+    @Test
+    void emptySourceReturnsSuccessfulEmptyResult() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(null);
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-empty-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("freshness-empty-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.freshness").value("EMPTY"))
+                .andExpect(jsonPath("$.data.staleReason").doesNotExist())
+                .andExpect(jsonPath("$.data.retained").value(false))
+                .andExpect(jsonPath("$.data.section.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.section.reason").value("NO_SOURCE"))
+                .andExpect(jsonPath("$.data.error").doesNotExist());
+    }
+
+    @Test
+    void freshnessUsesLatestSourceTimestampOnly() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(source("2026-09-02T09:59:50+08:00", "2026-09-02T09:59:55+08:00"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-current-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.updatedAt").value("2026-09-02T09:59:50+08:00"))
+                .andExpect(jsonPath("$.data.statusTime").value("2026-09-02T09:59:55+08:00"))
+                .andExpect(jsonPath("$.data.serverUpdatedAt").value(SERVER_TIME))
+                .andExpect(jsonPath("$.data.freshness").value("CURRENT"))
+                .andExpect(jsonPath("$.data.staleReason").doesNotExist())
+                .andExpect(jsonPath("$.data.dataAgeSeconds").value(5))
+                .andExpect(jsonPath("$.data.missedCycles").value(0))
+                .andExpect(jsonPath("$.data.retained").value(false))
+                .andExpect(jsonPath("$.data.section.state").value("CURRENT"))
+                .andExpect(jsonPath("$.data.section.data.dataAgeSeconds").value(5));
+    }
+
+    @Test
+    void oneMissedCycleMarksStaleAndRetainsCache() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(source("2026-09-02T09:59:00+08:00", null));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-stale-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.serverUpdatedAt").value(SERVER_TIME))
+                .andExpect(jsonPath("$.data.freshness").value("STALE"))
+                .andExpect(jsonPath("$.data.staleReason").value("ONE_UPDATE_CYCLE_MISSED"))
+                .andExpect(jsonPath("$.data.missedCycles").value(1))
+                .andExpect(jsonPath("$.data.retained").value(true))
+                .andExpect(jsonPath("$.data.section.state").value("STALE"))
+                .andExpect(jsonPath("$.data.section.data.retained").value(true));
+    }
+
+    @Test
+    void twoMissedCyclesMarkExpiredButRetainCache() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(source("2026-09-02T09:58:00+08:00", null));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-expired-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.freshness").value("EXPIRED"))
+                .andExpect(jsonPath("$.data.staleReason").value("TWO_UPDATE_CYCLES_MISSED"))
+                .andExpect(jsonPath("$.data.missedCycles").value(2))
+                .andExpect(jsonPath("$.data.retained").value(true))
+                .andExpect(jsonPath("$.data.section.state").value("EXPIRED"))
+                .andExpect(jsonPath("$.data.section.message").value("数据暂不可用/已过期"));
+    }
+
+    @Test
+    void calibrationPeriodIsConfigurablePerRequest() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(source("2026-09-02T09:59:30+08:00", null));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .param("calibrationPeriodSeconds", "15")
+                        .header("X-Request-Id", "freshness-configurable-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.calibrationPeriodSeconds").value(15))
+                .andExpect(jsonPath("$.data.freshness").value("EXPIRED"))
+                .andExpect(jsonPath("$.data.missedCycles").value(2));
+    }
+
+    @Test
+    void notFoundSourceReturnsTypedNotFoundError() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenThrow(new CockpitDeviceNotFoundException("device not found"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-404-001"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.code").value(404))
+                .andExpect(jsonPath("$.data.category").value("NOT_FOUND"))
+                .andExpect(jsonPath("$.data.requestId").value("freshness-404-001"))
+                .andExpect(jsonPath("$.data.serverTime").value(SERVER_TIME));
+    }
+
+    @Test
+    void sourceFailureReturnsTypedServerError() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenThrow(new CockpitReadException("source unavailable"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-500-001"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"))
+                .andExpect(jsonPath("$.data.requestId").value("freshness-500-001"))
+                .andExpect(jsonPath("$.data.serverTime").value(SERVER_TIME));
+    }
+
+    @Test
+    void invalidCalibrationPeriodReturnsTypedBadRequestBeforeAdapterIsCalled() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .param("calibrationPeriodSeconds", "0")
+                        .header("X-Request-Id", "freshness-400-001"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.requestId").value("freshness-400-001"));
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void invalidSourceTimestampReturnsTypedBadRequest() throws Exception {
+        when(adapter.load(DEVICE_CODE)).thenReturn(source("not-a-timestamp", null));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness")
+                        .header("X-Request-Id", "freshness-invalid-time-001"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.requestId").value("freshness-invalid-time-001"));
+    }
+
+    @Test
+    void mutatingRequestIsRejectedBeforeAdapterIsCalled() throws Exception {
+        mockMvc.perform(post("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/freshness"))
+                .andExpect(status().isMethodNotAllowed());
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void controllerExposesAuthenticatedReadOnlyOperationsOnly() {
+        Method[] methods = CockpitFreshnessController.class.getDeclaredMethods();
+        for (Method method : methods) {
+            if (method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class)) {
+                assertTrue(!method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class));
+            }
+        }
+        assertTrue(Arrays.stream(CockpitFreshnessController.class.getDeclaredMethods())
+                .filter(method -> method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class))
+                .allMatch(method -> method.isAnnotationPresent(org.springframework.security.access.prepost.PreAuthorize.class)
+                        && method.getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class)
+                        .value()
+                        .equals("isAuthenticated()")));
+    }
+
+    private void assertTrue(boolean condition) {
+        org.junit.jupiter.api.Assertions.assertTrue(condition);
+    }
+
+    private static CockpitFreshnessSource source(String updatedAt, String statusTime) {
+        return new CockpitFreshnessSource(DEVICE_CODE, updatedAt, statusTime);
+    }
+}

+ 282 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewInfrastructureControllerTest.java

@@ -0,0 +1,282 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.overview.CockpitOverviewInfrastructureAdapter;
+import com.zksy.cockpit.overview.CockpitOverviewInfrastructureService;
+import com.zksy.cockpit.overview.CockpitOverviewInfrastructureSnapshot;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.lang.reflect.Method;
+import java.math.BigDecimal;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.hamcrest.Matchers.hasSize;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitOverviewInfrastructureControllerTest {
+
+    private CockpitOverviewInfrastructureAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitOverviewInfrastructureAdapter.class);
+        CockpitOverviewInfrastructureService service = new CockpitOverviewInfrastructureService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new com.zksy.web.controller.cockpit.CockpitOverviewInfrastructureController(service))
+                .build();
+    }
+
+    @Test
+    void formalScopesExcludeUnknownAndMismatchedTypes() throws Exception {
+        when(adapter.load()).thenReturn(scopeFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/infrastructure"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.totals.facilityCount").value(3))
+                .andExpect(jsonPath("$.data.totals.smartDeviceCount").value(14))
+                .andExpect(jsonPath("$.data.industries", hasSize(3)))
+                .andExpect(jsonPath("$.data.industries[0].code").value("GAS"))
+                .andExpect(jsonPath("$.data.industries[0].facilityCount").value(0))
+                .andExpect(jsonPath("$.data.industries[0].smartDeviceCount").value(3))
+                .andExpect(jsonPath("$.data.industries[1].code").value("WATER_SUPPLY"))
+                .andExpect(jsonPath("$.data.industries[1].facilityCount").value(3))
+                .andExpect(jsonPath("$.data.industries[1].smartDeviceCount").value(0))
+                .andExpect(jsonPath("$.data.industries[2].code").value("DRAINAGE"))
+                .andExpect(jsonPath("$.data.industries[2].smartDeviceCount").value(9))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes", hasSize(2)))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes[0].code").value("RAINWATER_SENSOR"))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes[0].count").value(4))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes[1].code").value("SEWAGE_ENVIRONMENT_SENSOR"))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes[1].count").value(5))
+                .andExpect(jsonPath("$.data.excluded.unknownTypeCount").value(8))
+                .andExpect(jsonPath("$.data.excluded.typeKindMismatchCount").value(5));
+    }
+
+    @Test
+    void overviewSeparatesFacilitiesFromSmartDevices() throws Exception {
+        when(adapter.load()).thenReturn(fixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/infrastructure")
+                        .header("X-Request-Id", "overview-infrastructure-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"))
+                .andExpect(jsonPath("$.data.requestId").value("overview-infrastructure-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.totals.facilityCount").value(1))
+                .andExpect(jsonPath("$.data.totals.smartDeviceCount").value(1))
+                .andExpect(jsonPath("$.data.industries", org.hamcrest.Matchers.hasSize(3)))
+                .andExpect(jsonPath("$.data.industries[0].code").value("GAS"))
+                .andExpect(jsonPath("$.data.industries[1].code").value("WATER_SUPPLY"))
+                .andExpect(jsonPath("$.data.industries[1].facilityCount").value(1))
+                .andExpect(jsonPath("$.data.industries[1].smartDeviceCount").value(1))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].code").value("WATER_PLANT"))
+                .andExpect(jsonPath("$.data.industries[1].deviceTypes", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.industries[1].deviceTypes[0].code").value("WATER_SUPPLY_SENSOR"));
+    }
+
+    @Test
+    void infrastructureExposesScaleRangeTimezoneAndFreshness() throws Exception {
+        when(adapter.load()).thenReturn(metadataFixture());
+
+        MvcResult result = mockMvc.perform(get("/api/cockpit/v1/overview/infrastructure")
+                        .header("X-Request-Id", "overview-infrastructure-002"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.timezone").value("Asia/Shanghai"))
+                .andExpect(jsonPath("$.data.range.type").value("CURRENT_BASELINE"))
+                .andExpect(jsonPath("$.data.updatedAt").value("2026-09-02T09:59:50+08:00"))
+                .andExpect(jsonPath("$.data.freshness.status").value("CURRENT"))
+                .andExpect(jsonPath("$.data.freshness.updatedAt").value("2026-09-02T09:59:50+08:00"))
+                .andExpect(jsonPath("$.data.freshness.serverUpdatedAt").value("2026-09-02T10:00:00+08:00"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes", hasSize(2)))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].code").value("PIPELINE"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].lengthKm").value(12.5))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].range.type").value("DIAMETER_MM"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].range.start").value("100"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[0].range.end").value("800"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[1].code").value("PUMP_STATION"))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes[1].scale").value("medium"))
+                .andExpect(jsonPath("$.data.industries[1].deviceTypes[0].scale").value("pressure-meters"))
+                .andReturn();
+
+        String body = result.getResponse().getContentAsString();
+        assertFalse(body.contains("equipment_code"));
+        assertFalse(body.contains("facility_count"));
+        assertFalse(body.contains("smart_device_count"));
+    }
+
+    @Test
+    void emptySourceReturnsExplicitZeroState() throws Exception {
+        when(adapter.load()).thenReturn(new CockpitOverviewInfrastructureSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                Collections.emptyList(),
+                Collections.emptyList()));
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/infrastructure"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.totals.facilityCount").value(0))
+                .andExpect(jsonPath("$.data.totals.smartDeviceCount").value(0))
+                .andExpect(jsonPath("$.data.industries", hasSize(3)))
+                .andExpect(jsonPath("$.data.industries[0].facilityTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.industries[0].deviceTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.industries[1].facilityTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.industries[1].deviceTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.industries[2].facilityTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.industries[2].deviceTypes", hasSize(0)))
+                .andExpect(jsonPath("$.data.excluded.unknownTypeCount").value(0))
+                .andExpect(jsonPath("$.data.excluded.typeKindMismatchCount").value(0));
+    }
+
+    @Test
+    void serverFailureReturnsTypedErrorInsteadOfPretendingToBeEmpty() throws Exception {
+        when(adapter.load()).thenThrow(new CockpitReadException("upstream unavailable"));
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/infrastructure")
+                        .header("X-Request-Id", "overview-infrastructure-500"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.msg").value("驾驶舱基础设施概览数据暂不可用"))
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"))
+                .andExpect(jsonPath("$.data.message").value("驾驶舱基础设施概览数据暂不可用"))
+                .andExpect(jsonPath("$.data.requestId").value("overview-infrastructure-500"))
+                .andExpect(jsonPath("$.data.serverTime").value("2026-09-02T10:00:00+08:00"));
+    }
+
+    @Test
+    void mutatingRequestIsRejectedBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(post("/api/cockpit/v1/overview/infrastructure"))
+                .andExpect(status().isMethodNotAllowed());
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void controllerOnlyExposesAuthenticatedReadOnlyOperations() {
+        assertTrue(Arrays.stream(CockpitOverviewInfrastructureController.class.getDeclaredMethods())
+                .filter(method -> method.isAnnotationPresent(
+                        org.springframework.web.bind.annotation.RequestMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class))
+                .allMatch(CockpitOverviewInfrastructureControllerTest::isReadOnlyMappedMethod));
+
+        assertTrue(Arrays.stream(CockpitOverviewInfrastructureController.class.getDeclaredMethods())
+                .anyMatch(method -> method.isAnnotationPresent(
+                        org.springframework.security.access.prepost.PreAuthorize.class)
+                        && method.getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class)
+                        .value()
+                        .equals("isAuthenticated()")));
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot fixture() {
+        return new CockpitOverviewInfrastructureSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                Arrays.asList(
+                        new CockpitOverviewInfrastructureSnapshot.SourceType(
+                                "WATER_PLANT", "水厂", "WATER_SUPPLY", null, "FACILITY"),
+                        new CockpitOverviewInfrastructureSnapshot.SourceType(
+                                "WATER_SUPPLY_SENSOR", "供水压力计", "WATER_SUPPLY", null, "SMART_DEVICE")),
+                Arrays.asList(
+                        new CockpitOverviewInfrastructureSnapshot.SourceCount(
+                                "FACILITY", "WATER_PLANT", 1),
+                        new CockpitOverviewInfrastructureSnapshot.SourceCount(
+                                "SMART_DEVICE", "WATER_SUPPLY_SENSOR", 1)));
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot metadataFixture() {
+        return new CockpitOverviewInfrastructureSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                Arrays.asList(
+                        type("PIPELINE", "供水管线", "WATER_SUPPLY", null, "FACILITY"),
+                        type("PUMP_STATION", "泵站", "WATER_SUPPLY", null, "FACILITY"),
+                        type("WATER_SUPPLY_SENSOR", "供水压力计", "WATER_SUPPLY", null, "SMART_DEVICE")),
+                Arrays.asList(
+                        count("FACILITY", "PIPELINE", 1,
+                                value(new BigDecimal("12.5"), null, range("DIAMETER_MM", "100", "800"))),
+                        count("FACILITY", "PUMP_STATION", 1, value(null, "medium", null)),
+                        count("SMART_DEVICE", "WATER_SUPPLY_SENSOR", 2,
+                                value(null, "pressure-meters", null))));
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot scopeFixture() {
+        return new CockpitOverviewInfrastructureSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                Arrays.asList(
+                        type("WATER_PLANT", "水厂", "WATER_SUPPLY", null, "FACILITY"),
+                        type("PIPELINE", "供水管线", "WATER_SUPPLY", null, "FACILITY"),
+                        type("GAS_SENSOR", "燃气浓度计", "GAS", null, "SMART_DEVICE"),
+                        type("RAINWATER_SENSOR", "雨水流量计", "DRAINAGE", "RAINWATER", "SMART_DEVICE"),
+                        type("SEWAGE_ENVIRONMENT_SENSOR", "污水环境监测仪", "DRAINAGE", "SEWAGE", "SMART_DEVICE"),
+                        type("WATER_PLANT_DEVICE", "水厂设备", "WATER_SUPPLY", null, "SMART_DEVICE"),
+                        type("SMART_MANHOLE", "智能井盖", null, null, "SMART_DEVICE")),
+                Arrays.asList(
+                        count("FACILITY", "WATER_PLANT", 2),
+                        count("FACILITY", "PIPELINE", 1),
+                        count("SMART_DEVICE", "GAS_SENSOR", 3),
+                        count("SMART_DEVICE", "RAINWATER_SENSOR", 4),
+                        count("SMART_DEVICE", "SEWAGE_ENVIRONMENT_SENSOR", 5),
+                        count("SMART_DEVICE", "SMART_MANHOLE", 2),
+                        count("FACILITY", "UNKNOWN_FACILITY_TYPE", 7),
+                        count("SMART_DEVICE", "UNKNOWN_DEVICE_TYPE", 1),
+                        count("FACILITY", "WATER_PLANT_DEVICE", 3),
+                        count("SMART_DEVICE", "WATER_PLANT", 2)));
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot.SourceType type(
+            String code, String name, String industry, String scope, String objectKind) {
+        return new CockpitOverviewInfrastructureSnapshot.SourceType(
+                code, name, industry, scope, objectKind);
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot.SourceCount count(
+            String objectKind, String typeCode, int count) {
+        return new CockpitOverviewInfrastructureSnapshot.SourceCount(objectKind, typeCode, count);
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot.SourceCount count(
+            String objectKind, String typeCode, int count,
+            CockpitOverviewInfrastructureSnapshot.SourceValue value) {
+        return new CockpitOverviewInfrastructureSnapshot.SourceCount(objectKind, typeCode, count, value);
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot.SourceValue value(
+            BigDecimal lengthKm, String scale, CockpitOverviewInfrastructureSnapshot.SourceRange range) {
+        return new CockpitOverviewInfrastructureSnapshot.SourceValue(lengthKm, scale, range);
+    }
+
+    private static CockpitOverviewInfrastructureSnapshot.SourceRange range(
+            String type, String start, String end) {
+        return new CockpitOverviewInfrastructureSnapshot.SourceRange(type, start, end);
+    }
+
+    private static boolean isReadOnlyMappedMethod(Method method) {
+        return method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class)
+                && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                && !method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class);
+    }
+}

+ 167 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringControllerTest.java

@@ -0,0 +1,167 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringAdapter;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringService;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringSnapshot;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitOverviewMonitoringControllerTest {
+
+    private CockpitOverviewMonitoringAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitOverviewMonitoringAdapter.class);
+        CockpitOverviewMonitoringService service = new CockpitOverviewMonitoringService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitOverviewMonitoringController(service))
+                .build();
+    }
+
+    @Test
+    void overviewMonitoringUsesEnvelopeAndCamelCaseContract() throws Exception {
+        when(adapter.load()).thenReturn(fixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/monitoring")
+                        .header("X-Request-Id", "overview-monitoring-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"))
+                .andExpect(jsonPath("$.data.requestId").value("overview-monitoring-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.timezone").value("Asia/Shanghai"))
+                .andExpect(jsonPath("$.data.updatedAt").value("2026-09-02T09:59:50+08:00"))
+                .andExpect(jsonPath("$.data.selectedIndustry.code").doesNotExist())
+                .andExpect(jsonPath("$.data.formalScope.industries[0]").value("GAS"))
+                .andExpect(jsonPath("$.data.formalScope.keys[0]").value("gas"))
+                .andExpect(jsonPath("$.data.counts.deviceCount").value(4))
+                .andExpect(jsonPath("$.data.counts.monitoringPointCount").value(2))
+                .andExpect(jsonPath("$.data.counts.monitoringFacilityCount").value(3))
+                .andExpect(jsonPath("$.data.counts.infrastructureFacilityCount").value(99))
+                .andExpect(jsonPath("$.data.typeDistribution[0].industry.code").value("GAS"))
+                .andExpect(jsonPath("$.data.typeDistribution[0].deviceType.code").value("GAS_SENSOR"))
+                .andExpect(jsonPath("$.data.typeDistribution[0].deviceCount").value(2))
+                .andExpect(jsonPath("$.data.metricFreshness.status").value("CURRENT"));
+    }
+
+    @Test
+    void industryFilterIsAppliedAtTheRestControllerSeam() throws Exception {
+        when(adapter.load()).thenReturn(fixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/monitoring")
+                        .queryParam("industry", "GAS"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.selectedIndustry.code").value("GAS"))
+                .andExpect(jsonPath("$.data.selectedIndustry.key").value("gas"))
+                .andExpect(jsonPath("$.data.counts.deviceCount").value(2))
+                .andExpect(jsonPath("$.data.counts.monitoringPointCount").value(1))
+                .andExpect(jsonPath("$.data.typeDistribution", org.hamcrest.Matchers.hasSize(1)));
+    }
+
+    @Test
+    void invalidIndustryReturnsTypedBadRequestBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/overview/monitoring")
+                        .queryParam("industry", "MANHOLE"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.message").value("industry must be GAS, WATER_SUPPLY or DRAINAGE"));
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void mutatingRequestIsRejectedBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(post("/api/cockpit/v1/overview/monitoring"))
+                .andExpect(status().isMethodNotAllowed());
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void serverFailureReturnsTypedServerError() throws Exception {
+        when(adapter.load()).thenThrow(new CockpitReadException("upstream unavailable"));
+
+        mockMvc.perform(get("/api/cockpit/v1/overview/monitoring")
+                        .header("X-Request-Id", "overview-monitoring-500"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"))
+                .andExpect(jsonPath("$.data.message").value("驾驶舱运行监测概览数据暂不可用"))
+                .andExpect(jsonPath("$.data.requestId").value("overview-monitoring-500"))
+                .andExpect(jsonPath("$.data.serverTime").value("2026-09-02T10:00:00+08:00"));
+    }
+
+    @Test
+    void controllerOnlyExposesAuthenticatedReadOnlyOperations() {
+        assertTrue(Arrays.stream(CockpitOverviewMonitoringController.class.getDeclaredMethods())
+                .filter(method -> method.isAnnotationPresent(GetMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                        || method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class))
+                .allMatch(method -> method.isAnnotationPresent(GetMapping.class)));
+
+        assertTrue(Arrays.stream(CockpitOverviewMonitoringController.class.getDeclaredMethods())
+                .anyMatch(method -> method.isAnnotationPresent(
+                        org.springframework.security.access.prepost.PreAuthorize.class)
+                        && "isAuthenticated()".equals(method.getAnnotation(
+                                org.springframework.security.access.prepost.PreAuthorize.class).value())));
+    }
+
+    private static CockpitOverviewMonitoringSnapshot fixture() {
+        return new CockpitOverviewMonitoringSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                new CockpitOverviewMonitoringSnapshot.SourceMetricFreshness("CURRENT", "2026-09-02T09:59:50+08:00"),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "GAS_SENSOR", "燃气浓度计", "GAS", null, "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "WATER_SUPPLY_SENSOR", "供水压力计", "WATER_SUPPLY", null, "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "RAINWATER_SENSOR", "雨水流量计", "DRAINAGE", "RAINWATER", "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "WATER_PLANT", "水厂", "WATER_SUPPLY", null, "FACILITY"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "SMART_MANHOLE", "智能井盖", null, null, "SMART_DEVICE")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("GAS-001", "GAS_SENSOR", "ONLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("GAS-002", "GAS_SENSOR", "OFFLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-001", "WATER_SUPPLY_SENSOR", "STALE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-002", "WATER_SUPPLY_SENSOR", null),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("UNKNOWN-001", "SMART_MANHOLE", "ONLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("MISMATCH-001", "WATER_PLANT", "ONLINE")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringPoint("POINT-GAS", "GAS_SENSOR"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringPoint("POINT-WS", "WATER_SUPPLY_SENSOR")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-001", "WATER_PLANT"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-002", "WATER_PLANT"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-003", "WATER_PLANT")),
+                99);
+    }
+}

+ 202 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewMonitoringServiceTest.java

@@ -0,0 +1,202 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringAdapter;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringDeviceStatusDelta;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringResponse;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringService;
+import com.zksy.cockpit.overview.CockpitOverviewMonitoringSnapshot;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class CockpitOverviewMonitoringServiceTest {
+
+    private CockpitOverviewMonitoringAdapter adapter;
+    private CockpitOverviewMonitoringService service;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitOverviewMonitoringAdapter.class);
+        service = new CockpitOverviewMonitoringService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+    }
+
+    @Test
+    void mixedStatesExposeResolvedDenominatorAndExplicitUnknownState() {
+        when(adapter.load()).thenReturn(fixture());
+
+        CockpitOverviewMonitoringResponse response = service.load("request-001", null);
+
+        assertEquals(Integer.valueOf(4), response.getCounts().getDeviceCount());
+        assertEquals(Integer.valueOf(2), response.getCounts().getMonitoringPointCount());
+        assertEquals(Integer.valueOf(3), response.getCounts().getMonitoringFacilityCount());
+        assertEquals(Integer.valueOf(99), response.getCounts().getInfrastructureFacilityCount());
+        assertEquals(Integer.valueOf(1), response.getCounts().getStatus().getOnline());
+        assertEquals(Integer.valueOf(1), response.getCounts().getStatus().getOffline());
+        assertEquals(Integer.valueOf(1), response.getCounts().getStatus().getStale());
+        assertEquals(Integer.valueOf(1), response.getCounts().getStatus().getUnknownOrMissing());
+        assertEquals(Integer.valueOf(3), response.getCounts().getOnlineRate().getDenominator());
+        assertEquals("0.3333", response.getCounts().getOnlineRate().getValue().toPlainString());
+        assertEquals("AVAILABLE", response.getCounts().getOnlineRate().getState());
+        assertEquals("STALE", response.getFreshness().getStatus());
+        assertEquals("MONITORING_STATE_STALE", response.getFreshness().getReason());
+    }
+
+    @Test
+    void emptyCollectionReturnsExplicitZeroRateAndEmptyFreshness() {
+        when(adapter.load()).thenReturn(emptyFixture());
+
+        CockpitOverviewMonitoringResponse response = service.load("request-empty", null);
+
+        assertEquals(Integer.valueOf(0), response.getCounts().getDeviceCount());
+        assertEquals(Integer.valueOf(0), response.getCounts().getMonitoringPointCount());
+        assertEquals(Integer.valueOf(0), response.getCounts().getMonitoringFacilityCount());
+        assertEquals(Integer.valueOf(0), response.getCounts().getStatus().getUnknownOrMissing());
+        assertEquals(Integer.valueOf(0), response.getCounts().getOnlineRate().getDenominator());
+        assertEquals("0.0000", response.getCounts().getOnlineRate().getValue().toPlainString());
+        assertEquals("EMPTY", response.getCounts().getOnlineRate().getState());
+        assertEquals("NO_RESOLVED_DEVICES", response.getCounts().getOnlineRate().getReason());
+        assertEquals("EMPTY", response.getFreshness().getStatus());
+        assertEquals("NO_RESOLVED_DEVICES", response.getFreshness().getReason());
+    }
+
+    @Test
+    void industryFilterIncludesOnlyTheSelectedFormalIndustry() {
+        when(adapter.load()).thenReturn(fixture());
+
+        CockpitOverviewMonitoringResponse response = service.load("request-gas", "GAS");
+
+        assertEquals("GAS", response.getSelectedIndustry().getCode());
+        assertEquals("gas", response.getSelectedIndustry().getKey());
+        assertEquals(Integer.valueOf(2), response.getCounts().getDeviceCount());
+        assertEquals(Integer.valueOf(1), response.getCounts().getMonitoringPointCount());
+        assertEquals(Integer.valueOf(0), response.getCounts().getMonitoringFacilityCount());
+        assertEquals(Integer.valueOf(99), response.getCounts().getInfrastructureFacilityCount());
+        assertEquals(1, response.getTypeDistribution().size());
+        assertEquals("GAS_SENSOR", response.getTypeDistribution().get(0).getDeviceType().getCode());
+    }
+
+    @Test
+    void allUnknownStatesUseExplicitEmptyFreshnessAndZeroRateDenominator() {
+        when(adapter.load()).thenReturn(unknownOnlyFixture());
+
+        CockpitOverviewMonitoringResponse response = service.load("request-unknown", null);
+
+        assertEquals(Integer.valueOf(2), response.getCounts().getDeviceCount());
+        assertEquals(Integer.valueOf(2), response.getCounts().getStatus().getUnknownOrMissing());
+        assertEquals(Integer.valueOf(0), response.getCounts().getOnlineRate().getDenominator());
+        assertEquals("EMPTY", response.getCounts().getOnlineRate().getState());
+        assertEquals("EMPTY", response.getFreshness().getStatus());
+        assertEquals("NO_RESOLVED_DEVICES", response.getFreshness().getReason());
+    }
+
+    @Test
+    void unknownAndMismatchedTypesAreNotSilentlyCountedInFormalScope() {
+        when(adapter.load()).thenReturn(fixture());
+
+        CockpitOverviewMonitoringResponse response = service.load("request-scope", null);
+
+        assertEquals(Integer.valueOf(1), response.getExcluded().getUnknownTypeCount());
+        assertEquals(Integer.valueOf(1), response.getExcluded().getTypeKindMismatchCount());
+        assertEquals(2, response.getTypeDistribution().size());
+        assertEquals(Integer.valueOf(4), response.getCounts().getDeviceCount());
+    }
+
+    @Test
+    void deviceStatusDeltaRecomputesCountsOnlineRateAndDistribution() {
+        when(adapter.load()).thenReturn(fixture());
+
+        CockpitOverviewMonitoringResponse first = service.applyDeviceStatusDelta(
+                "request-delta-001",
+                null,
+                new CockpitOverviewMonitoringDeviceStatusDelta(
+                        "GAS-002", "ONLINE", null, "2026-09-02T10:05:00+08:00"));
+
+        assertEquals(Integer.valueOf(2), first.getCounts().getStatus().getOnline());
+        assertEquals(Integer.valueOf(0), first.getCounts().getStatus().getOffline());
+        assertEquals(Integer.valueOf(1), first.getCounts().getStatus().getStale());
+        assertEquals(Integer.valueOf(3), first.getCounts().getOnlineRate().getDenominator());
+        assertEquals("0.6667", first.getCounts().getOnlineRate().getValue().toPlainString());
+        assertEquals("2026-09-02T10:05:00+08:00", first.getUpdatedAt());
+
+        CockpitOverviewMonitoringResponse second = service.applyDeviceStatusDelta(
+                "request-delta-002",
+                null,
+                new CockpitOverviewMonitoringDeviceStatusDelta(
+                        "GAS-002", "OFFLINE", null, "2026-09-02T10:04:00+08:00"));
+
+        assertEquals(Integer.valueOf(2), second.getCounts().getStatus().getOnline());
+        assertEquals(Integer.valueOf(0), second.getCounts().getStatus().getOffline());
+        assertEquals(Integer.valueOf(1), second.getCounts().getStatus().getStale());
+        assertEquals("0.6667", second.getCounts().getOnlineRate().getValue().toPlainString());
+        assertEquals("2026-09-02T10:05:00+08:00", second.getUpdatedAt());
+    }
+
+    private static CockpitOverviewMonitoringSnapshot fixture() {
+        return new CockpitOverviewMonitoringSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                new CockpitOverviewMonitoringSnapshot.SourceMetricFreshness("CURRENT", "2026-09-02T09:59:50+08:00"),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "GAS_SENSOR", "燃气浓度计", "GAS", null, "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "WATER_SUPPLY_SENSOR", "供水压力计", "WATER_SUPPLY", null, "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "RAINWATER_SENSOR", "雨水流量计", "DRAINAGE", "RAINWATER", "SMART_DEVICE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "WATER_PLANT", "水厂", "WATER_SUPPLY", null, "FACILITY"),
+                        new CockpitOverviewMonitoringSnapshot.SourceType(
+                                "SMART_MANHOLE", "智能井盖", null, null, "SMART_DEVICE")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("GAS-001", "GAS_SENSOR", "ONLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("GAS-002", "GAS_SENSOR", "OFFLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-001", "WATER_SUPPLY_SENSOR", "STALE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-002", "WATER_SUPPLY_SENSOR", null),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("UNKNOWN-001", "SMART_MANHOLE", "ONLINE"),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("MISMATCH-001", "WATER_PLANT", "ONLINE")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringPoint("POINT-GAS", "GAS_SENSOR"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringPoint("POINT-WS", "WATER_SUPPLY_SENSOR")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-001", "WATER_PLANT"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-002", "WATER_PLANT"),
+                        new CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility("FACILITY-003", "WATER_PLANT")),
+                99);
+    }
+
+    private static CockpitOverviewMonitoringSnapshot emptyFixture() {
+        return new CockpitOverviewMonitoringSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                null,
+                Collections.emptyList(),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                0);
+    }
+
+    private static CockpitOverviewMonitoringSnapshot unknownOnlyFixture() {
+        return new CockpitOverviewMonitoringSnapshot(
+                "2026-09-02T09:59:50+08:00",
+                null,
+                Collections.singletonList(new CockpitOverviewMonitoringSnapshot.SourceType(
+                        "WATER_SUPPLY_SENSOR", "供水压力计", "WATER_SUPPLY", null, "SMART_DEVICE")),
+                Arrays.asList(
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-UNKNOWN-001", "WATER_SUPPLY_SENSOR", null),
+                        new CockpitOverviewMonitoringSnapshot.SourceDevice("WS-UNKNOWN-002", "WATER_SUPPLY_SENSOR", "UNKNOWN")),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                0);
+    }
+}

+ 272 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderReadControllerTest.java

@@ -0,0 +1,272 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.workorder.CockpitWorkOrderEventAssociation;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadAdapter;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadSnapshot;
+import com.zksy.cockpit.workorder.CockpitWorkOrderState;
+import com.zksy.cockpit.workorder.CockpitWorkOrderStateDictionary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderSummary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineEntry;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineSnapshot;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.hamcrest.Matchers.hasSize;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitWorkOrderReadControllerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+
+    private CockpitWorkOrderReadAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitWorkOrderReadAdapter.class);
+        CockpitWorkOrderReadService service = new CockpitWorkOrderReadService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitWorkOrderReadController(service))
+                .build();
+    }
+
+    @Test
+    void deviceWorkOrdersReturnSevenStateDictionary() throws Exception {
+        when(adapter.loadByDevice(DEVICE_CODE)).thenReturn(sevenStateFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/work-orders")
+                        .header("X-Request-Id", "work-order-device-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("work-order-device-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.stateDictionary", hasSize(7)))
+                .andExpect(jsonPath("$.data.stateDictionary[0].code").value(1))
+                .andExpect(jsonPath("$.data.stateDictionary[0].name").value("待派单"))
+                .andExpect(jsonPath("$.data.stateDictionary[5].code").value(6))
+                .andExpect(jsonPath("$.data.stateDictionary[5].name").value("已结案"))
+                .andExpect(jsonPath("$.data.stateDictionary[6].code").value(7))
+                .andExpect(jsonPath("$.data.stateDictionary[6].name").value("已取消"))
+                .andExpect(jsonPath("$.data.stateDictionary[0].legacyCode").doesNotExist())
+                .andExpect(jsonPath("$.data.stateDictionary[0].deprecated").doesNotExist())
+                .andExpect(jsonPath("$.data.workOrders", hasSize(7)))
+                .andExpect(jsonPath("$.data.workOrders[0].stateCode").value(1))
+                .andExpect(jsonPath("$.data.workOrders[0].stateName").value("待派单"))
+                .andExpect(jsonPath("$.data.workOrders[6].stateCode").value(7))
+                .andExpect(jsonPath("$.data.workOrders[6].stateName").value("已取消"))
+                .andExpect(jsonPath("$.data.workOrders[0].legacyState").doesNotExist())
+                .andExpect(jsonPath("$.data.workOrders[0].deprecatedState").doesNotExist());
+    }
+
+    @Test
+    void eventWorkOrdersPreserveAssociationsAndSeparateEventFamilies() throws Exception {
+        when(adapter.loadByEvent("ALARM", "ALM-20260902-001")).thenReturn(singleAlarmFixture());
+        when(adapter.loadByEvent("WARNING", "WRN-20260902-001")).thenReturn(singleWarningFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/events/ALARM/ALM-20260902-001/work-orders")
+                        .header("X-Request-Id", "work-order-alarm-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.eventSource").value("ALARM"))
+                .andExpect(jsonPath("$.data.eventCode").value("ALM-20260902-001"))
+                .andExpect(jsonPath("$.data.workOrders", hasSize(1)))
+                .andExpect(jsonPath("$.data.workOrders[0].eventAssociation.eventSource").value("ALARM"))
+                .andExpect(jsonPath("$.data.workOrders[0].eventAssociation.eventCode").value("ALM-20260902-001"));
+
+        mockMvc.perform(get("/api/cockpit/v1/events/WARNING/WRN-20260902-001/work-orders")
+                        .header("X-Request-Id", "work-order-warning-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.eventSource").value("WARNING"))
+                .andExpect(jsonPath("$.data.eventCode").value("WRN-20260902-001"))
+                .andExpect(jsonPath("$.data.workOrders", hasSize(1)))
+                .andExpect(jsonPath("$.data.workOrders[0].eventAssociation.eventSource").value("WARNING"))
+                .andExpect(jsonPath("$.data.workOrders[0].eventAssociation.eventCode").value("WRN-20260902-001"));
+    }
+
+    @Test
+    void sameDeviceDifferentAlarmTypesCanHaveSeparateWorkOrders() throws Exception {
+        when(adapter.loadByDevice(DEVICE_CODE)).thenReturn(new CockpitWorkOrderReadSnapshot(
+                DEVICE_CODE,
+                null,
+                null,
+                Arrays.asList(
+                        summary("WO-2026090200101", 4, "ALM-WS_ENV_HIGH-001"),
+                        summary("WO-2026090200102", 5, "ALM-WS_ENV_PH-002"))));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/work-orders"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.workOrders", hasSize(2)))
+                .andExpect(jsonPath("$.data.workOrders[0].eventAssociation.eventCode").value("ALM-WS_ENV_HIGH-001"))
+                .andExpect(jsonPath("$.data.workOrders[1].eventAssociation.eventCode").value("ALM-WS_ENV_PH-002"));
+    }
+
+    @Test
+    void timelinesAreIndependentBetweenWorkOrders() throws Exception {
+        when(adapter.loadTimeline("WO-2026090200001")).thenReturn(timelineFixture("WO-2026090200001", "3"));
+        when(adapter.loadTimeline("WO-2026090200002")).thenReturn(timelineFixture("WO-2026090200002", "6"));
+
+        mockMvc.perform(get("/api/cockpit/v1/work-orders/WO-2026090200001/timeline")
+                        .header("X-Request-Id", "timeline-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.requestId").value("timeline-001"))
+                .andExpect(jsonPath("$.data.workOrderCode").value("WO-2026090200001"))
+                .andExpect(jsonPath("$.data.stateDictionary", hasSize(7)))
+                .andExpect(jsonPath("$.data.timelineEntries", hasSize(3)))
+                .andExpect(jsonPath("$.data.timelineEntries[0].workOrderCode").value("WO-2026090200001"))
+                .andExpect(jsonPath("$.data.timelineEntries[0].stateCode").value(1))
+                .andExpect(jsonPath("$.data.timelineEntries[0].stateName").value("待派单"))
+                .andExpect(jsonPath("$.data.timelineEntries[2].stateCode").value(3))
+                .andExpect(jsonPath("$.data.timelineEntries[2].stateName").value("已接单"))
+                .andExpect(jsonPath("$.data.timelineEntries[0].legacyState").doesNotExist());
+
+        mockMvc.perform(get("/api/cockpit/v1/work-orders/WO-2026090200002/timeline")
+                        .header("X-Request-Id", "timeline-002"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.workOrderCode").value("WO-2026090200002"))
+                .andExpect(jsonPath("$.data.timelineEntries", hasSize(1)))
+                .andExpect(jsonPath("$.data.timelineEntries[0].workOrderCode").value("WO-2026090200002"))
+                .andExpect(jsonPath("$.data.timelineEntries[0].stateCode").value(6))
+                .andExpect(jsonPath("$.data.timelineEntries[0].stateName").value("已结案"));
+    }
+
+    @Test
+    void emptyDeviceWorkOrdersReturnSuccessfulEmptyState() throws Exception {
+        when(adapter.loadByDevice(DEVICE_CODE)).thenReturn(new CockpitWorkOrderReadSnapshot(
+                DEVICE_CODE, null, null, Collections.emptyList()));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/work-orders"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.stateReason").value("NO_WORK_ORDERS"))
+                .andExpect(jsonPath("$.data.workOrders", hasSize(0)));
+    }
+
+    @Test
+    void missingDeviceAndAdapterFailureUseTypedReadOnlyErrors() throws Exception {
+        when(adapter.loadByDevice("MISSING")).thenThrow(new CockpitDeviceNotFoundException("device not found"));
+        when(adapter.loadByDevice("BROKEN")).thenThrow(new CockpitReadException("read failed"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/MISSING/work-orders"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.data.category").value("NOT_FOUND"));
+        mockMvc.perform(get("/api/cockpit/v1/equipments/BROKEN/work-orders"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"));
+    }
+
+    @Test
+    void controllerExposesReadOnlyMappedMethodsOnly() throws Exception {
+        Method[] methods = CockpitWorkOrderReadController.class.getDeclaredMethods();
+        for (Method method : methods) {
+            if (method.isAnnotationPresent(org.springframework.web.bind.annotation.GetMapping.class)) {
+                assertTrue(!method.isAnnotationPresent(org.springframework.web.bind.annotation.PostMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PutMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.PatchMapping.class)
+                        && !method.isAnnotationPresent(org.springframework.web.bind.annotation.DeleteMapping.class));
+            }
+        }
+
+        mockMvc.perform(post("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/work-orders"))
+                .andExpect(status().isMethodNotAllowed());
+        verifyNoInteractions(adapter);
+    }
+
+    private void assertTrue(boolean condition) {
+        org.junit.jupiter.api.Assertions.assertTrue(condition);
+    }
+
+    private CockpitWorkOrderReadSnapshot sevenStateFixture() {
+        List<CockpitWorkOrderSummary> summaries = new java.util.ArrayList<>();
+        for (int state = 1; state <= 7; state++) {
+            summaries.add(summary("WO-202609020000" + state, state, "ALM-20260902-00" + state));
+        }
+        return new CockpitWorkOrderReadSnapshot(DEVICE_CODE, null, null, summaries);
+    }
+
+    private CockpitWorkOrderReadSnapshot singleAlarmFixture() {
+        return new CockpitWorkOrderReadSnapshot(
+                DEVICE_CODE,
+                "ALARM",
+                "ALM-20260902-001",
+                Collections.singletonList(summary("WO-2026090200001", 1, "ALM-20260902-001")));
+    }
+
+    private CockpitWorkOrderReadSnapshot singleWarningFixture() {
+        return new CockpitWorkOrderReadSnapshot(
+                DEVICE_CODE,
+                "WARNING",
+                "WRN-20260902-001",
+                Collections.singletonList(summary("WO-2026090200002", 2, "WARNING", "WRN-20260902-001")));
+    }
+    private CockpitWorkOrderSummary summary(String workOrderCode, int state, String eventCode) {
+        return summary(workOrderCode, state, "ALARM", eventCode);
+    }
+
+    private CockpitWorkOrderSummary summary(String workOrderCode, int state, String eventSource, String eventCode) {
+        CockpitWorkOrderState stateEntry = CockpitWorkOrderStateDictionary.byLegacyCode(state);
+        return new CockpitWorkOrderSummary(
+                workOrderCode,
+                DEVICE_CODE,
+                1,
+                "故障维修",
+                2,
+                "处理异常",
+                stateEntry.getCode(),
+                stateEntry.getName(),
+                "2026-09-02T09:59:30+08:00",
+                "2026-09-02T10:00:00+08:00",
+                "2026-09-02T09:00:00+08:00",
+                "2026-09-02T09:30:00+08:00",
+                                new CockpitWorkOrderEventAssociation(eventSource, eventCode, "2026-09-02T10:00:00+08:00"));
+    }
+
+    private CockpitWorkOrderTimelineSnapshot timelineFixture(String workOrderCode, String lastState) {
+        int state = Integer.parseInt(lastState);
+        CockpitWorkOrderSummary summary = summary(workOrderCode, state, "ALM-20260902-001");
+        if (state >= 6) {
+            return new CockpitWorkOrderTimelineSnapshot(
+                    summary,
+                    Collections.singletonList(entry(workOrderCode, 6)));
+        }
+        return new CockpitWorkOrderTimelineSnapshot(
+                summary,
+                Arrays.asList(
+                        entry(workOrderCode, 1),
+                        entry(workOrderCode, 2),
+                        entry(workOrderCode, 3)));
+    }
+
+    private CockpitWorkOrderTimelineEntry entry(String workOrderCode, int state) {
+        CockpitWorkOrderState stateEntry = CockpitWorkOrderStateDictionary.byLegacyCode(state);
+        return new CockpitWorkOrderTimelineEntry(
+                (long) state,
+                workOrderCode,
+                stateEntry.getCode(),
+                stateEntry.getName(),
+                "创建",
+                "创建工单",
+                "系统",
+                "2026-09-02T09:00:00+08:00");
+    }
+}

+ 317 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/websocket/DeviceStatusCockpitWebSocketHandlerTest.java

@@ -0,0 +1,317 @@
+package com.zksy.web.websocket;
+
+import com.alibaba.fastjson.JSONObject;
+import com.zksy.base.domain.EquipmentStatus;
+import com.zksy.base.service.EquipmentStatusService;
+import com.zksy.base.service.BusinessWorkOrderService;
+import com.zksy.framework.web.service.TokenService;
+import org.springframework.data.redis.connection.Message;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.socket.CloseStatus;
+import org.springframework.web.socket.TextMessage;
+import org.springframework.web.socket.WebSocketSession;
+
+import java.util.HashMap;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class DeviceStatusCockpitWebSocketHandlerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+
+    private DeviceStatusWebSocketHandler handler;
+    private WebSocketSession session;
+    private EquipmentStatusService equipmentStatusService;
+    private SubscriptionManager subscriptionManager;
+
+    @BeforeEach
+    void setUp() {
+        handler = new DeviceStatusWebSocketHandler();
+        session = mock(WebSocketSession.class);
+        HashMap<String, Object> attributes = new HashMap<>();
+        org.mockito.Mockito.doReturn("ws-session-1").when(session).getId();
+        org.mockito.Mockito.doReturn(true).when(session).isOpen();
+        org.mockito.Mockito.doReturn(attributes).when(session).getAttributes();
+
+        equipmentStatusService = mock(EquipmentStatusService.class);
+        subscriptionManager = new SubscriptionManager();
+        ReflectionTestUtils.setField(handler, "equipmentStatusService", equipmentStatusService);
+        ReflectionTestUtils.setField(handler, "subscriptionManager", subscriptionManager);
+        ReflectionTestUtils.setField(handler, "tokenService", mock(TokenService.class));
+        ReflectionTestUtils.setField(handler, "businessWorkOrderService", mock(BusinessWorkOrderService.class));
+        ReflectionTestUtils.setField(handler, "workOrderMaxItems", 100);
+    }
+
+    @Test
+    void cockpitSubscribeAllReturnsExplicitScopeSubscription() throws Exception {
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        ArgumentCaptor<TextMessage> response = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session).sendMessage(response.capture());
+        JSONObject payload = JSONObject.parseObject(response.getValue().getPayload());
+        assertEquals("cockpitSubscribed", payload.getString("type"));
+        assertEquals("all", payload.getString("scope"));
+        assertTrue(payload.containsKey("serverUpdatedAt"));
+    }
+
+    @Test
+    void cockpitAllScopeReceivesChangedDeviceDelta() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        EquipmentStatus status = new EquipmentStatus();
+        status.setCurrentStatus(1);
+        status.setAlarmStatus(1);
+        status.setOnlineStatus(1);
+        status.setStatusUpdateTime(LocalDateTime.parse("2026-09-02T09:59:50"));
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(status);
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = new DeviceStatusRedisListener();
+        ReflectionTestUtils.setField(listener, "subscriptionManager", subscriptionManager);
+        ReflectionTestUtils.setField(listener, "equipmentStatusService", equipmentStatusService);
+        ReflectionTestUtils.setField(listener, "webSocketHandler", handler);
+        ReflectionTestUtils.setField(listener, "deltaTracker", new DeviceStatusDeltaTracker());
+        listener.onMessage(message("{\"deviceCode\":\"" + DEVICE_CODE + "\","
+                + "\"serverUpdatedAt\":\"2026-09-02T10:00:00+08:00\"}"), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        JSONObject delta = messages.getAllValues().stream()
+                .map(item -> JSONObject.parseObject(item.getPayload()))
+                .filter(item -> "cockpitDeviceStatusDelta".equals(item.getString("type")))
+                .findFirst().orElse(null);
+        assertNotNull(delta);
+        assertEquals(DEVICE_CODE, delta.getString("deviceCode"));
+        assertEquals(DEVICE_CODE, delta.getString("device_code"));
+        assertEquals("ALARM", delta.getJSONObject("data").getString("status"));
+        assertEquals("2026-09-02T09:59:50+08:00", delta.getJSONObject("data").getString("statusTime"));
+        assertEquals("2026-09-02T10:00:00+08:00", delta.getJSONObject("data").getString("serverUpdatedAt"));
+    }
+
+    @Test
+    void existingDeviceCodeSubscriptionStillReceivesLegacyPush() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"subscribe\",\"deviceCodes\":[\"" + DEVICE_CODE + "\"]}"));
+
+        EquipmentStatus status = new EquipmentStatus();
+        status.setCurrentStatus(1);
+        status.setAlarmStatus(1);
+        status.setOnlineStatus(1);
+        status.setStatusUpdateTime(LocalDateTime.parse("2026-09-02T09:59:50"));
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(status);
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message("{\"deviceCode\":\"" + DEVICE_CODE + "\","
+                + "\"serverUpdatedAt\":\"2026-09-02T10:00:00+08:00\"}"), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        JSONObject push = messages.getAllValues().stream()
+                .map(item -> JSONObject.parseObject(item.getPayload()))
+                .filter(item -> "deviceStatusPush".equals(item.getString("type")))
+                .findFirst().orElse(null);
+        assertNotNull(push);
+        assertEquals(DEVICE_CODE, push.getString("deviceCode"));
+        assertEquals(DEVICE_CODE, push.getJSONObject("data").getString("deviceCode"));
+    }
+
+    @Test
+    void cockpitSubscriptionAcceptsLegacyRedisDeviceCodeAlias() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(alarmStatus());
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message("{\"device_code\":\"" + DEVICE_CODE + "\","
+                + "\"serverUpdatedAt\":\"2026-09-02T10:00:00+08:00\"}"), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        JSONObject delta = messages.getAllValues().stream()
+                .map(item -> JSONObject.parseObject(item.getPayload()))
+                .filter(item -> "cockpitDeviceStatusDelta".equals(item.getString("type")))
+                .findFirst().orElse(null);
+        assertNotNull(delta);
+        assertEquals(DEVICE_CODE, delta.getString("deviceCode"));
+    }
+
+    @Test
+    void cockpitAllScopeIgnoresUnchangedDeviceStates() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(alarmStatus());
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:00+08:00")), null);
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:01+08:00")), null);
+
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(ArgumentCaptor.forClass(TextMessage.class).capture());
+    }
+
+    @Test
+    void cockpitAllScopeIgnoresOldOutOfOrderServerUpdates() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(alarmStatus());
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:05+08:00")), null);
+
+        EquipmentStatus recovered = alarmStatus();
+        recovered.setAlarmStatus(0);
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(recovered);
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:00+08:00")), null);
+
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(ArgumentCaptor.forClass(TextMessage.class).capture());
+    }
+
+    @Test
+    void unknownDeviceReturnsExplicitCockpitFallback() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        String unknownCode = "TC-PS-WS-202609099999";
+        when(equipmentStatusService.existsByDeviceCode(unknownCode)).thenReturn(false);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message(event(unknownCode, "2026-09-02T10:00:00+08:00")), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        JSONObject delta = messages.getAllValues().stream()
+                .map(item -> JSONObject.parseObject(item.getPayload()))
+                .filter(item -> "cockpitDeviceStatusDelta".equals(item.getString("type")))
+                .findFirst().orElse(null);
+        assertNotNull(delta);
+        assertEquals(unknownCode, delta.getString("deviceCode"));
+        assertEquals("EMPTY", delta.getJSONObject("data").getString("status"));
+        assertEquals("DEVICE_NOT_FOUND", delta.getJSONObject("data").getString("reason"));
+        assertEquals("2026-09-02T10:00:00+08:00", delta.getJSONObject("data").getString("serverUpdatedAt"));
+    }
+
+    @Test
+    void missingPointStatusReturnsExplicitNoStatusFallback() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(null);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:00+08:00")), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        JSONObject delta = messages.getAllValues().stream()
+                .map(item -> JSONObject.parseObject(item.getPayload()))
+                .filter(item -> "cockpitDeviceStatusDelta".equals(item.getString("type")))
+                .findFirst().orElse(null);
+        assertNotNull(delta);
+        assertEquals("EMPTY", delta.getJSONObject("data").getString("status"));
+        assertEquals("NO_STATUS", delta.getJSONObject("data").getString("reason"));
+    }
+
+    @Test
+    void pingAnswersWithPong() throws Exception {
+        handler.handleTextMessage(session, new TextMessage("{\"type\":\"ping\"}"));
+
+        ArgumentCaptor<TextMessage> response = ArgumentCaptor.forClass(TextMessage.class);
+        verify(session).sendMessage(response.capture());
+        JSONObject payload = JSONObject.parseObject(response.getValue().getPayload());
+        assertEquals("pong", payload.getString("type"));
+        assertTrue(payload.getLongValue("timestamp") > 0);
+    }
+
+    @Test
+    void disconnectCleansUpSubscriptionAndReconnectRecoversIt() throws Exception {
+        handler.afterConnectionEstablished(session);
+        handler.handleTextMessage(session, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+        handler.afterConnectionClosed(session, CloseStatus.NORMAL);
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(alarmStatus());
+        when(equipmentStatusService.existsByDeviceCode(DEVICE_CODE)).thenReturn(true);
+        DeviceStatusRedisListener listener = newListener();
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:00+08:00")), null);
+
+        WebSocketSession reconnected = mock(WebSocketSession.class);
+        HashMap<String, Object> attributes = new HashMap<>();
+        org.mockito.Mockito.doReturn("ws-session-2").when(reconnected).getId();
+        org.mockito.Mockito.doReturn(true).when(reconnected).isOpen();
+        org.mockito.Mockito.doReturn(attributes).when(reconnected).getAttributes();
+        handler.afterConnectionEstablished(reconnected);
+        handler.handleTextMessage(reconnected, new TextMessage(
+                "{\"type\":\"cockpitSubscribe\",\"scope\":\"all\"}"));
+
+        when(equipmentStatusService.getByDeviceCode(DEVICE_CODE)).thenReturn(recoveredNormal());
+        listener.onMessage(message(event(DEVICE_CODE, "2026-09-02T10:00:01+08:00")), null);
+
+        ArgumentCaptor<TextMessage> messages = ArgumentCaptor.forClass(TextMessage.class);
+        verify(reconnected, org.mockito.Mockito.times(2)).sendMessage(messages.capture());
+        long deltas = messages.getAllValues().stream()
+                .filter(item -> JSONObject.parseObject(item.getPayload()).getString("type")
+                        .equals("cockpitDeviceStatusDelta"))
+                .count();
+        assertEquals(1, deltas);
+    }
+
+    private static Message message(String payload) {
+        return new Message() {
+            @Override
+            public byte[] getBody() {
+                return payload.getBytes(StandardCharsets.UTF_8);
+            }
+
+            @Override
+            public byte[] getChannel() {
+                return DeviceStatusRedisListener.CHANNEL.getBytes(StandardCharsets.UTF_8);
+            }
+        };
+    }
+
+    private DeviceStatusRedisListener newListener() {
+        DeviceStatusRedisListener listener = new DeviceStatusRedisListener();
+        ReflectionTestUtils.setField(listener, "subscriptionManager", subscriptionManager);
+        ReflectionTestUtils.setField(listener, "equipmentStatusService", equipmentStatusService);
+        ReflectionTestUtils.setField(listener, "webSocketHandler", handler);
+        ReflectionTestUtils.setField(listener, "deltaTracker", new DeviceStatusDeltaTracker());
+        return listener;
+    }
+
+    private static String event(String deviceCode, String serverUpdatedAt) {
+        return "{\"deviceCode\":\"" + deviceCode + "\",\"serverUpdatedAt\":\"" + serverUpdatedAt + "\"}";
+    }
+
+    private EquipmentStatus alarmStatus() {
+        EquipmentStatus status = new EquipmentStatus();
+        status.setCurrentStatus(1);
+        status.setAlarmStatus(1);
+        status.setOnlineStatus(1);
+        status.setStatusUpdateTime(LocalDateTime.parse("2026-09-02T09:59:50"));
+        return status;
+    }
+
+    private EquipmentStatus recoveredNormal() {
+        EquipmentStatus status = alarmStatus();
+        status.setAlarmStatus(0);
+        return status;
+    }
+}

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/event/DeviceStatusChangePublisher.java

@@ -10,6 +10,9 @@ import org.springframework.transaction.support.TransactionSynchronization;
 import org.springframework.transaction.support.TransactionSynchronizationManager;
 
 import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.UUID;
@@ -67,6 +70,8 @@ public class DeviceStatusChangePublisher {
         event.put("onlineStatus", onlineStatus);
         event.put("source", source);
         event.put("changedAt", LocalDateTime.now().toString());
+        event.put("serverUpdatedAt", DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
+                OffsetDateTime.now(ZoneOffset.ofHours(8))));
         try {
             redisTemplate.convertAndSend(CHANNEL, objectMapper.writeValueAsString(event));
             log.info("设备状态变更事件已发布: deviceCode={}, equipmentId={}, source={}",

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/EquipmentStatusService.java

@@ -49,4 +49,9 @@ public interface EquipmentStatusService extends IService<EquipmentStatus> {
      * @return 设备状态,未找到返回 null
      */
     EquipmentStatus getByDeviceCode(String deviceCode);
+
+    /**
+     * 判断设备编码对应的智能设备是否存在。
+     */
+    boolean existsByDeviceCode(String deviceCode);
 }

+ 10 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentStatusServiceImpl.java

@@ -294,6 +294,16 @@ public class EquipmentStatusServiceImpl extends ServiceImpl<EquipmentStatusMappe
         return status;
     }
 
+    @Override
+    public boolean existsByDeviceCode(String deviceCode) {
+        if (deviceCode == null || deviceCode.isEmpty()) {
+            return false;
+        }
+        LambdaQueryWrapper<EquipmentBase> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(EquipmentBase::getEquipmentCode, deviceCode);
+        return equipmentBaseMapper.selectCount(wrapper) > 0;
+    }
+
     private boolean hasStateChange(EquipmentStatus oldStatus, EquipmentStatus patch) {
         if (oldStatus == null || patch == null) {
             return false;

+ 75 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitEquipmentDetailAggregateResponse.java

@@ -0,0 +1,75 @@
+package com.zksy.cockpit.detail;
+
+import com.zksy.cockpit.equipment.CockpitEquipmentArchive;
+import com.zksy.cockpit.equipment.CockpitEquipmentImage;
+import com.zksy.cockpit.event.CockpitAlarmWarningRelation;
+import com.zksy.cockpit.event.CockpitEventAlarm;
+import com.zksy.cockpit.event.CockpitEventWarning;
+import com.zksy.cockpit.type.CockpitTypeMetricsResponse;
+import com.zksy.cockpit.workorder.CockpitWorkOrderSummary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineResponse;
+
+import java.util.List;
+
+public class CockpitEquipmentDetailAggregateResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String deviceCode;
+    private final String aggregateState;
+    private final String serverTime;
+    private final CockpitSectionResult<CockpitEquipmentArchive> archive;
+    private final CockpitSectionResult<CockpitTypeMetricsResponse> metrics;
+    private final CockpitSectionResult<java.util.List<CockpitEventWarning>> warnings;
+    private final CockpitSectionResult<java.util.List<CockpitEventAlarm>> alarms;
+    private final CockpitSectionResult<java.util.List<CockpitAlarmWarningRelation>> alarmWarningRelations;
+    private final CockpitSectionResult<java.util.List<CockpitWorkOrderSummary>> workOrders;
+    private final CockpitSectionResult<java.util.List<CockpitWorkOrderTimelineResponse>> timelines;
+    private final CockpitSectionResult<CockpitEquipmentImage> latestImage;
+
+    public CockpitEquipmentDetailAggregateResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String deviceCode,
+            String aggregateState,
+            String serverTime,
+            CockpitSectionResult<CockpitEquipmentArchive> archive,
+            CockpitSectionResult<CockpitTypeMetricsResponse> metrics,
+            CockpitSectionResult<java.util.List<CockpitEventWarning>> warnings,
+            CockpitSectionResult<java.util.List<CockpitEventAlarm>> alarms,
+            CockpitSectionResult<java.util.List<CockpitAlarmWarningRelation>> alarmWarningRelations,
+            CockpitSectionResult<java.util.List<CockpitWorkOrderSummary>> workOrders,
+            CockpitSectionResult<java.util.List<CockpitWorkOrderTimelineResponse>> timelines,
+            CockpitSectionResult<CockpitEquipmentImage> latestImage) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.deviceCode = deviceCode;
+        this.aggregateState = aggregateState;
+        this.serverTime = serverTime;
+        this.archive = archive;
+        this.metrics = metrics;
+        this.warnings = warnings;
+        this.alarms = alarms;
+        this.alarmWarningRelations = alarmWarningRelations;
+        this.workOrders = workOrders;
+        this.timelines = timelines;
+        this.latestImage = latestImage;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getAggregateState() { return aggregateState; }
+    public String getServerTime() { return serverTime; }
+    public CockpitSectionResult<CockpitEquipmentArchive> getArchive() { return archive; }
+    public CockpitSectionResult<CockpitTypeMetricsResponse> getMetrics() { return metrics; }
+    public CockpitSectionResult<java.util.List<CockpitEventWarning>> getWarnings() { return warnings; }
+    public CockpitSectionResult<java.util.List<CockpitEventAlarm>> getAlarms() { return alarms; }
+    public CockpitSectionResult<java.util.List<CockpitAlarmWarningRelation>> getAlarmWarningRelations() { return alarmWarningRelations; }
+    public CockpitSectionResult<java.util.List<CockpitWorkOrderSummary>> getWorkOrders() { return workOrders; }
+    public CockpitSectionResult<java.util.List<CockpitWorkOrderTimelineResponse>> getTimelines() { return timelines; }
+    public CockpitSectionResult<CockpitEquipmentImage> getLatestImage() { return latestImage; }
+}

+ 312 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitEquipmentDetailAggregateService.java

@@ -0,0 +1,312 @@
+package com.zksy.cockpit.detail;
+
+import com.zksy.cockpit.equipment.CockpitEquipmentArchive;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveResponse;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveService;
+import com.zksy.cockpit.equipment.CockpitEquipmentImage;
+import com.zksy.cockpit.event.CockpitAlarmWarningRelation;
+import com.zksy.cockpit.event.CockpitEventAlarm;
+import com.zksy.cockpit.event.CockpitEventReadResponse;
+import com.zksy.cockpit.event.CockpitEventReadService;
+import com.zksy.cockpit.event.CockpitEventWarning;
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.type.CockpitTypeMetricsResponse;
+import com.zksy.cockpit.type.CockpitTypeMetricsService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadResponse;
+import com.zksy.cockpit.workorder.CockpitWorkOrderReadService;
+import com.zksy.cockpit.workorder.CockpitWorkOrderSummary;
+import com.zksy.cockpit.workorder.CockpitWorkOrderTimelineResponse;
+import org.springframework.stereotype.Service;
+
+import java.time.Clock;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@Service
+public class CockpitEquipmentDetailAggregateService {
+    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+
+    private final CockpitEquipmentArchiveService archiveService;
+    private final CockpitTypeMetricsService metricsService;
+    private final CockpitEventReadService eventService;
+    private final CockpitWorkOrderReadService workOrderService;
+    private final Clock clock;
+
+    public CockpitEquipmentDetailAggregateService(
+            CockpitEquipmentArchiveService archiveService,
+            CockpitTypeMetricsService metricsService,
+            CockpitEventReadService eventService,
+            CockpitWorkOrderReadService workOrderService,
+            Clock clock) {
+        this.archiveService = archiveService;
+        this.metricsService = metricsService;
+        this.eventService = eventService;
+        this.workOrderService = workOrderService;
+        this.clock = clock;
+    }
+
+    public CockpitEquipmentDetailAggregateResponse loadAggregate(String requestId, String deviceCode) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+        String normalizedDeviceCode = deviceCode.trim();
+        CockpitSectionResult<CockpitEquipmentArchive> archive = loadArchive(requestId, normalizedDeviceCode);
+        CockpitSectionResult<CockpitTypeMetricsResponse> metrics = loadMetrics(requestId, normalizedDeviceCode);
+        CockpitEventSection eventSection = loadEventSection(requestId, normalizedDeviceCode);
+        CockpitSectionResult<List<CockpitEventWarning>> warnings = warningsFrom(eventSection);
+        CockpitSectionResult<List<CockpitEventAlarm>> alarms = alarmsFrom(eventSection);
+        CockpitSectionResult<List<CockpitAlarmWarningRelation>> relations = relationsFrom(eventSection);
+        CockpitSectionResult<List<CockpitWorkOrderSummary>> workOrders =
+                loadWorkOrders(requestId, normalizedDeviceCode);
+        CockpitSectionResult<List<CockpitWorkOrderTimelineResponse>> timelines =
+                loadTimelines(requestId, workOrders);
+        CockpitSectionResult<CockpitEquipmentImage> latestImage = loadLatestImage(archive);
+
+        return new CockpitEquipmentDetailAggregateResponse(
+                requestId,
+                "v1",
+                true,
+                normalizedDeviceCode,
+                aggregateState(archive, metrics, warnings, alarms, relations, workOrders, timelines, latestImage),
+                serverTime(),
+                archive,
+                metrics,
+                warnings,
+                alarms,
+                relations,
+                workOrders,
+                timelines,
+                latestImage);
+    }
+
+    private CockpitSectionResult<CockpitEquipmentArchive> loadArchive(String requestId, String deviceCode) {
+        try {
+            CockpitEquipmentArchiveResponse response = archiveService.load(requestId, deviceCode);
+            CockpitEquipmentArchive archive = response == null ? null : response.getArchive();
+            if (isEmptyArchive(archive)) {
+                return CockpitSectionResult.empty("NO_ARCHIVE");
+            }
+            if (!Objects.equals(deviceCode, archive.getDeviceCode())) {
+                return CockpitSectionResult.failure("DEVICE_CODE_MISMATCH", "设备档案编码不匹配");
+            }
+            return CockpitSectionResult.success(archive);
+        } catch (CockpitDeviceNotFoundException exception) {
+            return CockpitSectionResult.failure("NOT_FOUND", "设备档案不存在");
+        } catch (CockpitReadException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "设备档案数据暂不可用");
+        } catch (RuntimeException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "设备档案数据暂不可用");
+        }
+    }
+
+    private CockpitSectionResult<CockpitTypeMetricsResponse> loadMetrics(String requestId, String deviceCode) {
+        try {
+            CockpitTypeMetricsResponse response = metricsService.loadCurrent(requestId, deviceCode);
+            if (response == null) {
+                return CockpitSectionResult.empty("NO_METRICS");
+            }
+            if (!Objects.equals(deviceCode, response.getDeviceCode())) {
+                return CockpitSectionResult.failure("DEVICE_CODE_MISMATCH", "设备指标编码不匹配");
+            }
+            if ("EMPTY".equals(response.getState())) {
+                return CockpitSectionResult.empty("NO_METRICS");
+            }
+            if ("STALE".equals(response.getState())) {
+                return CockpitSectionResult.stale(response.getStateReason(), response);
+            }
+            return CockpitSectionResult.success(response);
+        } catch (CockpitDeviceNotFoundException exception) {
+            return CockpitSectionResult.failure("NOT_FOUND", "设备指标不存在");
+        } catch (CockpitReadException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "设备指标数据暂不可用");
+        } catch (RuntimeException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "设备指标数据暂不可用");
+        }
+    }
+
+    private CockpitSectionResult<List<CockpitEventWarning>> warningsFrom(CockpitEventSection eventSection) {
+        if (eventSection.result.getState() == CockpitSectionState.FAILED) {
+            return CockpitSectionResult.failure(eventSection.result.getReason(), eventSection.result.getMessage());
+        }
+        if (eventSection.result.getState() == CockpitSectionState.EMPTY) {
+            return CockpitSectionResult.empty(eventSection.result.getReason());
+        }
+        return CockpitSectionResult.success(safeList(eventSection.response.getWarnings()));
+    }
+
+    private CockpitSectionResult<List<CockpitEventAlarm>> alarmsFrom(CockpitEventSection eventSection) {
+        if (eventSection.result.getState() == CockpitSectionState.FAILED) {
+            return CockpitSectionResult.failure(eventSection.result.getReason(), eventSection.result.getMessage());
+        }
+        if (eventSection.result.getState() == CockpitSectionState.EMPTY) {
+            return CockpitSectionResult.empty(eventSection.result.getReason());
+        }
+        return CockpitSectionResult.success(safeList(eventSection.response.getAlarms()));
+    }
+
+    private CockpitSectionResult<List<CockpitAlarmWarningRelation>> relationsFrom(CockpitEventSection eventSection) {
+        if (eventSection.result.getState() == CockpitSectionState.FAILED) {
+            return CockpitSectionResult.failure(eventSection.result.getReason(), eventSection.result.getMessage());
+        }
+        if (eventSection.result.getState() == CockpitSectionState.EMPTY) {
+            return CockpitSectionResult.empty(eventSection.result.getReason());
+        }
+        return CockpitSectionResult.success(safeList(eventSection.response.getAlarmWarningRelations()));
+    }
+
+    private CockpitEventSection loadEventSection(String requestId, String deviceCode) {
+        try {
+            CockpitEventReadResponse response = eventService.loadCurrent(requestId, deviceCode);
+            if (response == null) {
+                return new CockpitEventSection(CockpitSectionResult.empty("NO_EVENTS"), null);
+            }
+            if (!Objects.equals(deviceCode, response.getDeviceCode())) {
+                return new CockpitEventSection(
+                        CockpitSectionResult.failure("DEVICE_CODE_MISMATCH", "事件设备编码不匹配"), response);
+            }
+            if ("EMPTY".equals(response.getState())) {
+                return new CockpitEventSection(CockpitSectionResult.empty("NO_EVENTS"), response);
+            }
+            if ("STALE".equals(response.getState())) {
+                return new CockpitEventSection(CockpitSectionResult.stale(response.getStateReason(), response), response);
+            }
+            return new CockpitEventSection(CockpitSectionResult.success(response), response);
+        } catch (CockpitDeviceNotFoundException exception) {
+            return new CockpitEventSection(CockpitSectionResult.failure("NOT_FOUND", "事件数据不存在"), null);
+        } catch (CockpitReadException exception) {
+            return new CockpitEventSection(CockpitSectionResult.failure("READ_FAILURE", "事件数据暂不可用"), null);
+        } catch (RuntimeException exception) {
+            return new CockpitEventSection(CockpitSectionResult.failure("READ_FAILURE", "事件数据暂不可用"), null);
+        }
+    }
+
+    private CockpitSectionResult<List<CockpitWorkOrderSummary>> loadWorkOrders(String requestId, String deviceCode) {
+        try {
+            CockpitWorkOrderReadResponse response = workOrderService.loadByDevice(requestId, deviceCode);
+            if (response == null) {
+                return CockpitSectionResult.empty("NO_WORK_ORDERS");
+            }
+            if (!Objects.equals(deviceCode, response.getDeviceCode())) {
+                return CockpitSectionResult.failure("DEVICE_CODE_MISMATCH", "工单设备编码不匹配");
+            }
+            if ("EMPTY".equals(response.getState())) {
+                return CockpitSectionResult.empty("NO_WORK_ORDERS");
+            }
+            return CockpitSectionResult.success(safeList(response.getWorkOrders()));
+        } catch (CockpitDeviceNotFoundException exception) {
+            return CockpitSectionResult.failure("NOT_FOUND", "工单数据不存在");
+        } catch (CockpitReadException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "工单数据暂不可用");
+        } catch (RuntimeException exception) {
+            return CockpitSectionResult.failure("READ_FAILURE", "工单数据暂不可用");
+        }
+    }
+
+    private CockpitSectionResult<List<CockpitWorkOrderTimelineResponse>> loadTimelines(
+            String requestId,
+            CockpitSectionResult<List<CockpitWorkOrderSummary>> workOrders) {
+        if (workOrders.getState() == CockpitSectionState.FAILED) {
+            return CockpitSectionResult.failure("SOURCE_SECTION_FAILED", "工单分区失败,时间线不可用");
+        }
+        if (workOrders.getState() == CockpitSectionState.EMPTY || workOrders.getData().isEmpty()) {
+            return CockpitSectionResult.empty("NO_WORK_ORDERS");
+        }
+
+        List<CockpitWorkOrderTimelineResponse> timelines = new ArrayList<>();
+        boolean failed = false;
+        boolean hasData = false;
+        for (CockpitWorkOrderSummary summary : workOrders.getData()) {
+            try {
+                CockpitWorkOrderTimelineResponse response =
+                        workOrderService.loadTimeline(requestId, summary.getWorkOrderCode());
+                if (response != null) {
+                    timelines.add(response);
+                    hasData = true;
+                }
+            } catch (RuntimeException exception) {
+                failed = true;
+            }
+        }
+        if (failed) {
+            return new CockpitSectionResult<>(
+                    CockpitSectionState.FAILED, "TIMELINE_FAILURE", "部分工单时间线不可用", hasData ? timelines : null);
+        }
+        if (!hasData) {
+            return CockpitSectionResult.empty("NO_TIMELINES");
+        }
+        return CockpitSectionResult.success(timelines);
+    }
+
+    private CockpitSectionResult<CockpitEquipmentImage> loadLatestImage(
+            CockpitSectionResult<CockpitEquipmentArchive> archive) {
+        if (archive.getState() == CockpitSectionState.FAILED) {
+            return CockpitSectionResult.failure("SOURCE_SECTION_FAILED", "设备档案失败,图片不可用");
+        }
+        CockpitEquipmentImage image = archive.getData() == null ? null : archive.getData().getLatestImage();
+        return image == null ? CockpitSectionResult.empty("NO_IMAGE") : CockpitSectionResult.success(image);
+    }
+
+    private String aggregateState(
+            CockpitSectionResult<?> archive,
+            CockpitSectionResult<?> metrics,
+            CockpitSectionResult<?> warnings,
+            CockpitSectionResult<?> alarms,
+            CockpitSectionResult<?> relations,
+            CockpitSectionResult<?> workOrders,
+            CockpitSectionResult<?> timelines,
+            CockpitSectionResult<?> latestImage) {
+        List<CockpitSectionResult<?>> sections = List.of(
+                archive, metrics, warnings, alarms, relations, workOrders, timelines, latestImage);
+        long failed = sections.stream().filter(section -> section.getState() == CockpitSectionState.FAILED).count();
+        boolean anySuccess = sections.stream().anyMatch(section -> section.getState() == CockpitSectionState.SUCCESS);
+        boolean anyStale = sections.stream().anyMatch(section -> section.getState() == CockpitSectionState.STALE);
+        boolean allEmpty = sections.stream().allMatch(section -> section.getState() == CockpitSectionState.EMPTY);
+        if (failed == sections.size()) {
+            return "FAILED";
+        }
+        if (allEmpty) {
+            return "EMPTY";
+        }
+        if (failed > 0 || anyStale) {
+            return "PARTIAL";
+        }
+        return anySuccess ? "READY" : "EMPTY";
+    }
+
+    private boolean isEmptyArchive(CockpitEquipmentArchive archive) {
+        return archive == null || (
+                isBlank(archive.getDeviceName())
+                        && isBlank(archive.getDeviceModel())
+                        && isBlank(archive.getManufacturer())
+                        && isBlank(archive.getDeviceTypeName()));
+    }
+
+    private <T> List<T> safeList(List<T> values) {
+        return values == null ? List.of() : values;
+    }
+
+    private String serverTime() {
+        return TIME_FORMATTER.format(clock.instant().atZone(ZoneId.of("Asia/Shanghai")));
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    private static final class CockpitEventSection {
+        private final CockpitSectionResult<CockpitEventReadResponse> result;
+        private final CockpitEventReadResponse response;
+
+        private CockpitEventSection(
+                CockpitSectionResult<CockpitEventReadResponse> result,
+                CockpitEventReadResponse response) {
+            this.result = result;
+            this.response = response;
+        }
+    }
+}

+ 36 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitSectionResult.java

@@ -0,0 +1,36 @@
+package com.zksy.cockpit.detail;
+
+public class CockpitSectionResult<T> {
+    private final CockpitSectionState state;
+    private final String reason;
+    private final String message;
+    private final T data;
+
+    CockpitSectionResult(CockpitSectionState state, String reason, String message, T data) {
+        this.state = state;
+        this.reason = reason;
+        this.message = message;
+        this.data = data;
+    }
+
+    public static <T> CockpitSectionResult<T> success(T data) {
+        return new CockpitSectionResult<>(CockpitSectionState.SUCCESS, "SUCCESS", null, data);
+    }
+
+    public static <T> CockpitSectionResult<T> empty(String reason) {
+        return new CockpitSectionResult<>(CockpitSectionState.EMPTY, reason, null, null);
+    }
+
+    public static <T> CockpitSectionResult<T> stale(String reason, T data) {
+        return new CockpitSectionResult<>(CockpitSectionState.STALE, reason, null, data);
+    }
+
+    public static <T> CockpitSectionResult<T> failure(String reason, String message) {
+        return new CockpitSectionResult<>(CockpitSectionState.FAILED, reason, message, null);
+    }
+
+    public CockpitSectionState getState() { return state; }
+    public String getReason() { return reason; }
+    public String getMessage() { return message; }
+    public T getData() { return data; }
+}

+ 8 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/detail/CockpitSectionState.java

@@ -0,0 +1,8 @@
+package com.zksy.cockpit.detail;
+
+public enum CockpitSectionState {
+    SUCCESS,
+    EMPTY,
+    STALE,
+    FAILED
+}

+ 1 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveResponse.java

@@ -37,4 +37,5 @@ public class CockpitEquipmentArchiveResponse {
     public String getOwnershipUnit() { return archive.getOwnershipUnit(); }
     public String getRemark() { return archive.getRemark(); }
     public CockpitEquipmentImage getLatestImage() { return archive.getLatestImage(); }
+    public CockpitEquipmentArchive getArchive() { return archive; }
 }

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessAdapter.java

@@ -0,0 +1,5 @@
+package com.zksy.cockpit.foundation;
+
+public interface CockpitFreshnessAdapter {
+    CockpitFreshnessSource load(String deviceCode);
+}

+ 68 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessResponse.java

@@ -0,0 +1,68 @@
+package com.zksy.cockpit.foundation;
+
+public class CockpitFreshnessResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String deviceCode;
+    private final String updatedAt;
+    private final String statusTime;
+    private final String serverUpdatedAt;
+    private final CockpitFreshnessStatus freshness;
+    private final String staleReason;
+    private final int calibrationPeriodSeconds;
+    private final int missedCycles;
+    private final long dataAgeSeconds;
+    private final boolean retained;
+    private final String message;
+    private final CockpitFreshnessSection section;
+
+    public CockpitFreshnessResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String deviceCode,
+            String updatedAt,
+            String statusTime,
+            String serverUpdatedAt,
+            CockpitFreshnessStatus freshness,
+            String staleReason,
+            int calibrationPeriodSeconds,
+            int missedCycles,
+            long dataAgeSeconds,
+            boolean retained,
+            String message,
+            CockpitFreshnessSection section) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.deviceCode = deviceCode;
+        this.updatedAt = updatedAt;
+        this.statusTime = statusTime;
+        this.serverUpdatedAt = serverUpdatedAt;
+        this.freshness = freshness;
+        this.staleReason = staleReason;
+        this.calibrationPeriodSeconds = calibrationPeriodSeconds;
+        this.missedCycles = missedCycles;
+        this.dataAgeSeconds = dataAgeSeconds;
+        this.retained = retained;
+        this.message = message;
+        this.section = section;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getUpdatedAt() { return updatedAt; }
+    public String getStatusTime() { return statusTime; }
+    public String getServerUpdatedAt() { return serverUpdatedAt; }
+    public CockpitFreshnessStatus getFreshness() { return freshness; }
+    public String getStaleReason() { return staleReason; }
+    public int getCalibrationPeriodSeconds() { return calibrationPeriodSeconds; }
+    public int getMissedCycles() { return missedCycles; }
+    public long getDataAgeSeconds() { return dataAgeSeconds; }
+    public boolean isRetained() { return retained; }
+    public String getMessage() { return message; }
+    public CockpitFreshnessSection getSection() { return section; }
+}

+ 24 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSection.java

@@ -0,0 +1,24 @@
+package com.zksy.cockpit.foundation;
+
+public class CockpitFreshnessSection {
+    private final CockpitFreshnessSectionState state;
+    private final String reason;
+    private final String message;
+    private final CockpitFreshnessSectionData data;
+
+    public CockpitFreshnessSection(
+            CockpitFreshnessSectionState state,
+            String reason,
+            String message,
+            CockpitFreshnessSectionData data) {
+        this.state = state;
+        this.reason = reason;
+        this.message = message;
+        this.data = data;
+    }
+
+    public CockpitFreshnessSectionState getState() { return state; }
+    public String getReason() { return reason; }
+    public String getMessage() { return message; }
+    public CockpitFreshnessSectionData getData() { return data; }
+}

+ 40 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSectionData.java

@@ -0,0 +1,40 @@
+package com.zksy.cockpit.foundation;
+
+public class CockpitFreshnessSectionData {
+    private final String updatedAt;
+    private final String statusTime;
+    private final String serverUpdatedAt;
+    private final CockpitFreshnessStatus freshness;
+    private final String staleReason;
+    private final int missedCycles;
+    private final long dataAgeSeconds;
+    private final boolean retained;
+
+    public CockpitFreshnessSectionData(
+            String updatedAt,
+            String statusTime,
+            String serverUpdatedAt,
+            CockpitFreshnessStatus freshness,
+            String staleReason,
+            int missedCycles,
+            long dataAgeSeconds,
+            boolean retained) {
+        this.updatedAt = updatedAt;
+        this.statusTime = statusTime;
+        this.serverUpdatedAt = serverUpdatedAt;
+        this.freshness = freshness;
+        this.staleReason = staleReason;
+        this.missedCycles = missedCycles;
+        this.dataAgeSeconds = dataAgeSeconds;
+        this.retained = retained;
+    }
+
+    public String getUpdatedAt() { return updatedAt; }
+    public String getStatusTime() { return statusTime; }
+    public String getServerUpdatedAt() { return serverUpdatedAt; }
+    public CockpitFreshnessStatus getFreshness() { return freshness; }
+    public String getStaleReason() { return staleReason; }
+    public int getMissedCycles() { return missedCycles; }
+    public long getDataAgeSeconds() { return dataAgeSeconds; }
+    public boolean isRetained() { return retained; }
+}

+ 9 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSectionState.java

@@ -0,0 +1,9 @@
+package com.zksy.cockpit.foundation;
+
+public enum CockpitFreshnessSectionState {
+    CURRENT,
+    STALE,
+    EXPIRED,
+    EMPTY,
+    FAILED
+}

+ 169 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessService.java

@@ -0,0 +1,169 @@
+package com.zksy.cockpit.foundation;
+
+import org.springframework.stereotype.Service;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.Objects;
+
+@Service
+public class CockpitFreshnessService {
+    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+    private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
+    private static final int DEFAULT_CALIBRATION_PERIOD_SECONDS = 60;
+    private static final int MAX_CALIBRATION_PERIOD_SECONDS = 3600;
+
+    private final CockpitFreshnessAdapter adapter;
+    private final Clock clock;
+    private final int defaultCalibrationPeriodSeconds;
+
+    public CockpitFreshnessService(
+            CockpitFreshnessAdapter adapter,
+            Clock clock,
+            int defaultCalibrationPeriodSeconds) {
+        this.adapter = adapter;
+        this.clock = clock;
+        this.defaultCalibrationPeriodSeconds = defaultCalibrationPeriodSeconds;
+    }
+
+    public CockpitFreshnessResponse load(String requestId, String deviceCode, Integer calibrationPeriodSeconds) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+        int period = resolvePeriod(calibrationPeriodSeconds);
+        String normalizedDeviceCode = deviceCode.trim();
+        CockpitFreshnessSource source = adapter.load(normalizedDeviceCode);
+        if (source == null) {
+            return emptyResponse(requestId, normalizedDeviceCode, period);
+        }
+        if (!Objects.equals(normalizedDeviceCode, source.getDeviceCode())) {
+            throw new CockpitInvalidRequestException("device code mismatch");
+        }
+        OffsetDateTime updatedAt = parseTime(source.getUpdatedAt(), "updatedAt");
+        OffsetDateTime statusTime = parseTime(source.getStatusTime(), "statusTime");
+        OffsetDateTime latest = latest(updatedAt, statusTime);
+        OffsetDateTime serverUpdatedAt = OffsetDateTime.now(clock).atZoneSameInstant(BUSINESS_ZONE).toOffsetDateTime();
+        long ageSeconds = Math.max(0, Duration.between(latest, serverUpdatedAt).getSeconds());
+        int missedCycles = (int) (ageSeconds / period);
+        CockpitFreshnessStatus freshness = statusFor(missedCycles);
+        String staleReason = staleReason(freshness);
+        boolean retained = freshness == CockpitFreshnessStatus.STALE
+                || freshness == CockpitFreshnessStatus.EXPIRED;
+        String message = freshness == CockpitFreshnessStatus.EXPIRED ? "数据暂不可用/已过期" : null;
+        CockpitFreshnessSectionData sectionData = new CockpitFreshnessSectionData(
+                source.getUpdatedAt(),
+                source.getStatusTime(),
+                TIME_FORMATTER.format(serverUpdatedAt),
+                freshness,
+                staleReason,
+                missedCycles,
+                ageSeconds,
+                retained);
+        CockpitFreshnessSection section = new CockpitFreshnessSection(
+                sectionState(freshness),
+                sectionReason(freshness),
+                message,
+                sectionData);
+        return new CockpitFreshnessResponse(
+                requestId,
+                "v1",
+                true,
+                normalizedDeviceCode,
+                source.getUpdatedAt(),
+                source.getStatusTime(),
+                TIME_FORMATTER.format(serverUpdatedAt),
+                freshness,
+                staleReason,
+                period,
+                missedCycles,
+                ageSeconds,
+                retained,
+                message,
+                section);
+    }
+
+    private CockpitFreshnessResponse emptyResponse(String requestId, String deviceCode, int period) {
+        CockpitFreshnessSection section = new CockpitFreshnessSection(
+                CockpitFreshnessSectionState.EMPTY,
+                "NO_SOURCE",
+                null,
+                null);
+        return new CockpitFreshnessResponse(
+                requestId,
+                "v1",
+                true,
+                deviceCode,
+                null,
+                null,
+                TIME_FORMATTER.format(OffsetDateTime.now(clock).atZoneSameInstant(BUSINESS_ZONE).toOffsetDateTime()),
+                CockpitFreshnessStatus.EMPTY,
+                null,
+                period,
+                0,
+                0,
+                false,
+                null,
+                section);
+    }
+
+    private int resolvePeriod(Integer calibrationPeriodSeconds) {
+        int period = calibrationPeriodSeconds == null
+                ? defaultCalibrationPeriodSeconds
+                : calibrationPeriodSeconds;
+        if (period < 1 || period > MAX_CALIBRATION_PERIOD_SECONDS) {
+            throw new CockpitInvalidRequestException("calibration period must be between 1 and 3600 seconds");
+        }
+        return period;
+    }
+
+    private OffsetDateTime parseTime(String value, String fieldName) {
+        if (isBlank(value)) {
+            return null;
+        }
+        try {
+            return OffsetDateTime.parse(value);
+        } catch (DateTimeParseException exception) {
+            throw new CockpitInvalidRequestException("invalid " + fieldName);
+        }
+    }
+
+    private OffsetDateTime latest(OffsetDateTime updatedAt, OffsetDateTime statusTime) {
+        if (updatedAt == null) return statusTime;
+        if (statusTime == null) return updatedAt;
+        return statusTime.isAfter(updatedAt) ? statusTime : updatedAt;
+    }
+
+    private CockpitFreshnessStatus statusFor(int missedCycles) {
+        if (missedCycles <= 0) return CockpitFreshnessStatus.CURRENT;
+        if (missedCycles == 1) return CockpitFreshnessStatus.STALE;
+        return CockpitFreshnessStatus.EXPIRED;
+    }
+
+    private String staleReason(CockpitFreshnessStatus freshness) {
+        if (freshness == CockpitFreshnessStatus.STALE) return "ONE_UPDATE_CYCLE_MISSED";
+        if (freshness == CockpitFreshnessStatus.EXPIRED) return "TWO_UPDATE_CYCLES_MISSED";
+        return null;
+    }
+
+    private CockpitFreshnessSectionState sectionState(CockpitFreshnessStatus freshness) {
+        if (freshness == CockpitFreshnessStatus.CURRENT) return CockpitFreshnessSectionState.CURRENT;
+        if (freshness == CockpitFreshnessStatus.STALE) return CockpitFreshnessSectionState.STALE;
+        if (freshness == CockpitFreshnessStatus.EXPIRED) return CockpitFreshnessSectionState.EXPIRED;
+        return CockpitFreshnessSectionState.EMPTY;
+    }
+
+    private String sectionReason(CockpitFreshnessStatus freshness) {
+        if (freshness == CockpitFreshnessStatus.CURRENT) return "CURRENT";
+        if (freshness == CockpitFreshnessStatus.STALE) return "ONE_UPDATE_CYCLE_MISSED";
+        if (freshness == CockpitFreshnessStatus.EXPIRED) return "TWO_UPDATE_CYCLES_MISSED";
+        return "NO_SOURCE";
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

+ 17 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessSource.java

@@ -0,0 +1,17 @@
+package com.zksy.cockpit.foundation;
+
+public class CockpitFreshnessSource {
+    private final String deviceCode;
+    private final String updatedAt;
+    private final String statusTime;
+
+    public CockpitFreshnessSource(String deviceCode, String updatedAt, String statusTime) {
+        this.deviceCode = deviceCode;
+        this.updatedAt = updatedAt;
+        this.statusTime = statusTime;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getUpdatedAt() { return updatedAt; }
+    public String getStatusTime() { return statusTime; }
+}

+ 9 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitFreshnessStatus.java

@@ -0,0 +1,9 @@
+package com.zksy.cockpit.foundation;
+
+public enum CockpitFreshnessStatus {
+    CURRENT,
+    STALE,
+    EXPIRED,
+    EMPTY,
+    FAILED
+}

+ 11 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/EmptyCockpitFreshnessAdapter.java

@@ -0,0 +1,11 @@
+package com.zksy.cockpit.foundation;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class EmptyCockpitFreshnessAdapter implements CockpitFreshnessAdapter {
+    @Override
+    public CockpitFreshnessSource load(String deviceCode) {
+        return null;
+    }
+}

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureAdapter.java

@@ -0,0 +1,5 @@
+package com.zksy.cockpit.overview;
+
+public interface CockpitOverviewInfrastructureAdapter {
+    CockpitOverviewInfrastructureSnapshot load();
+}

+ 185 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureResponse.java

@@ -0,0 +1,185 @@
+package com.zksy.cockpit.overview;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public class CockpitOverviewInfrastructureResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String timezone;
+    private final Range range;
+    private final String updatedAt;
+    private final Freshness freshness;
+    private final Totals totals;
+    private final List<Industry> industries;
+    private final Excluded excluded;
+
+    public CockpitOverviewInfrastructureResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String timezone,
+            Range range,
+            String updatedAt,
+            Freshness freshness,
+            Totals totals,
+            List<Industry> industries,
+            Excluded excluded) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.timezone = timezone;
+        this.range = range;
+        this.updatedAt = updatedAt;
+        this.freshness = freshness;
+        this.totals = totals;
+        this.industries = industries;
+        this.excluded = excluded;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getTimezone() { return timezone; }
+    public Range getRange() { return range; }
+    public String getUpdatedAt() { return updatedAt; }
+    public Freshness getFreshness() { return freshness; }
+    public Totals getTotals() { return totals; }
+    public List<Industry> getIndustries() { return industries; }
+    public Excluded getExcluded() { return excluded; }
+
+    public static class Freshness {
+        private final String status;
+        private final String updatedAt;
+        private final String serverUpdatedAt;
+
+        public Freshness(String status, String updatedAt, String serverUpdatedAt) {
+            this.status = status;
+            this.updatedAt = updatedAt;
+            this.serverUpdatedAt = serverUpdatedAt;
+        }
+
+        public String getStatus() { return status; }
+        public String getUpdatedAt() { return updatedAt; }
+        public String getServerUpdatedAt() { return serverUpdatedAt; }
+    }
+
+    public static class Range {
+        private final String type;
+
+        public Range(String type) {
+            this.type = type;
+        }
+
+        public String getType() { return type; }
+    }
+
+    public static class Totals {
+        private final int facilityCount;
+        private final int smartDeviceCount;
+
+        public Totals(int facilityCount, int smartDeviceCount) {
+            this.facilityCount = facilityCount;
+            this.smartDeviceCount = smartDeviceCount;
+        }
+
+        public int getFacilityCount() { return facilityCount; }
+        public int getSmartDeviceCount() { return smartDeviceCount; }
+    }
+
+    public static class Industry {
+        private final String code;
+        private final String key;
+        private final String label;
+        private final int facilityCount;
+        private final int smartDeviceCount;
+        private final List<TypeSummary> facilityTypes;
+        private final List<TypeSummary> deviceTypes;
+
+        public Industry(
+                String code,
+                String key,
+                String label,
+                int facilityCount,
+                int smartDeviceCount,
+                List<TypeSummary> facilityTypes,
+                List<TypeSummary> deviceTypes) {
+            this.code = code;
+            this.key = key;
+            this.label = label;
+            this.facilityCount = facilityCount;
+            this.smartDeviceCount = smartDeviceCount;
+            this.facilityTypes = facilityTypes;
+            this.deviceTypes = deviceTypes;
+        }
+
+        public String getCode() { return code; }
+        public String getKey() { return key; }
+        public String getLabel() { return label; }
+        public int getFacilityCount() { return facilityCount; }
+        public int getSmartDeviceCount() { return smartDeviceCount; }
+        public List<TypeSummary> getFacilityTypes() { return facilityTypes; }
+        public List<TypeSummary> getDeviceTypes() { return deviceTypes; }
+    }
+
+    public static class TypeSummary {
+        private final String code;
+        private final String name;
+        private final int count;
+        private final BigDecimal lengthKm;
+        private final String scale;
+        private final RangeMetadata range;
+
+        public TypeSummary(
+                String code,
+                String name,
+                int count,
+                BigDecimal lengthKm,
+                String scale,
+                RangeMetadata range) {
+            this.code = code;
+            this.name = name;
+            this.count = count;
+            this.lengthKm = lengthKm;
+            this.scale = scale;
+            this.range = range;
+        }
+
+        public String getCode() { return code; }
+        public String getName() { return name; }
+        public int getCount() { return count; }
+        public BigDecimal getLengthKm() { return lengthKm; }
+        public String getScale() { return scale; }
+        public RangeMetadata getRange() { return range; }
+    }
+
+    public static class RangeMetadata {
+        private final String type;
+        private final String start;
+        private final String end;
+
+        public RangeMetadata(String type, String start, String end) {
+            this.type = type;
+            this.start = start;
+            this.end = end;
+        }
+
+        public String getType() { return type; }
+        public String getStart() { return start; }
+        public String getEnd() { return end; }
+    }
+
+    public static class Excluded {
+        private final int unknownTypeCount;
+        private final int typeKindMismatchCount;
+
+        public Excluded(int unknownTypeCount, int typeKindMismatchCount) {
+            this.unknownTypeCount = unknownTypeCount;
+            this.typeKindMismatchCount = typeKindMismatchCount;
+        }
+
+        public int getUnknownTypeCount() { return unknownTypeCount; }
+        public int getTypeKindMismatchCount() { return typeKindMismatchCount; }
+    }
+}

+ 251 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureService.java

@@ -0,0 +1,251 @@
+package com.zksy.cockpit.overview;
+
+import com.zksy.cockpit.foundation.CockpitErrorCategory;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.time.Clock;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+@Service
+public class CockpitOverviewInfrastructureService {
+    private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
+
+    private final CockpitOverviewInfrastructureAdapter adapter;
+    private final Clock clock;
+
+    public CockpitOverviewInfrastructureService(
+            CockpitOverviewInfrastructureAdapter adapter,
+            Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public CockpitOverviewInfrastructureResponse load(String requestId) {
+        CockpitOverviewInfrastructureSnapshot snapshot = adapter.load();
+        String serverUpdatedAt = businessTime();
+        String updatedAt = snapshot == null || isBlank(snapshot.getUpdatedAt())
+                ? serverUpdatedAt
+                : snapshot.getUpdatedAt();
+        CockpitOverviewInfrastructureResponse.Freshness freshness =
+                new CockpitOverviewInfrastructureResponse.Freshness(
+                        "CURRENT", snapshot == null ? null : snapshot.getUpdatedAt(), serverUpdatedAt);
+        TotalsBuilder totals = new TotalsBuilder();
+        List<IndustryBuilder> industryBuilders = new ArrayList<>();
+        industryBuilders.add(new IndustryBuilder("GAS", "gas", "燃气"));
+        industryBuilders.add(new IndustryBuilder("WATER_SUPPLY", "waterSupply", "供水"));
+        industryBuilders.add(new IndustryBuilder("DRAINAGE", "drainage", "排水"));
+        int unknownTypeCount = 0;
+        int typeKindMismatchCount = 0;
+
+        if (snapshot != null && snapshot.getCounts() != null) {
+            Map<String, CockpitOverviewInfrastructureSnapshot.SourceType> types = types(snapshot);
+            for (CockpitOverviewInfrastructureSnapshot.SourceCount count : snapshot.getCounts()) {
+                if (count == null || isBlank(count.getTypeCode())) {
+                    continue;
+                }
+                CockpitOverviewInfrastructureSnapshot.SourceType type = types.get(count.getTypeCode());
+                if (type == null) {
+                    unknownTypeCount += count.getCount();
+                } else if (!Objects.equals(count.getObjectKind(), type.getObjectKind())) {
+                    typeKindMismatchCount += count.getCount();
+                } else {
+                    addResolvedCount(count, type, industryBuilders, totals);
+                }
+            }
+        }
+
+        return new CockpitOverviewInfrastructureResponse(
+                requestId,
+                "v1",
+                true,
+                "Asia/Shanghai",
+                new CockpitOverviewInfrastructureResponse.Range("CURRENT_BASELINE"),
+                updatedAt,
+                freshness,
+                totals.build(),
+                buildIndustries(industryBuilders),
+                new CockpitOverviewInfrastructureResponse.Excluded(unknownTypeCount, typeKindMismatchCount));
+    }
+
+    public CockpitErrorPayload serverError(String requestId) {
+        return new CockpitErrorPayload(
+                CockpitErrorCategory.SERVER_ERROR,
+                "驾驶舱基础设施概览数据暂不可用",
+                requestId,
+                businessTime());
+    }
+
+    private static Map<String, CockpitOverviewInfrastructureSnapshot.SourceType> types(
+            CockpitOverviewInfrastructureSnapshot snapshot) {
+        if (snapshot.getTypes() == null) {
+            return Collections.emptyMap();
+        }
+        Map<String, CockpitOverviewInfrastructureSnapshot.SourceType> types = new LinkedHashMap<>();
+        for (CockpitOverviewInfrastructureSnapshot.SourceType type : snapshot.getTypes()) {
+            if (type != null && !isBlank(type.getCode())) {
+                types.put(type.getCode(), type);
+            }
+        }
+        return types;
+    }
+
+    private static void addResolvedCount(
+            CockpitOverviewInfrastructureSnapshot.SourceCount source,
+            CockpitOverviewInfrastructureSnapshot.SourceType type,
+            List<IndustryBuilder> industries,
+            TotalsBuilder totals) {
+        IndustryBuilder industry = industries.stream()
+                .filter(candidate -> candidate.getCode().equals(type.getIndustry()))
+                .findFirst()
+                .orElse(null);
+
+        if ("FACILITY".equals(source.getObjectKind())) {
+            totals.addFacility(source.getCount());
+            if (industry != null) {
+                addSummary(industry.getFacilityTypes(), summary(source, type));
+                industry.addFacility(source.getCount());
+            }
+        } else if ("SMART_DEVICE".equals(source.getObjectKind())) {
+            totals.addSmartDevice(source.getCount());
+            if (industry != null) {
+                addSummary(industry.getDeviceTypes(), summary(source, type));
+                industry.addSmartDevice(source.getCount());
+            }
+        }
+    }
+
+    private static CockpitOverviewInfrastructureResponse.TypeSummary summary(
+            CockpitOverviewInfrastructureSnapshot.SourceCount source,
+            CockpitOverviewInfrastructureSnapshot.SourceType type) {
+        CockpitOverviewInfrastructureSnapshot.SourceValue value = source.getValue();
+        CockpitOverviewInfrastructureSnapshot.SourceRange range = value == null ? null : value.getRange();
+        return new CockpitOverviewInfrastructureResponse.TypeSummary(
+                type.getCode(),
+                type.getName(),
+                source.getCount(),
+                value == null ? null : value.getLengthKm(),
+                value == null ? null : value.getScale(),
+                range == null ? null : new CockpitOverviewInfrastructureResponse.RangeMetadata(
+                        range.getType(),
+                        range.getStart(),
+                        range.getEnd()));
+    }
+
+    private static void addSummary(
+            List<CockpitOverviewInfrastructureResponse.TypeSummary> summaries,
+            CockpitOverviewInfrastructureResponse.TypeSummary summary) {
+        for (int index = 0; index < summaries.size(); index++) {
+            CockpitOverviewInfrastructureResponse.TypeSummary existing = summaries.get(index);
+            if (Objects.equals(existing.getCode(), summary.getCode())) {
+                summaries.set(index, mergeSummary(existing, summary));
+                return;
+            }
+        }
+        summaries.add(summary);
+    }
+
+    private static CockpitOverviewInfrastructureResponse.TypeSummary mergeSummary(
+            CockpitOverviewInfrastructureResponse.TypeSummary left,
+            CockpitOverviewInfrastructureResponse.TypeSummary right) {
+        return new CockpitOverviewInfrastructureResponse.TypeSummary(
+                left.getCode(),
+                left.getName(),
+                left.getCount() + right.getCount(),
+                sumLength(left.getLengthKm(), right.getLengthKm()),
+                right.getScale() == null ? left.getScale() : right.getScale(),
+                right.getRange() == null ? left.getRange() : right.getRange());
+    }
+
+    private static BigDecimal sumLength(BigDecimal left, BigDecimal right) {
+        if (left == null) {
+            return right;
+        }
+        if (right == null) {
+            return left;
+        }
+        return left.add(right);
+    }
+
+    private static List<CockpitOverviewInfrastructureResponse.Industry> buildIndustries(
+            List<IndustryBuilder> builders) {
+        List<CockpitOverviewInfrastructureResponse.Industry> industries = new ArrayList<>();
+        for (IndustryBuilder builder : builders) {
+            industries.add(builder.build());
+        }
+        return industries;
+    }
+
+    private static class TotalsBuilder {
+        private int facilityCount;
+        private int smartDeviceCount;
+
+        private void addFacility(int count) {
+            facilityCount += count;
+        }
+
+        private void addSmartDevice(int count) {
+            smartDeviceCount += count;
+        }
+
+        private CockpitOverviewInfrastructureResponse.Totals build() {
+            return new CockpitOverviewInfrastructureResponse.Totals(facilityCount, smartDeviceCount);
+        }
+    }
+
+    private static class IndustryBuilder {
+        private final String code;
+        private final String key;
+        private final String label;
+        private final List<CockpitOverviewInfrastructureResponse.TypeSummary> facilityTypes = new ArrayList<>();
+        private final List<CockpitOverviewInfrastructureResponse.TypeSummary> deviceTypes = new ArrayList<>();
+        private int facilityCount;
+        private int smartDeviceCount;
+
+        private IndustryBuilder(String code, String key, String label) {
+            this.code = code;
+            this.key = key;
+            this.label = label;
+        }
+
+        private String getCode() { return code; }
+        private List<CockpitOverviewInfrastructureResponse.TypeSummary> getFacilityTypes() { return facilityTypes; }
+        private List<CockpitOverviewInfrastructureResponse.TypeSummary> getDeviceTypes() { return deviceTypes; }
+
+        private void addFacility(int count) {
+            facilityCount += count;
+        }
+
+        private void addSmartDevice(int count) {
+            smartDeviceCount += count;
+        }
+
+        private CockpitOverviewInfrastructureResponse.Industry build() {
+            return new CockpitOverviewInfrastructureResponse.Industry(
+                    code,
+                    key,
+                    label,
+                    facilityCount,
+                    smartDeviceCount,
+                    facilityTypes,
+                    deviceTypes);
+        }
+    }
+
+    private String businessTime() {
+        return DateTimeFormatter.ISO_OFFSET_DATE_TIME
+                .format(clock.instant().atZone(BUSINESS_ZONE));
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

+ 100 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewInfrastructureSnapshot.java

@@ -0,0 +1,100 @@
+package com.zksy.cockpit.overview;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public class CockpitOverviewInfrastructureSnapshot {
+    private final String updatedAt;
+    private final List<SourceType> types;
+    private final List<SourceCount> counts;
+
+    public CockpitOverviewInfrastructureSnapshot(
+            String updatedAt,
+            List<SourceType> types,
+            List<SourceCount> counts) {
+        this.updatedAt = updatedAt;
+        this.types = types;
+        this.counts = counts;
+    }
+
+    public String getUpdatedAt() { return updatedAt; }
+    public List<SourceType> getTypes() { return types; }
+    public List<SourceCount> getCounts() { return counts; }
+
+    public static class SourceType {
+        private final String code;
+        private final String name;
+        private final String industry;
+        private final String drainageScope;
+        private final String objectKind;
+
+        public SourceType(String code, String name, String industry, String drainageScope, String objectKind) {
+            this.code = code;
+            this.name = name;
+            this.industry = industry;
+            this.drainageScope = drainageScope;
+            this.objectKind = objectKind;
+        }
+
+        public String getCode() { return code; }
+        public String getName() { return name; }
+        public String getIndustry() { return industry; }
+        public String getDrainageScope() { return drainageScope; }
+        public String getObjectKind() { return objectKind; }
+    }
+
+    public static class SourceCount {
+        private final String objectKind;
+        private final String typeCode;
+        private final int count;
+        private final SourceValue value;
+
+        public SourceCount(String objectKind, String typeCode, int count) {
+            this(objectKind, typeCode, count, null);
+        }
+
+        public SourceCount(String objectKind, String typeCode, int count, SourceValue value) {
+            this.objectKind = objectKind;
+            this.typeCode = typeCode;
+            this.count = count;
+            this.value = value;
+        }
+
+        public String getObjectKind() { return objectKind; }
+        public String getTypeCode() { return typeCode; }
+        public int getCount() { return count; }
+        public SourceValue getValue() { return value; }
+    }
+
+    public static class SourceValue {
+        private final BigDecimal lengthKm;
+        private final String scale;
+        private final SourceRange range;
+
+        public SourceValue(BigDecimal lengthKm, String scale, SourceRange range) {
+            this.lengthKm = lengthKm;
+            this.scale = scale;
+            this.range = range;
+        }
+
+        public BigDecimal getLengthKm() { return lengthKm; }
+        public String getScale() { return scale; }
+        public SourceRange getRange() { return range; }
+    }
+
+    public static class SourceRange {
+        private final String type;
+        private final String start;
+        private final String end;
+
+        public SourceRange(String type, String start, String end) {
+            this.type = type;
+            this.start = start;
+            this.end = end;
+        }
+
+        public String getType() { return type; }
+        public String getStart() { return start; }
+        public String getEnd() { return end; }
+    }
+}

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringAdapter.java

@@ -0,0 +1,5 @@
+package com.zksy.cockpit.overview;
+
+public interface CockpitOverviewMonitoringAdapter {
+    CockpitOverviewMonitoringSnapshot load();
+}

+ 24 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringDeviceStatusDelta.java

@@ -0,0 +1,24 @@
+package com.zksy.cockpit.overview;
+
+public class CockpitOverviewMonitoringDeviceStatusDelta {
+    private final String deviceCode;
+    private final String monitoringState;
+    private final String statusTime;
+    private final String serverUpdatedAt;
+
+    public CockpitOverviewMonitoringDeviceStatusDelta(
+            String deviceCode,
+            String monitoringState,
+            String statusTime,
+            String serverUpdatedAt) {
+        this.deviceCode = deviceCode;
+        this.monitoringState = monitoringState;
+        this.statusTime = statusTime;
+        this.serverUpdatedAt = serverUpdatedAt;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getMonitoringState() { return monitoringState; }
+    public String getStatusTime() { return statusTime; }
+    public String getServerUpdatedAt() { return serverUpdatedAt; }
+}

+ 249 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringResponse.java

@@ -0,0 +1,249 @@
+package com.zksy.cockpit.overview;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public class CockpitOverviewMonitoringResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String timezone;
+    private final String updatedAt;
+    private final Freshness freshness;
+    private final MetricFreshness metricFreshness;
+    private final Industry selectedIndustry;
+    private final FormalScope formalScope;
+    private final Counts counts;
+    private final List<TypeDistribution> typeDistribution;
+    private final Excluded excluded;
+
+    public CockpitOverviewMonitoringResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String timezone,
+            String updatedAt,
+            Freshness freshness,
+            MetricFreshness metricFreshness,
+            Industry selectedIndustry,
+            FormalScope formalScope,
+            Counts counts,
+            List<TypeDistribution> typeDistribution,
+            Excluded excluded) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.timezone = timezone;
+        this.updatedAt = updatedAt;
+        this.freshness = freshness;
+        this.metricFreshness = metricFreshness;
+        this.selectedIndustry = selectedIndustry;
+        this.formalScope = formalScope;
+        this.counts = counts;
+        this.typeDistribution = typeDistribution;
+        this.excluded = excluded;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getTimezone() { return timezone; }
+    public String getUpdatedAt() { return updatedAt; }
+    public Freshness getFreshness() { return freshness; }
+    public MetricFreshness getMetricFreshness() { return metricFreshness; }
+    public Industry getSelectedIndustry() { return selectedIndustry; }
+    public FormalScope getFormalScope() { return formalScope; }
+    public Counts getCounts() { return counts; }
+    public List<TypeDistribution> getTypeDistribution() { return typeDistribution; }
+    public Excluded getExcluded() { return excluded; }
+
+    public static class Freshness {
+        private final String status;
+        private final String reason;
+        private final String updatedAt;
+        private final String serverUpdatedAt;
+
+        public Freshness(
+                String status,
+                String reason,
+                String updatedAt,
+                String serverUpdatedAt) {
+            this.status = status;
+            this.reason = reason;
+            this.updatedAt = updatedAt;
+            this.serverUpdatedAt = serverUpdatedAt;
+        }
+
+        public String getStatus() { return status; }
+        public String getReason() { return reason; }
+        public String getUpdatedAt() { return updatedAt; }
+        public String getServerUpdatedAt() { return serverUpdatedAt; }
+    }
+
+    public static class MetricFreshness {
+        private final String status;
+        private final String updatedAt;
+        private final String serverUpdatedAt;
+
+        public MetricFreshness(String status, String updatedAt, String serverUpdatedAt) {
+            this.status = status;
+            this.updatedAt = updatedAt;
+            this.serverUpdatedAt = serverUpdatedAt;
+        }
+
+        public String getStatus() { return status; }
+        public String getUpdatedAt() { return updatedAt; }
+        public String getServerUpdatedAt() { return serverUpdatedAt; }
+    }
+
+    public static class Industry {
+        private final String code;
+        private final String key;
+        private final String label;
+
+        public Industry(String code, String key, String label) {
+            this.code = code;
+            this.key = key;
+            this.label = label;
+        }
+
+        public String getCode() { return code; }
+        public String getKey() { return key; }
+        public String getLabel() { return label; }
+    }
+
+    public static class FormalScope {
+        private final List<String> industries;
+        private final List<String> keys;
+
+        public FormalScope(List<String> industries, List<String> keys) {
+            this.industries = industries;
+            this.keys = keys;
+        }
+
+        public List<String> getIndustries() { return industries; }
+        public List<String> getKeys() { return keys; }
+    }
+
+    public static class Counts {
+        private final int deviceCount;
+        private final int monitoringPointCount;
+        private final int monitoringFacilityCount;
+        private final int infrastructureFacilityCount;
+        private final Status status;
+        private final OnlineRate onlineRate;
+
+        public Counts(
+                int deviceCount,
+                int monitoringPointCount,
+                int monitoringFacilityCount,
+                int infrastructureFacilityCount,
+                Status status,
+                OnlineRate onlineRate) {
+            this.deviceCount = deviceCount;
+            this.monitoringPointCount = monitoringPointCount;
+            this.monitoringFacilityCount = monitoringFacilityCount;
+            this.infrastructureFacilityCount = infrastructureFacilityCount;
+            this.status = status;
+            this.onlineRate = onlineRate;
+        }
+
+        public int getDeviceCount() { return deviceCount; }
+        public int getMonitoringPointCount() { return monitoringPointCount; }
+        public int getMonitoringFacilityCount() { return monitoringFacilityCount; }
+        public int getInfrastructureFacilityCount() { return infrastructureFacilityCount; }
+        public Status getStatus() { return status; }
+        public OnlineRate getOnlineRate() { return onlineRate; }
+    }
+
+    public static class Status {
+        private final int online;
+        private final int offline;
+        private final int stale;
+        private final int unknownOrMissing;
+        private final int denominator;
+
+        public Status(int online, int offline, int stale, int unknownOrMissing, int denominator) {
+            this.online = online;
+            this.offline = offline;
+            this.stale = stale;
+            this.unknownOrMissing = unknownOrMissing;
+            this.denominator = denominator;
+        }
+
+        public int getOnline() { return online; }
+        public int getOffline() { return offline; }
+        public int getStale() { return stale; }
+        public int getUnknownOrMissing() { return unknownOrMissing; }
+        public int getDenominator() { return denominator; }
+    }
+
+    public static class OnlineRate {
+        private final BigDecimal value;
+        private final int onlineCount;
+        private final int denominator;
+        private final String state;
+        private final String reason;
+
+        public OnlineRate(
+                BigDecimal value,
+                int onlineCount,
+                int denominator,
+                String state,
+                String reason) {
+            this.value = value;
+            this.onlineCount = onlineCount;
+            this.denominator = denominator;
+            this.state = state;
+            this.reason = reason;
+        }
+
+        public BigDecimal getValue() { return value; }
+        public int getOnlineCount() { return onlineCount; }
+        public int getDenominator() { return denominator; }
+        public String getState() { return state; }
+        public String getReason() { return reason; }
+    }
+
+    public static class TypeDistribution {
+        private final Industry industry;
+        private final DeviceType deviceType;
+        private final int deviceCount;
+
+        public TypeDistribution(Industry industry, DeviceType deviceType, int deviceCount) {
+            this.industry = industry;
+            this.deviceType = deviceType;
+            this.deviceCount = deviceCount;
+        }
+
+        public Industry getIndustry() { return industry; }
+        public DeviceType getDeviceType() { return deviceType; }
+        public int getDeviceCount() { return deviceCount; }
+    }
+
+    public static class DeviceType {
+        private final String code;
+        private final String name;
+
+        public DeviceType(String code, String name) {
+            this.code = code;
+            this.name = name;
+        }
+
+        public String getCode() { return code; }
+        public String getName() { return name; }
+    }
+
+    public static class Excluded {
+        private final int unknownTypeCount;
+        private final int typeKindMismatchCount;
+
+        public Excluded(int unknownTypeCount, int typeKindMismatchCount) {
+            this.unknownTypeCount = unknownTypeCount;
+            this.typeKindMismatchCount = typeKindMismatchCount;
+        }
+
+        public int getUnknownTypeCount() { return unknownTypeCount; }
+        public int getTypeKindMismatchCount() { return typeKindMismatchCount; }
+    }
+}

+ 406 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringService.java

@@ -0,0 +1,406 @@
+package com.zksy.cockpit.overview;
+
+import com.zksy.cockpit.foundation.CockpitErrorCategory;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.Clock;
+import java.time.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+@Service
+public class CockpitOverviewMonitoringService {
+    private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
+    private static final List<String> FORMAL_INDUSTRIES =
+            Collections.unmodifiableList(Arrays.asList("GAS", "WATER_SUPPLY", "DRAINAGE"));
+    private static final List<String> FORMAL_INDUSTRY_KEYS =
+            Collections.unmodifiableList(Arrays.asList("gas", "waterSupply", "drainage"));
+
+    private final CockpitOverviewMonitoringAdapter adapter;
+    private final Clock clock;
+    private RuntimeState state;
+
+    public CockpitOverviewMonitoringService(
+            CockpitOverviewMonitoringAdapter adapter,
+            Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public synchronized CockpitOverviewMonitoringResponse load(String requestId, String industry) {
+        return read(industry, requestId, () -> refreshState());
+    }
+
+    public synchronized CockpitOverviewMonitoringResponse applyDeviceStatusDelta(
+            String requestId,
+            String industry,
+            CockpitOverviewMonitoringDeviceStatusDelta delta) {
+        return read(industry, requestId, () -> applyDelta(delta));
+    }
+
+    public CockpitErrorPayload invalidRequest(String requestId) {
+        return new CockpitErrorPayload(
+                CockpitErrorCategory.INVALID_REQUEST,
+                "industry must be GAS, WATER_SUPPLY or DRAINAGE",
+                requestId,
+                businessTime());
+    }
+
+    public CockpitErrorPayload serverError(String requestId) {
+        return new CockpitErrorPayload(
+                CockpitErrorCategory.SERVER_ERROR,
+                "驾驶舱运行监测概览数据暂不可用",
+                requestId,
+                businessTime());
+    }
+
+    private CockpitOverviewMonitoringResponse read(
+            String industry,
+            String requestId,
+            StateSupplier stateSupplier) {
+        validateIndustry(industry);
+        RuntimeState currentState = stateSupplier.get();
+        return buildResponse(requestId, industry, currentState);
+    }
+
+    private RuntimeState refreshState() {
+        CockpitOverviewMonitoringSnapshot snapshot = adapter.load();
+        Map<String, DeviceRuntime> devices = new LinkedHashMap<>();
+        if (snapshot != null && snapshot.getDevices() != null) {
+            for (CockpitOverviewMonitoringSnapshot.SourceDevice source : snapshot.getDevices()) {
+                if (source == null || isBlank(source.getDeviceCode())) {
+                    continue;
+                }
+                devices.put(
+                        source.getDeviceCode(),
+                        new DeviceRuntime(
+                                source.getTypeCode(),
+                                source.getMonitoringState(),
+                                null));
+            }
+        }
+        state = new RuntimeState(snapshot, devices, snapshot == null ? null : snapshot.getUpdatedAt());
+        return state;
+    }
+
+    private RuntimeState applyDelta(CockpitOverviewMonitoringDeviceStatusDelta delta) {
+        if (state == null) {
+            refreshState();
+        }
+        if (delta == null || isBlank(delta.getDeviceCode())) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+        OffsetDateTime serverUpdatedAt = parseTime(delta.getServerUpdatedAt(), "serverUpdatedAt");
+        DeviceRuntime previous = state.getDevices().get(delta.getDeviceCode());
+        if (previous == null) {
+            return state;
+        }
+        if (previous.getServerUpdatedAt() != null
+                && !serverUpdatedAt.isAfter(parseTime(previous.getServerUpdatedAt(), "serverUpdatedAt"))) {
+            return state;
+        }
+
+        Map<String, DeviceRuntime> devices = new LinkedHashMap<>(state.getDevices());
+        devices.put(
+                delta.getDeviceCode(),
+                new DeviceRuntime(
+                        previous.getTypeCode(),
+                        delta.getMonitoringState(),
+                        DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(serverUpdatedAt)));
+        state = new RuntimeState(state.getSnapshot(), devices, delta.getServerUpdatedAt());
+        return state;
+    }
+
+    private void validateIndustry(String industry) {
+        if (!isBlank(industry) && !FORMAL_INDUSTRIES.contains(industry)) {
+            throw new CockpitInvalidRequestException("industry must be GAS, WATER_SUPPLY or DRAINAGE");
+        }
+    }
+
+    private CockpitOverviewMonitoringResponse buildResponse(
+            String requestId,
+            String selectedIndustry,
+            RuntimeState currentState) {
+        CockpitOverviewMonitoringSnapshot snapshot = currentState.getSnapshot();
+        Map<String, CockpitOverviewMonitoringSnapshot.SourceType> types = types(snapshot);
+        List<CockpitOverviewMonitoringSnapshot.SourceDevice> selectedDevices = new ArrayList<>();
+        Map<String, Integer> distributionCounts = new LinkedHashMap<>();
+        Map<String, CockpitOverviewMonitoringSnapshot.SourceType> distributionTypes = new LinkedHashMap<>();
+        int online = 0;
+        int offline = 0;
+        int stale = 0;
+        int unknownOrMissing = 0;
+        int unknownTypeCount = 0;
+        int typeKindMismatchCount = 0;
+
+        for (CockpitOverviewMonitoringSnapshot.SourceDevice device : list(snapshot, snapshot == null ? null : snapshot.getDevices())) {
+            if (device == null || isBlank(device.getTypeCode())) {
+                unknownTypeCount++;
+                continue;
+            }
+            CockpitOverviewMonitoringSnapshot.SourceType type = types.get(device.getTypeCode());
+            if (type == null || !isFormal(type)) {
+                unknownTypeCount++;
+                continue;
+            }
+            if (!"SMART_DEVICE".equals(type.getObjectKind())) {
+                typeKindMismatchCount++;
+                continue;
+            }
+            if (selectedIndustry != null && !selectedIndustry.equals(type.getIndustry())) {
+                continue;
+            }
+
+            DeviceRuntime runtime = currentState.getDevices().get(device.getDeviceCode());
+            String monitoringState = runtime == null ? device.getMonitoringState() : runtime.getMonitoringState();
+            selectedDevices.add(device);
+            distributionCounts.merge(device.getTypeCode(), 1, Integer::sum);
+            distributionTypes.putIfAbsent(device.getTypeCode(), type);
+            if ("ONLINE".equals(monitoringState)) {
+                online++;
+            } else if ("OFFLINE".equals(monitoringState)) {
+                offline++;
+            } else if ("STALE".equals(monitoringState)) {
+                stale++;
+            } else {
+                unknownOrMissing++;
+            }
+        }
+
+        int monitoringPointCount = countByType(
+                snapshot,
+                snapshot == null ? null : snapshot.getMonitoringPoints(),
+                CockpitOverviewMonitoringSnapshot.SourceMonitoringPoint::getTypeCode,
+                types,
+                selectedIndustry,
+                "SMART_DEVICE");
+        int monitoringFacilityCount = countByType(
+                snapshot,
+                snapshot == null ? null : snapshot.getMonitoringFacilities(),
+                CockpitOverviewMonitoringSnapshot.SourceMonitoringFacility::getTypeCode,
+                types,
+                selectedIndustry,
+                "FACILITY");
+        int deviceCount = selectedDevices.size();
+        int denominator = online + offline + stale;
+        BigDecimal rate = denominator == 0
+                ? BigDecimal.ZERO.setScale(4)
+                : BigDecimal.valueOf(online)
+                        .divide(BigDecimal.valueOf(denominator), 4, RoundingMode.HALF_UP);
+        String freshnessStatus = deviceCount == 0
+                ? "EMPTY"
+                : denominator == 0 ? "EMPTY" : stale == 0 ? "CURRENT" : "STALE";
+        String freshnessReason = deviceCount == 0
+                ? "NO_RESOLVED_DEVICES"
+                : denominator == 0 ? "NO_RESOLVED_DEVICES" : stale == 0
+                        ? "RESOLVED_MONITORING_STATES" : "MONITORING_STATE_STALE";
+        String updatedAt = currentState.getAcceptedAt() == null
+                ? businessTime()
+                : currentState.getAcceptedAt();
+
+        CockpitOverviewMonitoringSnapshot.SourceMetricFreshness sourceFreshness =
+                snapshot == null ? null : snapshot.getMetricFreshness();
+        CockpitOverviewMonitoringResponse.MetricFreshness metricFreshness = sourceFreshness == null
+                ? null
+                : new CockpitOverviewMonitoringResponse.MetricFreshness(
+                        sourceFreshness.getStatus(),
+                        sourceFreshness.getUpdatedAt(),
+                        businessTime());
+        CockpitOverviewMonitoringResponse.Industry industry = industry(selectedIndustry);
+
+        return new CockpitOverviewMonitoringResponse(
+                requestId,
+                "v1",
+                true,
+                "Asia/Shanghai",
+                updatedAt,
+                new CockpitOverviewMonitoringResponse.Freshness(
+                        freshnessStatus,
+                        freshnessReason,
+                        updatedAt,
+                        businessTime()),
+                metricFreshness,
+                industry,
+                new CockpitOverviewMonitoringResponse.FormalScope(
+                        FORMAL_INDUSTRIES,
+                        FORMAL_INDUSTRY_KEYS),
+                new CockpitOverviewMonitoringResponse.Counts(
+                        deviceCount,
+                        monitoringPointCount,
+                        monitoringFacilityCount,
+                        snapshot == null ? 0 : snapshot.getInfrastructureFacilityCount(),
+                        new CockpitOverviewMonitoringResponse.Status(
+                                online,
+                                offline,
+                                stale,
+                                unknownOrMissing,
+                                denominator),
+                        new CockpitOverviewMonitoringResponse.OnlineRate(
+                                rate,
+                                online,
+                                denominator,
+                                denominator == 0 ? "EMPTY" : "AVAILABLE",
+                                denominator == 0 ? "NO_RESOLVED_DEVICES" : null)),
+                typeDistribution(distributionCounts, distributionTypes),
+                new CockpitOverviewMonitoringResponse.Excluded(unknownTypeCount, typeKindMismatchCount));
+    }
+
+    private List<CockpitOverviewMonitoringResponse.TypeDistribution> typeDistribution(
+            Map<String, Integer> counts,
+            Map<String, CockpitOverviewMonitoringSnapshot.SourceType> types) {
+        List<CockpitOverviewMonitoringResponse.TypeDistribution> distribution = new ArrayList<>();
+        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
+            CockpitOverviewMonitoringSnapshot.SourceType type = types.get(entry.getKey());
+            distribution.add(new CockpitOverviewMonitoringResponse.TypeDistribution(
+                    industry(type == null ? null : type.getIndustry()),
+                    new CockpitOverviewMonitoringResponse.DeviceType(
+                            entry.getKey(),
+                            type == null ? null : type.getName()),
+                    entry.getValue()));
+        }
+        return distribution;
+    }
+
+    private <T> int countByType(
+            CockpitOverviewMonitoringSnapshot snapshot,
+            List<T> sources,
+            java.util.function.Function<T, String> typeCodeGetter,
+            Map<String, CockpitOverviewMonitoringSnapshot.SourceType> types,
+            String selectedIndustry,
+            String expectedKind) {
+        if (snapshot == null || sources == null) {
+            return 0;
+        }
+        int count = 0;
+        for (T source : sources) {
+            if (source == null) {
+                continue;
+            }
+            String typeCode = typeCodeGetter.apply(source);
+            CockpitOverviewMonitoringSnapshot.SourceType type = isBlank(typeCode) ? null : types.get(typeCode);
+            if (type == null) {
+                continue;
+            }
+            if (!isFormal(type) || !expectedKind.equals(type.getObjectKind())) {
+                continue;
+            }
+            if (selectedIndustry != null && !selectedIndustry.equals(type.getIndustry())) {
+                continue;
+            }
+            count++;
+        }
+        return count;
+    }
+
+    private static boolean isFormal(CockpitOverviewMonitoringSnapshot.SourceType type) {
+        return type != null
+                && type.getIndustry() != null
+                && FORMAL_INDUSTRIES.contains(type.getIndustry());
+    }
+
+    private static Map<String, CockpitOverviewMonitoringSnapshot.SourceType> types(
+            CockpitOverviewMonitoringSnapshot snapshot) {
+        if (snapshot == null || snapshot.getTypes() == null) {
+            return Collections.emptyMap();
+        }
+        Map<String, CockpitOverviewMonitoringSnapshot.SourceType> types = new LinkedHashMap<>();
+        for (CockpitOverviewMonitoringSnapshot.SourceType type : snapshot.getTypes()) {
+            if (type != null && !isBlank(type.getCode())) {
+                types.putIfAbsent(type.getCode(), type);
+            }
+        }
+        return types;
+    }
+
+    private static <T> List<T> list(CockpitOverviewMonitoringSnapshot snapshot, List<T> values) {
+        return values == null ? Collections.emptyList() : values;
+    }
+
+    private static CockpitOverviewMonitoringResponse.Industry industry(String code) {
+        if (code == null) {
+            return new CockpitOverviewMonitoringResponse.Industry(null, null, "全部");
+        }
+        int index = FORMAL_INDUSTRIES.indexOf(code);
+        return new CockpitOverviewMonitoringResponse.Industry(
+                code,
+                FORMAL_INDUSTRY_KEYS.get(index),
+                label(code));
+    }
+
+    private static String label(String code) {
+        if ("GAS".equals(code)) return "燃气";
+        if ("WATER_SUPPLY".equals(code)) return "供水";
+        if ("DRAINAGE".equals(code)) return "排水";
+        return code;
+    }
+
+    private static OffsetDateTime parseTime(String value, String fieldName) {
+        if (isBlank(value)) {
+            throw new CockpitInvalidRequestException(fieldName + " is required");
+        }
+        try {
+            return OffsetDateTime.parse(value);
+        } catch (Exception exception) {
+            throw new CockpitInvalidRequestException("invalid " + fieldName);
+        }
+    }
+
+    private String businessTime() {
+        return DateTimeFormatter.ISO_OFFSET_DATE_TIME
+                .format(clock.instant().atZone(BUSINESS_ZONE));
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    private interface StateSupplier {
+        RuntimeState get();
+    }
+
+    private static class RuntimeState {
+        private final CockpitOverviewMonitoringSnapshot snapshot;
+        private final Map<String, DeviceRuntime> devices;
+        private final String acceptedAt;
+
+        private RuntimeState(
+                CockpitOverviewMonitoringSnapshot snapshot,
+                Map<String, DeviceRuntime> devices,
+                String acceptedAt) {
+            this.snapshot = snapshot;
+            this.devices = devices;
+            this.acceptedAt = acceptedAt;
+        }
+
+        private CockpitOverviewMonitoringSnapshot getSnapshot() { return snapshot; }
+        private Map<String, DeviceRuntime> getDevices() { return devices; }
+        private String getAcceptedAt() { return acceptedAt; }
+    }
+
+    private static class DeviceRuntime {
+        private final String typeCode;
+        private final String monitoringState;
+        private final String serverUpdatedAt;
+
+        private DeviceRuntime(String typeCode, String monitoringState, String serverUpdatedAt) {
+            this.typeCode = typeCode;
+            this.monitoringState = monitoringState;
+            this.serverUpdatedAt = serverUpdatedAt;
+        }
+
+        private String getTypeCode() { return typeCode; }
+        private String getMonitoringState() { return monitoringState; }
+        private String getServerUpdatedAt() { return serverUpdatedAt; }
+    }
+}

+ 120 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewMonitoringSnapshot.java

@@ -0,0 +1,120 @@
+package com.zksy.cockpit.overview;
+
+import java.util.List;
+
+public class CockpitOverviewMonitoringSnapshot {
+    private final String updatedAt;
+    private final SourceMetricFreshness metricFreshness;
+    private final List<SourceType> types;
+    private final List<SourceDevice> devices;
+    private final List<SourceMonitoringPoint> monitoringPoints;
+    private final List<SourceMonitoringFacility> monitoringFacilities;
+    private final int infrastructureFacilityCount;
+
+    public CockpitOverviewMonitoringSnapshot(
+            String updatedAt,
+            SourceMetricFreshness metricFreshness,
+            List<SourceType> types,
+            List<SourceDevice> devices,
+            List<SourceMonitoringPoint> monitoringPoints,
+            List<SourceMonitoringFacility> monitoringFacilities,
+            int infrastructureFacilityCount) {
+        this.updatedAt = updatedAt;
+        this.metricFreshness = metricFreshness;
+        this.types = types;
+        this.devices = devices;
+        this.monitoringPoints = monitoringPoints;
+        this.monitoringFacilities = monitoringFacilities;
+        this.infrastructureFacilityCount = infrastructureFacilityCount;
+    }
+
+    public String getUpdatedAt() { return updatedAt; }
+    public SourceMetricFreshness getMetricFreshness() { return metricFreshness; }
+    public List<SourceType> getTypes() { return types; }
+    public List<SourceDevice> getDevices() { return devices; }
+    public List<SourceMonitoringPoint> getMonitoringPoints() { return monitoringPoints; }
+    public List<SourceMonitoringFacility> getMonitoringFacilities() { return monitoringFacilities; }
+    public int getInfrastructureFacilityCount() { return infrastructureFacilityCount; }
+
+    public static class SourceMetricFreshness {
+        private final String status;
+        private final String updatedAt;
+
+        public SourceMetricFreshness(String status, String updatedAt) {
+            this.status = status;
+            this.updatedAt = updatedAt;
+        }
+
+        public String getStatus() { return status; }
+        public String getUpdatedAt() { return updatedAt; }
+    }
+
+    public static class SourceType {
+        private final String code;
+        private final String name;
+        private final String industry;
+        private final String drainageScope;
+        private final String objectKind;
+
+        public SourceType(
+                String code,
+                String name,
+                String industry,
+                String drainageScope,
+                String objectKind) {
+            this.code = code;
+            this.name = name;
+            this.industry = industry;
+            this.drainageScope = drainageScope;
+            this.objectKind = objectKind;
+        }
+
+        public String getCode() { return code; }
+        public String getName() { return name; }
+        public String getIndustry() { return industry; }
+        public String getDrainageScope() { return drainageScope; }
+        public String getObjectKind() { return objectKind; }
+    }
+
+    public static class SourceDevice {
+        private final String deviceCode;
+        private final String typeCode;
+        private final String monitoringState;
+
+        public SourceDevice(String deviceCode, String typeCode, String monitoringState) {
+            this.deviceCode = deviceCode;
+            this.typeCode = typeCode;
+            this.monitoringState = monitoringState;
+        }
+
+        public String getDeviceCode() { return deviceCode; }
+        public String getTypeCode() { return typeCode; }
+        public String getMonitoringState() { return monitoringState; }
+    }
+
+    public static class SourceMonitoringPoint {
+        private final String pointCode;
+        private final String typeCode;
+
+        public SourceMonitoringPoint(String pointCode, String typeCode) {
+            this.pointCode = pointCode;
+            this.typeCode = typeCode;
+        }
+
+        public String getPointCode() { return pointCode; }
+        public String getTypeCode() { return typeCode; }
+    }
+
+    public static class SourceMonitoringFacility {
+        private final String facilityCode;
+        private final String typeCode;
+
+        public SourceMonitoringFacility(String facilityCode, String typeCode) {
+            this.facilityCode = facilityCode;
+            this.typeCode = typeCode;
+        }
+
+        public String getFacilityCode() { return facilityCode; }
+        public String getTypeCode() { return typeCode; }
+    }
+}

+ 11 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/EmptyCockpitOverviewInfrastructureAdapter.java

@@ -0,0 +1,11 @@
+package com.zksy.cockpit.overview;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class EmptyCockpitOverviewInfrastructureAdapter implements CockpitOverviewInfrastructureAdapter {
+    @Override
+    public CockpitOverviewInfrastructureSnapshot load() {
+        return null;
+    }
+}

+ 20 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/EmptyCockpitOverviewMonitoringAdapter.java

@@ -0,0 +1,20 @@
+package com.zksy.cockpit.overview;
+
+import org.springframework.stereotype.Component;
+
+import java.util.Collections;
+
+@Component
+public class EmptyCockpitOverviewMonitoringAdapter implements CockpitOverviewMonitoringAdapter {
+    @Override
+    public CockpitOverviewMonitoringSnapshot load() {
+        return new CockpitOverviewMonitoringSnapshot(
+                null,
+                null,
+                Collections.emptyList(),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                0);
+    }
+}

+ 151 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/BusinessCockpitWorkOrderReadAdapter.java

@@ -0,0 +1,151 @@
+package com.zksy.cockpit.workorder;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.domain.WorkOrderLog;
+import com.zksy.base.service.BusinessWorkOrderService;
+import com.zksy.base.warning.domain.AlarmWarningRel;
+import com.zksy.base.warning.domain.EarlyWarning;
+import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
+import com.zksy.base.warning.service.EarlyWarningService;
+import org.springframework.context.annotation.Primary;
+import org.springframework.stereotype.Component;
+
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+@Component
+@Primary
+public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderReadAdapter {
+    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+
+    private final BusinessWorkOrderService workOrderService;
+    private final EarlyWarningService earlyWarningService;
+    private final AlarmWarningRelMapper alarmWarningRelMapper;
+
+    public BusinessCockpitWorkOrderReadAdapter(
+            BusinessWorkOrderService workOrderService,
+            EarlyWarningService earlyWarningService,
+            AlarmWarningRelMapper alarmWarningRelMapper) {
+        this.workOrderService = workOrderService;
+        this.earlyWarningService = earlyWarningService;
+        this.alarmWarningRelMapper = alarmWarningRelMapper;
+    }
+
+    @Override
+    public CockpitWorkOrderReadSnapshot loadByDevice(String deviceCode) {
+        List<WorkOrder> orders = workOrderService.lambdaQuery()
+                .eq(WorkOrder::getDeviceCode, deviceCode)
+                .orderByDesc(WorkOrder::getCreateTime)
+                .list();
+        List<CockpitWorkOrderSummary> summaries = orders.stream()
+                .map(order -> toSummary(order, null, null))
+                .collect(Collectors.toList());
+        return new CockpitWorkOrderReadSnapshot(deviceCode, null, null, summaries);
+    }
+
+    @Override
+    public CockpitWorkOrderReadSnapshot loadByEvent(String eventSource, String eventCode) {
+        if ("ALARM".equals(eventSource)) {
+            List<WorkOrder> orders = workOrderService.lambdaQuery()
+                    .eq(WorkOrder::getAlarmId, eventCode)
+                    .orderByDesc(WorkOrder::getCreateTime)
+                    .list();
+            return new CockpitWorkOrderReadSnapshot(null, eventSource, eventCode,
+                    orders.stream().map(order -> toSummary(order, eventSource, eventCode)).collect(Collectors.toList()));
+        }
+        if ("WARNING".equals(eventSource)) {
+            EarlyWarning warning = earlyWarningService.lambdaQuery()
+                    .eq(EarlyWarning::getWarningNo, eventCode)
+                    .one();
+            if (warning == null) {
+                return null;
+            }
+            List<AlarmWarningRel> relations = alarmWarningRelMapper.selectList(
+                    new LambdaQueryWrapper<AlarmWarningRel>()
+                            .eq(AlarmWarningRel::getWarningId, warning.getWarningId()));
+            List<String> alarmIds = relations.stream()
+                    .map(AlarmWarningRel::getAlarmId)
+                    .filter(Objects::nonNull)
+                    .distinct()
+                    .collect(Collectors.toList());
+            List<WorkOrder> orders = alarmIds.isEmpty()
+                    ? Collections.emptyList()
+                    : workOrderService.lambdaQuery()
+                            .in(WorkOrder::getAlarmId, alarmIds)
+                            .orderByDesc(WorkOrder::getCreateTime)
+                            .list();
+            List<CockpitWorkOrderSummary> summaries = orders.stream()
+                    .map(order -> toSummary(order, eventSource, eventCode))
+                    .collect(Collectors.toList());
+            return new CockpitWorkOrderReadSnapshot(null, eventSource, eventCode, summaries);
+        }
+        return null;
+    }
+
+    @Override
+    public CockpitWorkOrderTimelineSnapshot loadTimeline(String workOrderCode) {
+        WorkOrder order = workOrderService.lambdaQuery()
+                .eq(WorkOrder::getOrderNo, workOrderCode)
+                .one();
+        if (order == null) {
+            return null;
+        }
+        List<WorkOrderLog> logs = workOrderService.getWorkOrderLogs(order.getOrderId());
+        List<CockpitWorkOrderTimelineEntry> entries = logs.stream()
+                .map(log -> toTimelineEntry(order, log))
+                .collect(Collectors.toList());
+        return new CockpitWorkOrderTimelineSnapshot(toSummary(order, null, null), entries);
+    }
+
+    private CockpitWorkOrderSummary toSummary(WorkOrder order, String eventSource, String eventCode) {
+        CockpitWorkOrderState state = CockpitWorkOrderStateDictionary.byLegacyCode(order.getOrderStatus());
+        return new CockpitWorkOrderSummary(
+                order.getOrderNo(),
+                order.getDeviceCode(),
+                order.getOrderType(),
+                orderTypeName(order.getOrderType()),
+                order.getOrderLevel(),
+                order.getOrderDesc(),
+                state.getCode(),
+                state.getName(),
+                format(order.getCreateTime()),
+                format(order.getUpdateTime()),
+                format(order.getPlanFinishTime()),
+                format(order.getRealFinishTime()),
+                eventSource == null ? null : new CockpitWorkOrderEventAssociation(
+                        eventSource, eventCode, format(order.getCreateTime())));
+    }
+
+    private CockpitWorkOrderTimelineEntry toTimelineEntry(WorkOrder order, WorkOrderLog log) {
+        CockpitWorkOrderState state = CockpitWorkOrderStateDictionary.byLegacyCode(log.getOperType());
+        return new CockpitWorkOrderTimelineEntry(
+                log.getLogId(),
+                order.getOrderNo(),
+                state.getCode(),
+                state.getName(),
+                state.getName(),
+                log.getOperDesc(),
+                log.getOperUserName(),
+                format(log.getOperTime()));
+    }
+
+    private String orderTypeName(Integer orderType) {
+        if (orderType == null) return "未知";
+        switch (orderType) {
+            case 1: return "故障维修";
+            case 2: return "日常巡检";
+            case 3: return "设备保养";
+            default: return "未知";
+        }
+    }
+
+    private String format(Date value) {
+        return value == null ? null : TIME_FORMATTER.format(value.toInstant().atZone(ZoneId.of("Asia/Shanghai")));
+    }
+}

+ 20 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderEventAssociation.java

@@ -0,0 +1,20 @@
+package com.zksy.cockpit.workorder;
+
+public class CockpitWorkOrderEventAssociation {
+    private final String eventSource;
+    private final String eventCode;
+    private final String associatedAt;
+
+    public CockpitWorkOrderEventAssociation(
+            String eventSource,
+            String eventCode,
+            String associatedAt) {
+        this.eventSource = eventSource;
+        this.eventCode = eventCode;
+        this.associatedAt = associatedAt;
+    }
+
+    public String getEventSource() { return eventSource; }
+    public String getEventCode() { return eventCode; }
+    public String getAssociatedAt() { return associatedAt; }
+}

+ 9 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadAdapter.java

@@ -0,0 +1,9 @@
+package com.zksy.cockpit.workorder;
+
+public interface CockpitWorkOrderReadAdapter {
+    CockpitWorkOrderReadSnapshot loadByDevice(String deviceCode);
+
+    CockpitWorkOrderReadSnapshot loadByEvent(String eventSource, String eventCode);
+
+    CockpitWorkOrderTimelineSnapshot loadTimeline(String workOrderCode);
+}

+ 50 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadResponse.java

@@ -0,0 +1,50 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.List;
+
+public class CockpitWorkOrderReadResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String deviceCode;
+    private final String eventSource;
+    private final String eventCode;
+    private final String state;
+    private final String stateReason;
+    private final List<CockpitWorkOrderState> stateDictionary;
+    private final List<CockpitWorkOrderSummary> workOrders;
+
+    public CockpitWorkOrderReadResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String deviceCode,
+            String eventSource,
+            String eventCode,
+            String state,
+            String stateReason,
+            List<CockpitWorkOrderState> stateDictionary,
+            List<CockpitWorkOrderSummary> workOrders) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.deviceCode = deviceCode;
+        this.eventSource = eventSource;
+        this.eventCode = eventCode;
+        this.state = state;
+        this.stateReason = stateReason;
+        this.stateDictionary = stateDictionary;
+        this.workOrders = workOrders;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getEventSource() { return eventSource; }
+    public String getEventCode() { return eventCode; }
+    public String getState() { return state; }
+    public String getStateReason() { return stateReason; }
+    public List<CockpitWorkOrderState> getStateDictionary() { return stateDictionary; }
+    public List<CockpitWorkOrderSummary> getWorkOrders() { return workOrders; }
+}

+ 119 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadService.java

@@ -0,0 +1,119 @@
+package com.zksy.cockpit.workorder;
+
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitErrorCategory;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import org.springframework.stereotype.Service;
+
+import java.time.Clock;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@Service
+public class CockpitWorkOrderReadService {
+    private static final List<String> VALID_EVENT_SOURCES = Arrays.asList("ALARM", "WARNING");
+
+    private final CockpitWorkOrderReadAdapter adapter;
+    private final Clock clock;
+
+    public CockpitWorkOrderReadService(CockpitWorkOrderReadAdapter adapter, Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public CockpitWorkOrderReadResponse loadByDevice(String requestId, String deviceCode) {
+        validateCode(deviceCode, "device code is required");
+        CockpitWorkOrderReadSnapshot snapshot = adapter.loadByDevice(deviceCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+        return response(requestId, snapshot);
+    }
+
+    public CockpitWorkOrderReadResponse loadByEvent(
+            String requestId,
+            String eventSource,
+            String eventCode) {
+        if (eventSource == null || !VALID_EVENT_SOURCES.contains(eventSource.trim())) {
+            throw new CockpitInvalidRequestException("event source must be ALARM or WARNING");
+        }
+        validateCode(eventCode, "event code is required");
+        CockpitWorkOrderReadSnapshot snapshot = adapter.loadByEvent(
+                eventSource.trim(), eventCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("event not found");
+        }
+        return response(requestId, snapshot);
+    }
+
+    public CockpitWorkOrderTimelineResponse loadTimeline(String requestId, String workOrderCode) {
+        validateCode(workOrderCode, "work order code is required");
+        CockpitWorkOrderTimelineSnapshot snapshot = adapter.loadTimeline(workOrderCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("work order not found");
+        }
+        return timelineResponse(requestId, snapshot);
+    }
+
+    public CockpitErrorPayload invalidRequest(String requestId) {
+        return error(requestId, CockpitErrorCategory.INVALID_REQUEST, "工单查询参数不合法");
+    }
+
+    public CockpitErrorPayload notFound(String requestId) {
+        return error(requestId, CockpitErrorCategory.NOT_FOUND, "工单或关联对象不存在");
+    }
+
+    public CockpitErrorPayload serverError(String requestId) {
+        return error(requestId, CockpitErrorCategory.SERVER_ERROR, "驾驶舱工单数据暂不可用");
+    }
+
+    private CockpitWorkOrderReadResponse response(String requestId, CockpitWorkOrderReadSnapshot snapshot) {
+        List<CockpitWorkOrderSummary> workOrders = snapshot.getWorkOrders() == null
+                ? new ArrayList<>() : snapshot.getWorkOrders();
+        String state = workOrders.isEmpty() ? "EMPTY" : "READY";
+        return new CockpitWorkOrderReadResponse(
+                requestId,
+                "v1",
+                true,
+                snapshot.getDeviceCode(),
+                snapshot.getEventSource(),
+                snapshot.getEventCode(),
+                state,
+                workOrders.isEmpty() ? "NO_WORK_ORDERS" : "READY",
+                CockpitWorkOrderStateDictionary.states(),
+                workOrders);
+    }
+
+    private CockpitWorkOrderTimelineResponse timelineResponse(
+            String requestId,
+            CockpitWorkOrderTimelineSnapshot snapshot) {
+        return new CockpitWorkOrderTimelineResponse(
+                requestId,
+                "v1",
+                true,
+                snapshot.getWorkOrder().getWorkOrderCode(),
+                CockpitWorkOrderStateDictionary.states(),
+                snapshot.getWorkOrder(),
+                snapshot.getTimelineEntries() == null ? new ArrayList<>() : snapshot.getTimelineEntries());
+    }
+
+    private void validateCode(String value, String message) {
+        if (value == null || value.trim().isEmpty()) {
+            throw new CockpitInvalidRequestException(message);
+        }
+    }
+
+    private CockpitErrorPayload error(String requestId, CockpitErrorCategory category, String message) {
+        return new CockpitErrorPayload(
+                category,
+                message,
+                requestId,
+                DateTimeFormatter.ISO_OFFSET_DATE_TIME
+                        .format(clock.instant().atZone(ZoneId.of("Asia/Shanghai"))));
+    }
+}

+ 26 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderReadSnapshot.java

@@ -0,0 +1,26 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.List;
+
+public class CockpitWorkOrderReadSnapshot {
+    private final String deviceCode;
+    private final String eventSource;
+    private final String eventCode;
+    private final List<CockpitWorkOrderSummary> workOrders;
+
+    public CockpitWorkOrderReadSnapshot(
+            String deviceCode,
+            String eventSource,
+            String eventCode,
+            List<CockpitWorkOrderSummary> workOrders) {
+        this.deviceCode = deviceCode;
+        this.eventSource = eventSource;
+        this.eventCode = eventCode;
+        this.workOrders = workOrders;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getEventSource() { return eventSource; }
+    public String getEventCode() { return eventCode; }
+    public List<CockpitWorkOrderSummary> getWorkOrders() { return workOrders; }
+}

+ 14 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderState.java

@@ -0,0 +1,14 @@
+package com.zksy.cockpit.workorder;
+
+public class CockpitWorkOrderState {
+    private final int code;
+    private final String name;
+
+    public CockpitWorkOrderState(int code, String name) {
+        this.code = code;
+        this.name = name;
+    }
+
+    public int getCode() { return code; }
+    public String getName() { return name; }
+}

+ 49 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderStateDictionary.java

@@ -0,0 +1,49 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public final class CockpitWorkOrderStateDictionary {
+    private static final List<CockpitWorkOrderState> STATES = Collections.unmodifiableList(Arrays.asList(
+            new CockpitWorkOrderState(1, "待派单"),
+            new CockpitWorkOrderState(2, "待接单"),
+            new CockpitWorkOrderState(3, "已接单"),
+            new CockpitWorkOrderState(4, "处理中"),
+            new CockpitWorkOrderState(5, "待验收"),
+            new CockpitWorkOrderState(6, "已结案"),
+            new CockpitWorkOrderState(7, "已取消")
+    ));
+
+    private static final Map<Integer, CockpitWorkOrderState> BY_CODE = new HashMap<>();
+
+    static {
+        for (CockpitWorkOrderState state : STATES) {
+            BY_CODE.put(state.getCode(), state);
+        }
+    }
+
+    private CockpitWorkOrderStateDictionary() {
+    }
+
+    public static List<CockpitWorkOrderState> states() {
+        return STATES;
+    }
+
+    public static CockpitWorkOrderState byCode(Integer code) {
+        return code == null ? null : BY_CODE.get(code);
+    }
+
+    public static CockpitWorkOrderState byLegacyCode(Integer legacyCode) {
+        // 迁移期兼容:现网旧编码 1-6 与新模型同值;旧 7 为取消/驳回混用,收敛为“已取消”。
+        if (legacyCode == null) {
+            return null;
+        }
+        if (legacyCode >= 1 && legacyCode <= 7) {
+            return BY_CODE.get(legacyCode);
+        }
+        return BY_CODE.get(7);
+    }
+}

+ 60 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderSummary.java

@@ -0,0 +1,60 @@
+package com.zksy.cockpit.workorder;
+
+public class CockpitWorkOrderSummary {
+    private final String workOrderCode;
+    private final String deviceCode;
+    private final Integer orderType;
+    private final String orderTypeName;
+    private final Integer orderLevel;
+    private final String orderDesc;
+    private final Integer stateCode;
+    private final String stateName;
+    private final String createTime;
+    private final String updateTime;
+    private final String planFinishTime;
+    private final String realFinishTime;
+    private final CockpitWorkOrderEventAssociation eventAssociation;
+
+    public CockpitWorkOrderSummary(
+            String workOrderCode,
+            String deviceCode,
+            Integer orderType,
+            String orderTypeName,
+            Integer orderLevel,
+            String orderDesc,
+            Integer stateCode,
+            String stateName,
+            String createTime,
+            String updateTime,
+            String planFinishTime,
+            String realFinishTime,
+            CockpitWorkOrderEventAssociation eventAssociation) {
+        this.workOrderCode = workOrderCode;
+        this.deviceCode = deviceCode;
+        this.orderType = orderType;
+        this.orderTypeName = orderTypeName;
+        this.orderLevel = orderLevel;
+        this.orderDesc = orderDesc;
+        this.stateCode = stateCode;
+        this.stateName = stateName;
+        this.createTime = createTime;
+        this.updateTime = updateTime;
+        this.planFinishTime = planFinishTime;
+        this.realFinishTime = realFinishTime;
+        this.eventAssociation = eventAssociation;
+    }
+
+    public String getWorkOrderCode() { return workOrderCode; }
+    public String getDeviceCode() { return deviceCode; }
+    public Integer getOrderType() { return orderType; }
+    public String getOrderTypeName() { return orderTypeName; }
+    public Integer getOrderLevel() { return orderLevel; }
+    public String getOrderDesc() { return orderDesc; }
+    public Integer getStateCode() { return stateCode; }
+    public String getStateName() { return stateName; }
+    public String getCreateTime() { return createTime; }
+    public String getUpdateTime() { return updateTime; }
+    public String getPlanFinishTime() { return planFinishTime; }
+    public String getRealFinishTime() { return realFinishTime; }
+    public CockpitWorkOrderEventAssociation getEventAssociation() { return eventAssociation; }
+}

+ 40 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineEntry.java

@@ -0,0 +1,40 @@
+package com.zksy.cockpit.workorder;
+
+public class CockpitWorkOrderTimelineEntry {
+    private final Long logId;
+    private final String workOrderCode;
+    private final Integer stateCode;
+    private final String stateName;
+    private final String operationName;
+    private final String operationDesc;
+    private final String operatorName;
+    private final String operatedAt;
+
+    public CockpitWorkOrderTimelineEntry(
+            Long logId,
+            String workOrderCode,
+            Integer stateCode,
+            String stateName,
+            String operationName,
+            String operationDesc,
+            String operatorName,
+            String operatedAt) {
+        this.logId = logId;
+        this.workOrderCode = workOrderCode;
+        this.stateCode = stateCode;
+        this.stateName = stateName;
+        this.operationName = operationName;
+        this.operationDesc = operationDesc;
+        this.operatorName = operatorName;
+        this.operatedAt = operatedAt;
+    }
+
+    public Long getLogId() { return logId; }
+    public String getWorkOrderCode() { return workOrderCode; }
+    public Integer getStateCode() { return stateCode; }
+    public String getStateName() { return stateName; }
+    public String getOperationName() { return operationName; }
+    public String getOperationDesc() { return operationDesc; }
+    public String getOperatorName() { return operatorName; }
+    public String getOperatedAt() { return operatedAt; }
+}

+ 38 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineResponse.java

@@ -0,0 +1,38 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.List;
+
+public class CockpitWorkOrderTimelineResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String workOrderCode;
+    private final List<CockpitWorkOrderState> stateDictionary;
+    private final CockpitWorkOrderSummary workOrder;
+    private final List<CockpitWorkOrderTimelineEntry> timelineEntries;
+
+    public CockpitWorkOrderTimelineResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String workOrderCode,
+            List<CockpitWorkOrderState> stateDictionary,
+            CockpitWorkOrderSummary workOrder,
+            List<CockpitWorkOrderTimelineEntry> timelineEntries) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.workOrderCode = workOrderCode;
+        this.stateDictionary = stateDictionary;
+        this.workOrder = workOrder;
+        this.timelineEntries = timelineEntries;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getWorkOrderCode() { return workOrderCode; }
+    public List<CockpitWorkOrderState> getStateDictionary() { return stateDictionary; }
+    public CockpitWorkOrderSummary getWorkOrder() { return workOrder; }
+    public List<CockpitWorkOrderTimelineEntry> getTimelineEntries() { return timelineEntries; }
+}

+ 18 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderTimelineSnapshot.java

@@ -0,0 +1,18 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.List;
+
+public class CockpitWorkOrderTimelineSnapshot {
+    private final CockpitWorkOrderSummary workOrder;
+    private final List<CockpitWorkOrderTimelineEntry> timelineEntries;
+
+    public CockpitWorkOrderTimelineSnapshot(
+            CockpitWorkOrderSummary workOrder,
+            List<CockpitWorkOrderTimelineEntry> timelineEntries) {
+        this.workOrder = workOrder;
+        this.timelineEntries = timelineEntries;
+    }
+
+    public CockpitWorkOrderSummary getWorkOrder() { return workOrder; }
+    public List<CockpitWorkOrderTimelineEntry> getTimelineEntries() { return timelineEntries; }
+}

+ 21 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/EmptyCockpitWorkOrderReadAdapter.java

@@ -0,0 +1,21 @@
+package com.zksy.cockpit.workorder;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class EmptyCockpitWorkOrderReadAdapter implements CockpitWorkOrderReadAdapter {
+    @Override
+    public CockpitWorkOrderReadSnapshot loadByDevice(String deviceCode) {
+        return null;
+    }
+
+    @Override
+    public CockpitWorkOrderReadSnapshot loadByEvent(String eventSource, String eventCode) {
+        return null;
+    }
+
+    @Override
+    public CockpitWorkOrderTimelineSnapshot loadTimeline(String workOrderCode) {
+        return null;
+    }
+}

+ 24 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/base/service/impl/WaterSupplyDeviceServiceImplTest.java

@@ -32,6 +32,7 @@ import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
 import org.springframework.test.util.ReflectionTestUtils;
 
+import java.math.BigDecimal;
 import java.time.LocalDateTime;
 import java.util.Arrays;
 import java.util.Collections;
@@ -450,6 +451,29 @@ class WaterSupplyDeviceServiceImplTest {
                 .collect(Collectors.toList()));
     }
 
+    @Test
+    void deviceGisPointsIncludeWaterOnlyWithCoordinatesAndStatuses() {
+        pressureDevice.setLongitude(new BigDecimal("113.28000000"));
+        pressureDevice.setLatitude(new BigDecimal("23.12000000"));
+        gasDevice.setLongitude(new BigDecimal("113.32000000"));
+        gasDevice.setLatitude(new BigDecimal("23.16000000"));
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        when(equipmentTypeMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(
+                type("water-pressure", "压力监测", "water-root")));
+
+        List<DeviceGisVO> points = service.getAllDeviceGisPoints(null);
+
+        assertEquals(Collections.singletonList("water-pressure-1"), points.stream()
+                .map(DeviceGisVO::getEquipmentId)
+                .collect(Collectors.toList()));
+        assertEquals("压力监测", points.get(0).getEquipmentTypeName());
+        assertEquals(1, points.get(0).getOnlineStatus());
+        assertEquals(1, points.get(0).getAlarmStatus());
+        assertEquals(1, points.get(0).getCurrentStatus());
+        assertEquals(new BigDecimal("113.28000000"), points.get(0).getLongitude());
+    }
+
     @Test
     void deviceDetailIncludesAlarmAndRelatedWorkOrderSummary() {
         doReturn(pressureDevice).when(service).getById(pressureDevice.getEquipmentId());