Просмотр исходного кода

Merge remote-tracking branch 'origin/master'

zengy 2 месяцев назад
Родитель
Сommit
ba901f56e4
83 измененных файлов с 7389 добавлено и 2879 удалено
  1. 137 0
      docs/cockpit/equipment-archive-demo.html
  2. 112 0
      docs/cockpit/event-read-demo.html
  3. 145 0
      docs/cockpit/type-metrics-demo.html
  4. 10 2
      environment-service/src/main/java/com/zksy/environment/config/RSServerService.java
  5. 13 5
      firefighting-pressure-service/src/main/java/com/zksy/pressure/utils/MessageHandler.java
  6. 26 7
      flammable-gas-service/src/main/java/com/zksy/gas/utils/MessageHandler.java
  7. 1273 2511
      logs/pipe-network-service/spring.log
  8. 31 26
      manhole-service/src/main/java/com/zksy/manhole/service/impl/ManholeDataServiceImpl.java
  9. 5 1
      manhole-service/src/main/java/com/zksy/manhole/utils/AlarmUtil.java
  10. 43 0
      pipe-network-service/sql/migration_water_supply_device_menu_order.sql
  11. 191 0
      pipe-network-service/sql/water_supply_abnormal_test_data.sql
  12. 145 0
      pipe-network-service/sql/water_supply_device_test_data.sql
  13. 57 6
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceAbnormal/DeviceAbnormalController.java
  14. 61 7
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceLedger/DeviceLedgerController.java
  15. 29 4
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceMaintain/DeviceMaintainController.java
  16. 71 1
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/alarm/AlarmController.java
  17. 4 3
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/alarm/AlarmDataController.java
  18. 30 1
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/alarm/WarningThresholdController.java
  19. 87 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitEquipmentArchiveController.java
  20. 99 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitEventReadController.java
  21. 99 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitTypeMetricsController.java
  22. 7 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/risk/RiskController.java
  23. 156 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/WaterSupply/DeviceAbnormal/DeviceAbnormalControllerTest.java
  24. 50 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/WaterSupply/DeviceLedger/DeviceLedgerControllerTest.java
  25. 223 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitEquipmentArchiveControllerTest.java
  26. 251 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitEventReadControllerTest.java
  27. 272 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitTypeMetricsControllerTest.java
  28. 16 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/MonitorAlarm/service/impl/WaterSupplyAlarmServiceImpl.java
  29. 76 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/export/WaterDeviceAbnormalExportDTO.java
  30. 51 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/export/WaterDeviceLedgerExportDTO.java
  31. 55 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportDTO.java
  32. 126 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportService.java
  33. 8 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/domain/WarningThreshold.java
  34. 3 4
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmDataService.java
  35. 14 3
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/impl/AlarmDataServiceImpl.java
  36. 93 24
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/impl/WarningThresholdServiceImpl.java
  37. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/EquipmentBase.java
  38. 15 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/AbnormalDeviceVO.java
  39. 15 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceDetailVO.java
  40. 3 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceGisVO.java
  41. 22 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceLedgerStatisticsVO.java
  42. 9 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/MaintainOrderVO.java
  43. 4 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/RiskAssessmentService.java
  44. 23 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/WaterSupplyDeviceService.java
  45. 38 9
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/BusinessWorkOrderServiceImpl.java
  46. 75 9
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentBaseServiceImpl.java
  47. 90 15
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/GasDashboardServiceImpl.java
  48. 135 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/RiskAssessmentServiceImpl.java
  49. 602 211
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/WaterSupplyDeviceServiceImpl.java
  50. 36 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchive.java
  51. 5 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveAdapter.java
  52. 40 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveResponse.java
  53. 89 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveService.java
  54. 73 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentArchiveSnapshot.java
  55. 19 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/CockpitEquipmentImage.java
  56. 11 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/equipment/EmptyCockpitEquipmentArchiveAdapter.java
  57. 24 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitAlarmWarningRelation.java
  58. 70 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventAlarm.java
  59. 19 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventLevelColor.java
  60. 14 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadAdapter.java
  61. 78 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadResponse.java
  62. 170 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadService.java
  63. 38 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventSnapshot.java
  64. 58 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventWarning.java
  65. 23 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/EmptyCockpitEventReadAdapter.java
  66. 7 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/foundation/CockpitDeviceNotFoundException.java
  67. 43 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetric.java
  68. 22 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetricPoint.java
  69. 55 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetricSnapshot.java
  70. 14 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsAdapter.java
  71. 70 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsResponse.java
  72. 247 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsService.java
  73. 38 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsSnapshot.java
  74. 23 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/EmptyCockpitTypeMetricsAdapter.java
  75. 3 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/domain/DrainagePartition.java
  76. 5 2
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/DrainageWarningServiceImpl.java
  77. 2 2
      pipe-network-service/zksy-system/src/main/resources/mapper/WaterSupply/WaterSupplyGisMap/WaterSupplyGisMapMapper.xml
  78. 4 1
      pipe-network-service/zksy-system/src/main/resources/mapper/system/SysUserMapper.xml
  79. 91 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportServiceTest.java
  80. 62 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/service/impl/BusinessWorkOrderServiceImplTest.java
  81. 797 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/service/impl/WaterSupplyDeviceServiceImplTest.java
  82. 17 12
      radar-service/src/main/java/com/zksy/radar/utils/MessageHandler.java
  83. 17 12
      water-level-service/src/main/java/com/zksy/water/utils/MessageHandler.java

+ 137 - 0
docs/cockpit/equipment-archive-demo.html

@@ -0,0 +1,137 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Equipment Archive 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; }
+    .layout { display:grid; grid-template-columns:minmax(0,1fr) 340px; gap:18px; align-items:start; }
+    table { width:100%; border-collapse:collapse; }
+    th,td { border:1px solid #275b74; padding:8px; text-align:left; vertical-align:top; }
+    th { background:#123247; width:180px; }
+    td.mono { font-family:Consolas,monospace; }
+    .image-panel, .missing { background:#0b1922; border:1px solid #275b74; padding:12px; }
+    img { display:block; width:100%; height:180px; object-fit:cover; border:1px solid #2f7098; background:#071019; }
+    .image-meta { margin:10px 0 0; color:#8fb3c7; font-size:13px; overflow-wrap:anywhere; }
+    .missing { display:grid; place-items:center; min-height:180px; color:#a9b7c0; text-align:center; }
+    .note { color:#8fb3c7; font-size:13px; }
+    pre { max-height:300px; overflow:auto; background:#071019; border:1px solid #275b74; padding:12px; }
+  </style>
+</head>
+<body>
+<main>
+  <header>
+    <h1>驾驶舱设备基础档案演示</h1>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/archive</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="noImage">无图片</button>
+      <button type="button" data-mode="loadFailure">加载失败</button>
+    </div>
+    <div id="detail">
+      <div class="layout">
+        <div><h2>基础档案</h2><table><tbody id="archive"></tbody></table></div>
+        <div><h2>最新图片</h2><div id="image"></div></div>
+      </div>
+    </div>
+    <div id="error" hidden>
+      <h2 id="error-title"></h2>
+      <pre id="error-payload"></pre>
+    </div>
+  </section>
+  <section>
+    <h2>响应契约</h2>
+    <p class="note">坐标字段以 WGS84 发布;缺失档案字段显示“未提供”,无图片返回 latestImage 空值,加载失败使用 typed error。</p>
+    <pre id="payload"></pre>
+  </section>
+</main>
+<script>
+  var fields = [
+    ['deviceCode','设备编码'],['deviceName','设备名称'],['deviceModel','设备型号'],['deviceSpec','设备规格参数'],
+    ['manufacturer','设备制造商'],['productionDate','设备生产日期'],['deviceType','设备类别'],['deviceTypeName','类别名称'],
+    ['assetValue','设备资产价值(元)'],['expectedServiceYears','预计使用年限(年)'],
+    ['longitude','经度'],['latitude','纬度'],['coordinateSystem','坐标系'],
+    ['equipmentLocation','设备位置描述'],['installTime','安装时间'],
+    ['maintainer','设备维护人员'],['maintainerPhone','联系方式'],
+    ['ownershipUnit','权属单位'],['remark','备注信息']
+  ];
+  var image = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180"><rect width="100%" height="100%" fill="#123247"/><text x="50%" y="50%" fill="#dff2ff" text-anchor="middle" font-family="sans-serif">设备现场图</text></svg>';
+  var responses = {
+    full: response('TC-PS-YS-202609020012', {
+      deviceName:'污水管网环境监测设备', deviceModel:'WS-PRO-2000',
+      deviceSpec:'悬浮物/COD/氨氮/电导率/PH', manufacturer:'沅陵专用仪表厂',
+      productionDate:'2025-12-01', deviceType:'ws_sewage_environment', deviceTypeName:'污水环境监测设备',
+      assetValue:128000, expectedServiceYears:10, longitude:110.141, latitude:28.452, coordinateSystem:'WGS84',
+      equipmentLocation:'沅陵县太常片区污水干管检查井', installTime:'2026-01-10 09:30:00',
+      maintainer:'张维护', maintainerPhone:'13800000000', ownershipUnit:'沅陵县排水管理所',
+      remark:'监测点首选查看设备',
+      latestImage:{ url:image, capturedAt:'2026-08-30T10:20:00+08:00' }
+    }),
+    partial: response('TC-GS-202609020015', {
+      deviceName:'燃气压力监测设备', deviceModel:null, deviceSpec:'压力',
+      manufacturer:'沅陵专用仪表厂', productionDate:'2025-11-10', deviceType:'gs_pressure', deviceTypeName:'燃气压力设备',
+      assetValue:null, expectedServiceYears:8, longitude:110.151, latitude:28.462, coordinateSystem:'WGS84',
+      equipmentLocation:'沅陵县太常片区燃气中压管线', installTime:'2026-02-01 14:00:00',
+      maintainer:null, maintainerPhone:null, ownershipUnit:'沅陵县燃气公司', remark:null,
+      latestImage:{ url:image, capturedAt:'2026-08-29T16:40:00+08:00' }
+    }),
+    noImage: response('TC-PS-WS-202609020016', {
+      deviceName:'泵站液位监测设备', deviceModel:'LEVEL-300', deviceSpec:'液位/温度',
+      manufacturer:'沅陵专用仪表厂', productionDate:'2025-10-01', deviceType:'ps_level', deviceTypeName:'泵站液位设备',
+      assetValue:66000, expectedServiceYears:10, longitude:110.161, latitude:28.472, coordinateSystem:'WGS84',
+      equipmentLocation:'沅陵县太常片区泵站', installTime:'2026-03-01 08:00:00',
+      maintainer:'李巡检', maintainerPhone:'13900000000', ownershipUnit:'沅陵县排水管理所', remark:'演示无图片状态',
+      latestImage:null
+    }),
+    loadFailure: {
+      code:500, msg:'驾驶舱设备档案数据暂不可用',
+      data:{ category:'SERVER_ERROR', message:'驾驶舱设备档案数据暂不可用', requestId:'equipment-archive-demo-500', serverTime:'2026-09-02T10:00:00+08:00' }
+    }
+  };
+  function response(code, archive) {
+    return { code:200, msg:'操作成功', data:Object.assign({
+      requestId:'equipment-archive-demo-' + code, apiVersion:'v1', readOnly:true
+    }, archive) };
+  }
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(function(button) {
+      button.classList.toggle('active', button.dataset.mode === mode);
+    });
+    var payload = responses[mode];
+    var success = payload.code === 200;
+    document.getElementById('detail').hidden = !success;
+    document.getElementById('error').hidden = success;
+    if (success) {
+      var data = payload.data;
+      document.getElementById('archive').innerHTML = fields.map(function(field) {
+        var value = data[field[0]];
+        return '<tr><th>' + field[1] + '</th><td class="mono">' + (value === null || value === undefined ? '<span class="note">未提供</span>' : value) + '</td></tr>';
+      }).join('');
+      var latest = data.latestImage;
+      document.getElementById('image').innerHTML = latest
+        ? '<div class="image-panel"><img alt="设备最新图片" src="' + latest.url + '" /><p class="image-meta">' + latest.capturedAt + '<br />' + latest.url + '</p></div>'
+        : '<div class="missing">无设备图片</div>';
+    } else {
+      document.getElementById('error-title').textContent = 'HTTP ' + payload.code + ':' + payload.msg;
+      document.getElementById('error-payload').textContent = JSON.stringify(payload, null, 2);
+    }
+    document.getElementById('payload').textContent = JSON.stringify(payload, null, 2);
+  }
+  document.querySelectorAll('button[data-mode]').forEach(function(button) {
+    button.addEventListener('click', function() { render(button.dataset.mode); });
+  });
+  render('full');
+</script>
+</body>
+</html>

+ 112 - 0
docs/cockpit/event-read-demo.html

@@ -0,0 +1,112 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Warning/Alarm Read Model Demo</title>
+  <style>
+    body { margin:0; min-height:100vh; background:#08131f; color:#e8f1f8; font:15px/1.5 "Microsoft YaHei",sans-serif; }
+    main { width:min(1240px,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; }
+    .layout { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; align-items:start; }
+    .family { border:1px solid #275b74; background:#0b1922; padding:14px; }
+    .family.warning { border-color:#f2c94c; } .family.alarm { border-color:#ff7a7a; }
+    .event { border:1px solid #2f7098; background:#0e1e2d; padding:12px; margin-top:10px; }
+    .title { display:flex; justify-content:space-between; gap:8px; align-items:flex-start; }
+    .name { font-weight:700; } .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; }
+    .RED { color:#ff7a7a; border-color:#ff7a7a; } .YELLOW { color:#f2c94c; border-color:#f2c94c; }
+    .BLUE { color:#61c2ff; border-color:#61c2ff; } .GREEN { color:#68d095; border-color:#68d095; } .UNKNOWN { color:#a9b7c0; border-color:#a9b7c0; }
+    .meta { margin:8px 0 0; color:#8fb3c7; font-size:13px; } .value { font-size:22px; font-weight:700; margin-top:6px; }
+    .value small { font-size:13px; color:#8fb3c7; font-weight:400; margin-left:4px; }
+    .relation { margin-top:12px; border:1px dashed #f2c94c; background:#101a24; padding:12px; }
+    .empty { color:#a9b7c0; margin-top:10px; } .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}/events/current</p>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/events/history?startTime=&amp;endTime=&amp;page=1&amp;pageSize=100</p>
+  </header>
+  <section>
+    <div class="toolbar">
+      <button type="button" data-mode="warning" class="active">独立预警</button>
+      <button type="button" data-mode="alarm">独立报警</button>
+      <button type="button" data-mode="upgraded">预警升级为报警</button>
+    </div>
+    <div class="layout">
+      <div id="warning-family" class="family warning">
+        <h2>预警区域</h2><div id="warnings"></div>
+      </div>
+      <div id="alarm-family" class="family alarm">
+        <h2>报警区域</h2><div id="alarms"></div>
+      </div>
+    </div>
+    <div id="relation-panel"></div>
+  </section>
+  <section>
+    <h2>响应契约</h2>
+    <p class="note">预警与报警始终是两个事件族;alarmWarningRelations 只显示后端关联表给出的权威关系,前端不做真伪判断或时间戳推断。</p>
+    <pre id="payload" class="mono"></pre>
+  </section>
+</main>
+<script>
+  const response = (warnings, alarms, relations) => ({
+    code:200, msg:'操作成功', data:{
+      requestId:'event-read-demo', apiVersion:'v1', readOnly:true,
+      deviceCode:'TC-PS-WS-202609020012', deviceType:'ws_sewage_environment', deviceTypeName:'污水环境监测设备',
+      state: warnings.length || alarms.length ? 'READY' : 'EMPTY', stateReason: warnings.length || alarms.length ? 'READY' : 'NO_EVENTS',
+      warnings, alarms, alarmWarningRelations:relations, startTime:null, endTime:null,
+      timezone:'Asia/Shanghai', page:1, pageSize:0, total:warnings.length + alarms.length
+    }
+  });
+  const warning = (no, level, color, status, value, time) => ({ warningNo:no, warningName:'污水COD预警', warningType:'WS_ENV',
+    level, levelColor:color, status, eventTime:time, value, unit:'mg/L', deviceCode:'TC-PS-WS-202609020012',
+    deviceName:'污水环境监测设备', location:'太常片区' });
+  const alarm = (id, level, color, status, value, time) => ({ alarmId:id, warningCode:'WS_ENV_HIGH', warningName:'污水COD报警',
+    warningType:'WS_ENV', level, levelColor:color, status, eventTime:time, value, thresholdMinValue:40, thresholdMaxValue:50,
+    unit:'mg/L', deviceCode:'TC-PS-WS-202609020012', deviceName:'污水环境监测设备', location:'太常片区' });
+  const relation = (warningNo, alarmId) => ({ relationId:'REL-' + warningNo, warningNo, alarmId, relatedAt:'2026-09-02T10:00:00+08:00' });
+  const responses = {
+    warning: response([warning('WRN-20260902-001', 2, 'YELLOW', 'PROCESSING', 18.2, '2026-09-02T09:59:30+08:00')], [], []),
+    alarm: response([], [alarm('ALM-20260902-001', 1, 'RED', 'UNHANDLED', 42, '2026-09-02T10:00:00+08:00')], []),
+    upgraded: response(
+      [warning('WRN-20260902-001', 2, 'YELLOW', 'PROCESSING', 18.2, '2026-09-02T09:59:30+08:00')],
+      [alarm('ALM-20260902-001', 1, 'RED', 'UNHANDLED', 42, '2026-09-02T10:00:00+08:00')],
+      [relation('WRN-20260902-001', 'ALM-20260902-001')])
+  };
+  function renderEvent(item, codeField) {
+    return `<article class="event">
+      <div class="title"><div><div class="name">${item.warningName}</div><div class="code">${item[codeField]}</div></div><span class="badge ${item.levelColor}">${item.level} ${item.levelColor}</span></div>
+      <div class="value">${item.value ?? '—'}${item.unit ? '<small>' + item.unit + '</small>' : ''}</div>
+      <p class="meta">状态:${item.status}<br />时间:${item.eventTime}<br />设备:${item.deviceCode}</p>
+    </article>`;
+  }
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
+    const payload = responses[mode], data = payload.data;
+    document.getElementById('warnings').innerHTML = data.warnings.length
+      ? data.warnings.map(item => renderEvent(item, 'warningNo')).join('')
+      : '<p class="empty">本状态下没有预警事件。</p>';
+    document.getElementById('alarms').innerHTML = data.alarms.length
+      ? data.alarms.map(item => renderEvent(item, 'alarmId')).join('')
+      : '<p class="empty">本状态下没有报警事件。</p>';
+    document.getElementById('relation-panel').innerHTML = data.alarmWarningRelations.length
+      ? data.alarmWarningRelations.map(item => `<div class="relation"><strong>权威关联:</strong> ${item.warningNo} ⇄ ${item.alarmId}<br /><span class="note">${item.relationId} · ${item.relatedAt}</span></div>`).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('warning');
+</script>
+</body>
+</html>

+ 145 - 0
docs/cockpit/type-metrics-demo.html

@@ -0,0 +1,145 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1" />
+  <title>Cockpit Type Metrics Demo</title>
+  <style>
+    :root { color-scheme: dark; }
+    body { margin:0; min-height:100vh; background:#08131f; color:#e8f1f8; font:15px/1.5 "Microsoft YaHei",sans-serif; }
+    main { width:min(1240px,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; }
+    .state-grid { display:grid; grid-template-columns:repeat(4,minmax(140px,1fr)); gap:10px; margin-bottom:16px; }
+    .state { background:#0b1922; border:1px solid #275b74; padding:10px; }
+    .state strong { display:block; font-size:16px; } .state span { color:#8fb3c7; font-size:13px; }
+    .state.ok strong { color:#68d095; } .state.warning strong { color:#f2c94c; } .state.empty strong { color:#a9b7c0; } .state.error strong { color:#ff7a7a; }
+    .cards { display:grid; grid-template-columns:repeat(auto-fit,minmax(210px,1fr)); gap:12px; }
+    .card { background:#0b1922; border:1px solid #275b74; padding:12px; }
+    .card-top { display:flex; justify-content:space-between; gap:8px; align-items:flex-start; }
+    .metric-name { font-weight:700; } .metric-code { color:#78a2b8; font-family:Consolas,monospace; font-size:12px; }
+    .metric-value { font-size:26px; font-weight:700; margin:8px 0 4px; } .metric-value small { font-size:13px; font-weight:400; color:#8fb3c7; margin-left:4px; }
+    .badge { font-size:12px; padding:3px 8px; border:1px solid; white-space:nowrap; }
+    .normal { color:#68d095; border-color:#68d095; } .warning { color:#f2c94c; border-color:#f2c94c; } .alarm { color:#ff7a7a; border-color:#ff7a7a; }
+    .unknown { color:#a9b7c0; border-color:#a9b7c0; } .fresh { color:#68d095; border-color:#68d095; } .stale { color:#f2c94c; border-color:#f2c94c; }
+    .history { margin-top:10px; } .trend { display:block; width:100%; height:42px; }
+    .mono { font-family:Consolas,monospace; overflow-wrap:anywhere; } .note { color:#8fb3c7; font-size:13px; }
+    pre { max-height:360px; overflow:auto; background:#071019; border:1px solid #275b74; padding:12px; }
+    .missing { display:grid; place-items:center; min-height:220px; border:1px dashed #3f667d; color:#a9b7c0; }
+  </style>
+</head>
+<body>
+<main>
+  <header>
+    <h1>驾驶舱设备类型指标演示</h1>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/metrics/current</p>
+    <p class="endpoint">GET /api/cockpit/v1/equipments/{deviceCode}/metrics/history?startTime=&amp;endTime=&amp;page=1&amp;pageSize=100</p>
+  </header>
+  <section>
+    <div class="toolbar">
+      <button type="button" data-mode="gas" class="active">燃气</button>
+      <button type="button" data-mode="supply">供水</button>
+      <button type="button" data-mode="drainage">排水</button>
+      <button type="button" data-mode="sewage">污水环境</button>
+      <button type="button" data-mode="empty">成功空数据</button>
+      <button type="button" data-mode="stale">过期数据</button>
+      <button type="button" data-mode="failure">加载失败</button>
+    </div>
+    <div id="detail">
+      <div class="state-grid">
+        <div class="state ok"><strong id="state-value">CURRENT</strong><span>响应状态</span></div>
+        <div class="state"><strong id="state-reason">READY</strong><span>状态原因</span></div>
+        <div class="state"><strong id="device-type">-</strong><span>设备类型</span></div>
+        <div class="state"><strong id="read-only">true</strong><span>只读接口</span></div>
+      </div>
+      <h2>指标卡与历史趋势</h2>
+      <div id="metrics" class="cards"></div>
+    </div>
+    <div id="missing" class="missing" hidden><div><strong id="missing-title"></strong><p class="note" id="missing-reason"></p></div></div>
+  </section>
+  <section>
+    <h2>当前响应契约</h2>
+    <p class="note">页面只按接口返回的 metricCode / metricName / unit / points 渲染,不硬编码数据库字段;未知指标保留 UNKNOWN 展示。</p>
+    <pre id="payload" class="mono"></pre>
+  </section>
+</main>
+<script>
+  const demoClock = '2026-09-02T10:00:00+08:00';
+  const current = (deviceCode, deviceType, deviceTypeName, metrics, state='CURRENT', reason='READY') => ({
+    code:200, msg:'操作成功', data:{ requestId:'type-metrics-demo-' + deviceCode, apiVersion:'v1', readOnly:true,
+      deviceCode, deviceType, deviceTypeName, state, stateReason:reason, metrics, startTime:null, endTime:null,
+      timezone:'Asia/Shanghai', page:1, pageSize:0, total:0 }
+  });
+  const point = (value, sampledAt, status='NORMAL') => ({ value, status, sampledAt, freshness:'HISTORICAL' });
+  const metric = (code, name, value, unit, status, sampledAt, points=[]) => ({ metricCode:code, metricName:name, value, unit, status, sampledAt, freshness:'CURRENT', points });
+  const responses = {
+    gas: current('TC-RQ-202609020001', 'gas_pressure', '燃气压力计', [
+      metric('PRESSURE', '管道压力', 0.36, 'MPa', 'NORMAL', '2026-09-02T09:59:40+08:00', [point(.38,'09:40'),point(.37,'09:50'),point(.36,'10:00')]),
+      metric('TEMPERATURE', '介质温度', 23.4, '℃', 'NORMAL', '2026-09-02T09:59:40+08:00')
+    ]),
+    supply: current('TC-GS-202609020005', 'gs_pressure', '供水压力计', [
+      metric('PRESSURE', '供水压力', 0.29, 'MPa', 'NORMAL', '2026-09-02T09:59:45+08:00'),
+      metric('FLOW', '瞬时流量', 42.7, 'm³/h', 'WARNING', '2026-09-02T09:59:45+08:00')
+    ]),
+    drainage: current('TC-PS-YS-202609020009', 'ws_rainflow', '雨水流量计', [
+      metric('FLOW', '雨水流量', 138.2, 'L/s', 'NORMAL', '2026-09-02T09:59:50+08:00'),
+      metric('LIQUID_LEVEL', '液位', 1.18, 'm', 'NORMAL', '2026-09-02T09:59:50+08:00')
+    ]),
+    sewage: current('TC-PS-WS-202609020012', 'ws_sewage_environment', '污水环境监测设备', [
+      metric('SUSPENDED_SOLIDS', '悬浮物', 12.5, 'mg/L', 'NORMAL', '2026-09-02T09:59:30+08:00'),
+      metric('COD', 'COD', 18.2, 'mg/L', 'WARNING', '2026-09-02T09:59:30+08:00'),
+      metric('AMMONIA_NITROGEN', '氨氮', 0.8, 'mg/L', 'NORMAL', '2026-09-02T09:59:30+08:00'),
+      metric('CONDUCTIVITY', '电导率', 780, 'μS/cm', 'NORMAL', '2026-09-02T09:59:30+08:00'),
+      metric('PH', 'pH', 7.2, '', 'NORMAL', '2026-09-02T09:59:30+08:00'),
+      metric('UNKNOWN', '厂商私有参数', 1, '', 'UNKNOWN', '2026-09-02T09:59:30+08:00')
+    ]),
+    empty: current('TC-RQ-202609020021', 'gas_pressure', '燃气压力计', [], 'EMPTY', 'NO_METRICS'),
+    stale: current('TC-GS-202609020022', 'gs_pressure', '供水压力计', [
+      metric('PRESSURE', '供水压力', 0.31, 'MPa', 'NORMAL', '2026-09-02T09:58:00+08:00')
+    ], 'STALE', 'SAMPLE_OUTDATED'),
+    failure: { code:500, msg:'驾驶舱设备指标数据暂不可用', data:{ category:'SERVER_ERROR', message:'驾驶舱设备指标数据暂不可用', requestId:'type-metrics-demo-500', serverTime:demoClock } }
+  };
+  responses.stale.data.metrics[0].freshness = 'STALE';
+  function trend(points) {
+    if (!points || points.length < 2) return '<div class="note history">暂无历史序列</div>';
+    const values = points.map(item => item.value);
+    const min = Math.min(...values), max = Math.max(...values);
+    const range = max === min ? 1 : max - min;
+    const coords = points.map((item, index) => (10 + index * 80 / (points.length - 1)).toFixed(1) + ',' + (36 - (item.value - min) / range * 28).toFixed(1)).join(' ');
+    return '<svg class="trend history" viewBox="0 0 100 42" preserveAspectRatio="none"><polyline points="' + coords + '" fill="none" stroke="#61c2ff" stroke-width="2" /></svg>';
+  }
+  function render(mode) {
+    document.querySelectorAll('button[data-mode]').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
+    const payload = responses[mode], success = payload.code === 200;
+    document.getElementById('detail').hidden = !success;
+    document.getElementById('missing').hidden = success;
+    document.getElementById('payload').textContent = JSON.stringify(payload, null, 2);
+    if (!success) {
+      document.getElementById('missing-title').textContent = 'HTTP ' + payload.code + ':' + payload.msg;
+      document.getElementById('missing-reason').textContent = '失败状态独立展示,不与空数据或过期数据混淆。';
+      return;
+    }
+    const data = payload.data;
+    document.getElementById('state-value').textContent = data.state;
+    document.getElementById('state-reason').textContent = data.stateReason;
+    document.getElementById('device-type').textContent = data.deviceType;
+    document.getElementById('read-only').textContent = data.readOnly;
+    document.getElementById('metrics').innerHTML = data.metrics.map(item => `
+      <article class="card">
+        <div class="card-top">
+          <div><div class="metric-name">${item.metricName}</div><div class="metric-code">${item.metricCode}</div></div>
+          <div><span class="badge ${String(item.status).toLowerCase()}">${item.status || '-'}</span><span class="badge ${item.freshness === 'STALE' ? 'stale' : 'fresh'}">${item.freshness}</span></div>
+        </div>
+        <div class="metric-value">${item.value ?? '—'}${item.unit ? '<small>' + item.unit + '</small>' : ''}</div>
+        ${trend(item.points)}
+      </article>`).join('');
+  }
+  document.querySelectorAll('button[data-mode]').forEach(button => button.addEventListener('click', () => render(button.dataset.mode)));
+  render('gas');
+</script>
+</body>
+</html>

+ 10 - 2
environment-service/src/main/java/com/zksy/environment/config/RSServerService.java

@@ -134,6 +134,10 @@ public class RSServerService {
 
                 @Override
                 public void receiveRealtimeData(RealTimeData data) {
+                    if (data == null || data.getNodeList() == null) {
+                        log.warn("实时环境数据为空或缺少节点列表,跳过报警状态覆盖");
+                        return;
+                    }
                     String deviceId = String.valueOf(data.getDeviceId());
                     // 更新设备最后接收数据时间,并标记设备在线
                     DeviceOfflineCheckTask.deviceLastReceiveTimeMap.put(deviceId, new Date());
@@ -408,10 +412,14 @@ public class RSServerService {
             headers.setContentType(MediaType.APPLICATION_JSON);
             HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-            restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+                log.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+                return;
+            }
             log.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
         } catch (Exception e) {
             log.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
         }
     }
-}
+}

+ 13 - 5
firefighting-pressure-service/src/main/java/com/zksy/pressure/utils/MessageHandler.java

@@ -239,10 +239,11 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 	}
 	//检查是否会触发短信预警
 		public void checkIfSmsAlertNeeded(FirefightingPressure resultData){
+			boolean hasAlarm = false;
+			boolean evaluationCompleted = false;
 			try {
 				//用遥测站地址作为设备的设备编号
 				String deviceId = resultData.getTelemeteringStation();
-				boolean hasAlarm = false;
 
 				//1、获取到压力阈值
 				String warningCode = "WARN-PRESSURE";
@@ -322,10 +323,13 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 					hasAlarm = true;
 				}
 
-				// 同步设备报警状态到 equipment_status 表
-				updateDeviceAlarmStatus(deviceId, hasAlarm ? 1 : 0);
+				evaluationCompleted = true;
 			} catch (Exception e) {
 				log.error("设备报警处理失败", e);
+			} finally {
+				if (evaluationCompleted) {
+					updateDeviceAlarmStatus(resultData.getTelemeteringStation(), hasAlarm ? 1 : 0);
+				}
 			}
 
 		}
@@ -412,10 +416,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 				headers.setContentType(MediaType.APPLICATION_JSON);
 				HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-				restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+					log.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+					return;
+				}
 				log.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
 			} catch (Exception e) {
 				log.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
 			}
 		}
-	}
+	}

+ 26 - 7
flammable-gas-service/src/main/java/com/zksy/gas/utils/MessageHandler.java

@@ -198,9 +198,25 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 		}
 	}
 	public void checkIfSmsAlertNeeded(GasMonitorData resultData){
-        //用MAC地址作为设备的设备编号
-        String deviceId = resultData.getMacAddress();
-        boolean hasAlarm = false;
+		String deviceId = resultData == null ? null : resultData.getMacAddress();
+		try {
+			if (resultData == null || deviceId == null || deviceId.trim().isEmpty()) {
+				log.warn("可燃气体报警数据缺少设备编码,跳过状态覆盖");
+				return;
+			}
+			boolean hasAlarm = evaluateAlarmStatus(resultData);
+			updateDeviceAlarmStatus(deviceId, hasAlarm ? 1 : 0);
+		} catch (Exception e) {
+			// 评估不完整时不覆盖上一状态,避免异常数据误清除报警
+			log.error("可燃气体设备报警处理失败,保留原报警状态:deviceCode={}", deviceId, e);
+		}
+	}
+
+	/** 评估单条采集数据是否存在报警。只有完整评估成功才允许同步设备状态。 */
+	private boolean evaluateAlarmStatus(GasMonitorData resultData){
+	        //用MAC地址作为设备的设备编号
+	        String deviceId = resultData.getMacAddress();
+	        boolean hasAlarm = false;
 
 		//获取温度阈值
 		String temWarningCode = "WARN-GAS-TEMPERATURE";
@@ -390,8 +406,7 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 			hasAlarm = true;
 			}
 
-			// 同步设备报警状态到 equipment_status 表
-			updateDeviceAlarmStatus(deviceId, hasAlarm ? 1 : 0);
+			return hasAlarm;
 		}
 
 		private WarningThreshold checkThreshold(String deviceCode, String warningCode) {
@@ -485,10 +500,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
             headers.setContentType(MediaType.APPLICATION_JSON);
             HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-            restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+                log.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+                return;
+            }
             log.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
         } catch (Exception e) {
             log.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
         }
     }
-}
+}

Разница между файлами не показана из-за своего большого размера
+ 1273 - 2511
logs/pipe-network-service/spring.log


+ 31 - 26
manhole-service/src/main/java/com/zksy/manhole/service/impl/ManholeDataServiceImpl.java

@@ -54,35 +54,40 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
     private void checkAndSaveAlarm(ManholeData result) {
         String deviceCode = result.getImeiCardNumber();
         boolean hasAlarm = false;
+        boolean evaluationCompleted = false;
+        try {
+            // 1. 倾斜角度告警:阈值从采集数据字段 angleAlarmThreshold 获取
+            if (checkTiltAlarm(result, deviceCode)) {
+                hasAlarm = true;
+            }
 
-        // 1. 倾斜角度告警:阈值从采集数据字段 angleAlarmThreshold 获取
-        if (checkTiltAlarm(result, deviceCode)) {
-            hasAlarm = true;
-        }
-
-        // 2. 设备报警状态:告警即为1级
-        if ("1".equals(result.getAlarmStatus())) {
-            alarmUtil.saveAlarmWithLevel(deviceCode, "设备报警", WARN_CODE_DEVICE,
-                    null, 1, "井盖设备状态报警");
-            hasAlarm = true;
-        }
+            // 2. 设备报警状态:告警即为1级
+            if ("1".equals(result.getAlarmStatus())) {
+                alarmUtil.saveAlarmWithLevel(deviceCode, "设备报警", WARN_CODE_DEVICE,
+                        null, 1, "井盖设备状态报警");
+                hasAlarm = true;
+            }
 
-        // 3. 水浸报警状态:告警即为1级
-        if ("1".equals(result.getWaterInfiltrationAlarmStatus())) {
-            alarmUtil.saveAlarmWithLevel(deviceCode, "水浸预警", WARN_CODE_WATER_INFILTRATION,
-                    null, 1, "井盖水浸报警");
-            hasAlarm = true;
-        }
+            // 3. 水浸报警状态:告警即为1级
+            if ("1".equals(result.getWaterInfiltrationAlarmStatus())) {
+                alarmUtil.saveAlarmWithLevel(deviceCode, "水浸预警", WARN_CODE_WATER_INFILTRATION,
+                        null, 1, "井盖水浸报警");
+                hasAlarm = true;
+            }
 
-        // 4. 水位报警状态:告警即为1级
-        if ("1".equals(result.getWaterLevelAlarmStatus())) {
-            alarmUtil.saveAlarmWithLevel(deviceCode, "水位预警", WARN_CODE_WATER_LEVEL,
-                    null, 1, "井盖水位报警");
-            hasAlarm = true;
+            // 4. 水位报警状态:告警即为1级
+            if ("1".equals(result.getWaterLevelAlarmStatus())) {
+                alarmUtil.saveAlarmWithLevel(deviceCode, "水位预警", WARN_CODE_WATER_LEVEL,
+                        null, 1, "井盖水位报警");
+                hasAlarm = true;
+            }
+            evaluationCompleted = true;
+        } finally {
+            // 只有本条数据完整评估成功时才覆盖设备总报警状态;异常时保留上一状态
+            if (evaluationCompleted) {
+                alarmUtil.updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
+            }
         }
-
-        // 5. 同步设备报警状态到 equipment_status 表
-        alarmUtil.updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
     }
 
     /**
@@ -129,4 +134,4 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
             return false;
         }
     }
-}
+}

+ 5 - 1
manhole-service/src/main/java/com/zksy/manhole/utils/AlarmUtil.java

@@ -180,7 +180,11 @@ public class AlarmUtil {
             headers.setContentType(MediaType.APPLICATION_JSON);
             HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-            restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+            if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+                log.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+                return;
+            }
             log.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
         } catch (Exception e) {
             log.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);

+ 43 - 0
pipe-network-service/sql/migration_water_supply_device_menu_order.sql

@@ -0,0 +1,43 @@
+-- 供水设备管理菜单顺序迁移(KingbaseES)
+-- 目的:将“设备异常管理”排在“设备维修派单”之前。
+BEGIN;
+
+DO $$
+DECLARE
+    root_id bigint;
+    device_id bigint;
+BEGIN
+    SELECT menu_id INTO root_id
+      FROM app_user.sys_menu
+     WHERE parent_id = 0
+       AND (path = 'subSystem/waterSupply' OR menu_name = '供水管网安全运行监测系统')
+     ORDER BY menu_id
+     LIMIT 1;
+
+    IF root_id IS NULL THEN
+        RAISE EXCEPTION '供水根菜单不存在,未执行设备菜单顺序调整';
+    END IF;
+
+    SELECT menu_id INTO device_id
+      FROM app_user.sys_menu
+     WHERE parent_id = root_id
+       AND (menu_name = '监测设备管理' OR path IN ('subSystem/waterSupply/device', 'device'))
+     ORDER BY menu_id
+     LIMIT 1;
+
+    IF device_id IS NULL THEN
+        RAISE EXCEPTION '供水设备管理菜单不存在,未执行设备菜单顺序调整';
+    END IF;
+
+    UPDATE app_user.sys_menu
+       SET order_num = 2
+     WHERE parent_id = device_id
+       AND path = 'abnormal';
+
+    UPDATE app_user.sys_menu
+       SET order_num = 3
+     WHERE parent_id = device_id
+       AND path = 'maintain';
+END $$;
+
+COMMIT;

+ 191 - 0
pipe-network-service/sql/water_supply_abnormal_test_data.sql

@@ -0,0 +1,191 @@
+-- ============================================================
+-- 供水管网 设备异常管理页面 测试数据脚本(KingbaseES)
+-- 说明:
+--   1. 测试主键与编号均使用 T6-ABN-TEST- / WO20260905 前缀,可重复执行。
+--   2. 本脚本只初始化测试数据,不创建业务表;执行前请确认以下表已存在:
+--      app_user.equipment_type、app_user.equipment_base、app_user.equipment_status、
+--      app_user.alarm_data、app_user.work_order、app_user.work_order_log
+--   3. 覆盖场景:
+--      a. 有状态记录 + alarm_status=1 + 有效报警 -> 显示。
+--      b. 有状态记录 + current_status=3 + 无有效报警 -> 显示,原因为设备维修中。
+--      c. 无状态记录 + alarm_data.alarm_status=0 -> 显示(验证无状态回退修复)。
+--      d. 无状态记录 + 无报警 -> 不显示。
+--      e. 有状态记录但正常 + 仅存在已处理报警 -> 不显示。
+--      f. 非供水设备 + 报警 -> 不显示。
+-- ============================================================
+
+-- ------------------------------------------------------------
+-- 0. 清理历史测试数据(先清工单日志与工单,再清报警、状态、设备、临时类型)
+-- ------------------------------------------------------------
+DELETE FROM app_user.work_order_log WHERE order_id IN
+    (SELECT order_id FROM app_user.work_order WHERE order_no LIKE 'WO20260905%' AND order_no IN (
+        'WO202609050001', 'WO202609050002', 'WO202609050003'
+    ));
+DELETE FROM app_user.work_order WHERE order_no IN
+    ('WO202609050001', 'WO202609050002', 'WO202609050003');
+DELETE FROM app_user.alarm_data WHERE id LIKE 'T6-ABN-TEST-ALARM-%';
+DELETE FROM app_user.equipment_status WHERE equipment_id LIKE 'T6-ABN-TEST-EQ-%';
+DELETE FROM app_user.equipment_base WHERE equipment_id LIKE 'T6-ABN-TEST-EQ-%';
+DELETE FROM app_user.equipment_type WHERE id = 'T6-ABN-TEST-GAS-TYPE';
+
+-- ------------------------------------------------------------
+-- 1. 校验规范供水设备类型,并创建临时非供水类型用于边界排除
+-- ------------------------------------------------------------
+DO $$
+DECLARE
+    v_count integer;
+BEGIN
+    SELECT count(*) INTO v_count
+      FROM app_user.equipment_type
+     WHERE id = '1' AND parent_type_id = '0' AND type_name = '供水';
+    IF v_count <> 1 THEN
+        RAISE EXCEPTION '缺少规范供水顶级设备类型:id=1,type_name=供水,parent_type_id=0';
+    END IF;
+
+    SELECT count(*) INTO v_count
+      FROM app_user.equipment_type
+     WHERE type_id IN ('ws_flow', 'ws_pressure', 'ws_leak')
+       AND parent_type_id = '1';
+    IF v_count <> 3 THEN
+        RAISE EXCEPTION '缺少规范供水监测子类型:ws_flow/ws_pressure/ws_leak 必须 parent_type_id=1';
+    END IF;
+END $$;
+
+INSERT INTO app_user.equipment_type
+    (id, type_id, type_name, parent_type_id, type_remark)
+VALUES
+    ('T6-ABN-TEST-GAS-TYPE', 't6_abn_test_gas', '燃气(异常页测试)', '0',
+     'T6异常页非供水设备排除测试类型');
+
+-- ------------------------------------------------------------
+-- 2. 设备基础信息(6 台供水设备 + 1 台非供水设备)
+--    注意:T6-ABN-TEST-EQ-NOSTATUS-ALARM 不插入 equipment_status,
+--    专门用于验证 alarm_data.alarm_status=0 的无状态回退判定。
+-- ------------------------------------------------------------
+INSERT INTO app_user.equipment_base
+    (equipment_id, equipment_code, equipment_name, equipment_model, equipment_type_id,
+     longitude, latitude, equipment_location, maintainer, maintainer_phone,
+     ownership_unit, remark, create_time, update_time, del_flag, district)
+VALUES
+    ('T6-ABN-TEST-EQ-ALARM-OPEN', 'CN-GS-202609050001', '异常页测试压力报警设备', 'PRESSURE-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_pressure' AND parent_type_id = '1' LIMIT 1),
+     113.28000000, 23.12000000, '异常页测试大道1号', '异常页测试维护员', '13800000101',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '城南'),
+    ('T6-ABN-TEST-EQ-ALARM-ORDERED', 'CB-GS-202609050002', '异常页测试压力已派单设备', 'PRESSURE-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_pressure' AND parent_type_id = '1' LIMIT 1),
+     113.29000000, 23.13000000, '异常页测试大道2号', '异常页测试维护员', '13800000102',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '城北'),
+    ('T6-ABN-TEST-EQ-REPAIR', 'TC-GS-202609050003', '异常页测试流量维修中设备', 'FLOW-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_flow' AND parent_type_id = '1' LIMIT 1),
+     113.30000000, 23.14000000, '异常页测试大道3号', '异常页测试维护员', '13800000103',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '太常'),
+    ('T6-ABN-TEST-EQ-NOSTATUS-ALARM', 'CN-GS-202609050004', '异常页测试无状态报警设备', 'LEAK-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_leak' AND parent_type_id = '1' LIMIT 1),
+     113.31000000, 23.15000000, '异常页测试大道4号', '异常页测试维护员', '13800000104',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '城南'),
+    ('T6-ABN-TEST-EQ-NORMAL-HIDDEN', 'CB-GS-202609050005', '异常页测试正常隐藏设备', 'FLOW-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_flow' AND parent_type_id = '1' LIMIT 1),
+     113.32000000, 23.16000000, '异常页测试大道5号', '异常页测试维护员', '13800000105',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '城北'),
+    ('T6-ABN-TEST-EQ-NOSTATUS-HIDDEN', 'TC-GS-202609050007', '异常页测试无状态隐藏设备', 'PRESSURE-ABN-TEST',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_pressure' AND parent_type_id = '1' LIMIT 1),
+     113.33000000, 23.17000000, '异常页测试大道7号', '异常页测试维护员', '13800000107',
+     '异常页测试供水公司', '设备异常管理测试数据', now() - interval '7 days', now(), '0', '太常'),
+    ('T6-ABN-TEST-EQ-GAS-EXCLUDED', 'CN-RQ-202609050006', '异常页测试燃气排除设备', 'GAS-ABN-TEST',
+     'T6-ABN-TEST-GAS-TYPE', 113.34000000, 23.18000000, '异常页测试大道6号',
+     '异常页测试维护员', '13800000106', '异常页测试燃气公司', '非供水设备排除测试数据',
+     now() - interval '7 days', now(), '0', '城南');
+
+-- ------------------------------------------------------------
+-- 3. 设备状态
+-- ------------------------------------------------------------
+INSERT INTO app_user.equipment_status
+    (equipment_id, current_status, alarm_status, online_status,
+     installation_addr, status_update_time, create_time, del_flag)
+VALUES
+    ('T6-ABN-TEST-EQ-ALARM-OPEN', 1, 1, 1, '异常页测试大道1号',
+     now() - interval '1 hour', now() - interval '1 hour', '0'),
+    ('T6-ABN-TEST-EQ-ALARM-ORDERED', 1, 1, 1, '异常页测试大道2号',
+     now() - interval '2 hours', now() - interval '2 hours', '0'),
+    ('T6-ABN-TEST-EQ-REPAIR', 3, 0, 1, '异常页测试大道3号',
+     now() - interval '3 hours', now() - interval '3 hours', '0'),
+    ('T6-ABN-TEST-EQ-NORMAL-HIDDEN', 1, 0, 1, '异常页测试大道5号',
+     now() - interval '5 hours', now() - interval '5 hours', '0'),
+    ('T6-ABN-TEST-EQ-GAS-EXCLUDED', 1, 1, 1, '异常页测试大道6号',
+     now() - interval '6 hours', now() - interval '6 hours', '0');
+
+-- ------------------------------------------------------------
+-- 4. 报警数据
+--    alarm_status=0 表示未处置/有效报警;alarm_status=1 表示已处理报警。
+-- ------------------------------------------------------------
+INSERT INTO app_user.alarm_data
+    (id, device_code, device_name, device_type, warning_type, warning_code,
+     min_value, max_value, actual_value, alarm_level, deviation_ratio,
+     alarm_status, alarm_time, handle_time, handle_user, handle_remark, remark,
+     create_time, update_time)
+VALUES
+    ('T6-ABN-TEST-ALARM-OPEN', 'CN-GS-202609050001', '异常页测试压力报警设备', '压力监测',
+     '供水压力超限', 'WARN-ABN-PRESSURE-OPEN', 0.20, 0.80, 1.20, 1, 50.00,
+     0, now() - interval '1 hour', NULL, NULL, NULL, '设备异常管理测试数据',
+     now() - interval '1 hour', now() - interval '1 hour'),
+    ('T6-ABN-TEST-ALARM-ORDERED', 'CB-GS-202609050002', '异常页测试压力已派单设备', '压力监测',
+     '供水压力异常', 'WARN-ABN-PRESSURE-ORDERED', 0.20, 0.80, 0.95, 2, 18.75,
+     0, now() - interval '2 hours', NULL, NULL, NULL, '设备异常管理测试数据',
+     now() - interval '2 hours', now() - interval '2 hours'),
+    ('T6-ABN-TEST-ALARM-NOSTATUS', 'CN-GS-202609050004', '异常页测试无状态报警设备', '漏失监测',
+     '供水漏失异常', 'WARN-ABN-LEAK-NOSTATUS', 0.00, 5.00, 8.00, 3, 60.00,
+     0, now() - interval '3 hours', NULL, NULL, NULL, '设备异常管理测试数据',
+     now() - interval '3 hours', now() - interval '3 hours'),
+    ('T6-ABN-TEST-ALARM-NORMAL-RESOLVED', 'CB-GS-202609050005', '异常页测试正常隐藏设备', '流量监测',
+     '供水流量波动', 'WARN-ABN-FLOW-RESOLVED', 1.00, 10.00, 12.00, 4, 20.00,
+     1, now() - interval '5 hours', now() - interval '4 hours', 'admin', '测试已处理报警',
+     '设备异常管理测试数据', now() - interval '5 hours', now() - interval '4 hours'),
+    ('T6-ABN-TEST-ALARM-GAS-EXCLUDED', 'CN-RQ-202609050006', '异常页测试燃气排除设备', '燃气监测',
+     '燃气浓度超限', 'WARN-ABN-GAS-EXCLUDED', 0.00, 20.00, 45.00, 1, 125.00,
+     0, now() - interval '6 hours', NULL, NULL, NULL, '非供水设备排除测试数据',
+     now() - interval '6 hours', now() - interval '6 hours');
+
+-- ------------------------------------------------------------
+-- 5. 关联统一工单(order_type=1 表示故障维修)
+--    WO202609050001 为已结案工单,不应阻止报警设备重新派单。
+--    WO202609050002/003 为未结束工单,dispatchableOnly=true 时对应设备应被排除。
+-- ------------------------------------------------------------
+INSERT INTO app_user.work_order
+    (order_no, alarm_id, case_id, case_no, device_id, device_code,
+     order_type, order_level, order_desc, dept_id, dispatch_user, dispatch_time,
+     receive_user, order_status, delayed_reason, delayed_deadline, plan_finish_time,
+     real_finish_time, repair_result, maintenance_before_img, maintenance_after_img,
+     verify_user, verify_time, create_time, update_time)
+VALUES
+    ('WO202609050001', 'T6-ABN-TEST-ALARM-OPEN', NULL, NULL,
+     'T6-ABN-TEST-EQ-ALARM-OPEN', 'CN-GS-202609050001',
+     1, 1, '异常页测试历史已结案维修工单', NULL, NULL, now() - interval '55 minutes',
+     '1', 6, NULL, NULL, now() - interval '10 minutes',
+     now() - interval '15 minutes', '测试结案', NULL, NULL,
+     '1', now() - interval '12 minutes', now() - interval '55 minutes', now()),
+    ('WO202609050002', 'T6-ABN-TEST-ALARM-ORDERED', NULL, NULL,
+     'T6-ABN-TEST-EQ-ALARM-ORDERED', 'CB-GS-202609050002',
+     1, 2, '异常页测试压力报警处理中工单', NULL, NULL, now() - interval '110 minutes',
+     '2', 4, NULL, NULL, now() + interval '1 day',
+     NULL, NULL, NULL, NULL, NULL,
+     NULL, now() - interval '110 minutes', now()),
+    ('WO202609050003', NULL, NULL, NULL,
+     'T6-ABN-TEST-EQ-REPAIR', 'TC-GS-202609050003',
+     1, 3, '异常页测试流量设备维修中工单', NULL, NULL, now() - interval '3 hours',
+     '3', 4, NULL, NULL, now() + interval '2 days',
+     NULL, NULL, NULL, NULL, NULL,
+     NULL, now() - interval '3 hours', now());
+
+-- ============================================================
+-- 快速核验:
+--   1. 设备异常管理页应显示 4 台供水设备:
+--      CN-GS-202609050001(供水压力超限,可派单)。
+--      CB-GS-202609050002(供水压力异常,已派单)。
+--      TC-GS-202609050003(设备维修中,已派单)。
+--      CN-GS-202609050004(供水漏失异常,无状态记录但有效报警,可派单)。
+--   2. CB-GS-202609050005 不应显示:状态正常,且只有已处理报警。
+--   3. TC-GS-202609050007 不应显示:无状态记录且无有效报警。
+--   4. CN-RQ-202609050006 不应显示:属于非供水设备。
+--   5. dispatchableOnly=true 时,只应返回
+--      CN-GS-202609050001 和 CN-GS-202609050004。
+-- ============================================================

+ 145 - 0
pipe-network-service/sql/water_supply_device_test_data.sql

@@ -0,0 +1,145 @@
+-- ============================================================
+-- 供水管网 T6 设备准入、台账与异常态势 测试数据脚本(KingbaseES)
+-- 说明:
+--   1. 测试主键与编号均使用 T6-TEST- 前缀,可重复执行。
+--   2. 本脚本只初始化测试数据,不创建业务表;执行前请确认以下表已存在:
+--      app_user.equipment_type、app_user.equipment_base、app_user.equipment_status、
+--      app_user.alarm_data、app_user.work_order
+--   3. 覆盖场景:正常供水设备、报警供水设备、维修供水设备、离线供水设备、
+--      非供水设备排除、有效报警原因、真实工单编号与状态。
+-- ============================================================
+
+-- ------------------------------------------------------------
+-- 0. 清理历史测试数据(先清工单与报警,再清状态与设备,最后清临时类型)
+-- ------------------------------------------------------------
+DELETE FROM app_user.work_order_log WHERE order_id IN
+    (SELECT order_id FROM app_user.work_order WHERE order_no LIKE 'T6-TEST-WO-%');
+DELETE FROM app_user.work_order WHERE order_no LIKE 'T6-TEST-WO-%';
+DELETE FROM app_user.alarm_data WHERE id LIKE 'T6-TEST-ALARM-%';
+DELETE FROM app_user.equipment_status WHERE equipment_id LIKE 'T6-TEST-EQ-%';
+DELETE FROM app_user.equipment_base WHERE equipment_id LIKE 'T6-TEST-EQ-%';
+DELETE FROM app_user.equipment_type WHERE id = 'T6-TEST-GAS-TYPE';
+
+-- ------------------------------------------------------------
+-- 1. 校验规范供水设备类型,并创建临时非供水类型用于边界排除
+-- ------------------------------------------------------------
+DO $$
+DECLARE
+    v_count integer;
+BEGIN
+    SELECT count(*) INTO v_count
+      FROM app_user.equipment_type
+     WHERE id = '1' AND parent_type_id = '0' AND type_name = '供水';
+    IF v_count <> 1 THEN
+        RAISE EXCEPTION '缺少规范供水顶级设备类型:id=1,type_name=供水,parent_type_id=0';
+    END IF;
+
+    SELECT count(*) INTO v_count
+      FROM app_user.equipment_type
+     WHERE type_id IN ('ws_flow', 'ws_pressure', 'ws_leak')
+       AND parent_type_id = '1';
+    IF v_count <> 3 THEN
+        RAISE EXCEPTION '缺少规范供水监测子类型:ws_flow/ws_pressure/ws_leak 必须 parent_type_id=1';
+    END IF;
+END $$;
+
+INSERT INTO app_user.equipment_type
+    (id, type_id, type_name, parent_type_id, type_remark)
+VALUES
+    ('T6-TEST-GAS-TYPE', 't6_test_gas', '燃气(测试)', '0', 'T6非供水设备排除测试类型');
+
+-- ------------------------------------------------------------
+-- 2. 设备基础信息(4台供水设备 + 1台非供水设备)
+-- ------------------------------------------------------------
+INSERT INTO app_user.equipment_base
+    (equipment_id, equipment_code, equipment_name, equipment_model, equipment_type_id,
+     longitude, latitude, equipment_location, maintainer, maintainer_phone,
+     ownership_unit, remark, create_time, update_time, del_flag, district)
+VALUES
+    ('T6-TEST-EQ-PRESSURE-ALARM', 'CN-GS-202609020001', 'T6测试压力报警设备', 'PRESSURE-T6',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_pressure' AND parent_type_id = '1' LIMIT 1),
+     113.28000000, 23.12000000, 'T6测试大道1号', 'T6测试维护员', '13800000001',
+     'T6测试供水公司', 'T6设备准入与异常态势测试数据', now() - interval '7 days', now(), '0', '城南'),
+    ('T6-TEST-EQ-FLOW-REPAIR', 'CB-GS-202609020001', 'T6测试流量维修设备', 'FLOW-T6',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_flow' AND parent_type_id = '1' LIMIT 1),
+     113.29000000, 23.13000000, 'T6测试大道2号', 'T6测试维护员', '13800000002',
+     'T6测试供水公司', 'T6设备准入与异常态势测试数据', now() - interval '7 days', now(), '0', '城北'),
+    ('T6-TEST-EQ-LEAK-OFFLINE', 'TC-GS-202609020001', 'T6测试漏失离线设备', 'LEAK-T6',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_leak' AND parent_type_id = '1' LIMIT 1),
+     113.30000000, 23.14000000, 'T6测试大道3号', 'T6测试维护员', '13800000003',
+     'T6测试供水公司', 'T6设备准入与异常态势测试数据', now() - interval '7 days', now(), '0', '太常'),
+    ('T6-TEST-EQ-PRESSURE-NORMAL', 'CN-GS-202609020002', 'T6测试压力正常设备', 'PRESSURE-T6',
+     (SELECT id FROM app_user.equipment_type WHERE type_id = 'ws_pressure' AND parent_type_id = '1' LIMIT 1),
+     113.31000000, 23.15000000, 'T6测试大道4号', 'T6测试维护员', '13800000004',
+     'T6测试供水公司', 'T6设备准入与异常态势测试数据', now() - interval '7 days', now(), '0', '城南'),
+    ('T6-TEST-EQ-GAS-EXCLUDED', 'CN-RQ-202609020001', 'T6测试燃气排除设备', 'GAS-T6',
+     'T6-TEST-GAS-TYPE', 113.32000000, 23.16000000, 'T6测试大道5号',
+     'T6测试维护员', '13800000005', 'T6测试燃气公司', 'T6非供水排除测试数据',
+     now() - interval '7 days', now(), '0', '城南');
+
+-- ------------------------------------------------------------
+-- 3. 设备状态(current_status / alarm_status / online_status 分别表达不同状态)
+-- ------------------------------------------------------------
+INSERT INTO app_user.equipment_status
+    (equipment_id, current_status, alarm_status, online_status,
+     installation_addr, status_update_time, create_time, del_flag)
+VALUES
+    ('T6-TEST-EQ-PRESSURE-ALARM', 1, 1, 1, 'T6测试大道1号',
+     now() - interval '1 hour', now() - interval '1 hour', '0'),
+    ('T6-TEST-EQ-FLOW-REPAIR', 3, 0, 0, 'T6测试大道2号',
+     now() - interval '2 hours', now() - interval '2 hours', '0'),
+    ('T6-TEST-EQ-LEAK-OFFLINE', 1, 0, 0, 'T6测试大道3号',
+     now() - interval '3 hours', now() - interval '3 hours', '0'),
+    ('T6-TEST-EQ-PRESSURE-NORMAL', 1, 0, 1, 'T6测试大道4号',
+     now() - interval '4 hours', now() - interval '4 hours', '0'),
+    ('T6-TEST-EQ-GAS-EXCLUDED', 1, 1, 1, 'T6测试大道5号',
+     now() - interval '5 hours', now() - interval '5 hours', '0');
+
+-- ------------------------------------------------------------
+-- 4. 有效报警原因(供水报警设备 + 非供水排除设备)
+-- ------------------------------------------------------------
+INSERT INTO app_user.alarm_data
+    (id, device_code, device_name, device_type, warning_type, warning_code,
+     min_value, max_value, actual_value, alarm_level, deviation_ratio,
+     alarm_status, alarm_time, handle_time, handle_user, handle_remark, remark,
+     create_time, update_time)
+VALUES
+    ('T6-TEST-ALARM-PRESSURE', 'CN-GS-202609020001', 'T6测试压力报警设备', '压力监测',
+     '供水压力超限', 'WARN-PRESSURE-T6', 0.20, 0.80, 1.20, 2, 50.00,
+     0, now() - interval '1 hour', NULL, NULL, NULL, 'T6设备异常态势测试数据',
+     now() - interval '1 hour', now() - interval '1 hour'),
+    ('T6-TEST-ALARM-GAS-EXCLUDED', 'CN-RQ-202609020001', 'T6测试燃气排除设备', '燃气监测',
+     '燃气浓度超限', 'WARN-GAS-T6', 0.00, 20.00, 45.00, 1, 125.00,
+     0, now() - interval '1 hour', NULL, NULL, NULL, 'T6非供水排除测试数据',
+     now() - interval '1 hour', now() - interval '1 hour');
+
+-- ------------------------------------------------------------
+-- 5. 关联统一工单(真实 order_no,不用随机 ID)
+-- ------------------------------------------------------------
+INSERT INTO app_user.work_order
+    (order_no, alarm_id, case_id, case_no, device_id, device_code,
+     order_type, order_level, order_desc, dept_id, dispatch_user, dispatch_time,
+     receive_user, order_status, delayed_reason, delayed_deadline, plan_finish_time,
+     real_finish_time, repair_result, maintenance_before_img, maintenance_after_img,
+     verify_user, verify_time, create_time, update_time)
+VALUES
+    ('T6-TEST-WO-001', 'T6-TEST-ALARM-PRESSURE', NULL, NULL,
+     'T6-TEST-EQ-PRESSURE-ALARM', 'CN-GS-202609020001',
+     1, 2, 'T6供水压力超限故障维修', NULL, NULL, now() - interval '50 minutes',
+     '1', 4, NULL, NULL, now() + interval '1 day',
+     NULL, NULL, NULL, NULL, NULL, NULL, now() - interval '50 minutes', now()),
+    ('T6-TEST-WO-002', NULL, NULL, NULL,
+     'T6-TEST-EQ-FLOW-REPAIR', 'CB-GS-202609020001',
+     1, 2, 'T6供水流量设备维修', NULL, NULL, now() - interval '2 hours',
+     '2', 4, NULL, NULL, now() + interval '1 day',
+     NULL, NULL, NULL, NULL,
+     NULL, NULL, now() - interval '2 hours', now());
+
+-- ============================================================
+-- 快速核验:
+--   1. 供水设备台账应包含 4 台 T6 供水设备,不包含 CN-RQ-202609020001。
+--   2. 异常设备页应包含压力报警设备与流量维修设备;正常压力设备与漏失离线设备不进入异常页。
+--   3. CN-GS-202609020001 的异常原因为“供水压力超限”,关联工单号为 T6-TEST-WO-001,状态为处理中。
+--   4. CB-GS-202609020001 的异常原因为设备维修中,关联工单号为 T6-TEST-WO-002,状态为处理中。
+--   5. CN-RQ-202609020001 属于燃气测试类型,任何供水页面均不应展示。
+-- ============================================================

+ 57 - 6
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceAbnormal/DeviceAbnormalController.java

@@ -2,10 +2,17 @@ package com.zksy.web.controller.WaterSupply.DeviceAbnormal;
 
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zksy.base.domain.vo.AbnormalDeviceVO;
+import com.zksy.base.domain.vo.MaintainOrderVO;
+import com.zksy.base.domain.WorkOrder;
 import com.zksy.base.service.WaterSupplyDeviceService;
+import com.zksy.base.service.BusinessWorkOrderService;
+import com.zksy.WaterSupply.export.WaterDeviceAbnormalExportDTO;
 import com.zksy.common.annotation.Log;
 import com.zksy.common.core.domain.AjaxResult;
 import com.zksy.common.enums.BusinessType;
+import com.zksy.common.utils.poi.ExcelUtil;
+import com.zksy.common.utils.SecurityUtils;
+import com.zksy.common.exception.ServiceException;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
@@ -14,7 +21,9 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
+import java.util.stream.Collectors;
 
 @Slf4j
 @RestController
@@ -25,6 +34,9 @@ public class DeviceAbnormalController {
     @Autowired
     private WaterSupplyDeviceService waterSupplyDeviceService;
 
+    @Autowired
+    private BusinessWorkOrderService businessWorkOrderService;
+
     @GetMapping("/page")
     @ApiOperation("异常设备分页查询")
     @PreAuthorize("@ss.hasPermi('waterSupply:device:abnormal:list')")
@@ -34,9 +46,11 @@ public class DeviceAbnormalController {
             @ApiParam("设备名称") @RequestParam(required = false) String equipmentName,
             @ApiParam("设备编码") @RequestParam(required = false) String equipmentCode,
             @ApiParam("设备类型ID") @RequestParam(required = false) String equipmentTypeId,
-            @ApiParam("告警等级 1-4") @RequestParam(required = false) Integer alertLevel) {
+            @ApiParam("告警等级 1-4") @RequestParam(required = false) Integer alertLevel,
+            @ApiParam("仅返回没有未结束故障维修工单的可派单设备")
+            @RequestParam(required = false, defaultValue = "false") Boolean dispatchableOnly) {
         Page<AbnormalDeviceVO> page = waterSupplyDeviceService.getAbnormalDevicePage(
-                pageNum, pageSize, equipmentName, equipmentCode, equipmentTypeId, alertLevel);
+                pageNum, pageSize, equipmentName, equipmentCode, equipmentTypeId, alertLevel, dispatchableOnly);
         return AjaxResult.success(page);
     }
 
@@ -49,17 +63,54 @@ public class DeviceAbnormalController {
         return AjaxResult.success(list);
     }
 
+    @PostMapping("/order")
+    @ApiOperation("供水异常设备创建故障维修工单")
+    @Log(title = "供水异常设备派单", businessType = BusinessType.INSERT)
+    @PreAuthorize("@ss.hasPermi('waterSupply:device:maintain')")
+    public AjaxResult createAbnormalOrder(@RequestBody MaintainOrderVO vo) {
+        try {
+            Long receiveUserId = vo == null ? null : vo.getReceiveUserId();
+            WorkOrder order = waterSupplyDeviceService.createAbnormalWorkOrder(vo);
+            if (order == null || order.getOrderId() == null) {
+                return AjaxResult.error("派单失败:工单创建未返回有效工单ID");
+            }
+            if (receiveUserId == null) {
+                order.setOrderStatus(1);
+                return AjaxResult.success("工单创建成功,待派单", order);
+            }
+            Long operatorId = SecurityUtils.getUserId();
+            String operatorName = SecurityUtils.getUsername();
+            boolean dispatched = businessWorkOrderService.dispatchOrder(order.getOrderId(), receiveUserId,
+                    vo.getMaintainRemark(), operatorId, operatorName);
+            if (!dispatched) {
+                return AjaxResult.error("派单失败:工单仍为待派单状态,请稍后重试");
+            }
+            order.setReceiveUser(String.valueOf(receiveUserId));
+            order.setOrderStatus(2);
+            return AjaxResult.success("派单成功", order);
+        } catch (ServiceException e) {
+            log.warn("供水异常设备派单业务失败: {}", e.getMessage());
+            return AjaxResult.error("派单失败:" + e.getMessage());
+        } catch (Exception e) {
+            log.error("供水异常设备派单系统异常", e);
+            return AjaxResult.error("派单失败:服务暂不可用");
+        }
+    }
+
     @PostMapping("/export")
     @ApiOperation("导出异常设备台账")
     @Log(title = "导出异常设备", businessType = BusinessType.EXPORT)
     @PreAuthorize("@ss.hasPermi('waterSupply:device:abnormal:export')")
-    public AjaxResult exportAbnormalDevices(
+    public void exportAbnormalDevices(HttpServletResponse response,
             @ApiParam("设备名称") @RequestParam(required = false) String equipmentName,
             @ApiParam("设备编码") @RequestParam(required = false) String equipmentCode,
             @ApiParam("设备类型ID") @RequestParam(required = false) String equipmentTypeId,
             @ApiParam("告警等级") @RequestParam(required = false) Integer alertLevel) {
-        log.info("导出异常设备:name={}, code={}, typeId={}, level={}",
-                equipmentName, equipmentCode, equipmentTypeId, alertLevel);
-        return AjaxResult.success("导出功能待对接EasyExcel");
+        List<WaterDeviceAbnormalExportDTO> rows = waterSupplyDeviceService.getAbnormalDeviceExport(
+                        equipmentName, equipmentCode, equipmentTypeId, alertLevel)
+                .stream()
+                .map(WaterDeviceAbnormalExportDTO::from)
+                .collect(Collectors.toList());
+        new ExcelUtil<>(WaterDeviceAbnormalExportDTO.class).exportExcel(response, rows, "供水异常设备台账");
     }
 }

+ 61 - 7
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceLedger/DeviceLedgerController.java

@@ -4,9 +4,14 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zksy.base.domain.vo.DeviceGisVO;
 import com.zksy.base.domain.vo.DeviceTypeStatisticsVO;
 import com.zksy.base.service.WaterSupplyDeviceService;
+import com.zksy.WaterSupply.export.WaterDeviceLedgerExportDTO;
+import com.zksy.WaterSupply.importing.WaterDeviceLedgerImportDTO;
+import com.zksy.WaterSupply.importing.WaterDeviceLedgerImportService;
+import com.zksy.base.domain.EquipmentBase;
 import com.zksy.common.annotation.Log;
 import com.zksy.common.core.domain.AjaxResult;
 import com.zksy.common.enums.BusinessType;
+import com.zksy.common.utils.poi.ExcelUtil;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
@@ -14,8 +19,11 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
+import java.util.stream.Collectors;
 
 @Slf4j
 @RestController
@@ -26,6 +34,9 @@ public class DeviceLedgerController {
     @Autowired
     private WaterSupplyDeviceService waterSupplyDeviceService;
 
+    @Autowired
+    private WaterDeviceLedgerImportService waterDeviceLedgerImportService;
+
     @GetMapping("/typeStatistics")
     @ApiOperation("设备分类统计(树形结构)")
     @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
@@ -34,6 +45,13 @@ public class DeviceLedgerController {
         return AjaxResult.success(list);
     }
 
+    @GetMapping("/statistics")
+    @ApiOperation("设备台账运行状态统计")
+    @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
+    public AjaxResult getLedgerStatistics() {
+        return AjaxResult.success(waterSupplyDeviceService.getDeviceLedgerStatistics());
+    }
+
     @GetMapping("/page")
     @ApiOperation("设备台账分页查询")
     @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
@@ -43,9 +61,12 @@ public class DeviceLedgerController {
             @ApiParam("设备名称") @RequestParam(required = false) String equipmentName,
             @ApiParam("设备编码") @RequestParam(required = false) String equipmentCode,
             @ApiParam("设备类型ID") @RequestParam(required = false) String equipmentTypeId,
-            @ApiParam("设备状态") @RequestParam(required = false) Integer status) {
+            @ApiParam("设备状态") @RequestParam(required = false) Integer status,
+            @ApiParam("报警状态") @RequestParam(required = false) Integer alarmStatus,
+            @ApiParam("报警等级") @RequestParam(required = false) Integer alertLevel) {
         Page<DeviceGisVO> page = waterSupplyDeviceService.getDeviceLedgerPage(
-                pageNum, pageSize, equipmentName, equipmentCode, equipmentTypeId, status);
+                pageNum, pageSize, equipmentName, equipmentCode, equipmentTypeId,
+                status, alarmStatus, alertLevel);
         return AjaxResult.success(page);
     }
 
@@ -62,13 +83,46 @@ public class DeviceLedgerController {
     @ApiOperation("批量导出设备台账")
     @Log(title = "导出设备台账", businessType = BusinessType.EXPORT)
     @PreAuthorize("@ss.hasPermi('waterSupply:device:export')")
-    public AjaxResult exportDeviceLedger(
+    public void exportDeviceLedger(HttpServletResponse response,
             @ApiParam("设备名称") @RequestParam(required = false) String equipmentName,
             @ApiParam("设备编码") @RequestParam(required = false) String equipmentCode,
             @ApiParam("设备类型ID") @RequestParam(required = false) String equipmentTypeId,
-            @ApiParam("设备状态") @RequestParam(required = false) Integer status) {
-        log.info("导出设备台账:name={}, code={}, typeId={}, status={}",
-                equipmentName, equipmentCode, equipmentTypeId, status);
-        return AjaxResult.success("导出功能待对接EasyExcel");
+            @ApiParam("设备状态") @RequestParam(required = false) Integer status,
+            @ApiParam("报警状态") @RequestParam(required = false) Integer alarmStatus,
+            @ApiParam("报警等级") @RequestParam(required = false) Integer alertLevel) {
+        List<WaterDeviceLedgerExportDTO> rows = waterSupplyDeviceService.getDeviceLedgerExport(
+                        equipmentName, equipmentCode, equipmentTypeId, status, alarmStatus, alertLevel)
+                .stream()
+                .map(WaterDeviceLedgerExportDTO::from)
+                .collect(Collectors.toList());
+        new ExcelUtil<>(WaterDeviceLedgerExportDTO.class).exportExcel(response, rows, "供水设备台账");
+    }
+
+    @PostMapping("/import")
+    @ApiOperation("批量导入设备台账")
+    @Log(title = "导入设备台账", businessType = BusinessType.IMPORT)
+    @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
+    public AjaxResult importDeviceLedger(
+            @ApiParam("Excel 文件") @RequestParam("file") MultipartFile file,
+            @ApiParam("是否更新已存在设备") @RequestParam(defaultValue = "false") boolean updateSupport) throws Exception {
+        List<WaterDeviceLedgerImportDTO> rows = new ExcelUtil<>(WaterDeviceLedgerImportDTO.class)
+                .importExcel(file.getInputStream());
+        return AjaxResult.success(waterDeviceLedgerImportService.importDevices(rows, updateSupport));
+    }
+
+    @PostMapping("/create")
+    @ApiOperation("新增供水设备")
+    @Log(title = "新增供水设备", businessType = BusinessType.INSERT)
+    @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
+    public AjaxResult createDevice(@RequestBody EquipmentBase device) {
+        return AjaxResult.success("新增成功", waterSupplyDeviceService.createWaterDevice(device));
+    }
+
+    @DeleteMapping("/delete")
+    @ApiOperation("删除供水设备")
+    @Log(title = "删除供水设备", businessType = BusinessType.DELETE)
+    @PreAuthorize("@ss.hasPermi('waterSupply:device:list')")
+    public AjaxResult deleteDevices(@RequestParam List<String> equipmentIds) {
+        return AjaxResult.success("删除成功", waterSupplyDeviceService.deleteWaterDevices(equipmentIds));
     }
 }

+ 29 - 4
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/WaterSupply/DeviceMaintain/DeviceMaintainController.java

@@ -3,11 +3,14 @@ package com.zksy.web.controller.WaterSupply.DeviceMaintain;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zksy.base.domain.vo.EquipmentMaintainDataVO;
 import com.zksy.base.domain.vo.MaintainOrderVO;
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.service.BusinessWorkOrderService;
 import com.zksy.base.service.WaterSupplyDeviceService;
 import com.zksy.common.annotation.Log;
 import com.zksy.common.core.domain.AjaxResult;
 import com.zksy.common.enums.BusinessType;
 import com.zksy.common.utils.SecurityUtils;
+import com.zksy.common.exception.ServiceException;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
@@ -28,17 +31,39 @@ public class DeviceMaintainController {
     @Autowired
     private WaterSupplyDeviceService waterSupplyDeviceService;
 
+    @Autowired
+    private BusinessWorkOrderService businessWorkOrderService;
+
     @PostMapping("/order")
     @ApiOperation("创建维修派单")
     @Log(title = "设备维修派单", businessType = BusinessType.INSERT)
     @PreAuthorize("@ss.hasPermi('waterSupply:device:maintain')")
     public AjaxResult createMaintainOrder(@RequestBody MaintainOrderVO vo) {
         try {
-            boolean result = waterSupplyDeviceService.createMaintainOrder(vo);
-            return result ? AjaxResult.success("派单成功") : AjaxResult.error("派单失败");
-        } catch (Exception e) {
-            log.error("创建维修派单失败", e);
+            Long receiveUserId = vo == null ? null : vo.getReceiveUserId();
+            WorkOrder order = waterSupplyDeviceService.createAbnormalWorkOrder(vo);
+            if (order == null || order.getOrderId() == null) {
+                return AjaxResult.error("派单失败:工单创建未返回有效工单ID");
+            }
+            if (receiveUserId == null) {
+                order.setOrderStatus(1);
+                return AjaxResult.success("工单创建成功,待派单", order);
+            }
+            boolean dispatched = businessWorkOrderService.dispatchOrder(order.getOrderId(),
+                    receiveUserId, vo.getMaintainRemark(), SecurityUtils.getUserId(),
+                    SecurityUtils.getUsername());
+            if (!dispatched) {
+                return AjaxResult.error("派单失败:工单仍为待派单状态,请稍后重试");
+            }
+            order.setReceiveUser(String.valueOf(receiveUserId));
+            order.setOrderStatus(2);
+            return AjaxResult.success("派单成功", order);
+        } catch (ServiceException e) {
+            log.warn("创建维修派单业务失败: {}", e.getMessage());
             return AjaxResult.error("派单失败:" + e.getMessage());
+        } catch (Exception e) {
+            log.error("创建维修派单系统异常", e);
+            return AjaxResult.error("派单失败:服务暂不可用");
         }
     }
 

+ 71 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/alarm/AlarmController.java

@@ -3,18 +3,25 @@ package com.zksy.web.controller.alarm;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zksy.base.alarm.domain.AlarmData;
 import com.zksy.base.alarm.service.AlarmDataService;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.service.BusinessWorkOrderService;
 import com.zksy.common.annotation.Anonymous;
 import com.zksy.common.annotation.Log;
 import com.zksy.common.core.domain.AjaxResult;
 import com.zksy.common.enums.BusinessType;
+import com.zksy.common.utils.SecurityUtils;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.time.LocalDateTime;
+import java.util.Map;
 
 @Slf4j
 @RestController
@@ -25,6 +32,12 @@ public class AlarmController {
     @Autowired
     private AlarmDataService service;
 
+    @Autowired
+    private BusinessWorkOrderService businessWorkOrderService;
+
+    @Autowired
+    private EquipmentBaseMapper equipmentBaseMapper;
+
     @GetMapping("/findByPage")
     @ApiOperation("报警分页查询")
     @Anonymous
@@ -32,10 +45,67 @@ public class AlarmController {
                                   @ApiParam("每页条数") long pageSize,
                                   @RequestParam(required = false) String warningType,
                                   @RequestParam(required = false) Integer alarmStatus) {
-        Page<AlarmData> page = service.findByPage(pageNum, pageSize, null, warningType, null, alarmStatus, null);
+        Page<AlarmData> page = service.findByPage(pageNum, pageSize, null, warningType, null, alarmStatus, null, null, null);
         return AjaxResult.success(page);
     }
 
+    @PostMapping("/approve-to-work-order")
+    @ApiOperation("报警审核通过并创建运维工单")
+    @Transactional(rollbackFor = Exception.class)
+    public AjaxResult approveToWorkOrder(@RequestBody Map<String, Object> body) {
+        if (body == null || body.get("alarmId") == null) {
+            return AjaxResult.error("报警ID不能为空");
+        }
+        String alarmId = body.get("alarmId").toString();
+        AlarmData alarm = service.getById(alarmId);
+        if (alarm == null) {
+            return AjaxResult.error("报警信息不存在");
+        }
+
+        long existing = businessWorkOrderService.lambdaQuery()
+                .eq(WorkOrder::getAlarmId, alarmId)
+                .count();
+        if (existing > 0) {
+            return AjaxResult.error("该报警已上传工单,不能重复创建");
+        }
+
+        EquipmentBase equipment = alarm.getDeviceCode() == null ? null
+                : equipmentBaseMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<EquipmentBase>()
+                        .eq(EquipmentBase::getEquipmentCode, alarm.getDeviceCode())
+                        .last("LIMIT 1"));
+        WorkOrder order = new WorkOrder();
+        order.setAlarmId(alarmId);
+        order.setDeviceId(equipment != null ? equipment.getEquipmentId() : alarm.getDeviceCode());
+        order.setDeviceCode(alarm.getDeviceCode());
+        order.setOrderType(1);
+        Object orderLevel = body.get("orderLevel");
+        order.setOrderLevel(orderLevel == null ? mapAlarmLevel(alarm.getAlarmLevel()) : Integer.valueOf(orderLevel.toString()));
+        Object orderDesc = body.get("orderDesc");
+        order.setOrderDesc(orderDesc == null || orderDesc.toString().trim().isEmpty()
+                ? buildOrderDesc(alarm) : orderDesc.toString());
+        Long orderId = businessWorkOrderService.createWorkOrder(order);
+
+        alarm.setAlarmStatus(1);
+        alarm.setHandleTime(LocalDateTime.now());
+        alarm.setHandleUser(SecurityUtils.getUsername());
+        alarm.setHandleRemark("审核通过,已上传工单:" + orderId);
+        alarm.setUpdateTime(LocalDateTime.now());
+        service.updateById(alarm);
+        return AjaxResult.success("审核通过,工单创建成功", orderId);
+    }
+
+    private Integer mapAlarmLevel(Integer alarmLevel) {
+        if (alarmLevel == null || alarmLevel == 1) return 1;
+        if (alarmLevel == 4) return 3;
+        return 2;
+    }
+
+    private String buildOrderDesc(AlarmData alarm) {
+        String value = alarm.getActualValue() == null ? "-" : alarm.getActualValue().toPlainString();
+        return (alarm.getWarningType() == null ? "监测报警" : alarm.getWarningType())
+                + ",当前值:" + value + ",请现场核实处理";
+    }
+
     @GetMapping("/getById/{id}")
     @ApiOperation("根据ID查询报警")
     @Anonymous

+ 4 - 3
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/alarm/AlarmDataController.java

@@ -29,10 +29,11 @@ public class AlarmDataController {
                                  @ApiParam(value = "预警类型", required = false) String warningType,
                                  @ApiParam(value = "预警编码", required = false) String warningCode,
                                  @ApiParam(value = "报警状态 0-未处理 1-已处理", required = false) Integer alarmStatus,
-                                 @ApiParam(value = "设备类型(如drainage)", required = false) String equipmentType) {
-        return AjaxResult.success(service.findByPage(pageNum, pageSize, deviceCode, warningType, warningCode, alarmStatus, equipmentType));
+                                 @ApiParam(value = "设备类型(如drainage)", required = false) String equipmentType,
+                                 @ApiParam(value = "开始时间(yyyy-MM-dd HH:mm:ss)", required = false) String startTime,
+                                 @ApiParam(value = "结束时间(yyyy-MM-dd HH:mm:ss)", required = false) String endTime) {
+        return AjaxResult.success(service.findByPage(pageNum, pageSize, deviceCode, warningType, warningCode, alarmStatus, equipmentType, startTime, endTime));
     }
-
     @GetMapping("/getAlarmDataList")
     @ApiOperation(value = "报警数据信息查询")
     @Anonymous

+ 30 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/alarm/WarningThresholdController.java

@@ -46,7 +46,9 @@ public class WarningThresholdController {
                                        @ApiParam(value = "设备编码,模块内检索单个设备", required = false)String deviceCode,
                                        @ApiParam(value = "预警类型", allowableValues = "温度预警,压力预警,湿度预警", required = false) String warningType,
                                        @ApiParam(value = "预警编码", required = false) String warningCode){
-        return AjaxResult.success(service.findByModulePage(pageNum, pageSize, typeName, deviceCode, warningType, warningCode));
+        // 燃气阈值页面不再传模块名称;未传时按燃气设备处理。
+        String effectiveTypeName = org.springframework.util.StringUtils.hasText(typeName) ? typeName : "燃气";
+        return AjaxResult.success(service.findByModulePage(pageNum, pageSize, effectiveTypeName, deviceCode, warningType, warningCode));
     }
     @GetMapping("/getWarningThresholdList")
     @ApiOperation(value = "预警阈值信息查询")
@@ -66,6 +68,7 @@ public class WarningThresholdController {
     @ApiOperation(value = "预警阈值信息保存")
     public AjaxResult save(@RequestBody WarningThreshold entity,
                            @RequestParam(required = false) String moduleType) {
+        fillLegacyModuleFields(entity, moduleType);
         if (org.springframework.util.StringUtils.hasText(moduleType)
                 && !service.isDeviceInModule(entity.getDeviceCode(), moduleType)) {
             return AjaxResult.error("设备不属于指定模块,无法保存阈值");
@@ -76,6 +79,7 @@ public class WarningThresholdController {
     @ApiOperation(value = "预警阈值信息修改")
     public AjaxResult update(@RequestBody WarningThreshold entity,
                              @RequestParam(required = false) String moduleType) {
+        fillLegacyModuleFields(entity, moduleType);
         if (org.springframework.util.StringUtils.hasText(moduleType)
                 && !service.isDeviceInModule(entity.getDeviceCode(), moduleType)) {
             return AjaxResult.error("设备不属于指定模块,无法保存阈值");
@@ -83,6 +87,31 @@ public class WarningThresholdController {
         entity.setUpdateTime(LocalDateTime.now());
         return service.updateById(entity) ? AjaxResult.success(entity): AjaxResult.error("修改失败");
     }
+
+    /**
+     * 燃气、排水阈值页面不再使用预警类型和预警编码,但旧表可能将这两列定义为非空。
+     * 仅在接口层补齐兼容值,不作为查询条件,也不向前端展示。
+     */
+    private void fillLegacyModuleFields(WarningThreshold entity, String moduleType) {
+        if (entity == null) {
+            return;
+        }
+        if ("燃气".equals(moduleType)) {
+            if (!org.springframework.util.StringUtils.hasText(entity.getWarningType())) {
+                entity.setWarningType("燃气阈值");
+            }
+            if (!org.springframework.util.StringUtils.hasText(entity.getWarningCode())) {
+                entity.setWarningCode("GAS-THRESHOLD");
+            }
+        } else if ("排水".equals(moduleType)) {
+            if (!org.springframework.util.StringUtils.hasText(entity.getWarningType())) {
+                entity.setWarningType("排水阈值");
+            }
+            if (!org.springframework.util.StringUtils.hasText(entity.getWarningCode())) {
+                entity.setWarningCode("DRAINAGE-THRESHOLD");
+            }
+        }
+    }
     @PostMapping("/deleteBatch")
     @ApiOperation(value = "预警阈值信息删除")
     public AjaxResult delete(@RequestBody String[] ids) {

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

@@ -0,0 +1,87 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveResponse;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveService;
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitErrorPayload;
+import com.zksy.cockpit.foundation.CockpitInvalidCodeException;
+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 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 java.nio.charset.StandardCharsets;
+
+import javax.servlet.http.HttpServletRequest;
+
+@RestController
+public class CockpitEquipmentArchiveController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitEquipmentArchiveService archiveService;
+
+    public CockpitEquipmentArchiveController(CockpitEquipmentArchiveService archiveService) {
+        this.archiveService = archiveService;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/archive")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> equipmentArchive(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitEquipmentArchiveResponse response = archiveService.load(
+                resolveRequestId(requestId), decodePathSegment(deviceCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, archiveService.invalidRequest(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitInvalidCodeException.class)
+    public ResponseEntity<AjaxResult> handleInvalidCode(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, archiveService.invalidCode(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitDeviceNotFoundException.class)
+    public ResponseEntity<AjaxResult> handleNotFound(HttpServletRequest request) {
+        return error(HttpStatus.NOT_FOUND, archiveService.notFound(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, archiveService.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 CockpitInvalidCodeException("invalid device code encoding");
+        }
+    }
+}

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

@@ -0,0 +1,99 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.event.CockpitEventReadResponse;
+import com.zksy.cockpit.event.CockpitEventReadService;
+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.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.RequestParam;
+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 CockpitEventReadController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitEventReadService eventService;
+
+    public CockpitEventReadController(CockpitEventReadService eventService) {
+        this.eventService = eventService;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/events/current")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> currentEvents(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitEventReadResponse response = eventService.loadCurrent(
+                resolveRequestId(requestId), decodePathSegment(deviceCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/events/history")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> historyEvents(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestParam(value = "startTime") String startTime,
+            @RequestParam(value = "endTime") String endTime,
+            @RequestParam(value = "page", required = false) Integer page,
+            @RequestParam(value = "pageSize", required = false) Integer pageSize,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitEventReadResponse response = eventService.loadHistory(
+                resolveRequestId(requestId),
+                decodePathSegment(deviceCode),
+                startTime,
+                endTime,
+                page,
+                pageSize);
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, eventService.invalidRequest(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitDeviceNotFoundException.class)
+    public ResponseEntity<AjaxResult> handleNotFound(HttpServletRequest request) {
+        return error(HttpStatus.NOT_FOUND, eventService.notFound(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, eventService.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 device code encoding");
+        }
+    }
+}

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

@@ -0,0 +1,99 @@
+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.type.CockpitTypeMetricsResponse;
+import com.zksy.cockpit.type.CockpitTypeMetricsService;
+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.RequestParam;
+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 CockpitTypeMetricsController {
+    private static final String REQUEST_ID_HEADER = "X-Request-Id";
+
+    private final CockpitTypeMetricsService metricsService;
+
+    public CockpitTypeMetricsController(CockpitTypeMetricsService metricsService) {
+        this.metricsService = metricsService;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/metrics/current")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> currentMetrics(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitTypeMetricsResponse response = metricsService.loadCurrent(
+                resolveRequestId(requestId), decodePathSegment(deviceCode));
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/metrics/history")
+    @PreAuthorize("isAuthenticated()")
+    public ResponseEntity<AjaxResult> historyMetrics(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestParam(value = "startTime") String startTime,
+            @RequestParam(value = "endTime") String endTime,
+            @RequestParam(value = "page", required = false) Integer page,
+            @RequestParam(value = "pageSize", required = false) Integer pageSize,
+            @RequestHeader(value = REQUEST_ID_HEADER, required = false) String requestId) {
+        CockpitTypeMetricsResponse response = metricsService.loadHistory(
+                resolveRequestId(requestId),
+                decodePathSegment(deviceCode),
+                startTime,
+                endTime,
+                page,
+                pageSize);
+        return ResponseEntity.ok(AjaxResult.success(response));
+    }
+
+    @ExceptionHandler(CockpitInvalidRequestException.class)
+    public ResponseEntity<AjaxResult> handleInvalidRequest(HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, metricsService.invalidRequest(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitDeviceNotFoundException.class)
+    public ResponseEntity<AjaxResult> handleNotFound(HttpServletRequest request) {
+        return error(HttpStatus.NOT_FOUND, metricsService.notFound(
+                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
+    }
+
+    @ExceptionHandler(CockpitReadException.class)
+    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
+        return error(HttpStatus.INTERNAL_SERVER_ERROR, metricsService.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 device code encoding");
+        }
+    }
+}

+ 7 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/risk/RiskController.java

@@ -69,4 +69,11 @@ public class RiskController {
     public AjaxResult getFourColorMap() {
         return AjaxResult.success(service.getFourColorMapData());
     }
+
+    @GetMapping("/gas-assessments")
+    @ApiOperation("燃气管网风险评估初版(基础信息+近30天报警)")
+    @Anonymous
+    public AjaxResult getGasAssessments() {
+        return AjaxResult.success(service.getGasRiskAssessments());
+    }
 }

+ 156 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/WaterSupply/DeviceAbnormal/DeviceAbnormalControllerTest.java

@@ -0,0 +1,156 @@
+package com.zksy.web.controller.WaterSupply.DeviceAbnormal;
+
+import com.zksy.base.domain.vo.AbnormalDeviceVO;
+import com.zksy.base.service.WaterSupplyDeviceService;
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.domain.vo.MaintainOrderVO;
+import com.zksy.base.service.BusinessWorkOrderService;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class DeviceAbnormalControllerTest {
+
+    private WaterSupplyDeviceService deviceService;
+    private BusinessWorkOrderService businessWorkOrderService;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        deviceService = mock(WaterSupplyDeviceService.class);
+        businessWorkOrderService = mock(BusinessWorkOrderService.class);
+        DeviceAbnormalController controller = new DeviceAbnormalController();
+        ReflectionTestUtils.setField(controller, "waterSupplyDeviceService", deviceService);
+        ReflectionTestUtils.setField(controller, "businessWorkOrderService", businessWorkOrderService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+        SysUser user = new SysUser();
+        user.setUserId(7L);
+        user.setUserName("operator");
+        LoginUser loginUser = new LoginUser(7L, 1L, user, java.util.Collections.emptySet());
+        SecurityContextHolder.getContext().setAuthentication(
+                new UsernamePasswordAuthenticationToken(loginUser, null, java.util.Collections.emptyList()));
+    }
+
+    @Test
+    void abnormalExportWritesExcelResponse() throws Exception {
+        AbnormalDeviceVO row = new AbnormalDeviceVO();
+        row.setEquipmentId("water-pressure-1");
+        row.setEquipmentName("供水压力监测点");
+        row.setAbnormalReason("供水压力超限");
+        when(deviceService.getAbnormalDeviceExport("供水", null, null, 1))
+                .thenReturn(Collections.singletonList(row));
+
+        mockMvc.perform(post("/waterSupply/device/abnormal/export")
+                        .param("equipmentName", "供水")
+                        .param("alertLevel", "1"))
+                .andExpect(status().isOk())
+                .andExpect(header().string("Content-Type",
+                        org.hamcrest.Matchers.containsString("spreadsheetml.sheet")))
+                .andExpect(result -> assertTrue(
+                        result.getResponse().getContentAsByteArray().length > 0));
+    }
+
+    @Test
+    void abnormalOrderReturnsUnifiedWorkOrderSummary() throws Exception {
+        WorkOrder order = new WorkOrder();
+        order.setOrderId(12L);
+        order.setOrderNo("WO-T6-001");
+        order.setOrderStatus(1);
+        when(deviceService.createAbnormalWorkOrder(any())).thenReturn(order);
+        when(businessWorkOrderService.dispatchOrder(12L, 88L, null, 7L, "operator")).thenReturn(true);
+
+        mockMvc.perform(post("/waterSupply/device/abnormal/order")
+                        .contentType("application/json")
+                        .content("{\"equipmentId\":\"water-1\",\"faultDescription\":\"压力异常\",\"receiveUserId\":88}"))
+                .andExpect(status().isOk())
+                .andExpect(result -> {
+                    String body = result.getResponse().getContentAsString();
+                    assertTrue(body.contains("WO-T6-001"));
+                    assertTrue(body.contains("orderId"));
+                    assertTrue(body.contains("orderStatus"));
+                    assertTrue(body.contains("\"orderStatus\":2"));
+                    assertTrue(body.contains("\"receiveUser\":\"88\""));
+                });
+        verify(businessWorkOrderService).dispatchOrder(12L, 88L, null, 7L, "operator");
+    }
+
+    @Test
+    void abnormalOrderWithoutReceiverCreatesPendingOrderWithoutDispatch() {
+        WorkOrder order = new WorkOrder();
+        order.setOrderId(14L);
+        order.setOrderNo("WO-T6-PENDING");
+        order.setOrderStatus(1);
+        when(deviceService.createAbnormalWorkOrder(any())).thenReturn(order);
+
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId("water-1");
+        request.setFaultDescription("压力异常");
+        AjaxResult result = new DeviceAbnormalController() {{
+            ReflectionTestUtils.setField(this, "waterSupplyDeviceService", deviceService);
+            ReflectionTestUtils.setField(this, "businessWorkOrderService", businessWorkOrderService);
+        }}.createAbnormalOrder(request);
+
+        assertEquals(200, result.get("code"));
+        assertEquals(1, ((WorkOrder) result.get("data")).getOrderStatus());
+        verify(businessWorkOrderService, org.mockito.Mockito.never())
+                .dispatchOrder(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(),
+                        org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
+    }
+
+    @Test
+    void abnormalOrderHidesUnexpectedExceptionDetails() {
+        DeviceAbnormalController controller = new DeviceAbnormalController();
+        ReflectionTestUtils.setField(controller, "waterSupplyDeviceService", deviceService);
+        ReflectionTestUtils.setField(controller, "businessWorkOrderService", businessWorkOrderService);
+        when(deviceService.createAbnormalWorkOrder(any())).thenThrow(new IllegalStateException("database password"));
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId("water-1");
+        request.setReceiveUserId(88L);
+        AjaxResult result = controller.createAbnormalOrder(request);
+        assertEquals("派单失败:服务暂不可用", String.valueOf(result.get("msg")));
+        assertTrue(!String.valueOf(result.get("msg")).contains("database password"));
+    }
+
+    @Test
+    void abnormalOrderReportsDispatchFailureAndKeepsPendingStatus() throws Exception {
+        WorkOrder order = new WorkOrder();
+        order.setOrderId(13L);
+        order.setOrderNo("WO-T6-002");
+        order.setOrderStatus(1);
+        when(deviceService.createAbnormalWorkOrder(any())).thenReturn(order);
+        when(businessWorkOrderService.dispatchOrder(13L, 88L, null, 7L, "operator")).thenReturn(false);
+
+        mockMvc.perform(post("/waterSupply/device/abnormal/order")
+                        .contentType("application/json")
+                        .content("{\"equipmentId\":\"water-1\",\"faultDescription\":\"压力异常\",\"receiveUserId\":88}"))
+                .andExpect(status().isOk())
+                .andExpect(result -> {
+                    JsonNode json = new ObjectMapper().readTree(result.getResponse().getContentAsString());
+                    assertEquals(500, json.get("code").asInt());
+                    assertTrue(json.hasNonNull("msg"));
+                    assertTrue(!json.get("msg").asText().isEmpty());
+                });
+        assertEquals(1, order.getOrderStatus());
+    }
+}

+ 50 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/WaterSupply/DeviceLedger/DeviceLedgerControllerTest.java

@@ -0,0 +1,50 @@
+package com.zksy.web.controller.WaterSupply.DeviceLedger;
+
+import com.zksy.base.domain.vo.DeviceGisVO;
+import com.zksy.base.service.WaterSupplyDeviceService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class DeviceLedgerControllerTest {
+
+    private WaterSupplyDeviceService deviceService;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        deviceService = mock(WaterSupplyDeviceService.class);
+        DeviceLedgerController controller = new DeviceLedgerController();
+        ReflectionTestUtils.setField(controller, "waterSupplyDeviceService", deviceService);
+        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
+    }
+
+    @Test
+    void ledgerExportWritesExcelResponse() throws Exception {
+        DeviceGisVO row = new DeviceGisVO();
+        row.setEquipmentId("water-pressure-1");
+        row.setEquipmentName("供水压力监测点");
+        when(deviceService.getDeviceLedgerExport("供水", null, null, 1, null, null))
+                .thenReturn(Collections.singletonList(row));
+
+        mockMvc.perform(post("/waterSupply/device/ledger/export")
+                        .param("equipmentName", "供水")
+                        .param("status", "1"))
+                .andExpect(status().isOk())
+                .andExpect(header().string("Content-Type",
+                        org.hamcrest.Matchers.containsString("spreadsheetml.sheet")))
+                .andExpect(result -> assertTrue(
+                        result.getResponse().getContentAsByteArray().length > 0));
+    }
+}

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

@@ -0,0 +1,223 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveSnapshot;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveAdapter;
+import com.zksy.cockpit.equipment.CockpitEquipmentImage;
+import com.zksy.cockpit.equipment.CockpitEquipmentArchiveService;
+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.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.junit.jupiter.api.Assertions.assertTrue;
+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 CockpitEquipmentArchiveControllerTest {
+    private CockpitEquipmentArchiveAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitEquipmentArchiveAdapter.class);
+        CockpitEquipmentArchiveService service = new CockpitEquipmentArchiveService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitEquipmentArchiveController(service))
+                .build();
+    }
+
+    @Test
+    void archiveReturnsCompleteReadOnlyContractWithLatestImage() throws Exception {
+        when(adapter.load("TC-PS-YS-202609020012")).thenReturn(archive(
+                "TC-PS-YS-202609020012",
+                Collections.singletonList(new CockpitEquipmentImage(
+                        "https://cockpit.example/equipment-latest.jpg",
+                        "2026-08-30T10:20:00+08:00"))));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/TC-PS-YS-202609020012/archive")
+                        .header("X-Request-Id", "equipment-archive-request-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"))
+                .andExpect(jsonPath("$.data.requestId").value("equipment-archive-request-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value("TC-PS-YS-202609020012"))
+                .andExpect(jsonPath("$.data.deviceName").value("污水管网环境监测设备"))
+                .andExpect(jsonPath("$.data.deviceModel").value("WS-PRO-2000"))
+                .andExpect(jsonPath("$.data.deviceSpec").value("悬浮物/COD/氨氮/电导率/PH"))
+                .andExpect(jsonPath("$.data.manufacturer").value("沅陵专用仪表厂"))
+                .andExpect(jsonPath("$.data.productionDate").value("2025-12-01"))
+                .andExpect(jsonPath("$.data.deviceType").value("ws_sewage_environment"))
+                .andExpect(jsonPath("$.data.deviceTypeName").value("污水环境监测设备"))
+                .andExpect(jsonPath("$.data.assetValue").value(128000.0))
+                .andExpect(jsonPath("$.data.expectedServiceYears").value(10))
+                .andExpect(jsonPath("$.data.longitude").value(110.141))
+                .andExpect(jsonPath("$.data.latitude").value(28.452))
+                .andExpect(jsonPath("$.data.coordinateSystem").value("WGS84"))
+                .andExpect(jsonPath("$.data.equipmentLocation").value("沅陵县太常片区污水干管检查井"))
+                .andExpect(jsonPath("$.data.installTime").value("2026-01-10 09:30:00"))
+                .andExpect(jsonPath("$.data.maintainer").value("张维护"))
+                .andExpect(jsonPath("$.data.maintainerPhone").value("13800000000"))
+                .andExpect(jsonPath("$.data.ownershipUnit").value("沅陵县排水管理所"))
+                .andExpect(jsonPath("$.data.remark").value("监测点首选查看设备"))
+                .andExpect(jsonPath("$.data.latestImage.url").value("https://cockpit.example/equipment-latest.jpg"))
+                .andExpect(jsonPath("$.data.latestImage.capturedAt").value("2026-08-30T10:20:00+08:00"));
+    }
+
+    @Test
+    void archiveSucceedsWithoutImageWhenArchiveExists() throws Exception {
+        when(adapter.load("TC-PS-YS-202609020013")).thenReturn(archive(
+                "TC-PS-YS-202609020013", Collections.emptyList()));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/TC-PS-YS-202609020013/archive"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.deviceCode").value("TC-PS-YS-202609020013"))
+                .andExpect(jsonPath("$.data.latestImage").doesNotExist());
+    }
+
+    @Test
+    void archiveSelectsOnlyTheLatestImageByCapturedAt() throws Exception {
+        when(adapter.load("TC-PS-YS-202609020014")).thenReturn(archive(
+                "TC-PS-YS-202609020014",
+                Arrays.asList(
+                        new CockpitEquipmentImage(
+                                "https://cockpit.example/older.jpg",
+                                "2026-08-29T10:20:00+08:00"),
+                        new CockpitEquipmentImage(
+                                "https://cockpit.example/latest.jpg",
+                                "2026-08-30T10:20:00+08:00"))));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/TC-PS-YS-202609020014/archive"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.latestImage.url").value("https://cockpit.example/latest.jpg"))
+                .andExpect(jsonPath("$.data.latestImage.capturedAt").value("2026-08-30T10:20:00+08:00"));
+    }
+
+    @Test
+    void missingDeviceReturnsTypedNotFound() throws Exception {
+        when(adapter.load("TC-PS-YS-404")).thenReturn(null);
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/TC-PS-YS-404/archive")
+                        .header("X-Request-Id", "equipment-archive-request-404"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.code").value(404))
+                .andExpect(jsonPath("$.data.category").value("NOT_FOUND"))
+                .andExpect(jsonPath("$.data.message").value("设备不存在"))
+                .andExpect(jsonPath("$.data.requestId").value("equipment-archive-request-404"));
+    }
+
+    @Test
+    void blankCodeReturnsTypedBadRequestBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/equipments/%20/archive"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.message").value("设备编码不能为空"));
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void malformedPathEncodingReturnsTypedBadRequestBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/equipments/%ZZ/archive"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.message").value("设备编码不合法"));
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void serverFailureReturnsTypedServerError() throws Exception {
+        when(adapter.load("TC-PS-YS-500")).thenThrow(new CockpitReadException("upstream unavailable"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/TC-PS-YS-500/archive"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"))
+                .andExpect(jsonPath("$.data.message").value("驾驶舱设备档案数据暂不可用"));
+    }
+
+    @Test
+    void mutatingRequestIsRejectedBeforeReadAdapterIsCalled() throws Exception {
+        mockMvc.perform(post("/api/cockpit/v1/equipments/TC-PS-YS-202609020012/archive"))
+                .andExpect(status().isMethodNotAllowed());
+
+        verifyNoInteractions(adapter);
+    }
+
+    @Test
+    void controllerOnlyExposesAuthenticatedReadOnlyOperations() {
+        assertTrue(java.util.Arrays.stream(CockpitEquipmentArchiveController.class.getDeclaredMethods())
+                .filter(this::hasRequestMappingAnnotation)
+                .allMatch(CockpitEquipmentArchiveControllerTest::isReadOnlyMappedMethod));
+
+        assertTrue(java.util.Arrays.stream(CockpitEquipmentArchiveController.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 boolean hasRequestMappingAnnotation(Method method) {
+        return 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);
+    }
+
+    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);
+    }
+
+    private static CockpitEquipmentArchiveSnapshot archive(
+            String deviceCode,
+            java.util.List<CockpitEquipmentImage> images) {
+        return new CockpitEquipmentArchiveSnapshot(
+                deviceCode,
+                "污水管网环境监测设备",
+                "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",
+                "沅陵县排水管理所",
+                "监测点首选查看设备",
+                images);
+    }
+}

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

@@ -0,0 +1,251 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.event.CockpitAlarmWarningRelation;
+import com.zksy.cockpit.event.CockpitEventAlarm;
+import com.zksy.cockpit.event.CockpitEventReadAdapter;
+import com.zksy.cockpit.event.CockpitEventReadService;
+import com.zksy.cockpit.event.CockpitEventSnapshot;
+import com.zksy.cockpit.event.CockpitEventWarning;
+import com.zksy.cockpit.event.CockpitEventLevelColor;
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+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.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.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 CockpitEventReadControllerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+
+    private CockpitEventReadAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitEventReadAdapter.class);
+        CockpitEventReadService service = new CockpitEventReadService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitEventReadController(service))
+                .build();
+    }
+
+    @Test
+    void currentEventsReturnSeparateFamiliesAndAuthoritativeRelations() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(currentFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/current")
+                        .header("X-Request-Id", "event-current-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("event-current-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.state").value("READY"))
+                .andExpect(jsonPath("$.data.warnings", org.hamcrest.Matchers.hasSize(2)))
+                .andExpect(jsonPath("$.data.warnings[0].warningNo").value("WRN-20260902-001"))
+                .andExpect(jsonPath("$.data.warnings[0].level").value(1))
+                .andExpect(jsonPath("$.data.warnings[0].levelColor").value("RED"))
+                .andExpect(jsonPath("$.data.warnings[0].status").value("PROCESSING"))
+                .andExpect(jsonPath("$.data.warnings[0].deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.warnings[1].level").value(2))
+                .andExpect(jsonPath("$.data.warnings[1].levelColor").value("YELLOW"))
+                .andExpect(jsonPath("$.data.alarms", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.alarms[0].alarmId").value("ALM-20260902-001"))
+                .andExpect(jsonPath("$.data.alarms[0].level").value(3))
+                .andExpect(jsonPath("$.data.alarms[0].levelColor").value("BLUE"))
+                .andExpect(jsonPath("$.data.alarms[0].status").value("UNHANDLED"))
+                .andExpect(jsonPath("$.data.alarms[0].deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.alarmWarningRelations", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.alarmWarningRelations[0].warningNo").value("WRN-20260902-001"))
+                .andExpect(jsonPath("$.data.alarmWarningRelations[0].alarmId").value("ALM-20260902-001"));
+    }
+
+    @Test
+    void eventLevelColorDictionaryCoversOneRedToFourGreen() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(levelFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/current"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.warnings[0].levelColor").value("RED"))
+                .andExpect(jsonPath("$.data.warnings[1].levelColor").value("YELLOW"))
+                .andExpect(jsonPath("$.data.warnings[2].levelColor").value("BLUE"))
+                .andExpect(jsonPath("$.data.warnings[3].levelColor").value("GREEN"));
+    }
+
+    @Test
+    void historyEventsReturnPagedContractAndPreserveFamilies() throws Exception {
+        when(adapter.loadHistory(
+                DEVICE_CODE,
+                java.time.OffsetDateTime.parse("2026-09-01T10:00:00+08:00"),
+                java.time.OffsetDateTime.parse("2026-09-02T10:00:00+08:00"),
+                1,
+                100)).thenReturn(historyFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/history")
+                        .param("startTime", "2026-09-01T10:00:00+08:00")
+                        .param("endTime", "2026-09-02T10:00:00+08:00")
+                        .param("page", "1")
+                        .param("pageSize", "100")
+                        .header("X-Request-Id", "event-history-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.requestId").value("event-history-001"))
+                .andExpect(jsonPath("$.data.startTime").value("2026-09-01T10:00:00+08:00"))
+                .andExpect(jsonPath("$.data.endTime").value("2026-09-02T10:00:00+08:00"))
+                .andExpect(jsonPath("$.data.timezone").value("Asia/Shanghai"))
+                .andExpect(jsonPath("$.data.page").value(1))
+                .andExpect(jsonPath("$.data.pageSize").value(100))
+                .andExpect(jsonPath("$.data.total").value(3))
+                .andExpect(jsonPath("$.data.warnings", org.hamcrest.Matchers.hasSize(2)))
+                .andExpect(jsonPath("$.data.alarms", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.alarmWarningRelations", org.hamcrest.Matchers.hasSize(1)));
+    }
+
+    @Test
+    void historyRejectsInvertedRangeAndInvalidPage() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/history")
+                        .param("startTime", "2026-09-02T10:00:00+08:00")
+                        .param("endTime", "2026-09-01T10:00:00+08:00"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/history")
+                        .param("startTime", "2026-09-01T10:00:00+08:00")
+                        .param("endTime", "2026-09-02T10:00:00+08:00")
+                        .param("page", "0"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void currentEventsReturnSuccessfulEmptyState() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(emptyFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/events/current"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.stateReason").value("NO_EVENTS"))
+                .andExpect(jsonPath("$.data.warnings", org.hamcrest.Matchers.hasSize(0)))
+                .andExpect(jsonPath("$.data.alarms", org.hamcrest.Matchers.hasSize(0)))
+                .andExpect(jsonPath("$.data.alarmWarningRelations", org.hamcrest.Matchers.hasSize(0)));
+    }
+
+    @Test
+    void missingDeviceAndAdapterFailureUseTypedReadOnlyErrors() throws Exception {
+        when(adapter.loadCurrent("MISSING")).thenThrow(new CockpitDeviceNotFoundException("device not found"));
+        when(adapter.loadCurrent("BROKEN")).thenThrow(new CockpitReadException("read failed"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/MISSING/events/current"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.data.category").value("NOT_FOUND"));
+        mockMvc.perform(get("/api/cockpit/v1/equipments/BROKEN/events/current"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"));
+    }
+
+    @Test
+    void controllerExposesReadOnlyMappedMethodsOnly() throws Exception {
+        Method[] methods = CockpitEventReadController.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 + "/events/current"))
+                .andExpect(status().isMethodNotAllowed());
+        verifyNoInteractions(adapter);
+    }
+
+    private void assertTrue(boolean condition) {
+        org.junit.jupiter.api.Assertions.assertTrue(condition);
+    }
+
+    private CockpitEventSnapshot currentFixture() {
+        return new CockpitEventSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Arrays.asList(
+                        new CockpitEventWarning(
+                                "WRN-20260902-001", "污水COD预警", "WS_ENV", 1, "RED",
+                                "PROCESSING", "2026-09-02T09:59:30+08:00",
+                                new BigDecimal("18.2"), "mg/L", DEVICE_CODE, "污水环境监测设备", "太常片区"),
+                        new CockpitEventWarning(
+                                "WRN-20260902-002", "污水pH预警", "WS_ENV", 2, "YELLOW",
+                                "PENDING", "2026-09-02T09:58:30+08:00",
+                                new BigDecimal("8.1"), "", DEVICE_CODE, "污水环境监测设备", "太常片区")),
+                Collections.singletonList(new CockpitEventAlarm(
+                        "ALM-20260902-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 3, "BLUE",
+                        "UNHANDLED", "2026-09-02T10:00:00+08:00",
+                        new BigDecimal("42.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
+                        DEVICE_CODE, "污水环境监测设备", "太常片区")),
+                Collections.singletonList(new CockpitAlarmWarningRelation(
+                        "REL-20260902-001", "WRN-20260902-001", "ALM-20260902-001",
+                        "2026-09-02T10:00:00+08:00")),
+                null);
+    }
+
+    private CockpitEventSnapshot levelFixture() {
+        return new CockpitEventSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Arrays.asList(
+                        warning("WRN-1", 1), warning("WRN-2", 2),
+                        warning("WRN-3", 3), warning("WRN-4", 4)),
+                Collections.emptyList(),
+                Collections.emptyList(),
+                null);
+    }
+
+    private CockpitEventSnapshot historyFixture() {
+        return new CockpitEventSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Arrays.asList(warning("WRN-20260901-001", 2), warning("WRN-20260901-002", 4)),
+                Collections.singletonList(new CockpitEventAlarm(
+                        "ALM-20260901-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 1, "RED",
+                        "HANDLED", "2026-09-01T15:30:00+08:00",
+                        new BigDecimal("45.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
+                        DEVICE_CODE, "污水环境监测设备", "太常片区")),
+                Collections.singletonList(new CockpitAlarmWarningRelation(
+                        "REL-20260901-001", "WRN-20260901-001", "ALM-20260901-001",
+                        "2026-09-01T15:30:00+08:00")),
+                3);
+    }
+
+    private CockpitEventSnapshot emptyFixture() {
+        return new CockpitEventSnapshot(
+                DEVICE_CODE, "gas_pressure", "燃气压力计",
+                Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
+    }
+
+    private CockpitEventWarning warning(String warningNo, Integer level) {
+        return new CockpitEventWarning(
+                warningNo, "等级映射预警", "WS_ENV", level, CockpitEventLevelColor.resolve(level), "PENDING",
+                "2026-09-02T09:59:30+08:00", null, "", DEVICE_CODE, "污水环境监测设备", "太常片区");
+    }
+}

+ 272 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitTypeMetricsControllerTest.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.type.CockpitMetricSnapshot;
+import com.zksy.cockpit.type.CockpitTypeMetricsAdapter;
+import com.zksy.cockpit.type.CockpitTypeMetricsService;
+import com.zksy.cockpit.type.CockpitTypeMetricsSnapshot;
+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.junit.jupiter.api.Assertions.assertTrue;
+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 CockpitTypeMetricsControllerTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+    private static final String NOW = "2026-09-02T10:00:00+08:00";
+
+    private CockpitTypeMetricsAdapter adapter;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        adapter = mock(CockpitTypeMetricsAdapter.class);
+        CockpitTypeMetricsService service = new CockpitTypeMetricsService(
+                adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+        mockMvc = MockMvcBuilders
+                .standaloneSetup(new CockpitTypeMetricsController(service))
+                .build();
+    }
+
+    @Test
+    void currentMetricsReturnSewageFiveMetricContract() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(sewageFixture("2026-09-02T09:59:30+08:00"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/current")
+                        .header("X-Request-Id", "type-metrics-current-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"))
+                .andExpect(jsonPath("$.data.requestId").value("type-metrics-current-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(DEVICE_CODE))
+                .andExpect(jsonPath("$.data.deviceType").value("ws_sewage_environment"))
+                .andExpect(jsonPath("$.data.state").value("CURRENT"))
+                .andExpect(jsonPath("$.data.metrics", org.hamcrest.Matchers.hasSize(6)))
+                .andExpect(jsonPath("$.data.metrics[0].metricCode").value("SUSPENDED_SOLIDS"))
+                .andExpect(jsonPath("$.data.metrics[0].metricName").value("悬浮物"))
+                .andExpect(jsonPath("$.data.metrics[0].value").value(12.5))
+                .andExpect(jsonPath("$.data.metrics[0].unit").value("mg/L"))
+                .andExpect(jsonPath("$.data.metrics[0].status").value("NORMAL"))
+                .andExpect(jsonPath("$.data.metrics[0].sampledAt").value("2026-09-02T09:59:30+08:00"))
+                .andExpect(jsonPath("$.data.metrics[0].freshness").value("CURRENT"))
+                .andExpect(jsonPath("$.data.metrics[1].metricCode").value("COD"))
+                .andExpect(jsonPath("$.data.metrics[2].metricCode").value("AMMONIA_NITROGEN"))
+                .andExpect(jsonPath("$.data.metrics[3].metricCode").value("CONDUCTIVITY"))
+                .andExpect(jsonPath("$.data.metrics[4].metricCode").value("PH"))
+                .andExpect(jsonPath("$.data.metrics[5].metricCode").value("UNKNOWN"));
+    }
+
+    @Test
+    void currentMetricsMarkMissingRecentSampleAsStale() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(sewageFixture("2026-09-02T09:58:00+08:00"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/current"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("STALE"))
+                .andExpect(jsonPath("$.data.metrics[0].freshness").value("STALE"));
+    }
+
+    @Test
+    void historyMetricsReturnOrderedPagedContract() throws Exception {
+        when(adapter.loadHistory(
+                DEVICE_CODE,
+                java.time.OffsetDateTime.parse("2026-09-01T10:00:00+08:00"),
+                java.time.OffsetDateTime.parse("2026-09-02T10:00:00+08:00"),
+                1,
+                100)).thenReturn(sewageHistoryFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/history")
+                        .param("startTime", "2026-09-01T10:00:00+08:00")
+                        .param("endTime", "2026-09-02T10:00:00+08:00")
+                        .param("page", "1")
+                        .param("pageSize", "100")
+                        .header("X-Request-Id", "type-metrics-history-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("type-metrics-history-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.startTime").value("2026-09-01T10:00:00+08:00"))
+                .andExpect(jsonPath("$.data.endTime").value("2026-09-02T10:00:00+08:00"))
+                .andExpect(jsonPath("$.data.timezone").value("Asia/Shanghai"))
+                .andExpect(jsonPath("$.data.page").value(1))
+                .andExpect(jsonPath("$.data.pageSize").value(100))
+                .andExpect(jsonPath("$.data.total").value(2))
+                .andExpect(jsonPath("$.data.metrics", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.metrics[0].metricCode").value("PH"))
+                .andExpect(jsonPath("$.data.metrics[0].points", org.hamcrest.Matchers.hasSize(2)))
+                .andExpect(jsonPath("$.data.metrics[0].points[0].sampledAt").value("2026-09-02T09:58:00+08:00"))
+                .andExpect(jsonPath("$.data.metrics[0].points[1].sampledAt").value("2026-09-02T09:59:00+08:00"))
+                .andExpect(jsonPath("$.data.metrics[0].points[0].freshness").value("HISTORICAL"));
+    }
+
+    @Test
+    void historyResponseUsesAdapterTotalForPartialPage() throws Exception {
+        when(adapter.loadHistory(
+                DEVICE_CODE,
+                java.time.OffsetDateTime.parse("2026-09-01T10:00:00+08:00"),
+                java.time.OffsetDateTime.parse("2026-09-02T10:00:00+08:00"),
+                2,
+                1)).thenReturn(partialSewageHistoryFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/history")
+                        .param("startTime", "2026-09-01T10:00:00+08:00")
+                        .param("endTime", "2026-09-02T10:00:00+08:00")
+                        .param("page", "2")
+                        .param("pageSize", "1"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.page").value(2))
+                .andExpect(jsonPath("$.data.total").value(7))
+                .andExpect(jsonPath("$.data.metrics", org.hamcrest.Matchers.hasSize(1)))
+                .andExpect(jsonPath("$.data.metrics[0].points", org.hamcrest.Matchers.hasSize(1)));
+    }
+
+    @Test
+    void historyRejectsInvertedRange() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/history")
+                        .param("startTime", "2026-09-02T10:00:00+08:00")
+                        .param("endTime", "2026-09-01T10:00:00+08:00"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void currentMetricsReturnEmptyStateWithoutMistakingItForFailure() throws Exception {
+        when(adapter.loadCurrent(DEVICE_CODE)).thenReturn(emptyFixture());
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/" + DEVICE_CODE + "/metrics/current"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.stateReason").value("NO_METRICS"))
+                .andExpect(jsonPath("$.data.metrics", org.hamcrest.Matchers.hasSize(0)));
+    }
+
+    @Test
+    void missingDeviceAndAdapterFailureUseTypedReadOnlyErrors() throws Exception {
+        when(adapter.loadCurrent("MISSING")).thenThrow(new CockpitDeviceNotFoundException("device not found"));
+        when(adapter.loadCurrent("BROKEN")).thenThrow(new CockpitReadException("read failed"));
+
+        mockMvc.perform(get("/api/cockpit/v1/equipments/MISSING/metrics/current"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.data.category").value("NOT_FOUND"));
+        mockMvc.perform(get("/api/cockpit/v1/equipments/BROKEN/metrics/current"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"));
+    }
+
+    @Test
+    void controllerExposesReadOnlyMappedMethodsOnly() throws Exception {
+        Method[] methods = CockpitTypeMetricsController.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 + "/metrics/current"))
+                .andExpect(status().isMethodNotAllowed());
+        verifyNoInteractions(adapter);
+    }
+
+    private CockpitTypeMetricsSnapshot sewageFixture(String sampledAt) {
+        return new CockpitTypeMetricsSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Arrays.asList(
+                        metric("SUSPENDED_SOLIDS", "悬浮物", new BigDecimal("12.5"), "mg/L", "NORMAL", sampledAt, null),
+                        metric("COD", "COD", new BigDecimal("18.2"), "mg/L", "WARNING", sampledAt, null),
+                        metric("AMMONIA_NITROGEN", "氨氮", new BigDecimal("0.8"), "mg/L", "NORMAL", sampledAt, null),
+                        metric("CONDUCTIVITY", "电导率", new BigDecimal("780"), "μS/cm", "NORMAL", sampledAt, null),
+                        metric("PH", "pH", new BigDecimal("7.2"), "", "NORMAL", sampledAt, null),
+                        new CockpitMetricSnapshot(
+                                null,
+                                "厂商私有参数",
+                                new BigDecimal("1"),
+                                "",
+                                "UNKNOWN",
+                                sampledAt,
+                                null)));
+    }
+
+    private CockpitTypeMetricsSnapshot sewageHistoryFixture() {
+        return new CockpitTypeMetricsSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Collections.singletonList(new CockpitMetricSnapshot(
+                        "PH",
+                        "pH",
+                        null,
+                        "",
+                        null,
+                        null,
+                        Arrays.asList(
+                                new CockpitMetricSnapshot.PointSnapshot(
+                                        new BigDecimal("7.3"), "NORMAL", "2026-09-02T09:59:00+08:00"),
+                                new CockpitMetricSnapshot.PointSnapshot(
+                                        new BigDecimal("7.2"), "NORMAL", "2026-09-02T09:58:00+08:00")))));
+    }
+
+    private CockpitTypeMetricsSnapshot emptyFixture() {
+        return new CockpitTypeMetricsSnapshot(DEVICE_CODE, "gas_pressure", "燃气压力计", Collections.emptyList());
+    }
+
+    private CockpitMetricSnapshot metric(
+            String metricCode,
+            String metricName,
+            BigDecimal value,
+            String unit,
+            String status,
+            String sampledAt,
+            java.util.List<CockpitMetricSnapshot.PointSnapshot> points) {
+        return new CockpitMetricSnapshot(
+                metricCode,
+                metricName,
+                value,
+                unit,
+                status,
+                sampledAt,
+                points);
+    }
+    private CockpitTypeMetricsSnapshot partialSewageHistoryFixture() {
+        return new CockpitTypeMetricsSnapshot(
+                DEVICE_CODE,
+                "ws_sewage_environment",
+                "污水环境监测设备",
+                Collections.singletonList(new CockpitMetricSnapshot(
+                        "PH",
+                        "pH",
+                        null,
+                        "",
+                        null,
+                        null,
+                        Collections.singletonList(new CockpitMetricSnapshot.PointSnapshot(
+                                new BigDecimal("7.2"), "NORMAL", "2026-09-02T09:59:00+08:00")))),
+                7);
+    }
+}

+ 16 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/MonitorAlarm/service/impl/WaterSupplyAlarmServiceImpl.java

@@ -315,6 +315,13 @@ public class WaterSupplyAlarmServiceImpl implements IWaterSupplyAlarmService {
             throw new ServiceException("报警信息不存在");
         }
 
+        // 同一报警只允许生成一张工单,避免重复审核/重复点击造成重复派单
+        long existingOrderCount = workOrderMapper.selectCount(new LambdaQueryWrapper<WorkOrder>()
+                .eq(WorkOrder::getAlarmId, alarm.getId()));
+        if (existingOrderCount > 0) {
+            throw new ServiceException("该报警已上传工单,不能重复创建");
+        }
+
         // 设备信息(用于回填 deviceId/deviceCode)
         EquipmentBase equipment = alarm.getDeviceCode() == null ? null
                 : equipmentBaseMapper.selectOne(new LambdaQueryWrapper<EquipmentBase>()
@@ -434,6 +441,15 @@ public class WaterSupplyAlarmServiceImpl implements IWaterSupplyAlarmService {
             alarm.setHandleRemark("误报解除:" + StrUtil.blankToDefault(inDTO.getAuditOpinion(), "经审核确认为误报"));
             alarm.setUpdateTime(LocalDateTime.now());
             alarmDataService.updateById(alarm);
+        } else {
+            // 审核通过即上传至运维工单,工单默认待派单状态
+            AlarmDispatchInDTO dispatch = new AlarmDispatchInDTO();
+            dispatch.setAlarmId(alarm.getId());
+            dispatch.setOrderType(1);
+            dispatch.setOrderLevel(mapAlarmLevelToOrderLevel(alarm.getAlarmLevel()));
+            dispatch.setOrderDesc(StrUtil.isBlank(inDTO.getAuditOpinion())
+                    ? null : inDTO.getAuditOpinion());
+            dispatchToWorkOrder(dispatch);
         }
         return toAuditOutDTO(audit);
     }

+ 76 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/export/WaterDeviceAbnormalExportDTO.java

@@ -0,0 +1,76 @@
+package com.zksy.WaterSupply.export;
+
+import com.zksy.base.domain.vo.AbnormalDeviceVO;
+import com.zksy.common.annotation.Excel;
+import lombok.Data;
+
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+
+@Data
+public class WaterDeviceAbnormalExportDTO {
+    @Excel(name = "设备编码")
+    private String equipmentCode;
+
+    @Excel(name = "设备名称")
+    private String equipmentName;
+
+    @Excel(name = "设备类型")
+    private String equipmentTypeName;
+
+    @Excel(name = "安装位置")
+    private String equipmentLocation;
+
+    @Excel(name = "设备状态", readConverterExp = "1=在用,2=闲置,3=维修,4=报废,5=待入库")
+    private Integer currentStatus;
+
+    @Excel(name = "在线状态", readConverterExp = "0=离线,1=在线")
+    private Integer onlineStatus;
+
+    @Excel(name = "报警状态", readConverterExp = "0=正常,1=报警")
+    private Integer alarmStatus;
+
+    @Excel(name = "报警等级", readConverterExp = "1=一级,2=二级,3=三级,4=四级")
+    private Integer alertLevel;
+
+    @Excel(name = "异常原因")
+    private String abnormalReason;
+
+    @Excel(name = "关联工单号")
+    private String relatedWorkOrderNo;
+
+    @Excel(name = "工单状态", readConverterExp = "1=待派单,2=待接单,3=已接单,4=处理中,5=待验收,6=已结案,7=已驳回,8=延期审核,9=已延期")
+    private Integer relatedWorkOrderStatus;
+
+    @Excel(name = "接单责任人")
+    private String relatedWorkOrderPerson;
+
+    @Excel(name = "经度")
+    private BigDecimal longitude;
+
+    @Excel(name = "纬度")
+    private BigDecimal latitude;
+
+    @Excel(name = "状态更新时间", dateFormat = "yyyy-MM-dd HH:mm:ss")
+    private LocalDateTime statusUpdateTime;
+
+    public static WaterDeviceAbnormalExportDTO from(AbnormalDeviceVO value) {
+        WaterDeviceAbnormalExportDTO dto = new WaterDeviceAbnormalExportDTO();
+        dto.equipmentCode = value.getEquipmentCode();
+        dto.equipmentName = value.getEquipmentName();
+        dto.equipmentTypeName = value.getEquipmentTypeName();
+        dto.equipmentLocation = value.getEquipmentLocation();
+        dto.currentStatus = value.getCurrentStatus();
+        dto.onlineStatus = value.getOnlineStatus();
+        dto.alarmStatus = value.getAlarmStatus();
+        dto.alertLevel = value.getAlertLevel();
+        dto.abnormalReason = value.getAbnormalReason();
+        dto.relatedWorkOrderNo = value.getRelatedWorkOrderNo();
+        dto.relatedWorkOrderStatus = value.getRelatedWorkOrderStatus();
+        dto.relatedWorkOrderPerson = value.getRelatedWorkOrderPerson();
+        dto.longitude = value.getLongitude();
+        dto.latitude = value.getLatitude();
+        dto.statusUpdateTime = value.getStatusUpdateTime();
+        return dto;
+    }
+}

+ 51 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/export/WaterDeviceLedgerExportDTO.java

@@ -0,0 +1,51 @@
+package com.zksy.WaterSupply.export;
+
+import com.zksy.base.domain.vo.DeviceGisVO;
+import com.zksy.common.annotation.Excel;
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+@Data
+public class WaterDeviceLedgerExportDTO {
+    @Excel(name = "设备编码")
+    private String equipmentCode;
+
+    @Excel(name = "设备名称")
+    private String equipmentName;
+
+    @Excel(name = "设备类型")
+    private String equipmentTypeName;
+
+    @Excel(name = "安装位置")
+    private String equipmentLocation;
+
+    @Excel(name = "设备状态", readConverterExp = "1=在用,2=闲置,3=维修,4=报废,5=待入库")
+    private Integer currentStatus;
+
+    @Excel(name = "在线状态", readConverterExp = "0=离线,1=在线")
+    private Integer onlineStatus;
+
+    @Excel(name = "报警状态", readConverterExp = "0=正常,1=报警")
+    private Integer alarmStatus;
+
+    @Excel(name = "经度")
+    private BigDecimal longitude;
+
+    @Excel(name = "纬度")
+    private BigDecimal latitude;
+
+    public static WaterDeviceLedgerExportDTO from(DeviceGisVO value) {
+        WaterDeviceLedgerExportDTO dto = new WaterDeviceLedgerExportDTO();
+        dto.equipmentCode = value.getEquipmentCode();
+        dto.equipmentName = value.getEquipmentName();
+        dto.equipmentTypeName = value.getEquipmentTypeName();
+        dto.equipmentLocation = value.getEquipmentLocation();
+        dto.currentStatus = value.getCurrentStatus();
+        dto.onlineStatus = value.getOnlineStatus();
+        dto.alarmStatus = value.getAlarmStatus();
+        dto.longitude = value.getLongitude();
+        dto.latitude = value.getLatitude();
+        return dto;
+    }
+}

+ 55 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportDTO.java

@@ -0,0 +1,55 @@
+package com.zksy.WaterSupply.importing;
+
+import com.zksy.common.annotation.Excel;
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+/** 供水设备台账 Excel 导入行。 */
+@Data
+public class WaterDeviceLedgerImportDTO {
+    @Excel(name = "设备编码")
+    private String equipmentCode;
+
+    @Excel(name = "设备名称")
+    private String equipmentName;
+
+    @Excel(name = "设备类型")
+    private String equipmentTypeName;
+
+    @Excel(name = "设备型号")
+    private String equipmentModel;
+
+    @Excel(name = "设备规格参数")
+    private String equipmentSpec;
+
+    @Excel(name = "制造商")
+    private String manufacturer;
+
+    @Excel(name = "所属片区", readConverterExp = "CN=城南,CB=城北,TC=太常,城南=城南,城北=城北,太常=太常")
+    private String district;
+
+    @Excel(name = "经度")
+    private BigDecimal longitude;
+
+    @Excel(name = "纬度")
+    private BigDecimal latitude;
+
+    @Excel(name = "安装位置")
+    private String equipmentLocation;
+
+    @Excel(name = "设备负责人")
+    private String maintainer;
+
+    @Excel(name = "联系方式")
+    private String maintainerPhone;
+
+    @Excel(name = "权属单位")
+    private String ownershipUnit;
+
+    @Excel(name = "备注")
+    private String remark;
+
+    @Excel(name = "设备图片URL")
+    private String equipmentImage;
+}

+ 126 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportService.java

@@ -0,0 +1,126 @@
+package com.zksy.WaterSupply.importing;
+
+import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.core.bean.copier.CopyOptions;
+import cn.hutool.core.util.StrUtil;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.mapper.EquipmentTypeMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.time.LocalDateTime;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/** 供水设备台账 Excel 导入服务;设备类型必须归属供水顶级类型。 */
+@Service
+@Transactional(rollbackFor = Exception.class)
+public class WaterDeviceLedgerImportService {
+    private static final String WATER_TOP_TYPE_NAME = "供水";
+
+    private final EquipmentBaseService equipmentBaseService;
+    private final EquipmentTypeMapper equipmentTypeMapper;
+
+    public WaterDeviceLedgerImportService(EquipmentBaseService equipmentBaseService,
+                                          EquipmentTypeMapper equipmentTypeMapper) {
+        this.equipmentBaseService = equipmentBaseService;
+        this.equipmentTypeMapper = equipmentTypeMapper;
+    }
+
+    public String importDevices(List<WaterDeviceLedgerImportDTO> rows, boolean updateSupport) {
+        if (rows == null || rows.isEmpty()) {
+            throw new IllegalArgumentException("导入文件不能为空");
+        }
+
+        Set<String> seenCodes = new HashSet<>();
+        int count = 0;
+        for (int index = 0; index < rows.size(); index++) {
+            WaterDeviceLedgerImportDTO row = rows.get(index);
+            String code = StrUtil.trimToNull(row.getEquipmentCode());
+            if (code == null) {
+                throw new IllegalArgumentException("导入失败:第 " + (index + 1) + " 行设备编码不能为空");
+            }
+            if (!seenCodes.add(code)) {
+                throw new IllegalArgumentException("导入失败:设备编码重复:" + code);
+            }
+
+            String typeName = StrUtil.trimToNull(row.getEquipmentTypeName());
+            if (typeName == null) {
+                throw new IllegalArgumentException("导入失败:设备编码 " + code + " 的设备类型不能为空");
+            }
+            String waterTypeId = resolveWaterTypeId(typeName);
+
+            EquipmentBase existing = equipmentBaseService.getOne(
+                    Wrappers.<EquipmentBase>lambdaQuery().eq(EquipmentBase::getEquipmentCode, code), false);
+            boolean update = existing != null;
+            if (update && !updateSupport) {
+                continue;
+            }
+
+            EquipmentBase device = update ? existing : new EquipmentBase();
+            BeanUtil.copyProperties(row, device, CopyOptions.create().setIgnoreNullValue(true));
+            device.setEquipmentCode(code);
+            device.setEquipmentTypeId(waterTypeId);
+            LocalDateTime now = LocalDateTime.now();
+            if (update) {
+                device.setUpdateTime(now);
+                if (!equipmentBaseService.updateById(device)) {
+                    throw new IllegalStateException("供水设备数据更新失败:" + code);
+                }
+            } else {
+                device.setCreateTime(now);
+                device.setUpdateTime(now);
+                if (!equipmentBaseService.save(device)) {
+                    throw new IllegalStateException("供水设备数据保存失败:" + code);
+                }
+            }
+            count++;
+        }
+        return "成功导入 " + count + " 台供水设备";
+    }
+
+    private String resolveWaterTypeId(String typeName) {
+        List<EquipmentType> allTypes = equipmentTypeMapper.selectList(Wrappers.emptyWrapper());
+        Map<String, EquipmentType> typesById = allTypes.stream()
+                .collect(Collectors.toMap(EquipmentType::getId, Function.identity(), (left, right) -> left));
+        List<EquipmentType> matches = allTypes.stream()
+                .filter(type -> typeName.equals(type.getTypeName()))
+                .collect(Collectors.toList());
+        if (matches.isEmpty()) {
+            throw new IllegalArgumentException("导入失败:设备类型不存在:" + typeName);
+        }
+
+        Set<String> waterTypeIds = matches.stream()
+                .filter(type -> isWaterType(type, typesById))
+                .map(EquipmentType::getId)
+                .collect(Collectors.toSet());
+        if (waterTypeIds.isEmpty()) {
+            throw new IllegalArgumentException("导入失败:设备类型不属于供水:" + typeName);
+        }
+        if (waterTypeIds.size() > 1) {
+            throw new IllegalArgumentException("导入失败:存在多个同名供水设备类型:" + typeName);
+        }
+        return waterTypeIds.iterator().next();
+    }
+
+    private boolean isWaterType(EquipmentType type, Map<String, EquipmentType> typesById) {
+        EquipmentType cursor = type;
+        int guard = 0;
+        while (cursor != null && guard++ <= typesById.size()) {
+            if (WATER_TOP_TYPE_NAME.equals(cursor.getTypeName())
+                    && "0".equals(cursor.getParentTypeId())) {
+                return true;
+            }
+            cursor = typesById.get(cursor.getParentTypeId());
+        }
+        return false;
+    }
+}

+ 8 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/domain/WarningThreshold.java

@@ -94,6 +94,14 @@ public class WarningThreshold implements Serializable {
     @ApiModelProperty(value = "修改时间")
     private LocalDateTime updateTime;
 
+    /** 设备表关联展示字段,不落库 */
+    @TableField(exist = false)
+    private String equipmentName;
+
+    /** 设备类型表关联展示字段,不落库 */
+    @TableField(exist = false)
+    private String equipmentTypeName;
+
     @TableField(exist = false)
     private static final long serialVersionUID = 1L;
 }

+ 3 - 4
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmDataService.java

@@ -7,11 +7,10 @@ import com.zksy.base.alarm.domain.AlarmData;
 import java.util.List;
 
 public interface AlarmDataService extends IService<AlarmData> {
-    Page<AlarmData> findByPage(long pageNum, long pageSize, String deviceCode, 
+    Page<AlarmData> findByPage(long pageNum, long pageSize, String deviceCode,
                                  String warningType, String warningCode, Integer alarmStatus,
-                                 String equipmentType);
-    
-    List<AlarmData> getAlarmDataList(String deviceCode, 
+                                 String equipmentType, String startTime, String endTime);
+        List<AlarmData> getAlarmDataList(String deviceCode, 
                                        String warningType, String warningCode, Integer alarmStatus);
     
     boolean saveAlarmData(AlarmData alarmData);

+ 14 - 3
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/impl/AlarmDataServiceImpl.java

@@ -25,7 +25,8 @@ public class AlarmDataServiceImpl extends ServiceImpl<AlarmDataMapper, AlarmData
     @Override
     public Page<AlarmData> findByPage(long pageNum, long pageSize, String deviceCode,
                                         String warningType, String warningCode,
-                                        Integer alarmStatus, String equipmentType) {
+                                        Integer alarmStatus, String equipmentType,
+                                        String startTime, String endTime) {
         Page<AlarmData> page = new Page<>(pageNum, pageSize);
         LambdaQueryWrapper<AlarmData> queryWrapper = new LambdaQueryWrapper<>();
 
@@ -50,8 +51,14 @@ public class AlarmDataServiceImpl extends ServiceImpl<AlarmDataMapper, AlarmData
         queryWrapper.like(deviceCode != null, AlarmData::getDeviceCode, deviceCode)
                 .like(warningType != null, AlarmData::getWarningType, warningType)
                 .like(warningCode != null, AlarmData::getWarningCode, warningCode)
-                .eq(alarmStatus != null, AlarmData::getAlarmStatus, alarmStatus)
-                .orderByDesc(AlarmData::getAlarmTime);
+                .eq(alarmStatus != null, AlarmData::getAlarmStatus, alarmStatus);
+        if (startTime != null && !startTime.isEmpty()) {
+            queryWrapper.ge(AlarmData::getAlarmTime, parseDateTime(startTime));
+        }
+        if (endTime != null && !endTime.isEmpty()) {
+            queryWrapper.le(AlarmData::getAlarmTime, parseDateTime(endTime));
+        }
+        queryWrapper.orderByDesc(AlarmData::getAlarmTime);
         Page<AlarmData> result = this.page(page, queryWrapper);
 
         // 填充 deviceName/longitude/latitude:通过 device_code 从 equipment_base 表关联查询
@@ -60,6 +67,10 @@ public class AlarmDataServiceImpl extends ServiceImpl<AlarmDataMapper, AlarmData
         return result;
     }
 
+    private LocalDateTime parseDateTime(String value) {
+        return LocalDateTime.parse(value, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+    }
+
     /**
      * 根据 deviceCode 从 equipment_base 表批量填充 deviceName、longitude、latitude
      */

+ 93 - 24
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/impl/WarningThresholdServiceImpl.java

@@ -8,6 +8,8 @@ import com.zksy.base.alarm.domain.WarningThreshold;
 import com.zksy.base.alarm.mapper.WarningThresholdMapper;
 import com.zksy.base.alarm.service.WarningThresholdService;
 import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.mapper.EquipmentTypeMapper;
 import com.zksy.base.service.EquipmentBaseService;
 import cn.hutool.core.collection.CollUtil;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -16,6 +18,10 @@ import org.springframework.stereotype.Service;
 import java.util.List;
 import java.util.Set;
 import java.util.Arrays;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.stream.Collectors;
 
 /**
@@ -30,6 +36,9 @@ public class WarningThresholdServiceImpl extends ServiceImpl<WarningThresholdMap
     @Autowired
     private EquipmentBaseService equipmentBaseService;
 
+    @Autowired
+    private EquipmentTypeMapper equipmentTypeMapper;
+
     @Override
     public Page<WarningThreshold> findByPage(long pageNum, long pageSize, String deviceCode, String warningType, String warningCode) {
         Page<WarningThreshold> page = new Page<>(pageNum, pageSize);
@@ -40,44 +49,104 @@ public class WarningThresholdServiceImpl extends ServiceImpl<WarningThresholdMap
         queryWrapper.like(WarningThreshold::getWarningType,warningType)
                 .like(WarningThreshold::getWarningCode,warningCode);
         queryWrapper.orderByDesc(WarningThreshold::getUpdateTime);
-        return this.page(page, queryWrapper);
+        Page<WarningThreshold> result = this.page(page, queryWrapper);
+        fillEquipmentInfo(result.getRecords(), equipmentBaseService.findByTopLevelType("燃气"));
+        return result;
     }
 
     @Override
     public Page<WarningThreshold> findByModulePage(long pageNum, long pageSize, String typeName, String deviceCode, String warningType, String warningCode) {
         Page<WarningThreshold> page = new Page<>(pageNum, pageSize);
-        // 1. 查询该模块下所有设备编码
+        // 以设备表为主表:列表展示该模块的全部设备,阈值只作为附加信息。
         List<EquipmentBase> equipmentList = equipmentBaseService.findByTopLevelType(typeName);
-        if (CollUtil.isEmpty(equipmentList)) {
-            return page;
+        if (CollUtil.isEmpty(equipmentList) && "燃气".equals(typeName)) {
+            equipmentList = equipmentBaseService.findByTopLevelType("燃气管网");
         }
-        List<String> deviceCodes = equipmentList.stream()
-                .map(EquipmentBase::getEquipmentCode)
-                .filter(code -> code != null && !code.isEmpty())
-                .distinct()
-                .collect(Collectors.toList());
-        if (CollUtil.isEmpty(deviceCodes)) {
+        if (CollUtil.isEmpty(equipmentList)) {
             return page;
         }
-        // 2. 查询阈值:device_code 字段匹配任意一个模块设备编码(支持逗号分隔多设备)
+        List<WarningThreshold> configured = new ArrayList<>();
         LambdaQueryWrapper<WarningThreshold> queryWrapper = new LambdaQueryWrapper<>();
-        queryWrapper.and(w -> {
-            for (String code : deviceCodes) {
-                w.or().apply("CONCAT(',', device_code, ',') LIKE CONCAT('%,', {0}, ',%')", code);
+        // 设备阈值配置按设备和设备类型管理,预警类型/编码不参与模块列表查询。
+        queryWrapper.orderByDesc(WarningThreshold::getUpdateTime);
+        configured = this.list(queryWrapper);
+        Map<String, WarningThreshold> thresholdByDevice = new HashMap<>();
+        for (WarningThreshold threshold : configured) {
+            if (threshold.getDeviceCode() == null) continue;
+            for (String code : threshold.getDeviceCode().split(",")) {
+                if (!code.trim().isEmpty()) thresholdByDevice.putIfAbsent(code.trim(), threshold);
             }
-        });
-        // 3. 模块内按设备编码精确检索单个设备
-        if (deviceCode != null && !deviceCode.isEmpty()) {
-            queryWrapper.apply("CONCAT(',', device_code, ',') LIKE CONCAT('%,', {0}, ',%')", deviceCode);
         }
-        if (warningType != null && !warningType.isEmpty()) {
-            queryWrapper.like(WarningThreshold::getWarningType, warningType);
+        List<WarningThreshold> rows = new ArrayList<>();
+        for (EquipmentBase equipment : equipmentList) {
+            String code = equipment.getEquipmentCode();
+            if (code == null || code.trim().isEmpty()) continue;
+            if (deviceCode != null && !deviceCode.isEmpty() && !code.contains(deviceCode)) continue;
+            WarningThreshold configuredRow = thresholdByDevice.get(code);
+            WarningThreshold row = configuredRow == null ? new WarningThreshold() : copyThreshold(configuredRow);
+            row.setDeviceCode(code);
+            row.setEquipmentName(equipment.getEquipmentName());
+            row.setEquipmentTypeName(equipment.getEquipmentTypeName());
+            rows.add(row);
         }
-        if (warningCode != null && !warningCode.isEmpty()) {
-            queryWrapper.like(WarningThreshold::getWarningCode, warningCode);
+        long total = rows.size();
+        int from = (int) Math.min(total, Math.max(0, (pageNum - 1) * pageSize));
+        int to = (int) Math.min(total, from + pageSize);
+        Page<WarningThreshold> result = new Page<>(pageNum, pageSize, total);
+        result.setRecords(from < to ? rows.subList(from, to) : Collections.emptyList());
+        return result;
+    }
+
+    private WarningThreshold copyThreshold(WarningThreshold source) {
+        WarningThreshold target = new WarningThreshold();
+        target.setId(source.getId());
+        target.setWarningType(source.getWarningType());
+        target.setWarningCode(source.getWarningCode());
+        target.setMinValue(source.getMinValue());
+        target.setMaxValue(source.getMaxValue());
+        target.setPeriodStart(source.getPeriodStart());
+        target.setPeriodEnd(source.getPeriodEnd());
+        target.setRemark(source.getRemark());
+        target.setCreateTime(source.getCreateTime());
+        target.setUpdateTime(source.getUpdateTime());
+        return target;
+    }
+
+    private void fillEquipmentInfo(List<WarningThreshold> records, List<EquipmentBase> equipmentList) {
+        if (CollUtil.isEmpty(records) || CollUtil.isEmpty(equipmentList)) return;
+        Map<String, String> typeNames = new HashMap<>();
+        Set<String> typeIds = equipmentList.stream().map(EquipmentBase::getEquipmentTypeId)
+                .filter(v -> v != null && !v.isEmpty()).collect(Collectors.toSet());
+        if (!typeIds.isEmpty()) {
+            for (EquipmentType type : equipmentTypeMapper.selectBatchIds(typeIds)) {
+                if (type.getId() != null && type.getTypeName() != null) typeNames.put(type.getId(), type.getTypeName());
+            }
+        }
+        Map<String, EquipmentBase> byCode = new HashMap<>();
+        for (EquipmentBase equipment : equipmentList) {
+            if (equipment.getEquipmentCode() != null) byCode.put(equipment.getEquipmentCode(), equipment);
+        }
+        for (WarningThreshold threshold : records) {
+            String[] codes = threshold.getDeviceCode() == null ? new String[0] : threshold.getDeviceCode().split(",");
+            StringBuilder names = new StringBuilder();
+            StringBuilder types = new StringBuilder();
+            for (String rawCode : codes) {
+                EquipmentBase equipment = byCode.get(rawCode.trim());
+                if (equipment == null) continue;
+                if (equipment.getEquipmentName() != null && names.indexOf(equipment.getEquipmentName()) < 0) {
+                    if (names.length() > 0) names.append("、");
+                    names.append(equipment.getEquipmentName());
+                }
+                String equipmentTypeName = equipment.getEquipmentTypeName();
+                if (equipmentTypeName == null) equipmentTypeName = typeNames.get(equipment.getEquipmentTypeId());
+                if (equipmentTypeName != null && types.indexOf(equipmentTypeName) < 0) {
+                    if (types.length() > 0) types.append("、");
+                    types.append(equipmentTypeName);
+                }
+            }
+            threshold.setEquipmentName(names.length() == 0 ? null : names.toString());
+            threshold.setEquipmentTypeName(types.length() == 0 ? null : types.toString());
         }
-        queryWrapper.orderByDesc(WarningThreshold::getUpdateTime);
-        return this.page(page, queryWrapper);
     }
 
     @Override

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

@@ -2,6 +2,7 @@ package com.zksy.base.domain;
 
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import io.swagger.annotations.ApiModelProperty;
@@ -51,6 +52,10 @@ public class EquipmentBase {
     @ApiModelProperty("设备类别ID(关联equipment_type表)")
     private String equipmentTypeId;
 
+    @TableField(exist = false)
+    @ApiModelProperty("设备类别名称")
+    private String equipmentTypeName;
+
     @ApiModelProperty("设备资产价值(元)")
     private Double assetValue;
 

+ 15 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/AbnormalDeviceVO.java

@@ -53,6 +53,21 @@ public class AbnormalDeviceVO {
     @ApiModelProperty("告警等级 1-4,1级最高")
     private Integer alertLevel;
 
+    @ApiModelProperty("异常原因(来自未处理报警或维修状态)")
+    private String abnormalReason;
+
+    @ApiModelProperty("报警时间")
+    private LocalDateTime alarmTime;
+
+    @ApiModelProperty("关联统一工单号")
+    private String relatedWorkOrderNo;
+
+    @ApiModelProperty("关联统一工单状态:1-待派单 2-待接单 3-已接单 4-处理中 5-待验收 6-已结案 7-已驳回 8-延期审核 9-已延期")
+    private Integer relatedWorkOrderStatus;
+
+    @ApiModelProperty("关联统一工单运维人员")
+    private String relatedWorkOrderPerson;
+
     @ApiModelProperty("最新工单号")
     private String latestMaintainId;
 

+ 15 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceDetailVO.java

@@ -69,6 +69,21 @@ public class DeviceDetailVO {
     @ApiModelProperty("当前状态")
     private Integer currentStatus;
 
+    @ApiModelProperty("告警等级 1-4,1级最高")
+    private Integer alertLevel;
+
+    @ApiModelProperty("异常原因")
+    private String abnormalReason;
+
+    @ApiModelProperty("关联统一工单号")
+    private String relatedWorkOrderNo;
+
+    @ApiModelProperty("关联统一工单状态")
+    private Integer relatedWorkOrderStatus;
+
+    @ApiModelProperty("关联统一工单责任人")
+    private String relatedWorkOrderPerson;
+
     @ApiModelProperty("最新监测数据(动态字段)")
     private Map<String, Object> latestData;
 

+ 3 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceGisVO.java

@@ -43,6 +43,9 @@ public class DeviceGisVO {
     @ApiModelProperty("设备位置")
     private String equipmentLocation;
 
+    @ApiModelProperty("设备图片URL")
+    private String equipmentImage;
+
     @ApiModelProperty("在线状态 0-离线 1-在线")
     private Integer onlineStatus;
 

+ 22 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/DeviceLedgerStatisticsVO.java

@@ -0,0 +1,22 @@
+package com.zksy.base.domain.vo;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+@Data
+@ApiModel("供水设备台账统计VO")
+public class DeviceLedgerStatisticsVO {
+
+    @ApiModelProperty("设备总数")
+    private Integer total;
+
+    @ApiModelProperty("在线设备数")
+    private Integer online;
+
+    @ApiModelProperty("离线设备数")
+    private Integer offline;
+
+    @ApiModelProperty("在线率(0-100,保留1位小数)")
+    private Double onlineRate;
+}

+ 9 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/vo/MaintainOrderVO.java

@@ -26,6 +26,15 @@ public class MaintainOrderVO {
     @ApiModelProperty("维护内容/故障描述")
     private String maintainContent;
 
+    @ApiModelProperty("故障描述(兼容字段)")
+    private String faultDescription;
+
+    @ApiModelProperty("单一接单责任人用户ID")
+    private Long receiveUserId;
+
+    @ApiModelProperty("工单优先级:1-紧急 2-一般 3-低")
+    private Integer orderLevel;
+
     @ApiModelProperty("维护人")
     private String maintainPerson;
 

+ 4 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/RiskAssessmentService.java

@@ -7,10 +7,14 @@ import com.zksy.base.dto.RiskPageInDTO;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Map;
 
 public interface RiskAssessmentService extends IService<RiskAssessment> {
 
     Page<RiskAssessment> findByPage(RiskPageInDTO dto);
 
+    /** 基于管网基础信息和近30天报警数据计算燃气风险评估(初版模型) */
+    List<Map<String, Object>> getGasRiskAssessments();
+
     List<Map<String, Object>> getFourColorMapData();
 }

+ 23 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/WaterSupplyDeviceService.java

@@ -3,6 +3,7 @@ package com.zksy.base.service;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.WorkOrder;
 import com.zksy.base.domain.vo.*;
 
 import java.util.List;
@@ -12,9 +13,20 @@ public interface WaterSupplyDeviceService extends IService<EquipmentBase> {
 
     List<DeviceTypeStatisticsVO> getDeviceTypeStatistics();
 
+    DeviceLedgerStatisticsVO getDeviceLedgerStatistics();
+
     Page<DeviceGisVO> getDeviceLedgerPage(long pageNum, long pageSize,
                                            String equipmentName, String equipmentCode,
-                                           String equipmentTypeId, Integer status);
+                                           String equipmentTypeId, Integer status,
+                                           Integer alarmStatus, Integer alertLevel);
+
+    List<DeviceGisVO> getDeviceLedgerExport(String equipmentName, String equipmentCode,
+                                             String equipmentTypeId, Integer status,
+                                             Integer alarmStatus, Integer alertLevel);
+
+    boolean createWaterDevice(EquipmentBase device);
+
+    boolean deleteWaterDevices(List<String> equipmentIds);
 
     List<DeviceGisVO> getAllDeviceGisPoints(String equipmentTypeId);
 
@@ -22,10 +34,20 @@ public interface WaterSupplyDeviceService extends IService<EquipmentBase> {
 
     boolean createMaintainOrder(MaintainOrderVO vo);
 
+    WorkOrder createAbnormalWorkOrder(MaintainOrderVO vo);
+
     Page<AbnormalDeviceVO> getAbnormalDevicePage(long pageNum, long pageSize,
                                                   String equipmentName, String equipmentCode,
                                                   String equipmentTypeId, Integer alertLevel);
 
+    Page<AbnormalDeviceVO> getAbnormalDevicePage(long pageNum, long pageSize,
+                                                  String equipmentName, String equipmentCode,
+                                                  String equipmentTypeId, Integer alertLevel,
+                                                  Boolean dispatchableOnly);
+
+    List<AbnormalDeviceVO> getAbnormalDeviceExport(String equipmentName, String equipmentCode,
+                                                    String equipmentTypeId, Integer alertLevel);
+
     List<AbnormalDeviceVO> getAbnormalDeviceGisPoints(String equipmentTypeId);
 
     List<Map<String, Object>> getMaintainRecordList(String equipmentId);

+ 38 - 9
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/BusinessWorkOrderServiceImpl.java

@@ -14,7 +14,9 @@ import com.zksy.base.mapper.HazardHiddenAccountMapper;
 import com.zksy.base.mapper.WorkOrderLogMapper;
 import com.zksy.base.mapper.WorkOrderMapper;
 import com.zksy.base.service.BusinessWorkOrderService;
+import com.zksy.common.core.domain.entity.SysUser;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.system.service.ISysUserService;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -43,6 +45,9 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
     @Autowired
     private HazardHiddenAccountMapper hazardHiddenAccountMapper;
 
+    @Autowired
+    private ISysUserService sysUserService;
+
     @Override
     public IPage<WorkOrder> selectWorkOrderList(Integer orderType, Integer orderLevel, String orderStatus, String deviceCode, String keyword, String equipmentType, Integer pageNum, Integer pageSize) {
         Page<WorkOrder> page = new Page<>(pageNum, pageSize);
@@ -102,6 +107,7 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
     @Override
     @Transactional(rollbackFor = Exception.class)
     public boolean dispatchOrder(Long orderId, Long handlerId, String remarks, Long operUserId, String operUserName) {
+        validateDispatchHandler(handlerId);
         WorkOrder order = this.getById(orderId);
         if (order == null) throw new ServiceException("工单不存在");
         if (order.getOrderStatus() != 1) throw new ServiceException("当前工单状态不允许派单");
@@ -131,6 +137,7 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
         if (handlerIds == null || handlerIds.isEmpty()) {
             throw new ServiceException("派单人员不能为空");
         }
+        handlerIds.forEach(this::validateDispatchHandler);
         WorkOrder order = this.getById(orderId);
         if (order == null) throw new ServiceException("工单不存在");
         if (order.getOrderStatus() != 1) throw new ServiceException("当前工单状态不允许派单");
@@ -162,6 +169,20 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
         return true;
     }
 
+    private void validateDispatchHandler(Long handlerId) {
+        if (handlerId == null) {
+            throw new ServiceException("派单人员不能为空");
+        }
+        if (sysUserService == null) {
+            throw new ServiceException("责任人校验服务不可用");
+        }
+        SysUser user = sysUserService.selectUserById(handlerId);
+        if (user == null || !"0".equals(String.valueOf(user.getStatus()))
+                || !"0".equals(String.valueOf(user.getDelFlag()))) {
+            throw new ServiceException("接单责任人不存在或已停用");
+        }
+    }
+
     @Override
     @Transactional(rollbackFor = Exception.class)
     public boolean verifyOrder(Long orderId, String handleResult, String solution, Long operUserId, String operUserName) {
@@ -248,7 +269,7 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
     @Transactional(rollbackFor = Exception.class)
     public Long createWorkOrderFromHazard(String hazardId, String hazardNo, String hazardDesc, String equipmentId, String hazardLevel, String hazardImages, Date planFinishTime) {
         // 同一设备存在进行中工单(状态非 6 已结案/7 已驳回)时禁止重复建单
-        checkDeviceOrderConflict(equipmentId);
+        checkDeviceOrderConflict(equipmentId, 1, null);
 
         // 隐患等级映射到工单优先级:0-重大→紧急(1) 1-较大→一般(2) 2-一般→一般(2) 3-轻微→低(3)
         Integer orderLevel;
@@ -300,11 +321,10 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
     @Transactional(rollbackFor = Exception.class)
     public Long createWorkOrder(WorkOrder workOrder) {
         // 同一设备存在进行中工单(状态非 6 已结案/7 已驳回)时禁止重复建单
-        checkDeviceOrderConflict(workOrder.getDeviceId());
-
         if (workOrder.getOrderType() == null) {
             workOrder.setOrderType(1);
         }
+        checkDeviceOrderConflict(workOrder.getDeviceId(), workOrder.getOrderType(), workOrder.getAlarmId());
         if (workOrder.getOrderLevel() == null) {
             workOrder.setOrderLevel(2);
         }
@@ -378,17 +398,26 @@ public class BusinessWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, W
     }
 
     /**
-     * 校验设备是否存在进行中工单(状态 1-5/8/9),存在则禁止再次创建工单
-     * 业务规则:同一设备同一时间只能有一个进行中的工单,结案(6)或驳回(7)后方可再次创建
+     * 校验同一业务对象是否已经存在进行中的同类工单。
+     * 带报警身份的工单按设备、工单类型和报警记录去重;没有报警身份的
+     * 手工工单只与同设备的另一条未关联报警工单冲突,避免挡住不同报警原因。
      */
-    private void checkDeviceOrderConflict(String deviceId) {
+    private void checkDeviceOrderConflict(String deviceId, Integer orderType, String alarmId) {
         if (StringUtils.isEmpty(deviceId)) {
             return;
         }
-        Long count = this.lambdaQuery()
+        com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper<WorkOrder> query = this.lambdaQuery()
                 .eq(WorkOrder::getDeviceId, deviceId)
-                .notIn(WorkOrder::getOrderStatus, 6, 7)
-                .count();
+                .notIn(WorkOrder::getOrderStatus, 6, 7);
+        if (orderType != null) {
+            query.eq(WorkOrder::getOrderType, orderType);
+        }
+        if (StringUtils.isNotBlank(alarmId)) {
+            query.eq(WorkOrder::getAlarmId, alarmId);
+        } else {
+            query.isNull(WorkOrder::getAlarmId);
+        }
+        Long count = query.count();
         if (count > 0) {
             throw new ServiceException("该设备已有处理中的工单,需结案或驳回后才能创建新工单");
         }

+ 75 - 9
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentBaseServiceImpl.java

@@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.zksy.base.alarm.domain.WarningThreshold;
 import com.zksy.base.alarm.mapper.WarningThresholdMapper;
+import com.zksy.base.constant.GasEquipmentTypeEnum;
 import com.zksy.base.domain.*;
 import com.zksy.base.domain.vo.EquipmentFullVO;
 import com.zksy.base.event.DeviceStatusChangePublisher;
@@ -1169,19 +1170,68 @@ public class EquipmentBaseServiceImpl extends ServiceImpl<EquipmentBaseMapper, E
 
     @Override
     public List<EquipmentBase> findByTopLevelType(String typeName) {
-        EquipmentType topType = equipmentTypeMapper.selectOne(
+        Set<String> typeIds = new LinkedHashSet<>();
+        Set<String> parentIds = new LinkedHashSet<>();
+
+        // 优先按名称查找顶级分类;使用 selectList 取第一条,避免脏数据导致 selectOne 多结果异常。
+        List<EquipmentType> topTypes = equipmentTypeMapper.selectList(
                 new LambdaQueryWrapper<EquipmentType>()
                         .eq(EquipmentType::getTypeName, typeName)
-                        .eq(EquipmentType::getParentTypeId, "0"));
-        if (topType == null) {
+                        .eq(EquipmentType::getParentTypeId, "0")
+                        .last("LIMIT 1"));
+        if (CollUtil.isNotEmpty(topTypes)) {
+            String topId = topTypes.get(0).getId();
+            if (StringUtils.isNotEmpty(topId)) {
+                typeIds.add(topId);
+                parentIds.add(topId);
+            }
+        }
+
+        // 燃气类型历史数据存在根节点名称不统一的情况,固定兼容 parent_type_id=3
+        // 及 id=3 的根节点,确保设备表中 equipment_type_id=3 或其后代都能查到。
+        if (StringUtils.isNotEmpty(typeName) && typeName.contains("燃气")) {
+            List<EquipmentType> gasRoots = equipmentTypeMapper.selectList(
+                    new LambdaQueryWrapper<EquipmentType>()
+                            .and(w -> w.eq(EquipmentType::getId, GasEquipmentTypeEnum.PARENT_TYPE_ID)
+                                    .or().eq(EquipmentType::getTypeId, GasEquipmentTypeEnum.PARENT_TYPE_ID))
+                            .last("LIMIT 1"));
+            if (CollUtil.isNotEmpty(gasRoots) && StringUtils.isNotEmpty(gasRoots.get(0).getId())) {
+                EquipmentType gasRoot = gasRoots.get(0);
+                typeIds.add(gasRoot.getId());
+                parentIds.add(gasRoot.getId());
+            }
+            List<EquipmentType> gasChildren = equipmentTypeMapper.selectList(
+                    new LambdaQueryWrapper<EquipmentType>()
+                            .eq(EquipmentType::getParentTypeId, GasEquipmentTypeEnum.PARENT_TYPE_ID));
+            for (EquipmentType child : gasChildren) {
+                if (child != null && StringUtils.isNotEmpty(child.getId())) {
+                    typeIds.add(child.getId());
+                    parentIds.add(child.getId());
+                }
+            }
+        }
+
+        // 排水模块的顶级名称在历史数据中可能不是“排水”,按稳定 type_id 兼容查询。
+        if (typeIds.isEmpty() && StringUtils.isNotEmpty(typeName) && typeName.contains("排水")) {
+            List<EquipmentType> drainageTypes = equipmentTypeMapper.selectList(
+                    new LambdaQueryWrapper<EquipmentType>()
+                            .eq(EquipmentType::getTypeId, "drainage")
+                            .eq(EquipmentType::getParentTypeId, "0")
+                            .last("LIMIT 1"));
+            if (CollUtil.isNotEmpty(drainageTypes)) {
+                String drainageId = drainageTypes.get(0).getId();
+                if (StringUtils.isNotEmpty(drainageId)) {
+                    typeIds.add(drainageId);
+                    parentIds.add(drainageId);
+                }
+            }
+        }
+
+        if (typeIds.isEmpty()) {
             return new ArrayList<>();
         }
 
-        // 设备类型可能存在多级子分类,查询整个模块的类型树,避免漏掉深层燃气设备。
-        Set<String> typeIds = new LinkedHashSet<>();
-        Set<String> parentIds = new LinkedHashSet<>();
-        typeIds.add(topType.getId());
-        parentIds.add(topType.getId());
+        // 设备类型可能存在多级子分类,查询整个模块的类型树,避免漏掉深层设备。
         while (!parentIds.isEmpty()) {
             List<EquipmentType> children = equipmentTypeMapper.selectList(
                     new LambdaQueryWrapper<EquipmentType>()
@@ -1197,6 +1247,22 @@ public class EquipmentBaseServiceImpl extends ServiceImpl<EquipmentBaseMapper, E
         LambdaQueryWrapper<EquipmentBase> wrapper = new LambdaQueryWrapper<>();
         wrapper.in(EquipmentBase::getEquipmentTypeId, new ArrayList<>(typeIds));
         wrapper.orderByDesc(EquipmentBase::getCreateTime);
-        return this.list(wrapper);
+        List<EquipmentBase> equipmentList = this.list(wrapper);
+
+        // 回填设备类型名称,供阈值配置、设备台账等页面直接展示。
+        Map<String, String> typeNameMap = new HashMap<>();
+        List<EquipmentType> equipmentTypes = equipmentTypeMapper.selectList(
+                new LambdaQueryWrapper<EquipmentType>().in(EquipmentType::getId, new ArrayList<>(typeIds)));
+        for (EquipmentType type : equipmentTypes) {
+            if (type != null && StringUtils.isNotEmpty(type.getId())) {
+                typeNameMap.put(type.getId(), type.getTypeName());
+            }
+        }
+        equipmentList.forEach(equipment -> {
+            String resolvedTypeName = typeNameMap.get(equipment.getEquipmentTypeId());
+            equipment.setEquipmentTypeName(StringUtils.isNotEmpty(resolvedTypeName)
+                    ? resolvedTypeName : equipment.getEquipmentTypeId());
+        });
+        return equipmentList;
     }
 }

+ 90 - 15
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/GasDashboardServiceImpl.java

@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.zksy.base.constant.GasEquipmentTypeEnum;
 import com.zksy.base.domain.*;
 import com.zksy.base.mapper.*;
+import com.zksy.base.gas.domain.GasMonitorData;
+import com.zksy.base.gas.mapper.GasMonitorDataMapper;
 import com.zksy.base.service.GasDashboardService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -21,6 +23,12 @@ public class GasDashboardServiceImpl implements GasDashboardService {
     @Autowired
     private GasPipePointMapper gasPipePointMapper;
 
+    @Autowired
+    private GasPipePointDeviceRelMapper gasPipePointDeviceRelMapper;
+
+    @Autowired
+    private GasMonitorDataMapper gasMonitorDataMapper;
+
     @Autowired
     private EquipmentBaseMapper equipmentBaseMapper;
 
@@ -123,12 +131,15 @@ public class GasDashboardServiceImpl implements GasDashboardService {
                 .count();
         // 今日告警
         String todayStr = LocalDate.now().toString();
-        long todayAlarm = equipmentStatusMapper.selectList(
-                new LambdaQueryWrapper<EquipmentStatus>()
-                        .in(EquipmentStatus::getEquipmentId, gasEquipmentIds)
-                        .eq(EquipmentStatus::getAlarmStatus, 1)).stream()
-                .filter(s -> s.getStatusUpdateTime() != null && s.getStatusUpdateTime().toString().startsWith(todayStr))
-                .count();
+        long todayAlarm = 0;
+        if (!gasEquipmentIds.isEmpty()) {
+            todayAlarm = equipmentStatusMapper.selectList(
+                    new LambdaQueryWrapper<EquipmentStatus>()
+                            .in(EquipmentStatus::getEquipmentId, gasEquipmentIds)
+                            .eq(EquipmentStatus::getAlarmStatus, 1)).stream()
+                    .filter(s -> s.getStatusUpdateTime() != null && s.getStatusUpdateTime().toString().startsWith(todayStr))
+                    .count();
+        }
 
         // 压力均值(从firefighting_pressure取最新一条)
         double avgPressure = 0;
@@ -230,22 +241,86 @@ public class GasDashboardServiceImpl implements GasDashboardService {
         result.put("hazardStats", levelGroup);
 
         // 6. 监测点数据
+        List<GasPipePointDeviceRel> pointDeviceRels = gasPipePointDeviceRelMapper.selectList(
+                new LambdaQueryWrapper<GasPipePointDeviceRel>()
+                        .eq(GasPipePointDeviceRel::getDelFlag, "0"));
+        Map<Long, List<GasPipePointDeviceRel>> relByPoint = pointDeviceRels.stream()
+                .filter(rel -> rel.getPointId() != null)
+                .collect(Collectors.groupingBy(GasPipePointDeviceRel::getPointId));
         List<Map<String, Object>> pointRows = new ArrayList<>();
-        for (int i = 0; i < Math.min(allPoints.size(), 8); i++) {
-            GasPipePoint p = allPoints.get(i);
-            Map<String, Object> row = new LinkedHashMap<>();
-            row.put("id", i + 1);
-            row.put("name", p.getPointName());
-            row.put("time", new Date().toString().substring(11, 16));
-            row.put("value", String.format("%.2fMPa", 0.15 + Math.random() * 0.1));
-            row.put("status", "0".equals(p.getStatus()) || "ACTIVE".equals(p.getStatus()) ? "在线" : "离线");
-            pointRows.add(row);
+        int rowIndex = 1;
+        for (GasPipePoint p : allPoints) {
+            List<GasPipePointDeviceRel> relations = relByPoint.getOrDefault(p.getPointId(), Collections.emptyList());
+            // 没有关联设备的监测点也保留一行,便于识别未配置设备的点位。
+            if (relations.isEmpty()) {
+                pointRows.add(buildPointRow(rowIndex++, p, null));
+                continue;
+            }
+            for (GasPipePointDeviceRel rel : relations) {
+                pointRows.add(buildPointRow(rowIndex++, p, rel));
+            }
         }
         result.put("pointRows", pointRows);
 
         return result;
     }
 
+    private Map<String, Object> buildPointRow(int id, GasPipePoint point, GasPipePointDeviceRel relation) {
+        Map<String, Object> row = new LinkedHashMap<>();
+        row.put("id", id);
+        row.put("name", point.getPointName());
+        row.put("pointName", point.getPointName());
+        row.put("pointCode", point.getPointCode());
+        String equipmentName = relation == null ? null : relation.getEquipmentName();
+        String equipmentCode = null;
+        String status = "0".equals(point.getStatus()) || "ACTIVE".equals(point.getStatus()) ? "在线" : "离线";
+        String value = "--";
+        String time = "--";
+        if (relation != null && relation.getEquipmentId() != null) {
+            EquipmentBase equipment = equipmentBaseMapper.selectById(relation.getEquipmentId());
+            if (equipment != null) {
+                equipmentName = equipmentName == null || equipmentName.isEmpty() ? equipment.getEquipmentName() : equipmentName;
+                equipmentCode = equipment.getEquipmentCode();
+                EquipmentStatus equipmentStatus = equipmentStatusMapper.selectOne(
+                        new LambdaQueryWrapper<EquipmentStatus>()
+                                .eq(EquipmentStatus::getEquipmentId, equipment.getEquipmentId())
+                                .orderByDesc(EquipmentStatus::getStatusUpdateTime)
+                                .last("LIMIT 1"));
+                if (equipmentStatus != null && equipmentStatus.getOnlineStatus() != null) {
+                    status = equipmentStatus.getOnlineStatus() == 1 ? "在线" : "离线";
+                }
+                GasMonitorData latest = gasMonitorDataMapper.selectOne(
+                        new LambdaQueryWrapper<GasMonitorData>()
+                                .eq(GasMonitorData::getMacAddress, equipment.getEquipmentCode())
+                                .orderByDesc(GasMonitorData::getReportTime)
+                                .last("LIMIT 1"));
+                if (latest == null && relation.getEquipmentId() != null) {
+                    latest = gasMonitorDataMapper.selectOne(
+                            new LambdaQueryWrapper<GasMonitorData>()
+                                    .eq(GasMonitorData::getMacAddress, relation.getEquipmentId())
+                                    .orderByDesc(GasMonitorData::getReportTime)
+                                    .last("LIMIT 1"));
+                }
+                if (latest != null) {
+                    if (latest.getGasConcentration() != null) {
+                        value = latest.getGasConcentration().stripTrailingZeros().toPlainString() + "%LEL";
+                    }
+                    if (latest.getReportTime() != null) {
+                        time = latest.getReportTime().toString().replace('T', ' ');
+                    } else if (latest.getCreateTime() != null) {
+                        time = latest.getCreateTime().toString().replace('T', ' ');
+                    }
+                }
+            }
+        }
+        row.put("deviceName", equipmentName == null ? "-" : equipmentName);
+        row.put("deviceCode", equipmentCode == null && relation != null ? relation.getEquipmentId() : equipmentCode);
+        row.put("time", time);
+        row.put("value", value);
+        row.put("status", status);
+        return row;
+    }
+
     private String statusLabel(Integer currentStatus) {
         if (currentStatus == null) return "正常";
         switch (currentStatus) {

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

@@ -5,6 +5,14 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.zksy.base.domain.PipeNetworkBase;
 import com.zksy.base.domain.RiskAssessment;
+import com.zksy.base.domain.GasPipePoint;
+import com.zksy.base.domain.GasPipePointDeviceRel;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.alarm.domain.AlarmData;
+import com.zksy.base.mapper.GasPipePointMapper;
+import com.zksy.base.mapper.GasPipePointDeviceRelMapper;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.alarm.mapper.AlarmDataMapper;
 import com.zksy.base.dto.RiskPageInDTO;
 import com.zksy.base.mapper.PipeNetworkBaseMapper;
 import com.zksy.base.mapper.RiskAssessmentMapper;
@@ -14,6 +22,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.*;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.math.BigDecimal;
 import java.util.stream.Collectors;
 
 @Slf4j
@@ -24,6 +36,18 @@ public class RiskAssessmentServiceImpl extends ServiceImpl<RiskAssessmentMapper,
     @Autowired
     private PipeNetworkBaseMapper pipeNetworkBaseMapper;
 
+    @Autowired
+    private GasPipePointMapper gasPipePointMapper;
+
+    @Autowired
+    private GasPipePointDeviceRelMapper gasPipePointDeviceRelMapper;
+
+    @Autowired
+    private EquipmentBaseMapper equipmentBaseMapper;
+
+    @Autowired
+    private AlarmDataMapper alarmDataMapper;
+
     @Override
     public Page<RiskAssessment> findByPage(RiskPageInDTO dto) {
         Page<RiskAssessment> page = new Page<>(dto.getPageNum(), dto.getPageSize());
@@ -72,4 +96,115 @@ public class RiskAssessmentServiceImpl extends ServiceImpl<RiskAssessmentMapper,
         }
         return result;
     }
+
+    @Override
+    public List<Map<String, Object>> getGasRiskAssessments() {
+        List<PipeNetworkBase> networks = pipeNetworkBaseMapper.selectList(
+                new LambdaQueryWrapper<PipeNetworkBase>()
+                        .and(w -> w.in(PipeNetworkBase::getNetworkType, "gas", "GAS", "Gas", "燃气", "燃气管网")
+                                .or().like(PipeNetworkBase::getNetworkName, "燃气"))
+                        .orderByDesc(PipeNetworkBase::getCreateTime));
+        if (networks.isEmpty()) return Collections.emptyList();
+
+        Set<String> networkIds = networks.stream().map(PipeNetworkBase::getNetworkId)
+                .filter(Objects::nonNull).collect(Collectors.toSet());
+        List<GasPipePoint> points = gasPipePointMapper.selectList(new LambdaQueryWrapper<GasPipePoint>()
+                .in(GasPipePoint::getNetworkId, networkIds));
+        Set<Long> pointIds = points.stream().map(GasPipePoint::getPointId)
+                .filter(Objects::nonNull).collect(Collectors.toSet());
+        List<GasPipePointDeviceRel> rels = pointIds.isEmpty() ? Collections.emptyList() :
+                gasPipePointDeviceRelMapper.selectList(new LambdaQueryWrapper<GasPipePointDeviceRel>()
+                        .in(GasPipePointDeviceRel::getPointId, pointIds)
+                        .eq(GasPipePointDeviceRel::getDelFlag, "0"));
+
+        Map<String, String> equipmentToNetwork = new HashMap<>();
+        Map<Long, String> pointNetwork = points.stream().collect(Collectors.toMap(
+                GasPipePoint::getPointId, GasPipePoint::getNetworkId, (a, b) -> a));
+        Set<String> equipmentIds = rels.stream().map(GasPipePointDeviceRel::getEquipmentId)
+                .filter(Objects::nonNull).collect(Collectors.toSet());
+        if (!equipmentIds.isEmpty()) {
+            List<EquipmentBase> equipment = equipmentBaseMapper.selectBatchIds(equipmentIds);
+            Map<String, String> idToCode = equipment.stream().collect(Collectors.toMap(
+                    EquipmentBase::getEquipmentId, EquipmentBase::getEquipmentCode, (a, b) -> a));
+            for (GasPipePointDeviceRel rel : rels) {
+                String code = idToCode.get(rel.getEquipmentId());
+                String networkId = pointNetwork.get(rel.getPointId());
+                if (code != null && networkId != null) equipmentToNetwork.put(code, networkId);
+            }
+        }
+
+        LocalDateTime since = LocalDateTime.now().minusDays(30);
+        List<AlarmData> alarms = equipmentToNetwork.isEmpty() ? Collections.emptyList() :
+                alarmDataMapper.selectList(new LambdaQueryWrapper<AlarmData>()
+                        .in(AlarmData::getDeviceCode, equipmentToNetwork.keySet())
+                        .ge(AlarmData::getAlarmTime, since));
+        Map<String, List<AlarmData>> alarmsByNetwork = new HashMap<>();
+        for (AlarmData alarm : alarms) {
+            String networkId = equipmentToNetwork.get(alarm.getDeviceCode());
+            if (networkId != null) alarmsByNetwork.computeIfAbsent(networkId, k -> new ArrayList<>()).add(alarm);
+        }
+
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (PipeNetworkBase pipe : networks) {
+            List<AlarmData> networkAlarms = alarmsByNetwork.getOrDefault(pipe.getNetworkId(), Collections.emptyList());
+            int ageScore = ageScore(pipe.getBuildDate());
+            int alarmScore = alarmFrequencyScore(networkAlarms.size());
+            int unresolvedScore = (int) Math.min(20, networkAlarms.stream()
+                    .filter(a -> Objects.equals(a.getAlarmStatus(), 0)).count() * 5);
+            int highLevelScore = (int) Math.min(15, networkAlarms.stream()
+                    .filter(a -> a.getAlarmLevel() != null && a.getAlarmLevel() <= 2).count() * 5);
+            int pressureScore = pressureScore(pipe.getNetworkLevel());
+            int materialScore = "钢管".equals(pipe.getMaterial()) ? 5 : 2;
+            int score = Math.min(100, ageScore + alarmScore + unresolvedScore + highLevelScore + pressureScore + materialScore);
+            String level = score >= 70 ? "high" : score >= 40 ? "medium" : "low";
+
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("id", pipe.getNetworkId());
+            item.put("networkId", pipe.getNetworkId());
+            item.put("code", pipe.getNetworkCode());
+            item.put("name", pipe.getNetworkName());
+            item.put("area", pipe.getLocation());
+            item.put("material", pipe.getMaterial());
+            item.put("diameter", pipe.getDiameter());
+            item.put("length", pipe.getLength() == null ? null : pipe.getLength().doubleValue() / 1000d);
+            item.put("buildYear", pipe.getBuildDate() == null ? null : pipe.getBuildDate().toInstant().atZone(ZoneId.systemDefault()).getYear());
+            item.put("pressure", pressureValue(pipe.getNetworkLevel()));
+            item.put("pressureLevel", pipe.getNetworkLevel());
+            item.put("owner", pipe.getManagementUnit());
+            item.put("lastInspection", null);
+            // 同步返回管网起终点坐标,当前端 GIS 图层接口暂时无法按编号匹配时,
+            // 仍可直接使用风险评估结果绘制管线。
+            item.put("startLongitude", pipe.getStartLongitude());
+            item.put("startLatitude", pipe.getStartLatitude());
+            item.put("endLongitude", pipe.getEndLongitude());
+            item.put("endLatitude", pipe.getEndLatitude());
+            item.put("riskLevel", level);
+            item.put("riskScore", score);
+            item.put("dimensions", dimensions(ageScore, alarmScore, unresolvedScore + highLevelScore, pressureScore, materialScore));
+            List<String> factors = new ArrayList<>();
+            if (ageScore >= 15) factors.add("管网使用年限较长(" + ageYears(pipe.getBuildDate()) + "年)");
+            if (!networkAlarms.isEmpty()) factors.add("近30天发生" + networkAlarms.size() + "次报警");
+            if (unresolvedScore > 0) factors.add("存在" + unresolvedScore / 5 + "条未处理报警");
+            if (highLevelScore > 0) factors.add("存在高等级报警");
+            if (factors.isEmpty()) factors.add("近30天无报警,基础资料风险较低");
+            item.put("riskFactors", factors);
+            item.put("mitigationMeasures", Arrays.asList("按风险等级安排巡检频次", "持续补充管网检测和维修记录"));
+            item.put("historyRecords", Collections.emptyList());
+            item.put("attachments", Collections.emptyList());
+            result.add(item);
+        }
+        return result;
+    }
+
+    private int ageYears(Date date) {
+        if (date == null) return 0;
+        return Math.max(0, LocalDate.now().getYear() - date.toInstant().atZone(ZoneId.systemDefault()).getYear());
+    }
+    private int ageScore(Date date) { int age = ageYears(date); return age == 0 ? 0 : age <= 5 ? 5 : age <= 10 ? 15 : age <= 15 ? 22 : 30; }
+    private int alarmFrequencyScore(int count) { return count == 0 ? 0 : count <= 2 ? 10 : count <= 5 ? 20 : 30; }
+    private int pressureScore(String level) { if (level == null) return 0; return level.contains("高") || level.toLowerCase().contains("high") ? 20 : level.contains("中") || level.toLowerCase().contains("medium") ? 12 : 5; }
+    private String pressureValue(String level) { if (level == null) return null; if (level.contains("高")) return "1.6"; if (level.contains("中")) return "0.4"; if (level.contains("低")) return "0.1"; return null; }
+    private Map<String, Integer> dimensions(int age, int alarms, int severity, int pressure, int material) {
+        Map<String, Integer> d = new LinkedHashMap<>(); d.put("leakProbability", Math.min(100, alarms * 3 + age * 2)); d.put("consequenceSeverity", Math.min(100, pressure * 4 + severity * 2)); d.put("corrosionRisk", Math.min(100, age * 3 + material * 4)); d.put("thirdPartyRisk", Math.min(100, alarms * 2 + pressure * 2)); d.put("agingLevel", Math.min(100, age * 3)); return d;
+    }
 }

Разница между файлами не показана из-за своего большого размера
+ 602 - 211
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/WaterSupplyDeviceServiceImpl.java


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

@@ -0,0 +1,36 @@
+package com.zksy.cockpit.equipment;
+
+public class CockpitEquipmentArchive {
+    private final CockpitEquipmentArchiveSnapshot archive;
+    private final String coordinateSystem;
+    private final CockpitEquipmentImage latestImage;
+
+    public CockpitEquipmentArchive(
+            CockpitEquipmentArchiveSnapshot archive, String coordinateSystem, CockpitEquipmentImage latestImage) {
+        this.archive = archive;
+        this.coordinateSystem = coordinateSystem;
+        this.latestImage = latestImage;
+    }
+
+    public String getDeviceCode() { return archive.getDeviceCode(); }
+    public String getDeviceName() { return archive.getDeviceName(); }
+    public String getDeviceModel() { return archive.getDeviceModel(); }
+    public String getDeviceSpec() { return archive.getDeviceSpec(); }
+    public String getManufacturer() { return archive.getManufacturer(); }
+    public String getCoordinateSystem() { return coordinateSystem; }
+    public String getProductionDate() { return archive.getProductionDate(); }
+    public String getDeviceType() { return archive.getDeviceType(); }
+    public String getDeviceTypeName() { return archive.getDeviceTypeName(); }
+    public java.math.BigDecimal getAssetValue() { return archive.getAssetValue(); }
+    public Integer getExpectedServiceYears() { return archive.getExpectedServiceYears(); }
+    public java.math.BigDecimal getLongitude() { return archive.getLongitude(); }
+    public java.math.BigDecimal getLatitude() { return archive.getLatitude(); }
+    public String getEquipmentLocation() { return archive.getEquipmentLocation(); }
+    public String getInstallTime() { return archive.getInstallTime(); }
+    public String getMaintainer() { return archive.getMaintainer(); }
+    public String getMaintainerPhone() { return archive.getMaintainerPhone(); }
+    public String getOwnershipUnit() { return archive.getOwnershipUnit(); }
+    public String getRemark() { return archive.getRemark(); }
+    public CockpitEquipmentImage getLatestImage() { return latestImage; }
+
+}

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

@@ -0,0 +1,5 @@
+package com.zksy.cockpit.equipment;
+
+public interface CockpitEquipmentArchiveAdapter {
+    CockpitEquipmentArchiveSnapshot load(String deviceCode);
+}

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

@@ -0,0 +1,40 @@
+package com.zksy.cockpit.equipment;
+
+public class CockpitEquipmentArchiveResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final CockpitEquipmentArchive archive;
+
+    public CockpitEquipmentArchiveResponse(
+            String requestId, String apiVersion, boolean readOnly, CockpitEquipmentArchive archive) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.archive = archive;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return archive.getDeviceCode(); }
+    public String getDeviceName() { return archive.getDeviceName(); }
+    public String getDeviceModel() { return archive.getDeviceModel(); }
+    public String getDeviceSpec() { return archive.getDeviceSpec(); }
+    public String getManufacturer() { return archive.getManufacturer(); }
+    public String getCoordinateSystem() { return archive.getCoordinateSystem(); }
+    public String getProductionDate() { return archive.getProductionDate(); }
+    public String getDeviceType() { return archive.getDeviceType(); }
+    public String getDeviceTypeName() { return archive.getDeviceTypeName(); }
+    public java.math.BigDecimal getAssetValue() { return archive.getAssetValue(); }
+    public Integer getExpectedServiceYears() { return archive.getExpectedServiceYears(); }
+    public java.math.BigDecimal getLongitude() { return archive.getLongitude(); }
+    public java.math.BigDecimal getLatitude() { return archive.getLatitude(); }
+    public String getEquipmentLocation() { return archive.getEquipmentLocation(); }
+    public String getInstallTime() { return archive.getInstallTime(); }
+    public String getMaintainer() { return archive.getMaintainer(); }
+    public String getMaintainerPhone() { return archive.getMaintainerPhone(); }
+    public String getOwnershipUnit() { return archive.getOwnershipUnit(); }
+    public String getRemark() { return archive.getRemark(); }
+    public CockpitEquipmentImage getLatestImage() { return archive.getLatestImage(); }
+}

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

@@ -0,0 +1,89 @@
+package com.zksy.cockpit.equipment;
+
+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.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+
+@Service
+public class CockpitEquipmentArchiveService {
+    private final CockpitEquipmentArchiveAdapter adapter;
+    private final Clock clock;
+
+    public CockpitEquipmentArchiveService(CockpitEquipmentArchiveAdapter adapter, Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public CockpitEquipmentArchiveResponse load(String requestId, String deviceCode) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+
+        CockpitEquipmentArchiveSnapshot snapshot = adapter.load(deviceCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+
+        return new CockpitEquipmentArchiveResponse(
+                requestId,
+                "v1",
+                true,
+                new CockpitEquipmentArchive(snapshot, "WGS84", latestImage(snapshot.getImages())));
+    }
+
+    public CockpitErrorPayload invalidRequest(String requestId) {
+        return error(requestId, CockpitErrorCategory.INVALID_REQUEST, "设备编码不能为空");
+    }
+
+    public CockpitErrorPayload invalidCode(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 CockpitEquipmentImage latestImage(List<CockpitEquipmentImage> images) {
+        if (images == null || images.isEmpty()) {
+            return null;
+        }
+
+        try {
+            Optional<CockpitEquipmentImage> latest = images.stream()
+                    .filter(image -> image != null && image.getCapturedAt() != null)
+                    .max(Comparator.comparing(image -> OffsetDateTime.parse(image.getCapturedAt())));
+            return latest.orElse(null);
+        } catch (DateTimeParseException exception) {
+            throw new CockpitReadException("invalid equipment image timestamp: " + exception.getMessage());
+        }
+    }
+
+    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"))));
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

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

@@ -0,0 +1,73 @@
+package com.zksy.cockpit.equipment;
+
+import java.util.List;
+
+public class CockpitEquipmentArchiveSnapshot {
+    private final String deviceCode;
+    private final String deviceName;
+    private final String deviceModel;
+    private final String deviceSpec;
+    private final String manufacturer;
+    private final String productionDate;
+    private final String deviceType;
+    private final String deviceTypeName;
+    private final java.math.BigDecimal assetValue;
+    private final Integer expectedServiceYears;
+    private final java.math.BigDecimal longitude;
+    private final java.math.BigDecimal latitude;
+    private final String equipmentLocation;
+    private final String installTime;
+    private final String maintainer;
+    private final String maintainerPhone;
+    private final String ownershipUnit;
+    private final String remark;
+    private final List<CockpitEquipmentImage> images;
+
+    public CockpitEquipmentArchiveSnapshot(
+            String deviceCode, String deviceName, String deviceModel, String deviceSpec,
+            String manufacturer, String productionDate, String deviceType, String deviceTypeName,
+            java.math.BigDecimal assetValue, Integer expectedServiceYears,
+            java.math.BigDecimal longitude, java.math.BigDecimal latitude,
+            String equipmentLocation, String installTime, String maintainer, String maintainerPhone,
+            String ownershipUnit, String remark, List<CockpitEquipmentImage> images) {
+        this.deviceCode = deviceCode;
+        this.deviceName = deviceName;
+        this.deviceModel = deviceModel;
+        this.deviceSpec = deviceSpec;
+        this.manufacturer = manufacturer;
+        this.productionDate = productionDate;
+        this.deviceType = deviceType;
+        this.deviceTypeName = deviceTypeName;
+        this.assetValue = assetValue;
+        this.expectedServiceYears = expectedServiceYears;
+        this.longitude = longitude;
+        this.latitude = latitude;
+        this.equipmentLocation = equipmentLocation;
+        this.installTime = installTime;
+        this.maintainer = maintainer;
+        this.maintainerPhone = maintainerPhone;
+        this.ownershipUnit = ownershipUnit;
+        this.remark = remark;
+        this.images = images;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceName() { return deviceName; }
+    public String getDeviceModel() { return deviceModel; }
+    public String getDeviceSpec() { return deviceSpec; }
+    public String getManufacturer() { return manufacturer; }
+    public String getProductionDate() { return productionDate; }
+    public String getDeviceType() { return deviceType; }
+    public String getDeviceTypeName() { return deviceTypeName; }
+    public java.math.BigDecimal getAssetValue() { return assetValue; }
+    public Integer getExpectedServiceYears() { return expectedServiceYears; }
+    public java.math.BigDecimal getLongitude() { return longitude; }
+    public java.math.BigDecimal getLatitude() { return latitude; }
+    public String getEquipmentLocation() { return equipmentLocation; }
+    public String getInstallTime() { return installTime; }
+    public String getMaintainer() { return maintainer; }
+    public String getMaintainerPhone() { return maintainerPhone; }
+    public String getOwnershipUnit() { return ownershipUnit; }
+    public String getRemark() { return remark; }
+    public List<CockpitEquipmentImage> getImages() { return images; }
+}

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

@@ -0,0 +1,19 @@
+package com.zksy.cockpit.equipment;
+
+public class CockpitEquipmentImage {
+    private final String url;
+    private final String capturedAt;
+
+    public CockpitEquipmentImage(String url, String capturedAt) {
+        this.url = url;
+        this.capturedAt = capturedAt;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+
+    public String getCapturedAt() {
+        return capturedAt;
+    }
+}

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

@@ -0,0 +1,11 @@
+package com.zksy.cockpit.equipment;
+
+import org.springframework.stereotype.Service;
+
+@Service
+public class EmptyCockpitEquipmentArchiveAdapter implements CockpitEquipmentArchiveAdapter {
+    @Override
+    public CockpitEquipmentArchiveSnapshot load(String deviceCode) {
+        return null;
+    }
+}

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

@@ -0,0 +1,24 @@
+package com.zksy.cockpit.event;
+
+public class CockpitAlarmWarningRelation {
+    private final String relationId;
+    private final String warningNo;
+    private final String alarmId;
+    private final String relatedAt;
+
+    public CockpitAlarmWarningRelation(
+            String relationId,
+            String warningNo,
+            String alarmId,
+            String relatedAt) {
+        this.relationId = relationId;
+        this.warningNo = warningNo;
+        this.alarmId = alarmId;
+        this.relatedAt = relatedAt;
+    }
+
+    public String getRelationId() { return relationId; }
+    public String getWarningNo() { return warningNo; }
+    public String getAlarmId() { return alarmId; }
+    public String getRelatedAt() { return relatedAt; }
+}

+ 70 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventAlarm.java

@@ -0,0 +1,70 @@
+package com.zksy.cockpit.event;
+
+import java.math.BigDecimal;
+
+public class CockpitEventAlarm {
+    private final String alarmId;
+    private final String warningCode;
+    private final String warningName;
+    private final String warningType;
+    private final Integer level;
+    private final String levelColor;
+    private final String status;
+    private final String eventTime;
+    private final BigDecimal value;
+    private final BigDecimal thresholdMinValue;
+    private final BigDecimal thresholdMaxValue;
+    private final String unit;
+    private final String deviceCode;
+    private final String deviceName;
+    private final String location;
+
+    public CockpitEventAlarm(
+            String alarmId,
+            String warningCode,
+            String warningName,
+            String warningType,
+            Integer level,
+            String levelColor,
+            String status,
+            String eventTime,
+            BigDecimal value,
+            BigDecimal thresholdMinValue,
+            BigDecimal thresholdMaxValue,
+            String unit,
+            String deviceCode,
+            String deviceName,
+            String location) {
+        this.alarmId = alarmId;
+        this.warningCode = warningCode;
+        this.warningName = warningName;
+        this.warningType = warningType;
+        this.level = level;
+        this.levelColor = levelColor;
+        this.status = status;
+        this.eventTime = eventTime;
+        this.value = value;
+        this.thresholdMinValue = thresholdMinValue;
+        this.thresholdMaxValue = thresholdMaxValue;
+        this.unit = unit;
+        this.deviceCode = deviceCode;
+        this.deviceName = deviceName;
+        this.location = location;
+    }
+
+    public String getAlarmId() { return alarmId; }
+    public String getWarningCode() { return warningCode; }
+    public String getWarningName() { return warningName; }
+    public String getWarningType() { return warningType; }
+    public Integer getLevel() { return level; }
+    public String getLevelColor() { return levelColor; }
+    public String getStatus() { return status; }
+    public String getEventTime() { return eventTime; }
+    public BigDecimal getValue() { return value; }
+    public BigDecimal getThresholdMinValue() { return thresholdMinValue; }
+    public BigDecimal getThresholdMaxValue() { return thresholdMaxValue; }
+    public String getUnit() { return unit; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceName() { return deviceName; }
+    public String getLocation() { return location; }
+}

+ 19 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventLevelColor.java

@@ -0,0 +1,19 @@
+package com.zksy.cockpit.event;
+
+public final class CockpitEventLevelColor {
+    private CockpitEventLevelColor() {
+    }
+
+    public static String resolve(Integer level) {
+        if (level == null) {
+            return "UNKNOWN";
+        }
+        switch (level) {
+            case 1: return "RED";
+            case 2: return "YELLOW";
+            case 3: return "BLUE";
+            case 4: return "GREEN";
+            default: return "UNKNOWN";
+        }
+    }
+}

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

@@ -0,0 +1,14 @@
+package com.zksy.cockpit.event;
+
+import java.time.OffsetDateTime;
+
+public interface CockpitEventReadAdapter {
+    CockpitEventSnapshot loadCurrent(String deviceCode);
+
+    CockpitEventSnapshot loadHistory(
+            String deviceCode,
+            OffsetDateTime startTime,
+            OffsetDateTime endTime,
+            int page,
+            int pageSize);
+}

+ 78 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadResponse.java

@@ -0,0 +1,78 @@
+package com.zksy.cockpit.event;
+
+import java.util.List;
+
+public class CockpitEventReadResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String deviceCode;
+    private final String deviceType;
+    private final String deviceTypeName;
+    private final String state;
+    private final String stateReason;
+    private final List<CockpitEventWarning> warnings;
+    private final List<CockpitEventAlarm> alarms;
+    private final List<CockpitAlarmWarningRelation> alarmWarningRelations;
+    private final String startTime;
+    private final String endTime;
+    private final String timezone;
+    private final int page;
+    private final int pageSize;
+    private final int total;
+
+    public CockpitEventReadResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String deviceCode,
+            String deviceType,
+            String deviceTypeName,
+            String state,
+            String stateReason,
+            List<CockpitEventWarning> warnings,
+            List<CockpitEventAlarm> alarms,
+            List<CockpitAlarmWarningRelation> alarmWarningRelations,
+            String startTime,
+            String endTime,
+            String timezone,
+            int page,
+            int pageSize,
+            int total) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.deviceCode = deviceCode;
+        this.deviceType = deviceType;
+        this.deviceTypeName = deviceTypeName;
+        this.state = state;
+        this.stateReason = stateReason;
+        this.warnings = warnings;
+        this.alarms = alarms;
+        this.alarmWarningRelations = alarmWarningRelations;
+        this.startTime = startTime;
+        this.endTime = endTime;
+        this.timezone = timezone;
+        this.page = page;
+        this.pageSize = pageSize;
+        this.total = total;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceType() { return deviceType; }
+    public String getDeviceTypeName() { return deviceTypeName; }
+    public String getState() { return state; }
+    public String getStateReason() { return stateReason; }
+    public List<CockpitEventWarning> getWarnings() { return warnings; }
+    public List<CockpitEventAlarm> getAlarms() { return alarms; }
+    public List<CockpitAlarmWarningRelation> getAlarmWarningRelations() { return alarmWarningRelations; }
+    public String getStartTime() { return startTime; }
+    public String getEndTime() { return endTime; }
+    public String getTimezone() { return timezone; }
+    public int getPage() { return page; }
+    public int getPageSize() { return pageSize; }
+    public int getTotal() { return total; }
+}

+ 170 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadService.java

@@ -0,0 +1,170 @@
+package com.zksy.cockpit.event;
+
+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.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+public class CockpitEventReadService {
+    private static final int MAX_PAGE_SIZE = 1000;
+
+    private final CockpitEventReadAdapter adapter;
+    private final Clock clock;
+
+    public CockpitEventReadService(CockpitEventReadAdapter adapter, Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public CockpitEventReadResponse loadCurrent(String requestId, String deviceCode) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(deviceCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+        return response(requestId, snapshot, null, null, 1, 0);
+    }
+
+    public CockpitEventReadResponse loadHistory(
+            String requestId,
+            String deviceCode,
+            String startTime,
+            String endTime,
+            Integer page,
+            Integer pageSize) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+        OffsetDateTime start = parseTime(startTime, "start time");
+        OffsetDateTime end = parseTime(endTime, "end time");
+        if (start.isAfter(end)) {
+            throw new CockpitInvalidRequestException("start time must not be after end time");
+        }
+        int resolvedPage = page == null ? 1 : page;
+        int resolvedPageSize = pageSize == null ? 100 : pageSize;
+        if (resolvedPage < 1 || resolvedPageSize < 1 || resolvedPageSize > MAX_PAGE_SIZE) {
+            throw new CockpitInvalidRequestException("invalid history page");
+        }
+        CockpitEventSnapshot snapshot = adapter.loadHistory(
+                deviceCode.trim(), start, end, resolvedPage, resolvedPageSize);
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+        return response(requestId, snapshot, startTime, endTime, resolvedPage, resolvedPageSize);
+    }
+
+    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 CockpitEventReadResponse response(
+            String requestId,
+            CockpitEventSnapshot snapshot,
+            String startTime,
+            String endTime,
+            int page,
+            int pageSize) {
+        List<CockpitEventWarning> warnings = safeList(snapshot.getWarnings());
+        List<CockpitEventAlarm> alarms = safeList(snapshot.getAlarms());
+        List<CockpitAlarmWarningRelation> relations = safeList(snapshot.getAlarmWarningRelations());
+        String state = warnings.isEmpty() && alarms.isEmpty() ? "EMPTY" : "READY";
+        String stateReason = "EMPTY".equals(state) ? "NO_EVENTS" : "READY";
+        int resolvedTotal = snapshot.getTotal() == null ? warnings.size() + alarms.size() : snapshot.getTotal();
+        return new CockpitEventReadResponse(
+                requestId,
+                "v1",
+                true,
+                snapshot.getDeviceCode(),
+                snapshot.getDeviceType(),
+                snapshot.getDeviceTypeName(),
+                state,
+                stateReason,
+                warnings,
+                alarms,
+                relations,
+                startTime,
+                endTime,
+                "Asia/Shanghai",
+                page,
+                pageSize,
+                resolvedTotal);
+    }
+
+
+    private List<CockpitEventWarning> decorateWarnings(List<CockpitEventWarning> source) {
+        List<CockpitEventWarning> result = new ArrayList<>();
+        for (CockpitEventWarning item : source) {
+            if (item == null) {
+                continue;
+            }
+            result.add(new CockpitEventWarning(
+                    item.getWarningNo(), item.getWarningName(), item.getWarningType(), item.getLevel(),
+                    CockpitEventLevelColor.resolve(item.getLevel()), item.getStatus(), item.getEventTime(),
+                    item.getValue(), item.getUnit(), item.getDeviceCode(), item.getDeviceName(), item.getLocation()));
+        }
+        return result;
+    }
+
+    private List<CockpitEventAlarm> decorateAlarms(List<CockpitEventAlarm> source) {
+        List<CockpitEventAlarm> result = new ArrayList<>();
+        for (CockpitEventAlarm item : source) {
+            if (item == null) {
+                continue;
+            }
+            result.add(new CockpitEventAlarm(
+                    item.getAlarmId(), item.getWarningCode(), item.getWarningName(), item.getWarningType(),
+                    item.getLevel(), CockpitEventLevelColor.resolve(item.getLevel()), item.getStatus(),
+                    item.getEventTime(), item.getValue(), item.getThresholdMinValue(), item.getThresholdMaxValue(),
+                    item.getUnit(), item.getDeviceCode(), item.getDeviceName(), item.getLocation()));
+        }
+        return result;
+    }
+    private <T> List<T> safeList(List<T> values) {
+        return values == null ? new ArrayList<>() : values;
+    }
+
+    private OffsetDateTime parseTime(String value, String fieldName) {
+        if (isBlank(value)) {
+            throw new CockpitInvalidRequestException(fieldName + " is required");
+        }
+        try {
+            return OffsetDateTime.parse(value);
+        } catch (DateTimeParseException exception) {
+            throw new CockpitInvalidRequestException("invalid " + fieldName);
+        }
+    }
+
+    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"))));
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

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

@@ -0,0 +1,38 @@
+package com.zksy.cockpit.event;
+
+import java.util.List;
+
+public class CockpitEventSnapshot {
+    private final String deviceCode;
+    private final String deviceType;
+    private final String deviceTypeName;
+    private final List<CockpitEventWarning> warnings;
+    private final List<CockpitEventAlarm> alarms;
+    private final List<CockpitAlarmWarningRelation> alarmWarningRelations;
+    private final Integer total;
+
+    public CockpitEventSnapshot(
+            String deviceCode,
+            String deviceType,
+            String deviceTypeName,
+            List<CockpitEventWarning> warnings,
+            List<CockpitEventAlarm> alarms,
+            List<CockpitAlarmWarningRelation> alarmWarningRelations,
+            Integer total) {
+        this.deviceCode = deviceCode;
+        this.deviceType = deviceType;
+        this.deviceTypeName = deviceTypeName;
+        this.warnings = warnings;
+        this.alarms = alarms;
+        this.alarmWarningRelations = alarmWarningRelations;
+        this.total = total;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceType() { return deviceType; }
+    public String getDeviceTypeName() { return deviceTypeName; }
+    public List<CockpitEventWarning> getWarnings() { return warnings; }
+    public List<CockpitEventAlarm> getAlarms() { return alarms; }
+    public List<CockpitAlarmWarningRelation> getAlarmWarningRelations() { return alarmWarningRelations; }
+    public Integer getTotal() { return total; }
+}

+ 58 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventWarning.java

@@ -0,0 +1,58 @@
+package com.zksy.cockpit.event;
+
+import java.math.BigDecimal;
+
+public class CockpitEventWarning {
+    private final String warningNo;
+    private final String warningName;
+    private final String warningType;
+    private final Integer level;
+    private final String levelColor;
+    private final String status;
+    private final String eventTime;
+    private final BigDecimal value;
+    private final String unit;
+    private final String deviceCode;
+    private final String deviceName;
+    private final String location;
+
+    public CockpitEventWarning(
+            String warningNo,
+            String warningName,
+            String warningType,
+            Integer level,
+            String levelColor,
+            String status,
+            String eventTime,
+            BigDecimal value,
+            String unit,
+            String deviceCode,
+            String deviceName,
+            String location) {
+        this.warningNo = warningNo;
+        this.warningName = warningName;
+        this.warningType = warningType;
+        this.level = level;
+        this.levelColor = levelColor;
+        this.status = status;
+        this.eventTime = eventTime;
+        this.value = value;
+        this.unit = unit;
+        this.deviceCode = deviceCode;
+        this.deviceName = deviceName;
+        this.location = location;
+    }
+
+    public String getWarningNo() { return warningNo; }
+    public String getWarningName() { return warningName; }
+    public String getWarningType() { return warningType; }
+    public Integer getLevel() { return level; }
+    public String getLevelColor() { return levelColor; }
+    public String getStatus() { return status; }
+    public String getEventTime() { return eventTime; }
+    public BigDecimal getValue() { return value; }
+    public String getUnit() { return unit; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceName() { return deviceName; }
+    public String getLocation() { return location; }
+}

+ 23 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/EmptyCockpitEventReadAdapter.java

@@ -0,0 +1,23 @@
+package com.zksy.cockpit.event;
+
+import org.springframework.stereotype.Component;
+
+import java.time.OffsetDateTime;
+
+@Component
+public class EmptyCockpitEventReadAdapter implements CockpitEventReadAdapter {
+    @Override
+    public CockpitEventSnapshot loadCurrent(String deviceCode) {
+        return null;
+    }
+
+    @Override
+    public CockpitEventSnapshot loadHistory(
+            String deviceCode,
+            OffsetDateTime startTime,
+            OffsetDateTime endTime,
+            int page,
+            int pageSize) {
+        return null;
+    }
+}

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

@@ -0,0 +1,7 @@
+package com.zksy.cockpit.foundation;
+
+public class CockpitDeviceNotFoundException extends RuntimeException {
+    public CockpitDeviceNotFoundException(String message) {
+        super(message);
+    }
+}

+ 43 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetric.java

@@ -0,0 +1,43 @@
+package com.zksy.cockpit.type;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public class CockpitMetric {
+    private final String metricCode;
+    private final String metricName;
+    private final BigDecimal value;
+    private final String unit;
+    private final String status;
+    private final String sampledAt;
+    private final String freshness;
+    private final List<CockpitMetricPoint> points;
+
+    public CockpitMetric(
+            String metricCode,
+            String metricName,
+            BigDecimal value,
+            String unit,
+            String status,
+            String sampledAt,
+            String freshness,
+            List<CockpitMetricPoint> points) {
+        this.metricCode = metricCode;
+        this.metricName = metricName;
+        this.value = value;
+        this.unit = unit;
+        this.status = status;
+        this.sampledAt = sampledAt;
+        this.freshness = freshness;
+        this.points = points;
+    }
+
+    public String getMetricCode() { return metricCode; }
+    public String getMetricName() { return metricName; }
+    public BigDecimal getValue() { return value; }
+    public String getUnit() { return unit; }
+    public String getStatus() { return status; }
+    public String getSampledAt() { return sampledAt; }
+    public String getFreshness() { return freshness; }
+    public List<CockpitMetricPoint> getPoints() { return points; }
+}

+ 22 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetricPoint.java

@@ -0,0 +1,22 @@
+package com.zksy.cockpit.type;
+
+import java.math.BigDecimal;
+
+public class CockpitMetricPoint {
+    private final BigDecimal value;
+    private final String status;
+    private final String sampledAt;
+    private final String freshness;
+
+    public CockpitMetricPoint(BigDecimal value, String status, String sampledAt, String freshness) {
+        this.value = value;
+        this.status = status;
+        this.sampledAt = sampledAt;
+        this.freshness = freshness;
+    }
+
+    public BigDecimal getValue() { return value; }
+    public String getStatus() { return status; }
+    public String getSampledAt() { return sampledAt; }
+    public String getFreshness() { return freshness; }
+}

+ 55 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitMetricSnapshot.java

@@ -0,0 +1,55 @@
+package com.zksy.cockpit.type;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public class CockpitMetricSnapshot {
+    private final String metricCode;
+    private final String metricName;
+    private final BigDecimal value;
+    private final String unit;
+    private final String status;
+    private final String sampledAt;
+    private final List<PointSnapshot> points;
+
+    public CockpitMetricSnapshot(
+            String metricCode,
+            String metricName,
+            BigDecimal value,
+            String unit,
+            String status,
+            String sampledAt,
+            List<PointSnapshot> points) {
+        this.metricCode = metricCode;
+        this.metricName = metricName;
+        this.value = value;
+        this.unit = unit;
+        this.status = status;
+        this.sampledAt = sampledAt;
+        this.points = points;
+    }
+
+    public String getMetricCode() { return metricCode; }
+    public String getMetricName() { return metricName; }
+    public BigDecimal getValue() { return value; }
+    public String getUnit() { return unit; }
+    public String getStatus() { return status; }
+    public String getSampledAt() { return sampledAt; }
+    public List<PointSnapshot> getPoints() { return points; }
+
+    public static class PointSnapshot {
+        private final BigDecimal value;
+        private final String status;
+        private final String sampledAt;
+
+        public PointSnapshot(BigDecimal value, String status, String sampledAt) {
+            this.value = value;
+            this.status = status;
+            this.sampledAt = sampledAt;
+        }
+
+        public BigDecimal getValue() { return value; }
+        public String getStatus() { return status; }
+        public String getSampledAt() { return sampledAt; }
+    }
+}

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

@@ -0,0 +1,14 @@
+package com.zksy.cockpit.type;
+
+import java.time.OffsetDateTime;
+
+public interface CockpitTypeMetricsAdapter {
+    CockpitTypeMetricsSnapshot loadCurrent(String deviceCode);
+
+    CockpitTypeMetricsSnapshot loadHistory(
+            String deviceCode,
+            OffsetDateTime startTime,
+            OffsetDateTime endTime,
+            int page,
+            int pageSize);
+}

+ 70 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsResponse.java

@@ -0,0 +1,70 @@
+package com.zksy.cockpit.type;
+
+import java.util.List;
+
+public class CockpitTypeMetricsResponse {
+    private final String requestId;
+    private final String apiVersion;
+    private final boolean readOnly;
+    private final String deviceCode;
+    private final String deviceType;
+    private final String deviceTypeName;
+    private final String state;
+    private final String stateReason;
+    private final List<CockpitMetric> metrics;
+    private final String startTime;
+    private final String endTime;
+    private final String timezone;
+    private final int page;
+    private final int pageSize;
+    private final int total;
+
+    public CockpitTypeMetricsResponse(
+            String requestId,
+            String apiVersion,
+            boolean readOnly,
+            String deviceCode,
+            String deviceType,
+            String deviceTypeName,
+            String state,
+            String stateReason,
+            List<CockpitMetric> metrics,
+            String startTime,
+            String endTime,
+            String timezone,
+            int page,
+            int pageSize,
+            int total) {
+        this.requestId = requestId;
+        this.apiVersion = apiVersion;
+        this.readOnly = readOnly;
+        this.deviceCode = deviceCode;
+        this.deviceType = deviceType;
+        this.deviceTypeName = deviceTypeName;
+        this.state = state;
+        this.stateReason = stateReason;
+        this.metrics = metrics;
+        this.startTime = startTime;
+        this.endTime = endTime;
+        this.timezone = timezone;
+        this.page = page;
+        this.pageSize = pageSize;
+        this.total = total;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return apiVersion; }
+    public boolean isReadOnly() { return readOnly; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceType() { return deviceType; }
+    public String getDeviceTypeName() { return deviceTypeName; }
+    public String getState() { return state; }
+    public String getStateReason() { return stateReason; }
+    public List<CockpitMetric> getMetrics() { return metrics; }
+    public String getStartTime() { return startTime; }
+    public String getEndTime() { return endTime; }
+    public String getTimezone() { return timezone; }
+    public int getPage() { return page; }
+    public int getPageSize() { return pageSize; }
+    public int getTotal() { return total; }
+}

+ 247 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/CockpitTypeMetricsService.java

@@ -0,0 +1,247 @@
+package com.zksy.cockpit.type;
+
+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.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+@Service
+public class CockpitTypeMetricsService {
+    private static final int STALE_AFTER_SECONDS = 60;
+    private static final int MAX_PAGE_SIZE = 1000;
+
+    private final CockpitTypeMetricsAdapter adapter;
+    private final Clock clock;
+
+    public CockpitTypeMetricsService(CockpitTypeMetricsAdapter adapter, Clock clock) {
+        this.adapter = adapter;
+        this.clock = clock;
+    }
+
+    public CockpitTypeMetricsResponse loadCurrent(String requestId, String deviceCode) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+
+        CockpitTypeMetricsSnapshot snapshot = adapter.loadCurrent(deviceCode.trim());
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+
+        List<CockpitMetric> metrics = new ArrayList<>();
+        if (snapshot.getMetrics() != null) {
+            for (CockpitMetricSnapshot source : snapshot.getMetrics()) {
+                if (source == null) {
+                    continue;
+                }
+                String freshness = currentFreshness(source.getSampledAt());
+                metrics.add(new CockpitMetric(
+                        normalizedMetricCode(source.getMetricCode()),
+                        normalizedMetricName(source.getMetricName()),
+                        source.getValue(),
+                        normalizedUnit(source.getUnit()),
+                        source.getStatus(),
+                        source.getSampledAt(),
+                        freshness,
+                        null));
+            }
+        }
+
+        String state = stateForCurrent(metrics);
+        return new CockpitTypeMetricsResponse(
+                requestId,
+                "v1",
+                true,
+                snapshot.getDeviceCode(),
+                snapshot.getDeviceType(),
+                snapshot.getDeviceTypeName(),
+                state,
+                stateReason(state),
+                metrics,
+                null,
+                null,
+                "Asia/Shanghai",
+                1,
+                0,
+                0);
+    }
+
+    public CockpitTypeMetricsResponse loadHistory(
+            String requestId,
+            String deviceCode,
+            String startTime,
+            String endTime,
+            Integer page,
+            Integer pageSize) {
+        if (isBlank(deviceCode)) {
+            throw new CockpitInvalidRequestException("device code is required");
+        }
+
+        OffsetDateTime start = parseTime(startTime, "start time");
+        OffsetDateTime end = parseTime(endTime, "end time");
+        if (start.isAfter(end)) {
+            throw new CockpitInvalidRequestException("start time must not be after end time");
+        }
+        int resolvedPage = page == null ? 1 : page;
+        int resolvedPageSize = pageSize == null ? 100 : pageSize;
+        if (resolvedPage < 1 || resolvedPageSize < 1 || resolvedPageSize > MAX_PAGE_SIZE) {
+            throw new CockpitInvalidRequestException("invalid history page");
+        }
+
+        CockpitTypeMetricsSnapshot snapshot = adapter.loadHistory(
+                deviceCode.trim(),
+                start,
+                end,
+                resolvedPage,
+                resolvedPageSize);
+        if (snapshot == null) {
+            throw new CockpitDeviceNotFoundException("device not found");
+        }
+
+        List<CockpitMetric> metrics = new ArrayList<>();
+        int total = 0;
+        if (snapshot.getMetrics() != null) {
+            for (CockpitMetricSnapshot source : snapshot.getMetrics()) {
+                if (source == null) {
+                    continue;
+                }
+
+                List<CockpitMetricPoint> points = new ArrayList<>();
+                if (source.getPoints() != null) {
+                    for (CockpitMetricSnapshot.PointSnapshot sourcePoint : source.getPoints()) {
+                        if (sourcePoint == null) {
+                            continue;
+                        }
+                        points.add(new CockpitMetricPoint(
+                                sourcePoint.getValue(),
+                                sourcePoint.getStatus(),
+                                sourcePoint.getSampledAt(),
+                                "HISTORICAL"));
+                    }
+                    points.sort(Comparator.comparing(CockpitMetricPoint::getSampledAt));
+                }
+                total += points.size();
+                metrics.add(new CockpitMetric(
+                        normalizedMetricCode(source.getMetricCode()),
+                        normalizedMetricName(source.getMetricName()),
+                        source.getValue(),
+                        normalizedUnit(source.getUnit()),
+                        source.getStatus(),
+                        source.getSampledAt(),
+                        "HISTORICAL",
+                        points));
+            }
+        }
+
+        Integer adapterTotal = snapshot.getTotal();
+        int responseTotal = adapterTotal == null ? total : adapterTotal;
+        String state = metrics.isEmpty() || total == 0 ? "EMPTY" : "READY";
+        return new CockpitTypeMetricsResponse(
+                requestId,
+                "v1",
+                true,
+                snapshot.getDeviceCode(),
+                snapshot.getDeviceType(),
+                snapshot.getDeviceTypeName(),
+                state,
+                stateReason(state),
+                metrics,
+                startTime,
+                endTime,
+                "Asia/Shanghai",
+                resolvedPage,
+                resolvedPageSize,
+                responseTotal);
+    }
+
+    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 String currentFreshness(String sampledAt) {
+        try {
+            OffsetDateTime sampleTime = OffsetDateTime.parse(sampledAt);
+            Instant staleAt = clock.instant().minusSeconds(STALE_AFTER_SECONDS);
+            return sampleTime.toInstant().isBefore(staleAt) ? "STALE" : "CURRENT";
+        } catch (DateTimeParseException | NullPointerException exception) {
+            throw new CockpitReadException("invalid metric sampledAt: " + exception.getMessage());
+        }
+    }
+
+    private String stateForCurrent(List<CockpitMetric> metrics) {
+        if (metrics.isEmpty()) {
+            return "EMPTY";
+        }
+        boolean stale = metrics.stream().anyMatch(metric -> "STALE".equals(metric.getFreshness()));
+        return stale ? "STALE" : "CURRENT";
+    }
+
+    private String stateReason(String state) {
+        if ("EMPTY".equals(state)) {
+            return "NO_METRICS";
+        }
+        if ("STALE".equals(state)) {
+            return "SAMPLE_OUTDATED";
+        }
+        if ("CURRENT".equals(state)) {
+            return "READY";
+        }
+        return "READY";
+    }
+
+    private OffsetDateTime parseTime(String value, String fieldName) {
+        if (isBlank(value)) {
+            throw new CockpitInvalidRequestException(fieldName + " is required");
+        }
+        try {
+            return OffsetDateTime.parse(value);
+        } catch (DateTimeParseException exception) {
+            throw new CockpitInvalidRequestException("invalid " + fieldName);
+        }
+    }
+
+    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"))));
+    }
+
+    private String normalizedMetricCode(String value) {
+        return isBlank(value) ? "UNKNOWN" : value.trim();
+    }
+
+    private String normalizedMetricName(String value) {
+        return isBlank(value) ? "未知指标" : value.trim();
+    }
+
+    private String normalizedUnit(String value) {
+        return value == null ? "" : value;
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+}

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

@@ -0,0 +1,38 @@
+package com.zksy.cockpit.type;
+
+import java.util.List;
+
+public class CockpitTypeMetricsSnapshot {
+    private final String deviceCode;
+    private final String deviceType;
+    private final String deviceTypeName;
+    private final List<CockpitMetricSnapshot> metrics;
+    private final Integer total;
+
+    public CockpitTypeMetricsSnapshot(
+            String deviceCode,
+            String deviceType,
+            String deviceTypeName,
+            List<CockpitMetricSnapshot> metrics) {
+        this(deviceCode, deviceType, deviceTypeName, metrics, null);
+    }
+
+    public CockpitTypeMetricsSnapshot(
+            String deviceCode,
+            String deviceType,
+            String deviceTypeName,
+            List<CockpitMetricSnapshot> metrics,
+            Integer total) {
+        this.deviceCode = deviceCode;
+        this.deviceType = deviceType;
+        this.deviceTypeName = deviceTypeName;
+        this.metrics = metrics;
+        this.total = total;
+    }
+
+    public String getDeviceCode() { return deviceCode; }
+    public String getDeviceType() { return deviceType; }
+    public String getDeviceTypeName() { return deviceTypeName; }
+    public List<CockpitMetricSnapshot> getMetrics() { return metrics; }
+    public Integer getTotal() { return total; }
+}

+ 23 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/type/EmptyCockpitTypeMetricsAdapter.java

@@ -0,0 +1,23 @@
+package com.zksy.cockpit.type;
+
+import org.springframework.stereotype.Component;
+
+import java.time.OffsetDateTime;
+
+@Component
+public class EmptyCockpitTypeMetricsAdapter implements CockpitTypeMetricsAdapter {
+    @Override
+    public CockpitTypeMetricsSnapshot loadCurrent(String deviceCode) {
+        return null;
+    }
+
+    @Override
+    public CockpitTypeMetricsSnapshot loadHistory(
+            String deviceCode,
+            OffsetDateTime startTime,
+            OffsetDateTime endTime,
+            int page,
+            int pageSize) {
+        return null;
+    }
+}

+ 3 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/domain/DrainagePartition.java

@@ -50,6 +50,9 @@ public class DrainagePartition {
     @ApiModelProperty("纬度")
     private BigDecimal latitude;
 
+    @ApiModelProperty("分区面坐标JSON(百度坐标点数组)")
+    private String points;
+
     @ApiModelProperty("关联设备ID(多个用逗号分隔)")
     private String equipmentId;
 

+ 5 - 2
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/DrainageWarningServiceImpl.java

@@ -72,8 +72,11 @@ public class DrainageWarningServiceImpl extends ServiceImpl<DrainageWarningMappe
                                                   boolean historyOnly, String equipmentName) {
         Page<DrainageWarning> page = new Page<>(pageNum, pageSize);
         LambdaQueryWrapper<DrainageWarning> wrapper = new LambdaQueryWrapper<>();
-        // historyOnly=true 时不再自动添加 status IN (HISTORY_STATUSES) 条件
-        // 由前端通过 status 参数控制状态过滤,避免数据库 status 值格式不匹配导致查不到数据
+        // 历史查询默认只返回已处置或已解除的记录;传入 status 时允许
+        // 页面进一步限定其中一种状态。
+        if (historyOnly && (status == null || status.isEmpty())) {
+            wrapper.in(DrainageWarning::getStatus, HISTORY_STATUSES);
+        }
         // 附加筛选条件
         if (warningLevel != null) {
             wrapper.eq(DrainageWarning::getWarningLevel, warningLevel);

+ 2 - 2
pipe-network-service/zksy-system/src/main/resources/mapper/WaterSupply/WaterSupplyGisMap/WaterSupplyGisMapMapper.xml

@@ -11,7 +11,7 @@
     </select>
     <select id="selectPumpStationFeatures" resultType="java.util.Map">
         SELECT id, station_code code, station_name name, status, "location", longitude, latitude
-        FROM app_user.water_pump_station WHERE del_flag = '0' AND longitude IS NOT NULL AND latitude IS NOT NULL
+        FROM app_user.pump_station WHERE del_flag = '0' AND station_type = 'water_supply' AND longitude IS NOT NULL AND latitude IS NOT NULL
     </select>
     <select id="selectPipeFeatures" resultType="java.util.Map">
         SELECT id, pipe_code code, pipe_name name, status, start_point AS "location",
@@ -34,7 +34,7 @@
         FROM app_user.water_plant_info WHERE del_flag = '0'
         UNION ALL
         SELECT 'pumpStation', '泵站', COUNT(*), COALESCE(SUM(CASE WHEN longitude IS NOT NULL AND latitude IS NOT NULL THEN 1 ELSE 0 END), 0), COALESCE(SUM(CASE WHEN longitude IS NULL OR latitude IS NULL THEN 1 ELSE 0 END), 0)
-        FROM app_user.water_pump_station WHERE del_flag = '0'
+        FROM app_user.pump_station WHERE del_flag = '0' AND station_type = 'water_supply'
         UNION ALL
         SELECT 'pipe', '供水管网', COUNT(*), COALESCE(SUM(CASE WHEN start_longitude IS NOT NULL AND start_latitude IS NOT NULL AND end_longitude IS NOT NULL AND end_latitude IS NOT NULL THEN 1 ELSE 0 END), 0), COALESCE(SUM(CASE WHEN start_longitude IS NULL OR start_latitude IS NULL OR end_longitude IS NULL OR end_latitude IS NULL THEN 1 ELSE 0 END), 0)
         FROM app_user.water_pipe_info WHERE del_flag = '0'

+ 4 - 1
pipe-network-service/zksy-system/src/main/resources/mapper/system/SysUserMapper.xml

@@ -67,6 +67,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 		<if test="userName != null and userName != ''">
 			AND u.user_name like concat('%', #{userName}, '%')
 		</if>
+		<if test="nickName != null and nickName != ''">
+			AND u.nick_name like concat('%', #{nickName}, '%')
+		</if>
 		<if test="status != null and status != ''">
 			AND u.status = #{status}
 		</if>
@@ -227,4 +230,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         </foreach> 
  	</delete>
 	
-</mapper> 
+</mapper>

+ 91 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/WaterSupply/importing/WaterDeviceLedgerImportServiceTest.java

@@ -0,0 +1,91 @@
+package com.zksy.WaterSupply.importing;
+
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.mapper.EquipmentTypeMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.math.BigDecimal;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class WaterDeviceLedgerImportServiceTest {
+    private WaterDeviceLedgerImportService service;
+    private EquipmentBaseService equipmentBaseService;
+    private EquipmentTypeMapper equipmentTypeMapper;
+
+    @BeforeEach
+    void setUp() {
+        equipmentBaseService = mock(EquipmentBaseService.class);
+        equipmentTypeMapper = mock(EquipmentTypeMapper.class);
+        service = new WaterDeviceLedgerImportService(equipmentBaseService, equipmentTypeMapper);
+    }
+    @Test
+    void importDevicesSavesWaterTypeWithEquipmentImage() {
+        EquipmentType waterRoot = type("db-water-root", "water-root", "供水", "0");
+        EquipmentType pressureType = type("db-water-pressure", "water-pressure", "压力计", "db-water-root");
+        EquipmentType gasRoot = type("db-gas-root", "gas-root", "燃气", "0");
+        when(equipmentTypeMapper.selectList(any())).thenReturn(Arrays.asList(waterRoot, pressureType, gasRoot));
+        when(equipmentBaseService.getOne(any(), eq(false))).thenReturn(null);
+        when(equipmentBaseService.save(any(EquipmentBase.class))).thenReturn(true);
+
+        WaterDeviceLedgerImportDTO row = new WaterDeviceLedgerImportDTO();
+        row.setEquipmentCode(" CN-GS-202609050001 ");
+        row.setEquipmentName("导入压力计");
+        row.setEquipmentTypeName("压力计");
+        row.setEquipmentLocation("测试位置");
+        row.setLongitude(new BigDecimal("113.28"));
+        row.setLatitude(new BigDecimal("23.12"));
+        row.setEquipmentImage("https://example.com/device.jpg");
+
+        assertEquals("成功导入 1 台供水设备", service.importDevices(Collections.singletonList(row), false));
+
+        ArgumentCaptor<EquipmentBase> captor = ArgumentCaptor.forClass(EquipmentBase.class);
+        verify(equipmentBaseService).save(captor.capture());
+        assertEquals("CN-GS-202609050001", captor.getValue().getEquipmentCode());
+        assertEquals("db-water-pressure", captor.getValue().getEquipmentTypeId());
+        assertEquals("https://example.com/device.jpg", captor.getValue().getEquipmentImage());
+        verify(equipmentBaseService, never()).updateById(any(EquipmentBase.class));
+    }
+
+    @Test
+    void importDevicesRejectsNonWaterTypeWithoutSaving() {
+        EquipmentType waterRoot = type("db-water-root", "water-root", "供水", "0");
+        EquipmentType gasChild = type("db-gas-pressure", "gas-pressure", "燃气压力计", "db-gas-root");
+        EquipmentType gasRoot = type("db-gas-root", "gas-root", "燃气", "0");
+        when(equipmentTypeMapper.selectList(any())).thenReturn(Arrays.asList(waterRoot, gasChild, gasRoot));
+
+        WaterDeviceLedgerImportDTO row = new WaterDeviceLedgerImportDTO();
+        row.setEquipmentCode("CN-RQ-202609050001");
+        row.setEquipmentName("燃气压力计");
+        row.setEquipmentTypeName("燃气压力计");
+
+        IllegalArgumentException error = assertThrows(IllegalArgumentException.class,
+                () -> service.importDevices(Collections.singletonList(row), true));
+
+        assertEquals("导入失败:设备类型不属于供水:燃气压力计", error.getMessage());
+        verify(equipmentBaseService, never()).save(any(EquipmentBase.class));
+        verify(equipmentBaseService, never()).updateById(any(EquipmentBase.class));
+    }
+
+    private static EquipmentType type(String id, String typeId, String name, String parentId) {
+        EquipmentType value = new EquipmentType();
+        value.setId(id);
+        value.setTypeId(typeId);
+        value.setTypeName(name);
+        value.setParentTypeId(parentId);
+        return value;
+    }
+}

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

@@ -0,0 +1,62 @@
+package com.zksy.base.service.impl;
+
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.domain.WorkOrderLog;
+import com.zksy.base.mapper.WorkOrderLogMapper;
+import com.zksy.base.mapper.WorkOrderMapper;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.exception.ServiceException;
+import com.zksy.system.service.ISysUserService;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+class BusinessWorkOrderServiceImplTest {
+
+    @Test
+    void dispatchRejectsMissingOrInactiveReceiverBeforeUpdatingOrder() {
+        BusinessWorkOrderServiceImpl service = new BusinessWorkOrderServiceImpl();
+        WorkOrderMapper orderMapper = mock(WorkOrderMapper.class);
+        ISysUserService users = mock(ISysUserService.class);
+        ReflectionTestUtils.setField(service, "baseMapper", orderMapper);
+        ReflectionTestUtils.setField(service, "sysUserService", users);
+        when(users.selectUserById(88L)).thenReturn(null);
+
+        assertThrows(ServiceException.class, () -> service.dispatchOrder(1L, 88L, null, 7L, "operator"));
+        verify(orderMapper, never()).selectById(any());
+        verify(orderMapper, never()).updateById(any(WorkOrder.class));
+    }
+
+    @Test
+    void dispatchAcceptsActiveNonDeletedReceiverAndMovesOrderToStatusTwo() {
+        BusinessWorkOrderServiceImpl service = new BusinessWorkOrderServiceImpl();
+        WorkOrderMapper orderMapper = mock(WorkOrderMapper.class);
+        WorkOrderLogMapper logs = mock(WorkOrderLogMapper.class);
+        ISysUserService users = mock(ISysUserService.class);
+        ReflectionTestUtils.setField(service, "baseMapper", orderMapper);
+        ReflectionTestUtils.setField(service, "workOrderLogMapper", logs);
+        ReflectionTestUtils.setField(service, "sysUserService", users);
+
+        SysUser user = new SysUser();
+        user.setUserId(88L);
+        user.setStatus("0");
+        user.setDelFlag("0");
+        when(users.selectUserById(88L)).thenReturn(user);
+        WorkOrder pending = new WorkOrder();
+        pending.setOrderId(1L);
+        pending.setOrderStatus(1);
+        when(orderMapper.selectById(1L)).thenReturn(pending);
+
+        assertTrue(service.dispatchOrder(1L, 88L, "处理", 7L, "operator"));
+        ArgumentCaptor<WorkOrder> update = ArgumentCaptor.forClass(WorkOrder.class);
+        verify(orderMapper).updateById(update.capture());
+        org.junit.jupiter.api.Assertions.assertEquals(2, update.getValue().getOrderStatus());
+        org.junit.jupiter.api.Assertions.assertEquals("88", update.getValue().getReceiveUser());
+        verify(logs).insert(any(WorkOrderLog.class));
+    }
+}

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

@@ -0,0 +1,797 @@
+package com.zksy.base.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.zksy.base.alarm.domain.AlarmData;
+import com.zksy.base.alarm.mapper.AlarmDataMapper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentMaintain;
+import com.zksy.base.domain.EquipmentStatus;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.domain.WorkOrder;
+import com.zksy.base.domain.vo.AbnormalDeviceVO;
+import com.zksy.base.domain.vo.DeviceGisVO;
+import com.zksy.base.domain.vo.DeviceLedgerStatisticsVO;
+import com.zksy.base.domain.vo.DeviceTypeStatisticsVO;
+import com.zksy.base.domain.vo.MaintainOrderVO;
+import com.zksy.base.mapper.EquipmentMaintainMapper;
+import com.zksy.base.mapper.EquipmentStatusMapper;
+import com.zksy.base.mapper.EquipmentTypeMapper;
+import com.zksy.base.mapper.WorkOrderMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.system.service.ISysUserService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class WaterSupplyDeviceServiceImplTest {
+
+    @BeforeAll
+    static void initializeMybatisPlusLambdaCache() {
+        MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
+        TableInfoHelper.initTableInfo(assistant, EquipmentBase.class);
+        TableInfoHelper.initTableInfo(assistant, EquipmentStatus.class);
+        TableInfoHelper.initTableInfo(assistant, AlarmData.class);
+        TableInfoHelper.initTableInfo(assistant, WorkOrder.class);
+    }
+
+    private WaterSupplyDeviceServiceImpl service;
+    private EquipmentBaseService equipmentBaseService;
+    private EquipmentTypeMapper equipmentTypeMapper;
+    private EquipmentStatusMapper equipmentStatusMapper;
+    private EquipmentMaintainMapper equipmentMaintainMapper;
+    private AlarmDataMapper alarmDataMapper;
+    private WorkOrderMapper workOrderMapper;
+    private com.zksy.base.service.BusinessWorkOrderService businessWorkOrderService;
+
+    private EquipmentBase pressureDevice;
+    private EquipmentBase repairDevice;
+    private EquipmentBase gasDevice;
+
+    @BeforeEach
+    void setUp() {
+        service = Mockito.spy(new WaterSupplyDeviceServiceImpl());
+        equipmentBaseService = mock(EquipmentBaseService.class);
+        equipmentTypeMapper = mock(EquipmentTypeMapper.class);
+        equipmentStatusMapper = mock(EquipmentStatusMapper.class);
+        equipmentMaintainMapper = mock(EquipmentMaintainMapper.class);
+        alarmDataMapper = mock(AlarmDataMapper.class);
+        workOrderMapper = mock(WorkOrderMapper.class);
+        businessWorkOrderService = mock(com.zksy.base.service.BusinessWorkOrderService.class);
+
+        ReflectionTestUtils.setField(service, "equipmentBaseService", equipmentBaseService);
+        ReflectionTestUtils.setField(service, "equipmentTypeMapper", equipmentTypeMapper);
+        ReflectionTestUtils.setField(service, "equipmentStatusMapper", equipmentStatusMapper);
+        ReflectionTestUtils.setField(service, "equipmentMaintainMapper", equipmentMaintainMapper);
+        ReflectionTestUtils.setField(service, "alarmDataMapper", alarmDataMapper);
+        ReflectionTestUtils.setField(service, "workOrderMapper", workOrderMapper);
+        ReflectionTestUtils.setField(service, "businessWorkOrderService", businessWorkOrderService);
+
+        pressureDevice = device("water-pressure-1", "WS-PRESSURE-001", "供水压力监测点", "water-pressure");
+        repairDevice = device("water-flow-1", "WS-FLOW-001", "供水流量监测点", "water-flow");
+        gasDevice = device("gas-1", "GAS-001", "燃气监测点", "gas-root");
+
+        when(equipmentBaseService.findByTopLevelType("供水")).thenReturn(Arrays.asList(
+                pressureDevice, repairDevice));
+        when(equipmentTypeMapper.selectList(any())).thenReturn(Arrays.asList(
+                type("water-root", "供水", "0"),
+                type("water-pressure", "供水压力计", "water-root"),
+                type("water-flow", "供水流量计", "water-root"),
+                type("gas-root", "燃气设备", "0")));
+        when(equipmentTypeMapper.selectBatchIds(any())).thenReturn(Arrays.asList(
+                type("water-pressure", "供水压力计", "water-root"),
+                type("water-flow", "供水流量计", "water-root"),
+                type("gas-root", "燃气设备", "0")));
+    }
+
+    @Test
+    void typeStatisticsCountOnlyTheWaterTypeSubtree() {
+        EquipmentBase secondPressure = device("water-pressure-2", "WS-PRESSURE-002",
+                "第二供水压力监测点", "water-pressure");
+        when(equipmentBaseService.findByTopLevelType("供水")).thenReturn(Arrays.asList(
+                pressureDevice, secondPressure, repairDevice));
+        List<DeviceTypeStatisticsVO> roots = service.getDeviceTypeStatistics();
+
+        assertEquals(1, roots.size());
+        assertEquals("water-root", roots.get(0).getTypeId());
+        assertEquals(3, roots.get(0).getDeviceCount());
+        List<String> childTypeIds = roots.get(0).getChildren().stream()
+                .map(DeviceTypeStatisticsVO::getTypeId)
+                .sorted()
+                .collect(Collectors.toList());
+        assertEquals(Arrays.asList("water-flow", "water-pressure"), childTypeIds);
+    }
+
+    @Test
+    void ledgerStatisticsCountsOnlyWaterDevicesAndMissingStatusAsOffline() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+
+        DeviceLedgerStatisticsVO stats = service.getDeviceLedgerStatistics();
+
+        assertEquals(2, stats.getTotal());
+        assertEquals(1, stats.getOnline());
+        assertEquals(1, stats.getOffline());
+        assertEquals(50.0, stats.getOnlineRate());
+    }
+
+    @Test
+    void ledgerResolvesTypeNameByEquipmentTypePrimaryKey() {
+        pressureDevice.setEquipmentTypeId("db-pressure-id");
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 0, 1)));
+        EquipmentType resolvedType = type("db-pressure-id", "business-pressure", "water-root");
+        resolvedType.setTypeId("business-pressure-code");
+        when(equipmentTypeMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(resolvedType));
+
+        Page<DeviceGisVO> result = service.getDeviceLedgerPage(
+                1, 10, null, null, null, null, null, null);
+
+        assertEquals("business-pressure", result.getRecords().get(0).getEquipmentTypeName());
+    }
+
+    @Test
+    void ledgerPageReturnsEquipmentImage() {
+        pressureDevice.setEquipmentImage("https://example.com/pressure-device.jpg");
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 0, 1)));
+        when(equipmentTypeMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(
+                type("water-pressure", "water-pressure", "water-root")));
+
+        Page<DeviceGisVO> result = service.getDeviceLedgerPage(
+                1, 10, null, null, null, null, null, null);
+
+        assertEquals("https://example.com/pressure-device.jpg",
+                result.getRecords().get(0).getEquipmentImage());
+    }
+
+    @Test
+    void ledgerPageAppliesWaterOwnershipAndCurrentStatusFilter() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(repairDevice.getEquipmentId(), 3, 0, 0),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+
+        Page<DeviceGisVO> result = service.getDeviceLedgerPage(
+                1, 10, null, null, null, 1, null, null);
+
+        assertEquals(1, result.getTotal());
+        assertEquals(Collections.singletonList("water-pressure-1"), result.getRecords().stream()
+                .map(DeviceGisVO::getEquipmentId)
+                .collect(Collectors.toList()));
+        assertEquals(1, result.getRecords().get(0).getCurrentStatus());
+    }
+
+    @Test
+    void ledgerExportReturnsAllMatchingWaterDevicesWithoutPagination() {
+        EquipmentBase secondPressure = device("water-pressure-2", "WS-PRESSURE-002",
+                "第二供水压力监测点", "water-pressure");
+        when(equipmentBaseService.findByTopLevelType("供水")).thenReturn(Arrays.asList(
+                pressureDevice, secondPressure, repairDevice));
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(secondPressure.getEquipmentId(), 1, 0, 1),
+                status(repairDevice.getEquipmentId(), 3, 0, 0),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+
+        List<DeviceGisVO> result = service.getDeviceLedgerExport(
+                null, null, null, 1, null, null);
+
+        assertEquals(Arrays.asList("water-pressure-1", "water-pressure-2"), result.stream()
+                .map(DeviceGisVO::getEquipmentId)
+                .collect(Collectors.toList()));
+    }
+
+    @Test
+    void createWaterDeviceAcceptsWaterTypeAndRejectsNonWaterType() {
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentCode("WS-NEW-001");
+        device.setEquipmentName("新增供水设备");
+        device.setEquipmentTypeId("water-child");
+        when(equipmentTypeMapper.selectById("water-child"))
+                .thenReturn(type("water-child", "供水压力计", "water-root"));
+        when(equipmentTypeMapper.selectList(any())).thenReturn(Arrays.asList(
+                type("water-root", "供水", "0"),
+                type("water-child", "供水压力计", "water-root")));
+        doReturn(0L).when(service).count(any());
+        doReturn(true).when(service).save(any(EquipmentBase.class));
+
+        assertTrue(service.createWaterDevice(device));
+        assertEquals("water-child", device.getEquipmentTypeId());
+
+        EquipmentBase gasDevice = new EquipmentBase();
+        gasDevice.setEquipmentCode("GAS-NEW-001");
+        gasDevice.setEquipmentTypeId("gas-root");
+        when(equipmentTypeMapper.selectById("gas-root"))
+                .thenReturn(type("gas-root", "燃气", "0"));
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.createWaterDevice(gasDevice));
+        assertEquals("设备类型不属于供水:gas-root", error.getMessage());
+    }
+
+    @Test
+    void deleteWaterDevicesRejectsNonWaterDevices() {
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.deleteWaterDevices(Collections.singletonList("gas-1")));
+        assertEquals("存在非供水设备,无法删除:gas-1", error.getMessage());
+    }
+
+    @Test
+    void ledgerPageAppliesAlarmStatusAndAlertLevelFilters() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(repairDevice.getEquipmentId(), 1, 0, 1),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Arrays.asList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1),
+                alarm(gasDevice.getEquipmentCode(), "燃气浓度超限", 2)));
+
+        Page<DeviceGisVO> result = service.getDeviceLedgerPage(
+                1, 10, null, null, null, null, 1, 1);
+
+        assertEquals(1, result.getTotal());
+        assertEquals(Collections.singletonList("water-pressure-1"), result.getRecords().stream()
+                .map(DeviceGisVO::getEquipmentId)
+                .collect(Collectors.toList()));
+        assertEquals(1, result.getRecords().get(0).getAlarmStatus());
+        assertEquals(1, result.getRecords().get(0).getAlertLevel());
+    }
+
+    @Test
+    void abnormalPageUsesAlarmReasonAlertLevelAndUnifiedWorkOrder() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(repairDevice.getEquipmentId(), 3, 0, 0),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Arrays.asList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1),
+                alarm(gasDevice.getEquipmentCode(), "燃气浓度超限", 2)));
+        when(workOrderMapper.selectList(any())).thenReturn(Arrays.asList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-WS-001", 4, "张三"),
+                workOrder(repairDevice.getEquipmentId(), "WO-WS-002", 4, "李四"),
+                workOrder(gasDevice.getEquipmentId(), "WO-GAS-001", 2)));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(
+                1, 10, null, null, null, null);
+
+        assertEquals(2, result.getTotal());
+        assertEquals(Arrays.asList("water-pressure-1", "water-flow-1"), result.getRecords().stream()
+                .map(AbnormalDeviceVO::getEquipmentId)
+                .collect(Collectors.toList()));
+
+        AbnormalDeviceVO alarmRow = result.getRecords().get(0);
+        assertEquals(1, alarmRow.getAlarmStatus());
+        assertEquals(1, alarmRow.getCurrentStatus());
+        assertEquals(1, alarmRow.getOnlineStatus());
+        assertEquals(1, alarmRow.getAlertLevel());
+        assertEquals("供水压力超限", ReflectionTestUtils.getField(alarmRow, "abnormalReason"));
+        assertEquals("WO-WS-001", ReflectionTestUtils.getField(alarmRow, "relatedWorkOrderNo"));
+        assertEquals(4, ReflectionTestUtils.getField(alarmRow, "relatedWorkOrderStatus"));
+        assertEquals("张三", ReflectionTestUtils.getField(alarmRow, "relatedWorkOrderPerson"));
+
+        AbnormalDeviceVO repairRow = result.getRecords().get(1);
+        assertEquals(0, repairRow.getAlarmStatus());
+        assertEquals(3, repairRow.getCurrentStatus());
+        assertEquals(0, repairRow.getOnlineStatus());
+        assertNull(repairRow.getAlertLevel());
+        assertEquals("设备维修中", ReflectionTestUtils.getField(repairRow, "abnormalReason"));
+        assertEquals("WO-WS-002", ReflectionTestUtils.getField(repairRow, "relatedWorkOrderNo"));
+        assertEquals(4, ReflectionTestUtils.getField(repairRow, "relatedWorkOrderStatus"));
+        assertEquals("李四", ReflectionTestUtils.getField(repairRow, "relatedWorkOrderPerson"));
+
+        @SuppressWarnings("unchecked")
+        ArgumentCaptor<Wrapper<WorkOrder>> orderWrapperCaptor =
+                ArgumentCaptor.forClass(Wrapper.class);
+        verify(workOrderMapper).selectList(orderWrapperCaptor.capture());
+        String orderWrapperSql = orderWrapperCaptor.getValue().getSqlSegment();
+        assertTrue(orderWrapperSql.contains("order_type"), "异常设备关联工单必须限定故障维修: " + orderWrapperSql);
+        assertTrue(orderWrapperSql.contains("order_status"), "异常设备关联工单必须排除已结案工单: " + orderWrapperSql);
+        AbstractWrapper<?, ?, ?> orderWrapper = (AbstractWrapper<?, ?, ?>) orderWrapperCaptor.getValue();
+        assertTrue(orderWrapper.getParamNameValuePairs().containsValue(1), "关联工单类型必须为 1-故障维修");
+        assertTrue(orderWrapper.getParamNameValuePairs().containsValue(6), "关联工单必须排除 6-已结案");
+        assertTrue(orderWrapper.getParamNameValuePairs().containsValue(7), "关联工单必须排除 7-已驳回");
+    }
+
+    @Test
+    void abnormalPageMapsMultipleWorkOrderReceiversToDisplayNames() {
+        ISysUserService sysUserService = mock(ISysUserService.class);
+        ReflectionTestUtils.setField(service, "sysUserService", sysUserService);
+        when(sysUserService.selectUserById(1L)).thenReturn(sysUser(1L, "zhangsan", "张三丰"));
+        when(sysUserService.selectUserById(2L)).thenReturn(sysUser(2L, "lisi", null));
+
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1)));
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.singletonList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-WS-003", 4, "1, 2")));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(
+                1, 10, null, null, null, null);
+
+        assertEquals(1, result.getTotal());
+        assertEquals("张三丰、lisi", ReflectionTestUtils.getField(
+                result.getRecords().get(0), "relatedWorkOrderPerson"));
+        verify(sysUserService).selectUserById(1L);
+        verify(sysUserService).selectUserById(2L);
+    }
+
+    @Test
+    void abnormalExportReturnsAllWaterAbnormalDevicesWithoutPagination() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(repairDevice.getEquipmentId(), 3, 0, 0),
+                status(gasDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Arrays.asList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1),
+                alarm(gasDevice.getEquipmentCode(), "燃气浓度超限", 2)));
+        when(workOrderMapper.selectList(any())).thenReturn(Arrays.asList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-WS-001", 4),
+                workOrder(repairDevice.getEquipmentId(), "WO-WS-002", 6),
+                workOrder(gasDevice.getEquipmentId(), "WO-GAS-001", 2)));
+
+        List<AbnormalDeviceVO> result = service.getAbnormalDeviceExport(
+                null, null, null, null);
+
+        assertEquals(Arrays.asList("water-pressure-1", "water-flow-1"), result.stream()
+                .map(AbnormalDeviceVO::getEquipmentId)
+                .collect(Collectors.toList()));
+        assertEquals("供水压力超限", result.get(0).getAbnormalReason());
+        assertEquals("设备维修中", result.get(1).getAbnormalReason());
+        assertNull(result.get(1).getAlertLevel());
+    }
+
+    @Test
+    void abnormalPageIncludesActiveAlarmWhenRuntimeStatusRecordIsMissing() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.emptyList());
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1)));
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.emptyList());
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(1, 10, null, null, null, null);
+
+        assertEquals(1, result.getTotal());
+        AbnormalDeviceVO row = result.getRecords().get(0);
+        assertEquals(pressureDevice.getEquipmentId(), row.getEquipmentId());
+        assertEquals(1, row.getAlertLevel());
+        assertEquals("供水压力超限", ReflectionTestUtils.getField(row, "abnormalReason"));
+    }
+
+    @Test
+    void abnormalAlertLevelFilterUsesActiveAlarmLevel() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1)));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(
+                1, 10, null, null, null, 2);
+
+        assertEquals(0, result.getTotal());
+        assertTrue(result.getRecords().isEmpty());
+    }
+
+    @Test
+    void multipleActiveAlarmsChooseMostSevereLevelOne() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Arrays.asList(
+                alarm(pressureDevice.getEquipmentCode(), "一般告警", 3),
+                alarm(pressureDevice.getEquipmentCode(), "严重告警", 1),
+                alarm(pressureDevice.getEquipmentCode(), "较重告警", 2)));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(1, 10, null, null, null, null);
+
+        assertEquals(1, result.getRecords().get(0).getAlertLevel());
+        assertEquals("严重告警", result.getRecords().get(0).getAbnormalReason());
+    }
+
+    @Test
+    void abnormalPageExcludesClosedAndRejectedWorkOrders() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1)));
+        when(workOrderMapper.selectList(any())).thenReturn(Arrays.asList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-REJECTED", 7),
+                workOrder(pressureDevice.getEquipmentId(), "WO-CLOSED", 6)));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(1, 10, null, null, null, null);
+
+        assertNull(result.getRecords().get(0).getRelatedWorkOrderNo());
+        ArgumentCaptor<Wrapper<WorkOrder>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
+        verify(workOrderMapper).selectList(wrapperCaptor.capture());
+        AbstractWrapper<?, ?, ?> wrapper = (AbstractWrapper<?, ?, ?>) wrapperCaptor.getValue();
+        assertTrue(wrapper.getSqlSegment().contains("order_status"));
+    }
+
+    @Test
+    void dispatchableOnlyExcludesDevicesWithActiveFaultWorkOrders() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Arrays.asList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1),
+                status(repairDevice.getEquipmentId(), 3, 0, 1)));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.emptyList());
+        when(workOrderMapper.selectList(any())).thenReturn(Arrays.asList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-ACTIVE", 2),
+                workOrder(repairDevice.getEquipmentId(), "WO-CLOSED", 6)));
+
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(
+                1, 10, null, null, null, null, true);
+
+        assertEquals(Collections.singletonList(repairDevice.getEquipmentId()), result.getRecords().stream()
+                .map(AbnormalDeviceVO::getEquipmentId)
+                .collect(Collectors.toList()));
+    }
+
+    @Test
+    void deviceDetailIncludesAlarmAndRelatedWorkOrderSummary() {
+        doReturn(pressureDevice).when(service).getById(pressureDevice.getEquipmentId());
+        when(equipmentStatusMapper.selectOne(any())).thenReturn(status(pressureDevice.getEquipmentId(), 1, 1, 1));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(
+                alarm(pressureDevice.getEquipmentCode(), "供水压力超限", 1)));
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.singletonList(
+                workOrder(pressureDevice.getEquipmentId(), "WO-DETAIL", 2, "1")));
+
+        com.zksy.base.domain.vo.DeviceDetailVO detail = service.getDeviceDetail(pressureDevice.getEquipmentId());
+
+        assertEquals(1, detail.getAlertLevel());
+        assertEquals("供水压力超限", detail.getAbnormalReason());
+        assertEquals("WO-DETAIL", detail.getRelatedWorkOrderNo());
+        assertEquals(2, detail.getRelatedWorkOrderStatus());
+        assertEquals("1", detail.getRelatedWorkOrderPerson());
+    }
+
+    @Test
+    void deviceDetailKeepsMaintenanceStateSeparateFromAlarmLevel() {
+        doReturn(repairDevice).when(service).getById(repairDevice.getEquipmentId());
+        when(equipmentStatusMapper.selectOne(any())).thenReturn(
+                status(repairDevice.getEquipmentId(), 3, 0, 1));
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.emptyList());
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.emptyList());
+
+        com.zksy.base.domain.vo.DeviceDetailVO detail = service.getDeviceDetail(repairDevice.getEquipmentId());
+
+        assertEquals(3, detail.getCurrentStatus());
+        assertEquals(0, detail.getAlarmStatus());
+        assertNull(detail.getAlertLevel());
+        assertEquals("设备维修中", detail.getAbnormalReason());
+    }
+
+    @Test
+    void abnormalOrderCreatesUnifiedFaultWorkOrderWithSingleReceiver() {
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId(pressureDevice.getEquipmentId());
+        request.setMaintainContent("压力异常");
+        request.setReceiveUserId(88L);
+        WorkOrder created = workOrder(pressureDevice.getEquipmentId(), "WO-T6", 1, "88");
+        created.setOrderId(99L);
+        when(businessWorkOrderService.createWorkOrder(any(WorkOrder.class))).thenAnswer(invocation -> {
+            WorkOrder input = invocation.getArgument(0);
+            input.setOrderId(99L);
+            input.setOrderNo("WO-T6");
+            input.setOrderStatus(1);
+            return 99L;
+        });
+        WorkOrder result = service.createAbnormalWorkOrder(request);
+
+        assertEquals(99L, result.getOrderId());
+        assertEquals(1, result.getOrderType());
+        assertEquals(2, result.getOrderLevel());
+        assertEquals(1, result.getOrderStatus());
+        assertNull(result.getReceiveUser());
+        ArgumentCaptor<WorkOrder> workOrderCaptor = ArgumentCaptor.forClass(WorkOrder.class);
+        verify(businessWorkOrderService).createWorkOrder(workOrderCaptor.capture());
+        WorkOrder submitted = workOrderCaptor.getValue();
+        assertEquals(pressureDevice.getEquipmentId(), submitted.getDeviceId());
+        assertEquals(pressureDevice.getEquipmentCode(), submitted.getDeviceCode());
+        assertEquals(1, submitted.getOrderType());
+        assertEquals(2, submitted.getOrderLevel());
+        assertEquals("压力异常", submitted.getOrderDesc());
+        assertNull(submitted.getReceiveUser());
+        verify(equipmentMaintainMapper, never()).insert(any(EquipmentMaintain.class));
+    }
+
+    @Test
+    void abnormalOrderCanCreatePendingWorkOrderWithoutReceiverId() {
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId(pressureDevice.getEquipmentId());
+        when(businessWorkOrderService.createWorkOrder(any(WorkOrder.class))).thenAnswer(invocation -> {
+            WorkOrder submitted = invocation.getArgument(0);
+            submitted.setOrderId(101L);
+            submitted.setOrderStatus(1);
+            return 101L;
+        });
+
+        WorkOrder result = service.createAbnormalWorkOrder(request);
+
+        assertEquals(101L, result.getOrderId());
+        assertEquals(1, result.getOrderStatus());
+        assertNull(result.getReceiveUser());
+        verify(businessWorkOrderService).createWorkOrder(any(WorkOrder.class));
+    }
+
+    @Test
+    void deviceDetailIgnoresProcessedAlarmRecordWhenEquipmentIsNormal() {
+        doReturn(repairDevice).when(service).getById(repairDevice.getEquipmentId());
+        when(equipmentStatusMapper.selectOne(any())).thenReturn(
+                status(repairDevice.getEquipmentId(), 1, 0, 1));
+        AlarmData processedAlarm = new AlarmData();
+        processedAlarm.setDeviceCode(repairDevice.getEquipmentCode());
+        processedAlarm.setAlarmStatus(0);
+        processedAlarm.setAlarmLevel(1);
+        processedAlarm.setWarningType("历史压力超限");
+        when(alarmDataMapper.selectList(any())).thenReturn(Collections.singletonList(processedAlarm));
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.emptyList());
+
+        com.zksy.base.domain.vo.DeviceDetailVO detail = service.getDeviceDetail(repairDevice.getEquipmentId());
+
+        assertEquals(0, detail.getAlarmStatus());
+        assertNull(detail.getAlertLevel());
+        assertNull(detail.getAbnormalReason());
+    }
+
+    @Test
+    void noWaterDevicesReturnsEmptyAbnormalPageWithoutReadingStatuses() {
+        when(equipmentBaseService.findByTopLevelType("供水")).thenReturn(Collections.emptyList());
+        Page<AbnormalDeviceVO> result = service.getAbnormalDevicePage(
+                1, 10, null, null, null, null);
+
+        assertEquals(0, result.getTotal());
+        assertTrue(result.getRecords().isEmpty());
+        verify(equipmentStatusMapper, never()).selectList(any());
+    }
+
+    @Test
+    void deviceDetailDoesNotExposeNonWaterDevices() {
+        doReturn(gasDevice).when(service).getById(gasDevice.getEquipmentId());
+
+        assertNull(service.getDeviceDetail(gasDevice.getEquipmentId()));
+    }
+
+    @Test
+    void createMaintainOrderRejectsNonWaterDevices() {
+        MaintainOrderVO order = new MaintainOrderVO();
+        order.setEquipmentId(gasDevice.getEquipmentId());
+        doReturn(gasDevice).when(service).getById(gasDevice.getEquipmentId());
+
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.createMaintainOrder(order));
+
+        assertEquals("仅支持供水设备派发维修工单", error.getMessage());
+        verify(equipmentMaintainMapper, never()).insert(any(EquipmentMaintain.class));
+    }
+
+    @Test
+    void legacyMaintainOrderSignatureUsesUnifiedWorkOrderLifecycle() {
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId(pressureDevice.getEquipmentId());
+        request.setMaintainContent("压力异常");
+        request.setOrderLevel(1);
+        request.setMaintainRemark("请尽快处理");
+        request.setReceiveUserId(88L);
+        when(businessWorkOrderService.createWorkOrder(any(WorkOrder.class))).thenAnswer(invocation -> {
+            WorkOrder submitted = invocation.getArgument(0);
+            submitted.setOrderId(100L);
+            submitted.setOrderStatus(1);
+            return 100L;
+        });
+        when(businessWorkOrderService.dispatchOrder(100L, 88L, "请尽快处理", null, null))
+                .thenReturn(true);
+
+        assertTrue(service.createMaintainOrder(request));
+
+        verify(equipmentMaintainMapper, never()).insert(any(EquipmentMaintain.class));
+        ArgumentCaptor<WorkOrder> orderCaptor = ArgumentCaptor.forClass(WorkOrder.class);
+        verify(businessWorkOrderService).createWorkOrder(orderCaptor.capture());
+        assertEquals(1, orderCaptor.getValue().getOrderType());
+        assertEquals(1, orderCaptor.getValue().getOrderLevel());
+        verify(businessWorkOrderService).dispatchOrder(100L, 88L, "请尽快处理", null, null);
+    }
+
+    @Test
+    void createAbnormalWorkOrderRejectsWhenDeviceHasActiveWorkOrder() {
+        MaintainOrderVO request = new MaintainOrderVO();
+        request.setEquipmentId(pressureDevice.getEquipmentId());
+        request.setMaintainContent("压力异常");
+        doReturn(pressureDevice).when(service).getById(pressureDevice.getEquipmentId());
+
+        WorkOrder activeOrder = new WorkOrder();
+        activeOrder.setDeviceId(pressureDevice.getEquipmentId());
+        activeOrder.setOrderNo("WO-ACTIVE");
+        activeOrder.setOrderType(1);
+        activeOrder.setOrderStatus(2);
+        when(workOrderMapper.selectList(any())).thenReturn(Collections.singletonList(activeOrder));
+
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.createAbnormalWorkOrder(request));
+
+        assertEquals("该设备已有未结束故障维修工单,不能重复创建", error.getMessage());
+        verify(businessWorkOrderService, never()).createWorkOrder(any(WorkOrder.class));
+    }
+
+    @Test
+    void maintainRecordListDoesNotExposeNonWaterDevices() {
+        EquipmentMaintain gasRecord = new EquipmentMaintain();
+        gasRecord.setEquipmentId(gasDevice.getEquipmentId());
+        gasRecord.setMaintainId("gas-record");
+        when(equipmentMaintainMapper.selectList(any())).thenReturn(Collections.singletonList(gasRecord));
+
+        assertTrue(service.getMaintainRecordList(gasDevice.getEquipmentId()).isEmpty());
+    }
+
+    @Test
+    void maintainRecordPageReturnsOnlyWaterDevices() {
+        EquipmentMaintain waterRecord = maintain("water-record", pressureDevice.getEquipmentId());
+        EquipmentMaintain gasRecord = maintain("gas-record", gasDevice.getEquipmentId());
+        Page<EquipmentMaintain> mapperPage = new Page<>(1, 10, 2);
+        mapperPage.setRecords(Arrays.asList(gasRecord, waterRecord));
+        when(equipmentMaintainMapper.selectPage(any(), any())).thenReturn(mapperPage);
+        when(equipmentMaintainMapper.selectList(any())).thenReturn(Arrays.asList(gasRecord, waterRecord));
+        doReturn(Arrays.asList(pressureDevice, gasDevice)).when(service).listByIds(any());
+
+        Page<com.zksy.base.domain.vo.EquipmentMaintainDataVO> result =
+                service.getMaintainRecordPage(1, 10, null, null, null, null, null, null);
+
+        assertEquals(1, result.getTotal());
+        assertEquals(Collections.singletonList("water-record"), result.getRecords().stream()
+                .map(com.zksy.base.domain.vo.EquipmentMaintainDataVO::getMaintainId)
+                .collect(Collectors.toList()));
+    }
+
+    @Test
+    void myMaintainRecordPageReturnsOnlyWaterDevices() {
+        EquipmentMaintain waterRecord = maintain("water-record", pressureDevice.getEquipmentId());
+        EquipmentMaintain gasRecord = maintain("gas-record", gasDevice.getEquipmentId());
+        Page<EquipmentMaintain> mapperPage = new Page<>(1, 10, 2);
+        mapperPage.setRecords(Arrays.asList(gasRecord, waterRecord));
+        when(equipmentMaintainMapper.selectPage(any(), any())).thenReturn(mapperPage);
+        when(equipmentMaintainMapper.selectList(any())).thenReturn(Arrays.asList(gasRecord, waterRecord));
+        doReturn(Arrays.asList(pressureDevice, gasDevice)).when(service).listByIds(any());
+
+        Page<com.zksy.base.domain.vo.EquipmentMaintainDataVO> result =
+                service.getMyMaintainRecordPage(1, 10, "张三", null, null, null, null);
+
+        assertEquals(1, result.getTotal());
+        assertEquals(Collections.singletonList("water-record"), result.getRecords().stream()
+                .map(com.zksy.base.domain.vo.EquipmentMaintainDataVO::getMaintainId)
+                .collect(Collectors.toList()));
+    }
+
+    @Test
+    void updateMaintainRecordRejectsNonWaterRecords() {
+        com.zksy.base.domain.vo.EquipmentMaintainDataVO vo =
+                new com.zksy.base.domain.vo.EquipmentMaintainDataVO();
+        vo.setMaintainId("gas-record");
+        when(equipmentMaintainMapper.selectById("gas-record"))
+                .thenReturn(maintain("gas-record", gasDevice.getEquipmentId()));
+
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.updateMaintainRecord(vo));
+
+        assertEquals("仅支持供水设备维护记录", error.getMessage());
+        verify(equipmentMaintainMapper, never()).updateById(any(EquipmentMaintain.class));
+    }
+
+    @Test
+    void deleteMaintainRecordRejectsNonWaterRecords() {
+        when(equipmentMaintainMapper.selectById("gas-record"))
+                .thenReturn(maintain("gas-record", gasDevice.getEquipmentId()));
+
+        RuntimeException error = assertThrows(RuntimeException.class,
+                () -> service.deleteMaintainRecord("gas-record"));
+
+        assertEquals("仅支持供水设备维护记录", error.getMessage());
+        verify(equipmentMaintainMapper, never()).deleteById("gas-record");
+    }
+
+    @Test
+    void returnsEmptyRecordsWhenRequestedPageIsBeyondAbnormalDevices() {
+        when(equipmentStatusMapper.selectList(any())).thenReturn(Collections.singletonList(
+                status(pressureDevice.getEquipmentId(), 1, 1, 1)));
+        Page<AbnormalDeviceVO> result = assertDoesNotThrow(() -> service.getAbnormalDevicePage(
+                2, 10, null, null, null, null));
+
+        assertEquals(1, result.getTotal());
+        assertEquals(0, result.getRecords().size());
+    }
+
+    private static EquipmentBase device(String id, String code, String name, String typeId) {
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(id);
+        device.setEquipmentCode(code);
+        device.setEquipmentName(name);
+        device.setEquipmentTypeId(typeId);
+        device.setEquipmentLocation("测试位置");
+        return device;
+    }
+
+    private static EquipmentType type(String id, String name, String parentId) {
+        EquipmentType type = new EquipmentType();
+        type.setId(id);
+        type.setTypeId(id);
+        type.setTypeName(name);
+        type.setParentTypeId(parentId);
+        return type;
+    }
+
+    private static EquipmentStatus status(String equipmentId, int currentStatus,
+                                          int alarmStatus, int onlineStatus) {
+        EquipmentStatus status = new EquipmentStatus();
+        status.setEquipmentId(equipmentId);
+        status.setCurrentStatus(currentStatus);
+        status.setAlarmStatus(alarmStatus);
+        status.setOnlineStatus(onlineStatus);
+        status.setStatusUpdateTime(LocalDateTime.of(2026, 9, 2, 10, 0));
+        return status;
+    }
+
+    private static AlarmData alarm(String deviceCode, String warningType, int level) {
+        AlarmData alarm = new AlarmData();
+        alarm.setDeviceCode(deviceCode);
+        alarm.setWarningType(warningType);
+        alarm.setAlarmLevel(level);
+        alarm.setAlarmStatus(0);
+        alarm.setAlarmTime(LocalDateTime.of(2026, 9, 2, 9, 0));
+        return alarm;
+    }
+
+    private static WorkOrder workOrder(String deviceId, String orderNo, int orderStatus, String receiveUser) {
+        WorkOrder order = new WorkOrder();
+        order.setDeviceId(deviceId);
+        order.setOrderNo(orderNo);
+        order.setOrderType(1);
+        order.setOrderStatus(orderStatus);
+        order.setReceiveUser(receiveUser);
+        return order;
+    }
+
+    private static WorkOrder workOrder(String deviceId, String orderNo, int orderStatus) {
+        return workOrder(deviceId, orderNo, orderStatus, null);
+    }
+
+
+    private static SysUser sysUser(Long userId, String userName, String nickName) {
+        SysUser user = new SysUser();
+        user.setUserId(userId);
+        user.setUserName(userName);
+        user.setNickName(nickName);
+        return user;
+    }
+
+    private static EquipmentMaintain maintain(String maintainId, String equipmentId) {
+        EquipmentMaintain record = new EquipmentMaintain();
+        record.setMaintainId(maintainId);
+        record.setEquipmentId(equipmentId);
+        record.setMaintainType("故障维修");
+        record.setMaintainPerson("张三");
+        return record;
+    }
+
+}

+ 17 - 12
radar-service/src/main/java/com/zksy/radar/utils/MessageHandler.java

@@ -215,15 +215,13 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 		 * 处理雷达设备告警
 		 */
 		private void handleRadarAlarm(RadarData resultData) {
+			String deviceCode = resultData.getDeviceCode();
+			if (deviceCode == null) {
+				deviceCode = resultData.getSystemIdentifier();
+			}
+			boolean hasAlarm = false;
+			boolean evaluationCompleted = false;
 			try {
-				// 设备编码从设备数据获取
-				String deviceCode = resultData.getDeviceCode();
-				if (deviceCode == null) {
-					deviceCode = resultData.getSystemIdentifier();
-				}
-
-				boolean hasAlarm = false;
-
 				// 1. 处理瞬时流量告警
 				if (resultData.getMeter1InstantFlow() != null) {
 					if (handleAlarm(deviceCode, "WARN_INSTANT_FLOW", "瞬时流量", 
@@ -240,11 +238,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 					}
 				}
 
-				// 同步设备报警状态到 equipment_status 表
-				updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
+				evaluationCompleted = true;
 
 			} catch (Exception e) {
 				logger.error("雷达告警处理异常", e);
+			} finally {
+				if (evaluationCompleted) {
+					updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
+				}
 			}
 		}
 
@@ -390,10 +391,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 				headers.setContentType(MediaType.APPLICATION_JSON);
 				HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-				restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+					logger.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+					return;
+				}
 				logger.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
 			} catch (Exception e) {
 				logger.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
 			}
 		}
-	}
+	}

+ 17 - 12
water-level-service/src/main/java/com/zksy/water/utils/MessageHandler.java

@@ -215,15 +215,13 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 		 * 处理水位告警
 		 */
 		private void handleWaterLevelAlarm(WaterMonitorData resultData) {
+			String deviceCode = resultData.getDeviceCode();
+			if (deviceCode == null) {
+				deviceCode = resultData.getSystemIdentifier();
+			}
+			boolean hasAlarm = false;
+			boolean evaluationCompleted = false;
 			try {
-				// 设备编码从设备数据获取
-				String deviceCode = resultData.getDeviceCode();
-				if (deviceCode == null) {
-					deviceCode = resultData.getSystemIdentifier();
-				}
-
-				boolean hasAlarm = false;
-
 				// 处理水位告警
 				if (resultData.getWaterLevel() != null) {
 					if (handleAlarm(deviceCode, "WARN_WATER_LEVEL", "水位", 
@@ -232,11 +230,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 					}
 				}
 
-				// 同步设备报警状态到 equipment_status 表
-				updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
+				evaluationCompleted = true;
 
 			} catch (Exception e) {
 				logger.error("水位告警处理异常", e);
+			} finally {
+				if (evaluationCompleted) {
+					updateDeviceAlarmStatus(deviceCode, hasAlarm ? 1 : 0);
+				}
 			}
 		}
 
@@ -383,10 +384,14 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 				headers.setContentType(MediaType.APPLICATION_JSON);
 				HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
 
-				restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				Map<?, ?> response = restTemplate.postForObject(deviceStatusApiUrl, request, Map.class);
+				if (response == null || !Boolean.TRUE.equals(response.get("success"))) {
+					logger.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}, response={}", deviceCode, alarmStatus, response);
+					return;
+				}
 				logger.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
 			} catch (Exception e) {
 				logger.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
 			}
 		}
-	}
+	}

Некоторые файлы не были показаны из-за большого количества измененных файлов