Selaa lähdekoodia

Merge remote-tracking branch 'origin/master'

# Conflicts:
#	zk-api-service/src/test/java/com/zksy/api/service/CollectionAlarmLifecycleTest.java
zengy 3 viikkoa sitten
vanhempi
commit
eb409c5761
100 muutettua tiedostoa jossa 8727 lisäystä ja 626 poistoa
  1. 1 0
      .gitignore
  2. 54 0
      docs/alarm-log-gis-contract-closeout-20261111.md
  3. 2 2
      docs/alarm-operations-2026-09-24.md
  4. 27 0
      docs/video-session-anonymous-owner-20261110.sql
  5. 61 0
      docs/video-session-compatibility-20261110.md
  6. 8 0
      docs/video-session-media-node-20261112.sql
  7. 25 0
      docs/video-session-prepared-20261111.sql
  8. 6 2
      pipe-network-service/CONTEXT.md
  9. 4 7
      pipe-network-service/sql/apply_drainage_jcsj_fix.sql
  10. 18 0
      pipe-network-service/sql/migration_alarm_common_routes_20261111.sql
  11. 1 1
      pipe-network-service/sql/migration_alarm_operations.sql
  12. 44 0
      pipe-network-service/sql/migration_drainage_partition_drop_fields.sql
  13. 138 0
      pipe-network-service/sql/migration_drainage_sewage_type_dict.sql
  14. 175 0
      pipe-network-service/sql/migration_drainage_waterlogging_point_devices.sql
  15. 119 0
      pipe-network-service/sql/tests/alarm_common_routes.test.mjs
  16. 24 0
      pipe-network-service/sql/tests/video_session_media_node.test.mjs
  17. 8 0
      pipe-network-service/zksy-admin/pom.xml
  18. 150 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitVideoController.java
  19. 1 1
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/drainage/DrainagePartitionController.java
  20. 13 8
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/drainage/WaterloggingPointController.java
  21. 26 9
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/alarm/AlarmOperationsControllerTest.java
  22. 12 2
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/alarm/AlarmReviewControllerTest.java
  23. 3 1
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/BusinessCockpitWorkOrderReadAdapterTest.java
  24. 0 54
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitAnonymousAccessSecurityConfigTest.java
  25. 98 56
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitCurrentEventsControllerTest.java
  26. 16 7
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitEventReadControllerTest.java
  27. 53 14
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitHandlingEfficiencyControllerTest.java
  28. 60 16
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitHistoryAnalysisControllerTest.java
  29. 16 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitOverviewModulesServiceTest.java
  30. 576 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitVideoControllerTest.java
  31. 5 1
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderAssociationContractTest.java
  32. 5 1
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderListContractTest.java
  33. 345 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoPreparedSessionTest.java
  34. 595 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoPreparedSqlTransactionTest.java
  35. 383 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java
  36. 451 0
      pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java
  37. 12 0
      pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/config/SecurityConfig.java
  38. 1 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmReviewScopeService.java
  39. 53 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/PipeNetworkBase.java
  40. 3 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/dto/PipeNetworkPageInDTO.java
  41. 2 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/mapper/VideoSessionMapper.java
  42. 37 3
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/PipeNetworkBaseServiceImpl.java
  43. 318 40
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java
  44. 13 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoSession.java
  45. 30 4
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/BusinessCockpitEventAdapter.java
  46. 10 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventAlarm.java
  47. 106 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventLevelName.java
  48. 7 5
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventReadService.java
  49. 10 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/CockpitEventWarning.java
  50. 21 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewModulesService.java
  51. 16 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoException.java
  52. 69 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoMedia.java
  53. 316 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoService.java
  54. 302 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/VideoLiveLifecycle.java
  55. 162 13
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/BusinessCockpitWorkOrderReadAdapter.java
  56. 27 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderDelayApply.java
  57. 29 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderImages.java
  58. 77 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderLevelName.java
  59. 87 1
      pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/workorder/CockpitWorkOrderSummary.java
  60. 1 15
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/domain/DrainagePartition.java
  61. 5 19
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/domain/WaterloggingPoint.java
  62. 0 3
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/dto/WaterloggingPointPageInDTO.java
  63. 2 2
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/mapper/DrainageVideoMapper.java
  64. 3 3
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/DrainageVideoService.java
  65. 5 3
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/WaterloggingPointService.java
  66. 5 5
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/DrainageEquipmentBindingServiceImpl.java
  67. 12 98
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/DrainageRiskServiceImpl.java
  68. 64 28
      pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/WaterloggingPointServiceImpl.java
  69. 35 5
      pipe-network-service/zksy-system/src/main/resources/mapper/cockpit/CockpitOverviewModulesMapper.xml
  70. 1 1
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmLifecycleServiceTest.java
  71. 172 5
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmOperationsServiceTest.java
  72. 45 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmReviewScopeServiceTest.java
  73. 196 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/BusinessCockpitEventAdapterLevelNameTest.java
  74. 179 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventContentTest.java
  75. 66 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventLevelNameSerializationTest.java
  76. 114 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventLevelNameTest.java
  77. 185 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/overview/CockpitOverviewWarningStudyContractTest.java
  78. 87 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/video/VideoLiveSharingTest.java
  79. 343 0
      pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/workorder/CockpitWorkOrderDetailFieldsTest.java
  80. 3 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IInviteStreamService.java
  81. 11 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IPlayService.java
  82. 11 3
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/DeviceServiceImpl.java
  83. 32 1
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java
  84. 487 15
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java
  85. 25 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/PendingSipInvite.java
  86. 132 9
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SSRCFactory.java
  87. 342 1
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java
  88. 46 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRedisCompareAndSet.java
  89. 55 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRequestBinding.java
  90. 35 7
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/SIPProcessorObserver.java
  91. 101 8
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java
  92. 20 8
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/request/impl/ByeRequestProcessor.java
  93. 100 62
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/response/impl/InviteResponseProcessor.java
  94. 22 6
      video-service/src/main/java/com/ruoyi/wvp/media/event/hook/Hook.java
  95. 50 24
      video-service/src/main/java/com/ruoyi/wvp/media/event/hook/HookSubscribe.java
  96. 10 0
      video-service/src/main/java/com/ruoyi/wvp/service/IReceiveRtpServerService.java
  97. 380 26
      video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java
  98. 9 1
      video-service/src/main/java/com/zksy/video/ManualVideoController.java
  99. 100 17
      video-service/src/main/java/com/zksy/video/ManualVideoService.java
  100. 5 1
      video-service/src/main/java/com/zksy/video/VideoApplication.java

+ 1 - 0
.gitignore

@@ -56,3 +56,4 @@ logs/
 .scratch/
 .scratch/
 .planning/
 .planning/
 .dsh-edit-review*.json
 .dsh-edit-review*.json
+.workbuddy/

+ 54 - 0
docs/alarm-log-gis-contract-closeout-20261111.md

@@ -0,0 +1,54 @@
+# 日志与GIS合同收口(2026-11-11)
+
+## 已确认的合同
+
+用户在本会话确认:**结构化动作+描述快照**,以及 **common统一+精确旧路径授权兼容**;允许相关后端授权代码、SQL文件、文档和测试修改,不执行真实SQL、服务启停或浏览器/设备操作。随后另行批准在任务临时目录获取精确固定的PGlite测试依赖,禁安装脚本,不改应用依赖。
+
+### 日志
+
+- 触发日志动作通过类型0及显示名“报警触发”表达;操作人和操作时间独立呈现。
+- 正文仅保存触发时的 `alarmContent` 描述快照,零值、单位、有效上下限按现行快照规则保留;不再次拼触发前缀、单号或追加实际值。
+- 报警单号从所属报警上下文取得,不改变业务号码生成规则。
+- 不回写任何历史日志;未知旧动作类型仍呈“历史操作”,正文/ID/时间/附件/操作者原样保留。
+
+[管理前端历史组件](<E:/city-life-line/src/views/subSystem/alarm/AlarmHistory.vue#L7-L12>)已分列动作和正文,[摘要](<E:/city-life-line/src/views/subSystem/alarm/AlarmSummary.vue#L4-L9>)已有单号上下文;本次只读对照,没有改管理前端在制源码。[管理端写入](<E:/pipe-ner-server/pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/impl/AlarmDataServiceImpl.java#L268-L285>)与[采集端写入](<E:/pipe-ner-server/zk-api-service/src/main/java/com/zksy/api/service/CollectionAlarmWriter.java#L71-L78>)已经直接保存快照,生产写入不回退旧拼接格式。
+
+同步[领域上下文](<E:/pipe-ner-server/pipe-network-service/CONTEXT.md>)与[报警交付合同](<E:/pipe-ner-server/docs/alarm-operations-2026-09-24.md#L38-L50>);[日志保存测试](<E:/pipe-ner-server/pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmLifecycleServiceTest.java>)使用独立字面正文预期并保留insert→log→commit顺序/rollback等有效断言,[公开日志读取测试](<E:/pipe-ner-server/pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmOperationsServiceTest.java>)补动作显示、快照及旧历史保留。
+
+### GIS/研判
+
+- canonical组件为 `subSystem/alarm/common/alarmGIS` 与 `subSystem/alarm/common/analysis`,业务子系统仍由原query与服务端授权限定。
+- 后端仅兼容精确 `subSystem/drainage/alarm/alarmGIS`、`subSystem/drainage/alarm/analysis` 两旧组件字符串,保留原已支持的 `subSystem/waterSupply/alarm/alarmGIS`;不以prefix/contains/模糊匹配放宽。
+- 原菜单授权、启用状态、root和warningCode检查全部保留;运营菜单不授予审核权限,未知近似组件不获得范围。
+- [初装脚本](<E:/pipe-ner-server/pipe-network-service/sql/migration_alarm_operations.sql>)仅改2141/2143的component,不顺手改原脚本其它字段。
+- [增量脚本](<E:/pipe-ner-server/pipe-network-service/sql/migration_alarm_common_routes_20261111.sql>)只按上面三个准确旧component更新为common,保留path/query/perms/父级/排序/禁用状态/更新时间及角色关系,不恢复撤销的授权;不按menu_id或名字猜其它组件。
+
+管理前端正式HEAD `fe2f2928`已有common两组件,旧drainage/waterSupply对应组件文件已不存在。**后端授权别名兼容不等于前端能打开已删除组件**:已部署环境仍须按实际部署计划执行菜单增量并重新登录,不能把仅升级服务当完整过渡。本次脚本未在真实数据库执行,不保证现网菜单已一致。
+
+## 验证证据(已完成)
+
+- 先复跑剩余2个最小用例:1日志文案失败、1GIS AccessDenied,正式红信号仍在。
+- 管理端收口相关八类回归通过;日志14、scope11、OperationsService29(含原嵌套授权7及新增日志读取2),原18项更新仍保留。
+- 不带 `maven.test.failure.ignore` 的完整管网后端回归通过:zksy-system268项、zksy-admin814项,共1082项,0失败/错误/跳过。原先两项日志/GIS红信号均已闭合,不再被忽略失败参数掩盖。
+- [迁移行为测试](<E:/pipe-ner-server/pipe-network-service/sql/tests/alarm_common_routes.test.mjs>)在PGlite实际执行SQL,**4项全过**:初装canonical、精准增量及全字段/角色保留、重跑幂等不恢复撤权、约束失败完整回滚。
+- 依赖首次缺失(MODULE_NOT_FOUND)没有进入SQL行为,不算SQL逻辑RED。首次历史对照临时文件为空,亦排除该次结果;重建后Git blob与原提交均为 `51395c6492ebdc2e53531a77be43ffd8a79ca004`,真实历史脚本的RED只在2141/2143旧component与新合同不符。当前SQL随后保持实现不回退并通过4项验证。
+- 临时测试依赖 `@electric-sql/pglite@0.5.16`:npm元数据及安装后的包/许可证一致为Apache-2.0,完整性 `sha512-Nj8KcIsJL748W408U2N8q4+9IlONdpRIU8MJypIAAINMJ5nqKyqpX7Mgg/5XKkXiAib3AoZGR6hnJFlrlLBrcg==`。仅装在任务专用 `.scratch/log-gis-contract-20261111/sql-test-deps`,整次安装禁脚本,无应用package/lock修改。
+- 采集端同合同的两个旧预期也已确认。默认Maven缓存缺net-device、项目缓存测试插件来源不匹配的几次失败均未进入用例,不算逻辑红;任务临时settings保留既有依赖缓存并仅补已存在的public插件仓库,始终用-o,不下载Java依赖或修改全局配置。实际执行CollectionAlarmLifecycleTest 14项中2项精确旧正文失败后,仅将其更新为独立字面快照/无数值描述,保留所有事务与历史语义;绿色复验已完成:该类14/14通过,完整zk-api-service模块4类22项也全部通过(含两端枚举、Mapper及单号测试),没有采集端同合同遗漏。
+
+SQL复现(PGLITE_MODULE指向已获准准备的测试模块,不在应用运行时安装):
+
+```bash
+PGLITE_MODULE=/absolute/path/to/pglite/dist/index.js node --test pipe-network-service/sql/tests/alarm_common_routes.test.mjs
+```
+
+## 独立审查与提交范围
+
+独立只读审查相对80f7d42b核对指定既有文件及新增SQL:标准0项发现、合同0项确证问题。确认exact alias不绕过原守卫,增量不写角色或其它字段,快照预期保留顺序/回滚,SQL行为验证不是关键词匹配。审查代理不复跑测试,运行结果由本次工具证据支持。
+
+已按日志、GIS、文档三主题独立中文提交:`39dcbf0a` 收口管理/采集日志精确测试与公开历史读取覆盖;`ddcf856f` 收口两个准确授权alias、初装两组件、增量三组件及实际SQL行为回归。日志生产写入不回退;角色/菜单范围算法不改。文档同步已确认合同并补记验证结果,不包含原有阈值/采集记录/管理前端在制品、本机测试依赖或视频票。所有提交本地保留,未推送;本报告随文档主题提交。
+
+## 后续与边界
+
+离线内存SQL不等于KingbaseES真实迁移验收;真实菜单值、权限缓存、部署拓扑与重新登录仍须维护者安排。本次不操作真实数据库、服务或浏览器,不混入视频票/提交,不改阈值及管理前端现有在制品。领域词汇仅捕获已确认的快照/动作定义,未新建台账、审计页面或存储系统;易逆的路径统一不额外制造ADR。
+
+由于项目规则要求,已跳过应用build/debug、浏览器调试/截图、服务启停、真实SQL/迁移与设备操作,仅执行获授权的离线Java/Node/内存SQL验证。依赖获取是本会话另行批准的测试准备,不属于业务接口联调。

+ 2 - 2
docs/alarm-operations-2026-09-24.md

@@ -37,7 +37,7 @@ GIS 监测曲线选项/曲线操作与研判事件下拉只展示 `alarm_data.ac
 
 
 ## 数据库脚本及部署
 ## 数据库脚本及部署
 
 
-页面目录调整的已部署环境执行 `pipe-network-service/sql/migration_alarm_menu_components.sql`:仅更新审核菜单 2118/2142/2097/2024 和排水研判/GIS 菜单 2141/2143 的 component,不改变 path、query 或权限;同步更新前后端后重新登录。供水 GIS 菜单 2120 单独执行 `migration_water_supply_alarm_gis.sql`。初装脚本已经使用最新组件路径。
+现行研判与监测报警 GIS 统一使用 `subSystem/alarm/common/analysis` 与 `subSystem/alarm/common/alarmGIS`,业务子系统仍由原菜单 query 和服务端授权范围决定,不因共用组件获得跨系统权限。初装 `migration_alarm_operations.sql` 使用现行组件;已部署环境使用本次增量 `pipe-network-service/sql/migration_alarm_common_routes_20261111.sql`,只把准确历史 component 映射为 common,保留 path、query、perms、父级、排序和全部角色关联。该增量不执行历史日志或业务数据回写;同步部署后重新登录获取新菜单。旧文档引用的独立菜单组件脚本当前仓库已不存在,不作为本次执行入口。后端对准确旧 component 的过渡授权兼容不等于前端能加载已删除组件,真实菜单迁移仍是部署前提。
 
 
 本轮脚本:`pipe-network-service/sql/migration_alarm_operations.sql`(KingbaseES PostgreSQL 兼容模式)。首次部署顺序:`migration_alarm_case_work_order_id.sql` → `migration_alarm_review.sql` → `migration_alarm_operations.sql`,先落地 `work_order_id`/`create_time` 字段,再创建日志与菜单。各脚本均不再创建生命周期触发器或自定义函数。
 本轮脚本:`pipe-network-service/sql/migration_alarm_operations.sql`(KingbaseES PostgreSQL 兼容模式)。首次部署顺序:`migration_alarm_case_work_order_id.sql` → `migration_alarm_review.sql` → `migration_alarm_operations.sql`,先落地 `work_order_id`/`create_time` 字段,再创建日志与菜单。各脚本均不再创建生命周期触发器或自定义函数。
 
 
@@ -45,7 +45,7 @@ GIS 监测曲线选项/曲线操作与研判事件下拉只展示 `alarm_data.ac
 
 
 - `alarm_data.alarm_no varchar(64)`,唯一索引;管理端 `AlarmDataServiceImpl.saveAlarmData`(含新增/演练)和采集端 `CollectionAlarmWriter` 在 INSERT 前由程序生成 `BJyyyyMMddHHmmss + 4位随机数`,日期时间取北京时间,随机数为 0000~9999,总长 20 位。覆盖请求带入的号码,复用、恢复和普通更新不改号。两端通过相同的数据库事务锁串行执行随机取号、查重和入库,碰撞重试最多 100 次,耗尽明确报错回滚,不生成重复号或改变格式。不回填历史记录。
 - `alarm_data.alarm_no varchar(64)`,唯一索引;管理端 `AlarmDataServiceImpl.saveAlarmData`(含新增/演练)和采集端 `CollectionAlarmWriter` 在 INSERT 前由程序生成 `BJyyyyMMddHHmmss + 4位随机数`,日期时间取北京时间,随机数为 0000~9999,总长 20 位。覆盖请求带入的号码,复用、恢复和普通更新不改号。两端通过相同的数据库事务锁串行执行随机取号、查重和入库,碰撞重试最多 100 次,耗尽明确报错回滚,不生成重复号或改变格式。不回填历史记录。
 - 最新脚本删除旧 `trg_alarm_number` 触发器、`assign_alarm_number()` 函数、字段默认值及 `alarm_no_seq` 序列,不再由数据库赋号;既有号码保持原值。唯一索引继续作为最终约束。
 - 最新脚本删除旧 `trg_alarm_number` 触发器、`assign_alarm_number()` 函数、字段默认值及 `alarm_no_seq` 序列,不再由数据库赋号;既有号码保持原值。唯一索引继续作为最终约束。
-- 每次新增 `alarm_data` 写入一条类型 0 的 `alarm_log`,内容为“系统触发报警;报警单号:…;报警描述:…”。描述优先用非空 `remark`,否则依次用报警类型、报警编码、“监测报警”;保留有效触发值快照,数值为空时不生成实际值/阈值占位,数值 0 正常保留,未配置的上下限不生成空文案。
+- 2026-11-11 收口合同:每次新增报警写入一条类型 0(展示名“报警触发”)的日志,操作人/时间由日志独立字段表达;正文只保存当时已固化的 `alarm_content` 描述快照。报警单号从所属报警上下文取得,不在正文重复拼接“系统触发报警;报警单号…”或再次追加实际值。快照由当前指标名称、触发值和上下限形成,不再引用已删除的 remark;数值 0 与有效单位正常保留,无数值的状态报警不虚构数值内容。此约定同步管理端和采集端,不改写/回填任何历史日志;历史旧类型与旧文本仍原样展示。
 - 采集 API 的 `CollectionAlarmWriter.markRecovered` 在独立事务中锁定同设备同指标的全部未处理记录,逐条更新状态并主动插入“监测恢复,报警自动解除 / 系统自动”。重复恢复不重复写日志;历史重复报警逐条记日志。不再设置数据库事务来源变量,不调用自定义数据库函数。管理端 `updateById` 统一覆盖通用修改、报警处理、燃气/压力解除入口,人工处理记录“报警已处理”,不误标为自动恢复。
 - 采集 API 的 `CollectionAlarmWriter.markRecovered` 在独立事务中锁定同设备同指标的全部未处理记录,逐条更新状态并主动插入“监测恢复,报警自动解除 / 系统自动”。重复恢复不重复写日志;历史重复报警逐条记日志。不再设置数据库事务来源变量,不调用自定义数据库函数。管理端 `updateById` 统一覆盖通用修改、报警处理、燃气/压力解除入口,人工处理记录“报警已处理”,不误标为自动恢复。
 - 报警插入/恢复与日志在同一事务中,失败一起回滚。确认报警生成工单时,`work_order_log.oper_desc` 使用 `alarm_no` 而非 UUID。无号码的历史报警写明“历史记录(未生成单号)”,不迁移旧工单日志。
 - 报警插入/恢复与日志在同一事务中,失败一起回滚。确认报警生成工单时,`work_order_log.oper_desc` 使用 `alarm_no` 而非 UUID。无号码的历史报警写明“历史记录(未生成单号)”,不迁移旧工单日志。
 - 不引入 `source_key`,不回填历史业务数据,不改变审核结果或设备状态。
 - 不引入 `source_key`,不回填历史业务数据,不改变审核结果或设备状态。

+ 27 - 0
docs/video-session-anonymous-owner-20261110.sql

@@ -0,0 +1,27 @@
+-- cockpit-video-monitoring/01 — 基于维护者 2026-11-10 提供的实际 DDL。
+-- 原表 user_id int8 NOT NULL;保留原主键、ix_video_session_active、ix_video_session_expire。
+-- 仅生成,未对真实数据库执行。需先备份并核对目标环境;先迁移、后部署新代码。
+-- 一次性迁移:重复执行会失败并回滚,不用 IF NOT EXISTS 掩盖异构字段。
+BEGIN;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN anonymous_token_hash varchar(43) NULL;
+ALTER TABLE app_user.video_play_session
+    ALTER COLUMN user_id DROP NOT NULL;
+ALTER TABLE app_user.video_play_session
+    ADD CONSTRAINT video_session_owner_check CHECK (
+        (user_id IS NOT NULL AND anonymous_token_hash IS NULL)
+        OR (user_id IS NULL AND anonymous_token_hash IS NOT NULL
+            AND anonymous_token_hash ~ '^[A-Za-z0-9_-]{43}$')
+    );
+COMMENT ON COLUMN app_user.video_play_session.anonymous_token_hash
+    IS '匿名观看会话资源归属凭据的SHA-256摘要(Base64URL);不是实名,不存原始凭据';
+COMMIT;
+
+-- 回退须先停止匿名入口,并确认没有任何匿名会话行(含已停止行)。
+-- 不自动删除、伪造 user_id 或迁移历史数据;由维护者决定归档策略。
+-- 确认无匿名行后才可单独执行以下事务(不要与上面的升级事务一起执行):
+-- BEGIN;
+-- ALTER TABLE app_user.video_play_session ALTER COLUMN user_id SET NOT NULL;
+-- ALTER TABLE app_user.video_play_session DROP CONSTRAINT video_session_owner_check;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN anonymous_token_hash;
+-- COMMIT;

+ 61 - 0
docs/video-session-compatibility-20261110.md

@@ -0,0 +1,61 @@
+# 视频会话兼容准备(cockpit-video-monitoring/01)
+
+## 范围
+
+本票只扩展既有视频会话身份及资源归属接缝。管理端 Controller、路由、权限与前端页面不变,不发布驾驶舱视频 HTTP 接口,不增加云台租约或另一套会话/共享流业务。
+
+## 实际结构依据
+
+维护者在 2026-11-10 本次实施会话提供 `app_user.video_play_session` 的实际 DDL:
+
+- `session_id varchar(36)` 主键;`video_id varchar(64)`、`user_id int8`、`mode varchar(16)`、`status varchar(16)` 非空。
+- `stream_id varchar(200)`、`proxy_key varchar(300)`、`gb_device_id varchar(20)`、`gb_channel_id varchar(20)` 可空。
+- `create_time`、`last_seen` 为非空 `sys.timestamp`,默认 CURRENT_TIMESTAMP;`end_time` 可空。
+- `ix_video_session_active(video_id, mode, status)` 和 `ix_video_session_expire(status, last_seen)`;所贴定义无用户外键。
+
+不能用 Java 的 `Long` 类型推断可空。本票的[一次性迁移](<video-session-anonymous-owner-20261110.sql>)保留旧行/主键/索引,只放开 `user_id` 非空并新增匿名凭据摘要及互斥身份检查。**脚本未在真实数据库执行。必须先迁移、再部署依赖新列的代码。** 回退条件与不自动删数据的策略在脚本中说明。
+
+## 公开接缝
+
+- `start(id, range)`、`heartbeat(id)`、`stop(id)`、`control(id, input)` 继续依赖真实业务用户,旧 Controller 不改;旧用户不能通过这些方法管理匿名会话。
+- `startAnonymous(id, range)` 为服务端适配层创建独立会话,返回既有媒体字段、`sessionId`、`mode` 和只返回一次的 `sessionToken`。不是公开匿名路由,也不接收客户端伪造的用户 ID。
+- 匿名 `heartbeat(id, token)`、`stop(id, token)`、`control(id, token, input)` 校验独立资源归属;凭据不能跨会话使用。原始凭据由 SecureRandom 生成 256 位,不进入数据库/日志;仅存 SHA-256 Base64URL 摘要并常量时间比较。
+- 沿用同一张会话表、同一设备行锁、全部 ACTIVE LIVE 的共享计数及 PLAYBACK 占用。不按匿名/用户来源分割计数,不对其它观看者做通道 stop。
+- `requireAnonymousSession(id, token, videoId, mode)` 提供设备/模式/归属/120秒观看有效性的统一校验,不代替能力校验或云台互斥。匿名已停止/超时心跳和控制明确失败,正确归属的 stop 仍可幂等清理;旧接口的已停止心跳保留成功无操作语义。
+- 心跳与释放共用既有设备行锁,并在锁后重新读取;锁查询清除 MyBatis 会话级旧快照,过期回收在锁后重新核对 last_seen。Spring 管理入口在媒体调用前登记事务完成回调,最终回滚/提交异常后用 REQUIRES_NEW 重取锁、已提交会话及当前共享计数,避免原事务中止后用旧计数误停新观看者;提交结果不明但会话实际存在时保留给既有回收器。无 Spring 事务的构造调用仅供离线接缝测试,不作为生产并发保证。
+- 国标实时启动响应丢失可按已知设备/通道尝试补偿;没有取得回放 stream 或手动 proxyKey 时明确未确认并保留脱敏告警,不猜清理键、不声称自动回收成功。完整迟到/未知启动取消属于03的强化生命周期(见下文)。
+- 凭据是持有者能力,不是实名;不证明媒体地址受保护,不替代后续内网访问边界、能力/设备映射或物理云台停止验收。
+
+## 离线验证记录
+
+- 基线离线 reactor `test-compile` 成功;核心新增接缝经历缺方法/行为失败 RED → 最小实现 GREEN,包含心跳/停止交错、过期扫描旧快照及事务中止后的媒体补偿反例。
+- 视频专项目前 **67 项通过,0 失败、0 错误、0 跳过**:[旧 HTTP/安全权限合同](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java>) 36 项,[匿名/旧用户与共享资源接缝](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java>) 31 项;新增外层回滚、提交失败、成功提交、回滚后新观看者及实时启动响应丢失。事务测试由真实 Spring TransactionTemplate/同步回调驱动,数据库提交/回滚为边界替身。
+- 旧 HTTP 测试使用真实 SecurityConfig、JWT 过滤、TokenService、方法权限、Controller 和 VideoDeviceService,无真实应用服务启动;Redis/DB/媒体为外部替身。共享计数用数据库返回字面夹具(3→2→1),没有重写业务计数算法,但也不证明真实 SQL/锁执行。
+- 完整管网 reactor 回归已执行;默认失败即停在 zksy-system。为收齐其余结果,又用 `-Dmaven.test.failure.ignore=true` 继续收集,**该次退出0不代表全绿**:zksy-system 256 项中 2 失败、1 错误;zksy-admin 753 项中 17 失败。失败涉及报警生命周期/过滤权限与驾驶舱事件/历史统计,非视频用例;这些测试及报警实现未被本票修改,未另执行原始基点以作严格归因。保留原结果,不扩本票修复范围。
+- 数据库替身不等于 Kingbase 的真实 SQL、行锁、事务或迁移验证;媒体替身不等于真实播放或设备停止。脚本未执行,后续现场验收仍需迁移/旧新会话并存实证。
+- 双轴代码审查以用户确认的 `4c4bc50a8e6b73eb83ecfe61cffaba3c5a988a61` 为基点;首轮审查独立提交 `32b2cf4a`,修复后再核对01与02/03/05的实际切片边界。
+
+## 审查修复与切片边界
+
+### Standards
+
+首轮硬违规0、判断性重复代码建议2。已收拢匿名锁后归属校验;最终复核硬违规0、保留1项低优先级夹具去重建议,无规范阻断。两份测试的数据库行快照替身暂保留在各自HTTP/服务接缝内,避免额外测试基础设施;该建议不是验收前置。
+
+### Spec
+
+首轮指出媒体响应假成功与事务补偿缺口。空/缺必要字段/非法媒体地址或stream已用公开接缝反例修复;最终事务回滚/提交失败已补新事务内锁后复查和补偿,不把insert=1当提交成功。复查七票切片后,复杂取消、迟到和未知启动的强化补偿明确已分配在[03票:19–23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/03-三入口统一与观看资源生命周期.md#L19-L23>),本票不提前改造整套媒体信令层,也不以01完成替代03验收。最终规格复核确认该切片边界,并指出MANUAL代理响应的native标记绕过检查:已改为按真实源协议决定必需字段、拒绝空白proxyKey,并补旧用户/匿名用户的native/代理四组合成功例及三种畸形响应反例;67项专项复验全通过。
+
+### 交接给02/03/05/07的已知边界
+
+- [02票:21–23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/02-最新指标入口打开匿名实时视频.md#L21-L23>)仍须验证首链基本失败退出;[05票:23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/05-已有历史录像查询与可控回放.md#L23>)明确沿03处理迟到与登记失败。本票只交付兼容接缝,不发布匿名HTTP或播放器。
+- 回放stream由设备/通道/起止时间确定,不是唯一请求代次;手动proxyKey可能被ZLM响应覆盖。未知/迟到结果不能通过猜ID、同通道盲停来处理。03需核实/补齐精确取消及迟到防护,再由05消费。
+- 底层已有“尚未收流”超时关闭,但媒体到达会取消该定时器;成功响应丢失不能据此宣称有界回收。现有video-service stop的ready阶段、BYE失败及arrival订阅仍需03/07按实际资源路径验证。本轮未修改底层信令实现、未操作真实设备,不把HTTP200当资源已释放。
+- 真实迁移、SQL行锁、媒体播放、内部网络边界与物理停止仍须后续按既定票序验收;本票代码/离线替身不是可发布或现场验收结论。
+- 按用户本次明确授权,仅执行离线 Java 编译/测试;因项目规则,跳过应用 build/debug、浏览器调试、服务启停、真实迁移和设备操作。
+
+复现命令(仓库根目录,均不启动服务;源码工具保留 mtime 时需先刷新本票改动文件的 mtime,避免旧 compiler 增量缓存漏编):
+
+```bash
+JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 mvn -o -pl pipe-network-service/zksy-admin -am -Dtest=VideoSessionCompatibilityTest,VideoDeviceCompatibilityTest -Dsurefire.failIfNoSpecifiedTests=false test
+JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 mvn -o -pl pipe-network-service/zksy-admin -am test
+```

+ 8 - 0
docs/video-session-media-node-20261112.sql

@@ -0,0 +1,8 @@
+-- cockpit-video-monitoring/03: precise media-node binding for prepared and adopted streams.
+-- Generated only; NOT executed against a real database. Apply after 01 and prepared-session 03 migration.
+-- Never backfill a guessed default node for old sessions. Unknown legacy handles remain unconfirmed.
+BEGIN;
+ALTER TABLE app_user.video_play_session ADD COLUMN media_server_id varchar(64) NULL;
+COMMENT ON COLUMN app_user.video_play_session.media_server_id
+    IS '媒体创建响应确认的实际节点;释放时禁止猜默认节点,旧未知节点不回填';
+COMMIT;

+ 25 - 0
docs/video-session-prepared-20261111.sql

@@ -0,0 +1,25 @@
+-- cockpit-video-monitoring/03 — 观看代次与启动截止,基于 01 之后的实际表结构。
+-- 仅生成,未对真实数据库执行。必须在 01(anonymous_token_hash)之后、部署 03 代码之前执行。
+-- 一次性迁移:重复执行会失败并回滚,不用 IF NOT EXISTS 掩盖异构字段。
+BEGIN;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN media_generation varchar(64) NULL;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN start_deadline timestamp NULL;
+COMMENT ON COLUMN app_user.video_play_session.media_generation
+    IS '观看代次(UUID):媒体资源的身份,主服务与 video-service 用它精确启动/取消,不用设备号猜';
+COMMENT ON COLUMN app_user.video_play_session.start_deadline
+    IS '本代次媒体启动截止时间;同一代次不可延长,过期后不得迟到复活';
+-- 同一代次的共享观看者需要按代次分组查询(启动计数/最后一位回收)。
+CREATE INDEX ix_video_session_generation
+    ON app_user.video_play_session(video_id, media_generation)
+    WHERE media_generation IS NOT NULL;
+COMMIT;
+
+-- 回退须先停止视频入口,并确认没有任何 STARTING/ACTIVE/CLEANUP_PENDING 会话行。
+-- 不自动删除、回填或伪造代次;历史行的 media_generation 保持 NULL 由主服务按“句柄一致才采纳”处理。
+-- BEGIN;
+-- DROP INDEX app_user.ix_video_session_generation;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN start_deadline;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN media_generation;
+-- COMMIT;

+ 6 - 2
pipe-network-service/CONTEXT.md

@@ -51,7 +51,7 @@ _Avoid_:把供水子系统等同于单一的报警页面,或把监测设备
 
 
 ### 4. 监测报警
 ### 4. 监测报警
 
 
-4.1 **报警管理**:供水报警管理是供水专属的只读报警流水、四级趋势和态势台账;排水保留公共报警清单。报警展示状态由后端结合报警记录及关联工单推导,设备报警状态来自设备状态表,两者与工单处置状态分别展示;按菜单 `rootTypeId` 校验授权并过滤设备类型树。审核、派发和处置仍在相应页面。排水另有 `remind` 提醒、`drainage/analysis` 研判、`drainage/alarmGIS` GIS(无周边环境页签)。供水专属页面恢复态势、分类占比和导出能力;供水监测报警一张图继续保留。不同报警类型可形成不同工单;同一设备同一报警类型同时只能存在一个未结束的同类报警工单(2026-09-24)。
+4.1 **报警管理**:供水报警管理是供水专属的只读报警流水、四级趋势和态势台账;排水保留公共报警清单。报警展示状态由后端结合报警记录及关联工单推导,设备报警状态来自设备状态表,两者与工单处置状态分别展示;按菜单 `rootTypeId` 校验授权并过滤设备类型树。审核、派发和处置仍在相应页面。提醒、研判与监测报警 GIS 共用业务能力,展示范围仍由用户授权的子系统限定(GIS 无周边环境页签)。供水专属页面恢复态势、分类占比和导出能力;供水监测报警一张图继续保留。不同报警类型可形成不同工单;同一设备同一报警类型同时只能存在一个未结束的同类报警工单(2026-09-24)。
 
 
 4.2 **报警审核**:四个子系统统一使用 `AlarmController` 的审核接口和 `subSystem/alarm/common/audit` 页面,列表仅展示 `alarm_status=0` 的事件。`audit_status` 独立记录未审核、确认报警、误报警;确认报警时创建待派单工单,误报警只记录结论,两种审核都不直接修改设备状态或报警处理状态。完整派单、接单、处理、验收由统一工单页承载。旧供水审核、直接派单和停用的解除接口已删除。报警生成、审核及处理记录在 `alarm_log`,确认记录直接包含“已转工单(实际工单号)”及选填意见;关联工单、工单操作不再单独写入报警日志。人工操作使用 `sys_user.nick_name`,历史按时间和日志 ID 倒序展示,不回填或删除历史数据。运行采集系统在收到有效恢复数据时,可以自动处理同设备、同报警编码的未处理告警;数值回到预警区即可处理,处理记录注明“系统自动”,不自动完成关联工单(见仓库docs/collection-alarm-recovery-2026-09-23.md)。
 4.2 **报警审核**:四个子系统统一使用 `AlarmController` 的审核接口和 `subSystem/alarm/common/audit` 页面,列表仅展示 `alarm_status=0` 的事件。`audit_status` 独立记录未审核、确认报警、误报警;确认报警时创建待派单工单,误报警只记录结论,两种审核都不直接修改设备状态或报警处理状态。完整派单、接单、处理、验收由统一工单页承载。旧供水审核、直接派单和停用的解除接口已删除。报警生成、审核及处理记录在 `alarm_log`,确认记录直接包含“已转工单(实际工单号)”及选填意见;关联工单、工单操作不再单独写入报警日志。人工操作使用 `sys_user.nick_name`,历史按时间和日志 ID 倒序展示,不回填或删除历史数据。运行采集系统在收到有效恢复数据时,可以自动处理同设备、同报警编码的未处理告警;数值回到预警区即可处理,处理记录注明“系统自动”,不自动完成关联工单(见仓库docs/collection-alarm-recovery-2026-09-23.md)。
 
 
@@ -171,9 +171,13 @@ _Avoid_:设备报警状态、设备异常
 _Avoid_:用有无实际值判断报警是否存在、把数值 0 当作空值
 _Avoid_:用有无实际值判断报警是否存在、把数值 0 当作空值
 
 
 **报警单号**:
 **报警单号**:
-`alarm_data.alarm_no` 是报警事件的唯一业务号码,新建时由管理端或采集端程序生成,格式为 `BJyyyyMMddHHmmss` 加 4 位随机数(0000~9999),北京时间,总长 20 位。两端使用同一数据库事务锁保护取号、查重与入库,碰撞重试最多 100 次,唯一索引兜底;覆盖请求传入的号码,普通更新不改号,不回填历史。不使用单号生成触发器、默认值或序列。`alarm_data.alarm_content` 在新增时按 `warning_code` 关联的指标名称和触发值/上下限固化:触及下限追加“达到或低于下限”,触及上限追加“达到或超过上限”,否则只存指标名称;`remark` 列及两套 `AlarmData` 实体的 `remark`、`warningName` 属性均已删除,写入端不再通过报警对象传递指标名称。清单首列和报警转工单的创建日志使用该号,UUID 仅用于内部关联。新增、自动恢复和人工处理由业务代码在同一事务中主动写 `alarm_log`,不依赖任何自定义数据库函数或触发器;工单操作仅写 `work_order_log`,脚本删除旧日志镜像触发器及函数。`zksy-system` 与 `zk-api-service` 各保留一份 `AlarmLogOperTypeEnum`,不新增共享模块,两端值一致:0 报警触发、1 确认报警、2 误报警、3 报警处理,删除关联工单及工单操作类型。新增记录“系统触发报警”及已固化的报警描述,恢复时记录“监测恢复,报警自动解除”;重复恢复不重复记录,日志写入失败则报警变更一同回滚,自动恢复不关闭工单。
+`alarm_data.alarm_no` 是报警事件的唯一业务号码,新建时由管理端或采集端程序生成,格式为 `BJyyyyMMddHHmmss` 加 4 位随机数(0000~9999),北京时间,总长 20 位。两端使用同一数据库事务锁保护取号、查重与入库,碰撞重试最多 100 次,唯一索引兜底;覆盖请求传入的号码,普通更新不改号,不回填历史。不使用单号生成触发器、默认值或序列。`alarm_data.alarm_content` 在新增时按 `warning_code` 关联的指标名称和触发值/上下限固化:触及下限追加“达到或低于下限”,触及上限追加“达到或超过上限”,否则只存指标名称;`remark` 列及两套 `AlarmData` 实体的 `remark`、`warningName` 属性均已删除,写入端不再通过报警对象传递指标名称。清单首列和报警转工单的创建日志使用该号,UUID 仅用于内部关联。新增、自动恢复和人工处理由业务代码在同一事务中主动写 `alarm_log`,不依赖任何自定义数据库函数或触发器;工单操作仅写 `work_order_log`,脚本删除旧日志镜像触发器及函数。`zksy-system` 与 `zk-api-service` 各保留一份 `AlarmLogOperTypeEnum`,不新增共享模块,两端值一致:0 报警触发、1 确认报警、2 误报警、3 报警处理,删除关联工单及工单操作类型。报警触发记录通过独立操作类型表达触发动作,正文保存触发时固化的报警描述快照;单号从所属报警上下文取得,不重复拼入正文,也不重复追加实际值,恢复时记录“监测恢复,报警自动解除”;重复恢复不重复记录,日志写入失败则报警变更一同回滚,自动恢复不关闭工单。
 _Avoid_:报警主键、报警类型编码、工单号
 _Avoid_:报警主键、报警类型编码、工单号
 
 
+**报警描述快照**:
+报警发生时固化的指标名称、触发原因及当时有效的数值和上下限说明;它用于解释这次报警,不随后来的实时指标变化重写。数值零是有效事实,状态类报警可以没有数值内容。
+_Avoid_:实时指标、当前报警状态、操作类型
+
 **报警展示状态**:
 **报警展示状态**:
 由报警持久化状态、审核结果和关联工单推导出的面向用户的状态,用于区分待审核、已转工单、已解除和误报警;它不替代设备报警状态,误报警不代表监测数据已恢复。
 由报警持久化状态、审核结果和关联工单推导出的面向用户的状态,用于区分待审核、已转工单、已解除和误报警;它不替代设备报警状态,误报警不代表监测数据已恢复。
 _Avoid_:报警记录持久化状态、设备报警状态
 _Avoid_:报警记录持久化状态、设备报警状态

+ 4 - 7
pipe-network-service/sql/apply_drainage_jcsj_fix.sql

@@ -27,8 +27,10 @@ SET search_path TO app_user, public;
 
 
 -- ============================================================================
 -- ============================================================================
 -- 1. 易积水点表:补齐实体所需的全部列
 -- 1. 易积水点表:补齐实体所需的全部列
---    (老库可能只缺 duty_* 两列,也可能缺 water_depth / risk_level 等,
+--    (老库可能只缺 duty_* 两列,也可能缺 risk_level 等,
 --      这里按实体字段全集逐列判断,缺哪列补哪列)
 --      这里按实体字段全集逐列判断,缺哪列补哪列)
+--    注意:积水程度/深度/水量/面积四个属性已下线,camera_ids 已更名为 equipment_ids,
+--    这里不再补这些旧列,否则重跑本脚本会把已删除的列复活。
 -- ============================================================================
 -- ============================================================================
 DO $$
 DO $$
 DECLARE
 DECLARE
@@ -48,17 +50,13 @@ BEGIN
         ('location',            'varchar(500)'),
         ('location',            'varchar(500)'),
         ('longitude',           'numeric(12,8)'),
         ('longitude',           'numeric(12,8)'),
         ('latitude',            'numeric(12,8)'),
         ('latitude',            'numeric(12,8)'),
-        ('waterlogging_level',  'int2'),
-        ('water_depth',         'numeric(10,2)'),
-        ('water_volume',        'numeric(14,2)'),
-        ('water_area',          'numeric(14,2)'),
         ('risk_level',          'varchar(8)'),
         ('risk_level',          'varchar(8)'),
         ('duty_unit',           'varchar(200)'),
         ('duty_unit',           'varchar(200)'),
         ('duty_person',         'varchar(64)'),
         ('duty_person',         'varchar(64)'),
         ('duty_phone',          'varchar(32)'),
         ('duty_phone',          'varchar(32)'),
         ('duty_dept_id',        'bigint'),
         ('duty_dept_id',        'bigint'),
         ('duty_user_id',        'bigint'),
         ('duty_user_id',        'bigint'),
-        ('camera_ids',          'varchar(500)'),
+        ('equipment_ids',       'varchar(500)'),
         ('remark',              'varchar(500)'),
         ('remark',              'varchar(500)'),
         ('create_by',           'varchar(64)'),
         ('create_by',           'varchar(64)'),
         ('create_time',         'timestamp'),
         ('create_time',         'timestamp'),
@@ -98,7 +96,6 @@ BEGIN
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_point_code ON app_user.drainage_waterlogging_point (point_code)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_point_code ON app_user.drainage_waterlogging_point (point_code)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_point_name ON app_user.drainage_waterlogging_point (point_name)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_point_name ON app_user.drainage_waterlogging_point (point_name)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_district   ON app_user.drainage_waterlogging_point (district)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_district   ON app_user.drainage_waterlogging_point (district)';
-  EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_level      ON app_user.drainage_waterlogging_point (waterlogging_level)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_risk_level ON app_user.drainage_waterlogging_point (risk_level)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_risk_level ON app_user.drainage_waterlogging_point (risk_level)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_duty_dept  ON app_user.drainage_waterlogging_point (duty_dept_id)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_duty_dept  ON app_user.drainage_waterlogging_point (duty_dept_id)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_duty_user  ON app_user.drainage_waterlogging_point (duty_user_id)';
   EXECUTE 'CREATE INDEX IF NOT EXISTS idx_dwp_duty_user  ON app_user.drainage_waterlogging_point (duty_user_id)';

+ 18 - 0
pipe-network-service/sql/migration_alarm_common_routes_20261111.sql

@@ -0,0 +1,18 @@
+-- GIS/研判统一到 common;KingbaseES PostgreSQL 兼容模式,可重复执行。
+-- 仅按准确历史 component 迁移,不按菜单名称、ID、path 或 query 猜测。
+-- 保留所有其它菜单字段(含禁用状态、更新时间)及角色菜单授权,不恢复已撤销授权。
+BEGIN;
+
+UPDATE app_user.sys_menu
+SET component = CASE component
+    WHEN 'subSystem/drainage/alarm/analysis' THEN 'subSystem/alarm/common/analysis'
+    WHEN 'subSystem/drainage/alarm/alarmGIS' THEN 'subSystem/alarm/common/alarmGIS'
+    WHEN 'subSystem/waterSupply/alarm/alarmGIS' THEN 'subSystem/alarm/common/alarmGIS'
+END
+WHERE component IN (
+    'subSystem/drainage/alarm/analysis',
+    'subSystem/drainage/alarm/alarmGIS',
+    'subSystem/waterSupply/alarm/alarmGIS'
+);
+
+COMMIT;

+ 1 - 1
pipe-network-service/sql/migration_alarm_operations.sql

@@ -26,7 +26,7 @@ UPDATE app_user.sys_menu SET
     path = CASE menu_id WHEN 2139 THEN 'alarmRemind' WHEN 2140 THEN 'alarmList'
     path = CASE menu_id WHEN 2139 THEN 'alarmRemind' WHEN 2140 THEN 'alarmList'
         WHEN 2141 THEN 'drainageAlarmAnalysis' WHEN 2143 THEN 'drainageAlarmGIS' WHEN 2117 THEN 'alarmList' END,
         WHEN 2141 THEN 'drainageAlarmAnalysis' WHEN 2143 THEN 'drainageAlarmGIS' WHEN 2117 THEN 'alarmList' END,
     component = CASE menu_id WHEN 2139 THEN 'subSystem/alarm/common/remind' WHEN 2140 THEN 'subSystem/alarm/common/list'
     component = CASE menu_id WHEN 2139 THEN 'subSystem/alarm/common/remind' WHEN 2140 THEN 'subSystem/alarm/common/list'
-        WHEN 2141 THEN 'subSystem/drainage/alarm/analysis' WHEN 2143 THEN 'subSystem/drainage/alarm/alarmGIS'
+        WHEN 2141 THEN 'subSystem/alarm/common/analysis' WHEN 2143 THEN 'subSystem/alarm/common/alarmGIS'
         WHEN 2117 THEN 'subSystem/alarm/common/list' END,
         WHEN 2117 THEN 'subSystem/alarm/common/list' END,
     query = CASE WHEN menu_id = 2117 THEN '{"rootTypeId":1}' ELSE '{"rootTypeId":2}' END,
     query = CASE WHEN menu_id = 2117 THEN '{"rootTypeId":1}' ELSE '{"rootTypeId":2}' END,
     -- 框架按逗号拆分权限;供水首页的统计和实时异常仍使用原查询接口。
     -- 框架按逗号拆分权限;供水首页的统计和实时异常仍使用原查询接口。

+ 44 - 0
pipe-network-service/sql/migration_drainage_partition_drop_fields.sql

@@ -0,0 +1,44 @@
+-- 排水分区字段精简:下线「数据时间 / 排水量 / 积水量 / 积水等级」(KingbaseES)
+-- 用途:排水分区基础数据管理只保留 分区名称 / 分区类型 / 地址 三个业务字段,
+--      以下 4 列不再需要,从表结构中移除:
+--        time          数据时间
+--        drainage      排水量(m³)
+--        waterlogging  积水量(m³)
+--        "level"       积水等级
+-- 同步改动:后台实体 com.zksy.drainage.domain.DrainagePartition 已删除对应 4 个属性,
+--          前端 psfqgl.vue 的表单、列表、详情、校验规则一并移除。
+-- 注意:字典 drainage_waterlogging_level 仍被「易积水点」使用,**不要删字典**。
+-- 说明:脚本幂等,列不存在时自动跳过,可重复执行。
+--
+-- 前置(必须先执行):结束上一次失败执行遗留的 aborted 事务
+--   PG/KES 中语句报错后事务被标记为失败,同一连接上后续语句只会返回「当前事务被终止」。
+--   本句会回滚该连接上所有未提交事务,若另有手工操作未提交,请先单独提交再跑本脚本。
+ROLLBACK;
+
+-- ---------------------------------------------------------------------
+-- 步骤 1(可选):执行前备份这 4 列,确认数据不再需要可跳过本步
+-- ---------------------------------------------------------------------
+-- CREATE TABLE IF NOT EXISTS app_user.psgw_drainage_partition_bak_20261113 AS
+--   SELECT id, name, "time", drainage, waterlogging, "level"
+--     FROM app_user.psgw_drainage_partition;
+
+-- ---------------------------------------------------------------------
+-- 步骤 2:删除字段(已存在则跳过)
+-- ---------------------------------------------------------------------
+ALTER TABLE app_user.psgw_drainage_partition DROP COLUMN IF EXISTS "time";
+ALTER TABLE app_user.psgw_drainage_partition DROP COLUMN IF EXISTS drainage;
+ALTER TABLE app_user.psgw_drainage_partition DROP COLUMN IF EXISTS waterlogging;
+ALTER TABLE app_user.psgw_drainage_partition DROP COLUMN IF EXISTS "level";
+
+-- ---------------------------------------------------------------------
+-- 步骤 3:结果核验
+--   预期剩余列:id / name / district / partition_type / longitude / latitude /
+--               points / equipment_id / create_time / update_time
+--   若仍出现 time、drainage、waterlogging、level,说明该列存在依赖(视图或约束),
+--   需要先解除依赖再删除。
+-- ---------------------------------------------------------------------
+SELECT ordinal_position AS 序号, column_name AS 列名, data_type AS 类型
+  FROM information_schema.columns
+ WHERE table_schema = 'app_user'
+   AND table_name = 'psgw_drainage_partition'
+ ORDER BY ordinal_position;

+ 138 - 0
pipe-network-service/sql/migration_drainage_sewage_type_dict.sql

@@ -0,0 +1,138 @@
+-- 排水「管线类型(雨水/污水)」字典(KingbaseES)
+-- 用途:排水管网基础数据管理(psgwgl.vue)新增「管线类型」筛选与列表标签,
+--      地图按类型着色(雨水=蓝、污水=青)时图例文案统一读 sys_dict_data。
+-- 口径:直接对齐库表字段 pipe_network_base.network_level 的注释
+--      「实际用于区分排水管道(0-污水 1-雨水)」,即 0=污水 / 1=雨水,不做任何文本推导。
+--
+-- 说明:
+--   1. 排水口径下 network_level 不表示压力等级(燃气那套 0高压/1次高压/2中压/3低压 不适用),
+--      所以排水页面不再用 pipe_network_level,改用本字典。
+--   2. 本脚本只登记字典,不改表结构、不改业务数据;幂等,可重复执行。
+--
+-- =====================================================================
+-- 为什么本脚本要「显式指定主键」
+-- ---------------------------------------------------------------------
+-- 本库由 MySQL 迁移至 Kingbase,sys_dict_data / sys_dict_type 建表沿用了 MySQL 的
+-- auto_increment(KES 的 MySQL 兼容自增,不是 PG 的 serial/identity)。迁数据时是带显式
+-- 主键写入的,自增计数器没有跟着推进,于是「INSERT 不写主键」会发出一个已被占用的号:
+--     ERROR: 重复键违反唯一约束 "sys_dict_data_pkey"
+-- 且该列不是 identity 列,pg_get_serial_sequence / pg_depend 都拿不到序列,
+-- ALTER COLUMN ... RESTART WITH 也会报「不是标识列」。
+-- 因此 INSERT 一律写成 max(主键) + n,插完再尽力 setval(步骤 3)。
+-- =====================================================================
+--
+-- 前置:结束上一次失败执行遗留的 aborted 事务(会回滚本连接上所有未提交事务)
+ROLLBACK;
+
+BEGIN;
+
+-- 1. 字典类型(幂等登记;dict_id 显式取 max+1)
+INSERT INTO app_user.sys_dict_type
+    (dict_id, dict_name, dict_type, status, create_by, create_time, remark)
+SELECT (SELECT COALESCE(MAX(dict_id), 0) FROM app_user.sys_dict_type) + 1,
+       '排水管线类型', 'drainage_sewage_type', '0', 'admin', CURRENT_TIMESTAMP,
+       '排水管线类型:0污水 1雨水'
+ WHERE NOT EXISTS (SELECT 1 FROM app_user.sys_dict_type WHERE dict_type = 'drainage_sewage_type');
+
+UPDATE app_user.sys_dict_type
+   SET dict_name = '排水管线类型',
+       status = '0',
+       update_by = 'admin',
+       update_time = CURRENT_TIMESTAMP,
+       remark = '排水管线类型:0污水 1雨水(对应 pipe_network_base.network_level)'
+ WHERE dict_type = 'drainage_sewage_type';
+
+-- 2. 字典数据(幂等重写;list_class 决定列表标签配色,前端地图配色与此保持一致)
+DELETE FROM app_user.sys_dict_data WHERE dict_type = 'drainage_sewage_type';
+
+INSERT INTO app_user.sys_dict_data
+    (dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class,
+     is_default, status, create_by, create_time, remark)
+SELECT (SELECT COALESCE(MAX(dict_code), 0) FROM app_user.sys_dict_data) + v.rn,
+       v.dict_sort, v.dict_label, v.dict_value, 'drainage_sewage_type',
+       '', v.list_class, v.is_default, '0', 'admin', CURRENT_TIMESTAMP, v.remark
+  FROM (VALUES
+        (1, 2, '污水', '0', 'success', 'N', '污水管线,地图青色 #35BE83'),
+        (2, 1, '雨水', '1', 'primary', 'Y', '雨水管线,地图蓝色 #2F9BE8')
+       ) AS v(rn, dict_sort, dict_label, dict_value, list_class, is_default, remark)
+ ORDER BY v.rn;
+
+-- 3. 自增计数器校准(放在插入之后:此时 max 已含新插入的行)
+--    三种方式依次尝试,任一成功即可;都不成功只提示,不影响已插入的数据。
+DO $$
+DECLARE
+  t         record;
+  v_seq     text;
+  v_max     bigint;
+  v_default text;
+BEGIN
+  FOR t IN
+    SELECT * FROM (VALUES ('sys_dict_data', 'dict_code'),
+                          ('sys_dict_type', 'dict_id')) AS x(tbl, col)
+  LOOP
+    v_seq := NULL;
+    v_default := NULL;
+
+    -- 方式一 pg_get_serial_sequence(serial / identity)
+    BEGIN
+      v_seq := pg_get_serial_sequence(format('app_user.%I', t.tbl), t.col);
+    EXCEPTION WHEN OTHERS THEN
+      v_seq := NULL;
+    END;
+
+    -- 方式二 从列默认值里解析 nextval('...')
+    IF v_seq IS NULL THEN
+      BEGIN
+        SELECT pg_get_expr(ad.adbin, ad.adrelid) INTO v_default
+          FROM pg_attribute a
+          JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
+         WHERE a.attrelid = format('app_user.%I', t.tbl)::regclass
+           AND a.attname::text = t.col
+           AND a.attnum > 0
+           AND NOT a.attisdropped;
+      EXCEPTION WHEN OTHERS THEN
+        v_default := NULL;
+      END;
+
+      IF v_default LIKE '%nextval%' THEN
+        v_seq := substring(v_default from 'nextval\(''([^'']+)''');
+      END IF;
+    END IF;
+
+    -- 方式三 pg_depend 关联序列(兜底)
+    IF v_seq IS NULL THEN
+      BEGIN
+        SELECT d.objid::regclass::text INTO v_seq
+          FROM pg_depend d
+          JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
+          JOIN pg_class sc ON sc.oid = d.objid AND sc.relkind = 'S'
+         WHERE d.refobjid = format('app_user.%I', t.tbl)::regclass
+           AND a.attname::text = t.col
+           AND d.deptype IN ('a', 'i')
+         LIMIT 1;
+      EXCEPTION WHEN OTHERS THEN
+        v_seq := NULL;
+      END;
+    END IF;
+
+    IF v_seq IS NULL THEN
+      RAISE NOTICE '%.% 没有关联序列(应为 MySQL 兼容 auto_increment),跳过校准。本次数据已显式指定主键插入,不影响本脚本;但后续在该表手工新增行仍可能撞主键。',
+                   t.tbl, t.col;
+      CONTINUE;
+    END IF;
+
+    EXECUTE format('SELECT COALESCE(max(%I), 0) FROM app_user.%I', t.col, t.tbl) INTO v_max;
+    BEGIN
+      PERFORM setval(v_seq::regclass, GREATEST(v_max, 1), true);
+      RAISE NOTICE '%.% 自增序列已校准: % (max=%, next=%)', t.tbl, t.col, v_seq, v_max, v_max + 1;
+    EXCEPTION WHEN OTHERS THEN
+      RAISE NOTICE '%.% 序列校准失败: %,跳过', t.tbl, t.col, SQLERRM;
+    END;
+  END LOOP;
+END $$;
+
+-- 4. 结果核验(可选,取消注释执行):应返回 2 行,dict_value 依次 0、1
+--    SELECT dict_value, dict_label, list_class FROM app_user.sys_dict_data
+--     WHERE dict_type = 'drainage_sewage_type' ORDER BY dict_sort;
+
+COMMIT;

+ 175 - 0
pipe-network-service/sql/migration_drainage_waterlogging_point_devices.sql

@@ -0,0 +1,175 @@
+-- 易积水点:属性精简 + 关联对象由「摄像头」改为「设备」(KingbaseES, schema app_user)
+--
+-- 变更内容
+--   1. 下线四个属性:
+--        waterlogging_level(积水程度)、water_depth(积水深度 cm)、
+--        water_volume(积水量 m³)、water_area(积水面积 m²);
+--   2. 关联列 camera_ids 更名为 equipment_ids,语义由「摄像头」扩大为「设备」,
+--      仅允许 equipment_type.id 为 16(雷达液位计)与 20(视频监控-排口+内涝点)。
+--      存量数据直接搬迁:历史只存过 20 类摄像头设备,搬迁后仍在允许范围内。
+--
+-- 执行顺序(重要)
+--   后端实体已改为读 equipment_ids,**本脚本必须先于新版本服务启动执行**,
+--   否则易积水点相关接口会报「字段 equipment_ids 不存在」。
+--
+-- 幂等
+--   每一步都先查 information_schema 判断列是否存在,重复执行只输出 NOTICE。
+--   删列会连带删除依赖它的索引(idx_dwp_level),无需手工 DROP INDEX。
+--
+-- 2026-11-13 修订(必须用本版)
+--   初版第 3、4 步用了 FOREACH + format(%I) 和跨行的 EXECUTE 'xxx' || 'yyy',
+--   在本库的 KingbaseES 上 plpgsql 把该表达式解析成了非法语句,
+--   报「语法错误 在 "f" 或附近的 / QUERY: f」(f 来自 format 的首字母),
+--   整个 DO 块因此回滚,等于什么都没改。
+--   本版改为:删列用静态 ALTER(逐个 IF EXISTS 守卫),注释用单行 EXECUTE 字面量,
+--   不再有任何动态拼接 / format / FOREACH。
+--
+-- 字典
+--   drainage_waterlogging_level 保留不删(历史数据与其它模块可能引用)。
+--   确认无用后可单独执行:
+--     DELETE FROM app_user.sys_dict_data WHERE dict_type = 'drainage_waterlogging_level';
+--     DELETE FROM app_user.sys_dict_type WHERE dict_type = 'drainage_waterlogging_level';
+--
+-- 前置:结束上一次失败执行遗留的 aborted 事务(事务外执行只会告警,不报错)
+ROLLBACK;
+
+BEGIN;
+
+SET search_path TO app_user, public;
+
+DO $$
+DECLARE
+  has_equipment_ids boolean;
+  has_camera_ids    boolean;
+  moved             int := 0;
+BEGIN
+  IF to_regclass('app_user.drainage_waterlogging_point') IS NULL THEN
+    RAISE NOTICE '表 app_user.drainage_waterlogging_point 不存在,跳过';
+    RETURN;
+  END IF;
+
+  SELECT EXISTS (SELECT 1 FROM information_schema.columns
+                  WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                    AND column_name = 'equipment_ids') INTO has_equipment_ids;
+  SELECT EXISTS (SELECT 1 FROM information_schema.columns
+                  WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                    AND column_name = 'camera_ids') INTO has_camera_ids;
+
+  -- 1. 新增 equipment_ids
+  IF NOT has_equipment_ids THEN
+    ALTER TABLE app_user.drainage_waterlogging_point ADD COLUMN equipment_ids varchar(500);
+    RAISE NOTICE '1. 已新增列 equipment_ids';
+  ELSE
+    RAISE NOTICE '1. equipment_ids 已存在,跳过新增';
+  END IF;
+
+  -- 2. 存量关联从 camera_ids 搬到 equipment_ids(仅搬空值,避免覆盖手工修正)
+  IF has_camera_ids THEN
+    UPDATE app_user.drainage_waterlogging_point
+       SET equipment_ids = camera_ids
+     WHERE (equipment_ids IS NULL OR btrim(equipment_ids) = '')
+       AND camera_ids IS NOT NULL
+       AND btrim(camera_ids) <> '';
+    GET DIAGNOSTICS moved = ROW_COUNT;
+    RAISE NOTICE '2. 已从 camera_ids 搬迁 % 条关联记录', moved;
+  ELSE
+    RAISE NOTICE '2. camera_ids 已不存在,跳过数据搬迁';
+  END IF;
+
+  -- 3. 逐个删除下线字段与旧关联列(静态 DDL,不用动态 SQL)
+  IF EXISTS (SELECT 1 FROM information_schema.columns
+              WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                AND column_name = 'camera_ids') THEN
+    ALTER TABLE app_user.drainage_waterlogging_point DROP COLUMN camera_ids;
+    RAISE NOTICE '3. 已删除列 camera_ids';
+  ELSE
+    RAISE NOTICE '3. camera_ids 已不存在,跳过';
+  END IF;
+
+  IF EXISTS (SELECT 1 FROM information_schema.columns
+              WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                AND column_name = 'waterlogging_level') THEN
+    ALTER TABLE app_user.drainage_waterlogging_point DROP COLUMN waterlogging_level;
+    RAISE NOTICE '3. 已删除列 waterlogging_level';
+  ELSE
+    RAISE NOTICE '3. waterlogging_level 已不存在,跳过';
+  END IF;
+
+  IF EXISTS (SELECT 1 FROM information_schema.columns
+              WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                AND column_name = 'water_depth') THEN
+    ALTER TABLE app_user.drainage_waterlogging_point DROP COLUMN water_depth;
+    RAISE NOTICE '3. 已删除列 water_depth';
+  ELSE
+    RAISE NOTICE '3. water_depth 已不存在,跳过';
+  END IF;
+
+  IF EXISTS (SELECT 1 FROM information_schema.columns
+              WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                AND column_name = 'water_volume') THEN
+    ALTER TABLE app_user.drainage_waterlogging_point DROP COLUMN water_volume;
+    RAISE NOTICE '3. 已删除列 water_volume';
+  ELSE
+    RAISE NOTICE '3. water_volume 已不存在,跳过';
+  END IF;
+
+  IF EXISTS (SELECT 1 FROM information_schema.columns
+              WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+                AND column_name = 'water_area') THEN
+    ALTER TABLE app_user.drainage_waterlogging_point DROP COLUMN water_area;
+    RAISE NOTICE '3. 已删除列 water_area';
+  ELSE
+    RAISE NOTICE '3. water_area 已不存在,跳过';
+  END IF;
+
+  -- 4. 列注释(单行字面量,不拼接)
+  EXECUTE 'COMMENT ON COLUMN app_user.drainage_waterlogging_point.equipment_ids IS ''关联设备ID(equipment_base.equipment_id,多个用逗号分隔;仅允许 equipment_type.id = 16 雷达液位计 / 20 视频监控)''';
+  RAISE NOTICE '4. 已更新 equipment_ids 列注释';
+END $$;
+
+COMMIT;
+
+-- =====================================================================
+-- 5. 存量核对(只读;放在 COMMIT 之后,即使这一步有问题,上面的结构变更也已提交)
+--    正常 bad 应为 0;非 0 时页面仍能展示,但这些关联再次保存会被后端拦截,
+--    需要在「关联设备」里重新选择。
+-- =====================================================================
+DO $$
+DECLARE
+  v_points int := 0;
+  v_bad    int := 0;
+BEGIN
+  IF to_regclass('app_user.drainage_waterlogging_point') IS NULL THEN
+    RAISE NOTICE '5. 表不存在,跳过核对';
+    RETURN;
+  END IF;
+
+  SELECT count(*) INTO v_points
+    FROM app_user.drainage_waterlogging_point
+   WHERE equipment_ids IS NOT NULL AND btrim(equipment_ids) <> '';
+
+  SELECT count(*) INTO v_bad
+    FROM app_user.drainage_waterlogging_point p
+   WHERE EXISTS (
+           SELECT 1
+             FROM unnest(string_to_array(coalesce(p.equipment_ids, ''), ',')) AS t(eid)
+            WHERE btrim(t.eid) <> ''
+              AND NOT EXISTS (
+                    SELECT 1 FROM app_user.equipment_base e
+                     WHERE e.equipment_id = btrim(t.eid)
+                       AND e.equipment_type_id IN (16, 20)
+                  )
+         );
+
+  RAISE NOTICE '5. 已关联设备的易积水点 % 个,其中含无效或类型越界设备关联的 % 个', v_points, v_bad;
+END $$;
+
+-- =====================================================================
+-- 核验(可选,取消注释后单独执行)
+-- =====================================================================
+-- SELECT column_name, data_type FROM information_schema.columns
+--  WHERE table_schema = 'app_user' AND table_name = 'drainage_waterlogging_point'
+--  ORDER BY ordinal_position;
+--
+-- SELECT point_code, point_name, equipment_ids FROM app_user.drainage_waterlogging_point
+--  ORDER BY create_time DESC LIMIT 20;

+ 119 - 0
pipe-network-service/sql/tests/alarm_common_routes.test.mjs

@@ -0,0 +1,119 @@
+// Execute the actual migration SQL in an in-memory PostgreSQL-compatible engine.
+// PGLITE_MODULE points to an external, explicitly provisioned test dependency.
+// This harness never installs packages or connects to a real DB.
+// PGLITE_MODULE=/absolute/path/to/pglite/dist/index.js node --test alarm_common_routes.test.mjs
+import { readFile } from 'node:fs/promises'
+import { pathToFileURL } from 'node:url'
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+
+const { PGlite } = await import(process.env.PGLITE_MODULE
+  ? pathToFileURL(process.env.PGLITE_MODULE).href : '@electric-sql/pglite')
+// The optional baseline path exercises historical SQL without rewriting current implementation.
+const operationsSql = await readFile(process.env.ALARM_ROUTES_OPERATIONS_SQL
+  ? pathToFileURL(process.env.ALARM_ROUTES_OPERATIONS_SQL) : new URL('../migration_alarm_operations.sql', import.meta.url), 'utf8')
+const patchSql = () => readFile(new URL('../migration_alarm_common_routes_20261111.sql', import.meta.url), 'utf8')
+
+const schema = `
+  CREATE SCHEMA app_user;
+  CREATE TABLE app_user.sys_menu (
+    menu_id int8 PRIMARY KEY, menu_name text, parent_id int8, order_num integer,
+    path text, component text, query text, perms text, status text, visible text,
+    update_time timestamp
+  );
+  CREATE TABLE app_user.sys_role_menu (
+    role_id int8, menu_id int8, PRIMARY KEY (role_id, menu_id)
+  );
+`
+const rows = async (db, sql) => (await db.query(sql)).rows
+const menus = db => rows(db, 'SELECT * FROM app_user.sys_menu ORDER BY menu_id')
+const grants = db => rows(db, 'SELECT * FROM app_user.sys_role_menu ORDER BY role_id,menu_id')
+
+async function incrementalFixture() {
+  const db = new PGlite()
+  await db.exec(schema)
+  await db.exec(`
+    INSERT INTO app_user.sys_menu VALUES
+      (2141,'drainage analysis',2100,1,'keep-analysis','subSystem/drainage/alarm/analysis','{"rootTypeId":2,"warning_code":"WARN-ONLY"}','custom:analysis','0','0','2026-01-01'),
+      (2143,'drainage GIS',2100,3,'keep-gis','subSystem/drainage/alarm/alarmGIS','{"rootTypeId":2}','custom:gis','0','1','2026-01-02'),
+      (4301,'water GIS',2000,9,'keep-water','subSystem/waterSupply/alarm/alarmGIS','{"rootTypeId":1}','waterSupply:alarm:list','0','0','2026-01-03'),
+      (4302,'disabled exact legacy',999,7,'keep-disabled','subSystem/drainage/alarm/alarmGIS','{"rootTypeId":3,"warningCode":"WARN-GAS"}','custom:revoked','1','1','2026-01-04'),
+      (2117,'known ID but unknown component',999,4,'do-not-guess','subSystem/unknown/alarm/alarmGIS','{"rootTypeId":4}','custom:other','0','0','2026-01-05'),
+      (9001,'near-match suffix',999,5,'keep-suffix','subSystem/drainage/alarm/alarmGIS/extra','{}','custom:suffix','0','0','2026-01-06'),
+      (9002,'near-match whitespace',999,6,'keep-space',' subSystem/drainage/alarm/analysis','{}','custom:space','0','0','2026-01-07'),
+      (9003,'already canonical GIS',999,7,'keep-common','subSystem/alarm/common/alarmGIS','{"rootTypeId":1}','custom:common','0','0','2026-01-08'),
+      (9004,'already canonical analysis',999,8,'keep-common-analysis','subSystem/alarm/common/analysis','{}','custom:common-analysis','0','0','2026-01-09'),
+      (9005,'null component',999,9,'keep-null',NULL,'{}','custom:null','0','0','2026-01-10'),
+      (9006,'unsupported water analysis',999,10,'keep-water-analysis','subSystem/waterSupply/alarm/analysis','{}','custom:water-analysis','0','0','2026-01-11');
+    INSERT INTO app_user.sys_role_menu VALUES (9,2141),(9,2143),(10,4301),(10,9001);
+  `)
+  return db
+}
+
+test('fresh operations install points only the intended analysis/GIS menu components at common', async () => {
+  const db = new PGlite()
+  try {
+    await db.exec(schema + `
+      CREATE TABLE app_user.alarm_data (id text PRIMARY KEY);
+      CREATE TABLE app_user.work_order_log (log_id int8 PRIMARY KEY);
+      INSERT INTO app_user.sys_menu(menu_id,parent_id,order_num,path,component,query,perms,status)
+        VALUES (2141,2000,3,'old-analysis','old-analysis','{}','old:analysis','0'),
+        (2143,2000,4,'old-gis','old-gis','{}','old:gis','1'),
+        (9999,3000,9,'keep','custom/unrelated','{"rootTypeId":4}','keep:permission','1');
+      INSERT INTO app_user.sys_role_menu VALUES (9,2141),(10,2143);
+    `)
+    const beforeGrants = await grants(db)
+    const [unrelated] = await rows(db, 'SELECT * FROM app_user.sys_menu WHERE menu_id=9999')
+    await db.exec(operationsSql)
+    assert.deepEqual(await rows(db, 'SELECT menu_id,component,path,query,perms,parent_id,order_num,status FROM app_user.sys_menu WHERE menu_id IN (2141,2143) ORDER BY menu_id'), [
+      { menu_id: 2141, component: 'subSystem/alarm/common/analysis', path: 'drainageAlarmAnalysis', query: '{"rootTypeId":2}', perms: 'alarm:operations:list', parent_id: 2000, order_num: 3, status: '0' },
+      { menu_id: 2143, component: 'subSystem/alarm/common/alarmGIS', path: 'drainageAlarmGIS', query: '{"rootTypeId":2}', perms: 'alarm:operations:list', parent_id: 2000, order_num: 4, status: '1' },
+    ])
+    assert.deepEqual(await grants(db), beforeGrants)
+    assert.deepEqual(await rows(db, 'SELECT * FROM app_user.sys_menu WHERE menu_id=9999'), [unrelated])
+  } finally { await db.close() }
+})
+
+test('incremental patch maps exact legacy components and preserves every other menu field and role grant', async () => {
+  const db = await incrementalFixture()
+  try {
+    const before = await menus(db)
+    const beforeGrants = await grants(db)
+    await db.exec(await patchSql())
+    const expectedComponents = new Map([
+      [2141, 'subSystem/alarm/common/analysis'],
+      [2143, 'subSystem/alarm/common/alarmGIS'],
+      [4301, 'subSystem/alarm/common/alarmGIS'],
+      [4302, 'subSystem/alarm/common/alarmGIS'],
+    ])
+    assert.deepEqual(await menus(db), before.map(row => expectedComponents.has(row.menu_id)
+      ? { ...row, component: expectedComponents.get(row.menu_id) } : row))
+    assert.deepEqual(await grants(db), beforeGrants)
+  } finally { await db.close() }
+})
+
+test('repeat deployment is a no-op and never restores deliberately revoked role grants', async () => {
+  const db = await incrementalFixture()
+  try {
+    await db.exec(await patchSql())
+    await db.exec('DELETE FROM app_user.sys_role_menu WHERE role_id=9 AND menu_id=2141')
+    const once = await menus(db)
+    const revokedGrants = await grants(db)
+    await db.exec(await patchSql())
+    assert.deepEqual(await menus(db), once)
+    assert.deepEqual(await grants(db), revokedGrants)
+  } finally { await db.close() }
+})
+
+test('a failed component update rolls back the incremental patch without partial changes', async () => {
+  const db = await incrementalFixture()
+  try {
+    const before = await menus(db)
+    const beforeGrants = await grants(db)
+    await db.exec("ALTER TABLE app_user.sys_menu ADD CONSTRAINT reject_water_conversion CHECK (menu_id <> 4301 OR component <> 'subSystem/alarm/common/alarmGIS')")
+    await assert.rejects(db.exec(await patchSql()))
+    await db.exec('ROLLBACK')
+    assert.deepEqual(await menus(db), before)
+    assert.deepEqual(await grants(db), beforeGrants)
+  } finally { await db.close() }
+})

+ 24 - 0
pipe-network-service/sql/tests/video_session_media_node.test.mjs

@@ -0,0 +1,24 @@
+// In-memory SQL only. PGLITE_MODULE points to an already provisioned test module.
+import { readFile } from 'node:fs/promises'
+import { pathToFileURL } from 'node:url'
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+const { PGlite } = await import(process.env.PGLITE_MODULE ? pathToFileURL(process.env.PGLITE_MODULE).href : '@electric-sql/pglite')
+const sql = await readFile(new URL('../../../docs/video-session-media-node-20261112.sql', import.meta.url), 'utf8')
+
+test('media node migration preserves unknown legacy handles and stores only explicitly confirmed nodes', async () => {
+    const db = new PGlite()
+    try {
+        await db.exec(`CREATE SCHEMA app_user;
+            CREATE TABLE app_user.video_play_session(session_id text PRIMARY KEY, video_id text, stream_id text, status text);
+            INSERT INTO app_user.video_play_session VALUES ('legacy','camera','legacy_stream','ACTIVE');`)
+        await db.exec(sql)
+        assert.deepEqual((await db.query('SELECT * FROM app_user.video_play_session')).rows,
+            [{ session_id: 'legacy', video_id: 'camera', stream_id: 'legacy_stream', status: 'ACTIVE', media_server_id: null }])
+        await db.query("UPDATE app_user.video_play_session SET media_server_id=$1 WHERE session_id=$2", ['confirmed-node-A', 'legacy'])
+        assert.equal((await db.query("SELECT media_server_id FROM app_user.video_play_session WHERE session_id='legacy'")).rows[0].media_server_id, 'confirmed-node-A')
+        await assert.rejects(db.exec(sql)) // One-time migration deliberately refuses heterogeneous/repeated installs.
+        await db.exec('ROLLBACK')
+        assert.equal((await db.query("SELECT media_server_id FROM app_user.video_play_session WHERE session_id='legacy'")).rows[0].media_server_id, 'confirmed-node-A')
+    } finally { await db.close() }
+})

+ 8 - 0
pipe-network-service/zksy-admin/pom.xml

@@ -13,6 +13,14 @@
 
 
     <dependencies>
     <dependencies>
 
 
+        <!-- Only the offline SQL/transaction regression uses H2; never packaged at runtime. -->
+        <dependency>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
+            <version>2.1.214</version>
+            <scope>test</scope>
+        </dependency>
+
         <!-- spring-boot-devtools -->
         <!-- spring-boot-devtools -->
         <dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <groupId>org.springframework.boot</groupId>

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

@@ -0,0 +1,150 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.video.CockpitVideoException;
+import com.zksy.cockpit.video.CockpitVideoService;
+import com.zksy.common.core.domain.AjaxResult;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.time.Clock;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.UUID;
+
+@RestController
+@RequestMapping("/api/cockpit/v1/video")
+public class CockpitVideoController {
+    private final CockpitVideoService videos;
+    private final Clock clock;
+
+    public CockpitVideoController(CockpitVideoService videos, Clock clock) {
+        this.videos = videos;
+        this.clock = clock;
+    }
+
+    @GetMapping("/device")
+    public ResponseEntity<AjaxResult> device(@RequestParam("deviceCode") String code, HttpServletRequest request) {
+        return success(videos.device(code), request);
+    }
+
+    @PostMapping("/live")
+    public ResponseEntity<AjaxResult> live(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.live(field(body, "deviceCode")), request);
+    }
+
+    @PostMapping("/sessions/prepare")
+    public ResponseEntity<AjaxResult> prepare(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        Map<String, Object> data = videos.prepare(field(body, "deviceCode"));
+        data.putAll(metadata(request));
+        return ResponseEntity.status(201).cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
+    }
+
+    @PostMapping("/sessions/{id}/live")
+    public ResponseEntity<AjaxResult> preparedLive(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.startPrepared(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    /** Existing device/NVR recordings for one bounded UTC+8 window. */
+    @GetMapping("/records")
+    public ResponseEntity<AjaxResult> records(@RequestParam("deviceCode") String code,
+            @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
+            HttpServletRequest request) {
+        return success(videos.records(code, startTime, endTime), request);
+    }
+
+    /** Starts one anonymous playback session over an already-listed recording window. */
+    @PostMapping("/playback")
+    public ResponseEntity<AjaxResult> playback(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        Map<String, String> input = fields(body, "deviceCode", "startTime", "endTime");
+        return success(videos.playback(input.get("deviceCode"), input.get("startTime"),
+                input.get("endTime")), request);
+    }
+
+    @PostMapping("/sessions/{id}/status")
+    public ResponseEntity<AjaxResult> sessionStatus(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.status(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    @PostMapping("/sessions/{id}/heartbeat")
+    public ResponseEntity<AjaxResult> heartbeat(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.heartbeat(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    @PostMapping("/sessions/{id}/stop")
+    public ResponseEntity<AjaxResult> stop(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.stop(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    /** Controls this viewer's own playback session; values are bounded by the reused seam. */
+    @PostMapping("/sessions/{id}/control")
+    public ResponseEntity<AjaxResult> control(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        if (body == null || !(body.get("sessionToken") instanceof String) || !(body.get("action") instanceof String))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+        Double value = body.get("value") instanceof Number ? ((Number) body.get("value")).doubleValue() : null;
+        return success(videos.control(sessionId(id), (String) body.get("sessionToken"),
+                (String) body.get("action"), value), request);
+    }
+
+    private static String sessionId(String id) {
+        if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}"))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "播放会话标识无效");
+        return id;
+    }
+
+    private static String field(Map<String, Object> body, String field) {
+        if (body == null || body.size() != 1 || !(body.get(field) instanceof String))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+        return (String) body.get(field);
+    }
+
+    /** A playback request carries three required strings and nothing else. */
+    private static Map<String, String> fields(Map<String, Object> body, String... names) {
+        if (body == null || body.size() != names.length)
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+        Map<String, String> values = new java.util.LinkedHashMap<>();
+        for (String name : names) {
+            if (!(body.get(name) instanceof String)) throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+            values.put(name, (String) body.get(name));
+        }
+        return values;
+    }
+
+    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class,
+            org.springframework.web.bind.MissingServletRequestParameterException.class,
+            org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class})
+    public ResponseEntity<AjaxResult> invalidRequest(Exception failure, HttpServletRequest request) {
+        return error(new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效"), request);
+    }
+
+    private ResponseEntity<AjaxResult> success(Map<String, Object> data, HttpServletRequest request) {
+        data.putAll(metadata(request));
+        int status = "STARTING".equals(data.get("status")) || "CLEANUP_PENDING".equals(data.get("status")) ? 202 : 200;
+        return ResponseEntity.status(status).cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
+    }
+
+    @ExceptionHandler(CockpitVideoException.class)
+    public ResponseEntity<AjaxResult> error(CockpitVideoException failure, HttpServletRequest request) {
+        Map<String, Object> data = metadata(request);
+        data.put("category", failure.getCategory());
+        data.put("message", failure.getMessage());
+        return ResponseEntity.status(failure.getStatus()).cacheControl(org.springframework.http.CacheControl.noStore())
+                .body(new AjaxResult(failure.getStatus(), failure.getMessage(), data));
+    }
+
+    private Map<String, Object> metadata(HttpServletRequest request) {
+        String requestId = request.getHeader("X-Request-Id");
+        if (requestId == null || !requestId.matches("[A-Za-z0-9._-]{1,100}")) requestId = UUID.randomUUID().toString();
+        Map<String, Object> metadata = new LinkedHashMap<>();
+        metadata.put("requestId", requestId);
+        metadata.put("serverTime", DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(clock.instant().atZone(ZoneId.of("Asia/Shanghai"))));
+        return metadata;
+    }
+}

+ 1 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/drainage/DrainagePartitionController.java

@@ -37,7 +37,7 @@ public class DrainagePartitionController {
             @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
             @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
             @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
             @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
             @ApiParam("监测点名称") @RequestParam(required = false) String name,
             @ApiParam("监测点名称") @RequestParam(required = false) String name,
-            @ApiParam("行政区域") @RequestParam(required = false) String district,
+            @ApiParam("地址") @RequestParam(required = false) String district,
             @ApiParam("分区类型") @RequestParam(required = false) String partitionType) {
             @ApiParam("分区类型") @RequestParam(required = false) String partitionType) {
         return service.findByPage(pageNum, pageSize, name, district, partitionType);
         return service.findByPage(pageNum, pageSize, name, district, partitionType);
     }
     }

+ 13 - 8
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/drainage/WaterloggingPointController.java

@@ -28,7 +28,8 @@ import java.util.Map;
 
 
 /**
 /**
  * 易积水点管理
  * 易积水点管理
- * <p>易积水点关联的是视频摄像头,不是通用监测设备;前端在地图/列表中点击可直接播放关联摄像头。</p>
+ * 易积水点关联的是设备,限 equipment_type.id 为 16(雷达液位计)与 20(视频监控-排口+内涝点);
+ * 前端在地图/列表中点击可查看关联设备,视频类设备可直接播放实时画面。
  */
  */
 @Slf4j
 @Slf4j
 @RestController
 @RestController
@@ -119,17 +120,21 @@ public class WaterloggingPointController {
     }
     }
 
 
     @Anonymous
     @Anonymous
-    @PostMapping("/{id}/cameras")
-    @ApiOperation(value = "关联摄像头到易积水点(整体替换,空列表表示解除全部)")
-    public AjaxResult bindCameras(@PathVariable String id, @RequestBody Map<String, Object> params) {
-        Object raw = params == null ? null : params.get("cameraIds");
-        List<String> cameraIds = new ArrayList<>();
+    @PostMapping({"/{id}/devices", "/{id}/cameras"})
+    @ApiOperation(value = "关联设备到易积水点(整体替换,空列表表示解除全部;仅支持设备类型 16/20)")
+    public AjaxResult bindDevices(@PathVariable String id, @RequestBody Map<String, Object> params) {
+        Object raw = params == null ? null : params.get("equipmentIds");
+        if (raw == null && params != null) {
+            // 兼容旧前端字段名,语义已由「摄像头」扩展为「设备」
+            raw = params.get("cameraIds");
+        }
+        List<String> equipmentIds = new ArrayList<>();
         if (raw instanceof List) {
         if (raw instanceof List) {
             for (Object item : (List<?>) raw) {
             for (Object item : (List<?>) raw) {
-                if (item != null) cameraIds.add(String.valueOf(item));
+                if (item != null) equipmentIds.add(String.valueOf(item));
             }
             }
         }
         }
-        boolean success = service.bindCameras(id, cameraIds);
+        boolean success = service.bindDevices(id, equipmentIds);
         return success ? AjaxResult.success("关联成功") : AjaxResult.error("关联失败");
         return success ? AjaxResult.success("关联成功") : AjaxResult.error("关联失败");
     }
     }
 }
 }

+ 26 - 9
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/alarm/AlarmOperationsControllerTest.java

@@ -27,24 +27,41 @@ class AlarmOperationsControllerTest {
         assertEquals(2,query.getValue().getRootTypeId()); assertEquals(3,query.getValue().getPageNum());
         assertEquals(2,query.getValue().getRootTypeId()); assertEquals(3,query.getValue().getPageNum());
         assertEquals(20,query.getValue().getPageSize()); assertEquals(1,query.getValue().getAlarmStatus());
         assertEquals(20,query.getValue().getPageSize()); assertEquals(1,query.getValue().getAlarmStatus());
     }
     }
-    @Test void missingScopeAndOversizedPageAreRejected() throws Exception {
-        mvc.perform(get("/api/alarm")).andExpect(status().isBadRequest());
+    @Test void listWithoutRootBindsNullScope() throws Exception {
+        mvc.perform(get("/api/alarm")).andExpect(status().isOk());
+        ArgumentCaptor<AlarmQuery> query = ArgumentCaptor.forClass(AlarmQuery.class);
+        verify(operations).page(query.capture());
+        assertNull(query.getValue().getRootTypeId());
+        assertEquals(1, query.getValue().getPageNum());
+        assertEquals(10, query.getValue().getPageSize());
+        verifyNoMoreInteractions(operations);
+    }
+    @Test void oversizedPageIsRejectedBeforeCallingService() throws Exception {
         mvc.perform(get("/api/alarm").param("rootTypeId","2").param("pageSize","1001")).andExpect(status().isBadRequest());
         mvc.perform(get("/api/alarm").param("rootTypeId","2").param("pageSize","1001")).andExpect(status().isBadRequest());
+        mvc.perform(get("/api/alarm").param("pageSize","1001")).andExpect(status().isBadRequest());
         verifyNoInteractions(operations);
         verifyNoInteractions(operations);
     }
     }
-    @Test void dashboardBindsSupplyScopeAndDefaultOrExplicitDays() throws Exception {
+    @Test void dashboardBindsOptionalScopeAndDefaultOrExplicitDays() throws Exception {
         mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1")).andExpect(status().isOk());
         mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1")).andExpect(status().isOk());
-        ArgumentCaptor<AlarmQuery> query = ArgumentCaptor.forClass(AlarmQuery.class);
-        verify(operations).dashboard(query.capture(),eq(7));
-        assertEquals(1,query.getValue().getRootTypeId());
         mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1").param("days","14")).andExpect(status().isOk());
         mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1").param("days","14")).andExpect(status().isOk());
-        verify(operations).dashboard(any(AlarmQuery.class),eq(14));
-        mvc.perform(get("/api/alarm/dashboard")).andExpect(status().isBadRequest());
-        mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1").param("days","bad")).andExpect(status().isBadRequest());
+        mvc.perform(get("/api/alarm/dashboard")).andExpect(status().isOk());
+        ArgumentCaptor<AlarmQuery> query = ArgumentCaptor.forClass(AlarmQuery.class);
+        ArgumentCaptor<Integer> days = ArgumentCaptor.forClass(Integer.class);
+        verify(operations, times(3)).dashboard(query.capture(), days.capture());
+        assertEquals(1, query.getAllValues().get(0).getRootTypeId());
+        assertEquals(1, query.getAllValues().get(1).getRootTypeId());
+        assertNull(query.getAllValues().get(2).getRootTypeId());
+        assertEquals(java.util.Arrays.asList(7, 14, 7), days.getAllValues());
+        verifyNoMoreInteractions(operations);
         assertEquals("@ss.hasPermi('alarm:operations:list')", AlarmController.class
         assertEquals("@ss.hasPermi('alarm:operations:list')", AlarmController.class
                 .getMethod("dashboard",AlarmQuery.class,int.class)
                 .getMethod("dashboard",AlarmQuery.class,int.class)
                 .getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class).value());
                 .getAnnotation(org.springframework.security.access.prepost.PreAuthorize.class).value());
     }
     }
+    @Test void dashboardRejectsMalformedDaysBeforeCallingService() throws Exception {
+        mvc.perform(get("/api/alarm/dashboard").param("rootTypeId","1").param("days","bad")).andExpect(status().isBadRequest());
+        mvc.perform(get("/api/alarm/dashboard").param("days","bad")).andExpect(status().isBadRequest());
+        verifyNoInteractions(operations);
+    }
     @Test void analysisChoicesBindActualValueFilterBeforePagination() throws Exception {
     @Test void analysisChoicesBindActualValueFilterBeforePagination() throws Exception {
         mvc.perform(get("/api/alarm").param("rootTypeId","2").param("actualValueOnly","true").param("pageSize","100"))
         mvc.perform(get("/api/alarm").param("rootTypeId","2").param("actualValueOnly","true").param("pageSize","100"))
                 .andExpect(status().isOk());
                 .andExpect(status().isOk());

+ 12 - 2
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/alarm/AlarmReviewControllerTest.java

@@ -30,10 +30,20 @@ class AlarmReviewControllerTest {
         ArgumentCaptor<AlarmReviewQuery> query = ArgumentCaptor.forClass(AlarmReviewQuery.class);
         ArgumentCaptor<AlarmReviewQuery> query = ArgumentCaptor.forClass(AlarmReviewQuery.class);
         verify(reviews).page(query.capture()); assertEquals(999999000, query.getValue().getEndTime().getNano());
         verify(reviews).page(query.capture()); assertEquals(999999000, query.getValue().getEndTime().getNano());
     }
     }
-    @Test void missingRootAndMissingAuditStatusAreRejected() throws Exception {
-        mvc.perform(get("/api/alarm/reviews")).andExpect(status().isBadRequest());
+    @Test void reviewsWithoutRootBindNullScope() throws Exception {
+        mvc.perform(get("/api/alarm/reviews")).andExpect(status().isOk());
+        ArgumentCaptor<AlarmReviewQuery> query = ArgumentCaptor.forClass(AlarmReviewQuery.class);
+        verify(reviews).page(query.capture());
+        assertNull(query.getValue().getRootTypeId());
+        assertEquals(1, query.getValue().getPageNum());
+        assertEquals(10, query.getValue().getPageSize());
+        verifyNoMoreInteractions(reviews);
+    }
+    @Test void missingAuditStatusIsRejectedBeforeCallingService() throws Exception {
         mvc.perform(post("/api/alarm/a1/reviews").param("rootTypeId","1").contentType("application/json")
         mvc.perform(post("/api/alarm/a1/reviews").param("rootTypeId","1").contentType("application/json")
                 .content("{\"opinion\":\" \"}")).andExpect(status().isBadRequest());
                 .content("{\"opinion\":\" \"}")).andExpect(status().isBadRequest());
+        mvc.perform(post("/api/alarm/a1/reviews").contentType("application/json")
+                .content("{\"opinion\":\" \"}")).andExpect(status().isBadRequest());
         verifyNoInteractions(reviews);
         verifyNoInteractions(reviews);
     }
     }
     @ParameterizedTest
     @ParameterizedTest

+ 3 - 1
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/BusinessCockpitWorkOrderReadAdapterTest.java

@@ -71,7 +71,9 @@ class BusinessCockpitWorkOrderReadAdapterTest {
                 mock(AlarmWarningRelMapper.class),
                 mock(AlarmWarningRelMapper.class),
                 alarmDataService,
                 alarmDataService,
                 equipmentBaseMapper,
                 equipmentBaseMapper,
-                mock(com.zksy.base.service.EquipmentTypeService.class));
+                mock(com.zksy.base.service.EquipmentTypeService.class),
+                mock(com.zksy.system.mapper.SysDictDataMapper.class),
+                mock(com.zksy.system.service.ISysUserService.class));
     }
     }
 
 
     /** 注册实体的 lambda 缓存(等价于 MyBatis-Plus 启动时的 TableInfoHelper 初始化)。 */
     /** 注册实体的 lambda 缓存(等价于 MyBatis-Plus 启动时的 TableInfoHelper 初始化)。 */

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

@@ -1,54 +0,0 @@
-package com.zksy.web.controller.cockpit;
-
-import org.junit.jupiter.api.Test;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * Locks the confirmed cockpit anonymous-read policy (2026-09-28): GET /api/cockpit/v1/**
- * is served without authentication, everything else still requires authentication, and
- * deployment relies on intranet network isolation.
- *
- * <p>The full Spring Security chain needs the application context, so this test freezes
- * the matcher contract directly on {@code zksy-framework/.../SecurityConfig.java}.
- */
-class CockpitAnonymousAccessSecurityConfigTest {
-
-    private static final Path SECURITY_CONFIG = Path.of(
-            "..", "zksy-framework", "src", "main", "java", "com", "zksy", "framework",
-            "config", "SecurityConfig.java");
-
-    @Test
-    void cockpitPermitAllIsGetScopedAndSingleRule() throws Exception {
-        assertTrue(Files.exists(SECURITY_CONFIG), "SecurityConfig.java must exist at " + SECURITY_CONFIG);
-        List<String> lines = Files.readAllLines(SECURITY_CONFIG);
-
-        long cockpitPermitLines = lines.stream()
-                .filter(line -> line.contains("permitAll") && line.contains("/api/cockpit"))
-                .count();
-        assertEquals(1, cockpitPermitLines, "exactly one cockpit permitAll rule may exist");
-
-        String permitLine = lines.stream()
-                .filter(line -> line.contains("permitAll") && line.contains("/api/cockpit"))
-                .findFirst()
-                .orElseThrow();
-        assertTrue(permitLine.contains("HttpMethod.GET"),
-                "cockpit permitAll must be scoped to GET only");
-        assertTrue(permitLine.contains("\"/api/cockpit/v1/**\""),
-                "cockpit permitAll must cover /api/cockpit/v1/**");
-    }
-
-    @Test
-    void everythingOutsideCockpitGetStillRequiresAuthentication() throws Exception {
-        String source = Files.readString(SECURITY_CONFIG);
-        assertTrue(source.contains(".anyRequest().authenticated()"),
-                "the catch-all rule must still require authentication");
-        assertTrue(source.contains("\"/ws/deviceStatus\""),
-                "the WebSocket endpoint must keep its existing access rule");
-    }
-}

+ 98 - 56
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitCurrentEventsControllerTest.java

@@ -23,6 +23,7 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.Collections;
 import java.util.List;
 import java.util.List;
 
 
+import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.Matchers.nullValue;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -73,49 +74,58 @@ class CockpitCurrentEventsControllerTest {
                 .andExpect(jsonPath("$.data.filters.status").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.status").value(nullValue()))
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(100))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(100))
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
+                .andExpect(jsonPath("$.data.pagination.total").value(6))
                 .andExpect(jsonPath("$.data.pagination.totalPages").value(1))
                 .andExpect(jsonPath("$.data.pagination.totalPages").value(1))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false))
                 .andExpect(jsonPath("$.data.sections.events.state").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.sections.events.state").value("SUCCESS"))
-                .andExpect(jsonPath("$.data.sections.events.data", hasSize(5)))
-                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-001"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].level").value(1))
-                .andExpect(jsonPath("$.data.sections.events.data[0].levelColor").value("RED"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].deviceCode").value("D-GAS-1"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].monitoringPointCode").value("MP-A-001"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].monitoringPointName").value("城区A-燃气1号点"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].industry").value("GAS"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].coordinateValidation.state").value("VALID"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].coordinateValidation.reason").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[0].coordinateValidation.renderable").value(true))
-                .andExpect(jsonPath("$.data.sections.events.data[0].coordinateValidation.crs").value("WGS84"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].thresholdMinValue").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[0].thresholdMaxValue").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary.workOrderCode").value("WO-1"))
-                .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary.stateCode").value(3))
-                .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary.stateName").value("处理中"))
-                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-002"))
-                .andExpect(jsonPath("$.data.sections.events.data[1].levelColor").value("YELLOW"))
-                .andExpect(jsonPath("$.data.sections.events.data[1].workOrderSummary").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[2].eventNo").value("W-003"))
-                .andExpect(jsonPath("$.data.sections.events.data[2].levelColor").value("BLUE"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].eventNo").value("W-004"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].levelColor").value("GREEN"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].coordinateValidation.state").value("INVALID"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].coordinateValidation.reason").value("LONGITUDE_OUT_OF_RANGE"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].coordinateValidation.renderable").value(false))
-                .andExpect(jsonPath("$.data.sections.events.data[3].monitoringPointCode").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[4].eventNo").value("W-005"))
-                .andExpect(jsonPath("$.data.sections.events.data[4].levelColor").value("UNKNOWN"))
+                .andExpect(jsonPath("$.data.sections.events.data", hasSize(6)))
+                // 42bdb3db:未登记类型 W-006 保留,按时间排到正式行业事件之前。
+                .andExpect(jsonPath("$.data.sections.events.data[*].eventNo").value(
+                        contains("W-006", "W-001", "W-002", "W-003", "W-004", "W-005")))
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-006"))
+                .andExpect(jsonPath("$.data.sections.events.data[0].industry").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[0].deviceCode").value("D-LEGACY"))
+                .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-001"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].level").value(1))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-001')].levelColor").value(contains("RED")))
+                .andExpect(jsonPath("$.data.sections.events.data[1].deviceCode").value("D-GAS-1"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].monitoringPointCode").value("MP-A-001"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].monitoringPointName").value("城区A-燃气1号点"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].industry").value("GAS"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].coordinateValidation.state").value("VALID"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].coordinateValidation.reason").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[1].coordinateValidation.renderable").value(true))
+                .andExpect(jsonPath("$.data.sections.events.data[1].coordinateValidation.crs").value("WGS84"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].thresholdMinValue").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[1].thresholdMaxValue").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[1].workOrderSummary.workOrderCode").value("WO-1"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].workOrderSummary.stateCode").value(3))
+                .andExpect(jsonPath("$.data.sections.events.data[1].workOrderSummary.stateName").value("处理中"))
+                .andExpect(jsonPath("$.data.sections.events.data[2].eventNo").value("W-002"))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-002')].levelColor").value(contains("YELLOW")))
+                .andExpect(jsonPath("$.data.sections.events.data[2].workOrderSummary").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[3].eventNo").value("W-003"))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-003')].levelColor").value(contains("BLUE")))
+                .andExpect(jsonPath("$.data.sections.events.data[4].eventNo").value("W-004"))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-004')].levelColor").value(contains("GREEN")))
+                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.state").value("INVALID"))
+                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.reason").value("LONGITUDE_OUT_OF_RANGE"))
+                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.renderable").value(false))
+                .andExpect(jsonPath("$.data.sections.events.data[4].monitoringPointCode").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[5].eventNo").value("W-005"))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-005')].levelColor").value(contains("UNKNOWN")))
                 // 2026-10-12 契约:W-005 坐标 110.381/28.461 落在主场景区内 → 可上图。
                 // 2026-10-12 契约:W-005 坐标 110.381/28.461 落在主场景区内 → 可上图。
-                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.state").value("VALID"))
-                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.reason").value(nullValue()))
-                .andExpect(jsonPath("$.data.sections.events.data[4].coordinateValidation.renderable").value(true))
-                .andExpect(jsonPath("$.data.sections.events.data[4].workOrderSummary.stateName").value("已结案"))
+                .andExpect(jsonPath("$.data.sections.events.data[5].coordinateValidation.state").value("VALID"))
+                .andExpect(jsonPath("$.data.sections.events.data[5].coordinateValidation.reason").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[5].coordinateValidation.renderable").value(true))
+                .andExpect(jsonPath("$.data.sections.events.data[5].workOrderSummary.stateName").value("已结案"))
                 .andExpect(jsonPath("$.data.sections.workOrders.state").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.sections.workOrders.state").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.sections.workOrders.reason").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.sections.workOrders.reason").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.mapFilter.mode").value("WARNING"))
                 .andExpect(jsonPath("$.data.mapFilter.mode").value("WARNING"))
-                .andExpect(jsonPath("$.data.mapFilter.deviceCodes", hasSize(5)));
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes", hasSize(6)))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(
+                        contains("D-DR-1", "D-GAS-1", "D-GAS-2", "D-LEGACY", "D-WS-1", "D-WS-2")));
     }
     }
 
 
     @Test
     @Test
@@ -146,20 +156,36 @@ class CockpitCurrentEventsControllerTest {
     void levelColorsFollowOneRedTwoYellowThreeBlueFourGreen() throws Exception {
     void levelColorsFollowOneRedTwoYellowThreeBlueFourGreen() throws Exception {
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.sections.events.data[0].levelColor").value("RED"))
-                .andExpect(jsonPath("$.data.sections.events.data[1].levelColor").value("YELLOW"))
-                .andExpect(jsonPath("$.data.sections.events.data[2].levelColor").value("BLUE"))
-                .andExpect(jsonPath("$.data.sections.events.data[3].levelColor").value("GREEN"))
-                .andExpect(jsonPath("$.data.sections.events.data[4].levelColor").value("UNKNOWN"));
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-001')].levelColor").value(contains("RED")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-002')].levelColor").value(contains("YELLOW")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-003')].levelColor").value(contains("BLUE")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-004')].levelColor").value(contains("GREEN")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-005')].levelColor").value(contains("UNKNOWN")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-006')].levelColor").value(contains("RED")));
     }
     }
 
 
     @Test
     @Test
-    void unknownOrNonFormalEventTypesAreDroppedFromTheList() throws Exception {
+    void unknownEventTypesStayVisibleUntilAnIndustryFilterIsApplied() throws Exception {
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
-                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-001"))
-                .andExpect(jsonPath("$.data.mapFilter.deviceCodes", hasSize(5)));
+                .andExpect(jsonPath("$.data.pagination.total").value(6))
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-006"))
+                .andExpect(jsonPath("$.data.sections.events.data[0].industry").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[0].deviceCode").value("D-LEGACY"))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-007')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes", hasSize(6)))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(
+                        contains("D-DR-1", "D-GAS-1", "D-GAS-2", "D-LEGACY", "D-WS-1", "D-WS-2")));
+
+        // 未登记类型保留不等于归入燃气;旧井盖夹具仍为 industry=null,保持原样。
+        mockMvc.perform(get(ENDPOINT).param("mode", "WARNING").param("industry", "GAS"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.pagination.total").value(2))
+                .andExpect(jsonPath("$.data.sections.events.data[*].eventNo").value(contains("W-001", "W-002")))
+                .andExpect(jsonPath("$.data.sections.events.data[*].industry").value(contains("GAS", "GAS")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-006')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.mapFilter.industry").value("GAS"))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains("D-GAS-1", "D-GAS-2")));
     }
     }
 
 
     @Test
     @Test
@@ -181,8 +207,10 @@ class CockpitCurrentEventsControllerTest {
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.sections.events.state").value("SUCCESS"))
                 .andExpect(jsonPath("$.data.sections.events.state").value("SUCCESS"))
-                .andExpect(jsonPath("$.data.sections.events.data", hasSize(5)))
+                .andExpect(jsonPath("$.data.sections.events.data", hasSize(6)))
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-006"))
                 .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary").value(nullValue()))
                 .andExpect(jsonPath("$.data.sections.events.data[0].workOrderSummary").value(nullValue()))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-001')].workOrderSummary").value(contains(nullValue())))
                 .andExpect(jsonPath("$.data.sections.workOrders.state").value("FAILED"))
                 .andExpect(jsonPath("$.data.sections.workOrders.state").value("FAILED"))
                 .andExpect(jsonPath("$.data.sections.workOrders.reason").value("WORK_ORDER_SECTION_UNAVAILABLE"))
                 .andExpect(jsonPath("$.data.sections.workOrders.reason").value("WORK_ORDER_SECTION_UNAVAILABLE"))
                 .andExpect(jsonPath("$.data.sections.workOrders.message").value("工单状态分区暂不可用"));
                 .andExpect(jsonPath("$.data.sections.workOrders.message").value("工单状态分区暂不可用"));
@@ -210,20 +238,26 @@ class CockpitCurrentEventsControllerTest {
                         .param("page", "1")
                         .param("page", "1")
                         .param("pageSize", "2"))
                         .param("pageSize", "2"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
+                .andExpect(jsonPath("$.data.pagination.total").value(6))
                 .andExpect(jsonPath("$.data.pagination.totalPages").value(3))
                 .andExpect(jsonPath("$.data.pagination.totalPages").value(3))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(true))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(true))
                 .andExpect(jsonPath("$.data.sections.events.data", hasSize(2)))
                 .andExpect(jsonPath("$.data.sections.events.data", hasSize(2)))
-                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-001"))
-                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-002"));
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-006"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-001"))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(
+                        contains("D-DR-1", "D-GAS-1", "D-GAS-2", "D-LEGACY", "D-WS-1", "D-WS-2")));
 
 
         mockMvc.perform(get(ENDPOINT)
         mockMvc.perform(get(ENDPOINT)
                         .param("mode", "WARNING")
                         .param("mode", "WARNING")
                         .param("page", "3")
                         .param("page", "3")
                         .param("pageSize", "2"))
                         .param("pageSize", "2"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.sections.events.data", hasSize(1)))
-                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-005"))
+                .andExpect(jsonPath("$.data.sections.events.data", hasSize(2)))
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-004"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-005"))
+                .andExpect(jsonPath("$.data.pagination.total").value(6))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(
+                        contains("D-DR-1", "D-GAS-1", "D-GAS-2", "D-LEGACY", "D-WS-1", "D-WS-2")))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
     }
     }
 
 
@@ -242,15 +276,21 @@ class CockpitCurrentEventsControllerTest {
                         .param("industry", "WATER_SUPPLY"))
                         .param("industry", "WATER_SUPPLY"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.pagination.total").value(2))
                 .andExpect(jsonPath("$.data.pagination.total").value(2))
+                .andExpect(jsonPath("$.data.sections.events.data[*].eventNo").value(contains("W-003", "W-005")))
+                .andExpect(jsonPath("$.data.sections.events.data[?(@.eventNo == 'W-006')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains("D-WS-1", "D-WS-2")))
                 .andExpect(jsonPath("$.data.mapFilter.industry").value("WATER_SUPPLY"));
                 .andExpect(jsonPath("$.data.mapFilter.industry").value("WATER_SUPPLY"));
 
 
         mockMvc.perform(get(ENDPOINT)
         mockMvc.perform(get(ENDPOINT)
                         .param("mode", "WARNING")
                         .param("mode", "WARNING")
                         .param("status", "ACTIVE"))
                         .param("status", "ACTIVE"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.pagination.total").value(3))
-                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-001"))
-                .andExpect(jsonPath("$.data.sections.events.data[2].eventNo").value("W-005"))
+                .andExpect(jsonPath("$.data.pagination.total").value(4))
+                .andExpect(jsonPath("$.data.sections.events.data[0].eventNo").value("W-006"))
+                .andExpect(jsonPath("$.data.sections.events.data[1].eventNo").value("W-001"))
+                .andExpect(jsonPath("$.data.sections.events.data[3].eventNo").value("W-005"))
+                .andExpect(jsonPath("$.data.sections.events.data[*].eventNo").value(contains("W-006", "W-001", "W-002", "W-005")))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains("D-GAS-1", "D-GAS-2", "D-LEGACY", "D-WS-2")))
                 .andExpect(jsonPath("$.data.mapFilter.status").value("ACTIVE"));
                 .andExpect(jsonPath("$.data.mapFilter.status").value("ACTIVE"));
     }
     }
 
 
@@ -324,14 +364,16 @@ class CockpitCurrentEventsControllerTest {
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value("未分区"))
                 .andExpect(jsonPath("$.data.filters.districtName").value("未分区"))
-                .andExpect(jsonPath("$.data.pagination.total").value(2));
+                .andExpect(jsonPath("$.data.pagination.total").value(3))
+                .andExpect(jsonPath("$.data.sections.events.data[*].eventNo").value(contains("W-006", "W-004", "W-005")))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains("D-DR-1", "D-LEGACY", "D-WS-2")));
 
 
         // 不传=全域
         // 不传=全域
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
         mockMvc.perform(get(ENDPOINT).param("mode", "WARNING"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value(nullValue()))
-                .andExpect(jsonPath("$.data.pagination.total").value(5));
+                .andExpect(jsonPath("$.data.pagination.total").value(6));
 
 
         // 报警模式同一套语义(片区是事件族共同维度,不是预警专属)
         // 报警模式同一套语义(片区是事件族共同维度,不是预警专属)
         mockMvc.perform(get(ENDPOINT).param("mode", "ALARM").param("district", "2"))
         mockMvc.perform(get(ENDPOINT).param("mode", "ALARM").param("district", "2"))

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

@@ -64,6 +64,10 @@ class CockpitEventReadControllerTest {
                 .andExpect(jsonPath("$.data.warnings[0].warningNo").value("WRN-20260902-001"))
                 .andExpect(jsonPath("$.data.warnings[0].warningNo").value("WRN-20260902-001"))
                 .andExpect(jsonPath("$.data.warnings[0].level").value(1))
                 .andExpect(jsonPath("$.data.warnings[0].level").value(1))
                 .andExpect(jsonPath("$.data.warnings[0].levelColor").value("RED"))
                 .andExpect(jsonPath("$.data.warnings[0].levelColor").value("RED"))
+                .andExpect(jsonPath("$.data.warnings[0].levelName").value("一级预警"))
+                .andExpect(jsonPath("$.data.warnings[0].content")
+                        .value("化学需氧量(COD)预警接近上限\n实际值:14.6 mg/L;阈值:上限 20 mg/L"))
+                .andExpect(jsonPath("$.data.warnings[1].content").value(org.hamcrest.Matchers.nullValue()))
                 .andExpect(jsonPath("$.data.warnings[0].status").value("PROCESSING"))
                 .andExpect(jsonPath("$.data.warnings[0].status").value("PROCESSING"))
                 .andExpect(jsonPath("$.data.warnings[0].deviceCode").value(DEVICE_CODE))
                 .andExpect(jsonPath("$.data.warnings[0].deviceCode").value(DEVICE_CODE))
                 .andExpect(jsonPath("$.data.warnings[1].level").value(2))
                 .andExpect(jsonPath("$.data.warnings[1].level").value(2))
@@ -72,6 +76,8 @@ class CockpitEventReadControllerTest {
                 .andExpect(jsonPath("$.data.alarms[0].alarmId").value("ALM-20260902-001"))
                 .andExpect(jsonPath("$.data.alarms[0].alarmId").value("ALM-20260902-001"))
                 .andExpect(jsonPath("$.data.alarms[0].level").value(3))
                 .andExpect(jsonPath("$.data.alarms[0].level").value(3))
                 .andExpect(jsonPath("$.data.alarms[0].levelColor").value("BLUE"))
                 .andExpect(jsonPath("$.data.alarms[0].levelColor").value("BLUE"))
+                .andExpect(jsonPath("$.data.alarms[0].levelName").value("三级报警"))
+                .andExpect(jsonPath("$.data.alarms[0].content").value("化学需氧量(COD)报警超过上限"))
                 .andExpect(jsonPath("$.data.alarms[0].status").value("UNHANDLED"))
                 .andExpect(jsonPath("$.data.alarms[0].status").value("UNHANDLED"))
                 .andExpect(jsonPath("$.data.alarms[0].deviceCode").value(DEVICE_CODE))
                 .andExpect(jsonPath("$.data.alarms[0].deviceCode").value(DEVICE_CODE))
                 .andExpect(jsonPath("$.data.alarmWarningRelations", org.hamcrest.Matchers.hasSize(1)))
                 .andExpect(jsonPath("$.data.alarmWarningRelations", org.hamcrest.Matchers.hasSize(1)))
@@ -189,16 +195,18 @@ class CockpitEventReadControllerTest {
                 "污水环境监测设备",
                 "污水环境监测设备",
                 Arrays.asList(
                 Arrays.asList(
                         new CockpitEventWarning(
                         new CockpitEventWarning(
-                                "WRN-20260902-001", "污水COD预警", "WS_ENV", 1, "RED",
+                                "WRN-20260902-001", "污水COD预警", "WS_ENV", 1, "RED", "一级预警",
+                                "化学需氧量(COD)预警接近上限\n实际值:14.6 mg/L;阈值:上限 20 mg/L",
                                 "PROCESSING", "2026-09-02T09:59:30+08:00",
                                 "PROCESSING", "2026-09-02T09:59:30+08:00",
                                 new BigDecimal("18.2"), "mg/L", DEVICE_CODE, "污水环境监测设备", "太常片区"),
                                 new BigDecimal("18.2"), "mg/L", DEVICE_CODE, "污水环境监测设备", "太常片区"),
                         new CockpitEventWarning(
                         new CockpitEventWarning(
-                                "WRN-20260902-002", "污水pH预警", "WS_ENV", 2, "YELLOW",
+                                "WRN-20260902-002", "污水pH预警", "WS_ENV", 2, "YELLOW", "二级预警",
+                                null,
                                 "PENDING", "2026-09-02T09:58:30+08:00",
                                 "PENDING", "2026-09-02T09:58:30+08:00",
                                 new BigDecimal("8.1"), "", DEVICE_CODE, "污水环境监测设备", "太常片区")),
                                 new BigDecimal("8.1"), "", DEVICE_CODE, "污水环境监测设备", "太常片区")),
                 Collections.singletonList(new CockpitEventAlarm(
                 Collections.singletonList(new CockpitEventAlarm(
-                        "ALM-20260902-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 3, "BLUE",
-                        "UNHANDLED", "2026-09-02T10:00:00+08:00",
+                        "ALM-20260902-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 3, "BLUE", "三级报警",
+                        "化学需氧量(COD)报警超过上限", "UNHANDLED", "2026-09-02T10:00:00+08:00",
                         new BigDecimal("42.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
                         new BigDecimal("42.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
                         DEVICE_CODE, "污水环境监测设备", "太常片区")),
                         DEVICE_CODE, "污水环境监测设备", "太常片区")),
                 Collections.singletonList(new CockpitAlarmWarningRelation(
                 Collections.singletonList(new CockpitAlarmWarningRelation(
@@ -227,8 +235,8 @@ class CockpitEventReadControllerTest {
                 "污水环境监测设备",
                 "污水环境监测设备",
                 Arrays.asList(warning("WRN-20260901-001", 2), warning("WRN-20260901-002", 4)),
                 Arrays.asList(warning("WRN-20260901-001", 2), warning("WRN-20260901-002", 4)),
                 Collections.singletonList(new CockpitEventAlarm(
                 Collections.singletonList(new CockpitEventAlarm(
-                        "ALM-20260901-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 1, "RED",
-                        "HANDLED", "2026-09-01T15:30:00+08:00",
+                        "ALM-20260901-001", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 1, "RED", "一级报警",
+                        null, "HANDLED", "2026-09-01T15:30:00+08:00",
                         new BigDecimal("45.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
                         new BigDecimal("45.0"), new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
                         DEVICE_CODE, "污水环境监测设备", "太常片区")),
                         DEVICE_CODE, "污水环境监测设备", "太常片区")),
                 Collections.singletonList(new CockpitAlarmWarningRelation(
                 Collections.singletonList(new CockpitAlarmWarningRelation(
@@ -245,7 +253,8 @@ class CockpitEventReadControllerTest {
 
 
     private CockpitEventWarning warning(String warningNo, Integer level) {
     private CockpitEventWarning warning(String warningNo, Integer level) {
         return new CockpitEventWarning(
         return new CockpitEventWarning(
-                warningNo, "等级映射预警", "WS_ENV", level, CockpitEventLevelColor.resolve(level), "PENDING",
+                warningNo, "等级映射预警", "WS_ENV", level, CockpitEventLevelColor.resolve(level),
+                level == null ? null : level + "级预警", null, "PENDING",
                 "2026-09-02T09:59:30+08:00", null, "", DEVICE_CODE, "污水环境监测设备", "太常片区");
                 "2026-09-02T09:59:30+08:00", null, "", DEVICE_CODE, "污水环境监测设备", "太常片区");
     }
     }
 }
 }

+ 53 - 14
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitHandlingEfficiencyControllerTest.java

@@ -22,6 +22,7 @@ import java.time.ZoneOffset;
 import java.util.Arrays;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Collections;
 
 
+import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.Matchers.nullValue;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -85,9 +86,9 @@ class CockpitHandlingEfficiencyControllerTest {
                 .andExpect(jsonPath("$.data.filters.eventFamily").value("WARNING"))
                 .andExpect(jsonPath("$.data.filters.eventFamily").value("WARNING"))
                 .andExpect(jsonPath("$.data.filters.workOrderState").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.workOrderState").value(nullValue()))
                 // 事件口径两族共用(真实计数,不是第二轮读数)。
                 // 事件口径两族共用(真实计数,不是第二轮读数)。
-                .andExpect(jsonPath("$.data.summary.totalEvents").value(8))
+                .andExpect(jsonPath("$.data.summary.totalEvents").value(9))
                 .andExpect(jsonPath("$.data.summary.linkedWorkOrderCount").value(6))
                 .andExpect(jsonPath("$.data.summary.linkedWorkOrderCount").value(6))
-                .andExpect(jsonPath("$.data.summary.missingWorkOrderCount").value(2))
+                .andExpect(jsonPath("$.data.summary.missingWorkOrderCount").value(3))
                 // 票 74:**工单口径**对预警族不成立 → 显式 null(不是 0,也不是别的族的数)。
                 // 票 74:**工单口径**对预警族不成立 → 显式 null(不是 0,也不是别的族的数)。
                 .andExpect(jsonPath("$.data.summary.handledCount").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.handledCount").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.inProgressCount").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.inProgressCount").value(nullValue()))
@@ -95,8 +96,8 @@ class CockpitHandlingEfficiencyControllerTest {
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.averageDuration").value(nullValue()))
                 .andExpect(jsonPath("$.data.summary.averageDuration").value(nullValue()))
                 .andExpect(jsonPath("$.data.workOrderStateCounts").value(nullValue()))
                 .andExpect(jsonPath("$.data.workOrderStateCounts").value(nullValue()))
-                // 预警自身六态全铺(缺的态计 0),顺序即 WarningWorkflow 主线。
-                .andExpect(jsonPath("$.data.warningStateCounts", hasSize(6)))
+                // 六个已知态全铺;EW-LEGACY 状态为空,另计 UNKNOWN,桶和仍为 9。
+                .andExpect(jsonPath("$.data.warningStateCounts", hasSize(7)))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].stateCode").value("DRAFT"))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].stateCode").value("DRAFT"))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].stateName").value("草稿"))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].stateName").value("草稿"))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].count").value(1))
                 .andExpect(jsonPath("$.data.warningStateCounts[0].count").value(1))
@@ -112,10 +113,13 @@ class CockpitHandlingEfficiencyControllerTest {
                 .andExpect(jsonPath("$.data.warningStateCounts[5].stateCode").value("CLOSED"))
                 .andExpect(jsonPath("$.data.warningStateCounts[5].stateCode").value("CLOSED"))
                 .andExpect(jsonPath("$.data.warningStateCounts[5].stateName").value("已解除"))
                 .andExpect(jsonPath("$.data.warningStateCounts[5].stateName").value("已解除"))
                 .andExpect(jsonPath("$.data.warningStateCounts[5].count").value(3))
                 .andExpect(jsonPath("$.data.warningStateCounts[5].count").value(3))
-                // 已解除率=已解除 ÷ 窗口内预警数(3/8),基线与工单口径不同名。
+                .andExpect(jsonPath("$.data.warningStateCounts[6].stateCode").value("UNKNOWN"))
+                .andExpect(jsonPath("$.data.warningStateCounts[6].stateName").value("未知"))
+                .andExpect(jsonPath("$.data.warningStateCounts[6].count").value(1))
+                // 已解除率=已解除 ÷ 窗口内全部预警数(含未知类型,3/9)。
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.numerator").value(3))
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.numerator").value(3))
-                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.denominator").value(8))
-                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.value").value("0.3750"))
+                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.denominator").value(9))
+                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.value").value("0.3333"))
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.basis")
                 .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.basis")
                         .value("CLOSED_WARNINGS_OVER_WINDOW_WARNINGS"))
                         .value("CLOSED_WARNINGS_OVER_WINDOW_WARNINGS"))
@@ -124,16 +128,28 @@ class CockpitHandlingEfficiencyControllerTest {
                 .andExpect(jsonPath("$.data.summary.warningDuration.unit").value("HOURS"))
                 .andExpect(jsonPath("$.data.summary.warningDuration.unit").value("HOURS"))
                 .andExpect(jsonPath("$.data.summary.warningDuration.sampleCount").value(3))
                 .andExpect(jsonPath("$.data.summary.warningDuration.sampleCount").value(3))
                 .andExpect(jsonPath("$.data.summary.warningDuration.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.summary.warningDuration.state").value("AVAILABLE"))
-                .andExpect(jsonPath("$.data.events", hasSize(8)))
+                .andExpect(jsonPath("$.data.events", hasSize(9)))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("EW-007"))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("EW-007"))
                 .andExpect(jsonPath("$.data.events[0].hasWorkOrder").value(true))
                 .andExpect(jsonPath("$.data.events[0].hasWorkOrder").value(true))
-                .andExpect(jsonPath("$.data.pagination.total").value(8))
+                .andExpect(jsonPath("$.data.events[*].eventNo").value(contains(
+                        "EW-007", "EW-006", "EW-005", "EW-004", "EW-008", "EW-003", "EW-LEGACY", "EW-002", "EW-001")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')].deviceCode").value(contains("D-LEGACY")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')].hasWorkOrder").value(contains(false)))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')].workOrderStateCode").value(contains(nullValue())))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')].levelColor").value(contains("RED")))
+                .andExpect(jsonPath("$.data.pagination.total").value(9))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains(
+                        "D-DR-1", "D-DR-2", "D-DR-3", "D-GAS-1", "D-GAS-2", "D-GAS-3", "D-LEGACY", "D-WS-1", "D-WS-2")))
                 // 趋势桶:事件发布量照实给,工单结案量与结案时长两族口径 → null。
                 // 趋势桶:事件发布量照实给,工单结案量与结案时长两族口径 → null。
                 .andExpect(jsonPath("$.data.durationTrend", hasSize(5)))
                 .andExpect(jsonPath("$.data.durationTrend", hasSize(5)))
                 .andExpect(jsonPath("$.data.durationTrend[0].timeBucket").value("2026-09-02T08:00:00+08:00"))
                 .andExpect(jsonPath("$.data.durationTrend[0].timeBucket").value("2026-09-02T08:00:00+08:00"))
                 .andExpect(jsonPath("$.data.durationTrend[0].eventCount").value(2))
                 .andExpect(jsonPath("$.data.durationTrend[0].eventCount").value(2))
                 .andExpect(jsonPath("$.data.durationTrend[0].handledCount").value(nullValue()))
                 .andExpect(jsonPath("$.data.durationTrend[0].handledCount").value(nullValue()))
                 .andExpect(jsonPath("$.data.durationTrend[0].averageDuration").value(nullValue()))
                 .andExpect(jsonPath("$.data.durationTrend[0].averageDuration").value(nullValue()))
+                .andExpect(jsonPath("$.data.durationTrend[1].timeBucket").value("2026-09-02T09:00:00+08:00"))
+                .andExpect(jsonPath("$.data.durationTrend[1].eventCount").value(3))
+                .andExpect(jsonPath("$.data.durationTrend[2].eventCount").value(2))
+                .andExpect(jsonPath("$.data.durationTrend[3].eventCount").value(2))
                 .andExpect(jsonPath("$.data.durationTrend[4].timeBucket").value("2026-09-02T12:00:00+08:00"))
                 .andExpect(jsonPath("$.data.durationTrend[4].timeBucket").value("2026-09-02T12:00:00+08:00"))
                 .andExpect(jsonPath("$.data.durationTrend[4].eventCount").value(0));
                 .andExpect(jsonPath("$.data.durationTrend[4].eventCount").value(0));
     }
     }
@@ -321,9 +337,32 @@ class CockpitHandlingEfficiencyControllerTest {
                         .param("startTime", START)
                         .param("startTime", START)
                         .param("endTime", END))
                         .param("endTime", END))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
-                .andExpect(jsonPath("$.data.summary.missingWorkOrderCount").value(2))
-                .andExpect(jsonPath("$.data.events", hasSize(8)))
-                .andExpect(jsonPath("$.data.summary.totalEvents").value(8));
+                .andExpect(jsonPath("$.data.summary.missingWorkOrderCount").value(3))
+                .andExpect(jsonPath("$.data.events", hasSize(9)))
+                .andExpect(jsonPath("$.data.summary.totalEvents").value(9))
+                .andExpect(jsonPath("$.data.events[?(@.hasWorkOrder == false)].eventNo").value(contains("EW-005", "EW-008", "EW-LEGACY")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')].deviceCode").value(contains("D-LEGACY")))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes", hasSize(9)));
+
+        // EventItem 不公开 industry;以真实筛选结果证明未知类型未被归入燃气。
+        mockMvc.perform(get(ENDPOINT)
+                        .param("eventFamily", "WARNING")
+                        .param("industry", "GAS")
+                        .param("startTime", START)
+                        .param("endTime", END))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.filters.industry").value("GAS"))
+                .andExpect(jsonPath("$.data.summary.totalEvents").value(3))
+                .andExpect(jsonPath("$.data.summary.linkedWorkOrderCount").value(3))
+                .andExpect(jsonPath("$.data.summary.missingWorkOrderCount").value(0))
+                .andExpect(jsonPath("$.data.events[*].eventNo").value(contains("EW-006", "EW-002", "EW-001")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'EW-LEGACY')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.warningStateCounts", hasSize(6)))
+                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.numerator").value(1))
+                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.denominator").value(3))
+                .andExpect(jsonPath("$.data.summary.warningHandlingEfficiency.value").value("0.3333"))
+                .andExpect(jsonPath("$.data.pagination.total").value(3))
+                .andExpect(jsonPath("$.data.mapFilter.deviceCodes").value(contains("D-GAS-1", "D-GAS-2", "D-GAS-3")));
     }
     }
 
 
     @Test
     @Test
@@ -559,8 +598,8 @@ class CockpitHandlingEfficiencyControllerTest {
     }
     }
 
 
     /**
     /**
-     * 主样本:8 条在范围内预警(`EW-LEGACY` 的类型不在设备类型表里,被行业范围判定排除),
-     * 状态覆盖六态 —— DRAFT 1 / PENDING 1 / RECEIVED 1 / PROCESSING 1 / HANDLED 1 / CLOSED 3,
+     * 主样本:9 条在范围内预警;`EW-LEGACY` 类型未登记但全域保留,状态为空计 UNKNOWN。
+     * 已知状态覆盖六态 —— DRAFT 1 / PENDING 1 / RECEIVED 1 / PROCESSING 1 / HANDLED 1 / CLOSED 3,
      * 其中三条 CLOSED 的 `update_time` 分别距发布 0.50h / 2.00h / 1.00h。
      * 其中三条 CLOSED 的 `update_time` 分别距发布 0.50h / 2.00h / 1.00h。
      */
      */
     private static CockpitHandlingEfficiencySnapshot fixture() {
     private static CockpitHandlingEfficiencySnapshot fixture() {

+ 60 - 16
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitHistoryAnalysisControllerTest.java

@@ -23,6 +23,7 @@ import java.time.ZoneOffset;
 import java.util.Arrays;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Collections;
 
 
+import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.Matchers.nullValue;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -81,23 +82,34 @@ class CockpitHistoryAnalysisControllerTest {
                 .andExpect(jsonPath("$.data.filters.eventFamily").value("WARNING"))
                 .andExpect(jsonPath("$.data.filters.eventFamily").value("WARNING"))
                 .andExpect(jsonPath("$.data.filters.level").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.level").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.industry").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.industry").value(nullValue()))
-                .andExpect(jsonPath("$.data.summary.eventCount").value(5))
+                .andExpect(jsonPath("$.data.summary.eventCount").value(7))
                 .andExpect(jsonPath("$.data.summary.handledCount").value(2))
                 .andExpect(jsonPath("$.data.summary.handledCount").value(2))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.value").value("0.4000"))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.value").value("0.4000"))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.numerator").value(2))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.numerator").value(2))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.denominator").value(5))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.denominator").value(5))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.summary.handlingEfficiency.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.rows", hasSize(4)))
                 .andExpect(jsonPath("$.data.rows", hasSize(4)))
-                .andExpect(jsonPath("$.data.events", hasSize(5)))
+                .andExpect(jsonPath("$.data.events", hasSize(7)))
+                .andExpect(jsonPath("$.data.events[*].eventNo").value(contains(
+                        "HW-005", "HW-004", "HW-003", "HW-002", "HW-LEGACY", "HW-MH", "HW-001")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-LEGACY')].industry").value(contains(nullValue())))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-LEGACY')].deviceCode").value(contains("D-LEGACY")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-MH')].industry").value(contains(nullValue())))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-MH')].deviceCode").value(contains("D-MH")))
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(100))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(100))
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
-                .andExpect(jsonPath("$.data.rows[0].timeBucket").value(BUCKET_23))                .andExpect(jsonPath("$.data.rows[0].eventCount").value(1))
+                .andExpect(jsonPath("$.data.pagination.total").value(7))
+                .andExpect(jsonPath("$.data.rows[0].timeBucket").value(BUCKET_23))
+                .andExpect(jsonPath("$.data.rows[0].eventCount").value(2))
                 .andExpect(jsonPath("$.data.rows[0].handledCount").value(1))
                 .andExpect(jsonPath("$.data.rows[0].handledCount").value(1))
-                .andExpect(jsonPath("$.data.rows[0].handlingEfficiency.value").value("1.0000"))
+                .andExpect(jsonPath("$.data.rows[0].handlingEfficiency.value").value("0.5000"))
+                .andExpect(jsonPath("$.data.rows[0].handlingEfficiency.numerator").value(1))
+                .andExpect(jsonPath("$.data.rows[0].handlingEfficiency.denominator").value(2))
                 .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes[0]").value("D-GAS-1"))
                 .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes[0]").value("D-GAS-1"))
+                .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes").value(contains("D-GAS-1", "D-MH")))
                 .andExpect(jsonPath("$.data.rows[1].timeBucket").value(BUCKET_00))
                 .andExpect(jsonPath("$.data.rows[1].timeBucket").value(BUCKET_00))
-                .andExpect(jsonPath("$.data.rows[1].eventCount").value(2))
+                .andExpect(jsonPath("$.data.rows[1].eventCount").value(3))
+                .andExpect(jsonPath("$.data.rows[1].mapFilter.deviceCodes").value(contains("D-GAS-2", "D-LEGACY", "D-WS-1")))
                 .andExpect(jsonPath("$.data.rows[1].handledCount").value(0))
                 .andExpect(jsonPath("$.data.rows[1].handledCount").value(0))
                 .andExpect(jsonPath("$.data.rows[1].handlingEfficiency.value").value("0.0000"))
                 .andExpect(jsonPath("$.data.rows[1].handlingEfficiency.value").value("0.0000"))
                 .andExpect(jsonPath("$.data.rows[1].handlingEfficiency.state").value("AVAILABLE"))
                 .andExpect(jsonPath("$.data.rows[1].handlingEfficiency.state").value("AVAILABLE"))
@@ -157,7 +169,10 @@ class CockpitHistoryAnalysisControllerTest {
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value("未分区"))
                 .andExpect(jsonPath("$.data.filters.districtName").value("未分区"))
-                .andExpect(jsonPath("$.data.summary.eventCount").value(2));
+                .andExpect(jsonPath("$.data.summary.eventCount").value(4))
+                .andExpect(jsonPath("$.data.events[*].eventNo").value(contains("HW-005", "HW-004", "HW-LEGACY", "HW-MH")))
+                .andExpect(jsonPath("$.data.summary.handlingEfficiency.numerator").value(0))
+                .andExpect(jsonPath("$.data.summary.handlingEfficiency.denominator").value(1));
 
 
         // 不传=全域(双字段都为空,不是「未分区」)
         // 不传=全域(双字段都为空,不是「未分区」)
         mockMvc.perform(get(ENDPOINT)
         mockMvc.perform(get(ENDPOINT)
@@ -167,7 +182,7 @@ class CockpitHistoryAnalysisControllerTest {
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.district").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value(nullValue()))
                 .andExpect(jsonPath("$.data.filters.districtName").value(nullValue()))
-                .andExpect(jsonPath("$.data.summary.eventCount").value(5));
+                .andExpect(jsonPath("$.data.summary.eventCount").value(7));
     }
     }
 
 
     @Test
     @Test
@@ -207,15 +222,19 @@ class CockpitHistoryAnalysisControllerTest {
                         .param("endTime", END))
                         .param("endTime", END))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.rows[0].timeBucket").value("2026-09-01T23:00:00+08:00"))
                 .andExpect(jsonPath("$.data.rows[0].timeBucket").value("2026-09-01T23:00:00+08:00"))
-                .andExpect(jsonPath("$.data.rows[0].eventCount").value(1))
+                .andExpect(jsonPath("$.data.rows[0].eventCount").value(2))
+                .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes").value(contains("D-GAS-1", "D-MH")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-001')].eventTime").value(contains("2026-09-01T23:30:00+08:00")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-MH')].eventTime").value(contains("2026-09-01T23:59:00+08:00")))
                 .andExpect(jsonPath("$.data.rows[1].timeBucket").value("2026-09-02T00:00:00+08:00"))
                 .andExpect(jsonPath("$.data.rows[1].timeBucket").value("2026-09-02T00:00:00+08:00"))
+                .andExpect(jsonPath("$.data.rows[1].eventCount").value(3))
                 .andExpect(jsonPath("$.data.rows[2].timeBucket").value("2026-09-02T01:00:00+08:00"));
                 .andExpect(jsonPath("$.data.rows[2].timeBucket").value("2026-09-02T01:00:00+08:00"));
     }
     }
 
 
     @Test
     @Test
     void handledScopeCountsOnlyClosedStateFiveOrders() throws Exception {
     void handledScopeCountsOnlyClosedStateFiveOrders() throws Exception {
         CockpitHistoryAnalysisResponse response = service("WARNING", START, END);
         CockpitHistoryAnalysisResponse response = service("WARNING", START, END);
-        assertEquals(5, response.getSummary().getEventCount());
+        assertEquals(7, response.getSummary().getEventCount());
         assertEquals(2, response.getSummary().getHandledCount());
         assertEquals(2, response.getSummary().getHandledCount());
         // 汇总处置率=状态 5 ÷ 状态 0–6 工单数(决策票 06)→ 2/5。
         // 汇总处置率=状态 5 ÷ 状态 0–6 工单数(决策票 06)→ 2/5。
         assertEquals("0.4000", response.getSummary().getHandlingEfficiency().getValue().toPlainString());
         assertEquals("0.4000", response.getSummary().getHandlingEfficiency().getValue().toPlainString());
@@ -276,7 +295,13 @@ class CockpitHistoryAnalysisControllerTest {
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.summary.eventCount").value(2))
                 .andExpect(jsonPath("$.data.summary.eventCount").value(2))
                 .andExpect(jsonPath("$.data.summary.handledCount").value(1))
                 .andExpect(jsonPath("$.data.summary.handledCount").value(1))
-                .andExpect(jsonPath("$.data.events", hasSize(2)));
+                .andExpect(jsonPath("$.data.events", hasSize(2)))
+                .andExpect(jsonPath("$.data.events[*].eventNo").value(contains("HW-002", "HW-001")))
+                .andExpect(jsonPath("$.data.events[*].industry").value(contains("GAS", "GAS")))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-LEGACY')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-MH')]", hasSize(0)))
+                .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes").value(contains("D-GAS-1")))
+                .andExpect(jsonPath("$.data.rows[1].mapFilter.deviceCodes").value(contains("D-GAS-2")));
     }
     }
 
 
     @Test
     @Test
@@ -291,16 +316,19 @@ class CockpitHistoryAnalysisControllerTest {
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.page").value(1))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(2))
                 .andExpect(jsonPath("$.data.pagination.pageSize").value(2))
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
-                .andExpect(jsonPath("$.data.pagination.totalPages").value(3))
+                .andExpect(jsonPath("$.data.pagination.total").value(7))
+                .andExpect(jsonPath("$.data.pagination.totalPages").value(4))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(true))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(true))
                 .andExpect(jsonPath("$.data.events", hasSize(2)))
                 .andExpect(jsonPath("$.data.events", hasSize(2)))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("HW-005"))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("HW-005"))
                 .andExpect(jsonPath("$.data.events[0].eventTime").value("2026-09-02T01:50:00+08:00"))
                 .andExpect(jsonPath("$.data.events[0].eventTime").value("2026-09-02T01:50:00+08:00"))
-                .andExpect(jsonPath("$.data.events[0].levelColor").value("RED"))
+                .andExpect(jsonPath("$.data.events[?(@.eventNo == 'HW-005')].levelColor").value(contains("RED")))
                 .andExpect(jsonPath("$.data.events[0].deviceCode").value("D-WS-2"))
                 .andExpect(jsonPath("$.data.events[0].deviceCode").value("D-WS-2"))
                 .andExpect(jsonPath("$.data.events[0].industry").value("WATER_SUPPLY"))
                 .andExpect(jsonPath("$.data.events[0].industry").value("WATER_SUPPLY"))
-                .andExpect(jsonPath("$.data.events[1].eventNo").value("HW-004"));
+                .andExpect(jsonPath("$.data.events[1].eventNo").value("HW-004"))
+                // 小时桶/map 范围不由当前页反推;未在首屏的两个未知行仍参与桶统计。
+                .andExpect(jsonPath("$.data.rows[0].mapFilter.deviceCodes").value(contains("D-GAS-1", "D-MH")))
+                .andExpect(jsonPath("$.data.rows[1].mapFilter.deviceCodes").value(contains("D-GAS-2", "D-LEGACY", "D-WS-1")));
 
 
         mockMvc.perform(get(ENDPOINT)
         mockMvc.perform(get(ENDPOINT)
                         .param("eventFamily", "WARNING")
                         .param("eventFamily", "WARNING")
@@ -309,8 +337,24 @@ class CockpitHistoryAnalysisControllerTest {
                         .param("page", "3")
                         .param("page", "3")
                         .param("pageSize", "2"))
                         .param("pageSize", "2"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.events", hasSize(2)))
+                .andExpect(jsonPath("$.data.events[0].eventNo").value("HW-LEGACY"))
+                .andExpect(jsonPath("$.data.events[0].industry").value(nullValue()))
+                .andExpect(jsonPath("$.data.events[1].eventNo").value("HW-MH"))
+                .andExpect(jsonPath("$.data.events[1].industry").value(nullValue()))
+                .andExpect(jsonPath("$.data.pagination.total").value(7))
+                .andExpect(jsonPath("$.data.pagination.hasMore").value(true));
+
+        mockMvc.perform(get(ENDPOINT)
+                        .param("eventFamily", "WARNING")
+                        .param("startTime", START)
+                        .param("endTime", END)
+                        .param("page", "4")
+                        .param("pageSize", "2"))
+                .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.events", hasSize(1)))
                 .andExpect(jsonPath("$.data.events", hasSize(1)))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("HW-001"))
                 .andExpect(jsonPath("$.data.events[0].eventNo").value("HW-001"))
+                .andExpect(jsonPath("$.data.pagination.total").value(7))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
 
 
         // 越界页:事件为空但仍返回成功信封与真实 total(不由当前页反推)。
         // 越界页:事件为空但仍返回成功信封与真实 total(不由当前页反推)。
@@ -322,7 +366,7 @@ class CockpitHistoryAnalysisControllerTest {
                         .param("pageSize", "2"))
                         .param("pageSize", "2"))
                 .andExpect(status().isOk())
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.data.events", hasSize(0)))
                 .andExpect(jsonPath("$.data.events", hasSize(0)))
-                .andExpect(jsonPath("$.data.pagination.total").value(5))
+                .andExpect(jsonPath("$.data.pagination.total").value(7))
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
                 .andExpect(jsonPath("$.data.pagination.hasMore").value(false));
     }
     }
 
 

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

@@ -327,6 +327,22 @@ class CockpitOverviewModulesServiceTest {
         assertEquals(1, response.getByLevel().get(1).getCount());
         assertEquals(1, response.getByLevel().get(1).getCount());
     }
     }
 
 
+    @Test
+    void warningTypeRankingShowsPlaceholderCodeAsChineseName() {
+        // mapper 把空 / NULL 类型归成 UNKNOWN(否则空行会被丢弃、行之和小于「共 XX 起」)。
+        // 这个占位码不能直接上界面 —— 界面上只看得到中文。
+        when(adapter.loadWarningStudy(any(), any(), any())).thenReturn(warnings(0, 0, 4,
+                Collections.emptyList(),
+                Arrays.asList(typeCount("WARN-A", 3), typeCount("UNKNOWN", 1)),
+                names("WARN-A", "压力预警"), Collections.emptyMap()));
+
+        CockpitOverviewWarningStudyResponse.TypeRanking ranking =
+                service.loadWarningStudy("warning-007").getTypeRanking();
+
+        assertEquals("未分类", ranking.getTop().get(1).getName(), "占位码必须给中文名,不在界面露码值");
+        assertEquals("UNKNOWN", ranking.getTop().get(1).getCode(), "码值仍如实下发(点击筛选需要它)");
+    }
+
     @Test
     @Test
     void warningTypeRankingTieBreaksByCodeAndDegradesUnknownName() {
     void warningTypeRankingTieBreaksByCodeAndDegradesUnknownName() {
         when(adapter.loadWarningStudy(any(), any(), any())).thenReturn(warnings(0, 0, 10,
         when(adapter.loadWarningStudy(any(), any(), any())).thenReturn(warnings(0, 0, 10,

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

@@ -0,0 +1,576 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.base.video.VideoSession;
+import com.zksy.cockpit.video.CockpitVideoService;
+import com.zksy.common.core.redis.RedisCache;
+import com.zksy.framework.config.ResourcesConfig;
+import com.zksy.framework.config.SecurityConfig;
+import com.zksy.framework.config.properties.PermitAllUrlProperties;
+import com.zksy.framework.security.filter.JwtAuthenticationTokenFilter;
+import com.zksy.framework.security.handle.AuthenticationEntryPointImpl;
+import com.zksy.framework.security.handle.CockpitAuthenticationEntryPoint;
+import com.zksy.framework.security.handle.LogoutSuccessHandlerImpl;
+import com.zksy.framework.web.exception.GlobalExceptionHandler;
+import com.zksy.framework.web.service.PermissionService;
+import com.zksy.framework.web.service.TokenService;
+import com.zksy.web.controller.video.VideoDeviceController;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import com.zksy.common.exception.ServiceException;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+
+import javax.servlet.Filter;
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** HTTP seam with the real security/JWT chain and both business services.
+ * Only DB, Redis storage and media transport are replaced. No server, scheduler,
+ * database connection or media/network request is started by this fixture.
+ */
+class CockpitVideoControllerTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String CODE = " CN/摄像机+%2F 001 ";
+    private static final String ID = "internal-ledger-id";
+    private static final String GB = "34020000002000000001";
+    private static final String CHANNEL = "34020000001320000001";
+    private static final String START = "/api/play/start/" + GB + "/" + CHANNEL;
+    private static final String STOP = "/api/play/stop/" + GB + "/" + CHANNEL;
+    private static final String URL = "https://media.invalid/live.flv";
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private EquipmentBaseMapper devices;
+    private EquipmentVideoBindingMapper bindings;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient collector;
+    private EquipmentBase equipment;
+    private VideoDeviceRecord binding;
+
+    @BeforeEach
+    void setUp() {
+        SecurityContextHolder.clearContext();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-test", Map.of(
+                "token.header", "Authorization", "token.secret", "offline-video-contract-only-secret-not-for-production", "token.expireTime", "60")));
+        context.register(HttpConfiguration.class);
+        context.refresh();
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        devices = context.getBean(EquipmentBaseMapper.class);
+        bindings = context.getBean(EquipmentVideoBindingMapper.class);
+        sessions = context.getBean(VideoSessionMapper.class);
+        collector = context.getBean(VideoCollectorClient.class);
+        equipment = new EquipmentBase();
+        equipment.setEquipmentId(ID);
+        equipment.setEquipmentCode(CODE);
+        equipment.setEquipmentName("测试摄像机");
+        equipment.setEquipmentTypeId(20);
+        when(devices.selectList(any())).thenReturn(List.of(equipment));
+        binding = new VideoDeviceRecord();
+        BeanUtils.copyProperties(equipment, binding);
+        binding.setVideoId(ID);
+        binding.setDeviceCode(CODE);
+        binding.setDeviceName("测试摄像机");
+        binding.setSourceType("GB28181");
+        binding.setGbDeviceId(GB);
+        binding.setGbChannelId(CHANNEL);
+        when(bindings.find(ID)).thenReturn(binding);
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL));
+        Map<String, VideoSession> rows = new ConcurrentHashMap<>();
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = call.getArgument(0);
+            rows.put(row.getSessionId(), copy(row));
+            return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(call -> copy(rows.get(call.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = call.getArgument(0);
+            return rows.replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        // Literal single-viewer DB fixture; no copy of shared-count business logic.
+        when(sessions.selectCount(any())).thenReturn(0L);
+    }
+
+    @AfterEach
+    void tearDown() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    private static final String RECORD_QUERY = "/api/gb_record/query";
+
+    @Test
+    void anonymousHistoryListsOnlyRealReturnedRecordingsForTheRequestedWindow() throws Exception {
+        when(collector.get(RECORD_QUERY, Map.of("deviceId", GB, "channelId", CHANNEL,
+                "startTime", "2026-11-10 00:00:00", "endTime", "2026-11-10 12:00:00", "type", "all")))
+                .thenReturn(Map.of("recordList", List.of(Map.of("name", "通道01", "startTime", "2026-11-10 01:00:00",
+                        "endTime", "2026-11-10 02:00:00", "type", "time"))));
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-10 00:00:00").param("endTime", "2026-11-10 12:00:00"))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.empty").value(false))
+                .andExpect(jsonPath("$.data.records[0].name").value("通道01"))
+                .andExpect(jsonPath("$.data.records[0].startTime").value("2026-11-10 01:00:00"))
+                .andExpect(jsonPath("$.data.records[0].endTime").value("2026-11-10 02:00:00"))
+                .andExpect(jsonPath("$.data.records[0].type").value("time"));
+    }
+
+    @Test
+    void emptyRecordingWindowIsAnAnswerNotAFailure() throws Exception {
+        when(collector.get(RECORD_QUERY, Map.of("deviceId", GB, "channelId", CHANNEL,
+                "startTime", "2026-11-10 00:00:00", "endTime", "2026-11-10 12:00:00", "type", "all")))
+                .thenReturn(Map.of("recordList", List.of()));
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-10 00:00:00").param("endTime", "2026-11-10 12:00:00"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.empty").value(true))
+                .andExpect(jsonPath("$.data.records").isEmpty());
+    }
+
+    @Test
+    void playbackControlReachesTheOwnedSessionAndRejectsInvalidRates() throws Exception {
+        when(collector.post(eq("/api/playback/start"), any())).thenReturn(Map.of());
+        when(collector.get(eq("/api/playback/start"), any())).thenReturn(Map.of("stream", "stream_pb", "native", true,
+                "flv", "https://media.invalid/pb.flv"));
+        JSONObject owned = JSON.parseObject(mvc.perform(post(ROOT + "/playback").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("deviceCode", CODE,
+                                "startTime", "2026-11-10 01:00:00", "endTime", "2026-11-10 02:00:00"))))
+                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()).getJSONObject("data");
+        String token = owned.getString("sessionToken");
+        String id = owned.getString("sessionId");
+        // A confirmed capability is forwarded to the reused media seam.
+        mvc.perform(post(ROOT + "/sessions/" + id + "/control").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("sessionToken", token, "action", "pause"))))
+                .andExpect(status().isOk());
+        // An unsupported rate is refused before any media call.
+        mvc.perform(post(ROOT + "/sessions/" + id + "/control").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("sessionToken", token, "action", "speed", "value", 3))))
+                .andExpect(status().isServiceUnavailable());
+        // Another viewer's token cannot control this session.
+        mvc.perform(post(ROOT + "/sessions/" + id + "/control").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("sessionToken", "A".repeat(43), "action", "pause"))))
+                .andExpect(status().isForbidden());
+    }
+
+    @Test
+    void aFailedRecordingQueryIsItsOwnCategoryNotAGenericVideoRead() throws Exception {
+        when(collector.get(RECORD_QUERY, Map.of("deviceId", GB, "channelId", CHANNEL,
+                "startTime", "2026-11-10 00:00:00", "endTime", "2026-11-10 12:00:00", "type", "all")))
+                .thenThrow(new ServiceException("查询录像失败"));
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-10 00:00:00").param("endTime", "2026-11-10 12:00:00"))
+                .andExpect(status().isBadGateway())
+                .andExpect(jsonPath("$.data.category").value("VIDEO_RECORDS_FAILED"));
+    }
+
+    @Test
+    void recordingRangeOverSevenDaysIsRejectedBeforeTouchingTheDevice() throws Exception {
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-01 00:00:00").param("endTime", "2026-11-10 00:00:00"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void playbackReusesTheAnonymousSeamAndPublishesOnlyTheReturnedMedia() throws Exception {
+        when(collector.get(eq("/api/playback/start"), any())).thenReturn(Map.of("stream", "stream_pb", "native", true,
+                "rtcs", "https://media.invalid/index/api/webrtc?app=rtp&stream=stream_pb&type=play",
+                "flv", "https://media.invalid/pb.flv", "secret", "internal-secret", "proxyKey", "internal-key"));
+        mvc.perform(post(ROOT + "/playback").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("deviceCode", CODE,
+                                "startTime", "2026-11-10 01:00:00", "endTime", "2026-11-10 02:00:00"))))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.mode").value("PLAYBACK"))
+                .andExpect(jsonPath("$.data.startTime").value("2026-11-10 01:00:00"))
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media.webrtc").exists())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("internal-key"))));
+    }
+
+    @Test
+    void aBusyChannelReportsOccupancyInsteadOfStoppingTheExistingPlayback() throws Exception {
+        // The single-active-playback rule is enforced by the reused session store, not by the media adapter.
+        when(sessions.selectCount(any())).thenReturn(1L);
+        mvc.perform(post(ROOT + "/playback").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("deviceCode", CODE,
+                                "startTime", "2026-11-10 01:00:00", "endTime", "2026-11-10 02:00:00"))))
+                .andExpect(status().isConflict())
+                .andExpect(jsonPath("$.data.category").value("PLAYBACK_OCCUPIED"));
+        // Never stop somebody else's playback just because this request lost the race.
+        verify(collector, never()).get(STOP, Map.of());
+        verify(collector, never()).get(eq("/api/playback/start"), any());
+    }
+
+    @Test
+    void anonymousDeviceLookupKeepsExactBusinessCodeAndPublishesOnlyConfirmedLiveCapability() throws Exception {
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE).header("X-Request-Id", "video-lookup-1"))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.deviceName").value("测试摄像机"))
+                .andExpect(jsonPath("$.data.typeCode").value("20"))
+                .andExpect(jsonPath("$.data.bound").value(true))
+                .andExpect(jsonPath("$.data.capabilities.live").value(true))
+                // Records and playback follow the GB28181 binding; control stays grey until a real device confirms it.
+                .andExpect(jsonPath("$.data.capabilities.records").value(true))
+                .andExpect(jsonPath("$.data.capabilities.playback").value(true))
+                .andExpect(jsonPath("$.data.capabilities.playbackControl").value(false))
+                .andExpect(jsonPath("$.data.capabilities.ptz").value(false))
+                .andExpect(jsonPath("$.data.capabilities.ptzStopGuaranteed").value(false))
+                .andExpect(jsonPath("$.data.requestId").value("video-lookup-1"))
+                .andExpect(jsonPath("$.data.serverTime").value("2026-11-10T16:00:00+08:00"))
+                .andExpect(jsonPath("$.data.equipmentId").doesNotExist())
+                .andExpect(jsonPath("$.data.videoId").doesNotExist())
+                .andExpect(jsonPath("$.data.gbChannelId").doesNotExist());
+        verifyNoInteractions(collector, sessions);
+    }
+
+    @Test
+    void anonymousViewerStartsMaintainsAndIdempotentlyReleasesOnlyItsOwnSession() throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL,
+                "rtcs", "https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play",
+                "native", true, "secret", "internal-secret", "proxyKey", "internal-key"));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.mode").value("LIVE"))
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media.flv").value(URL))
+                .andExpect(jsonPath("$.data.media.webrtc").value("https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play"))
+                .andExpect(jsonPath("$.data.media.native").value(false))
+                .andExpect(jsonPath("$.data.secret").doesNotExist())
+                .andExpect(jsonPath("$.data.stream").doesNotExist())
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.media.secret").doesNotExist())
+                .andExpect(header().string("Cache-Control", "no-store"))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
+                .getJSONObject("data");
+        clearInvocations(collector);
+        session(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden())
+                .andExpect(jsonPath("$.data.category").value("SESSION_FORBIDDEN"));
+        verifyNoInteractions(collector);
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"))
+                .andExpect(jsonPath("$.data.sessionToken").doesNotExist());
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector, times(1)).get(STOP, Map.of());
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isGone())
+                .andExpect(jsonPath("$.data.category").value("SESSION_EXPIRED"));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"GET,/live", "GET,/sessions/example/stop", "GET,/sessions/example/heartbeat",
+            "GET,/devices/remove", "GET,/record", "POST,/device", "PUT,/live", "DELETE,/live",
+            "POST,/sessions/example/playback", "POST,/ptz", "POST,/playback/control", "POST,/devices",
+            "POST,/sessions/example/nested/stop", "POST,/live/nested"})
+    void unpublishedVideoMethodAndPathPairsRequireAuthentication(String method, String path) throws Exception {
+        mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), ROOT + path))
+                .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value(401));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"/devices/internal/live", "/devices/internal/playback", "/devices",
+            "/sessions/another/heartbeat", "/sessions/another/stop", "/sessions/another/control"})
+    void legacyVideoEndpointsStillRequireBusinessAuthentication(String path) throws Exception {
+        mvc.perform(post("/api/video" + path)).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"CN/摄像机+%2F 001", " CN/摄像机+%2f 001 ", " CN/摄像机+/ 001 ", "internal-ledger-id"})
+    void neverNormalizesOrDecodesBusinessCodeAgain(String differentCode) throws Exception {
+        mvc.perform(get(ROOT + "/device").param("deviceCode", differentCode))
+                .andExpect(status().isNotFound()).andExpect(jsonPath("$.data.category").value("DEVICE_NOT_FOUND"));
+        verifyNoInteractions(bindings, sessions, collector);
+    }
+
+    @Test
+    void ordinaryDeviceCannotGainVideoFromItsNameOrALeftoverBinding() throws Exception {
+        equipment.setEquipmentTypeId(12);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.typeCode").value("12"))
+                .andExpect(jsonPath("$.data.bound").value(false))
+                .andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict()).andExpect(jsonPath("$.data.category").value("VIDEO_UNAVAILABLE"));
+        verifyNoInteractions(bindings, sessions, collector);
+    }
+
+    @Test
+    void unboundCameraIsGreyWithoutConsultingMediaOrCollectionRecords() throws Exception {
+        when(bindings.find(ID)).thenReturn(null);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.bound").value(false)).andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(sessions, collector);
+    }
+
+    @Test
+    void unknownSourceAndIncompleteGbBindingRemainGrey() throws Exception {
+        binding.setSourceType("unknown");
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.bound").value(true)).andExpect(jsonPath("$.data.capabilities.live").value(false));
+        binding.setSourceType("GB28181");
+        binding.setGbChannelId(null);
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(sessions, collector);
+    }
+
+    @Test
+    void ambiguousOrFailedLedgerQueriesDoNotGuessADeviceOrLeakDatabaseDetails() throws Exception {
+        when(devices.selectList(any())).thenReturn(List.of(equipment, equipment));
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("VIDEO_READ_FAILED"));
+        when(devices.selectList(any())).thenThrow(new IllegalStateException("jdbc password=do-not-publish"));
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("do-not-publish"))));
+        verifyNoInteractions(bindings, collector, sessions);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"{}", "{bad-json", "{\"deviceCode\":123}", "{\"deviceCode\":\"\"}",
+            "{\"deviceCode\":\"x\",\"userId\":1}"})
+    void malformedLiveRequestsUseThePublicInvalidRequestEnvelope(String body) throws Exception {
+        mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON).content(body))
+                .andExpect(status().isBadRequest()).andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+        verifyNoInteractions(devices, bindings, collector, sessions);
+    }
+
+    @Test
+    void missingDeviceQueryIsBadRequestRatherThanAnInternalError() throws Exception {
+        mvc.perform(get(ROOT + "/device")).andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void manualNativeVideoIsExplicitAndNeverLeaksItsLedgerFields() throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl("https://media.invalid/live.mp4");
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.capabilities.live").value(true));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.media.url").value("https://media.invalid/live.mp4"))
+                .andExpect(jsonPath("$.data.media.native").value(true))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verifyNoInteractions(collector);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"https://user:password@media.invalid/live.mp4", "https://media.invalid/live.mp4?secret=hidden",
+            "https://media.invalid/live.flv", "https://media.invalid/error.html", "ws://media.invalid/live.flv"})
+    void manualSourcesThatCannotBePublicNativeMediaAreGrey(String url) throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl(url);
+        mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.capabilities.live").value(false));
+        live().andExpect(status().isConflict());
+        verifyNoInteractions(collector, sessions);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"https://user:password@media.invalid/live.flv", "https://media.invalid/live.flv?secret=hidden",
+            "https://media.invalid/live.flv?%73ecret=hidden", "https://media.invalid/live.flv?internal-token=hidden",
+            "https://media.invalid/live.flv?proxyKey=hidden", "https://media.invalid/live.flv?password=hidden"})
+    void unsafeMediaAddressTriggersOwnSessionCleanupInsteadOfPublishingCredentials(String url) throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", url));
+        live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void failedStopIsUnconfirmedAndTheSameOwnerCanRetry() throws Exception {
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("secret=hidden transport detail"));
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
+                .andExpect(jsonPath("$.data.message").value("清理未确认,请等待回收"));
+        session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk());
+        doReturn(Map.of()).when(collector).get(STOP, Map.of());
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+    }
+
+    @Test
+    void unsafeMediaAndFailedCompensationDoNotClaimThatResourcesWereStopped() throws Exception {
+        when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL + "?token=hidden"));
+        when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("password=hidden"));
+        live().andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+    }
+
+    @Test
+    void twoAnonymousViewersDoNotShareOwnershipOrStopEachOthersLiveStream() throws Exception {
+        when(sessions.selectCount(any())).thenReturn(0L, 1L, 1L, 0L);
+        JSONObject first = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject second = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
+                .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        org.junit.jupiter.api.Assertions.assertNotEquals(first.getString("sessionToken"), second.getString("sessionToken"));
+        session(first, "stop", second.getString("sessionToken")).andExpect(status().isForbidden());
+        clearInvocations(collector);
+        session(first, "stop", first.getString("sessionToken")).andExpect(status().isOk());
+        verifyNoInteractions(collector);
+        session(second, "heartbeat", second.getString("sessionToken")).andExpect(status().isOk());
+        session(second, "stop", second.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void upstreamFailureIsSanitizedAndNeverReportedAsAnEmptyOrSuccessfulStream() throws Exception {
+        when(collector.get(START, Map.of())).thenThrow(new ServiceException("password=hidden upstream failure"));
+        live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
+        verify(collector).get(STOP, Map.of());
+    }
+
+    @Test
+    void manualRtspCredentialsStayInsideProxyAndOnlyPublicWebRtcIsReturned() throws Exception {
+        binding.setSourceType("MANUAL");
+        binding.setVideoUrl("rtsp://user:private-password@camera.invalid/live");
+        when(collector.post("/internal/video/manual/start", Map.of("id", ID, "url", binding.getVideoUrl())))
+                .thenReturn(Map.of("stream", "proxy_stream", "proxyKey", "private-proxy-key", "flv", URL,
+                        "webrtc", "https://media.invalid/index/api/webrtc?app=proxy&stream=proxy_stream&type=play"));
+        JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.media.native").value(false))
+                .andExpect(jsonPath("$.data.media.webrtc").isNotEmpty())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("private-"))))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
+        verify(collector).post("/internal/video/manual/stop", Map.of("key", "private-proxy-key"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"/api/cockpit/v1/security-contract-probe", "/api/cockpit/v1/security-contract-probe/nested"})
+    void existingCockpitReadPolicyAllowsAnonymousGetButNotPost(String path) throws Exception {
+        mvc.perform(get(path)).andExpect(status().isOk())
+                .andExpect(jsonPath("$.reached").value("security-policy-probe"))
+                .andExpect(jsonPath("$.method").value("GET"));
+        mvc.perform(post(path)).andExpect(status().isUnauthorized())
+                .andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.data.category").value("UNAUTHORIZED"))
+                .andExpect(jsonPath("$.reached").doesNotExist());
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest
+    @CsvSource({"GET,/api/security-contract-probe", "POST,/api/security-contract-probe",
+            "GET,/ws/deviceStatus/nested", "POST,/ws/deviceStatus/nested"})
+    void theDefaultRuleStillRejectsAnonymousRequestsOutsideExplicitExceptions(String method, String path)
+            throws Exception {
+        mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), path))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.reached").doesNotExist());
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @Test
+    void existingWebSocketHandshakePathStillPassesTheRealAuthenticationChain() throws Exception {
+        // This observes authorization before an Upgrade endpoint, not a real socket handshake.
+        mvc.perform(get("/ws/deviceStatus").header("Connection", "Upgrade").header("Upgrade", "websocket")
+                .header("Sec-WebSocket-Version", "13").header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.reached").value("security-policy-probe"))
+                .andExpect(jsonPath("$.method").value("GET"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    private ResultActions live() throws Exception {
+        return mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))));
+    }
+
+    private ResultActions session(JSONObject viewer, String action, String token) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) return null;
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(source, copy);
+        return copy;
+    }
+
+    /** Replaces the old source-text matcher/count assertions with actual filter-chain outcomes.
+     * The same endpoint accepts GET and POST, so denied requests cannot pass by falling through to 404.
+     * Only the downstream HTTP handler is a fixture; SecurityConfig and all authentication filters are real.
+     */
+    @org.springframework.web.bind.annotation.RestController
+    static class SecurityPolicyProbe {
+        @org.springframework.web.bind.annotation.RequestMapping({"/api/cockpit/v1/security-contract-probe",
+                "/api/cockpit/v1/security-contract-probe/nested", "/api/security-contract-probe",
+                "/ws/deviceStatus", "/ws/deviceStatus/nested"})
+        Map<String, String> reached(javax.servlet.http.HttpServletRequest request) {
+            return Map.of("reached", "security-policy-probe", "method", request.getMethod());
+        }
+    }
+
+    @Configuration
+    @EnableWebMvc
+    @EnableWebSecurity
+    @Import({SecurityConfig.class, PermitAllUrlProperties.class, PermissionService.class,
+            JwtAuthenticationTokenFilter.class, TokenService.class, RedisCache.class,
+            AuthenticationEntryPointImpl.class, CockpitAuthenticationEntryPoint.class,
+            LogoutSuccessHandlerImpl.class, GlobalExceptionHandler.class,
+            CockpitVideoController.class, CockpitVideoService.class, VideoDeviceController.class, SecurityPolicyProbe.class})
+    static class HttpConfiguration {
+        @Bean Clock clock() { return Clock.fixed(Instant.parse("2026-11-10T08:00:00Z"), ZoneOffset.UTC); }
+        @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(); }
+        @Bean CorsFilter corsFilter() { return new ResourcesConfig().corsFilter(); }
+        @Bean EquipmentBaseMapper devices() { return mock(EquipmentBaseMapper.class); }
+        @Bean EquipmentVideoBindingMapper bindings() { return mock(EquipmentVideoBindingMapper.class); }
+        @Bean VideoSessionMapper sessions() { return mock(VideoSessionMapper.class); }
+        @Bean VideoCollectorClient collector() { return mock(VideoCollectorClient.class); }
+        @Bean RedisTemplate<String, Object> redisTemplate() { return mock(RedisTemplate.class); }
+        @Bean VideoDeviceService videoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector,
+                VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings, Clock clock) {
+            return new VideoDeviceService(devices, collector, sessions, mock(EquipmentBaseService.class), bindings, clock);
+        }
+    }
+}

+ 5 - 1
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderAssociationContractTest.java

@@ -77,6 +77,8 @@ class CockpitWorkOrderAssociationContractTest {
         equipment.setEquipmentCode(DEVICE_CODE);
         equipment.setEquipmentCode(DEVICE_CODE);
         when(equipmentMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(equipment);
         when(equipmentMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(equipment);
         when(equipmentMapper.selectById(EQUIPMENT_ID)).thenReturn(equipment);
         when(equipmentMapper.selectById(EQUIPMENT_ID)).thenReturn(equipment);
+        // 详情字段按整页批量取设备(一次 selectBatchIds),设备编码/名称/位置同源。
+        when(equipmentMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(equipment));
 
 
         linkedOrder = order(279L, ORDER_CODE);
         linkedOrder = order(279L, ORDER_CODE);
         linkedAlarm = new AlarmData();
         linkedAlarm = new AlarmData();
@@ -96,7 +98,9 @@ class CockpitWorkOrderAssociationContractTest {
 
 
         BusinessCockpitWorkOrderReadAdapter adapter = new BusinessCockpitWorkOrderReadAdapter(
         BusinessCockpitWorkOrderReadAdapter adapter = new BusinessCockpitWorkOrderReadAdapter(
                 workOrderService, mock(EarlyWarningService.class), mock(AlarmWarningRelMapper.class),
                 workOrderService, mock(EarlyWarningService.class), mock(AlarmWarningRelMapper.class),
-                alarmDataService, equipmentMapper, mock(com.zksy.base.service.EquipmentTypeService.class));
+                alarmDataService, equipmentMapper, mock(com.zksy.base.service.EquipmentTypeService.class),
+                mock(com.zksy.system.mapper.SysDictDataMapper.class),
+                mock(com.zksy.system.service.ISysUserService.class));
         CockpitWorkOrderReadService service = new CockpitWorkOrderReadService(
         CockpitWorkOrderReadService service = new CockpitWorkOrderReadService(
                 adapter, Clock.fixed(Instant.parse("2026-10-10T07:11:30Z"), ZoneOffset.UTC));
                 adapter, Clock.fixed(Instant.parse("2026-10-10T07:11:30Z"), ZoneOffset.UTC));
         mockMvc = MockMvcBuilders.standaloneSetup(new CockpitWorkOrderReadController(service)).build();
         mockMvc = MockMvcBuilders.standaloneSetup(new CockpitWorkOrderReadController(service)).build();

+ 5 - 1
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitWorkOrderListContractTest.java

@@ -78,6 +78,8 @@ class CockpitWorkOrderListContractTest {
         equipment.setEquipmentId("equipment-id");
         equipment.setEquipmentId("equipment-id");
         equipment.setEquipmentCode(DEVICE_CODE);
         equipment.setEquipmentCode(DEVICE_CODE);
         when(equipmentMapper.selectById("equipment-id")).thenReturn(equipment);
         when(equipmentMapper.selectById("equipment-id")).thenReturn(equipment);
+        // 详情字段按整页批量取设备(一次 selectBatchIds),不逐条回查。
+        when(equipmentMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(equipment));
 
 
         WorkOrder order = new WorkOrder();
         WorkOrder order = new WorkOrder();
         order.setOrderId(279L);
         order.setOrderId(279L);
@@ -105,7 +107,9 @@ class CockpitWorkOrderListContractTest {
                 equipmentType(11, 3)));
                 equipmentType(11, 3)));
         BusinessCockpitWorkOrderReadAdapter adapter = new BusinessCockpitWorkOrderReadAdapter(
         BusinessCockpitWorkOrderReadAdapter adapter = new BusinessCockpitWorkOrderReadAdapter(
                 workOrderService, mock(EarlyWarningService.class), mock(AlarmWarningRelMapper.class),
                 workOrderService, mock(EarlyWarningService.class), mock(AlarmWarningRelMapper.class),
-                alarmDataService, equipmentMapper, equipmentTypeService);
+                alarmDataService, equipmentMapper, equipmentTypeService,
+                mock(com.zksy.system.mapper.SysDictDataMapper.class),
+                mock(com.zksy.system.service.ISysUserService.class));
         CockpitWorkOrderReadService service = new CockpitWorkOrderReadService(
         CockpitWorkOrderReadService service = new CockpitWorkOrderReadService(
                 adapter, Clock.fixed(Instant.parse("2026-10-10T07:11:30Z"), ZoneOffset.UTC));
                 adapter, Clock.fixed(Instant.parse("2026-10-10T07:11:30Z"), ZoneOffset.UTC));
         mockMvc = MockMvcBuilders.standaloneSetup(new CockpitWorkOrderReadController(service)).build();
         mockMvc = MockMvcBuilders.standaloneSetup(new CockpitWorkOrderReadController(service)).build();

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

@@ -0,0 +1,345 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.transaction.support.AbstractPlatformTransactionManager;
+import org.springframework.transaction.support.DefaultTransactionStatus;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+import javax.servlet.Filter;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** Prepared lifecycle at HTTP + real security/service/transaction seams.
+ * DB rows/commit outcome and media transport are adapters; no shared-count algorithm is copied here.
+ */
+class VideoPreparedSessionTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String CODE = "摄像机/ PREPARED+01";
+    private static final String VIDEO = "prepared-ledger-id";
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient media;
+    private RowTransactions transactions;
+    private VideoSessionMapper sqlQueries;
+    private org.springframework.jdbc.core.JdbcTemplate queryStorage;
+
+    @BeforeEach void setUp() throws Exception {
+        SecurityContextHolder.clearContext();
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("prepared-test", Map.of(
+                "token.header", "Authorization", "token.secret", "prepared-offline-contract-not-a-production-secret", "token.expireTime", "60")));
+        context.register(ConfigurationUnderTest.class);
+        context.refresh();
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        sessions = context.getBean(VideoSessionMapper.class);
+        media = context.getBean(VideoCollectorClient.class);
+        transactions = context.getBean(RowTransactions.class);
+        VideoPreparedSqlTransactionTest.SqlConfiguration sqlFixture = new VideoPreparedSqlTransactionTest.SqlConfiguration();
+        javax.sql.DataSource ds = sqlFixture.dataSource();
+        queryStorage = new org.springframework.jdbc.core.JdbcTemplate(ds);
+        VideoPreparedSqlTransactionTest.createSchema(queryStorage);
+        sqlQueries = sqlFixture.sqlSessions(ds);
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("准备态摄像机"); device.setEquipmentTypeId(20);
+        when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
+        VideoDeviceRecord binding = new VideoDeviceRecord(); BeanUtils.copyProperties(device, binding);
+        binding.setVideoId(VIDEO); binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001"); binding.setGbChannelId("34020000001320000001");
+        when(context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO)).thenReturn(binding);
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "identity must be persisted in a transaction");
+            VideoSession row = call.getArgument(0);
+            transactions.rows().put(row.getSessionId(), copy(row)); return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(call -> copy(transactions.rows().get(call.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = call.getArgument(0);
+            return transactions.rows().replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        when(sessions.lockVideo(VIDEO)).thenAnswer(call -> {
+            assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "device lock requires a short DB transaction");
+            return VIDEO;
+        });
+        // Execute the complete production SQL, including field names/operators/NULL/IN/NE/count.
+        // Only row commit outcomes are substituted here; the companion SQL test uses real JDBC commits too.
+        when(sessions.selectList(any())).thenAnswer(call -> {
+            refreshQueryStorage(); return sqlQueries.selectList(call.getArgument(0));
+        });
+        when(sessions.selectCount(any())).thenAnswer(call -> {
+            refreshQueryStorage(); return sqlQueries.selectCount(call.getArgument(0));
+        });
+    }
+
+    @AfterEach void close() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    @Test void prepareCommitsKnownOwnershipBeforeAnyMediaAndStoppedIdentityCannotStartLater() throws Exception {
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.status").value("PREPARED"))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.sessionId").isNotEmpty())
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaGeneration").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("PREPARED"));
+        action(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden());
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        verifyNoInteractions(media);
+    }
+
+    @Test void knownIdentityStartsAndStopsOneExactGenerationOutsideSqlTransactions() throws Exception {
+        java.util.concurrent.atomic.AtomicReference<Map<String,Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "never hold a DB transaction while starting media");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(Map.of("type", "GB28181", "videoId", VIDEO, "deviceId", "34020000002000000001",
+                    "channelId", "34020000001320000001"), request.get("source"));
+            assertEquals(java.time.Instant.parse("2026-11-10T08:00:30Z").toEpochMilli(), request.get("startDeadline"));
+            assertTrue(request.get("generation") instanceof String);
+            assertNotNull(java.util.UUID.fromString((String) request.get("generation")));
+            started.set(new LinkedHashMap<>(request));
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv", "secret", "internal-secret"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "status must not hold a SQL lock");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(started.get().get("generation"), request.get("generation"));
+            assertEquals(started.get().get("startDeadline"), request.get("startDeadline"));
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "cancel must not hold a SQL lock");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(started.get().get("generation"), request.get("generation"));
+            assertEquals(started.get().get("source"), request.get("source"));
+            return Map.of("generation", request.get("generation"), "status", "STOPPED");
+        });
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        new org.springframework.transaction.support.TransactionTemplate(transactions).executeWithoutResult(transaction -> {
+            try {
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"))
+                .andExpect(jsonPath("$.data.media.flv").value("https://media.invalid/prepared.flv"))
+                .andExpect(jsonPath("$.data.media.secret").doesNotExist())
+                .andExpect(jsonPath("$.data.media.stream").doesNotExist())
+                .andExpect(jsonPath("$.data.generation").doesNotExist());
+        action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+            } catch (Exception failure) { throw new RuntimeException(failure); }
+        });
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void failedIdentityRegistrationLeavesNoSessionAndStartsNoMedia() throws Exception {
+        when(sessions.insert(any(VideoSession.class))).thenReturn(0);
+        mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.code").value(503))
+                .andExpect(jsonPath("$.data.category").value("VIDEO_PREPARE_FAILED"));
+        assertTrue(transactions.rows().isEmpty(), "登记失败不得留下半条会话");
+        verifyNoInteractions(media);
+    }
+
+    @Test void anAnonymousViewerJoinsTheLegacyGenerationAndLeavingDoesNotCancelTheSharedStream() throws Exception {
+        VideoSession legacy = seed("legacy-business-viewer", "ACTIVE", null, "legacy_stream");
+        legacy.setUserId(7L);
+        java.util.concurrent.atomic.AtomicReference<Map<String, Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            started.set(request);
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE",
+                    "media", Map.of("stream", "legacy_stream", "flv", "https://media.invalid/legacy.flv"));
+        });
+        JSONObject viewer = prepare();
+        String liveBody = action(viewer, "live", viewer.getString("sessionToken"))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
+        assertEquals("ACTIVE", JSON.parseObject(liveBody).getJSONObject("data").getString("status"), "live 响应: " + liveBody);
+        assertNotNull(started.get(), "start 必须被调用一次");
+        assertEquals("legacy_stream", ((Map<?, ?>) started.get().get("existingMedia")).get("stream"),
+                "加入既有代次必须带上真实旧句柄,而不是重建");
+        assertEquals("legacy-origin-node", ((Map<?, ?>) started.get().get("existingMedia")).get("mediaServerId"));
+        VideoSession anonymous = transactions.rows().get(viewer.getString("sessionId"));
+        VideoSession storedLegacy = transactions.rows().get("legacy-business-viewer");
+        assertNotNull(storedLegacy.getMediaGeneration(), "旧观看者必须被并入一个代次");
+        assertEquals(storedLegacy.getMediaGeneration(), anonymous.getMediaGeneration(), "匿名观看必须加入同一代次");
+        assertEquals("legacy_stream", anonymous.getStreamId());
+
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, never()).post(eq("/internal/video/lifecycle/cancel"), any());
+        assertEquals("ACTIVE", transactions.rows().get("legacy-business-viewer").getStatus(),
+                "还有另一位有效观看者时不得回收共享底流");
+    }
+
+    @Test void disagreeingLegacyHandlesRefuseTheStartInsteadOfGuessingOne() throws Exception {
+        seed("legacy-a", "ACTIVE", null, "legacy_stream_a");
+        seed("legacy-b", "ACTIVE", null, "legacy_stream_b");
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("SESSION_HEARTBEAT_FAILED"));
+        verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
+        assertNull(transactions.rows().get(viewer.getString("sessionId")).getMediaGeneration(),
+                "句柄冲突时不得自行挑一个代次");
+    }
+
+    @Test void aLegacyActiveViewerWithoutAConfirmedHandleRefusesTheStart() throws Exception {
+        seed("legacy-no-handle", "ACTIVE", null, null);
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable());
+        verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @Test void aSessionFailedByTheProviderCannotBeRevivedByALaterStart() throws Exception {
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            return Map.of("generation", request.get("generation"), "status", "STARTING");
+        });
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            return Map.of("generation", request.get("generation"), "status", "FAILED");
+        });
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isAccepted());
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("FAILED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("FAILED"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    /** 预置一位已有观看者(可来自旧业务用户),用于混合观看与旧句柄场景。 */
+    private VideoSession seed(String sessionId, String status, String generation, String stream) {
+        VideoSession row = new VideoSession();
+        row.setSessionId(sessionId); row.setVideoId(VIDEO); row.setMode("LIVE"); row.setStatus(status);
+        row.setMediaGeneration(generation); row.setStreamId(stream);
+        row.setMediaServerId("legacy-origin-node");
+        row.setGbDeviceId("34020000002000000001"); row.setGbChannelId("34020000001320000001");
+        java.time.LocalDateTime now = java.time.LocalDateTime.ofInstant(
+                java.time.Instant.parse("2026-11-10T08:00:00Z"), java.time.ZoneOffset.UTC);
+        row.setCreateTime(now); row.setLastSeen(now);
+        row.setStartDeadline(java.time.LocalDateTime.ofInstant(
+                java.time.Instant.parse("2026-11-10T08:00:30Z"), java.time.ZoneOffset.UTC));
+        transactions.rows().put(sessionId, row);
+        return row;
+    }
+
+    private JSONObject prepare() throws Exception {
+        return JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
+                .getJSONObject("data");
+    }
+
+    private void refreshQueryStorage() {
+        queryStorage.update("DELETE FROM app_user.video_play_session");
+        transactions.rows().values().forEach(sqlQueries::insert);
+    }
+
+    private ResultActions action(JSONObject viewer, String action, String token) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) return null;
+        VideoSession copy = new VideoSession(); BeanUtils.copyProperties(source, copy); return copy;
+    }
+
+    @Configuration
+    @Import(CockpitVideoControllerTest.HttpConfiguration.class)
+    static class ConfigurationUnderTest {
+        @Bean RowTransactions transactionManager() { return new RowTransactions(); }
+    }
+
+    /** Transactional row storage, with no video selection/counting or lifecycle decisions. */
+    static class RowTransactions extends AbstractPlatformTransactionManager {
+        private final Map<String, VideoSession> committed = new LinkedHashMap<>();
+        private final ThreadLocal<Map<String, VideoSession>> originals = new ThreadLocal<>();
+        private final ThreadLocal<Map<String, VideoSession>> pending = new ThreadLocal<>();
+        Map<String, VideoSession> rows() { return pending.get() == null ? committed : pending.get(); }
+        @Override protected Object doGetTransaction() { return new Object(); }
+        @Override protected boolean isExistingTransaction(Object transaction) { return pending.get() != null; }
+        @Override protected void doBegin(Object transaction, TransactionDefinition definition) {
+            Map<String, VideoSession> snapshot = new LinkedHashMap<>();
+            committed.forEach((id, row) -> snapshot.put(id, copy(row)));
+            originals.set(new LinkedHashMap<>(snapshot)); pending.set(snapshot);
+        }
+        @Override protected void doCommit(DefaultTransactionStatus status) {
+            // A read-only outer transaction must not overwrite independently committed inner writes.
+            originals.get().keySet().stream().filter(id -> !pending.get().containsKey(id)).forEach(committed::remove);
+            pending.get().forEach((id, row) -> {
+                if (!java.util.Objects.equals(row, originals.get().get(id))) committed.put(id, copy(row));
+            });
+        }
+        @Override protected void doRollback(DefaultTransactionStatus status) { }
+        @Override protected Object doSuspend(Object transaction) {
+            Object[] state = {pending.get(), originals.get()}; pending.remove(); originals.remove(); return state;
+        }
+        @SuppressWarnings("unchecked")
+        @Override protected void doResume(Object transaction, Object suspended) {
+            Object[] state = (Object[]) suspended;
+            pending.set((Map<String, VideoSession>) state[0]); originals.set((Map<String, VideoSession>) state[1]);
+        }
+        @Override protected void doCleanupAfterCompletion(Object transaction) { pending.remove(); originals.remove(); }
+    }
+}

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

@@ -0,0 +1,595 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.framework.web.service.TokenService;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.Set;
+import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mybatis.spring.SqlSessionTemplate;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Primary;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.http.MediaType;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.transaction.TransactionSystemException;
+import org.springframework.transaction.support.DefaultTransactionStatus;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+import javax.servlet.Filter;
+import javax.sql.DataSource;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** Real HTTP/security/services, production MyBatis SQL and local in-memory SQL transactions.
+ * No server, application scheduler, external database or device is started. Media is the only
+ * lifecycle boundary substitute; it must never be called with a SQL transaction held.
+ */
+class VideoPreparedSqlTransactionTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String VIDEO = "sql-ledger-id";
+    private static final String CODE = "摄像机/ SQL+01";
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private JdbcTemplate sql;
+    private VideoCollectorClient media;
+    private final AtomicReference<Map<String, Object>> start = new AtomicReference<>();
+    private final AtomicReference<Map<String, Object>> cancel = new AtomicReference<>();
+
+    @BeforeEach void setUp() {
+        SecurityContextHolder.clearContext();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-sql-test", Map.of(
+                "token.header", "Authorization", "token.secret", "offline-sql-contract-not-a-production-secret", "token.expireTime", "60")));
+        context.register(SqlConfiguration.class);
+        context.refresh();
+        sql = new JdbcTemplate(context.getBean(DataSource.class));
+        createSchema(sql);
+        sql.update("INSERT INTO app_user.equipment_base VALUES (?)", VIDEO);
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("SQL摄像机"); device.setEquipmentTypeId(20);
+        when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
+        VideoDeviceRecord binding = new VideoDeviceRecord(); BeanUtils.copyProperties(device, binding);
+        binding.setVideoId(VIDEO); binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001"); binding.setGbChannelId("34020000001320000001");
+        when(context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO)).thenReturn(binding);
+        media = context.getBean(VideoCollectorClient.class);
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            start.set(new LinkedHashMap<>(body));
+            assertTrue(sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='STARTING' AND media_generation=?",
+                    Long.class, body.get("generation")) > 0, "intent must really commit before media starts");
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        });
+        when(media.get(eq("/api/play/start/34020000002000000001/34020000001320000001"), any()))
+                .thenReturn(Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+    }
+
+    @AfterEach void close() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    @Test void activeSqlFailureCompensatesTheAlreadyStartedGenerationBeforeReturning() throws Exception {
+        JSONObject viewer = prepare();
+        // This is a real failed SQL statement AFTER identity/STARTING commit and AFTER media start.
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
+        action(viewer, "live").andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        assertNotNull(start.get(), "the test must actually start media before the injected failure");
+        assertNotNull(cancel.get(), "ACTIVE persistence failure must immediately compensate, not leave a STARTING orphan");
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        assertEquals(start.get().get("source"), cancel.get().get("source"));
+        assertEquals(start.get().get("startDeadline"), cancel.get().get("startDeadline"));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void activeCommitFailureOrLostAcknowledgementCompensatesExactlyThisGeneration(boolean committed) throws Exception {
+        JSONObject viewer = prepare();
+        CommitFaultTransactions transactions = context.getBean(CommitFaultTransactions.class);
+        transactions.failActiveCommit = true;
+        transactions.commitBeforeFailure = committed;
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        assertTrue(transactions.failureInjected, "must fail ACTIVE commit, not prepare or intent commit");
+        assertNotNull(cancel.get(), "commit failure after media creation must compensate immediately");
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void failedCompensationRemainsPendingAndCanBeReclaimedWithoutASecondStart() throws Exception {
+        JSONObject viewer = prepare();
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            throw new IllegalStateException("offline media boundary failure");
+        });
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        assertNotNull(cancel.get(), "failed SQL must trigger compensation even when cancel also fails");
+        action(viewer, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("CLEANUP_PENDING"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(start.get().get("generation"), body.get("generation"));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void oldUserAndPreparedAnonymousReleaseOnlyTheLastSharedGeneration(boolean oldUserLast) throws Exception {
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        assertEquals("sql_stream", ((Map<?, ?>) start.get().get("existingMedia")).get("stream"));
+        mvc.perform(post("/api/video/sessions/{id}/stop", legacy.getString("sessionId"))
+                .header("Authorization", userToken(8))).andExpect(jsonPath("$.code").value(500));
+        assertNull(cancel.get(), "wrong ownership cannot release any media");
+        if (oldUserLast) {
+            action(viewer, "stop").andExpect(status().isOk());
+            assertNull(cancel.get(), "one remaining user still owns this generation");
+            oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        } else {
+            oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+            assertNull(cancel.get(), "one remaining anonymous viewer still owns this generation");
+            action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+            action(viewer, "stop").andExpect(status().isOk());
+        }
+        assertNotNull(cancel.get());
+        assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        action(viewer, "stop").andExpect(status().isOk());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+        verify(media, never()).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"PREPARED", "STARTING", "CLEANUP_PENDING"})
+    void expiryReclaimsEveryNonterminalIntentWithoutAnHttpPoll(String initial) throws Exception {
+        JSONObject viewer = prepare();
+        if (!"PREPARED".equals(initial)) {
+            if ("STARTING".equals(initial)) when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+                Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
+                return Map.of("generation", body.get("generation"), "status", "STARTING");
+            });
+            action(viewer, "live");
+            if ("CLEANUP_PENDING".equals(initial)) {
+                when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+                    Map<String, Object> body = call.getArgument(1);
+                    return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
+                });
+                action(viewer, "stop").andExpect(status().isAccepted());
+                when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+                    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+                    Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+                    return Map.of("generation", body.get("generation"), "status", "STOPPED");
+                });
+            }
+        }
+        context.getBean(MutableClock.class).advance("PREPARED".equals(initial) ? 121 : 31);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        // Read persisted outcome before status (which is itself allowed to perform cleanup).
+        assertEquals("STOPPED", sql.queryForObject("SELECT status FROM app_user.video_play_session WHERE session_id=?",
+                String.class, viewer.getString("sessionId")));
+        action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        if ("PREPARED".equals(initial)) verifyNoInteractions(media);
+        else assertEquals(start.get().get("generation"), cancel.get().get("generation"));
+    }
+
+    @ParameterizedTest
+    @CsvSource({"STARTING,false", "UNKNOWN,false", "STARTING,true", "UNKNOWN,true"})
+    void joiningAHealthyGenerationSurvivesItsOldDeadlineUntilTheActivePeerLeaves(String outcome, boolean peerExpires) throws Exception {
+        JSONObject active = prepare();
+        action(active, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        Map<String, Object> original = new LinkedHashMap<>(start.get());
+        MutableClock clock = context.getBean(MutableClock.class);
+        clock.advance(31);
+        action(active, "heartbeat").andExpect(status().isOk());
+        JSONObject joining = prepare();
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(original.get("generation"), body.get("generation"));
+            assertEquals(original.get("startDeadline"), body.get("startDeadline"));
+            if ("UNKNOWN".equals(outcome)) throw new IllegalStateException("offline lost start acknowledgement");
+            return Map.of("generation", body.get("generation"), "status", "STARTING");
+        }).when(media).post(eq("/internal/video/lifecycle/start"), any());
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "STARTING");
+        }).when(media).post(eq("/internal/video/lifecycle/status"), any());
+        action(joining, "live").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
+        assertNull(cancel.get(), "neither status nor the expiry worker may kill a healthy generation's joining viewer");
+        if (peerExpires) clock.advance(121);
+        else action(active, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNotNull(cancel.get(), "without a healthy peer the original expired deadline must reclaim the join");
+        assertEquals(original.get("generation"), cancel.get().get("generation"));
+        assertEquals(original.get("startDeadline"), cancel.get().get("startDeadline"));
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void aHealthyPeerDoesNotKeepAnAbandonedJoiningIntentForever() throws Exception {
+        JSONObject active = prepare();
+        action(active, "live").andExpect(status().isOk());
+        Object generation = start.get().get("generation");
+        MutableClock clock = context.getBean(MutableClock.class);
+        clock.advance(31);
+        action(active, "heartbeat").andExpect(status().isOk());
+        JSONObject joining = prepare();
+        doThrow(new IllegalStateException("offline start acknowledgement lost"))
+                .when(media).post(eq("/internal/video/lifecycle/start"), any());
+        action(joining, "live").andExpect(status().isAccepted());
+        clock.advance(119);
+        action(active, "heartbeat").andExpect(status().isOk());
+        clock.advance(2);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        // An abandoned viewer's own lease is bounded even while another viewer renews forever.
+        action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNull(cancel.get(), "expiring the abandoned join must not cancel its healthy peer");
+        action(active, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        action(active, "stop").andExpect(status().isOk());
+        assertEquals(generation, cancel.get().get("generation"));
+    }
+
+    @Test void legacyAnonymousStopReadsBackTheCommittedStoppedState() throws Exception {
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, times(1)).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
+    }
+
+    @Test void anOldApiViewerJoiningAnExistingPreparedGenerationNeverUsesBlindStart() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        String generation = (String) start.get().get("generation");
+        Object originalDeadline = start.get().get("startDeadline");
+        context.getBean(MutableClock.class).advance(31);
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/sql.flv"))
+                .andExpect(jsonPath("$.data.generation").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        assertEquals(generation, start.get().get("generation"));
+        assertEquals(originalDeadline, start.get().get("startDeadline"), "joining must not extend a generation's start deadline");
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        assertNull(cancel.get());
+        action(viewer, "stop").andExpect(status().isOk());
+        assertEquals(generation, cancel.get().get("generation"));
+        verify(media, never()).get(startsWith("/api/play/start/"), any());
+        verify(media, never()).get(startsWith("/api/play/stop/"), any());
+    }
+
+    @Test void sqlFailureWhileJoiningDoesNotCancelTheOtherActiveViewer() throws Exception {
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        JSONObject viewer = prepare();
+        String rejectedId = viewer.getString("sessionId");
+        assertNotNull(UUID.fromString(rejectedId));
+        sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_join CHECK (status <> 'ACTIVE' OR session_id <> '"
+                + rejectedId + "')");
+        action(viewer, "live").andExpect(status().isServiceUnavailable());
+        action(viewer, "status").andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNull(cancel.get(), "a failed joining viewer must not cancel the existing user's generation");
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        assertNotNull(cancel.get());
+        verify(media, never()).get(startsWith("/api/play/stop/"), any());
+    }
+
+    @Test void unrelatedVideoModeAndGenerationDoNotCountAsOwnersOfThisGeneration() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        String generation = (String) start.get().get("generation");
+        // Adversarial persisted rows: the actual SQL must filter on all three dimensions.
+        seedOtherOwner(VIDEO, "PLAYBACK", generation);
+        seedOtherOwner("another-video", "LIVE", generation);
+        seedOtherOwner(VIDEO, "LIVE", UUID.randomUUID().toString());
+        action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
+        assertNotNull(cancel.get(), "unrelated owners must not suppress last-viewer reclamation");
+        assertEquals(generation, cancel.get().get("generation"));
+        assertEquals(3L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class));
+    }
+
+    private void seedOtherOwner(String videoId, String mode, String generation) {
+        sql.update("INSERT INTO app_user.video_play_session (session_id,video_id,user_id,mode,status,media_generation,create_time,last_seen) "
+                + "VALUES (?,?,7,?,'ACTIVE',?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", UUID.randomUUID().toString(),videoId,mode,generation);
+    }
+
+    @Test void liveHeartbeatsKeepANonexpiredViewerOutOfTheExpiryScan() throws Exception {
+        JSONObject viewer = prepare();
+        action(viewer, "live").andExpect(status().isOk());
+        context.getBean(MutableClock.class).advance(119);
+        action(viewer, "heartbeat").andExpect(status().isOk());
+        context.getBean(MutableClock.class).advance(2);
+        context.getBean(VideoDeviceService.class).expireSessions();
+        action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        assertNull(cancel.get());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    void oldManualStopRetainsOnlyTheKnownOriginAndNeverAcknowledgesUnknownCleanup(boolean knownNode) throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/old-camera");
+        Map<String, Object> legacyMedia = new LinkedHashMap<>(Map.of("stream", "old_manual_stream",
+                "proxyKey", "old-private-key", "flv", "https://media.invalid/old.flv"));
+        if (knownNode) legacyMedia.put("mediaServerId", "origin-not-default");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(legacyMedia);
+        String bearer = userToken(7);
+        JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
+                .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/old.flv"))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        AtomicReference<Map<String, Object>> stopBody = new AtomicReference<>();
+        doAnswer(call -> {
+            stopBody.set(new LinkedHashMap<>(call.getArgument(1)));
+            // The external client reports pending/transport-unknown as failure, not confirmed stop.
+            throw new com.zksy.common.exception.ServiceException("offline provider cleanup pending after restart");
+        }).when(media).post(eq("/internal/video/manual/stop"), any());
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(500));
+        Map<String, Object> expected = knownNode ? Map.of("mediaServerId", "origin-not-default", "key", "old-private-key")
+                : Map.of("key", "old-private-key");
+        assertEquals(expected, stopBody.get(), "SQL's source node must survive provider restart; an unknown node must never be invented");
+        doAnswer(call -> {
+            assertEquals(expected, call.getArgument(1));
+            return null; // The existing successful manual-stop envelope has no data.
+        }).when(media).post(eq("/internal/video/manual/stop"), any());
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
+        verify(media, times(2)).post(eq("/internal/video/manual/stop"), any());
+        verify(media, never()).post(startsWith("/internal/video/lifecycle/"), any());
+    }
+
+    @Test void twoOldManualUsersAdoptOneKnownHandleAndOnlyTheLastUserCancels() throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/shared-old-camera");
+        Map<String, Object> knownMedia = Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node",
+                "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(knownMedia);
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
+            assertEquals(Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node", "proxyKey", "shared-private-key"),
+                    body.get("existingMedia"), "adoption must be bound to the persisted physical handle");
+            return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media", knownMedia);
+        }).when(media).post(eq("/internal/video/lifecycle/start"), any());
+        String firstBearer = userToken(7), secondBearer = userToken(8);
+        JSONObject first = oldManualStart(firstBearer);
+        assertNull(start.get(), "the very first old LIVE request retains its legacy start contract");
+        JSONObject second = oldManualStart(secondBearer);
+        assertNotNull(start.get(), "the second old user must coordinate adoption instead of starting another proxy");
+        String generation = (String) start.get().get("generation");
+        assertEquals(2L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE mode='LIVE' AND status='ACTIVE' AND media_generation=?",
+                Long.class, generation));
+        oldStop(first, secondBearer).andExpect(jsonPath("$.code").value(500));
+        assertNull(cancel.get());
+        oldStop(first, firstBearer).andExpect(jsonPath("$.code").value(200));
+        assertNull(cancel.get(), "the second old viewer still owns the adopted handle");
+        doAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
+            Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
+            return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
+        }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(500));
+        assertEquals(generation, cancel.get().get("generation"));
+        assertEquals(start.get().get("existingMedia"), cancel.get().get("existingMedia"));
+        doAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            assertEquals(generation, body.get("generation"));
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
+        oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
+        verify(media, times(1)).post(eq("/internal/video/manual/start"), any());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+        verify(media, times(2)).post(eq("/internal/video/lifecycle/cancel"), any());
+        verify(media, never()).post(eq("/internal/video/manual/stop"), any());
+    }
+
+    @Test void anUnknownLegacyManualNodeCannotBeGuessedOrBlindlyRestartedForAnotherOldUser() throws Exception {
+        VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
+        binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/unknown-node-camera");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(Map.of("stream", "shared_old_stream",
+                "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv"));
+        String bearer = userToken(7);
+        JSONObject first = oldManualStart(bearer);
+        clearInvocations(media);
+        mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", userToken(8)))
+                .andExpect(jsonPath("$.code").value(500));
+        verifyNoInteractions(media); // No guessed default node, adoption or second legacy start.
+        oldStop(first, bearer).andExpect(jsonPath("$.code").value(200));
+        verify(media).post("/internal/video/manual/stop", Map.of("key", "shared-private-key"));
+    }
+
+    private JSONObject oldManualStart(String bearer) throws Exception {
+        return JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", bearer))
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.flv").value("https://media.invalid/shared-old.flv"))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
+                .andExpect(jsonPath("$.data.generation").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+    }
+
+    private ResultActions oldStop(JSONObject viewer, String bearer) throws Exception {
+        return mvc.perform(post("/api/video/sessions/{id}/stop", viewer.getString("sessionId")).header("Authorization", bearer));
+    }
+
+    private String userToken(long id) {
+        SysUser user = new SysUser(); user.setUserId(id); user.setUserName("sql-viewer-" + id);
+        LoginUser login = new LoginUser(id, 101L, user, Set.of("video:device:play"));
+        MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("127.0.0.1");
+        ServletRequestAttributes attributes = new ServletRequestAttributes(request);
+        RequestContextHolder.setRequestAttributes(attributes);
+        try { return "Bearer " + context.getBean(TokenService.class).createToken(login); }
+        finally { attributes.requestCompleted(); RequestContextHolder.resetRequestAttributes(); }
+    }
+
+    static void createSchema(JdbcTemplate sql) {
+        sql.execute("CREATE SCHEMA app_user");
+        sql.execute("CREATE TABLE app_user.equipment_base (equipment_id varchar(64) PRIMARY KEY)");
+        sql.execute("CREATE TABLE app_user.video_play_session (session_id varchar(36) PRIMARY KEY, "
+                + "video_id varchar(64) NOT NULL, user_id bigint, anonymous_token_hash varchar(43), "
+                + "mode varchar(16) NOT NULL, status varchar(16) NOT NULL, stream_id varchar(200), proxy_key varchar(300), "
+                + "gb_device_id varchar(20), gb_channel_id varchar(20), media_generation varchar(64), media_server_id varchar(64), start_deadline timestamp, "
+                + "create_time timestamp NOT NULL, last_seen timestamp NOT NULL, end_time timestamp)");
+    }
+
+    private JSONObject prepare() throws Exception {
+        return JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare").contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+    }
+
+    private ResultActions action(JSONObject viewer, String action) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", viewer.getString("sessionToken")))));
+    }
+
+    /** Injects only the external commit outcome; all statements/rollback/normal commits are real JDBC. */
+    static class CommitFaultTransactions extends DataSourceTransactionManager {
+        boolean failActiveCommit;
+        boolean commitBeforeFailure;
+        boolean failureInjected;
+        CommitFaultTransactions(DataSource ds) { super(ds); setRollbackOnCommitFailure(true); }
+        @Override protected void doCommit(DefaultTransactionStatus status) {
+            if (failActiveCommit && new JdbcTemplate(getDataSource()).queryForObject(
+                    "SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class) > 0) {
+                failActiveCommit = false;
+                failureInjected = true;
+                if (commitBeforeFailure) super.doCommit(status);
+                throw new TransactionSystemException("offline injected ACTIVE commit failure");
+            }
+            super.doCommit(status);
+        }
+    }
+
+    static class MutableClock extends Clock {
+        private Instant now = Instant.parse("2026-11-10T08:00:00Z");
+        void advance(long seconds) { now = now.plusSeconds(seconds); }
+        @Override public Instant instant() { return now; }
+        @Override public ZoneId getZone() { return ZoneOffset.UTC; }
+        @Override public Clock withZone(ZoneId zone) { return Clock.fixed(now, zone); }
+    }
+
+    @Configuration
+    @EnableTransactionManagement
+    @Import(CockpitVideoControllerTest.HttpConfiguration.class)
+    static class SqlConfiguration {
+        @Bean @Primary MutableClock sqlClock() { return new MutableClock(); }
+        @Bean @Primary @SuppressWarnings("unchecked") RedisTemplate<String, Object> sqlRedis() {
+            Map<String, Object> values = new HashMap<>();
+            RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
+            ValueOperations<String, Object> operations = mock(ValueOperations.class);
+            when(redis.opsForValue()).thenReturn(operations);
+            when(operations.get(anyString())).thenAnswer(call -> values.get(call.getArgument(0)));
+            doAnswer(call -> { values.put(call.getArgument(0), call.getArgument(1)); return null; })
+                    .when(operations).set(anyString(), any(), anyLong(), any(TimeUnit.class));
+            return redis;
+        }
+        @Bean DataSource dataSource() {
+            DriverManagerDataSource ds = new DriverManagerDataSource();
+            ds.setDriverClassName("org.h2.Driver");
+            ds.setUrl("jdbc:h2:mem:video_" + UUID.randomUUID() + ";MODE=PostgreSQL;DB_CLOSE_DELAY=-1");
+            ds.setUsername("sa"); ds.setPassword(""); return ds;
+        }
+        @Bean CommitFaultTransactions transactionManager(DataSource ds) { return new CommitFaultTransactions(ds); }
+        @Bean @Primary VideoSessionMapper sqlSessions(DataSource ds) throws Exception {
+            MybatisConfiguration config = new MybatisConfiguration();
+            config.setMapUnderscoreToCamelCase(true);
+            config.addMapper(VideoSessionMapper.class);
+            MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
+            factory.setDataSource(ds); factory.setConfiguration(config);
+            SqlSessionFactory built = factory.getObject();
+            return new SqlSessionTemplate(built).getMapper(VideoSessionMapper.class);
+        }
+    }
+}

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

@@ -0,0 +1,383 @@
+package com.zksy.web.controller.cockpit;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.video.*;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.common.exception.ServiceException;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.BeanUtils;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import java.util.*;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/** Public service contract. Persistence and media are boundary substitutes, not a database integration test. */
+class VideoSessionCompatibilityTest {
+    private final VideoSessionMapper sessions = mock(VideoSessionMapper.class);
+    private final EquipmentVideoBindingMapper bindings = mock(EquipmentVideoBindingMapper.class);
+    private final VideoCollectorClient media = mock(VideoCollectorClient.class);
+    private final Map<String, VideoSession> rows = new HashMap<>();
+    private VideoDeviceService service;
+    private static final String DEVICE = "camera-1";
+    private static final String LIVE_START = "/api/play/start/34020000001320000001/34020000001320000002";
+    private static final String LIVE_STOP = "/api/play/stop/34020000001320000001/34020000001320000002";
+
+    @BeforeEach void setUp() {
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
+        VideoDeviceRecord device = new VideoDeviceRecord();
+        device.setEquipmentId(DEVICE);
+        device.setSourceType("GB28181");
+        device.setGbDeviceId("34020000001320000001");
+        device.setGbChannelId("34020000001320000002");
+        when(bindings.find(DEVICE)).thenReturn(device);
+        when(media.get(eq(LIVE_START), anyMap())).thenReturn(Map.of("stream", "live-1", "flv", "https://media.invalid/live.flv"));
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = copy(call.getArgument(0));
+            rows.put(row.getSessionId(), row);
+            return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(call -> copy(rows.get(call.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = copy(call.getArgument(0));
+            rows.put(row.getSessionId(), row);
+            return 1;
+        });
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings);
+    }
+
+    @AfterEach void clearIdentity() { SecurityContextHolder.clearContext(); }
+
+    @Test void anonymousViewersHaveIndependentCredentialsAndCannotMaintainEachOther() {
+        Map<String, Object> first = service.startAnonymous(DEVICE, null);
+        Map<String, Object> second = service.startAnonymous(DEVICE, null);
+        String id = (String) first.get("sessionId");
+        String token = (String) first.get("sessionToken");
+        assertEquals("LIVE", first.get("mode"));
+        assertEquals("https://media.invalid/live.flv", first.get("flv"));
+        assertNotEquals(token, second.get("sessionToken"));
+        assertNotEquals(id, token);
+        assertDoesNotThrow(() -> service.heartbeat(id, token));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, (String) second.get("sessionToken")));
+        assertThrows(ServiceException.class, () -> service.stop(id, (String) second.get("sessionToken")));
+        assertThrows(ServiceException.class, () -> service.stop(id, null));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void playbackControlRequiresItsOwnAnonymousCredentialAndActivePlayback() {
+        when(media.get(eq("/api/playback/start"), anyMap())).thenReturn(Map.of("stream", "record-1", "flv", "https://media.invalid/record.flv"));
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime("2026-11-10 10:00:00");
+        range.setEndTime("2026-11-10 10:10:00");
+        Map<String, Object> playback = service.startAnonymous(DEVICE, range);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) playback.get("sessionId"), token = (String) playback.get("sessionToken");
+        VideoRequests.Control pause = new VideoRequests.Control();
+        pause.setAction("pause");
+        assertThrows(ServiceException.class, () -> service.control(id, (String) live.get("sessionToken"), pause));
+        assertThrows(ServiceException.class, () -> service.control((String) live.get("sessionId"), (String) live.get("sessionToken"), pause));
+        verify(media, never()).get(eq("/api/playback/pause/record-1"), anyMap());
+        service.control(id, token, pause);
+        verify(media).get(eq("/api/playback/pause/record-1"), anyMap());
+        service.stop(id, token);
+        assertThrows(ServiceException.class, () -> service.control(id, token, pause));
+    }
+
+    @Test void anonymousValidityChecksDeviceModeAndWatchingTimeoutWithoutPreventingCleanup() {
+        Clock clock = mock(Clock.class);
+        when(clock.getZone()).thenReturn(ZoneOffset.ofHours(8));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:00:00Z"));
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings, clock);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, "another-device", "LIVE"));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, DEVICE, "PLAYBACK"));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:00Z"));
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:01Z"));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+        assertThrows(ServiceException.class, () -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        assertDoesNotThrow(() -> service.stop(id, token));
+        assertDoesNotThrow(() -> service.stop(id, token));
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void aRenewedWatcherIsNotStoppedByAnOlderExpiryScan() {
+        Clock clock = mock(Clock.class);
+        when(clock.getZone()).thenReturn(ZoneOffset.ofHours(8));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:00:00Z"));
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions,
+                mock(EquipmentBaseService.class), bindings, clock);
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        // The storage boundary returns an old scan snapshot, while selectById returns current data.
+        VideoSession snapshot = copy(rows.get(id));
+        when(sessions.selectList(any())).thenReturn(List.of(snapshot));
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:01:59Z"));
+        service.heartbeat(id, token);
+        when(clock.instant()).thenReturn(Instant.parse("2026-11-10T06:02:01Z"));
+        service.expireSessions();
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false})
+    void heartbeatCannotResurrectAWatcherStoppedAfterItsInitialRead(boolean anonymous) {
+        login(41);
+        Map<String, Object> live = anonymous ? service.startAnonymous(DEVICE, null) : service.start(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        java.util.concurrent.atomic.AtomicBoolean race = new java.util.concurrent.atomic.AtomicBoolean(true);
+        when(sessions.selectById(id)).thenAnswer(call -> {
+            VideoSession snapshot = copy(rows.get(id));
+            if (race.getAndSet(false)) {
+                if (anonymous) service.stop(id, token); else service.stop(id);
+            }
+            return snapshot;
+        });
+        if (anonymous) {
+            assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+            service.stop(id, token);
+        } else {
+            assertDoesNotThrow(() -> service.heartbeat(id)); // legacy stopped heartbeat remains an idempotent no-op
+            service.stop(id);
+        }
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(longs = {0, 1})
+    void failedRegistrationCompensatesWithoutStoppingAnExistingViewer(long existingViewers) {
+        if (existingViewers > 0) { login(41); service.start(DEVICE, null); }
+        // Literal database results: no viewer, or the one existing business-user viewer.
+        when(sessions.selectCount(any())).thenReturn(existingViewers);
+        when(sessions.insert(any(VideoSession.class))).thenReturn(0);
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(media, times(existingViewers == 0 ? 1 : 0)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void mixedUserAndAnonymousViewersReleaseOnlyTheLastSharedLiveStream() {
+        login(41);
+        Map<String, Object> legacy = service.start(DEVICE, null);
+        assertFalse(legacy.containsKey("sessionToken"));
+        SecurityContextHolder.clearContext();
+        Map<String, Object> first = service.startAnonymous(DEVICE, null);
+        Map<String, Object> second = service.startAnonymous(DEVICE, null);
+        String oldId = (String) legacy.get("sessionId"), firstId = (String) first.get("sessionId"), secondId = (String) second.get("sessionId");
+        String firstToken = (String) first.get("sessionToken"), secondToken = (String) second.get("sessionToken");
+        // A fresh service instance must use persisted ownership, not an in-process token registry.
+        service = new VideoDeviceService(mock(EquipmentBaseMapper.class), media, sessions, mock(EquipmentBaseService.class), bindings);
+        assertThrows(ServiceException.class, () -> service.stop(oldId, firstToken));
+        login(41);
+        assertThrows(ServiceException.class, () -> service.stop(firstId));
+        assertThrows(ServiceException.class, () -> service.heartbeat(firstId));
+        // External DB boundary fixtures for 3 -> 2 -> 1 viewers. No shared-count algorithm is copied here.
+        when(sessions.selectCount(any())).thenReturn(2L, 1L, 0L);
+        service.stop(firstId, firstToken);
+        service.heartbeat(secondId, secondToken);
+        service.heartbeat(oldId);
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+        service.stop(oldId);
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+        service.stop(secondId, secondToken);
+        verify(media, times(1)).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void playbackOccupiedByAnotherSourceIsRejectedWithoutStartingOrStoppingIt() {
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime("2026-11-10 10:00:00"); range.setEndTime("2026-11-10 10:10:00");
+        when(sessions.selectCount(any())).thenReturn(1L); // one ACTIVE playback in the storage boundary
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, range));
+        login(41);
+        assertThrows(ServiceException.class, () -> service.start(DEVICE, range));
+        verifyNoInteractions(media);
+    }
+
+    @Test void mediaStopFailureRemainsAnErrorAndCanBeRetried() {
+        Map<String, Object> live = service.startAnonymous(DEVICE, null);
+        String id = (String) live.get("sessionId"), token = (String) live.get("sessionToken");
+        when(media.get(eq(LIVE_STOP), anyMap())).thenThrow(new ServiceException("媒体不可用"));
+        assertThrows(ServiceException.class, () -> service.stop(id, token));
+        assertDoesNotThrow(() -> service.requireAnonymousSession(id, token, DEVICE, "LIVE"));
+        when(media.get(eq(LIVE_STOP), anyMap())).thenReturn(Map.of());
+        service.stop(id, token);
+        assertThrows(ServiceException.class, () -> service.heartbeat(id, token));
+    }
+
+    @Test void failedRegistrationAndFailedCompensationExplicitlyReportUnconfirmedCleanup() {
+        when(sessions.insert(any(VideoSession.class))).thenThrow(new IllegalStateException("database unavailable"));
+        when(media.get(eq(LIVE_STOP), anyMap())).thenThrow(new ServiceException("media unavailable"));
+        ServiceException failure = assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        assertEquals("播放会话登记失败,媒体清理未确认,请联系管理员", failure.getMessage());
+    }
+
+    @Test void missingLoginIsRejectedBeforeStartingMediaThroughTheLegacySeam() {
+        SecurityContextHolder.clearContext();
+        assertThrows(ServiceException.class, () -> service.start(DEVICE, null));
+        verifyNoInteractions(media);
+    }
+
+    @Test void databaseAbortingTheInsertDoesNotPreventMediaCompensation() {
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            // PostgreSQL/Kingbase rejects further queries in an aborted transaction.
+            when(sessions.selectCount(any())).thenThrow(new IllegalStateException("transaction is aborted"));
+            throw new IllegalStateException("insert failed");
+        });
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(strings = {"empty", "missingUrl", "missingStream", "badUrl", "badStream"})
+    void invalidMediaResponseIsNotPackagedAsAnActiveAnonymousSession(String scenario) {
+        Map<String, Object> response;
+        switch (scenario) {
+            case "missingUrl": response = Map.of("stream", "live-1"); break;
+            case "missingStream": response = Map.of("flv", "https://media.invalid/live.flv"); break;
+            case "badUrl": response = Map.of("stream", "live-1", "flv", "javascript:alert(1)"); break;
+            case "badStream": response = Map.of("stream", "../other", "flv", "https://media.invalid/live.flv"); break;
+            default: response = Map.of();
+        }
+        when(media.get(eq(LIVE_START), anyMap())).thenReturn(response);
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(sessions, never()).insert(any(VideoSession.class));
+    }
+
+    @Test void outerTransactionRollbackReleasesTheMediaStartedByAnUncommittedSession() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> rows.clear());
+        withTransactions(transactions, template -> template.execute(status -> {
+            service.startAnonymous(DEVICE, null);
+            status.setRollbackOnly();
+            return null;
+        }));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void aLostLiveStartResponseStillUsesTheKnownResourceForRollbackCleanup() {
+        when(media.get(eq(LIVE_START), anyMap())).thenThrow(new ServiceException("启动响应超时"));
+        withTransactions(new BoundaryTransactions(() -> rows.clear()), template ->
+                assertThrows(ServiceException.class, () -> template.execute(status -> service.startAnonymous(DEVICE, null))));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void failedCommitIsNotConfusedWithSuccessfulSessionRegistration() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> rows.clear());
+        transactions.failNextCommit = true;
+        withTransactions(transactions, template -> assertThrows(org.springframework.transaction.TransactionSystemException.class,
+                () -> template.execute(status -> service.startAnonymous(DEVICE, null))));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void rollbackCleanupPreservesAViewerThatJoinedAfterTheFailedTransaction() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> {
+            rows.clear();
+            when(sessions.selectCount(any())).thenReturn(1L); // a new committed viewer after rollback
+        });
+        withTransactions(transactions, template -> template.execute(status -> {
+            service.startAnonymous(DEVICE, null);
+            status.setRollbackOnly();
+            return null;
+        }));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void successfulCommitDoesNotRunFailureCleanup() {
+        withTransactions(new BoundaryTransactions(() -> rows.clear()), template ->
+                template.execute(status -> service.startAnonymous(DEVICE, null)));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    private void withTransactions(BoundaryTransactions transactions,
+                                  java.util.function.Consumer<org.springframework.transaction.support.TransactionTemplate> work) {
+        try (org.springframework.context.annotation.AnnotationConfigApplicationContext context =
+                     new org.springframework.context.annotation.AnnotationConfigApplicationContext()) {
+            context.registerBean(org.springframework.transaction.PlatformTransactionManager.class, () -> transactions);
+            context.refresh();
+            context.getAutowireCapableBeanFactory().autowireBean(service);
+            work.accept(new org.springframework.transaction.support.TransactionTemplate(transactions));
+        }
+    }
+
+    /** Database transaction boundary substitute; Spring drives real synchronization callbacks. */
+    private static final class BoundaryTransactions extends org.springframework.transaction.support.AbstractPlatformTransactionManager {
+        private final Runnable rollback;
+        private boolean failNextCommit;
+        private BoundaryTransactions(Runnable rollback) { this.rollback = rollback; setRollbackOnCommitFailure(true); }
+        @Override protected Object doGetTransaction() { return new Object(); }
+        @Override protected void doBegin(Object transaction, org.springframework.transaction.TransactionDefinition definition) { }
+        @Override protected void doCommit(org.springframework.transaction.support.DefaultTransactionStatus status) {
+            if (failNextCommit) {
+                failNextCommit = false;
+                throw new org.springframework.transaction.TransactionSystemException("database commit failed");
+            }
+        }
+        @Override protected void doRollback(org.springframework.transaction.support.DefaultTransactionStatus status) { rollback.run(); }
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.ValueSource(strings = {"native", "emptyKey", "blankKey"})
+    void aProxyResponseCannotBypassCleanupIdentity(String scenario) {
+        VideoDeviceRecord manual = new VideoDeviceRecord();
+        manual.setEquipmentId(DEVICE);
+        manual.setSourceType("MANUAL");
+        manual.setVideoUrl("rtsp://camera.invalid/live");
+        when(bindings.find(DEVICE)).thenReturn(manual);
+        Map<String, Object> response = scenario.equals("native")
+                ? Map.of("url", "https://media.invalid/live.flv", "native", true)
+                : Map.of("url", "https://media.invalid/live.flv", "stream", "manual_camera-1", "proxyKey", scenario.equals("emptyKey") ? "" : " ");
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(response);
+        assertThrows(ServiceException.class, () -> service.startAnonymous(DEVICE, null));
+        verify(sessions, never()).insert(any(VideoSession.class));
+    }
+
+    @org.junit.jupiter.params.ParameterizedTest
+    @org.junit.jupiter.params.provider.CsvSource({"true,true", "true,false", "false,true", "false,false"})
+    void manualNativeAndProxySourcesKeepWorkingForBothOwnerKinds(boolean nativeStream, boolean anonymous) {
+        VideoDeviceRecord manual = new VideoDeviceRecord();
+        manual.setEquipmentId(DEVICE); manual.setSourceType("MANUAL");
+        manual.setVideoUrl(nativeStream ? "HTTPS://camera.invalid/live.mp4" : "rtsp://camera.invalid/live");
+        when(bindings.find(DEVICE)).thenReturn(manual);
+        String key = "__defaultVhost__/city_video/manual_camera-1";
+        when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(
+                Map.of("flv", "https://media.invalid/live.flv", "stream", "manual_camera-1", "proxyKey", key));
+        login(41);
+        Map<String, Object> result = anonymous ? service.startAnonymous(DEVICE, null) : service.start(DEVICE, null);
+        assertFalse(result.containsKey("proxyKey"));
+        String id = (String) result.get("sessionId");
+        if (anonymous) service.stop(id, (String) result.get("sessionToken")); else service.stop(id);
+        if (nativeStream) verifyNoInteractions(media);
+        else verify(media).post("/internal/video/manual/stop", Map.of("key", key));
+    }
+
+    private static VideoSession copy(VideoSession row) {
+        if (row == null) return null;
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(row, copy);
+        return copy;
+    }
+
+    private static void login(long userId) {
+        LoginUser user = new LoginUser();
+        user.setUserId(userId);
+        SecurityContextHolder.getContext().setAuthentication(
+                new UsernamePasswordAuthenticationToken(user, null, List.of()));
+    }
+}

+ 451 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java

@@ -0,0 +1,451 @@
+package com.zksy.web.controller.video;
+
+import com.alibaba.fastjson2.JSON;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.base.video.VideoSession;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.common.core.redis.RedisCache;
+import com.zksy.framework.config.ResourcesConfig;
+import com.zksy.framework.config.SecurityConfig;
+import com.zksy.framework.config.properties.PermitAllUrlProperties;
+import com.zksy.framework.security.filter.JwtAuthenticationTokenFilter;
+import com.zksy.framework.security.handle.AuthenticationEntryPointImpl;
+import com.zksy.framework.security.handle.CockpitAuthenticationEntryPoint;
+import com.zksy.framework.security.handle.LogoutSuccessHandlerImpl;
+import com.zksy.framework.web.exception.GlobalExceptionHandler;
+import com.zksy.framework.web.service.PermissionService;
+import com.zksy.framework.web.service.TokenService;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+
+import javax.servlet.Filter;
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+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.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * The agreed seam is the existing /api/video HTTP contract, not controller metadata.
+ * Uses the real controller, SecurityConfig, method authorization, PermissionService,
+ * JWT filter, TokenService, RedisCache, exception handlers and VideoDeviceService.
+ * Only database/media boundaries and RedisTemplate storage are replaced in memory.
+ * No preinstalled Authentication, security-test request postprocessor, service stub,
+ * private-method assertion or source-text assertion stands in for those behaviors.
+ *
+ * <p>This is an isolated single-session contract test: it does not verify SQL,
+ * transaction locking, scheduled expiry or old/cockpit mixed-session reference counts.
+ * The mapper's count is zero because each fixture has no competing session. The
+ * service is constructed by a bean factory, not component-scanned: its scheduling
+ * configuration is intentionally not bootstrapped. No Boot application, Nacos,
+ * servlet server, database connection or media/Redis network client is started.
+ */
+class VideoDeviceCompatibilityTest {
+    private static final long OWNER = 41L;
+    private static final long OTHER_USER = 42L;
+    private static final String DEVICE_ID = "legacy-video-01";
+    private static final String GB_DEVICE = "34020000002000000001";
+    private static final String GB_CHANNEL = "34020000001320000001";
+    private static final String STREAM = "legacy_stream_001";
+    private static final String MEDIA_URL = "https://media.invalid/legacy.flv";
+    private static final String START_TIME = "2026-10-01 10:00:00";
+    private static final String END_TIME = "2026-10-01 10:30:00";
+    private static final String RANGE_JSON = "{\"startTime\":\"2026-10-01 10:00:00\","
+            + "\"endTime\":\"2026-10-01 10:30:00\"}";
+    private static final String CONTROL_JSON = "{\"action\":\"pause\"}";
+
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private TokenService tokens;
+    private EquipmentBaseMapper devices;
+    private EquipmentVideoBindingMapper bindings;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient collector;
+
+    @BeforeEach
+    void setUp() {
+        SecurityContextHolder.clearContext();
+        RequestContextHolder.resetRequestAttributes();
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-test", Map.of(
+                "token.header", "Authorization",
+                "token.secret", "dmlkZW8tY29tcGF0aWJpbGl0eS10ZXN0LW9ubHktbm90LWEtcHJvZHVjdGlvbi1zZWNyZXQtdmlkZW8tY29tcGF0aWJpbGl0eS10ZXN0",
+                "token.expireTime", "60")));
+        context.register(HttpContractConfiguration.class);
+        context.refresh();
+        // Mount the actual FilterChainProxy; spring-security-test is not required.
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        tokens = context.getBean(TokenService.class);
+        devices = context.getBean(EquipmentBaseMapper.class);
+        bindings = context.getBean(EquipmentVideoBindingMapper.class);
+        sessions = context.getBean(VideoSessionMapper.class);
+        collector = context.getBean(VideoCollectorClient.class);
+
+        VideoDeviceRecord device = new VideoDeviceRecord();
+        device.setEquipmentId(DEVICE_ID);
+        device.setVideoId(DEVICE_ID);
+        device.setSourceType("GB28181");
+        device.setGbDeviceId(GB_DEVICE);
+        device.setGbChannelId(GB_CHANNEL);
+        when(bindings.find(DEVICE_ID)).thenReturn(device);
+        Map<String, Object> playback = Map.of("stream", STREAM, "url", MEDIA_URL,
+                "proxyKey", "internal-media-proxy-key");
+        when(collector.get("/api/play/start/" + GB_DEVICE + "/" + GB_CHANNEL, Map.of()))
+                .thenReturn(playback);
+        when(collector.get("/api/playback/start", rangeParameters())).thenReturn(playback);
+
+        Map<String, VideoSession> rows = new ConcurrentHashMap<>();
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(invocation -> {
+            VideoSession row = invocation.getArgument(0);
+            rows.put(row.getSessionId(), copy(row));
+            return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(invocation -> copy(rows.get(invocation.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(invocation -> {
+            VideoSession row = invocation.getArgument(0);
+            return rows.replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        when(sessions.selectCount(any())).thenReturn(0L);
+    }
+
+    @AfterEach
+    void tearDown() {
+        try {
+            if (context != null) {
+                context.close();
+            }
+        } finally {
+            SecurityContextHolder.clearContext();
+            RequestContextHolder.resetRequestAttributes();
+        }
+    }
+
+    @Test
+    void playPermissionStartsLiveWithTheLegacyResponseFields() throws Exception {
+        startSession(Operation.LIVE, token(OWNER, "video:device:play"));
+        verify(collector).get("/api/play/start/" + GB_DEVICE + "/" + GB_CHANNEL, Map.of());
+    }
+
+    @Test
+    void recordPermissionStartsPlaybackWithTheLegacyRangeFields() throws Exception {
+        startSession(Operation.PLAYBACK, token(OWNER, "video:device:record"));
+        verify(collector).get("/api/playback/start", rangeParameters());
+    }
+
+    @ParameterizedTest(name = "{0} rejects unrelated and empty permission sets")
+    @EnumSource(Operation.class)
+    void loggedInUsersWithoutTheRequiredPermissionAreRejectedBeforeBusinessAccess(Operation operation)
+            throws Exception {
+        for (String bearer : Arrays.asList(token(OWNER, "video:device:list"), token(OWNER))) {
+            perform(operation, "not-reached", bearer)
+                    .andExpect(status().isOk())
+                    .andExpect(jsonPath("$.code").value(403))
+                    .andExpect(jsonPath("$.msg").value("没有权限,请联系管理员授权"));
+        }
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} does not accept {1}")
+    @CsvSource({
+            "LIVE, video:device:record",
+            "PLAYBACK, video:device:play",
+            "CONTROL, video:device:play"
+    })
+    void playAndRecordPermissionsAreNotInterchangeableForStartAndControl(Operation operation, String permission)
+            throws Exception {
+        perform(operation, "not-reached", token(OWNER, permission))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.msg").value("没有权限,请联系管理员授权"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} on {1}: {2} allows only the session owner")
+    @CsvSource({
+            "HEARTBEAT, LIVE, video:device:play",
+            "HEARTBEAT, LIVE, video:device:record",
+            "HEARTBEAT, PLAYBACK, video:device:play",
+            "HEARTBEAT, PLAYBACK, video:device:record",
+            "STOP, LIVE, video:device:play",
+            "STOP, LIVE, video:device:record",
+            "STOP, PLAYBACK, video:device:play",
+            "STOP, PLAYBACK, video:device:record",
+            "CONTROL, PLAYBACK, video:device:record"
+    })
+    void sessionActionsKeepAnyPermissionSemanticsButStillRequireTheRealSessionOwner(
+            Operation operation, Operation start, String permission) throws Exception {
+        // Create ownership via HTTP and the JWT principal, never by seeding an owner in a service stub.
+        String sessionId = startSession(start, token(OWNER, "video:device:play", "video:device:record"));
+        clearInvocations(devices, bindings, sessions, collector);
+
+        perform(operation, sessionId, token(OTHER_USER, permission))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.msg").value("播放会话不存在或无权操作"));
+        verifyNoInteractions(devices, bindings, collector);
+        verify(sessions, never()).updateById(any(VideoSession.class));
+        verify(sessions, never()).lockVideo(anyString());
+
+        success(perform(operation, sessionId, token(OWNER, permission)));
+        if (operation == Operation.CONTROL) {
+            verify(collector).get("/api/playback/pause/" + STREAM, Map.of());
+        } else if (operation == Operation.STOP) {
+            String path = start == Operation.LIVE
+                    ? "/api/play/stop/" + GB_DEVICE + "/" + GB_CHANNEL
+                    : "/api/playback/stop/" + GB_DEVICE + "/" + GB_CHANNEL + "/" + STREAM;
+            verify(collector).get(path, Map.of());
+        } else {
+            verify(sessions).updateById(any(VideoSession.class));
+            verifyNoInteractions(collector);
+        }
+    }
+
+    @ParameterizedTest(name = "legacy control action {0}")
+    @CsvSource({
+            "pause, 0, /api/playback/pause/legacy_stream_001",
+            "resume, 0, /api/playback/resume/legacy_stream_001",
+            "seek, 45, /api/playback/seek/legacy_stream_001/45",
+            "speed, 2, /api/playback/speed/legacy_stream_001/2.0"
+    })
+    void recordPermissionKeepsLegacyPlaybackControlBodyAndMediaCommand(
+            String action, double value, String mediaPath) throws Exception {
+        String bearer = token(OWNER, "video:device:record");
+        String sessionId = startSession(Operation.PLAYBACK, bearer);
+        clearInvocations(collector);
+        success(mvc.perform(post("/api/video/sessions/{id}/control", sessionId)
+                .header("Authorization", bearer).contentType(MediaType.APPLICATION_JSON)
+                .content(JSON.toJSONString(Map.of("action", action, "value", value)))));
+        verify(collector).get(mediaPath, Map.of());
+    }
+
+    @ParameterizedTest(name = "anonymous {0} keeps legacy code 401, not cockpit HTTP 401")
+    @EnumSource(Operation.class)
+    void anonymousRequestsAreRejectedByTheRealSecurityChain(Operation operation) throws Exception {
+        MockHttpServletRequestBuilder request = request(operation, "not-reached");
+        mvc.perform(request).andExpect(status().isOk())
+                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
+                .andExpect(jsonPath("$.code").value(401))
+                .andExpect(jsonPath("$.msg").value(
+                        "请求访问:" + path(operation, "not-reached") + ",认证失败,无法访问系统资源"));
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "{0} cannot authenticate with an invalid or revoked JWT")
+    @EnumSource(Operation.class)
+    void malformedAndRevokedTokensCannotBypassAuthentication(Operation operation) throws Exception {
+        String revoked = token(OWNER, "video:device:play", "video:device:record");
+        LoginUser login = tokens.getLoginUserByToken(revoked);
+        tokens.delLoginUser(login.getToken());
+        for (String bearer : Arrays.asList("Bearer not-a-jwt", revoked)) {
+            perform(operation, "not-reached", bearer)
+                    .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401));
+        }
+        verifyNoInteractions(devices, bindings, sessions, collector);
+    }
+
+    @ParameterizedTest(name = "missing session is not accessible through {0}")
+    @EnumSource(value = Operation.class, names = {"HEARTBEAT", "STOP", "CONTROL"})
+    void missingSessionUsesTheSameLegacyOwnershipFailure(Operation operation) throws Exception {
+        perform(operation, "missing-session", token(OWNER, "video:device:play", "video:device:record"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.msg").value("播放会话不存在或无权操作"));
+        verifyNoInteractions(devices, bindings, collector);
+        verify(sessions, never()).updateById(any(VideoSession.class));
+    }
+
+    private String startSession(Operation operation, String bearer) throws Exception {
+        String mode = operation == Operation.LIVE ? "LIVE" : "PLAYBACK";
+        String body = success(perform(operation, DEVICE_ID, bearer))
+                .andExpect(jsonPath("$.data.sessionId").isNotEmpty())
+                .andExpect(jsonPath("$.data.mode").value(mode))
+                .andExpect(jsonPath("$.data.stream").value(STREAM))
+                .andExpect(jsonPath("$.data.url").value(MEDIA_URL))
+                .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
+        return JSON.parseObject(body).getJSONObject("data").getString("sessionId");
+    }
+
+    private ResultActions success(ResultActions result) throws Exception {
+        return result.andExpect(status().isOk())
+                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.msg").value("操作成功"));
+    }
+
+    private ResultActions perform(Operation operation, String sessionId, String bearer) throws Exception {
+        return mvc.perform(request(operation, sessionId).header("Authorization", bearer));
+    }
+
+    private MockHttpServletRequestBuilder request(Operation operation, String sessionId) {
+        MockHttpServletRequestBuilder request = post(path(operation, sessionId));
+        if (operation == Operation.PLAYBACK) {
+            request.contentType(MediaType.APPLICATION_JSON).content(RANGE_JSON);
+        } else if (operation == Operation.CONTROL) {
+            request.contentType(MediaType.APPLICATION_JSON).content(CONTROL_JSON);
+        }
+        return request;
+    }
+
+    private String path(Operation operation, String sessionId) {
+        String resource = operation == Operation.LIVE || operation == Operation.PLAYBACK
+                ? "/devices/" + DEVICE_ID : "/sessions/" + sessionId;
+        return "/api/video" + resource + "/" + operation.name().toLowerCase(Locale.ROOT);
+    }
+
+    private String token(long userId, String... permissions) {
+        SysUser user = new SysUser();
+        user.setUserId(userId);
+        user.setUserName("video-user-" + userId);
+        LoginUser login = new LoginUser(userId, 101L, user, new HashSet<>(Arrays.asList(permissions)));
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setRemoteAddr("127.0.0.1"); // TokenService's location lookup short-circuits for an internal IP.
+        request.addHeader("User-Agent", "VideoDeviceCompatibilityTest");
+        ServletRequestAttributes attributes = new ServletRequestAttributes(request);
+        RequestContextHolder.setRequestAttributes(attributes);
+        try {
+            return "Bearer " + tokens.createToken(login);
+        } finally {
+            attributes.requestCompleted();
+            RequestContextHolder.resetRequestAttributes();
+        }
+    }
+
+    private static Map<String, Object> rangeParameters() {
+        return Map.of("deviceId", GB_DEVICE, "channelId", GB_CHANNEL,
+                "startTime", START_TIME, "endTime", END_TIME, "type", "all");
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) {
+            return null;
+        }
+        VideoSession copy = new VideoSession();
+        BeanUtils.copyProperties(source, copy);
+        return copy;
+    }
+
+    enum Operation { LIVE, PLAYBACK, HEARTBEAT, STOP, CONTROL }
+
+    @Configuration
+    @EnableWebMvc
+    @EnableWebSecurity
+    @Import({SecurityConfig.class, PermitAllUrlProperties.class, PermissionService.class,
+            JwtAuthenticationTokenFilter.class, TokenService.class, RedisCache.class,
+            AuthenticationEntryPointImpl.class, CockpitAuthenticationEntryPoint.class,
+            LogoutSuccessHandlerImpl.class, GlobalExceptionHandler.class, VideoDeviceController.class})
+    static class HttpContractConfiguration {
+        @Bean
+        Clock clock() {
+            return Clock.systemUTC();
+        }
+
+        @Bean
+        UserDetailsService userDetailsService() {
+            return new InMemoryUserDetailsManager();
+        }
+
+        @Bean
+        CorsFilter corsFilter() {
+            // Reuse the real CORS bean factory, without importing unrelated resource/interceptor setup.
+            return new ResourcesConfig().corsFilter();
+        }
+
+        @Bean
+        EquipmentBaseMapper equipmentBaseMapper() {
+            return mock(EquipmentBaseMapper.class);
+        }
+
+        @Bean
+        EquipmentVideoBindingMapper equipmentVideoBindingMapper() {
+            return mock(EquipmentVideoBindingMapper.class);
+        }
+
+        @Bean
+        VideoSessionMapper videoSessionMapper() {
+            return mock(VideoSessionMapper.class);
+        }
+
+        @Bean
+        VideoCollectorClient videoCollectorClient() {
+            return mock(VideoCollectorClient.class);
+        }
+
+        @Bean
+        VideoDeviceService videoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector,
+                VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings) {
+            // Equipment writes are outside these five endpoints; no ledger service graph is bootstrapped.
+            return new VideoDeviceService(devices, collector, sessions, mock(EquipmentBaseService.class), bindings);
+        }
+
+        @Bean
+        @SuppressWarnings("unchecked")
+        RedisTemplate<String, Object> redisTemplate() {
+            Map<String, Object> values = new ConcurrentHashMap<>();
+            RedisTemplate<String, Object> template = mock(RedisTemplate.class);
+            ValueOperations<String, Object> operations = mock(ValueOperations.class);
+            when(template.opsForValue()).thenReturn(operations);
+            when(operations.get(anyString())).thenAnswer(invocation -> values.get(invocation.getArgument(0)));
+            doAnswer(invocation -> {
+                values.put(invocation.getArgument(0), invocation.getArgument(1));
+                return null;
+            }).when(operations).set(anyString(), any(), anyLong(), any(TimeUnit.class));
+            when(template.delete(anyString())).thenAnswer(invocation -> values.remove(invocation.getArgument(0)) != null);
+            return template;
+        }
+    }
+}

+ 12 - 0
pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/config/SecurityConfig.java

@@ -122,6 +122,18 @@ public class SecurityConfig
             .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
             .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
             // 注解标记允许匿名访问的url
             // 注解标记允许匿名访问的url
             .authorizeHttpRequests((requests) -> {
             .authorizeHttpRequests((requests) -> {
+                // Video is a narrow anonymous exception, before any broad GET/annotation rule.
+                requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/video/device",
+                        "/api/cockpit/v1/video/records").permitAll()
+                    .antMatchers(HttpMethod.POST, "/api/cockpit/v1/video/live",
+                        "/api/cockpit/v1/video/playback",
+                        "/api/cockpit/v1/video/sessions/prepare",
+                        "/api/cockpit/v1/video/sessions/*/live",
+                        "/api/cockpit/v1/video/sessions/*/status",
+                        "/api/cockpit/v1/video/sessions/*/heartbeat",
+                        "/api/cockpit/v1/video/sessions/*/control",
+                        "/api/cockpit/v1/video/sessions/*/stop").permitAll()
+                    .antMatchers("/api/cockpit/v1/video/**").authenticated();
                 permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
                 permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
                 requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/**").permitAll()
                 requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/**").permitAll()
                     // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                     // 对于登录login 注册register 验证码captchaImage 允许匿名访问

+ 1 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/alarm/service/AlarmReviewScopeService.java

@@ -58,6 +58,7 @@ public class AlarmReviewScopeService {
     public List<Integer> resolveOperations(AlarmReviewQuery query) {
     public List<Integer> resolveOperations(AlarmReviewQuery query) {
         return resolve(query, new HashSet<>(Arrays.asList("subSystem/alarm/common/remind", "subSystem/alarm/common/list",
         return resolve(query, new HashSet<>(Arrays.asList("subSystem/alarm/common/remind", "subSystem/alarm/common/list",
                 "subSystem/alarm/common/analysis", "subSystem/alarm/common/alarmGIS",
                 "subSystem/alarm/common/analysis", "subSystem/alarm/common/alarmGIS",
+                "subSystem/drainage/alarm/analysis", "subSystem/drainage/alarm/alarmGIS",
                 "subSystem/waterSupply/alarm/alarmGIS",
                 "subSystem/waterSupply/alarm/alarmGIS",
                 // 四大子系统通用首页:菜单 query.rootTypeId 同样作为报警清单的数据范围依据
                 // 四大子系统通用首页:菜单 query.rootTypeId 同样作为报警清单的数据范围依据
                 "subSystem/pipeNetwork/home/index")));
                 "subSystem/pipeNetwork/home/index")));

+ 53 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/PipeNetworkBase.java

@@ -1,6 +1,7 @@
 package com.zksy.base.domain;
 package com.zksy.base.domain;
 
 
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableLogic;
 import com.baomidou.mybatisplus.annotation.TableLogic;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.baomidou.mybatisplus.annotation.TableName;
@@ -40,6 +41,18 @@ public class PipeNetworkBase {
      */
      */
     public static final String NETWORK_TYPE_WATER = "2";
     public static final String NETWORK_TYPE_WATER = "2";
 
 
+    /**
+     * 排水管线类型:污水(network_level = 0)
+     *
+     * 排水口径下 network_level 不表示压力等级,而是雨污类型,与库表注释一致。
+     */
+    public static final String SEWAGE_TYPE_SEWAGE = "0";
+
+    /**
+     * 排水管线类型:雨水(network_level = 1)
+     */
+    public static final String SEWAGE_TYPE_RAIN = "1";
+
     @TableId(value = "network_id", type = IdType.ASSIGN_UUID)
     @TableId(value = "network_id", type = IdType.ASSIGN_UUID)
     @ApiModelProperty("管网设施ID")
     @ApiModelProperty("管网设施ID")
     private String networkId;
     private String networkId;
@@ -53,7 +66,12 @@ public class PipeNetworkBase {
     @ApiModelProperty("设施类型(0=燃气设施)")
     @ApiModelProperty("设施类型(0=燃气设施)")
     private String networkType;
     private String networkType;
 
 
-    @ApiModelProperty("等级")
+    /**
+     * 等级
+     *
+     * 燃气/供水为压力等级;排水口径下该列用于区分排水管道:0=污水 1=雨水(见库表注释)。
+     */
+    @ApiModelProperty("等级(燃气/供水为压力等级;排水为雨污类型:0=污水 1=雨水)")
     private String networkLevel;
     private String networkLevel;
 
 
     @ApiModelProperty("管养单位")
     @ApiModelProperty("管养单位")
@@ -110,4 +128,38 @@ public class PipeNetworkBase {
 
 
     @ApiModelProperty("管网终点WGS84纬度")
     @ApiModelProperty("管网终点WGS84纬度")
     private BigDecimal endLatitude;
     private BigDecimal endLatitude;
+
+    /**
+     * 排水管线类型:0=污水 1=雨水,空=未识别
+     *
+     * 排水口径下库里的 network_level 就是雨污类型,这里只做语义化重命名后返回,
+     * 由 {@link #fillSewageType()} 在查询后填充,不落库。
+     */
+    @TableField(exist = false)
+    @ApiModelProperty("排水管线类型(0=污水 1=雨水,空=未识别)")
+    private String sewageType;
+
+    /**
+     * 按 network_level 填充雨污类型
+     */
+    public void fillSewageType() {
+        this.sewageType = normalizeSewageType(networkLevel);
+    }
+
+    /**
+     * 把 network_level 归一化成雨污类型
+     *
+     * @param networkLevel 库里的 network_level,排水管道下 0=污水 1=雨水
+     * @return 0=污水 1=雨水,其余(空、非 0/1 的脏值)返回 null 表示未识别
+     */
+    public static String normalizeSewageType(String networkLevel) {
+        if (networkLevel == null) {
+            return null;
+        }
+        String value = networkLevel.trim();
+        if (SEWAGE_TYPE_SEWAGE.equals(value) || SEWAGE_TYPE_RAIN.equals(value)) {
+            return value;
+        }
+        return null;
+    }
 }
 }

+ 3 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/dto/PipeNetworkPageInDTO.java

@@ -30,6 +30,9 @@ public class PipeNetworkPageInDTO implements Serializable {
     @ApiModelProperty(value = "状态")
     @ApiModelProperty(value = "状态")
     private String status;
     private String status;
 
 
+    @ApiModelProperty(value = "排水管线类型(0=污水 1=雨水,对应 network_level,仅排水模块使用)")
+    private String sewageType;
+
     @ApiModelProperty(value = "位置描述(模糊匹配)")
     @ApiModelProperty(value = "位置描述(模糊匹配)")
     private String location;
     private String location;
 
 

+ 2 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/mapper/VideoSessionMapper.java

@@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 
 
 @Mapper
 @Mapper
 public interface VideoSessionMapper extends BaseMapper<VideoSession> {
 public interface VideoSessionMapper extends BaseMapper<VideoSession> {
+    // Discard session-local snapshots before re-reading ownership/status under the lock.
+    @Options(flushCache = Options.FlushCachePolicy.TRUE)
     @Select("SELECT equipment_id FROM app_user.equipment_base WHERE equipment_id=#{videoId} FOR UPDATE")
     @Select("SELECT equipment_id FROM app_user.equipment_base WHERE equipment_id=#{videoId} FOR UPDATE")
     String lockVideo(@Param("videoId") String videoId);
     String lockVideo(@Param("videoId") String videoId);
 }
 }

+ 37 - 3
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/PipeNetworkBaseServiceImpl.java

@@ -247,7 +247,9 @@ public class PipeNetworkBaseServiceImpl extends ServiceImpl<PipeNetworkBaseMappe
     public Page<PipeNetworkBase> queryDrainageByPage(PipeNetworkPageInDTO dto) {
     public Page<PipeNetworkBase> queryDrainageByPage(PipeNetworkPageInDTO dto) {
         long pageNum = dto.getPageNum() == null ? 1L : dto.getPageNum();
         long pageNum = dto.getPageNum() == null ? 1L : dto.getPageNum();
         long pageSize = dto.getPageSize() == null ? 10L : dto.getPageSize();
         long pageSize = dto.getPageSize() == null ? 10L : dto.getPageSize();
-        return this.page(new Page<>(pageNum, pageSize), buildDrainageWrapper(dto));
+        Page<PipeNetworkBase> page = this.page(new Page<>(pageNum, pageSize), buildDrainageWrapper(dto));
+        fillSewageTypes(page.getRecords());
+        return page;
     }
     }
 
 
     @Override
     @Override
@@ -259,7 +261,11 @@ public class PipeNetworkBaseServiceImpl extends ServiceImpl<PipeNetworkBaseMappe
         wrapper.eq(PipeNetworkBase::getNetworkId, networkId);
         wrapper.eq(PipeNetworkBase::getNetworkId, networkId);
         // 排水模块只允许查询排水设施
         // 排水模块只允许查询排水设施
         wrapper.eq(PipeNetworkBase::getNetworkType, PipeNetworkBase.NETWORK_TYPE_DRAINAGE);
         wrapper.eq(PipeNetworkBase::getNetworkType, PipeNetworkBase.NETWORK_TYPE_DRAINAGE);
-        return this.getOne(wrapper, false);
+        PipeNetworkBase entity = this.getOne(wrapper, false);
+        if (entity != null) {
+            entity.fillSewageType();
+        }
+        return entity;
     }
     }
 
 
     @Override
     @Override
@@ -272,7 +278,19 @@ public class PipeNetworkBaseServiceImpl extends ServiceImpl<PipeNetworkBaseMappe
                 .or()
                 .or()
                 .and(e -> e.isNotNull(PipeNetworkBase::getEndLongitude)
                 .and(e -> e.isNotNull(PipeNetworkBase::getEndLongitude)
                         .isNotNull(PipeNetworkBase::getEndLatitude)));
                         .isNotNull(PipeNetworkBase::getEndLatitude)));
-        return this.list(wrapper);
+        List<PipeNetworkBase> list = this.list(wrapper);
+        fillSewageTypes(list);
+        return list;
+    }
+
+    /**
+     * 批量填充雨污类型(取 network_level:0=污水 1=雨水),不修改数据库
+     */
+    private static void fillSewageTypes(List<PipeNetworkBase> list) {
+        if (CollectionUtils.isEmpty(list)) {
+            return;
+        }
+        list.forEach(PipeNetworkBase::fillSewageType);
     }
     }
 
 
     /**
     /**
@@ -317,6 +335,7 @@ public class PipeNetworkBaseServiceImpl extends ServiceImpl<PipeNetworkBaseMappe
         wrapper.like(hasText(dto.getMaterial()), PipeNetworkBase::getMaterial, dto.getMaterial());
         wrapper.like(hasText(dto.getMaterial()), PipeNetworkBase::getMaterial, dto.getMaterial());
         wrapper.eq(hasText(dto.getStatus()), PipeNetworkBase::getStatus, dto.getStatus());
         wrapper.eq(hasText(dto.getStatus()), PipeNetworkBase::getStatus, dto.getStatus());
         wrapper.like(hasText(dto.getLocation()), PipeNetworkBase::getLocation, dto.getLocation());
         wrapper.like(hasText(dto.getLocation()), PipeNetworkBase::getLocation, dto.getLocation());
+        applySewageTypeCondition(wrapper, dto.getSewageType());
 
 
         Date buildStart = parseDate(dto.getBuildDateStart());
         Date buildStart = parseDate(dto.getBuildDateStart());
         Date buildEnd = parseDate(dto.getBuildDateEnd());
         Date buildEnd = parseDate(dto.getBuildDateEnd());
@@ -333,6 +352,21 @@ public class PipeNetworkBaseServiceImpl extends ServiceImpl<PipeNetworkBaseMappe
         return value != null && !value.trim().isEmpty();
         return value != null && !value.trim().isEmpty();
     }
     }
 
 
+    /**
+     * 追加雨污类型筛选条件
+     *
+     * 排水口径下 network_level 即雨污类型(0=污水 1=雨水),直接等值匹配,不做任何文本猜测。
+     */
+    private void applySewageTypeCondition(LambdaQueryWrapper<PipeNetworkBase> wrapper, String sewageType) {
+        if (!hasText(sewageType)) {
+            return;
+        }
+        String value = sewageType.trim();
+        if (PipeNetworkBase.SEWAGE_TYPE_SEWAGE.equals(value) || PipeNetworkBase.SEWAGE_TYPE_RAIN.equals(value)) {
+            wrapper.eq(PipeNetworkBase::getNetworkLevel, value);
+        }
+    }
+
     /**
     /**
      * 解析 yyyy-MM-dd,格式非法时返回 null(视为不按该端筛选)
      * 解析 yyyy-MM-dd,格式非法时返回 null(视为不按该端筛选)
      */
      */

+ 318 - 40
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java

@@ -15,7 +15,17 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
 import java.net.URI;
 import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Clock;
 import java.time.Duration;
 import java.time.Duration;
 import java.time.LocalDateTime;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 import java.time.format.DateTimeFormatter;
@@ -29,6 +39,7 @@ public class VideoDeviceService {
     public static final int VIDEO_EQUIPMENT_TYPE_ID = 20;
     public static final int VIDEO_EQUIPMENT_TYPE_ID = 20;
 
 
     private static final String GB28181 = "GB28181";
     private static final String GB28181 = "GB28181";
+    private static final SecureRandom RANDOM = new SecureRandom();
 
 
     private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
     private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
     private final EquipmentBaseMapper devices;
     private final EquipmentBaseMapper devices;
@@ -36,13 +47,30 @@ public class VideoDeviceService {
     private final VideoCollectorClient collector;
     private final VideoCollectorClient collector;
     private final VideoSessionMapper sessions;
     private final VideoSessionMapper sessions;
     private final EquipmentBaseService equipmentService;
     private final EquipmentBaseService equipmentService;
+    private final Clock clock;
+    private TransactionTemplate rollbackCleanup;
+    private final com.zksy.cockpit.video.VideoLiveLifecycle liveLifecycle;
 
 
+    @org.springframework.beans.factory.annotation.Autowired(required=false)
+    void configureRollbackCleanup(PlatformTransactionManager manager) {
+        rollbackCleanup=new TransactionTemplate(manager);
+        rollbackCleanup.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+        liveLifecycle.configure(manager);
+    }
+
+    @org.springframework.beans.factory.annotation.Autowired
     public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
     public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
+        this(devices, collector, sessions, equipmentService, bindings, Clock.systemDefaultZone());
+    }
+
+    public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings, Clock clock) {
+        this.clock=Objects.requireNonNull(clock);
         this.bindings=bindings;
         this.bindings=bindings;
         this.devices=devices;
         this.devices=devices;
         this.collector=collector;
         this.collector=collector;
         this.sessions=sessions;
         this.sessions=sessions;
         this.equipmentService=equipmentService;
         this.equipmentService=equipmentService;
+        this.liveLifecycle=new com.zksy.cockpit.video.VideoLiveLifecycle(sessions, bindings, collector, clock);
     }
     }
 
 
     public Page<VideoDeviceRecord> list(int pageNum,int pageSize,String query,String sourceType,String stationId) {
     public Page<VideoDeviceRecord> list(int pageNum,int pageSize,String query,String sourceType,String stationId) {
@@ -131,41 +159,186 @@ public class VideoDeviceService {
         return response instanceof Map?new HashMap<>((Map<String,Object>)response):Map.of();
         return response instanceof Map?new HashMap<>((Map<String,Object>)response):Map.of();
     }
     }
     @Transactional
     @Transactional
-    @SuppressWarnings("unchecked") public Map<String,Object> start(String id,VideoRequests.Range range) {
+    public Map<String,Object> start(String id,VideoRequests.Range range) {
+        // Resolve identity before allocating media resources.
+        return startSession(id, range, SecurityUtils.getUserId(), null);
+    }
+
+    /** Internal seam for the cockpit adapter; no anonymous HTTP route is published here. */
+    @Transactional
+    public Map<String,Object> startAnonymous(String id,VideoRequests.Range range) {
+        byte[] secret = new byte[32];
+        RANDOM.nextBytes(secret);
+        String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
+        Map<String,Object> data = startSession(id, range, null, tokenHash(token));
+        data.put("sessionToken", token);
+        return data;
+    }
+
+    @SuppressWarnings("unchecked")
+    /** Persist anonymous ownership before any request is allowed to allocate media. */
+    public Map<String,Object> prepareAnonymous(String id) {
+        byte[] secret = new byte[32];
+        RANDOM.nextBytes(secret);
+        String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
+        if (rollbackCleanup == null) throw new ServiceException("视频事务未配置");
+        VideoSession session = liveLifecycle.prepare(id, null, tokenHash(token));
+        Map<String,Object> data = sessionState(session);
+        data.put("sessionToken", token);
+        return data;
+    }
+
+    public Map<String,Object> anonymousState(String id, String token) {
+        return liveLifecycle.status(() -> ownedAnonymous(id, token));
+    }
+
+    public Map<String,Object> startPrepared(String id, String token) {
+        return liveLifecycle.start(() -> ownedAnonymous(id, token));
+    }
+
+    public Map<String,Object> stopAnonymousState(String id, String token) {
+        VideoSession current = ownedAnonymous(id, token);
+        if ("PREPARED".equals(current.getStatus()) || current.getMediaGeneration() != null)
+            return liveLifecycle.stop(() -> ownedAnonymous(id, token));
+        if (!"STOPPED".equals(current.getStatus()) && !"FAILED".equals(current.getStatus())) stop(id, token);
+        return sessionState(ownedAnonymous(id, token));
+    }
+
+    private static Map<String,Object> sessionState(VideoSession session) {
+        Map<String,Object> data = new LinkedHashMap<>();
+        data.put("sessionId", session.getSessionId());
+        data.put("status", session.getStatus());
+        data.put("mode", session.getMode());
+        return data;
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String,Object> startSession(String id,VideoRequests.Range range,Long userId,String anonymousTokenHash) {
+        // Managed or legacy ACTIVE LIVE streams must join through coordinated adoption,
+        // never another blind proxy start. No device lock is held before this I/O path.
+        if(range==null && managedLivePresent(id))return startManagedCompatibility(id,userId,anonymousTokenHash);
         VideoDeviceRecord row=find(id);
         VideoDeviceRecord row=find(id);
         sessions.lockVideo(id);
         sessions.lockVideo(id);
+        // A generation may have been created between the optimistic read and this lock.
+        // Fail safely instead of starting the old physical stream over a new generation.
+        if(range==null && managedLivePresent(id))throw new ServiceException("视频代次已变化,请重试播放");
         String mode=range==null?"LIVE":"PLAYBACK";
         String mode=range==null?"LIVE":"PLAYBACK";
-        Object response;
+        // Capture under the video lock, before an insert error can abort the DB transaction.
+        long existingLive=range==null?activeLiveCount(id,null):0;
         if(range!=null) {
         if(range!=null) {
             requireGb(row);
             requireGb(row);
             validateRange(range);
             validateRange(range);
             if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getMode,"PLAYBACK").eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("此通道已有录像回放,请结束后重试");
             if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getMode,"PLAYBACK").eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("此通道已有录像回放,请结束后重试");
-            response=collector.get("/api/playback/start",rangeParams(row,range));
-        }
-        else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
-        else {
-            validateManualUrl(row.getVideoUrl());
-            String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
-            response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
-        }
-        if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
-        Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
+        } else if(!GB28181.equals(row.getSourceType()))validateManualUrl(row.getVideoUrl());
         VideoSession session=new VideoSession();
         VideoSession session=new VideoSession();
         session.setSessionId(UUID.randomUUID().toString());
         session.setSessionId(UUID.randomUUID().toString());
         session.setVideoId(id);
         session.setVideoId(id);
-        session.setUserId(SecurityUtils.getUserId());
+        session.setUserId(userId);
+        session.setAnonymousTokenHash(anonymousTokenHash);
         session.setMode(mode);
         session.setMode(mode);
         session.setStatus("ACTIVE");
         session.setStatus("ACTIVE");
-        session.setGbDeviceId(row.getGbDeviceId());
-        session.setGbChannelId(row.getGbChannelId());
-        session.setStreamId((String)data.get("stream"));
-        session.setProxyKey((String)data.remove("proxyKey"));
-        session.setCreateTime(LocalDateTime.now());
+        session.setGbDeviceId(GB28181.equals(row.getSourceType())?row.getGbDeviceId():null);
+        session.setGbChannelId(GB28181.equals(row.getSourceType())?row.getGbChannelId():null);
+        session.setCreateTime(LocalDateTime.now(clock));
         session.setLastSeen(session.getCreateTime());
         session.setLastSeen(session.getCreateTime());
-        sessions.insert(session);
-        data.put("sessionId",session.getSessionId());
-        data.put("mode",mode);
-        return data;
+        boolean deferredCleanup=false;
+        boolean responseReceived=false;
+        boolean mediaAttempted=false;
+        boolean nativeStream=!GB28181.equals(row.getSourceType())&&!URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT).startsWith("rt");
+        try {
+            deferredCleanup=cleanupOnRollback(session,nativeStream);
+            mediaAttempted=true;
+            Object response;
+            if(range!=null)response=collector.get("/api/playback/start",rangeParams(row,range));
+            else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
+            else {
+                String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
+                response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
+            }
+            responseReceived=true;
+            if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
+            Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
+            session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
+            Object mediaServerId = data.remove("mediaServerId");
+            session.setMediaServerId(mediaServerId instanceof String ? (String) mediaServerId : null);
+            Object proxyKey=data.remove("proxyKey");
+            session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
+            if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
+                    .map(data::get).anyMatch(VideoDeviceService::isPlayableAddress))throw new ServiceException("媒体服务没有返回有效播放地址");
+            if(!nativeStream)safeStream(session.getStreamId());
+            if(!GB28181.equals(row.getSourceType())&&!nativeStream&&(session.getProxyKey()==null||session.getProxyKey().isBlank()))
+                throw new ServiceException("媒体服务没有返回代理清理标识");
+            if(!nativeStream)data.remove("native");
+            if(sessions.insert(session)!=1)throw new ServiceException("播放会话登记失败");
+            data.put("sessionId",session.getSessionId());
+            data.put("mode",mode);
+            return data;
+        } catch(RuntimeException registrationFailure) {
+            if(!mediaAttempted)throw registrationFailure;
+            if(deferredCleanup)throw new ServiceException("视频启动或会话登记失败,媒体清理结果未确认");
+            try { stopMedia(session,existingLive); }
+            catch(RuntimeException cleanupFailure) {
+                log.warn("视频会话登记失败且媒体清理未确认: {}",session.getSessionId());
+                throw new ServiceException("播放会话登记失败,媒体清理未确认,请联系管理员");
+            }
+            throw new ServiceException(responseReceived?"播放会话登记失败":"视频启动失败,媒体结果与清理未确认");
+        }
+    }
+
+    private boolean managedLivePresent(String videoId) {
+        return !sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId,videoId).eq(VideoSession::getMode,"LIVE")
+                .in(VideoSession::getStatus,"STARTING","ACTIVE","CLEANUP_PENDING")
+                .and(q -> q.isNotNull(VideoSession::getMediaGeneration).or().eq(VideoSession::getStatus,"ACTIVE"))).isEmpty();
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String,Object> startManagedCompatibility(String videoId,Long userId,String tokenHash) {
+        VideoSession prepared=liveLifecycle.prepare(videoId,userId,tokenHash);
+        java.util.function.Supplier<VideoSession> current=() -> sessions.selectById(prepared.getSessionId());
+        Map<String,Object> state;
+        try {
+            state=liveLifecycle.start(current);
+            if(!"ACTIVE".equals(state.get("status")) || !(state.get("media") instanceof Map))
+                throw new ServiceException("视频尚未就绪,请等待回收后重试");
+        } catch(RuntimeException failure) {
+            try { liveLifecycle.stop(current); } catch(RuntimeException cleanupUnknown) { failure.addSuppressed(cleanupUnknown); }
+            throw failure;
+        }
+        Map<String,Object> result=new HashMap<>((Map<String,Object>)state.get("media"));
+        result.remove("proxyKey"); result.remove("mediaServerId");
+        result.put("sessionId",prepared.getSessionId()); result.put("mode","LIVE");
+        return result;
+    }
+
+    private boolean cleanupOnRollback(VideoSession session,boolean nativeStream) {
+        if(!TransactionSynchronizationManager.isActualTransactionActive())return false;
+        if(rollbackCleanup==null||!TransactionSynchronizationManager.isSynchronizationActive())
+            throw new ServiceException("视频事务清理未配置");
+        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+            @Override public void afterCompletion(int status) {
+                if(status==STATUS_COMMITTED||nativeStream)return;
+                try {
+                    rollbackCleanup.execute(cleanupStatus -> {
+                        sessions.lockVideo(session.getVideoId());
+                        // A commit with an uncertain acknowledgement may have persisted the session.
+                        // Keep it for the ordinary heartbeat reaper, never stop a registered viewer.
+                        if(sessions.selectById(session.getSessionId())!=null)return null;
+                        if("PLAYBACK".equals(session.getMode())&&sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                                .eq(VideoSession::getVideoId,session.getVideoId()).eq(VideoSession::getMode,"PLAYBACK")
+                                .eq(VideoSession::getStatus,"ACTIVE"))>0)return null;
+                        long others=activeLiveCount(session.getVideoId(),null);
+                        if(others==0&&session.getGbDeviceId()==null&&session.getProxyKey()==null)
+                            throw new ServiceException("未取得代理清理标识,媒体资源需人工核查");
+                        stopMedia(session,others);
+                        return null;
+                    });
+                } catch(RuntimeException cleanupFailure) {
+                    log.warn("视频事务结束后媒体清理未确认,需人工核查: {}",session.getSessionId());
+                }
+            }
+        });
+        return true;
     }
     }
 
 
     public Object records(String id,VideoRequests.Range range) {
     public Object records(String id,VideoRequests.Range range) {
@@ -180,42 +353,142 @@ public class VideoDeviceService {
         requireGb(row);
         requireGb(row);
         collector.get("/api/front-end/ptz/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of("command",input.getCommand(),"horizonSpeed",input.getSpeed(),"verticalSpeed",input.getSpeed(),"zoomSpeed",input.getZoomSpeed()));
         collector.get("/api/front-end/ptz/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of("command",input.getCommand(),"horizonSpeed",input.getSpeed(),"verticalSpeed",input.getSpeed(),"zoomSpeed",input.getZoomSpeed()));
     }
     }
+    /** Checks only ownership and watching validity, not device capability or exclusive PTZ rights. */
+    public void requireAnonymousSession(String id,String token,String videoId,String mode) {
+        VideoSession s=ownedAnonymous(id,token);
+        requireActiveAnonymous(s);
+        if(!Objects.equals(videoId,s.getVideoId())||!Objects.equals(mode,s.getMode()))throw new ServiceException("播放会话与设备或播放模式不匹配");
+    }
+
+    private void requireActiveAnonymous(VideoSession s) {
+        if(!"ACTIVE".equals(s.getStatus())||s.getLastSeen()==null||s.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120)))
+            throw new ServiceException("播放会话已失效");
+    }
+
+    private VideoSession ownedAnonymous(String id,String token) {
+        if(token==null||!token.matches("[A-Za-z0-9_-]{43}"))throw new ServiceException("播放会话不存在或无权操作");
+        VideoSession s=sessions.selectById(id);
+        if(s==null||s.getUserId()!=null||s.getAnonymousTokenHash()==null||!MessageDigest.isEqual(
+                s.getAnonymousTokenHash().getBytes(StandardCharsets.US_ASCII),
+                tokenHash(token).getBytes(StandardCharsets.US_ASCII)))throw new ServiceException("播放会话不存在或无权操作");
+        return s;
+    }
+
+    private static boolean isPlayableAddress(Object value) {
+        if(!(value instanceof String))return false;
+        try {
+            URI uri=URI.create((String)value);
+            return uri.getHost()!=null&&uri.getScheme()!=null&&Set.of("http","https","ws","wss").contains(uri.getScheme().toLowerCase(Locale.ROOT));
+        } catch(IllegalArgumentException invalid) { return false; }
+    }
+
+    private static String tokenHash(String token) {
+        try {
+            return Base64.getUrlEncoder().withoutPadding().encodeToString(
+                    MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII)));
+        } catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
+    }
+
+    private VideoSession activeAnonymousLocked(String id,String token) {
+        VideoSession session=ownedAnonymous(id,token);
+        sessions.lockVideo(session.getVideoId());
+        session=ownedAnonymous(id,token);
+        requireActiveAnonymous(session);
+        return session;
+    }
+
+    @Transactional
+    public void heartbeat(String id,String token) {
+        VideoSession s=activeAnonymousLocked(id,token);
+        s.setLastSeen(LocalDateTime.now(clock));
+        sessions.updateById(s);
+    }
+
+    public void stop(String id,String token) {
+        finish(ownedAnonymous(id,token));
+    }
+
     private VideoSession owned(String id) {
     private VideoSession owned(String id) {
         VideoSession s=sessions.selectById(id);
         VideoSession s=sessions.selectById(id);
-        if(s==null||!Objects.equals(s.getUserId(),SecurityUtils.getUserId()))throw new ServiceException("播放会话不存在或无权操作");
+        if(s==null||s.getAnonymousTokenHash()!=null||s.getUserId()==null||!Objects.equals(s.getUserId(),SecurityUtils.getUserId()))throw new ServiceException("播放会话不存在或无权操作");
         return s;
         return s;
     }
     }
     @Transactional
     @Transactional
 
 
     public void heartbeat(String id) {
     public void heartbeat(String id) {
         VideoSession s=owned(id);
         VideoSession s=owned(id);
+        sessions.lockVideo(s.getVideoId());
+        s=owned(id);
         if("ACTIVE".equals(s.getStatus())) {
         if("ACTIVE".equals(s.getStatus())) {
-            s.setLastSeen(LocalDateTime.now());
+            s.setLastSeen(LocalDateTime.now(clock));
             sessions.updateById(s);
             sessions.updateById(s);
         }
         }
     }
     }
-    @Transactional
-
     public void stop(String id) {
     public void stop(String id) {
         finish(owned(id));
         finish(owned(id));
     }
     }
     private void finish(VideoSession session) {
     private void finish(VideoSession session) {
-        if(!"ACTIVE".equals(session.getStatus()))return;
-        sessions.lockVideo(session.getVideoId());
-        VideoSession current=sessions.selectById(session.getSessionId());
-        if(current==null||!"ACTIVE".equals(current.getStatus()))return;
-        long others=sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,session.getVideoId()).eq(VideoSession::getStatus,"ACTIVE").eq(VideoSession::getMode,"LIVE").ne(VideoSession::getSessionId,session.getSessionId()));
+        finish(session,null);
+    }
+
+    private void finish(VideoSession session,LocalDateTime expiredBefore) {
+        // The old user stop can race with adoption into a managed generation. Decide only
+        // after a fresh locked read, then release this transaction before lifecycle I/O.
+        java.util.function.Supplier<VideoSession> releaseLegacy = () -> {
+            sessions.lockVideo(session.getVideoId());
+            VideoSession current=sessions.selectById(session.getSessionId());
+            if(current==null)return null;
+            if("LIVE".equals(current.getMode()) && (current.getMediaGeneration()!=null
+                    || Set.of("PREPARED", "STARTING", "CLEANUP_PENDING").contains(current.getStatus()))) return current;
+            if(!"ACTIVE".equals(current.getStatus()))return null;
+            if(expiredBefore!=null&&current.getLastSeen()!=null&&!current.getLastSeen().isBefore(expiredBefore))return null;
+            stopMedia(current,activeLiveCount(current.getVideoId(),current.getSessionId()));
+            current.setStatus("STOPPED");
+            current.setEndTime(LocalDateTime.now(clock));
+            if(sessions.updateById(current)!=1)throw new ServiceException("播放会话状态登记失败");
+            return null;
+        };
+        VideoSession managed = rollbackCleanup == null ? releaseLegacy.get()
+                : rollbackCleanup.execute(transaction -> releaseLegacy.get());
+        if(managed!=null) {
+            java.util.function.Supplier<VideoSession> current = () -> sessions.selectById(managed.getSessionId());
+            Map<String,Object> result = expiredBefore==null ? liveLifecycle.stop(current) : liveLifecycle.expire(current);
+            if(expiredBefore==null && "CLEANUP_PENDING".equals(result.get("status")))
+                throw new ServiceException("媒体清理未确认,请等待回收");
+        }
+    }
+
+    private long activeLiveCount(String videoId,String excludingSessionId) {
+        return sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,videoId)
+                .in(VideoSession::getStatus,"STARTING","ACTIVE","CLEANUP_PENDING").eq(VideoSession::getMode,"LIVE")
+                .ne(excludingSessionId!=null,VideoSession::getSessionId,excludingSessionId));
+    }
+
+    // No DB access: compensation must also work after a failed SQL statement.
+    private void stopMedia(VideoSession session,long others) {
         if("PLAYBACK".equals(session.getMode()))collector.get("/api/playback/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId()+"/"+safeStream(session.getStreamId()),Map.of());
         if("PLAYBACK".equals(session.getMode()))collector.get("/api/playback/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId()+"/"+safeStream(session.getStreamId()),Map.of());
         else if(others==0&&session.getGbDeviceId()!=null)collector.get("/api/play/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId(),Map.of());
         else if(others==0&&session.getGbDeviceId()!=null)collector.get("/api/play/stop/"+session.getGbDeviceId()+"/"+session.getGbChannelId(),Map.of());
-        else if(others==0&&session.getProxyKey()!=null)collector.post("/internal/video/manual/stop",Map.of("key",session.getProxyKey()));
-        current.setStatus("STOPPED");
-        current.setEndTime(LocalDateTime.now());
-        sessions.updateById(current);
+        else if(others==0&&session.getProxyKey()!=null) {
+            Map<String,Object> body=new LinkedHashMap<>();
+            body.put("key",session.getProxyKey());
+            if(session.getMediaServerId()!=null&&!session.getMediaServerId().isBlank())
+                body.put("mediaServerId",session.getMediaServerId());
+            collector.post("/internal/video/manual/stop",body);
+        }
+    }
+
+    @Transactional
+    public void control(String id,String token,VideoRequests.Control input) {
+        controlSession(activeAnonymousLocked(id,token),input);
     }
     }
 
 
     public void control(String id,VideoRequests.Control input) {
     public void control(String id,VideoRequests.Control input) {
-        VideoSession s=owned(id);
+        controlSession(owned(id),input);
+    }
+
+    private void controlSession(VideoSession s,VideoRequests.Control input) {
         if(!"ACTIVE".equals(s.getStatus())||!"PLAYBACK".equals(s.getMode()))throw new ServiceException("没有正在进行的录像回放");
         if(!"ACTIVE".equals(s.getStatus())||!"PLAYBACK".equals(s.getMode()))throw new ServiceException("没有正在进行的录像回放");
+        if(input==null||input.getAction()==null||!Set.of("pause","resume","speed","seek").contains(input.getAction()))throw new ServiceException("不支持的回放控制操作");
         String suffix="";
         String suffix="";
         if("speed".equals(input.getAction())) {
         if("speed".equals(input.getAction())) {
             if(input.getValue()==null||!Set.of(0.25,0.5,1.0,2.0,4.0).contains(input.getValue()))throw new ServiceException("回放速度支持 0.25、0.5、1、2、4 倍");
             if(input.getValue()==null||!Set.of(0.25,0.5,1.0,2.0,4.0).contains(input.getValue()))throw new ServiceException("回放速度支持 0.25、0.5、1、2、4 倍");
@@ -228,9 +501,12 @@ public class VideoDeviceService {
         collector.get("/api/playback/"+input.getAction()+"/"+safeStream(s.getStreamId())+suffix,Map.of());
         collector.get("/api/playback/"+input.getAction()+"/"+safeStream(s.getStreamId())+suffix,Map.of());
     }
     }
     @Scheduled(fixedDelay=30000)
     @Scheduled(fixedDelay=30000)
-    @Transactional public void expireSessions() {
-        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getStatus,"ACTIVE").lt(VideoSession::getLastSeen,LocalDateTime.now().minusSeconds(120))))try {
-            finish(s);
+    public void expireSessions() {
+        LocalDateTime expiredBefore=LocalDateTime.now(clock).minusSeconds(120);
+        // Select nonterminal candidates only; HTTP and the locked recheck use this same policy.
+        for(VideoSession s:sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .in(VideoSession::getStatus,"ACTIVE","PREPARED","STARTING","CLEANUP_PENDING")))try {
+            if(liveLifecycle.shouldExpire(s))finish(s,expiredBefore);
         }
         }
         catch(Exception e) {
         catch(Exception e) {
             log.warn("视频会话回收失败,稍后重试: {}",s.getSessionId());
             log.warn("视频会话回收失败,稍后重试: {}",s.getSessionId());
@@ -242,7 +518,9 @@ public class VideoDeviceService {
         return row;
         return row;
     }
     }
     private void ensureIdle(String id) {
     private void ensureIdle(String id) {
-        if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("设备正在播放,请结束播放后再修改或移除");
+        if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id)
+                .in(VideoSession::getStatus,"PREPARED","STARTING","ACTIVE","CLEANUP_PENDING"))>0)
+            throw new ServiceException("设备正在播放或等待回收,请结束播放后再修改或移除");
     }
     }
 
 
     static void requireGbId(String value) {
     static void requireGbId(String value) {

+ 13 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoSession.java

@@ -10,12 +10,25 @@ public class VideoSession {
     @TableId(type=IdType.INPUT) private String sessionId;
     @TableId(type=IdType.INPUT) private String sessionId;
     private String videoId;
     private String videoId;
     private Long userId;
     private Long userId;
+    // Anonymous ownership is independent of business users; the bearer token is never persisted.
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    @lombok.ToString.Exclude
+    private String anonymousTokenHash;
     private String mode;
     private String mode;
     private String streamId;
     private String streamId;
     private String proxyKey;
     private String proxyKey;
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    private String mediaServerId;
     private String gbDeviceId;
     private String gbDeviceId;
     private String gbChannelId;
     private String gbChannelId;
     private String status;
     private String status;
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    @lombok.ToString.Exclude
+    private String mediaGeneration;
+    private LocalDateTime startDeadline;
     private LocalDateTime createTime;
     private LocalDateTime createTime;
     private LocalDateTime lastSeen;
     private LocalDateTime lastSeen;
     private LocalDateTime endTime;
     private LocalDateTime endTime;

+ 30 - 4
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/event/BusinessCockpitEventAdapter.java

@@ -21,6 +21,7 @@ import com.zksy.cockpit.foundation.CockpitDistrict;
 import com.zksy.cockpit.foundation.CockpitTypeIndustry;
 import com.zksy.cockpit.foundation.CockpitTypeIndustry;
 import com.zksy.ops.domain.WorkOrder;
 import com.zksy.ops.domain.WorkOrder;
 import com.zksy.ops.service.WorkOrderService;
 import com.zksy.ops.service.WorkOrderService;
+import com.zksy.system.mapper.SysDictDataMapper;
 import org.springframework.context.annotation.Primary;
 import org.springframework.context.annotation.Primary;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
@@ -71,6 +72,7 @@ public class BusinessCockpitEventAdapter {
     private final WarningTypeMapper refWarningTypeMapper;
     private final WarningTypeMapper refWarningTypeMapper;
     private final AlarmWarningRelMapper alarmWarningRelMapper;
     private final AlarmWarningRelMapper alarmWarningRelMapper;
     private final WorkOrderService workOrderService;
     private final WorkOrderService workOrderService;
+    private final SysDictDataMapper sysDictDataMapper;
     private final Clock clock;
     private final Clock clock;
     private Map<Integer, WarningType> warningTypeById = Collections.emptyMap();
     private Map<Integer, WarningType> warningTypeById = Collections.emptyMap();
 
 
@@ -84,6 +86,7 @@ public class BusinessCockpitEventAdapter {
             WarningTypeMapper refWarningTypeMapper,
             WarningTypeMapper refWarningTypeMapper,
             AlarmWarningRelMapper alarmWarningRelMapper,
             AlarmWarningRelMapper alarmWarningRelMapper,
             WorkOrderService workOrderService,
             WorkOrderService workOrderService,
+            SysDictDataMapper sysDictDataMapper,
             Clock clock) {
             Clock clock) {
         this.equipmentBaseService = equipmentBaseService;
         this.equipmentBaseService = equipmentBaseService;
         this.equipmentTypeService = equipmentTypeService;
         this.equipmentTypeService = equipmentTypeService;
@@ -94,6 +97,7 @@ public class BusinessCockpitEventAdapter {
         this.refWarningTypeMapper = refWarningTypeMapper;
         this.refWarningTypeMapper = refWarningTypeMapper;
         this.alarmWarningRelMapper = alarmWarningRelMapper;
         this.alarmWarningRelMapper = alarmWarningRelMapper;
         this.workOrderService = workOrderService;
         this.workOrderService = workOrderService;
+        this.sysDictDataMapper = sysDictDataMapper;
         this.clock = clock;
         this.clock = clock;
     }
     }
 
 
@@ -216,11 +220,17 @@ public class BusinessCockpitEventAdapter {
             List<WarningFact> warnings,
             List<WarningFact> warnings,
             List<AlarmFact> alarms,
             List<AlarmFact> alarms,
             Integer total) {
             Integer total) {
+        // 等级名称按族批量取一次字典(每族每请求一次 selectDictDataByType),不逐事件回查;
+        // 该族没有事件时不查库。
+        Map<Integer, String> alertLevelLabels = warnings.isEmpty() ? Collections.emptyMap()
+                : CockpitEventLevelName.labels(sysDictDataMapper, CockpitEventLevelName.WARNING_LEVEL_DICT);
+        Map<Integer, String> alarmLevelLabels = alarms.isEmpty() ? Collections.emptyMap()
+                : CockpitEventLevelName.labels(sysDictDataMapper, CockpitEventLevelName.ALARM_LEVEL_DICT);
         List<CockpitEventWarning> warningItems = warnings.stream()
         List<CockpitEventWarning> warningItems = warnings.stream()
-                .map(item -> toEventWarning(item, facts))
+                .map(item -> toEventWarning(item, facts, alertLevelLabels))
                 .collect(Collectors.toList());
                 .collect(Collectors.toList());
         List<CockpitEventAlarm> alarmItems = alarms.stream()
         List<CockpitEventAlarm> alarmItems = alarms.stream()
-                .map(item -> toEventAlarm(item, facts))
+                .map(item -> toEventAlarm(item, facts, alarmLevelLabels))
                 .collect(Collectors.toList());
                 .collect(Collectors.toList());
         return new CockpitEventSnapshot(
         return new CockpitEventSnapshot(
                 device.getEquipmentCode().trim(),
                 device.getEquipmentCode().trim(),
@@ -232,7 +242,8 @@ public class BusinessCockpitEventAdapter {
                 total);
                 total);
     }
     }
 
 
-    private CockpitEventWarning toEventWarning(WarningFact item, Facts facts) {
+    private CockpitEventWarning toEventWarning(
+            WarningFact item, Facts facts, Map<Integer, String> alertLevelLabels) {
         EarlyWarning warning = item.warning;
         EarlyWarning warning = item.warning;
         PointFact point = facts.pointsByDevice.get(normalize(warning.getDeviceCode()));
         PointFact point = facts.pointsByDevice.get(normalize(warning.getDeviceCode()));
         return new CockpitEventWarning(
         return new CockpitEventWarning(
@@ -241,6 +252,9 @@ public class BusinessCockpitEventAdapter {
                 trimToNull(warning.getWarningType()),
                 trimToNull(warning.getWarningType()),
                 level(warning.getWarningLevel()),
                 level(warning.getWarningLevel()),
                 CockpitEventLevelColor.resolve(warning.getWarningLevel()),
                 CockpitEventLevelColor.resolve(warning.getWarningLevel()),
+                CockpitEventLevelName.warningOf(level(warning.getWarningLevel()), alertLevelLabels),
+                // 描述原文来自同一条已加载的 early_warning 行,原样透传,不二次格式化。
+                contentOrNull(warning.getWarningContent()),
                 trimToNull(warning.getStatus()),
                 trimToNull(warning.getStatus()),
                 offsetTime(warning.getPublishTime()),
                 offsetTime(warning.getPublishTime()),
                 null,
                 null,
@@ -250,7 +264,8 @@ public class BusinessCockpitEventAdapter {
                 point == null ? null : point.location);
                 point == null ? null : point.location);
     }
     }
 
 
-    private CockpitEventAlarm toEventAlarm(AlarmFact item, Facts facts) {
+    private CockpitEventAlarm toEventAlarm(
+            AlarmFact item, Facts facts, Map<Integer, String> alarmLevelLabels) {
         AlarmData alarm = item.alarm;
         AlarmData alarm = item.alarm;
         PointFact point = facts.pointsByDevice.get(normalize(alarm.getDeviceCode()));
         PointFact point = facts.pointsByDevice.get(normalize(alarm.getDeviceCode()));
         EquipmentWarningType metadata = warningType(alarm, facts);
         EquipmentWarningType metadata = warningType(alarm, facts);
@@ -261,6 +276,9 @@ public class BusinessCockpitEventAdapter {
                 null,
                 null,
                 level(alarm.getAlarmLevel()),
                 level(alarm.getAlarmLevel()),
                 CockpitEventLevelColor.resolve(alarm.getAlarmLevel()),
                 CockpitEventLevelColor.resolve(alarm.getAlarmLevel()),
+                CockpitEventLevelName.alarmOf(level(alarm.getAlarmLevel()), alarmLevelLabels),
+                // 描述原文来自同一条已加载的 alarm_data 行,原样透传,不二次格式化。
+                contentOrNull(alarm.getAlarmContent()),
                 alarmStatus(alarm.getAlarmStatus()),
                 alarmStatus(alarm.getAlarmStatus()),
                 offsetTime(alarm.getCreateTime()),
                 offsetTime(alarm.getCreateTime()),
                 alarm.getActualValue(),
                 alarm.getActualValue(),
@@ -887,6 +905,14 @@ public class BusinessCockpitEventAdapter {
         return isBlank(value) ? null : value.trim();
         return isBlank(value) ? null : value.trim();
     }
     }
 
 
+    /**
+     * 入库描述原文:缺行/空白视为「没有描述」回 {@code null},
+     * 有内容时**原样**返回(不 trim、不改换行),保证与管理端展示逐字一致。
+     */
+    private static String contentOrNull(String value) {
+        return isBlank(value) ? null : value;
+    }
+
     private static String firstNonBlank(String first, String second) {
     private static String firstNonBlank(String first, String second) {
         return isBlank(first) ? trimToNull(second) : first.trim();
         return isBlank(first) ? trimToNull(second) : first.trim();
     }
     }

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

@@ -9,6 +9,8 @@ public class CockpitEventAlarm {
     private final String warningType;
     private final String warningType;
     private final Integer level;
     private final Integer level;
     private final String levelColor;
     private final String levelColor;
+    private final String levelName;
+    private final String content;
     private final String status;
     private final String status;
     private final String eventTime;
     private final String eventTime;
     private final BigDecimal value;
     private final BigDecimal value;
@@ -26,6 +28,8 @@ public class CockpitEventAlarm {
             String warningType,
             String warningType,
             Integer level,
             Integer level,
             String levelColor,
             String levelColor,
+            String levelName,
+            String content,
             String status,
             String status,
             String eventTime,
             String eventTime,
             BigDecimal value,
             BigDecimal value,
@@ -41,6 +45,8 @@ public class CockpitEventAlarm {
         this.warningType = warningType;
         this.warningType = warningType;
         this.level = level;
         this.level = level;
         this.levelColor = levelColor;
         this.levelColor = levelColor;
+        this.levelName = levelName;
+        this.content = content;
         this.status = status;
         this.status = status;
         this.eventTime = eventTime;
         this.eventTime = eventTime;
         this.value = value;
         this.value = value;
@@ -58,6 +64,10 @@ public class CockpitEventAlarm {
     public String getWarningType() { return warningType; }
     public String getWarningType() { return warningType; }
     public Integer getLevel() { return level; }
     public Integer getLevel() { return level; }
     public String getLevelColor() { return levelColor; }
     public String getLevelColor() { return levelColor; }
+    /** 等级名称:字典 alarm_level 的 dict_label;缺项回退「N级报警」,等级缺失为 null。 */
+    public String getLevelName() { return levelName; }
+    /** 描述原文:alarm_data.alarm_content 原样透传(含换行),缺失为 null。 */
+    public String getContent() { return content; }
     public String getStatus() { return status; }
     public String getStatus() { return status; }
     public String getEventTime() { return eventTime; }
     public String getEventTime() { return eventTime; }
     public BigDecimal getValue() { return value; }
     public BigDecimal getValue() { return value; }

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

@@ -0,0 +1,106 @@
+package com.zksy.cockpit.event;
+
+import com.zksy.common.core.domain.entity.SysDictData;
+import com.zksy.system.mapper.SysDictDataMapper;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 设备详情预警/报警事件的等级展示名(票:等级显示字典口径)。
+ *
+ * <p>取值与概览模块同一口径:预警取字典 {@code alert_level}、报警取字典 {@code alarm_level}
+ * 的 {@code dict_label};字典缺项按既有「N级预警 / N级报警」兜底(前缀「一/二/三/四」),
+ * 不另造措辞。等级缺失或越界(非 1–4)如实回 {@code null},不伪造。</p>
+ *
+ * <p>字典按请求批量读取一次(每族一次 {@code selectDictDataByType}),不逐事件回查。</p>
+ */
+public final class CockpitEventLevelName {
+    public static final String WARNING_LEVEL_DICT = "alert_level";
+    public static final String ALARM_LEVEL_DICT = "alarm_level";
+    public static final String WARNING_SUFFIX = "预警";
+    public static final String ALARM_SUFFIX = "报警";
+
+    /** 与概览模块 {@code LEVEL_PREFIXES} 同一套中文序号,避免两处措辞分叉。 */
+    private static final String[] LEVEL_PREFIXES = {"一", "二", "三", "四"};
+
+    private CockpitEventLevelName() {
+    }
+
+    /**
+     * 一次取全一族的等级字典({@code dict_value → dict_label})。
+     *
+     * <p>字典只影响展示名:查询异常时退回空表,让事件列表按既有「N级」口径继续下发,
+     * 不因为一个辅助表象把整份事件数据判死。</p>
+     */
+    public static Map<Integer, String> labels(SysDictDataMapper dictMapper, String dictType) {
+        if (dictMapper == null || dictType == null) {
+            return Collections.emptyMap();
+        }
+        try {
+            return labels(dictMapper.selectDictDataByType(dictType));
+        } catch (RuntimeException ignored) {
+            return Collections.emptyMap();
+        }
+    }
+
+    /** 字典行 → 等级标签;仅取 {@code dict_value} 为 1–4 且标签非空的行,重复值保留首条。 */
+    public static Map<Integer, String> labels(List<SysDictData> source) {
+        Map<Integer, String> result = new LinkedHashMap<>();
+        if (source == null) {
+            return result;
+        }
+        for (SysDictData data : source) {
+            if (data == null) {
+                continue;
+            }
+            String label = trimToNull(data.getDictLabel());
+            Integer level = levelOf(data.getDictValue());
+            if (label != null && level != null) {
+                result.putIfAbsent(level, label);
+            }
+        }
+        return result;
+    }
+
+    /** 等级展示名:字典有标签用标签,缺项回退「N级<suffix>」;等级为空/越界回 {@code null}。 */
+    public static String of(Integer level, Map<Integer, String> dictLabels, String suffix) {
+        if (level == null || level < 1 || level > 4) {
+            return null;
+        }
+        String label = dictLabels == null ? null : trimToNull(dictLabels.get(level));
+        if (label != null) {
+            return label;
+        }
+        return LEVEL_PREFIXES[level - 1] + "级" + suffix;
+    }
+
+    /** 预警族:{@code alert_level} + 「N级预警」兜底。 */
+    public static String warningOf(Integer level, Map<Integer, String> alertLevelLabels) {
+        return of(level, alertLevelLabels, WARNING_SUFFIX);
+    }
+
+    /** 报警族:{@code alarm_level} + 「N级报警」兜底。 */
+    public static String alarmOf(Integer level, Map<Integer, String> alarmLevelLabels) {
+        return of(level, alarmLevelLabels, ALARM_SUFFIX);
+    }
+
+    private static Integer levelOf(String value) {
+        String normalized = trimToNull(value);
+        if (normalized == null) {
+            return null;
+        }
+        try {
+            int resolved = Integer.parseInt(normalized);
+            return resolved >= 1 && resolved <= 4 ? resolved : null;
+        } catch (NumberFormatException ignored) {
+            return null;
+        }
+    }
+
+    private static String trimToNull(String value) {
+        return value == null || value.trim().isEmpty() ? null : value.trim();
+    }
+}

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

@@ -120,8 +120,9 @@ public class CockpitEventReadService {
             }
             }
             result.add(new CockpitEventWarning(
             result.add(new CockpitEventWarning(
                     item.getWarningNo(), item.getWarningName(), item.getWarningType(), item.getLevel(),
                     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()));
+                    CockpitEventLevelColor.resolve(item.getLevel()), item.getLevelName(), item.getContent(),
+                    item.getStatus(), item.getEventTime(), item.getValue(), item.getUnit(),
+                    item.getDeviceCode(), item.getDeviceName(), item.getLocation()));
         }
         }
         return result;
         return result;
     }
     }
@@ -134,9 +135,10 @@ public class CockpitEventReadService {
             }
             }
             result.add(new CockpitEventAlarm(
             result.add(new CockpitEventAlarm(
                     item.getAlarmId(), item.getWarningCode(), item.getWarningName(), item.getWarningType(),
                     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()));
+                    item.getLevel(), CockpitEventLevelColor.resolve(item.getLevel()), item.getLevelName(),
+                    item.getContent(), item.getStatus(), item.getEventTime(), item.getValue(),
+                    item.getThresholdMinValue(), item.getThresholdMaxValue(), item.getUnit(),
+                    item.getDeviceCode(), item.getDeviceName(), item.getLocation()));
         }
         }
         return result;
         return result;
     }
     }

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

@@ -8,6 +8,8 @@ public class CockpitEventWarning {
     private final String warningType;
     private final String warningType;
     private final Integer level;
     private final Integer level;
     private final String levelColor;
     private final String levelColor;
+    private final String levelName;
+    private final String content;
     private final String status;
     private final String status;
     private final String eventTime;
     private final String eventTime;
     private final BigDecimal value;
     private final BigDecimal value;
@@ -22,6 +24,8 @@ public class CockpitEventWarning {
             String warningType,
             String warningType,
             Integer level,
             Integer level,
             String levelColor,
             String levelColor,
+            String levelName,
+            String content,
             String status,
             String status,
             String eventTime,
             String eventTime,
             BigDecimal value,
             BigDecimal value,
@@ -34,6 +38,8 @@ public class CockpitEventWarning {
         this.warningType = warningType;
         this.warningType = warningType;
         this.level = level;
         this.level = level;
         this.levelColor = levelColor;
         this.levelColor = levelColor;
+        this.levelName = levelName;
+        this.content = content;
         this.status = status;
         this.status = status;
         this.eventTime = eventTime;
         this.eventTime = eventTime;
         this.value = value;
         this.value = value;
@@ -48,6 +54,10 @@ public class CockpitEventWarning {
     public String getWarningType() { return warningType; }
     public String getWarningType() { return warningType; }
     public Integer getLevel() { return level; }
     public Integer getLevel() { return level; }
     public String getLevelColor() { return levelColor; }
     public String getLevelColor() { return levelColor; }
+    /** 等级名称:字典 alert_level 的 dict_label;缺项回退「N级预警」,等级缺失为 null。 */
+    public String getLevelName() { return levelName; }
+    /** 描述原文:early_warning.warning_content 原样透传(含换行),缺失为 null。 */
+    public String getContent() { return content; }
     public String getStatus() { return status; }
     public String getStatus() { return status; }
     public String getEventTime() { return eventTime; }
     public String getEventTime() { return eventTime; }
     public BigDecimal getValue() { return value; }
     public BigDecimal getValue() { return value; }

+ 21 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/overview/CockpitOverviewModulesService.java

@@ -53,6 +53,15 @@ public class CockpitOverviewModulesService {
     // 排行不再截断(维护者 2026-10-26:近 30 日共 27 起,页面只列出 14+6+3=23 起,读者对不上数)。
     // 排行不再截断(维护者 2026-10-26:近 30 日共 27 起,页面只列出 14+6+3=23 起,读者对不上数)。
     // 保留常量为 0 表达「全部」,比删掉更明确 —— 调用点读到它就知道这是刻意口径。
     // 保留常量为 0 表达「全部」,比删掉更明确 —— 调用点读到它就知道这是刻意口径。
     private static final int RANKING_TOP_SIZE = 0;
     private static final int RANKING_TOP_SIZE = 0;
+    /**
+     * 类型排行里代表「预警类型未填」的占位码(mapper 把空 / NULL 归入它)。
+     *
+     * 为什么需要它:{@code warning_type} 是 NOT NULL 但可为空串。旧实现让空串单独成一行,
+     * 服务层又把空 code 丢掉,于是「近30日共 XX 起」总是大于各行之和(维护者 2026-11-12)。
+     * 归一个显式占位码后行之和与 total 同源;界面用中文名,不露码值。
+     */
+    private static final String UNKNOWN_WARNING_TYPE = "UNKNOWN";
+    private static final String UNKNOWN_WARNING_TYPE_NAME = "未分类";
     private static final int TREND_DAYS = 7;
     private static final int TREND_DAYS = 7;
     private static final int WORK_ORDER_CLOSED = 5;
     private static final int WORK_ORDER_CLOSED = 5;
     private static final int OPER_TYPE_RECEIVE = 2;
     private static final int OPER_TYPE_RECEIVE = 2;
@@ -404,7 +413,7 @@ public class CockpitOverviewModulesService {
                 snapshot == null ? null : snapshot.getTypeCounts())) {
                 snapshot == null ? null : snapshot.getTypeCounts())) {
             String code = row.getTypeCode();
             String code = row.getTypeCode();
             top.add(new CockpitOverviewWarningStudyResponse.TopType(
             top.add(new CockpitOverviewWarningStudyResponse.TopType(
-                    code, typeName(code, typeNames, normalizedNames), row.getCount()));
+                    code, rankingTypeName(code, typeNames, normalizedNames), row.getCount()));
         }
         }
 
 
         int rankingTotal = snapshot == null ? 0 : snapshot.getRankingTotal();
         int rankingTotal = snapshot == null ? 0 : snapshot.getRankingTotal();
@@ -661,6 +670,17 @@ public class CockpitOverviewModulesService {
         return result;
         return result;
     }
     }
 
 
+    /**
+     * 排行行的展示名:占位码给中文名(界面不露码值),其余沿用 warning_type 词表的降级链。
+     */
+    private static String rankingTypeName(
+            String code, Map<String, String> typeNames, Map<String, String> normalizedNames) {
+        if (UNKNOWN_WARNING_TYPE.equals(code)) {
+            return UNKNOWN_WARNING_TYPE_NAME;
+        }
+        return typeName(code, typeNames, normalizedNames);
+    }
+
     private static String typeName(
     private static String typeName(
             String code, Map<String, String> typeNames, Map<String, String> normalizedNames) {
             String code, Map<String, String> typeNames, Map<String, String> normalizedNames) {
         String name = code == null ? null : typeNames.get(code);
         String name = code == null ? null : typeNames.get(code);

+ 16 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoException.java

@@ -0,0 +1,16 @@
+package com.zksy.cockpit.video;
+
+/** Deliberately contains only public, fixed error text; never wraps transport details. */
+public class CockpitVideoException extends RuntimeException {
+    private final int status;
+    private final String category;
+
+    public CockpitVideoException(int status, String category, String message) {
+        super(message);
+        this.status = status;
+        this.category = category;
+    }
+
+    public int getStatus() { return status; }
+    public String getCategory() { return category; }
+}

+ 69 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoMedia.java

@@ -0,0 +1,69 @@
+package com.zksy.cockpit.video;
+
+import com.zksy.base.video.VideoDeviceRecord;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/** Public media allowlist, not a copy of the collector's response or credentials. */
+final class CockpitVideoMedia {
+    private CockpitVideoMedia() { }
+
+    static Map<String, Object> publish(Map<String, Object> source, VideoDeviceRecord binding) {
+        Map<String, Object> media = new LinkedHashMap<>();
+        for (String field : Set.of("url", "flv", "https_flv", "ws_flv", "wss_flv", "hls", "https_hls", "webrtc")) {
+            Object value = source.get(field);
+            if (value instanceof String && publicAddress((String) value)) media.put(field, value);
+        }
+        // StreamContent publishes rtc/rtcs, while the cockpit exposes one WebRTC endpoint.
+        for (String field : new String[]{"rtcs", "rtc"}) {
+            Object value = source.get(field);
+            if (!media.containsKey("webrtc") && value instanceof String && publicAddress((String) value))
+                media.put("webrtc", value);
+        }
+        if (!media.isEmpty()) media.put("native", "MANUAL".equals(binding.getSourceType())
+                && nativeAddress(binding.getVideoUrl()) && binding.getVideoUrl().equals(media.get("url")));
+        return media;
+    }
+
+    static boolean manualSupported(String address) {
+        if (nativeAddress(address)) return true;
+        try {
+            URI uri = URI.create(address);
+            return uri.getHost() != null && Set.of("rtsp", "rtsps", "rtmp", "rtmps").contains(uri.getScheme().toLowerCase(Locale.ROOT));
+        } catch (RuntimeException invalid) { return false; }
+    }
+
+    private static boolean nativeAddress(String address) {
+        if (!publicAddress(address)) return false;
+        URI uri = URI.create(address);
+        String path = uri.getPath().toLowerCase(Locale.ROOT);
+        return Set.of("http", "https").contains(uri.getScheme().toLowerCase(Locale.ROOT))
+                && (path.endsWith(".mp4") || path.endsWith(".webm") || path.endsWith(".ogv")
+                || path.endsWith(".ogg") || path.endsWith(".m3u8"));
+    }
+
+    private static boolean publicAddress(String address) {
+        try {
+            URI uri = URI.create(address);
+            if (uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null
+                    || !Set.of("http", "https", "ws", "wss").contains(uri.getScheme().toLowerCase(Locale.ROOT))) return false;
+            // Fail closed on unknown query fields: do not silently strip a password/token and publish a broken URL.
+            String query = uri.getRawQuery();
+            if (query != null) for (String entry : query.split("&", -1)) {
+                String[] pair = entry.split("=", 2);
+                if (pair.length != 2) return false;
+                String name = URLDecoder.decode(pair[0], StandardCharsets.UTF_8);
+                String value = URLDecoder.decode(pair[1], StandardCharsets.UTF_8);
+                if (!Set.of("app", "stream", "type", "callId").contains(name)
+                        || !value.matches("[A-Za-z0-9_.:-]{1,200}")) return false;
+                if ("type".equals(name) && !"play".equals(value)) return false;
+            }
+            return true;
+        } catch (RuntimeException invalid) { return false; }
+    }
+}

+ 316 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoService.java

@@ -0,0 +1,316 @@
+package com.zksy.cockpit.video;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoDeviceService;
+import com.zksy.base.video.VideoRequests;
+import com.zksy.common.exception.ServiceException;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/** Resolves business identity without normalizing it or publishing internal ledger/binding fields. */
+@Service
+public class CockpitVideoService {
+    private final EquipmentBaseMapper devices;
+    private final EquipmentVideoBindingMapper bindings;
+    private final VideoDeviceService videos;
+
+    public CockpitVideoService(EquipmentBaseMapper devices, EquipmentVideoBindingMapper bindings, VideoDeviceService videos) {
+        this.devices = devices;
+        this.bindings = bindings;
+        this.videos = videos;
+    }
+
+    public Map<String, Object> device(String code) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        boolean bound = binding != null;
+        boolean live = liveSupported(binding);
+        // Records and playback are properties of a GB28181-bound channel, not of the live probe.
+        boolean records = gbBound(binding);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("typeCode", device.getEquipmentTypeId() == null ? null : device.getEquipmentTypeId().toString());
+        data.put("bound", bound);
+        // playbackControl stays false until a real device confirms pause/speed/seek support.
+        data.put("capabilities", Map.of("live", live, "records", records, "playback", records,
+                "playbackControl", false, "ptz", false, "ptzStopGuaranteed", false));
+        data.put("unavailableReason", live ? null : "设备未绑定或实时视频能力未确认");
+        return data;
+    }
+
+    /** Existing device/NVR recordings in a bounded UTC+8 window; never invents a recording. */
+    public Map<String, Object> records(String code, String startTime, String endTime) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!gbBound(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定国标通道,无法查询录像");
+        VideoRequests.Range range = range(startTime, endTime);
+        Object raw;
+        try {
+            raw = videos.records(device.getEquipmentId(), range);
+        } catch (RuntimeException failure) {
+            if (invalidRange(failure))
+                throw new CockpitVideoException(400, "INVALID_REQUEST", "录像时间格式为 yyyy-MM-dd HH:mm:ss,结束时间须晚于开始时间且范围不超过 7 天");
+            throw new CockpitVideoException(502, "VIDEO_RECORDS_FAILED", "录像查询失败,请稍后重试");
+        }
+        List<Map<String, Object>> items = recordItems(raw);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("startTime", range.getStartTime());
+        data.put("endTime", range.getEndTime());
+        data.put("records", items);
+        // An empty list is a legitimate answer, not a failure.
+        data.put("empty", items.isEmpty());
+        return data;
+    }
+
+    /** Starts an anonymous playback session over one already-listed recording window. */
+    public Map<String, Object> playback(String code, String startTime, String endTime) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!gbBound(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定国标通道,无法回放录像");
+        VideoRequests.Range range = range(startTime, endTime);
+        Map<String, Object> started;
+        try {
+            started = videos.startAnonymous(device.getEquipmentId(), range);
+        } catch (RuntimeException failure) {
+            // A busy channel is an expected, distinguishable outcome, not a broken stream.
+            if (failure.getMessage() != null && failure.getMessage().contains("已有录像回放"))
+                throw new CockpitVideoException(409, "PLAYBACK_OCCUPIED", "此通道已有录像回放,请结束后重试");
+            if (invalidRange(failure))
+                throw new CockpitVideoException(400, "INVALID_REQUEST", "录像时间格式为 yyyy-MM-dd HH:mm:ss,结束时间须晚于开始时间且范围不超过 7 天");
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "录像回放启动失败,请稍后重试");
+        }
+        Map<String, Object> media = CockpitVideoMedia.publish(started, binding);
+        if (media.isEmpty()) {
+            try {
+                videos.stop((String) started.get("sessionId"), (String) started.get("sessionToken"));
+            } catch (RuntimeException failure) {
+                throw new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "媒体不可用且清理未确认,请等待回收");
+            }
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("sessionId", started.get("sessionId"));
+        data.put("sessionToken", started.get("sessionToken"));
+        data.put("mode", "PLAYBACK");
+        data.put("startTime", range.getStartTime());
+        data.put("endTime", range.getEndTime());
+        data.put("media", media);
+        return data;
+    }
+
+    /** The window is validated by the reused service seam; this only shapes the request. */
+    private static VideoRequests.Range range(String startTime, String endTime) {
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime(startTime);
+        range.setEndTime(endTime);
+        return range;
+    }
+
+    /** Only existing device/NVR recordings are exposed; a stray payload never becomes a recording. */
+    private static List<Map<String, Object>> recordItems(Object raw) {
+        Object list = raw instanceof Map ? ((Map<?, ?>) raw).get("recordList") : raw;
+        if (!(list instanceof List)) return List.of();
+        List<Map<String, Object>> items = new ArrayList<>();
+        for (Object entry : (List<?>) list) {
+            if (!(entry instanceof Map)) continue;
+            Map<?, ?> row = (Map<?, ?>) entry;
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("name", row.get("name"));
+            item.put("startTime", row.get("startTime"));
+            item.put("endTime", row.get("endTime"));
+            item.put("type", row.get("type"));
+            items.add(item);
+        }
+        return items;
+    }
+
+    /** Range validation is a caller error, not an upstream failure. */
+    private static boolean invalidRange(RuntimeException failure) {
+        String message = failure.getMessage();
+        return message != null && message.contains("录像时间格式为");
+    }
+
+    private static boolean gbBound(VideoDeviceRecord binding) {
+        return binding != null && "GB28181".equals(binding.getSourceType())
+                && gbId(binding.getGbDeviceId()) && gbId(binding.getGbChannelId());
+    }
+
+    public Map<String, Object> live(String code) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!liveSupported(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定或实时视频能力未确认");
+        Map<String, Object> started;
+        try {
+            started = videos.startAnonymous(device.getEquipmentId(), null);
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "实时视频启动失败,请稍后重试");
+        }
+        Map<String, Object> media = CockpitVideoMedia.publish(started, binding);
+        if (media.isEmpty()) {
+            try {
+                videos.stop((String) started.get("sessionId"), (String) started.get("sessionToken"));
+            } catch (RuntimeException failure) {
+                throw new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "媒体不可用且清理未确认,请等待回收");
+            }
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("sessionId", started.get("sessionId"));
+        data.put("sessionToken", started.get("sessionToken"));
+        data.put("mode", "LIVE");
+        data.put("media", media);
+        return data;
+    }
+
+    public Map<String, Object> prepare(String code) {
+        EquipmentBase device = findDevice(code);
+        if (!liveSupported(findBinding(device)))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定或实时视频能力未确认");
+        try {
+            Map<String, Object> data = videos.prepareAnonymous(device.getEquipmentId());
+            data.put("deviceCode", device.getEquipmentCode());
+            data.put("deviceName", device.getEquipmentName());
+            return data;
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_PREPARE_FAILED", "观看会话准备失败,尚未启动媒体");
+        }
+    }
+
+    public Map<String, Object> startPrepared(String id, String token) {
+        try { return preparedResult(videos.startPrepared(id, token), id, token); }
+        catch (RuntimeException failure) { throw sessionError(failure, false); }
+    }
+
+    public Map<String, Object> status(String id, String token) {
+        try { return preparedResult(videos.anonymousState(id, token), id, token); }
+        catch (RuntimeException failure) { throw sessionError(failure, false); }
+    }
+
+    public Map<String, Object> heartbeat(String id, String token) {
+        try {
+            videos.heartbeat(id, token);
+        } catch (RuntimeException failure) {
+            throw sessionError(failure, false);
+        }
+        return sessionState(id, "ACTIVE");
+    }
+
+    public Map<String, Object> stop(String id, String token) {
+        try {
+            return preparedResult(videos.stopAnonymousState(id, token), id, token);
+        } catch (RuntimeException failure) {
+            throw sessionError(failure, true);
+        }
+    }
+
+    /** Applies one playback control to this viewer's own session; the reused seam enforces value bounds. */
+    public Map<String, Object> control(String id, String token, String action, Double value) {
+        VideoRequests.Control input = new VideoRequests.Control();
+        input.setAction(action);
+        input.setValue(value);
+        try {
+            videos.control(id, token, input);
+        } catch (RuntimeException failure) {
+            throw sessionError(failure, false);
+        }
+        return sessionState(id, "ACTIVE");
+    }
+
+    private Map<String, Object> preparedResult(Map<String, Object> raw, String id, String token) {
+        Map<String, Object> data = new LinkedHashMap<>();
+        for (String field : List.of("sessionId", "status", "mode")) data.put(field, raw.get(field));
+        if (raw.get("media") instanceof Map) {
+            VideoDeviceRecord binding = bindings.find((String) raw.get("videoId"));
+            @SuppressWarnings("unchecked") Map<String, Object> source = (Map<String, Object>) raw.get("media");
+            Map<String, Object> media = binding == null ? Map.of() : CockpitVideoMedia.publish(source, binding);
+            if (media.isEmpty()) {
+                Map<String, Object> stopped = videos.stopAnonymousState(id, token);
+                if ("CLEANUP_PENDING".equals(stopped.get("status"))) return preparedResult(stopped, id, token);
+                throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+            }
+            data.put("media", media);
+        }
+        return data;
+    }
+
+    private static Map<String, Object> sessionState(String id, String state) {
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("sessionId", id);
+        data.put("status", state);
+        return data;
+    }
+
+    private static CockpitVideoException sessionError(RuntimeException error, boolean stop) {
+        if (error instanceof CockpitVideoException) return (CockpitVideoException) error;
+        // 01's public compatibility seam has no typed codes. Match only its two fixed ownership outcomes.
+        if (error instanceof ServiceException && "播放会话不存在或无权操作".equals(error.getMessage()))
+            return new CockpitVideoException(403, "SESSION_FORBIDDEN", "播放会话不存在或无权操作");
+        if (error instanceof ServiceException && "播放会话已失效".equals(error.getMessage()))
+            return new CockpitVideoException(410, "SESSION_EXPIRED", "播放会话已失效");
+        return stop ? new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "清理未确认,请等待回收")
+                : new CockpitVideoException(503, "SESSION_HEARTBEAT_FAILED", "观看会话维护失败");
+    }
+
+    private VideoDeviceRecord findBinding(EquipmentBase device) {
+        if (!Objects.equals(20, device.getEquipmentTypeId())) return null;
+        try {
+            VideoDeviceRecord binding = bindings.find(device.getEquipmentId());
+            return binding != null && Objects.equals(device.getEquipmentId(), binding.getEquipmentId())
+                    && Objects.equals(device.getEquipmentCode(), binding.getEquipmentCode())
+                    && Objects.equals(20, binding.getEquipmentTypeId()) ? binding : null;
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "视频设备信息暂不可用");
+        }
+    }
+
+    private static boolean liveSupported(VideoDeviceRecord binding) {
+        if (binding == null) return false;
+        if ("GB28181".equals(binding.getSourceType()))
+            return gbId(binding.getGbDeviceId()) && gbId(binding.getGbChannelId());
+        return "MANUAL".equals(binding.getSourceType()) && CockpitVideoMedia.manualSupported(binding.getVideoUrl());
+    }
+
+    private EquipmentBase findDevice(String code) {
+        if (code == null || code.isBlank() || code.length() > 512 || code.codePoints().anyMatch(Character::isISOControl))
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "设备业务编码无效");
+        List<EquipmentBase> rows;
+        try {
+            rows = devices.selectList(new QueryWrapper<EquipmentBase>()
+                    .eq("equipment_code", code).eq("del_flag", "0").last("LIMIT 2"));
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "视频设备信息暂不可用");
+        }
+        if (rows == null || rows.isEmpty())
+            throw new CockpitVideoException(404, "DEVICE_NOT_FOUND", "设备不存在");
+        if (rows.size() != 1)
+            throw new CockpitVideoException(503, "VIDEO_READ_FAILED", "设备业务编码存在歧义");
+        EquipmentBase row = rows.get(0);
+        // Defend against a DB collation ignoring whitespace/case, never guess a different identity.
+        if (row == null || !Objects.equals(code, row.getEquipmentCode()))
+            throw new CockpitVideoException(404, "DEVICE_NOT_FOUND", "设备不存在");
+        return row;
+    }
+
+    private static boolean gbId(String value) {
+        return value != null && value.matches("[0-9]{20}");
+    }
+}

+ 302 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/VideoLiveLifecycle.java

@@ -0,0 +1,302 @@
+package com.zksy.cockpit.video;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import com.zksy.common.exception.ServiceException;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import java.net.URI;
+import java.time.Clock;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.*;
+import java.util.function.Supplier;
+
+/** LIVE generation coordination. Every collector call occurs after intent commit, outside even a caller's transaction. */
+public final class VideoLiveLifecycle {
+    private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
+    private static final Set<String> PROVIDER_STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
+    private final VideoSessionMapper sessions;
+    private final EquipmentVideoBindingMapper bindings;
+    private final VideoCollectorClient collector;
+    private final Clock clock;
+    private TransactionTemplate shortTransaction;
+    private TransactionTemplate outsideTransaction;
+
+    public VideoLiveLifecycle(VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings,
+            VideoCollectorClient collector, Clock clock) {
+        this.sessions = sessions; this.bindings = bindings; this.collector = collector; this.clock = clock;
+    }
+
+    public void configure(PlatformTransactionManager manager) {
+        shortTransaction = new TransactionTemplate(manager);
+        shortTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+        outsideTransaction = new TransactionTemplate(manager);
+        outsideTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
+    }
+
+    public VideoSession prepare(String videoId, Long userId, String tokenHash) {
+        return outside(() -> transaction(() -> {
+            binding(videoId);
+            VideoSession row = new VideoSession();
+            row.setSessionId(UUID.randomUUID().toString()); row.setVideoId(videoId);
+            row.setUserId(userId); row.setAnonymousTokenHash(tokenHash);
+            row.setMode("LIVE"); row.setStatus("PREPARED");
+            row.setCreateTime(LocalDateTime.now(clock)); row.setLastSeen(row.getCreateTime());
+            if (sessions.insert(row) != 1) throw new ServiceException("播放会话登记失败");
+            return row;
+        }));
+    }
+
+    public Map<String,Object> start(Supplier<VideoSession> owned) {
+        return outside(() -> {
+            VideoSession intent = transaction(() -> {
+                VideoSession row = locked(owned);
+                if (TERMINAL.contains(row.getStatus())) return row;
+                if ("PREPARED".equals(row.getStatus()) && shouldExpire(row)) return finish(row, "FAILED");
+                if ("PREPARED".equals(row.getStatus())) bindGeneration(row, true);
+                return row;
+            });
+            if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
+            if ("CLEANUP_PENDING".equals(intent.getStatus())) return stop(owned);
+            // A new viewer may join a still-ACTIVE generation after its original creation
+            // deadline; do not extend that deadline or treat a join as a new media start.
+            if (shouldExpire(intent)) return expire(owned);
+            return invoke("ACTIVE".equals(intent.getStatus()) ? "status" : "start", owned, intent);
+        });
+    }
+
+    public Map<String,Object> status(Supplier<VideoSession> owned) {
+        return outside(() -> {
+            VideoSession row = owned.get();
+            if (TERMINAL.contains(row.getStatus())) return result(row, null);
+            if (shouldExpire(row)) return expire(owned);
+            if ("PREPARED".equals(row.getStatus())) return result(row, null);
+            if (row.getMediaGeneration() == null) row = transaction(() -> {
+                VideoSession locked = locked(owned); bindGeneration(locked, false); return locked;
+            });
+            return invoke("status", owned, row);
+        });
+    }
+
+    public Map<String,Object> stop(Supplier<VideoSession> owned) {
+        return stop(owned, null, false);
+    }
+
+    /** Re-read expiry under the same device lock as heartbeat; a stale scan must not stop a renewed viewer. */
+    public Map<String,Object> expire(Supplier<VideoSession> owned) {
+        return stop(owned, null, true);
+    }
+
+    private Map<String,Object> stop(Supplier<VideoSession> owned, String expectedGeneration, boolean expiredOnly) {
+        return outside(() -> {
+            VideoSession intent = transaction(() -> {
+                VideoSession row = locked(owned);
+                if (TERMINAL.contains(row.getStatus())) return row;
+                if (expectedGeneration != null && !Objects.equals(expectedGeneration, row.getMediaGeneration())) return row;
+                if (expiredOnly && !shouldExpire(row)) return row;
+                if ("PREPARED".equals(row.getStatus())) return finish(row, "STOPPED");
+                if (row.getMediaGeneration() == null) bindGeneration(row, false);
+                row.setStatus("CLEANUP_PENDING"); update(row);
+                long others = sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                        .eq(VideoSession::getVideoId, row.getVideoId()).eq(VideoSession::getMode, "LIVE")
+                        .eq(VideoSession::getMediaGeneration, row.getMediaGeneration())
+                        .in(VideoSession::getStatus, "STARTING", "ACTIVE").ne(VideoSession::getSessionId, row.getSessionId()));
+                return others > 0 ? finish(row, "STOPPED") : row;
+            });
+            if (!"CLEANUP_PENDING".equals(intent.getStatus())
+                    || expectedGeneration != null && !Objects.equals(expectedGeneration, intent.getMediaGeneration()))
+                return result(intent, null);
+            return invoke("cancel", owned, intent);
+        });
+    }
+
+    /** Called under the device row lock. Never pick an arbitrary row when generations or handles disagree. */
+    private void bindGeneration(VideoSession row, boolean activating) {
+        VideoDeviceRecord source = binding(row.getVideoId());
+        List<VideoSession> resources = new ArrayList<>(sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId, row.getVideoId()).eq(VideoSession::getMode, "LIVE")
+                .in(VideoSession::getStatus, "STARTING", "ACTIVE", "CLEANUP_PENDING")));
+        if (!"PREPARED".equals(row.getStatus()) && resources.stream().noneMatch(value -> row.getSessionId().equals(value.getSessionId())))
+            resources.add(row);
+        if (activating && resources.stream().anyMatch(value -> "CLEANUP_PENDING".equals(value.getStatus())))
+            throw new ServiceException("视频资源回收中,请等待确认");
+        Set<String> generations = new HashSet<>(), streams = new HashSet<>(), keys = new HashSet<>(), nodes = new HashSet<>();
+        Set<LocalDateTime> deadlines = new HashSet<>();
+        boolean nativeSource = nativeSource(source);
+        for (VideoSession value : resources) {
+            if (value.getMediaGeneration() != null) generations.add(value.getMediaGeneration());
+            if (value.getStartDeadline() != null) deadlines.add(value.getStartDeadline());
+            if ("GB28181".equals(source.getSourceType()) && (!Objects.equals(source.getGbDeviceId(), value.getGbDeviceId())
+                    || !Objects.equals(source.getGbChannelId(), value.getGbChannelId())))
+                throw new ServiceException("现存视频来源不一致,需人工核查");
+            if (value.getMediaServerId() != null) nodes.add(value.getMediaServerId());
+            if (value.getStreamId() != null) streams.add(value.getStreamId());
+            if (!"GB28181".equals(source.getSourceType()) && value.getProxyKey() != null) keys.add(value.getProxyKey());
+            if (value.getMediaGeneration() == null && "ACTIVE".equals(value.getStatus()) && !nativeSource) {
+                if (value.getMediaServerId() == null || value.getMediaServerId().isBlank()
+                        || !safeStream(value.getStreamId()) || (!"GB28181".equals(source.getSourceType())
+                        && (value.getProxyKey() == null || value.getProxyKey().isBlank())))
+                    throw new ServiceException("旧视频资源句柄未确认,需人工核查");
+            }
+        }
+        if (generations.size() > 1 || deadlines.size() > 1 || streams.size() > 1 || keys.size() > 1 || nodes.size() > 1)
+            throw new ServiceException("现存视频代次或句柄不一致,需人工核查");
+        String generation = generations.isEmpty() ? UUID.randomUUID().toString() : generations.iterator().next();
+        LocalDateTime deadline = deadlines.isEmpty() ? LocalDateTime.ofInstant(clock.instant().plusSeconds(30), ZoneOffset.UTC)
+                : deadlines.iterator().next();
+        for (VideoSession value : resources) if (value.getMediaGeneration() == null) {
+            value.setMediaGeneration(generation); value.setStartDeadline(deadline); update(value);
+        }
+        row.setMediaGeneration(generation); row.setStartDeadline(deadline);
+        row.setGbDeviceId("GB28181".equals(source.getSourceType()) ? source.getGbDeviceId() : null);
+        row.setGbChannelId("GB28181".equals(source.getSourceType()) ? source.getGbChannelId() : null);
+        if (!nodes.isEmpty()) row.setMediaServerId(nodes.iterator().next());
+        if (!streams.isEmpty()) row.setStreamId(streams.iterator().next());
+        if (!keys.isEmpty()) row.setProxyKey(keys.iterator().next());
+        if (activating) row.setStatus("STARTING");
+        update(row);
+    }
+
+    private Map<String,Object> invoke(String action, Supplier<VideoSession> owned, VideoSession intent) {
+        Map<String,Object> response = null;
+        try {
+            Object raw = collector.post("/internal/video/lifecycle/" + action, request(intent));
+            if (raw instanceof Map) response = cast(raw);
+        } catch (RuntimeException transportUnknown) {
+            // A transport failure cannot establish whether this generation was created or stopped.
+        }
+        Map<String,Object> observed = response;
+        try {
+            return apply(owned, intent, observed);
+        } catch (RuntimeException persistenceFailure) {
+            // The media effect happened outside SQL: a failed UPDATE or commit is not a failed start.
+            // Stop only this persisted generation after rollback, and re-count current shared viewers.
+            // If storage is still unavailable, the previously committed STARTING/PENDING intent is
+            // deliberately retained for the expiry worker. Never guess a channel-wide stop.
+            if (!"cancel".equals(action)) {
+                try { stop(owned, intent.getMediaGeneration(), false); }
+                catch (RuntimeException cleanupUnknown) { persistenceFailure.addSuppressed(cleanupUnknown); }
+            }
+            throw persistenceFailure;
+        }
+    }
+
+    private Map<String,Object> apply(Supplier<VideoSession> owned, VideoSession intent, Map<String,Object> observed) {
+        return transaction(() -> {
+            VideoSession current = locked(owned);
+            if (!Objects.equals(current.getMediaGeneration(), intent.getMediaGeneration()) || TERMINAL.contains(current.getStatus()))
+                return result(current, null);
+            if (observed == null || !Objects.equals(intent.getMediaGeneration(), observed.get("generation"))
+                    || !PROVIDER_STATES.contains(observed.get("status"))) return result(current, null);
+            String state = (String) observed.get("status");
+            if ("CLEANUP_PENDING".equals(current.getStatus()) && !TERMINAL.contains(state)) return result(current, null);
+            if (TERMINAL.contains(state)) return result(finish(current, state), null);
+            if ("CLEANUP_PENDING".equals(state)) {
+                current.setStatus(state); update(current); return result(current, null);
+            }
+            if ("ACTIVE".equals(state) && observed.get("media") instanceof Map) {
+                Map<String,Object> media = cast(observed.get("media"));
+                if (!validMedia(binding(current.getVideoId()), media)) return result(current, null);
+                boolean newlyActive = !"ACTIVE".equals(current.getStatus());
+                current.setStatus("ACTIVE");
+                current.setMediaServerId(media.get("mediaServerId") instanceof String ? (String) media.get("mediaServerId") : current.getMediaServerId());
+                current.setStreamId(media.get("stream") instanceof String ? (String) media.get("stream") : null);
+                current.setProxyKey(media.get("proxyKey") instanceof String ? (String) media.get("proxyKey") : null);
+                if (newlyActive) current.setLastSeen(LocalDateTime.now(clock));
+                update(current);
+                return result(current, media);
+            }
+            return result(current, null);
+        });
+    }
+
+    private Map<String,Object> request(VideoSession row) {
+        VideoDeviceRecord binding = binding(row.getVideoId());
+        Map<String,Object> source = new LinkedHashMap<>();
+        source.put("type", binding.getSourceType()); source.put("videoId", row.getVideoId());
+        if ("GB28181".equals(binding.getSourceType())) {
+            source.put("deviceId", binding.getGbDeviceId()); source.put("channelId", binding.getGbChannelId());
+        } else source.put("url", binding.getVideoUrl());
+        Map<String,Object> body = new LinkedHashMap<>();
+        body.put("generation", row.getMediaGeneration()); body.put("source", source);
+        body.put("startDeadline", row.getStartDeadline().toInstant(ZoneOffset.UTC).toEpochMilli());
+        if (!nativeSource(binding) && row.getStreamId() != null) {
+            Map<String,Object> existing = new LinkedHashMap<>(); existing.put("stream", row.getStreamId());
+            if (row.getMediaServerId() != null) existing.put("mediaServerId", row.getMediaServerId());
+            if (!"GB28181".equals(binding.getSourceType()) && row.getProxyKey() != null) existing.put("proxyKey", row.getProxyKey());
+            body.put("existingMedia", existing);
+        }
+        return body;
+    }
+
+    private boolean hasActivePeer(VideoSession row) {
+        return "STARTING".equals(row.getStatus()) && row.getMediaGeneration() != null
+                && sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId,row.getVideoId()).eq(VideoSession::getMode,"LIVE")
+                .eq(VideoSession::getMediaGeneration,row.getMediaGeneration()).eq(VideoSession::getStatus,"ACTIVE")
+                .ge(VideoSession::getLastSeen, LocalDateTime.now(clock).minusSeconds(120))
+                .ne(VideoSession::getSessionId,row.getSessionId())) > 0;
+    }
+
+    /** One expiry policy for HTTP, scan selection and the locked recheck. Joining a healthy
+     * generation does not restart its media deadline; once the peer leaves, that deadline applies.
+     * The joining viewer's own lease still bounds an abandoned/unknown request. */
+    public boolean shouldExpire(VideoSession row) {
+        if ("CLEANUP_PENDING".equals(row.getStatus())) return true;
+        boolean leaseExpired = row.getLastSeen() == null
+                || row.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120));
+        if ("STARTING".equals(row.getStatus())) return leaseExpired || (row.getStartDeadline() == null
+                || !clock.instant().isBefore(row.getStartDeadline().toInstant(ZoneOffset.UTC))) && !hasActivePeer(row);
+        return ("PREPARED".equals(row.getStatus()) || "ACTIVE".equals(row.getStatus())) && leaseExpired;
+    }
+
+    private VideoSession locked(Supplier<VideoSession> owned) {
+        VideoSession before = owned.get(); sessions.lockVideo(before.getVideoId()); return owned.get();
+    }
+    private VideoSession finish(VideoSession row, String state) {
+        row.setStatus(state); row.setEndTime(LocalDateTime.now(clock)); update(row); return row;
+    }
+    private void update(VideoSession row) {
+        if (sessions.updateById(row) != 1) throw new ServiceException("播放会话状态登记失败");
+    }
+    private VideoDeviceRecord binding(String id) {
+        VideoDeviceRecord value = bindings.find(id);
+        if (value == null) throw new ServiceException("视频设备不存在");
+        return value;
+    }
+    private static boolean nativeSource(VideoDeviceRecord source) {
+        return "MANUAL".equals(source.getSourceType()) && source.getVideoUrl() != null
+                && !URI.create(source.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT).startsWith("rt");
+    }
+    private static boolean safeStream(String value) { return value != null && value.matches("[A-Za-z0-9_-]{1,200}"); }
+    private static boolean validMedia(VideoDeviceRecord source, Map<String,Object> media) {
+        boolean address = List.of("url", "flv", "https_flv", "ws_flv", "wss_flv", "hls", "https_hls", "webrtc", "rtc", "rtcs")
+                .stream().map(media::get).anyMatch(value -> {
+                    try {
+                        URI uri = URI.create((String) value);
+                        return uri.getHost() != null && Set.of("http", "https", "ws", "wss").contains(uri.getScheme().toLowerCase(Locale.ROOT));
+                    } catch (RuntimeException invalid) { return false; }
+                });
+        return address && (nativeSource(source) || media.get("stream") instanceof String && safeStream((String) media.get("stream")))
+                && (nativeSource(source) || "GB28181".equals(source.getSourceType())
+                    || media.get("proxyKey") instanceof String && !((String) media.get("proxyKey")).isBlank());
+    }
+    private static Map<String,Object> result(VideoSession row, Map<String,Object> media) {
+        Map<String,Object> result = new LinkedHashMap<>();
+        result.put("sessionId", row.getSessionId()); result.put("status", row.getStatus());
+        result.put("mode", row.getMode()); result.put("videoId", row.getVideoId());
+        if (media != null) result.put("media", media);
+        return result;
+    }
+    @SuppressWarnings("unchecked") private static Map<String,Object> cast(Object value) { return (Map<String,Object>) value; }
+    // Plain constructor calls remain useful for legacy offline fixtures; production configures the real manager.
+    private <T> T transaction(Supplier<T> work) { return shortTransaction == null ? work.get() : shortTransaction.execute(status -> work.get()); }
+    private <T> T outside(Supplier<T> work) { return outsideTransaction == null ? work.get() : outsideTransaction.execute(status -> work.get()); }
+}

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

@@ -14,6 +14,10 @@ import com.zksy.base.warning.domain.AlarmWarningRel;
 import com.zksy.base.warning.domain.EarlyWarning;
 import com.zksy.base.warning.domain.EarlyWarning;
 import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
 import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
 import com.zksy.base.warning.service.EarlyWarningService;
 import com.zksy.base.warning.service.EarlyWarningService;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.ops.enums.WorkOrderDelayApplyStatusEnum;
+import com.zksy.system.mapper.SysDictDataMapper;
+import com.zksy.system.service.ISysUserService;
 import com.zksy.cockpit.foundation.CockpitDistrict;
 import com.zksy.cockpit.foundation.CockpitDistrict;
 import com.zksy.cockpit.foundation.CockpitReadException;
 import com.zksy.cockpit.foundation.CockpitReadException;
 import com.zksy.cockpit.foundation.CockpitTypeIndustry;
 import com.zksy.cockpit.foundation.CockpitTypeIndustry;
@@ -32,6 +36,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Objects;
 import java.util.stream.Collectors;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 
 @Component
 @Component
 @Primary
 @Primary
@@ -44,6 +49,9 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
     private final AlarmDataService alarmDataService;
     private final AlarmDataService alarmDataService;
     private final EquipmentBaseMapper equipmentBaseMapper;
     private final EquipmentBaseMapper equipmentBaseMapper;
     private final EquipmentTypeService equipmentTypeService;
     private final EquipmentTypeService equipmentTypeService;
+    /** 优先级字典(work_order_level)与用户姓名的批量数据源:只用于详情展示,查不到如实为 null。 */
+    private final SysDictDataMapper sysDictDataMapper;
+    private final ISysUserService sysUserService;
 
 
     public BusinessCockpitWorkOrderReadAdapter(
     public BusinessCockpitWorkOrderReadAdapter(
             WorkOrderService workOrderService,
             WorkOrderService workOrderService,
@@ -51,13 +59,17 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
             AlarmWarningRelMapper alarmWarningRelMapper,
             AlarmWarningRelMapper alarmWarningRelMapper,
             AlarmDataService alarmDataService,
             AlarmDataService alarmDataService,
             EquipmentBaseMapper equipmentBaseMapper,
             EquipmentBaseMapper equipmentBaseMapper,
-            EquipmentTypeService equipmentTypeService) {
+            EquipmentTypeService equipmentTypeService,
+            SysDictDataMapper sysDictDataMapper,
+            ISysUserService sysUserService) {
         this.workOrderService = workOrderService;
         this.workOrderService = workOrderService;
         this.earlyWarningService = earlyWarningService;
         this.earlyWarningService = earlyWarningService;
         this.alarmWarningRelMapper = alarmWarningRelMapper;
         this.alarmWarningRelMapper = alarmWarningRelMapper;
         this.alarmDataService = alarmDataService;
         this.alarmDataService = alarmDataService;
         this.equipmentBaseMapper = equipmentBaseMapper;
         this.equipmentBaseMapper = equipmentBaseMapper;
         this.equipmentTypeService = equipmentTypeService;
         this.equipmentTypeService = equipmentTypeService;
+        this.sysDictDataMapper = sysDictDataMapper;
+        this.sysUserService = sysUserService;
     }
     }
 
 
     @Override
     @Override
@@ -79,8 +91,10 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
 
 
     private List<CockpitWorkOrderSummary> toAlarmSummaries(List<WorkOrder> orders) {
     private List<CockpitWorkOrderSummary> toAlarmSummaries(List<WorkOrder> orders) {
         Map<Long, AlarmData> alarmByOrderId = alarmsByOrderId(orders);
         Map<Long, AlarmData> alarmByOrderId = alarmsByOrderId(orders);
+        // 详情字段按整页批量解析一次(设备/用户/优先级字典),不逐条回查。
+        Enrichment enrichment = enrichment(orders);
         return orders.stream()
         return orders.stream()
-                .map(order -> toAlarmSummary(order, alarmByOrderId.get(order.getOrderId())))
+                .map(order -> toAlarmSummary(order, alarmByOrderId.get(order.getOrderId()), enrichment))
                 .collect(Collectors.toList());
                 .collect(Collectors.toList());
     }
     }
 
 
@@ -289,8 +303,9 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
             List<WorkOrder> orders = alarmIds.isEmpty()
             List<WorkOrder> orders = alarmIds.isEmpty()
                     ? Collections.emptyList()
                     ? Collections.emptyList()
                     : findOrdersByAlarmIds(alarmIds);
                     : findOrdersByAlarmIds(alarmIds);
+            Enrichment enrichment = enrichment(orders);
             List<CockpitWorkOrderSummary> summaries = orders.stream()
             List<CockpitWorkOrderSummary> summaries = orders.stream()
-                    .map(order -> toSummary(order, eventSource, eventCode, true))
+                    .map(order -> toSummary(order, eventSource, eventCode, true, enrichment))
                     .collect(Collectors.toList());
                     .collect(Collectors.toList());
             return new CockpitWorkOrderReadSnapshot(null, eventSource, eventCode, summaries);
             return new CockpitWorkOrderReadSnapshot(null, eventSource, eventCode, summaries);
         }
         }
@@ -311,24 +326,31 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
                 .collect(Collectors.toList());
                 .collect(Collectors.toList());
         // 时间线与设备维度按同一真实关联键解析,不因缺少事件查询参数而标为未关联。
         // 时间线与设备维度按同一真实关联键解析,不因缺少事件查询参数而标为未关联。
         AlarmData alarm = alarmsByOrderId(Collections.singletonList(order)).get(order.getOrderId());
         AlarmData alarm = alarmsByOrderId(Collections.singletonList(order)).get(order.getOrderId());
-        return new CockpitWorkOrderTimelineSnapshot(toAlarmSummary(order, alarm), entries);
+        return new CockpitWorkOrderTimelineSnapshot(
+                toAlarmSummary(order, alarm, enrichment(Collections.singletonList(order))), entries);
     }
     }
 
 
-    private CockpitWorkOrderSummary toAlarmSummary(WorkOrder order, AlarmData alarm) {
+    private CockpitWorkOrderSummary toAlarmSummary(
+            WorkOrder order, AlarmData alarm, Enrichment enrichment) {
         boolean associated = alarm != null && order.getOrderId() != null
         boolean associated = alarm != null && order.getOrderId() != null
                 && order.getOrderId().equals(alarm.getWorkOrderId());
                 && order.getOrderId().equals(alarm.getWorkOrderId());
         return associated
         return associated
-                ? toSummary(order, "ALARM", alarmReference(alarm), true)
-                : toSummary(order, null, null, false);
+                ? toSummary(order, "ALARM", alarmReference(alarm), true, enrichment)
+                : toSummary(order, null, null, false, enrichment);
     }
     }
 
 
     private CockpitWorkOrderSummary toSummary(
     private CockpitWorkOrderSummary toSummary(
-            WorkOrder order, String eventSource, String eventCode, boolean associatedWithCurrentEvent) {
+            WorkOrder order,
+            String eventSource,
+            String eventCode,
+            boolean associatedWithCurrentEvent,
+            Enrichment enrichment) {
         CockpitWorkOrderState state = CockpitWorkOrderStateDictionary.byCode(order.getOrderStatus());
         CockpitWorkOrderState state = CockpitWorkOrderStateDictionary.byCode(order.getOrderStatus());
+        EquipmentBase device = enrichment.deviceByEquipmentId.get(order.getDeviceId());
         return new CockpitWorkOrderSummary(
         return new CockpitWorkOrderSummary(
                 order.getOrderId(),
                 order.getOrderId(),
                 order.getOrderNo(),
                 order.getOrderNo(),
-                resolveDeviceCode(order.getDeviceId()),
+                device == null ? null : trimToNull(device.getEquipmentCode()),
                 order.getOrderLevel(),
                 order.getOrderLevel(),
                 order.getOrderDesc(),
                 order.getOrderDesc(),
                 state.getCode(),
                 state.getCode(),
@@ -339,7 +361,16 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
                 format(order.getRealFinishTime()),
                 format(order.getRealFinishTime()),
                 eventSource == null ? null : new CockpitWorkOrderEventAssociation(
                 eventSource == null ? null : new CockpitWorkOrderEventAssociation(
                         eventSource, eventCode, format(order.getCreateTime())),
                         eventSource, eventCode, format(order.getCreateTime())),
-                associatedWithCurrentEvent);
+                associatedWithCurrentEvent,
+                format(order.getFaultTime()),
+                device == null ? null : trimToNull(device.getEquipmentName()),
+                device == null ? null : trimToNull(device.getEquipmentLocation()),
+                CockpitWorkOrderLevelName.of(order.getOrderLevel(), enrichment.levelLabels),
+                enrichment.userNames.get(order.getReceiveUser()),
+                enrichment.userNames.get(order.getVerifyUser()),
+                CockpitWorkOrderImages.split(order.getMaintenanceBeforeImg()),
+                CockpitWorkOrderImages.split(order.getMaintenanceAfterImg()),
+                delayApply(order));
     }
     }
 
 
     /**
     /**
@@ -362,9 +393,127 @@ public class BusinessCockpitWorkOrderReadAdapter implements CockpitWorkOrderRead
         return ids;
         return ids;
     }
     }
 
 
-    private String resolveDeviceCode(String deviceId) {
-        EquipmentBase equipment = deviceId == null ? null : equipmentBaseMapper.selectById(deviceId);
-        return equipment == null ? null : equipment.getEquipmentCode();
+    /**
+     * 整页详情字段的批量数据源:设备(名称/编码/位置)、用户姓名、优先级字典。
+     *
+     * <p>一次请求各查一次(设备一次 {@code selectBatchIds}、用户一次
+     * {@code selectEnabledUsersByIds}、字典一次 {@code selectDictDataByType}),
+     * 不随工单条数增长;任何一族查不到都退化成「该字段为 null」,不影响工单本身。</p>
+     */
+    private Enrichment enrichment(List<WorkOrder> orders) {
+        if (orders == null || orders.isEmpty()) {
+            return Enrichment.empty();
+        }
+        return new Enrichment(
+                devicesByIds(orders),
+                userNamesByIds(orders),
+                CockpitWorkOrderLevelName.labels(sysDictDataMapper));
+    }
+
+    /** 工单设备 → 设备台账;一次批量查询,缺失设备自然不在 Map 里。 */
+    private Map<String, EquipmentBase> devicesByIds(List<WorkOrder> orders) {
+        List<String> deviceIds = orders.stream()
+                .filter(Objects::nonNull)
+                .map(WorkOrder::getDeviceId)
+                .filter(id -> !isBlank(id))
+                .map(String::trim)
+                .distinct()
+                .collect(Collectors.toList());
+        if (deviceIds.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        List<EquipmentBase> devices;
+        try {
+            devices = equipmentBaseMapper.selectBatchIds(deviceIds);
+        } catch (DataAccessException | PersistenceException exception) {
+            throw new CockpitReadException("work order device read failed");
+        }
+        if (devices == null) {
+            return Collections.emptyMap();
+        }
+        Map<String, EquipmentBase> result = new LinkedHashMap<>();
+        for (EquipmentBase device : devices) {
+            if (device != null && !isBlank(device.getEquipmentId())) {
+                result.putIfAbsent(device.getEquipmentId(), device);
+            }
+        }
+        return result;
+    }
+
+    /** 处置人/核验人 → 姓名;一次批查询,只取启用用户(停用/删除当作查不到 → null)。 */
+    private Map<Long, String> userNamesByIds(List<WorkOrder> orders) {
+        List<Long> userIds = orders.stream()
+                .filter(Objects::nonNull)
+                .flatMap(order -> Stream.of(order.getReceiveUser(), order.getVerifyUser()))
+                .filter(Objects::nonNull)
+                .distinct()
+                .collect(Collectors.toList());
+        if (userIds.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        List<SysUser> users;
+        try {
+            users = sysUserService.selectEnabledUsersByIds(userIds);
+        } catch (RuntimeException exception) {
+            // 姓名只是展示字段:查询失败退化为 null,不把整份工单数据判死。
+            return Collections.emptyMap();
+        }
+        if (users == null) {
+            return Collections.emptyMap();
+        }
+        Map<Long, String> result = new LinkedHashMap<>();
+        for (SysUser user : users) {
+            if (user == null || user.getUserId() == null) {
+                continue;
+            }
+            String name = trimToNull(user.getNickName()) == null
+                    ? trimToNull(user.getUserName()) : trimToNull(user.getNickName());
+            if (name != null) {
+                result.putIfAbsent(user.getUserId(), name);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 延期申请:状态 0(无延期申请)或状态缺失时整块 {@code null},不造空的申请对象。
+     * 状态名取仓库既有 {@link WorkOrderDelayApplyStatusEnum} 口径;未知码不编名字。
+     */
+    private CockpitWorkOrderDelayApply delayApply(WorkOrder order) {
+        Integer status = order.getDelayApplyStatus();
+        if (status == null || WorkOrderDelayApplyStatusEnum.NONE.getCode().equals(status)) {
+            return null;
+        }
+        WorkOrderDelayApplyStatusEnum entry = WorkOrderDelayApplyStatusEnum.getByCode(status);
+        return new CockpitWorkOrderDelayApply(
+                status,
+                entry == null ? null : entry.getDesc(),
+                trimToNull(order.getDelayedReason()),
+                format(order.getDelayedDeadline()));
+    }
+
+    private static String trimToNull(String value) {
+        return isBlank(value) ? null : value.trim();
+    }
+
+    /** 批量详情字段的快照;空页时全空,避免任何查询。 */
+    private static final class Enrichment {
+        private final Map<String, EquipmentBase> deviceByEquipmentId;
+        private final Map<Long, String> userNames;
+        private final Map<Integer, String> levelLabels;
+
+        private Enrichment(
+                Map<String, EquipmentBase> deviceByEquipmentId,
+                Map<Long, String> userNames,
+                Map<Integer, String> levelLabels) {
+            this.deviceByEquipmentId = deviceByEquipmentId;
+            this.userNames = userNames;
+            this.levelLabels = levelLabels;
+        }
+
+        private static Enrichment empty() {
+            return new Enrichment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());
+        }
     }
     }
 
 
     private List<WorkOrder> findOrdersByAlarmIds(List<String> alarmIds) {
     private List<WorkOrder> findOrdersByAlarmIds(List<String> alarmIds) {

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

@@ -0,0 +1,27 @@
+package com.zksy.cockpit.workorder;
+
+/**
+ * 工单延期申请(只读视图)。
+ *
+ * <p>数据全部来自 {@code work_order} 同一行的既有列:{@code delay_apply_status}、
+ * {@code delayed_reason}、{@code delayed_deadline}。状态名取仓库既有枚举
+ * {@code WorkOrderDelayApplyStatusEnum} 的口径,不另立词表;无延期申请时整块为 {@code null}。</p>
+ */
+public class CockpitWorkOrderDelayApply {
+    private final Integer status;
+    private final String statusName;
+    private final String reason;
+    private final String deadline;
+
+    public CockpitWorkOrderDelayApply(Integer status, String statusName, String reason, String deadline) {
+        this.status = status;
+        this.statusName = statusName;
+        this.reason = reason;
+        this.deadline = deadline;
+    }
+
+    public Integer getStatus() { return status; }
+    public String getStatusName() { return statusName; }
+    public String getReason() { return reason; }
+    public String getDeadline() { return deadline; }
+}

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

@@ -0,0 +1,29 @@
+package com.zksy.cockpit.workorder;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * 工单附件图片解析。
+ *
+ * <p>库内 {@code work_order.maintenance_before_img / maintenance_after_img} 是**逗号分隔**的 URL 串
+ * (见实体注释),对外暴露成数组。空串/缺失一律空数组,不产出 {@code [""]} 这种假元素。</p>
+ */
+public final class CockpitWorkOrderImages {
+    private CockpitWorkOrderImages() {
+    }
+
+    public static List<String> split(String commaSeparated) {
+        if (commaSeparated == null || commaSeparated.trim().isEmpty()) {
+            return Collections.emptyList();
+        }
+        List<String> result = new ArrayList<>();
+        for (String part : commaSeparated.split(",")) {
+            if (part != null && !part.trim().isEmpty()) {
+                result.add(part.trim());
+            }
+        }
+        return result;
+    }
+}

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

@@ -0,0 +1,77 @@
+package com.zksy.cockpit.workorder;
+
+import com.zksy.common.core.domain.entity.SysDictData;
+import com.zksy.system.mapper.SysDictDataMapper;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 工单优先级展示名({@code work_order_level} 字典)。
+ *
+ * <p>与管理端同一数据源:{@code sys_dict_data.dict_type='work_order_level'} 的
+ * {@code dict_value → dict_label}(现网 0-紧急 / 1-一般 / 2-低)。这里**不内置任何词表**,
+ * 字典缺项如实回 {@code null},不猜、不硬编码中文。</p>
+ *
+ * <p>字典按请求批量读取一次(每次列表请求一次 {@code selectDictDataByType}),不逐条回查。</p>
+ */
+public final class CockpitWorkOrderLevelName {
+    public static final String LEVEL_DICT = "work_order_level";
+
+    private CockpitWorkOrderLevelName() {
+    }
+
+    /** 一次取全字典({@code dict_value → dict_label});空表/查询异常如实为空表(展示名降级,不影响工单数据)。 */
+    public static Map<Integer, String> labels(SysDictDataMapper dictMapper) {
+        if (dictMapper == null) {
+            return Collections.emptyMap();
+        }
+        try {
+            return labels(dictMapper.selectDictDataByType(LEVEL_DICT));
+        } catch (RuntimeException ignored) {
+            return Collections.emptyMap();
+        }
+    }
+
+    /** 字典行 → 等级标签;仅取 {@code dict_value} 可解析且标签非空的行,重复值保留首条。 */
+    public static Map<Integer, String> labels(List<SysDictData> source) {
+        Map<Integer, String> result = new LinkedHashMap<>();
+        if (source == null) {
+            return result;
+        }
+        for (SysDictData data : source) {
+            if (data == null) {
+                continue;
+            }
+            Integer value = levelOf(data.getDictValue());
+            String label = trimToNull(data.getDictLabel());
+            if (value != null && label != null) {
+                result.putIfAbsent(value, label);
+            }
+        }
+        return result;
+    }
+
+    /** 展示名:字典有标签用标签,缺项回 {@code null}(不伪造优先级名称)。 */
+    public static String of(Integer level, Map<Integer, String> labels) {
+        return level == null || labels == null ? null : trimToNull(labels.get(level));
+    }
+
+    private static Integer levelOf(String value) {
+        String normalized = trimToNull(value);
+        if (normalized == null) {
+            return null;
+        }
+        try {
+            return Integer.parseInt(normalized);
+        } catch (NumberFormatException ignored) {
+            return null;
+        }
+    }
+
+    private static String trimToNull(String value) {
+        return value == null || value.trim().isEmpty() ? null : value.trim();
+    }
+}

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

@@ -2,6 +2,9 @@ package com.zksy.cockpit.workorder;
 
 
 import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonIgnore;
 
 
+import java.util.Collections;
+import java.util.List;
+
 public class CockpitWorkOrderSummary {
 public class CockpitWorkOrderSummary {
     private final Long orderId;
     private final Long orderId;
     private final String workOrderCode;
     private final String workOrderCode;
@@ -17,6 +20,24 @@ public class CockpitWorkOrderSummary {
     private final CockpitWorkOrderEventAssociation eventAssociation;
     private final CockpitWorkOrderEventAssociation eventAssociation;
     /** 该工单是否与本查询的报警/预警**实际关联**(决策票 12:未关联须显式提示,不靠 null 猜)。 */
     /** 该工单是否与本查询的报警/预警**实际关联**(决策票 12:未关联须显式提示,不靠 null 猜)。 */
     private final boolean associatedWithCurrentEvent;
     private final boolean associatedWithCurrentEvent;
+    /** 故障发生时间(ISO-8601);缺值 null。 */
+    private final String faultTime;
+    /** 关联设备名称(取 equipment_base.equipment_name);缺值 null。 */
+    private final String deviceName;
+    /** 设备安装位置(取 equipment_base.equipment_location);缺值 null。 */
+    private final String deviceLocation;
+    /** 优先级展示名(work_order_level 字典);字典缺项 null,不伪造。 */
+    private final String orderLevelName;
+    /** 处置人姓名(sys_user.nick_name 优先);批量回填,查不到 null。 */
+    private final String receiveUserName;
+    /** 核验人姓名;批量回填,查不到 null。 */
+    private final String verifyUserName;
+    /** 维修前图片数组(库内逗号分隔串解析);无图空数组。 */
+    private final List<String> maintenanceBeforeImages;
+    /** 维修后图片数组;无图空数组。 */
+    private final List<String> maintenanceAfterImages;
+    /** 延期申请;无延期申请(或状态为 0)时 null。 */
+    private final CockpitWorkOrderDelayApply delayApply;
 
 
     public CockpitWorkOrderSummary(
     public CockpitWorkOrderSummary(
             Long orderId,
             Long orderId,
@@ -31,7 +52,16 @@ public class CockpitWorkOrderSummary {
             String planFinishTime,
             String planFinishTime,
             String realFinishTime,
             String realFinishTime,
             CockpitWorkOrderEventAssociation eventAssociation,
             CockpitWorkOrderEventAssociation eventAssociation,
-            boolean associatedWithCurrentEvent) {
+            boolean associatedWithCurrentEvent,
+            String faultTime,
+            String deviceName,
+            String deviceLocation,
+            String orderLevelName,
+            String receiveUserName,
+            String verifyUserName,
+            List<String> maintenanceBeforeImages,
+            List<String> maintenanceAfterImages,
+            CockpitWorkOrderDelayApply delayApply) {
         this.orderId = orderId;
         this.orderId = orderId;
         this.workOrderCode = workOrderCode;
         this.workOrderCode = workOrderCode;
         this.deviceCode = deviceCode;
         this.deviceCode = deviceCode;
@@ -45,6 +75,43 @@ public class CockpitWorkOrderSummary {
         this.realFinishTime = realFinishTime;
         this.realFinishTime = realFinishTime;
         this.eventAssociation = eventAssociation;
         this.eventAssociation = eventAssociation;
         this.associatedWithCurrentEvent = associatedWithCurrentEvent;
         this.associatedWithCurrentEvent = associatedWithCurrentEvent;
+        this.faultTime = faultTime;
+        this.deviceName = deviceName;
+        this.deviceLocation = deviceLocation;
+        this.orderLevelName = orderLevelName;
+        this.receiveUserName = receiveUserName;
+        this.verifyUserName = verifyUserName;
+        this.maintenanceBeforeImages = maintenanceBeforeImages == null
+                ? Collections.emptyList() : Collections.unmodifiableList(maintenanceBeforeImages);
+        this.maintenanceAfterImages = maintenanceAfterImages == null
+                ? Collections.emptyList() : Collections.unmodifiableList(maintenanceAfterImages);
+        this.delayApply = delayApply;
+    }
+
+    /**
+     * 兼容旧构造:只给原有字段,新增详情字段一律为「无值」。
+     *
+     * <p>保留它是因为 {@code CockpitWorkOrderSummary} 在测试夹具与既有调用点里以位置参数构造;
+     * 旧口子必须继续可用,且不得伪造任何详情值(数组给空、其余 null)。</p>
+     */
+    public CockpitWorkOrderSummary(
+            Long orderId,
+            String workOrderCode,
+            String deviceCode,
+            Integer orderLevel,
+            String orderDesc,
+            Integer stateCode,
+            String stateName,
+            String createTime,
+            String updateTime,
+            String planFinishTime,
+            String realFinishTime,
+            CockpitWorkOrderEventAssociation eventAssociation,
+            boolean associatedWithCurrentEvent) {
+        this(orderId, workOrderCode, deviceCode, orderLevel, orderDesc, stateCode, stateName,
+                createTime, updateTime, planFinishTime, realFinishTime, eventAssociation,
+                associatedWithCurrentEvent, null, null, null, null, null, null,
+                Collections.emptyList(), Collections.emptyList(), null);
     }
     }
 
 
     /**
     /**
@@ -75,4 +142,23 @@ public class CockpitWorkOrderSummary {
      * 而不是让调用方从 {@code eventAssociation == null} 反推(执行票 12 范围 1)。
      * 而不是让调用方从 {@code eventAssociation == null} 反推(执行票 12 范围 1)。
      */
      */
     public boolean isAssociatedWithCurrentEvent() { return associatedWithCurrentEvent; }
     public boolean isAssociatedWithCurrentEvent() { return associatedWithCurrentEvent; }
+
+    /** 故障发生时间(ISO-8601,Asia/Shanghai 偏移);缺值 null。 */
+    public String getFaultTime() { return faultTime; }
+    /** 关联设备名称;设备缺失时 null(不拿设备编码冒充)。 */
+    public String getDeviceName() { return deviceName; }
+    /** 设备安装位置;缺失 null。 */
+    public String getDeviceLocation() { return deviceLocation; }
+    /** 优先级中文名(work_order_level 字典);字典缺项 null。 */
+    public String getOrderLevelName() { return orderLevelName; }
+    /** 处置人姓名;用户缺失/已停用时 null。 */
+    public String getReceiveUserName() { return receiveUserName; }
+    /** 核验人姓名;未核验或用户缺失时 null。 */
+    public String getVerifyUserName() { return verifyUserName; }
+    /** 维修前图片 URL 数组;无图空数组。 */
+    public List<String> getMaintenanceBeforeImages() { return maintenanceBeforeImages; }
+    /** 维修后图片 URL 数组;无图空数组。 */
+    public List<String> getMaintenanceAfterImages() { return maintenanceAfterImages; }
+    /** 延期申请详情;无申请时 null。 */
+    public CockpitWorkOrderDelayApply getDelayApply() { return delayApply; }
 }
 }

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

@@ -1,7 +1,6 @@
 package com.zksy.drainage.domain;
 package com.zksy.drainage.domain;
 
 
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.IdType;
-import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonFormat;
@@ -25,25 +24,12 @@ public class DrainagePartition {
     @ApiModelProperty("监测点名称")
     @ApiModelProperty("监测点名称")
     private String name;
     private String name;
 
 
-    @ApiModelProperty("行政区域")
+    @ApiModelProperty("地址")
     private String district;
     private String district;
 
 
     @ApiModelProperty("分区类型(雨水分区/污水分区)")
     @ApiModelProperty("分区类型(雨水分区/污水分区)")
     private String partitionType;
     private String partitionType;
 
 
-    @ApiModelProperty("数据时间")
-    private String time;
-
-    @ApiModelProperty("排水量")
-    private BigDecimal drainage;
-
-    @ApiModelProperty("积水量")
-    private BigDecimal waterlogging;
-
-    @ApiModelProperty("积水等级")
-    @TableField("\"level\"")
-    private Integer level;
-
     @ApiModelProperty("经度")
     @ApiModelProperty("经度")
     private BigDecimal longitude;
     private BigDecimal longitude;
 
 

+ 5 - 19
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/domain/WaterloggingPoint.java

@@ -18,7 +18,8 @@ import java.time.LocalDateTime;
  * 易积水点台账
  * 易积水点台账
  *
  *
  * 一个易积水点在地图上就是一个位置,直接落 WGS84 经纬度;
  * 一个易积水点在地图上就是一个位置,直接落 WGS84 经纬度;
- * 关联的是视频摄像头(equipment_base.equipment_id),不是通用监测设备。
+ * 关联的是设备(equipment_base.equipment_id),限 equipment_type.id 为 16(雷达液位计)
+ * 与 20(视频监控-排口+内涝点)两类。
  * 责任单位 / 责任人通过 duty_dept_id、duty_user_id 关联系统部门与用户,
  * 责任单位 / 责任人通过 duty_dept_id、duty_user_id 关联系统部门与用户,
  * duty_unit、duty_person、duty_phone 存当时的名称与号码快照。
  * duty_unit、duty_person、duty_phone 存当时的名称与号码快照。
  */
  */
@@ -50,22 +51,6 @@ public class WaterloggingPoint {
     @ApiModelProperty("WGS84 纬度")
     @ApiModelProperty("WGS84 纬度")
     private BigDecimal latitude;
     private BigDecimal latitude;
 
 
-    @ApiModelProperty("积水程度(0未积水 1轻度 2中度 3严重)")
-    @TableField("waterlogging_level")
-    private Integer waterloggingLevel;
-
-    @ApiModelProperty("积水深度(cm)")
-    @TableField("water_depth")
-    private BigDecimal waterDepth;
-
-    @ApiModelProperty("积水量(m³)")
-    @TableField("water_volume")
-    private BigDecimal waterVolume;
-
-    @ApiModelProperty("积水面积(m²)")
-    @TableField("water_area")
-    private BigDecimal waterArea;
-
     @ApiModelProperty("风险等级(0低 1中 2高)")
     @ApiModelProperty("风险等级(0低 1中 2高)")
     @TableField("risk_level")
     @TableField("risk_level")
     private String riskLevel;
     private String riskLevel;
@@ -90,8 +75,9 @@ public class WaterloggingPoint {
     @TableField("duty_phone")
     @TableField("duty_phone")
     private String dutyPhone;
     private String dutyPhone;
 
 
-    @ApiModelProperty("关联摄像头ID(多个用逗号分隔)")
-    private String cameraIds;
+    @ApiModelProperty("关联设备ID(equipment_base.equipment_id,多个用逗号分隔,限设备类型 16/20)")
+    @TableField("equipment_ids")
+    private String equipmentIds;
 
 
     @ApiModelProperty("备注")
     @ApiModelProperty("备注")
     private String remark;
     private String remark;

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

@@ -23,9 +23,6 @@ public class WaterloggingPointPageInDTO implements Serializable {
     @ApiModelProperty(value = "所属片区(字典 drainage_district:0城南 1城北 2太常,精确匹配)")
     @ApiModelProperty(value = "所属片区(字典 drainage_district:0城南 1城北 2太常,精确匹配)")
     private String district;
     private String district;
 
 
-    @ApiModelProperty(value = "积水程度(0未积水 1轻度 2中度 3严重)")
-    private Integer waterloggingLevel;
-
     @ApiModelProperty(value = "风险等级(0低 1中 2高)")
     @ApiModelProperty(value = "风险等级(0低 1中 2高)")
     private String riskLevel;
     private String riskLevel;
 
 

+ 2 - 2
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/mapper/DrainageVideoMapper.java

@@ -12,7 +12,7 @@ public interface DrainageVideoMapper {
         "e.district,e.equipment_location AS location,e.longitude,e.latitude,v.source_type," +
         "e.district,e.equipment_location AS location,e.longitude,e.latitude,v.source_type," +
         "w.point_id AS point_id,w.point_name AS point_name,(f.user_id IS NOT NULL) AS favorite " +
         "w.point_id AS point_id,w.point_name AS point_name,(f.user_id IS NOT NULL) AS favorite " +
         "FROM app_user.equipment_base e JOIN app_user.equipment_video_binding v ON v.equipment_id=e.equipment_id " +
         "FROM app_user.equipment_base e JOIN app_user.equipment_video_binding v ON v.equipment_id=e.equipment_id " +
-        "LEFT JOIN app_user.drainage_waterlogging_point w ON STRPOS(CONCAT(',',REPLACE(COALESCE(w.camera_ids,''),' ',''),','),CONCAT(',',e.equipment_id,','))>0 " +
+        "LEFT JOIN app_user.drainage_waterlogging_point w ON STRPOS(CONCAT(',',REPLACE(COALESCE(w.equipment_ids,''),' ',''),','),CONCAT(',',e.equipment_id,','))>0 " +
         "LEFT JOIN app_user.drainage_video_favorite f ON f.equipment_id=e.equipment_id AND f.user_id=#{userId} ";
         "LEFT JOIN app_user.drainage_video_favorite f ON f.equipment_id=e.equipment_id AND f.user_id=#{userId} ";
     String FILTER = "WHERE e.equipment_type_id=20 AND e.del_flag='0' " +
     String FILTER = "WHERE e.equipment_type_id=20 AND e.del_flag='0' " +
         "<if test='query != null and query != &quot;&quot;'>AND (e.equipment_name LIKE CONCAT('%',#{query},'%') OR e.equipment_code LIKE CONCAT('%',#{query},'%'))</if> " +
         "<if test='query != null and query != &quot;&quot;'>AND (e.equipment_name LIKE CONCAT('%',#{query},'%') OR e.equipment_code LIKE CONCAT('%',#{query},'%'))</if> " +
@@ -42,6 +42,6 @@ public interface DrainageVideoMapper {
     @Delete("DELETE FROM app_user.drainage_video_favorite WHERE user_id=#{userId} AND equipment_id=#{videoId}")
     @Delete("DELETE FROM app_user.drainage_video_favorite WHERE user_id=#{userId} AND equipment_id=#{videoId}")
     int unfavorite(@Param("userId") Long userId,@Param("videoId") String videoId);
     int unfavorite(@Param("userId") Long userId,@Param("videoId") String videoId);
 
 
-    @Update("UPDATE app_user.drainage_waterlogging_point SET camera_ids=#{equipmentIds},update_time=CURRENT_TIMESTAMP WHERE point_id=#{pointId}")
+    @Update("UPDATE app_user.drainage_waterlogging_point SET equipment_ids=#{equipmentIds},update_time=CURRENT_TIMESTAMP WHERE point_id=#{pointId}")
     int updatePoint(@Param("pointId") String pointId,@Param("equipmentIds") String equipmentIds);
     int updatePoint(@Param("pointId") String pointId,@Param("equipmentIds") String equipmentIds);
 }
 }

+ 3 - 3
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/DrainageVideoService.java

@@ -75,16 +75,16 @@ public class DrainageVideoService {
         if(pointId!=null&&!pointId.isBlank()) {
         if(pointId!=null&&!pointId.isBlank()) {
             target=all.stream().filter(p->pointId.equals(p.getPointId())).findFirst().orElseThrow(()->new ServiceException("易积水点不存在"));
             target=all.stream().filter(p->pointId.equals(p.getPointId())).findFirst().orElseThrow(()->new ServiceException("易积水点不存在"));
             for(WaterloggingPoint point:all) {
             for(WaterloggingPoint point:all) {
-                if(!pointId.equals(point.getPointId())&&ids(point.getCameraIds()).contains(videoId))
+                if(!pointId.equals(point.getPointId())&&ids(point.getEquipmentIds()).contains(videoId))
                     throw new ServiceException("视频已关联其他易积水点,请先解除关联");
                     throw new ServiceException("视频已关联其他易积水点,请先解除关联");
             }
             }
             Map<String,String> occupied=binding.findBoundEquipment(DrainageEquipmentBindingService.TYPE_WATERLOGGING,pointId);
             Map<String,String> occupied=binding.findBoundEquipment(DrainageEquipmentBindingService.TYPE_WATERLOGGING,pointId);
             if(occupied.containsKey(videoId))throw new ServiceException("视频已被其他位置关联:"+occupied.get(videoId));
             if(occupied.containsKey(videoId))throw new ServiceException("视频已被其他位置关联:"+occupied.get(videoId));
-            Set<String> merged=ids(target.getCameraIds());merged.add(videoId);
+            Set<String> merged=ids(target.getEquipmentIds());merged.add(videoId);
             videos.updatePoint(pointId,String.join(",",merged));
             videos.updatePoint(pointId,String.join(",",merged));
         } else {
         } else {
             for(WaterloggingPoint point:all) {
             for(WaterloggingPoint point:all) {
-                Set<String> existing=ids(point.getCameraIds());
+                Set<String> existing=ids(point.getEquipmentIds());
                 if(existing.remove(videoId))videos.updatePoint(point.getPointId(),String.join(",",existing));
                 if(existing.remove(videoId))videos.updatePoint(point.getPointId(),String.join(",",existing));
             }
             }
         }
         }

+ 5 - 3
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/WaterloggingPointService.java

@@ -24,7 +24,7 @@ public interface WaterloggingPointService extends IService<WaterloggingPoint> {
     List<WaterloggingPoint> listForMap(WaterloggingPointPageInDTO dto);
     List<WaterloggingPoint> listForMap(WaterloggingPointPageInDTO dto);
 
 
     /**
     /**
-     * 筛选下拉项:所属区域、积水程度的库内去重值
+     * 筛选下拉项:风险等级的库内去重值
      */
      */
     Map<String, List<String>> getFilterOptions();
     Map<String, List<String>> getFilterOptions();
 
 
@@ -49,7 +49,9 @@ public interface WaterloggingPointService extends IService<WaterloggingPoint> {
     boolean removeBatchWithCheck(List<String> ids);
     boolean removeBatchWithCheck(List<String> ids);
 
 
     /**
     /**
-     * 关联摄像头到易积水点(整体替换,传空列表表示解除全部关联)
+     * 关联设备到易积水点(整体替换,传空列表表示解除全部关联)
+     *
+     * 只接受 equipment_type.id 为 16(雷达液位计)、20(视频监控-排口+内涝点)的设备。
      */
      */
-    boolean bindCameras(String pointId, List<String> cameraIds);
+    boolean bindDevices(String pointId, List<String> equipmentIds);
 }
 }

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

@@ -57,12 +57,12 @@ public class DrainageEquipmentBindingServiceImpl implements DrainageEquipmentBin
             addBindings(result, TYPE_FACILITY, item.getFacilityId(), item.getFacilityName(), item.getEquipmentId(),
             addBindings(result, TYPE_FACILITY, item.getFacilityId(), item.getFacilityName(), item.getEquipmentId(),
                     excludeType, excludeId, "工程设施");
                     excludeType, excludeId, "工程设施");
         }
         }
-        // 易积水点关联的是摄像头(equipment_base.equipment_type_id=20),同样参与占用校验
+        // 易积水点关联的是设备(equipment_type.id 为 16/20),同样参与占用校验
         for (WaterloggingPoint item : waterloggingPointMapper.selectList(
         for (WaterloggingPoint item : waterloggingPointMapper.selectList(
                 new LambdaQueryWrapper<WaterloggingPoint>().select(
                 new LambdaQueryWrapper<WaterloggingPoint>().select(
                         WaterloggingPoint::getPointId, WaterloggingPoint::getPointName,
                         WaterloggingPoint::getPointId, WaterloggingPoint::getPointName,
-                        WaterloggingPoint::getCameraIds))) {
-            addBindings(result, TYPE_WATERLOGGING, item.getPointId(), item.getPointName(), item.getCameraIds(),
+                        WaterloggingPoint::getEquipmentIds))) {
+            addBindings(result, TYPE_WATERLOGGING, item.getPointId(), item.getPointName(), item.getEquipmentIds(),
                     excludeType, excludeId, "易积水点");
                     excludeType, excludeId, "易积水点");
         }
         }
         return result;
         return result;
@@ -112,8 +112,8 @@ public class DrainageEquipmentBindingServiceImpl implements DrainageEquipmentBin
                 facility.setEquipmentId(value);
                 facility.setEquipmentId(value);
                 return engineeringFacilityMapper.updateById(facility) > 0;
                 return engineeringFacilityMapper.updateById(facility) > 0;
             case TYPE_WATERLOGGING:
             case TYPE_WATERLOGGING:
-                // 易积水点关联的是摄像头,走 WaterloggingPointService.bindCameras,不再共用设备关联入口
-                throw new ServiceException("易积水点关联的是摄像头,请使用关联摄像头功能");
+                // 易积水点关联的是设备,走 WaterloggingPointService.bindDevices,不再共用设备关联入口
+                throw new ServiceException("易积水点请使用关联设备功能");
             default:
             default:
                 return false;
                 return false;
         }
         }

+ 12 - 98
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/DrainageRiskServiceImpl.java

@@ -10,12 +10,10 @@ import com.zksy.base.domain.PipeNetworkBase;
 import com.zksy.base.mapper.EquipmentBaseMapper;
 import com.zksy.base.mapper.EquipmentBaseMapper;
 import com.zksy.base.mapper.EquipmentTypeMapper;
 import com.zksy.base.mapper.EquipmentTypeMapper;
 import com.zksy.base.mapper.PipeNetworkBaseMapper;
 import com.zksy.base.mapper.PipeNetworkBaseMapper;
-import com.zksy.drainage.domain.DrainageWarning;
 import com.zksy.drainage.domain.EngineeringFacility;
 import com.zksy.drainage.domain.EngineeringFacility;
 import com.zksy.drainage.domain.WaterloggingPoint;
 import com.zksy.drainage.domain.WaterloggingPoint;
 import com.zksy.drainage.dto.DrainageRiskItemVO;
 import com.zksy.drainage.dto.DrainageRiskItemVO;
 import com.zksy.drainage.dto.DrainageRiskPageInDTO;
 import com.zksy.drainage.dto.DrainageRiskPageInDTO;
-import com.zksy.drainage.mapper.DrainageWarningMapper;
 import com.zksy.drainage.mapper.EngineeringFacilityMapper;
 import com.zksy.drainage.mapper.EngineeringFacilityMapper;
 import com.zksy.drainage.mapper.WaterloggingPointMapper;
 import com.zksy.drainage.mapper.WaterloggingPointMapper;
 import com.zksy.drainage.service.DrainageRiskService;
 import com.zksy.drainage.service.DrainageRiskService;
@@ -45,10 +43,11 @@ import java.util.stream.Collectors;
  * 排水管网综合风险评估实现
  * 排水管网综合风险评估实现
  *
  *
  * 评估对象为 pipe_network_base 中 network_type=1 的排水管网,输入数据全部来自本系统已有业务表:
  * 评估对象为 pipe_network_base 中 network_type=1 的排水管网,输入数据全部来自本系统已有业务表:
- * 设备台账(equipment_base)、报警(alarm_data)、预警(early_warning)、
+ * 设备台账(equipment_base)、报警(alarm_data)、
  * 易积水点(drainage_waterlogging_point)、工程设施(drainage_engineering_facility)。
  * 易积水点(drainage_waterlogging_point)、工程设施(drainage_engineering_facility)。
  *
  *
- * 评分模型为 4 个维度合计 100 分:管网本体 35、运行报警 35、环境叠加 20、数据质量 10。
+ * 评分模型仅保留管网本体一个维度:管网本体 35 分(管龄/材质/管径/管线类别),
+ * 按 35 分制得分折算为百分制总分。报警、易积水点等数据仅作展示与风险构成要素,不参与计分。
  * 结果整体走内存快照,避免逐行查库,也保证列表、统计、地图三处口径一致。
  * 结果整体走内存快照,避免逐行查库,也保证列表、统计、地图三处口径一致。
  */
  */
 @Slf4j
 @Slf4j
@@ -89,9 +88,6 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
     @Autowired
     @Autowired
     private AlarmDataMapper alarmDataMapper;
     private AlarmDataMapper alarmDataMapper;
 
 
-    @Autowired
-    private DrainageWarningMapper drainageWarningMapper;
-
     @Autowired
     @Autowired
     private WaterloggingPointMapper waterloggingPointMapper;
     private WaterloggingPointMapper waterloggingPointMapper;
 
 
@@ -204,7 +200,7 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
             assessBlock.put("riskLevelName", levelName(assessment.level));
             assessBlock.put("riskLevelName", levelName(assessment.level));
             assessBlock.put("riskColor", levelColor(assessment.level));
             assessBlock.put("riskColor", levelColor(assessment.level));
             assessBlock.put("dimensions", assessment.dimensions);
             assessBlock.put("dimensions", assessment.dimensions);
-            assessBlock.put("assessmentModel", "排水管网综合风险模型 v1(本体/报警/环境/数据质量)");
+            assessBlock.put("assessmentModel", "排水管网综合风险模型 v2(管网本体)");
             assessBlock.put("assessmentTime", current.loadTime);
             assessBlock.put("assessmentTime", current.loadTime);
         }
         }
 
 
@@ -298,12 +294,7 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
                 .map(EquipmentBase::getEquipmentCode)
                 .map(EquipmentBase::getEquipmentCode)
                 .filter(Objects::nonNull)
                 .filter(Objects::nonNull)
                 .collect(Collectors.toSet());
                 .collect(Collectors.toSet());
-        Set<String> drainageEquipmentIds = equipments.stream()
-                .map(EquipmentBase::getEquipmentId)
-                .filter(Objects::nonNull)
-                .collect(Collectors.toSet());
         Map<String, long[]> alarmStat = loadAlarmStat(drainageEquipmentCodes);
         Map<String, long[]> alarmStat = loadAlarmStat(drainageEquipmentCodes);
-        Map<String, Long> warningStat = loadWarningStat(drainageEquipmentIds);
         List<WaterloggingPoint> waterloggingPoints = loadWaterloggingPoints();
         List<WaterloggingPoint> waterloggingPoints = loadWaterloggingPoints();
         List<EngineeringFacility> facilities = loadFacilities();
         List<EngineeringFacility> facilities = loadFacilities();
 
 
@@ -320,7 +311,6 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
             int alarmCount = 0;
             int alarmCount = 0;
             int openAlarmCount = 0;
             int openAlarmCount = 0;
             int highAlarmCount = 0;
             int highAlarmCount = 0;
-            long openWarningCount = 0;
             for (EquipmentBase equipment : matched) {
             for (EquipmentBase equipment : matched) {
                 long[] stat = alarmStat.get(equipment.getEquipmentCode());
                 long[] stat = alarmStat.get(equipment.getEquipmentCode());
                 if (stat != null) {
                 if (stat != null) {
@@ -328,17 +318,13 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
                     openAlarmCount += (int) stat[1];
                     openAlarmCount += (int) stat[1];
                     highAlarmCount += (int) stat[2];
                     highAlarmCount += (int) stat[2];
                 }
                 }
-                Long warning = warningStat.get(equipment.getEquipmentId());
-                if (warning != null) {
-                    openWarningCount += warning;
-                }
             }
             }
 
 
             int waterloggingCount = countPointsWithin(pipe, waterloggingPoints, WATERLOGGING_RADIUS_METERS);
             int waterloggingCount = countPointsWithin(pipe, waterloggingPoints, WATERLOGGING_RADIUS_METERS);
             int facilityCount = countFacilitiesWithin(pipe, facilities, FACILITY_RADIUS_METERS);
             int facilityCount = countFacilitiesWithin(pipe, facilities, FACILITY_RADIUS_METERS);
 
 
             Assessment assessment = assess(pipe, matched.size(), alarmCount, openAlarmCount,
             Assessment assessment = assess(pipe, matched.size(), alarmCount, openAlarmCount,
-                    highAlarmCount, (int) openWarningCount, waterloggingCount, facilityCount);
+                    highAlarmCount, waterloggingCount, facilityCount);
 
 
             DrainageRiskItemVO row = toRow(pipe, matched.size(), alarmCount, openAlarmCount,
             DrainageRiskItemVO row = toRow(pipe, matched.size(), alarmCount, openAlarmCount,
                     waterloggingCount, assessment);
                     waterloggingCount, assessment);
@@ -448,36 +434,6 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
         return result;
         return result;
     }
     }
 
 
-    /**
-     * 近30天未闭环预警按设备ID聚合
-     *
-     * 只统计传入的排水设备ID,early_warning 中其他业务线的预警不进统计。
-     */
-    private Map<String, Long> loadWarningStat(Set<String> drainageEquipmentIds) {
-        Map<String, Long> result = new HashMap<>();
-        if (drainageEquipmentIds.isEmpty()) {
-            return result;
-        }
-        try {
-            QueryWrapper<DrainageWarning> wrapper = new QueryWrapper<>();
-            wrapper.select("equipment_id as equipment_id", "count(*) as total_cnt")
-                    .ge("create_time", LocalDateTime.now().minusDays(RUNNING_WINDOW_DAYS))
-                    .in("equipment_id", drainageEquipmentIds)
-                    .and(w -> w.isNull("status").or().ne("status", "CLOSED"))
-                    .groupBy("equipment_id");
-            List<Map<String, Object>> rows = drainageWarningMapper.selectMaps(wrapper);
-            for (Map<String, Object> row : rows) {
-                String equipmentId = str(row, "equipment_id");
-                if (equipmentId != null) {
-                    result.put(equipmentId, num(row, "total_cnt"));
-                }
-            }
-        } catch (Exception e) {
-            log.warn("统计排水管网预警数据失败", e);
-        }
-        return result;
-    }
-
     private List<WaterloggingPoint> loadWaterloggingPoints() {
     private List<WaterloggingPoint> loadWaterloggingPoints() {
         try {
         try {
             LambdaQueryWrapper<WaterloggingPoint> wrapper = new LambdaQueryWrapper<>();
             LambdaQueryWrapper<WaterloggingPoint> wrapper = new LambdaQueryWrapper<>();
@@ -570,10 +526,12 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
     /* ==================== 评分模型 ==================== */
     /* ==================== 评分模型 ==================== */
 
 
     /**
     /**
-     * 四维评分:管网本体 35 + 运行报警 35 + 环境叠加 20 + 数据质量 10
+     * 评分仅保留管网本体维度:管网本体 35 分(管龄/材质/管径/管线类别),折算为百分制总分。
+     *
+     * 报警、易积水点、设施等数据保留用于展示与风险构成要素,不再单独计分。
      */
      */
     private Assessment assess(PipeNetworkBase pipe, int equipmentCount, int alarmCount, int openAlarmCount,
     private Assessment assess(PipeNetworkBase pipe, int equipmentCount, int alarmCount, int openAlarmCount,
-                              int highAlarmCount, int openWarningCount, int waterloggingCount, int facilityCount) {
+                              int highAlarmCount, int waterloggingCount, int facilityCount) {
         int age = pipeAge(pipe.getBuildDate());
         int age = pipeAge(pipe.getBuildDate());
 
 
         int ageScore = age <= 5 ? 3 : age <= 10 ? 8 : age <= 15 ? 12 : age <= 20 ? 14 : 15;
         int ageScore = age <= 5 ? 3 : age <= 10 ? 8 : age <= 15 ? 12 : age <= 20 ? 14 : 15;
@@ -582,23 +540,7 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
         int levelScore = levelScore(pipe.getNetworkLevel());
         int levelScore = levelScore(pipe.getNetworkLevel());
         int pipeScore = ageScore + materialScore + diameterScore + levelScore;
         int pipeScore = ageScore + materialScore + diameterScore + levelScore;
 
 
-        int alarmScore = alarmCount <= 0 ? 0 : alarmCount <= 2 ? 8 : alarmCount <= 5 ? 12 : 15;
-        int openScore = openAlarmCount <= 0 ? 0 : openAlarmCount == 1 ? 5 : openAlarmCount == 2 ? 8 : 10;
-        int highScore = highAlarmCount <= 0 ? 0 : highAlarmCount == 1 ? 5 : 10;
-        int runningScore = alarmScore + openScore + highScore;
-
-        int waterScore = waterloggingCount <= 0 ? 0 : waterloggingCount == 1 ? 5 : waterloggingCount == 2 ? 7 : 10;
-        int warningScore = openWarningCount <= 0 ? 0 : openWarningCount == 1 ? 4 : 6;
-        int facilityScore = facilityCount > 0 ? 4 : 0;
-        int environmentScore = waterScore + warningScore + facilityScore;
-
-        int missingCoordinate = hasAnyCoordinate(pipe) ? 0 : 4;
-        int missingMaterial = isBlank(pipe.getMaterial()) ? 3 : 0;
-        int missingDimension = isBlank(pipe.getLength() == null ? null : pipe.getLength().toPlainString())
-                || pipe.getDiameter() == null ? 3 : 0;
-        int qualityScore = missingCoordinate + missingMaterial + missingDimension;
-
-        int total = Math.min(100, pipeScore + runningScore + environmentScore + qualityScore);
+        int total = (int) Math.round(Math.min(35, pipeScore) / 35.0 * 100.0);
         String level = total >= 70 ? LEVEL_HIGH : total >= 40 ? LEVEL_MEDIUM : LEVEL_LOW;
         String level = total >= 70 ? LEVEL_HIGH : total >= 40 ? LEVEL_MEDIUM : LEVEL_LOW;
 
 
         Assessment assessment = new Assessment();
         Assessment assessment = new Assessment();
@@ -608,10 +550,7 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
         assessment.openAlarmCount = openAlarmCount;
         assessment.openAlarmCount = openAlarmCount;
         assessment.waterloggingCount = waterloggingCount;
         assessment.waterloggingCount = waterloggingCount;
         assessment.dimensions = dimensions(pipeScore, ageScore, materialScore, diameterScore, levelScore,
         assessment.dimensions = dimensions(pipeScore, ageScore, materialScore, diameterScore, levelScore,
-                runningScore, alarmScore, openScore, highScore,
-                environmentScore, waterScore, warningScore, facilityScore,
-                qualityScore, missingCoordinate, missingMaterial, missingDimension,
-                age, pipe.getMaterial(), pipe.getDiameter(), waterloggingCount, facilityCount);
+                age, pipe.getMaterial(), pipe.getDiameter());
         assessment.factors = factors(pipe, age, alarmCount, openAlarmCount, highAlarmCount,
         assessment.factors = factors(pipe, age, alarmCount, openAlarmCount, highAlarmCount,
                 waterloggingCount, facilityCount);
                 waterloggingCount, facilityCount);
         assessment.measures = measures(level, age, alarmCount, openAlarmCount, waterloggingCount);
         assessment.measures = measures(level, age, alarmCount, openAlarmCount, waterloggingCount);
@@ -621,11 +560,7 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
     }
     }
 
 
     private List<Map<String, Object>> dimensions(int pipeScore, int ageScore, int materialScore, int diameterScore,
     private List<Map<String, Object>> dimensions(int pipeScore, int ageScore, int materialScore, int diameterScore,
-                                                 int levelScore, int runningScore, int alarmScore, int openScore,
-                                                 int highScore, int environmentScore, int waterScore, int warningScore,
-                                                 int facilityScore, int qualityScore, int missingCoordinate,
-                                                 int missingMaterial, int missingDimension, int age, String material,
-                                                 BigDecimal diameter, int waterloggingCount, int facilityCount) {
+                                                 int levelScore, int age, String material, BigDecimal diameter) {
         List<Map<String, Object>> dimensions = new ArrayList<>();
         List<Map<String, Object>> dimensions = new ArrayList<>();
 
 
         Map<String, Object> pipeDim = dimension("pipe", "管网本体", pipeScore, 35);
         Map<String, Object> pipeDim = dimension("pipe", "管网本体", pipeScore, 35);
@@ -635,24 +570,6 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
         addItem(pipeDim, "管线类别", levelScore, "按类别影响范围计分");
         addItem(pipeDim, "管线类别", levelScore, "按类别影响范围计分");
         dimensions.add(pipeDim);
         dimensions.add(pipeDim);
 
 
-        Map<String, Object> runningDim = dimension("running", "运行报警", runningScore, 35);
-        addItem(runningDim, "近30天报警", alarmScore, alarmScore + " 分");
-        addItem(runningDim, "未处置报警", openScore, openScore + " 分");
-        addItem(runningDim, "高等级报警", highScore, highScore + " 分");
-        dimensions.add(runningDim);
-
-        Map<String, Object> envDim = dimension("environment", "环境叠加", environmentScore, 20);
-        addItem(envDim, "周边易积水点", waterScore, waterloggingCount + " 处");
-        addItem(envDim, "周边未闭环预警", warningScore, "按关联设备预警计分");
-        addItem(envDim, "周边工程设施", facilityScore, facilityCount + " 处");
-        dimensions.add(envDim);
-
-        Map<String, Object> qualityDim = dimension("quality", "数据质量", qualityScore, 10);
-        addItem(qualityDim, "坐标完整性", missingCoordinate, missingCoordinate > 0 ? "缺起终点坐标" : "正常");
-        addItem(qualityDim, "材质完整性", missingMaterial, missingMaterial > 0 ? "缺材质" : "正常");
-        addItem(qualityDim, "规格完整性", missingDimension, missingDimension > 0 ? "缺管径或长度" : "正常");
-        dimensions.add(qualityDim);
-
         return dimensions;
         return dimensions;
     }
     }
 
 
@@ -709,9 +626,6 @@ public class DrainageRiskServiceImpl implements DrainageRiskService {
         if (facilityCount > 0) {
         if (facilityCount > 0) {
             factors.add("周边 " + (int) FACILITY_RADIUS_METERS + " 米内存在 " + facilityCount + " 处泵站/闸门等设施");
             factors.add("周边 " + (int) FACILITY_RADIUS_METERS + " 米内存在 " + facilityCount + " 处泵站/闸门等设施");
         }
         }
-        if (!hasAnyCoordinate(pipe)) {
-            factors.add("缺少起终点坐标,未能完成空间关联,实际风险可能被低估");
-        }
         if (factors.isEmpty()) {
         if (factors.isEmpty()) {
             factors.add("管网本体状态良好,近 " + RUNNING_WINDOW_DAYS + " 天无关联报警");
             factors.add("管网本体状态良好,近 " + RUNNING_WINDOW_DAYS + " 天无关联报警");
         }
         }

+ 64 - 28
pipe-network-service/zksy-system/src/main/java/com/zksy/drainage/service/impl/WaterloggingPointServiceImpl.java

@@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
 import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.enums.EquipmentTypeEnum;
+import com.zksy.base.mapper.EquipmentBaseMapper;
 import com.zksy.common.exception.ServiceException;
 import com.zksy.common.exception.ServiceException;
 import com.zksy.drainage.domain.WaterloggingPoint;
 import com.zksy.drainage.domain.WaterloggingPoint;
 import com.zksy.drainage.dto.WaterloggingPointPageInDTO;
 import com.zksy.drainage.dto.WaterloggingPointPageInDTO;
@@ -16,10 +19,13 @@ import org.springframework.transaction.annotation.Transactional;
 
 
 import java.time.LocalDateTime;
 import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.Collectors;
 
 
@@ -31,9 +37,20 @@ import java.util.stream.Collectors;
 public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointMapper, WaterloggingPoint>
 public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointMapper, WaterloggingPoint>
         implements WaterloggingPointService {
         implements WaterloggingPointService {
 
 
+    /**
+     * 易积水点只接受两类设备:16 雷达液位计、20 视频监控(排口+内涝点)
+     */
+    private static final Set<Integer> ALLOWED_EQUIPMENT_TYPE_IDS = Collections.unmodifiableSet(
+            new LinkedHashSet<>(Arrays.asList(
+                    EquipmentTypeEnum.RADAR_LEVEL_GAUGE.getId(),
+                    EquipmentTypeEnum.VIDEO_MONITOR_OUT_WL.getId())));
+
     @org.springframework.beans.factory.annotation.Autowired
     @org.springframework.beans.factory.annotation.Autowired
     private com.zksy.drainage.mapper.DrainageBindingLockMapper bindingLock;
     private com.zksy.drainage.mapper.DrainageBindingLockMapper bindingLock;
 
 
+    @org.springframework.beans.factory.annotation.Autowired
+    private EquipmentBaseMapper equipmentBaseMapper;
+
     @Override
     @Override
     public Page<WaterloggingPoint> findByPage(WaterloggingPointPageInDTO dto) {
     public Page<WaterloggingPoint> findByPage(WaterloggingPointPageInDTO dto) {
         WaterloggingPointPageInDTO query = dto == null ? new WaterloggingPointPageInDTO() : dto;
         WaterloggingPointPageInDTO query = dto == null ? new WaterloggingPointPageInDTO() : dto;
@@ -57,7 +74,6 @@ public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointM
         Map<String, List<String>> options = new LinkedHashMap<>();
         Map<String, List<String>> options = new LinkedHashMap<>();
         // district 不再参与:所属片区改由字典 drainage_district(0城南/1城北/2太常)提供选项。
         // district 不再参与:所属片区改由字典 drainage_district(0城南/1城北/2太常)提供选项。
         // 用存量值去重当下拉项会把历史脏数据回灌到界面,这条路径已废弃。
         // 用存量值去重当下拉项会把历史脏数据回灌到界面,这条路径已废弃。
-        options.put("waterloggingLevel", distinctValues(WaterloggingPoint::getWaterloggingLevel));
         options.put("riskLevel", distinctValues(WaterloggingPoint::getRiskLevel));
         options.put("riskLevel", distinctValues(WaterloggingPoint::getRiskLevel));
         return options;
         return options;
     }
     }
@@ -71,8 +87,6 @@ public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointM
         wrapper.like(hasText(query.getPointName()), WaterloggingPoint::getPointName, query.getPointName());
         wrapper.like(hasText(query.getPointName()), WaterloggingPoint::getPointName, query.getPointName());
         // 片区存的是字典编码(0/1/2),必须精确匹配;like 会让 '0' 命中 '10' 这类越界值
         // 片区存的是字典编码(0/1/2),必须精确匹配;like 会让 '0' 命中 '10' 这类越界值
         wrapper.eq(hasText(query.getDistrict()), WaterloggingPoint::getDistrict, query.getDistrict());
         wrapper.eq(hasText(query.getDistrict()), WaterloggingPoint::getDistrict, query.getDistrict());
-        wrapper.eq(query.getWaterloggingLevel() != null,
-                WaterloggingPoint::getWaterloggingLevel, query.getWaterloggingLevel());
         wrapper.eq(hasText(query.getRiskLevel()), WaterloggingPoint::getRiskLevel, query.getRiskLevel());
         wrapper.eq(hasText(query.getRiskLevel()), WaterloggingPoint::getRiskLevel, query.getRiskLevel());
         wrapper.orderByDesc(WaterloggingPoint::getCreateTime);
         wrapper.orderByDesc(WaterloggingPoint::getCreateTime);
         return wrapper;
         return wrapper;
@@ -101,12 +115,12 @@ public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointM
     @Transactional
     @Transactional
     public boolean saveWithCheck(WaterloggingPoint entity) {
     public boolean saveWithCheck(WaterloggingPoint entity) {
         bindingLock.lock();
         bindingLock.lock();
-        String cameraIds = entity.getCameraIds();
-        entity.setCameraIds(null);
+        String equipmentIds = entity.getEquipmentIds();
+        entity.setEquipmentIds(null);
         entity.setCreateTime(LocalDateTime.now());
         entity.setCreateTime(LocalDateTime.now());
         entity.setUpdateTime(LocalDateTime.now());
         entity.setUpdateTime(LocalDateTime.now());
         if (!this.save(entity)) return false;
         if (!this.save(entity)) return false;
-        return applyCameras(entity.getPointId(), cameraIds);
+        return applyDevices(entity.getPointId(), equipmentIds);
     }
     }
 
 
     @Override
     @Override
@@ -117,57 +131,79 @@ public class WaterloggingPointServiceImpl extends ServiceImpl<WaterloggingPointM
         if (this.getById(pointId) == null) {
         if (this.getById(pointId) == null) {
             throw new ServiceException("易积水点不存在,无法修改:" + pointId);
             throw new ServiceException("易积水点不存在,无法修改:" + pointId);
         }
         }
-        String cameraIds = entity.getCameraIds();
-        entity.setCameraIds(null);
+        String equipmentIds = entity.getEquipmentIds();
+        entity.setEquipmentIds(null);
         entity.setUpdateTime(LocalDateTime.now());
         entity.setUpdateTime(LocalDateTime.now());
         if (!this.updateById(entity)) return false;
         if (!this.updateById(entity)) return false;
-        // cameraIds 传 null 表示本次不动关联;传空串表示解除全部关联
-        if (cameraIds == null) return true;
-        return applyCameras(pointId, cameraIds);
+        // equipmentIds 传 null 表示本次不动关联;传空串表示解除全部关联
+        if (equipmentIds == null) return true;
+        return applyDevices(pointId, equipmentIds);
     }
     }
 
 
     /**
     /**
-     * 整体替换某点位的摄像头关联,并校验摄像头是否已被其他点位占用。
+     * 整体替换某点位的设备关联,先校验类型与占用再落库。
      */
      */
-    private boolean applyCameras(String pointId, String cameraIds) {
-        List<String> normalized = parseIds(cameraIds);
-        checkCameraOccupation(pointId, normalized);
+    private boolean applyDevices(String pointId, String equipmentIds) {
+        List<String> normalized = parseIds(equipmentIds);
+        checkDeviceTypes(normalized);
+        checkDeviceOccupation(pointId, normalized);
         WaterloggingPoint patch = new WaterloggingPoint();
         WaterloggingPoint patch = new WaterloggingPoint();
         patch.setPointId(pointId);
         patch.setPointId(pointId);
-        patch.setCameraIds(String.join(",", normalized));
+        patch.setEquipmentIds(String.join(",", normalized));
         patch.setUpdateTime(LocalDateTime.now());
         patch.setUpdateTime(LocalDateTime.now());
         return this.updateById(patch);
         return this.updateById(patch);
     }
     }
 
 
     @Override
     @Override
     @Transactional
     @Transactional
-    public boolean bindCameras(String pointId, List<String> cameraIds) {
+    public boolean bindDevices(String pointId, List<String> equipmentIds) {
         bindingLock.lock();
         bindingLock.lock();
         if (this.getById(pointId) == null) {
         if (this.getById(pointId) == null) {
             throw new ServiceException("易积水点不存在:" + pointId);
             throw new ServiceException("易积水点不存在:" + pointId);
         }
         }
-        List<String> normalized = normalizeIds(cameraIds);
-        checkCameraOccupation(pointId, normalized);
+        List<String> normalized = normalizeIds(equipmentIds);
+        checkDeviceTypes(normalized);
+        checkDeviceOccupation(pointId, normalized);
         WaterloggingPoint patch = new WaterloggingPoint();
         WaterloggingPoint patch = new WaterloggingPoint();
         patch.setPointId(pointId);
         patch.setPointId(pointId);
-        patch.setCameraIds(String.join(",", normalized));
+        patch.setEquipmentIds(String.join(",", normalized));
         patch.setUpdateTime(LocalDateTime.now());
         patch.setUpdateTime(LocalDateTime.now());
         return this.updateById(patch);
         return this.updateById(patch);
     }
     }
 
 
-    /** 摄像头只能挂在一个易积水点上,避免摄像头不在现场却出现在两个点位。 */
-    private void checkCameraOccupation(String pointId, List<String> cameraIds) {
-        if (cameraIds.isEmpty()) return;
+    /**
+     * 只允许关联雷达液位计(16)与视频监控-排口+内涝点(20),其他类型一律拒绝。
+     */
+    private void checkDeviceTypes(List<String> equipmentIds) {
+        if (equipmentIds.isEmpty()) return;
+        List<EquipmentBase> devices = equipmentBaseMapper.selectBatchIds(equipmentIds);
+        Map<String, EquipmentBase> deviceMap = devices.stream()
+                .collect(Collectors.toMap(EquipmentBase::getEquipmentId, device -> device, (a, b) -> a));
+        for (String equipmentId : equipmentIds) {
+            EquipmentBase device = deviceMap.get(equipmentId);
+            if (device == null) {
+                throw new ServiceException("设备不存在或已删除:" + equipmentId);
+            }
+            if (!ALLOWED_EQUIPMENT_TYPE_IDS.contains(device.getEquipmentTypeId())) {
+                String name = hasText(device.getEquipmentName()) ? device.getEquipmentName() : equipmentId;
+                throw new ServiceException("易积水点仅支持关联雷达液位计、视频监控设备,不支持:" + name);
+            }
+        }
+    }
+
+    /** 同一台设备只能挂在一个易积水点上,避免设备不在现场却出现在两个点位。 */
+    private void checkDeviceOccupation(String pointId, List<String> equipmentIds) {
+        if (equipmentIds.isEmpty()) return;
         List<WaterloggingPoint> others = this.list(new LambdaQueryWrapper<WaterloggingPoint>()
         List<WaterloggingPoint> others = this.list(new LambdaQueryWrapper<WaterloggingPoint>()
                 .ne(WaterloggingPoint::getPointId, pointId)
                 .ne(WaterloggingPoint::getPointId, pointId)
-                .isNotNull(WaterloggingPoint::getCameraIds));
+                .isNotNull(WaterloggingPoint::getEquipmentIds));
         for (WaterloggingPoint other : others) {
         for (WaterloggingPoint other : others) {
-            Set<String> occupied = parseIds(other.getCameraIds()).stream()
+            Set<String> occupied = parseIds(other.getEquipmentIds()).stream()
                     .collect(Collectors.toCollection(LinkedHashSet::new));
                     .collect(Collectors.toCollection(LinkedHashSet::new));
-            for (String cameraId : cameraIds) {
-                if (occupied.contains(cameraId)) {
+            for (String equipmentId : equipmentIds) {
+                if (occupied.contains(equipmentId)) {
                     String name = hasText(other.getPointName()) ? other.getPointName() : other.getPointId();
                     String name = hasText(other.getPointName()) ? other.getPointName() : other.getPointId();
-                    throw new ServiceException("摄像头已被易积水点「" + name + "」关联,请先解除");
+                    throw new ServiceException("设备已被易积水点「" + name + "」关联,请先解除");
                 }
                 }
             }
             }
         }
         }

+ 35 - 5
pipe-network-service/zksy-system/src/main/resources/mapper/cockpit/CockpitOverviewModulesMapper.xml

@@ -123,11 +123,32 @@
         GROUP BY pb.network_type, LEFT(UPPER(COALESCE(pb.network_code, '')), 2)
         GROUP BY pb.network_type, LEFT(UPPER(COALESCE(pb.network_code, '')), 2)
     </select>
     </select>
 
 
+    <!-- 可统计的预警集合:草稿(DRAFT)还没发布,不属于任何对外读数
+         (维护者 2026-11-12:「预警统计要排除草稿状态的预警」)。
+         今日/昨日新增、区间总数与类型排行共用这一个判据,避免四处各写一份日后漂移。
+         未解除集合另有白名单,见 selectUnresolvedStatusLevelCounts。
+
+         两条硬约束(评审指出的副作用,勿改):
+           1. `status IS NULL` 的要**保留**:改动前这三条查询没有状态条件,NULL 行原本计入;
+              单写 `<> 'DRAFT'` 会把它们默默丢掉(NULL 比较得 UNKNOWN),那是本票之外的口径变更。
+           2. 片段只能用在**计数**条件上。`selectWarningCounts` 里的 `MAX(w.update_time)`
+              是数据新鲜度(服务层 freshness)的数据源,代表"源数据最后动过的时间",
+              不能跟着排除草稿:否则编辑草稿后面板会被误判为数据过旧。
+              所以那条查询把筛选写进 CASE,而不是放 WHERE(见下面注释)。
+
+         片段写死了别名 `w`(与同文件其他片段一致),只能 include 在同样把预警表别名成 w 的查询里。 -->
+    <sql id="countableWarningFilter">
+        AND (w.status IS NULL OR UPPER(TRIM(w.status)) &lt;&gt; 'DRAFT')
+    </sql>
+
+    <!-- 新鲜度(source_updated_at)取全表 MAX,不受草稿筛选影响;只有两个计数带筛选。 -->
     <select id="selectWarningCounts" resultType="java.util.LinkedHashMap">
     <select id="selectWarningCounts" resultType="java.util.LinkedHashMap">
         <include refid="typeTree"/>
         <include refid="typeTree"/>
-        SELECT COALESCE(SUM(CASE WHEN w.create_time &gt;= #{todayStart} AND w.create_time &lt; #{tomorrowStart}
+        SELECT COALESCE(SUM(CASE WHEN (w.status IS NULL OR UPPER(TRIM(w.status)) &lt;&gt; 'DRAFT')
+                                  AND w.create_time &gt;= #{todayStart} AND w.create_time &lt; #{tomorrowStart}
                                  THEN 1 ELSE 0 END), 0) AS today_new,
                                  THEN 1 ELSE 0 END), 0) AS today_new,
-               COALESCE(SUM(CASE WHEN w.create_time &gt;= #{yesterdayStart} AND w.create_time &lt; #{todayStart}
+               COALESCE(SUM(CASE WHEN (w.status IS NULL OR UPPER(TRIM(w.status)) &lt;&gt; 'DRAFT')
+                                  AND w.create_time &gt;= #{yesterdayStart} AND w.create_time &lt; #{todayStart}
                                  THEN 1 ELSE 0 END), 0) AS yesterday_new,
                                  THEN 1 ELSE 0 END), 0) AS yesterday_new,
                MAX(w.update_time) AS source_updated_at
                MAX(w.update_time) AS source_updated_at
         FROM app_user.early_warning w
         FROM app_user.early_warning w
@@ -153,18 +174,27 @@
         SELECT COUNT(*) AS warning_count
         SELECT COUNT(*) AS warning_count
         FROM app_user.early_warning w
         FROM app_user.early_warning w
         WHERE w.create_time &gt;= #{startInclusive} AND w.create_time &lt; #{endExclusive}
         WHERE w.create_time &gt;= #{startInclusive} AND w.create_time &lt; #{endExclusive}
+        <include refid="countableWarningFilter"/>
         <include refid="deviceDistrictFilter"/>
         <include refid="deviceDistrictFilter"/>
     </select>
     </select>
 
 
+    <!-- 类型排行:排行的每行与标题「共 XX 起」必须同源,否则读者对不上数
+         (维护者 2026-10-26:「页面「共27起」而三行只凑出 23 起」;2026-11-12 要求审查本项)。
+         所以这里与 selectWarningCountInWindow 用**完全相同的 WHERE**:时间窗 + 草稿排除 + 片区/行业。
+         注意 `warning_type` 是 NOT NULL 但可为空串:空串不能单独占一行(服务层会把它丢掉,
+         那样行之和就小于 total),所以归入一个明确的占位码 UNKNOWN,由同一套名称降级逻辑展示。 -->
     <select id="selectWarningTypeCountsInWindow" resultType="java.util.LinkedHashMap">
     <select id="selectWarningTypeCountsInWindow" resultType="java.util.LinkedHashMap">
         <include refid="typeTree"/>
         <include refid="typeTree"/>
-        SELECT w.warning_type AS type_code,
+        SELECT CASE WHEN w.warning_type IS NULL OR TRIM(w.warning_type) = ''
+                    THEN 'UNKNOWN' ELSE w.warning_type END AS type_code,
                COUNT(*) AS type_count
                COUNT(*) AS type_count
         FROM app_user.early_warning w
         FROM app_user.early_warning w
         WHERE w.create_time &gt;= #{startInclusive} AND w.create_time &lt; #{endExclusive}
         WHERE w.create_time &gt;= #{startInclusive} AND w.create_time &lt; #{endExclusive}
+        <include refid="countableWarningFilter"/>
         <include refid="deviceDistrictFilter"/>
         <include refid="deviceDistrictFilter"/>
-        GROUP BY w.warning_type
-        ORDER BY COUNT(*) DESC, w.warning_type ASC
+        GROUP BY CASE WHEN w.warning_type IS NULL OR TRIM(w.warning_type) = ''
+                      THEN 'UNKNOWN' ELSE w.warning_type END
+        ORDER BY COUNT(*) DESC, type_code ASC
     </select>
     </select>
 
 
     <!-- 基础集合 = alarm_data.audit_status = 1(维护者 2026-10-22 裁定,规格 §0)。
     <!-- 基础集合 = alarm_data.audit_status = 1(维护者 2026-10-22 裁定,规格 §0)。

+ 1 - 1
pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmLifecycleServiceTest.java

@@ -51,7 +51,7 @@ class AlarmLifecycleServiceTest {
         assertEquals("压力过低\n实际值:0;阈值:—", alarm.getAlarmContent());
         assertEquals("压力过低\n实际值:0;阈值:—", alarm.getAlarmContent());
         var ordered=inOrder(mapper,logs,manager);
         var ordered=inOrder(mapper,logs,manager);
         ordered.verify(mapper).insert(alarm);
         ordered.verify(mapper).insert(alarm);
-        ordered.verify(logs).insertLifecycleIfAbsent(eq("a1"),eq(0),eq("系统触发报警;报警单号:"+alarm.getAlarmNo()+";报警描述:"+alarm.getAlarmContent()+";实际值:0"),eq("监测系统"),any(),anyLong(),nullable(Long.class));
+        ordered.verify(logs).insertLifecycleIfAbsent(eq("a1"),eq(0),eq("压力过低\n实际值:0;阈值:—"),eq("监测系统"),any(),anyLong(),nullable(Long.class));
         ordered.verify(manager).commit(any());
         ordered.verify(manager).commit(any());
     }
     }
     @Test void insertBuildsContentFromWarningNameAndLowerThreshold() {
     @Test void insertBuildsContentFromWarningNameAndLowerThreshold() {

+ 172 - 5
pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmOperationsServiceTest.java

@@ -1,10 +1,21 @@
 package com.zksy.base.alarm.service;
 package com.zksy.base.alarm.service;
 
 
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.zksy.base.alarm.domain.AlarmLog;
 import com.zksy.base.alarm.dto.*;
 import com.zksy.base.alarm.dto.*;
 import com.zksy.base.alarm.enums.*;
 import com.zksy.base.alarm.enums.*;
 import com.zksy.base.alarm.mapper.*;
 import com.zksy.base.alarm.mapper.*;
 import com.zksy.common.exception.ServiceException;
 import com.zksy.common.exception.ServiceException;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.mapper.EquipmentTypeMapper;
+import com.zksy.common.core.domain.entity.SysMenu;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.common.core.domain.model.LoginUser;
+import com.zksy.ops.support.OpsAssignScopeSupport;
+import com.zksy.system.service.ISysMenuService;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
 import org.junit.jupiter.api.*;
 import org.junit.jupiter.api.*;
 import java.math.BigDecimal;
 import java.math.BigDecimal;
 import java.time.LocalDateTime;
 import java.time.LocalDateTime;
@@ -125,16 +136,172 @@ class AlarmOperationsServiceTest {
         verify(mapper,never()).selectSamples(any(),anyString(),any(),any(),anyString());
         verify(mapper,never()).selectSamples(any(),anyString(),any(),any(),anyString());
         verify(mapper,never()).selectLatestSample(any(),anyString());
         verify(mapper,never()).selectLatestSample(any(),anyString());
     }
     }
+    @Test void triggerLogsExposeActionLabelAndSnapshotWithoutRepeatingAlarmContext() {
+        alarm.setAlarmNo("BJ202611110900000001");
+        AlarmLog triggered = new AlarmLog();
+        triggered.setLogId(20L); triggered.setAlarmId("a1"); triggered.setOperType(0);
+        triggered.setOperDesc("压力过低\n实际值:0;阈值:—");
+        triggered.setOperUserName("监测系统"); triggered.setOperTime(LocalDateTime.of(2026,11,11,9,0));
+        when(logs.selectHistory("a1")).thenReturn(Collections.singletonList(triggered));
+
+        AlarmVO context = service.detail("a1", query);
+        List<AlarmLog> result = service.logs("a1", query);
+
+        assertEquals("BJ202611110900000001", context.getAlarmNo());
+        assertEquals(1, result.size());
+        assertEquals(0, result.get(0).getOperType());
+        assertEquals("报警触发", result.get(0).getOperTypeName());
+        assertEquals("压力过低\n实际值:0;阈值:—", result.get(0).getOperDesc());
+        assertFalse(result.get(0).getOperDesc().contains("BJ202611110900000001"));
+        assertEquals(1, result.get(0).getOperDesc().split("实际值:", -1).length - 1);
+        verify(mapper, times(2)).selectDetail("a1", query, Arrays.asList(2,21));
+        verify(logs).selectHistory("a1");
+        verifyNoMoreInteractions(logs);
+    }
+    @Test void logsPreserveUnknownHistoricalTypesAndOriginalFieldsWithoutRewriting() {
+        AlarmLog legacy = new AlarmLog();
+        legacy.setLogId(7L); legacy.setAlarmId("a1"); legacy.setOperType(8);
+        legacy.setOperDesc("系统触发报警;报警单号:OLD-2019;报警描述:旧版正文;实际值:0");
+        legacy.setOperUserId(9L); legacy.setOperUserName("历史操作人");
+        legacy.setOperTime(LocalDateTime.of(2019,1,2,3,4,5)); legacy.setAttachUrl("/archive/original.png");
+        AlarmLog missingType = new AlarmLog();
+        missingType.setLogId(6L); missingType.setAlarmId("a1"); missingType.setOperType(null);
+        missingType.setOperDesc("旧记录\n保留第二行及末尾空格 ");
+        List<AlarmLog> history = List.of(legacy, missingType);
+        when(logs.selectHistory("a1")).thenReturn(history);
+
+        for (int read = 0; read < 2; read++) {
+            List<AlarmLog> result = service.logs("a1", query);
+            assertEquals(2, result.size());
+            assertEquals(7L, result.get(0).getLogId());
+            assertEquals("a1", result.get(0).getAlarmId());
+            assertEquals(8, result.get(0).getOperType());
+            assertEquals("历史操作", result.get(0).getOperTypeName());
+            assertEquals("系统触发报警;报警单号:OLD-2019;报警描述:旧版正文;实际值:0", result.get(0).getOperDesc());
+            assertEquals(9L, result.get(0).getOperUserId());
+            assertEquals("历史操作人", result.get(0).getOperUserName());
+            assertEquals(LocalDateTime.of(2019,1,2,3,4,5), result.get(0).getOperTime());
+            assertEquals("/archive/original.png", result.get(0).getAttachUrl());
+            assertEquals(6L, result.get(1).getLogId());
+            assertNull(result.get(1).getOperType());
+            assertEquals("历史操作", result.get(1).getOperTypeName());
+            assertEquals("旧记录\n保留第二行及末尾空格 ", result.get(1).getOperDesc());
+        }
+        verify(logs, times(2)).selectHistory("a1");
+        verifyNoMoreInteractions(logs);
+    }
     @Test void timelineUsesTheSharedNewestFirstQuery() {
     @Test void timelineUsesTheSharedNewestFirstQuery() {
         when(logs.selectHistory("a1")).thenReturn(Collections.emptyList());
         when(logs.selectHistory("a1")).thenReturn(Collections.emptyList());
         assertEquals(Collections.emptyList(),service.logs("a1",query));
         assertEquals(Collections.emptyList(),service.logs("a1",query));
         verify(logs).selectHistory("a1");
         verify(logs).selectHistory("a1");
     }
     }
-    @Test void invalidFiltersAndNonWaterSubsystemAnalysisAreRejected() {
-        query.setAlarmStatus(5); assertThrows(ServiceException.class, () -> service.page(query));
-        query.setRootTypeId(3); assertThrows(ServiceException.class, () -> service.map(query));
-        assertThrows(ServiceException.class, () -> service.analysis("a1",query,AlarmSeriesPeriod.CURVE));
-        verifyNoInteractions(mapper);
+    @Test void invalidFiltersAreRejectedBeforeResolvingScopeOrReadingData() {
+        query.setAlarmStatus(5);
+        assertThrows(ServiceException.class, () -> service.page(query));
+        verifyNoInteractions(scope, mapper);
+    }
+
+    /** 真实范围服务,仅替换菜单/类型数据库边界;不能用内部 scope mock 证明授权。 */
+    @Nested
+    class NonWaterSubsystemAuthorization {
+        private final EquipmentTypeMapper types = mock(EquipmentTypeMapper.class);
+        private final ISysMenuService menus = mock(ISysMenuService.class);
+        private final OpsAssignScopeSupport company = mock(OpsAssignScopeSupport.class);
+        private final AlarmReviewScopeService realScope = new AlarmReviewScopeService(types, menus, company);
+        private final AlarmOperationsService scopedService = new AlarmOperationsService(mapper, realScope, logs, dictionaries, workOrders);
+        private final SysMenu menu = new SysMenu();
+
+        @BeforeEach void loginAndPrepareExternalScopeBoundaries() {
+            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
+                    new LoginUser(9L, 10L, new SysUser(), Collections.emptySet()), null));
+            menu.setComponent("subSystem/alarm/common/list"); menu.setStatus("0");
+            menu.setQuery("{\"rootTypeId\":3,\"warning_code\":\"WARN-GAS-CONCENTRATION\"}");
+            when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));
+            when(types.selectList(null)).thenReturn(Arrays.asList(type(1,0), type(12,1), type(2,0),
+                    type(3,0), type(22,3), type(99,22), type(4,0), type(24,4), type(44,24)));
+        }
+        @AfterEach void clearLogin() { SecurityContextHolder.clearContext(); }
+
+        @Test void authorizedGasMapAndAnalysisUseOnlyItsRealTypeTree() {
+            assertAuthorizedStateAlarmRead(3, Arrays.asList(3,22,99), "WARN-GAS-CONCENTRATION");
+        }
+        @Test void authorizedManholeMapAndAnalysisUseOnlyItsRealTypeTree() {
+            menu.setQuery("{\"rootTypeId\":4}");
+            assertAuthorizedStateAlarmRead(4, Arrays.asList(4,24,44), "WARN-OFFLINE");
+        }
+        private void assertAuthorizedStateAlarmRead(int root, List<Integer> ids, String warningCode) {
+            query.setRootTypeId(root); query.setWarningCode(warningCode); alarm.setWarningCode(warningCode);
+            when(mapper.selectMap(query, ids)).thenReturn(Collections.singletonList(alarm));
+            assertEquals(Collections.singletonList(alarm), scopedService.map(query));
+            assertEquals(AlarmRecordStatusEnum.UNHANDLED.getCode(), query.getAlarmStatus());
+            Map<String,Object> result = scopedService.analysis("a1", query, AlarmSeriesPeriod.CURVE);
+            assertSame(alarm, result.get("alarm"));
+            assertEquals(false, result.get("supported"));
+            assertEquals(Collections.emptyList(), result.get("samples"));
+            assertEquals("该报警指标暂无对应的数值采集曲线", result.get("message"));
+            verify(mapper).selectMap(query, ids);
+            verify(mapper).selectDetail("a1", query, ids);
+            verify(mapper, never()).selectSamples(any(), anyString(), any(), any(), anyString());
+            verify(mapper, never()).selectLatestSample(any(), anyString());
+            verify(menus, times(2)).selectMenuList(9L);
+            verify(types, times(2)).selectList(null);
+            verifyNoInteractions(scope);
+        }
+        @Test void authorizedNonWaterNumericCurveReadsSamplesAfterRealScopeCheck() {
+            // 数值来源按既有指标白名单判定,不因根为燃气而直接拒绝或伪造燃气采集源。
+            menu.setQuery("{\"rootTypeId\":3}");
+            query.setRootTypeId(3); query.setWarningCode("WARN-PRESSURE"); alarm.setWarningCode("WARN-PRESSURE");
+            List<Integer> ids = Arrays.asList(3,22,99);
+            AlarmSampleVO sample = new AlarmSampleVO(); sample.setTime(alarm.getCreateTime()); sample.setValue(BigDecimal.TEN);
+            List<AlarmSampleVO> samples = Collections.singletonList(sample);
+            when(mapper.selectSamples(eq(AlarmMetricSource.PRESSURE), eq("D1"), any(), any(), eq("CURVE"))).thenReturn(samples);
+            when(mapper.selectLatestSample(AlarmMetricSource.PRESSURE, "D1")).thenReturn(sample);
+            Map<String,Object> result = scopedService.analysis("a1", query, AlarmSeriesPeriod.CURVE);
+            assertEquals(true, result.get("supported")); assertSame(samples, result.get("samples"));
+            assertSame(sample, result.get("latestSample"));
+            var ordered = inOrder(menus, types, mapper);
+            ordered.verify(menus).selectMenuList(9L);
+            ordered.verify(types).selectList(null);
+            ordered.verify(mapper).selectDetail("a1", query, ids);
+            ordered.verify(mapper).selectSamples(AlarmMetricSource.PRESSURE, "D1",
+                    LocalDateTime.of(2026,1,10,11,0), LocalDateTime.of(2026,1,10,13,0), "CURVE");
+            ordered.verify(mapper).selectLatestSample(AlarmMetricSource.PRESSURE, "D1");
+            verifyNoInteractions(scope);
+        }
+        @Test void tamperedRootAndOmittedRootCannotBypassGasMenuScope() {
+            query.setWarningCode("WARN-GAS-CONCENTRATION");
+            for (Integer root : Arrays.asList(1, 4, null)) {
+                query.setRootTypeId(root);
+                assertMapAndAnalysisDeniedBeforeReads();
+            }
+        }
+        @Test void disabledMenuCannotReadMapOrAnalysis() {
+            query.setRootTypeId(3); query.setWarningCode("WARN-GAS-CONCENTRATION"); menu.setStatus("1");
+            assertMapAndAnalysisDeniedBeforeReads();
+        }
+        @Test void omittedOrReplacedWarningCodeCannotBypassMenuRestriction() {
+            query.setRootTypeId(3);
+            for (String code : Arrays.asList(null, "WARN-GAS-PRESSURE")) {
+                query.setWarningCode(code);
+                assertMapAndAnalysisDeniedBeforeReads();
+            }
+        }
+        private void assertMapAndAnalysisDeniedBeforeReads() {
+            assertThrows(AccessDeniedException.class, () -> scopedService.map(query));
+            assertThrows(AccessDeniedException.class, () -> scopedService.analysis("a1", query, AlarmSeriesPeriod.CURVE));
+            verifyNoInteractions(mapper, logs, workOrders, types, scope);
+        }
+        @Test void unknownAndNonRootTypesAreRejectedBeforeMenusOrDataAreRead() {
+            for (int root : new int[] { 99, 22 }) {
+                query.setRootTypeId(root);
+                assertThrows(ServiceException.class, () -> scopedService.map(query));
+                assertThrows(ServiceException.class, () -> scopedService.analysis("a1", query, AlarmSeriesPeriod.CURVE));
+            }
+            verifyNoInteractions(menus, types, mapper, logs, workOrders, scope);
+        }
+        private EquipmentType type(int id, int parent) {
+            EquipmentType type = new EquipmentType(); type.setId(id); type.setParentId(parent); return type;
+        }
     }
     }
     @Test void unsupportedStateAlarmReturnsNoFabricatedCurve() {
     @Test void unsupportedStateAlarmReturnsNoFabricatedCurve() {
         alarm.setWarningCode("WARN-OFFLINE");
         alarm.setWarningCode("WARN-OFFLINE");

+ 45 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/base/alarm/service/AlarmReviewScopeServiceTest.java

@@ -59,6 +59,51 @@ class AlarmReviewScopeServiceTest {
     @Test void reviewMenuDoesNotGrantOperationsAccess() {
     @Test void reviewMenuDoesNotGrantOperationsAccess() {
         assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query));
         assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query));
     }
     }
+    @Test void commonAndExactLegacyOperationsComponentsKeepAllMenuScopeGuards() {
+        for (String component : Arrays.asList("subSystem/alarm/common/alarmGIS", "subSystem/alarm/common/analysis",
+                "subSystem/drainage/alarm/alarmGIS", "subSystem/drainage/alarm/analysis",
+                "subSystem/waterSupply/alarm/alarmGIS")) {
+            int root = component.contains("waterSupply") ? 1 : 2;
+            SysMenu menu = new SysMenu(); menu.setStatus("0"); menu.setComponent(component);
+            menu.setQuery("{\"rootTypeId\":" + root + ",\"warning_code\":\"WARN-SCOPED\"}");
+            when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));
+            when(types.selectList(null)).thenReturn(Arrays.asList(type(1,0),type(11,1),type(111,11),type(2,0),type(21,2),type(22,21)));
+            query.setRootTypeId(root); query.setWarningCode("WARN-SCOPED");
+            assertEquals(root == 1 ? Arrays.asList(1,11,111) : Arrays.asList(2,21,22),
+                    service.resolveOperations(query), component);
+            assertThrows(AccessDeniedException.class, () -> service.resolve(query), component + " cannot grant audit");
+            query.setRootTypeId(root == 1 ? 2 : 1);
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), component + " wrong root");
+            query.setRootTypeId(null);
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), component + " missing root");
+            query.setRootTypeId(root); query.setWarningCode(null);
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), component + " missing code");
+            query.setWarningCode("WARN-OTHER");
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), component + " wrong code");
+            query.setWarningCode("WARN-SCOPED"); menu.setStatus("1");
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), component + " disabled");
+        }
+    }
+
+    @Test void similarOrUnknownComponentsNeverAcquireOperationsScope() {
+        for (String component : Arrays.asList("subSystem/drainage/alarm/alarmGIS/extra",
+                "subSystem/alarm/common/alarmGIS/extra", " subSystem/drainage/alarm/analysis",
+                "subSystem/waterSupply/alarm/analysis", "subSystem/other/alarm/alarmGIS", null)) {
+            SysMenu menu = new SysMenu(); menu.setStatus("0"); menu.setComponent(component);
+            menu.setQuery("{\"rootTypeId\":3,\"warning_code\":\"WARN-GAS-CONCENTRATION\"}");
+            when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));
+            assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query), String.valueOf(component));
+        }
+    }
+
+    @Test void malformedScopeAndNonRootTypeCannotUseCommonOperationsMenu() {
+        SysMenu menu = new SysMenu(); menu.setStatus("0"); menu.setComponent("subSystem/alarm/common/alarmGIS");
+        menu.setQuery("{not-json"); when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));
+        assertThrows(AccessDeniedException.class, () -> service.resolveOperations(query));
+        menu.setQuery("{\"rootTypeId\":22,\"warning_code\":\"WARN-GAS-CONCENTRATION\"}"); query.setRootTypeId(22);
+        assertThrows(com.zksy.common.exception.ServiceException.class, () -> service.resolveOperations(query));
+    }
+
     @Test void waterSupplyGisMenuOnlyGrantsWaterOperationsAndNotAudit() {
     @Test void waterSupplyGisMenuOnlyGrantsWaterOperationsAndNotAudit() {
         SysMenu menu = new SysMenu(); menu.setStatus("0"); menu.setComponent("subSystem/waterSupply/alarm/alarmGIS");
         SysMenu menu = new SysMenu(); menu.setStatus("0"); menu.setComponent("subSystem/waterSupply/alarm/alarmGIS");
         menu.setQuery("{\"rootTypeId\":1}"); when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));
         menu.setQuery("{\"rootTypeId\":1}"); when(menus.selectMenuList(9L)).thenReturn(Collections.singletonList(menu));

+ 196 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/BusinessCockpitEventAdapterLevelNameTest.java

@@ -0,0 +1,196 @@
+package com.zksy.cockpit.event;
+
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+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.EquipmentType;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.service.EquipmentTypeService;
+import com.zksy.base.service.MonitorPointService;
+import com.zksy.base.warning.domain.EarlyWarning;
+import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
+import com.zksy.base.warning.mapper.EquipmentWarningTypeMapper;
+import com.zksy.base.warning.mapper.WarningTypeMapper;
+import com.zksy.base.warning.service.EarlyWarningService;
+import com.zksy.common.core.domain.entity.SysDictData;
+import com.zksy.ops.service.WorkOrderService;
+import com.zksy.system.mapper.SysDictDataMapper;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 设备详情事件适配器:等级名称按族取字典(预警 alert_level、报警 alarm_level),
+ * 缺项回退既有「N级预警 / N级报警」,且每族每请求只查一次字典。
+ */
+class BusinessCockpitEventAdapterLevelNameTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+
+    private final EquipmentBaseService equipmentBaseService = mock(EquipmentBaseService.class);
+    private final EquipmentTypeService equipmentTypeService = mock(EquipmentTypeService.class);
+    private final MonitorPointService monitorPointService = mock(MonitorPointService.class);
+    private final EarlyWarningService earlyWarningService = mock(EarlyWarningService.class);
+    private final AlarmDataService alarmDataService = mock(AlarmDataService.class);
+    private final EquipmentWarningTypeMapper warningTypeMapper = mock(EquipmentWarningTypeMapper.class);
+    private final WarningTypeMapper refWarningTypeMapper = mock(WarningTypeMapper.class);
+    private final AlarmWarningRelMapper alarmWarningRelMapper = mock(AlarmWarningRelMapper.class);
+    private final WorkOrderService workOrderService = mock(WorkOrderService.class);
+    private final SysDictDataMapper sysDictDataMapper = mock(SysDictDataMapper.class);
+
+    private final BusinessCockpitEventAdapter adapter = new BusinessCockpitEventAdapter(
+            equipmentBaseService, equipmentTypeService, monitorPointService, earlyWarningService,
+            alarmDataService, warningTypeMapper, refWarningTypeMapper, alarmWarningRelMapper,
+            workOrderService, sysDictDataMapper,
+            Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+
+    @Test
+    void warningUsesAlertLevelDictAndAlarmUsesAlarmLevelDictInOneBatch() {
+        stubBaseFacts();
+        when(earlyWarningService.list()).thenReturn(Arrays.asList(
+                warning("WRN-1", "1"), warning("WRN-2", "2")));
+        // 报警等级写在 alarm_level 字典里;与预警字典刻意给不同的标签,证明按族取值。
+        when(alarmDataService.list()).thenReturn(Collections.singletonList(alarm("ALM-1", "4")));
+        when(sysDictDataMapper.selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT))
+                .thenReturn(Collections.singletonList(dict("alert_level", "1", "一级预警")));
+        when(sysDictDataMapper.selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT))
+                .thenReturn(Collections.singletonList(dict("alarm_level", "4", "四级报警")));
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        // 字典命中:取 dict_label。
+        assertEquals("一级预警", snapshot.getWarnings().get(0).getLevelName());
+        // 字典缺项:回退既有「N级预警」口径,不猜、不硬编码前端。
+        assertEquals("二级预警", snapshot.getWarnings().get(1).getLevelName());
+        assertEquals("四级报警", snapshot.getAlarms().get(0).getLevelName());
+        // 既有字段与行为不变。
+        assertEquals(1, snapshot.getWarnings().get(0).getLevel());
+        assertEquals("RED", snapshot.getWarnings().get(0).getLevelColor());
+        assertEquals(4, snapshot.getAlarms().get(0).getLevel());
+        assertEquals("GREEN", snapshot.getAlarms().get(0).getLevelColor());
+        // 批量:每族一次字典查询,不随事件条数增长。
+        verify(sysDictDataMapper, times(1)).selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT);
+        verify(sysDictDataMapper, times(1)).selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT);
+    }
+
+    @Test
+    void dictionaryUnavailableFallsBackAndMissingLevelStaysNull() {
+        stubBaseFacts();
+        when(earlyWarningService.list()).thenReturn(Arrays.asList(
+                warning("WRN-1", "3"), warning("WRN-2", null)));
+        when(alarmDataService.list()).thenReturn(Collections.singletonList(alarm("ALM-1", "2")));
+        when(sysDictDataMapper.selectDictDataByType(any())).thenReturn(Collections.emptyList());
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        assertEquals("三级预警", snapshot.getWarnings().get(0).getLevelName());
+        assertNull(snapshot.getWarnings().get(1).getLevel());
+        assertNull(snapshot.getWarnings().get(1).getLevelName());
+        assertEquals("二级报警", snapshot.getAlarms().get(0).getLevelName());
+    }
+
+    @Test
+    void dictionaryFailureDegradesToFallbackInsteadOfFailingTheEvents() {
+        stubBaseFacts();
+        when(earlyWarningService.list()).thenReturn(Collections.singletonList(warning("WRN-1", "2")));
+        when(alarmDataService.list()).thenReturn(Collections.singletonList(alarm("ALM-1", "1")));
+        when(sysDictDataMapper.selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT))
+                .thenThrow(new IllegalStateException("dict table unavailable"));
+        when(sysDictDataMapper.selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT))
+                .thenThrow(new IllegalStateException("dict table unavailable"));
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        assertEquals("二级预警", snapshot.getWarnings().get(0).getLevelName());
+        assertEquals("一级报警", snapshot.getAlarms().get(0).getLevelName());
+    }
+
+    @Test
+    void familyWithoutEventsDoesNotTouchItsDictionary() {
+        stubBaseFacts();
+        when(earlyWarningService.list()).thenReturn(Collections.singletonList(warning("WRN-1", "1")));
+        when(alarmDataService.list()).thenReturn(Collections.emptyList());
+        when(sysDictDataMapper.selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT))
+                .thenReturn(Collections.singletonList(dict("alert_level", "1", "一级预警")));
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        assertEquals("一级预警", snapshot.getWarnings().get(0).getLevelName());
+        verify(sysDictDataMapper, times(1)).selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT);
+        verify(sysDictDataMapper, times(0)).selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT);
+    }
+
+    private void stubBaseFacts() {
+        EquipmentType type = new EquipmentType();
+        type.setId(7);
+        type.setTypeName("污水环境监测设备");
+        when(equipmentTypeService.list()).thenReturn(Collections.singletonList(type));
+
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId("EQ-1");
+        device.setEquipmentCode(DEVICE_CODE);
+        device.setEquipmentName("污水环境监测设备");
+        device.setEquipmentTypeId(7);
+        when(equipmentBaseService.list()).thenReturn(Collections.singletonList(device));
+        when(equipmentBaseService.getEquipmentByPoint(any())).thenReturn(Collections.emptyList());
+
+        when(monitorPointService.list()).thenReturn(Collections.emptyList());
+        when(warningTypeMapper.selectList(any(Wrapper.class))).thenReturn(Collections.emptyList());
+        when(alarmWarningRelMapper.selectList(any(Wrapper.class))).thenReturn(Collections.emptyList());
+        when(workOrderService.list()).thenReturn(Collections.emptyList());
+    }
+
+    private static EarlyWarning warning(String warningNo, String level) {
+        EarlyWarning warning = new EarlyWarning();
+        warning.setWarningId("WID-" + warningNo);
+        warning.setWarningNo(warningNo);
+        warning.setWarningType("WS_ENV");
+        warning.setWarningLevel(level);
+        warning.setStatus("PROCESSING");
+        warning.setPublishTime(LocalDateTime.of(2026, 9, 2, 9, 59, 30));
+        warning.setDeviceCode(DEVICE_CODE);
+        warning.setDeviceName("污水环境监测设备");
+        return warning;
+    }
+
+    private static AlarmData alarm(String id, String level) {
+        AlarmData alarm = new AlarmData();
+        alarm.setId(id);
+        alarm.setAlarmNo(id);
+        alarm.setWarningCode("WS_ENV_HIGH");
+        alarm.setAlarmLevel(level);
+        alarm.setAlarmStatus(0);
+        alarm.setCreateTime(LocalDateTime.of(2026, 9, 2, 10, 0, 0));
+        alarm.setDeviceCode(DEVICE_CODE);
+        alarm.setDeviceName("污水环境监测设备");
+        return alarm;
+    }
+
+    private static SysDictData dict(String dictType, String value, String label) {
+        SysDictData data = new SysDictData();
+        data.setDictType(dictType);
+        data.setDictValue(value);
+        data.setDictLabel(label);
+        data.setStatus("0");
+        return data;
+    }
+}

+ 179 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventContentTest.java

@@ -0,0 +1,179 @@
+package com.zksy.cockpit.event;
+
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+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.EquipmentType;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.service.EquipmentTypeService;
+import com.zksy.base.service.MonitorPointService;
+import com.zksy.base.warning.domain.EarlyWarning;
+import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
+import com.zksy.base.warning.mapper.EquipmentWarningTypeMapper;
+import com.zksy.base.warning.mapper.WarningTypeMapper;
+import com.zksy.base.warning.service.EarlyWarningService;
+import com.zksy.ops.service.WorkOrderService;
+import com.zksy.system.mapper.SysDictDataMapper;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 事件描述原文(content):预警取 early_warning.warning_content、报警取 alarm_data.alarm_content,
+ * 原样透传(含管理端文案里的换行),缺失为 null;不额外查库。
+ */
+class CockpitEventContentTest {
+    private static final String DEVICE_CODE = "TC-PS-WS-202609020012";
+    private static final String WARNING_CONTENT =
+            "化学需氧量(COD)预警接近上限\n实际值:14.6 mg/L;阈值:上限 20 mg/L";
+
+    private final EquipmentBaseService equipmentBaseService = mock(EquipmentBaseService.class);
+    private final EquipmentTypeService equipmentTypeService = mock(EquipmentTypeService.class);
+    private final MonitorPointService monitorPointService = mock(MonitorPointService.class);
+    private final EarlyWarningService earlyWarningService = mock(EarlyWarningService.class);
+    private final AlarmDataService alarmDataService = mock(AlarmDataService.class);
+    private final EquipmentWarningTypeMapper warningTypeMapper = mock(EquipmentWarningTypeMapper.class);
+    private final WarningTypeMapper refWarningTypeMapper = mock(WarningTypeMapper.class);
+    private final AlarmWarningRelMapper alarmWarningRelMapper = mock(AlarmWarningRelMapper.class);
+    private final WorkOrderService workOrderService = mock(WorkOrderService.class);
+    private final SysDictDataMapper sysDictDataMapper = mock(SysDictDataMapper.class);
+
+    private final BusinessCockpitEventAdapter adapter = new BusinessCockpitEventAdapter(
+            equipmentBaseService, equipmentTypeService, monitorPointService, earlyWarningService,
+            alarmDataService, warningTypeMapper, refWarningTypeMapper, alarmWarningRelMapper,
+            workOrderService, sysDictDataMapper,
+            Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+
+    @Test
+    void storedDescriptionsArePassedThroughVerbatimForBothFamilies() {
+        stubBaseFacts();
+        EarlyWarning warning = warning("WRN-1", "1");
+        warning.setWarningContent(WARNING_CONTENT);
+        AlarmData alarm = alarm("ALM-1", "2");
+        alarm.setAlarmContent("化学需氧量(COD)报警超过上限\n实际值:24.6 mg/L;阈值:上限 20 mg/L");
+        when(earlyWarningService.list()).thenReturn(Collections.singletonList(warning));
+        when(alarmDataService.list()).thenReturn(Collections.singletonList(alarm));
+        when(sysDictDataMapper.selectDictDataByType(any())).thenReturn(Collections.emptyList());
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        // 逐字相同(含换行与空格),不做二次格式化。
+        assertEquals(WARNING_CONTENT, snapshot.getWarnings().get(0).getContent());
+        assertEquals("化学需氧量(COD)报警超过上限\n实际值:24.6 mg/L;阈值:上限 20 mg/L",
+                snapshot.getAlarms().get(0).getContent());
+        // 既有字段照旧。
+        assertEquals("WRN-1", snapshot.getWarnings().get(0).getWarningNo());
+        assertEquals(1, snapshot.getWarnings().get(0).getLevel());
+        assertEquals("ALM-1", snapshot.getAlarms().get(0).getAlarmId());
+        // 描述随已加载实体一起读出,没有为它新增逐条查询。
+        verify(earlyWarningService, times(1)).list();
+        verify(alarmDataService, times(1)).list();
+    }
+
+    @Test
+    void missingStoredDescriptionStaysNullInsteadOfBeingSynthesized() {
+        stubBaseFacts();
+        EarlyWarning warning = warning("WRN-1", "2");
+        warning.setWarningContent(null);
+        AlarmData alarm = alarm("ALM-1", "1");
+        alarm.setAlarmContent("   ");
+        when(earlyWarningService.list()).thenReturn(Collections.singletonList(warning));
+        when(alarmDataService.list()).thenReturn(Collections.singletonList(alarm));
+        when(sysDictDataMapper.selectDictDataByType(any())).thenReturn(Collections.emptyList());
+
+        CockpitEventSnapshot snapshot = adapter.loadCurrent(DEVICE_CODE);
+
+        assertNotNull(snapshot);
+        assertNull(snapshot.getWarnings().get(0).getContent());
+        // 空串/空白不当作描述,也不拼装替代文案。
+        assertNull(snapshot.getAlarms().get(0).getContent());
+    }
+
+    @Test
+    void contentSerializesAsPlainStringWithNewlinesPreserved() throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        CockpitEventWarning warning = new CockpitEventWarning(
+                "WRN-1", "污水COD预警", "WS_ENV", 1, "RED", "一级预警",
+                WARNING_CONTENT, "PROCESSING", "2026-09-02T09:59:30+08:00",
+                null, null, DEVICE_CODE, "污水环境监测设备", "太常片区");
+        CockpitEventAlarm alarm = new CockpitEventAlarm(
+                "ALM-1", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 2, "YELLOW", "二级报警",
+                null, "UNHANDLED", "2026-09-02T10:00:00+08:00", null, null, null, null,
+                DEVICE_CODE, "污水环境监测设备", "太常片区");
+
+        JsonNode warningJson = mapper.readTree(mapper.writeValueAsString(warning));
+        assertEquals(WARNING_CONTENT, warningJson.get("content").asText());
+        assertArrayEquals(WARNING_CONTENT.split("\n"), warningJson.get("content").asText().split("\n"));
+        // 既有字段仍在。
+        assertEquals(1, warningJson.get("level").asInt());
+        assertEquals("RED", warningJson.get("levelColor").asText());
+
+        JsonNode alarmJson = mapper.readTree(mapper.writeValueAsString(alarm));
+        assertNull(alarmJson.get("content").textValue());
+    }
+
+    private void stubBaseFacts() {
+        EquipmentType type = new EquipmentType();
+        type.setId(7);
+        type.setTypeName("污水环境监测设备");
+        when(equipmentTypeService.list()).thenReturn(Collections.singletonList(type));
+
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId("EQ-1");
+        device.setEquipmentCode(DEVICE_CODE);
+        device.setEquipmentName("污水环境监测设备");
+        device.setEquipmentTypeId(7);
+        when(equipmentBaseService.list()).thenReturn(Collections.singletonList(device));
+        when(equipmentBaseService.getEquipmentByPoint(any())).thenReturn(Collections.emptyList());
+
+        when(monitorPointService.list()).thenReturn(Collections.emptyList());
+        when(warningTypeMapper.selectList(any(Wrapper.class))).thenReturn(Collections.emptyList());
+        when(alarmWarningRelMapper.selectList(any(Wrapper.class))).thenReturn(Collections.emptyList());
+        when(workOrderService.list()).thenReturn(Collections.emptyList());
+    }
+
+    private static EarlyWarning warning(String warningNo, String level) {
+        EarlyWarning warning = new EarlyWarning();
+        warning.setWarningId("WID-" + warningNo);
+        warning.setWarningNo(warningNo);
+        warning.setWarningType("WS_ENV");
+        warning.setWarningLevel(level);
+        warning.setStatus("PROCESSING");
+        warning.setPublishTime(LocalDateTime.of(2026, 9, 2, 9, 59, 30));
+        warning.setDeviceCode(DEVICE_CODE);
+        warning.setDeviceName("污水环境监测设备");
+        return warning;
+    }
+
+    private static AlarmData alarm(String id, String level) {
+        AlarmData alarm = new AlarmData();
+        alarm.setId(id);
+        alarm.setAlarmNo(id);
+        alarm.setWarningCode("WS_ENV_HIGH");
+        alarm.setAlarmLevel(level);
+        alarm.setAlarmStatus(0);
+        alarm.setCreateTime(LocalDateTime.of(2026, 9, 2, 10, 0, 0));
+        alarm.setDeviceCode(DEVICE_CODE);
+        alarm.setDeviceName("污水环境监测设备");
+        return alarm;
+    }
+}

+ 66 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventLevelNameSerializationTest.java

@@ -0,0 +1,66 @@
+package com.zksy.cockpit.event;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+import java.util.Collections;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** 事件 DTO 的对外 JSON 形状:新增 levelName 与既有 level/levelColor 并存,缺名时为 null。 */
+class CockpitEventLevelNameSerializationTest {
+    private final ObjectMapper mapper = new ObjectMapper();
+
+    @Test
+    void warningAndAlarmSerializeLevelNameAlongsideLegacyLevelFields() throws Exception {
+        CockpitEventWarning warning = new CockpitEventWarning(
+                "WRN-1", "污水COD预警", "WS_ENV", 1, "RED", "一级预警", "化学需氧量(COD)预警接近上限", "PROCESSING",
+                "2026-09-02T09:59:30+08:00", new BigDecimal("18.2"), "mg/L",
+                "TC-PS-WS-202609020012", "污水环境监测设备", "太常片区");
+        CockpitEventAlarm alarm = new CockpitEventAlarm(
+                "ALM-1", "WS_ENV_HIGH", "污水COD报警", "WS_ENV", 4, "GREEN", "四级报警",
+                "化学需氧量(COD)报警超过上限", "UNHANDLED", "2026-09-02T10:00:00+08:00", new BigDecimal("42.0"),
+                new BigDecimal("40.0"), new BigDecimal("50.0"), "mg/L",
+                "TC-PS-WS-202609020012", "污水环境监测设备", "太常片区");
+
+        JsonNode warningJson = mapper.readTree(mapper.writeValueAsString(warning));
+        assertEquals("一级预警", warningJson.get("levelName").asText());
+        assertEquals(1, warningJson.get("level").asInt());
+        assertEquals("RED", warningJson.get("levelColor").asText());
+
+        JsonNode alarmJson = mapper.readTree(mapper.writeValueAsString(alarm));
+        assertEquals("四级报警", alarmJson.get("levelName").asText());
+        assertEquals(4, alarmJson.get("level").asInt());
+        assertEquals("GREEN", alarmJson.get("levelColor").asText());
+    }
+
+    @Test
+    void missingLevelKeepsLegacyUnknownColorAndNullLevelName() throws Exception {
+        CockpitEventWarning warning = new CockpitEventWarning(
+                "WRN-2", "无等级预警", "WS_ENV", null, "UNKNOWN", null, null, "PENDING",
+                null, null, null, null, null, null);
+
+        JsonNode json = mapper.readTree(mapper.writeValueAsString(warning));
+
+        assertTrue(json.has("levelName"));
+        assertTrue(json.get("levelName").isNull());
+        assertTrue(json.get("level").isNull());
+        assertEquals("UNKNOWN", json.get("levelColor").asText());
+    }
+
+    @Test
+    void emptyBatchStillSerializesEmptyFamilies() throws Exception {
+        CockpitEventSnapshot snapshot = new CockpitEventSnapshot(
+                "TC-PS-WS-202609020012", "ws_sewage_environment", "污水环境监测设备",
+                Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), 0);
+
+        JsonNode json = mapper.readTree(mapper.writeValueAsString(snapshot));
+
+        assertEquals(0, json.get("warnings").size());
+        assertEquals(0, json.get("alarms").size());
+        assertEquals(0, json.get("total").asInt());
+    }
+}

+ 114 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/event/CockpitEventLevelNameTest.java

@@ -0,0 +1,114 @@
+package com.zksy.cockpit.event;
+
+import com.zksy.common.core.domain.entity.SysDictData;
+import com.zksy.system.mapper.SysDictDataMapper;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+/** 事件等级展示名:字典命中、缺项兜底、缺失等级不伪造,以及每族只查一次字典。 */
+class CockpitEventLevelNameTest {
+
+    @Test
+    void dictionaryLabelWinsOverFallbackForBothFamilies() {
+        Map<Integer, String> alert = CockpitEventLevelName.labels(Arrays.asList(
+                dict("alert_level", "1", "一级预警"),
+                dict("alert_level", "2", "二级预警"),
+                dict("alert_level", "3", "三级预警"),
+                dict("alert_level", "4", "四级预警")));
+        Map<Integer, String> alarm = CockpitEventLevelName.labels(Arrays.asList(
+                dict("alarm_level", "1", "一级报警"),
+                dict("alarm_level", "4", "四级报警")));
+
+        assertEquals("一级预警", CockpitEventLevelName.warningOf(1, alert));
+        assertEquals("四级预警", CockpitEventLevelName.warningOf(4, alert));
+        assertEquals("一级报警", CockpitEventLevelName.alarmOf(1, alarm));
+        assertEquals("四级报警", CockpitEventLevelName.alarmOf(4, alarm));
+    }
+
+    @Test
+    void missingDictionaryEntryFallsBackToTheExistingChineseLevelWording() {
+        Map<Integer, String> onlyLevelOne = CockpitEventLevelName.labels(
+                Collections.singletonList(dict("alert_level", "1", "一级预警")));
+
+        assertEquals("一级预警", CockpitEventLevelName.warningOf(1, onlyLevelOne));
+        assertEquals("二级预警", CockpitEventLevelName.warningOf(2, onlyLevelOne));
+        assertEquals("三级预警", CockpitEventLevelName.warningOf(3, onlyLevelOne));
+        assertEquals("四级预警", CockpitEventLevelName.warningOf(4, onlyLevelOne));
+
+        // 整族字典缺失(含查询异常回空表)同样按既有口径兜底,不猜、不抛。
+        assertEquals("三级报警", CockpitEventLevelName.alarmOf(3, Collections.emptyMap()));
+        assertEquals("二级报警", CockpitEventLevelName.alarmOf(2, null));
+    }
+
+    @Test
+    void absentOrOutOfRangeLevelHasNoName() {
+        Map<Integer, String> alert = CockpitEventLevelName.labels(
+                Collections.singletonList(dict("alert_level", "1", "一级预警")));
+
+        assertNull(CockpitEventLevelName.warningOf(null, alert));
+        assertNull(CockpitEventLevelName.warningOf(0, alert));
+        assertNull(CockpitEventLevelName.warningOf(5, alert));
+        assertNull(CockpitEventLevelName.alarmOf(null, null));
+    }
+
+    @Test
+    void blankLabelAndInvalidDictValueAreIgnoredInsteadOfInventingAName() {
+        Map<Integer, String> alert = CockpitEventLevelName.labels(Arrays.asList(
+                dict("alert_level", "1", "  "),
+                dict("alert_level", "x", "非数字"),
+                dict("alert_level", "9", "越界标签"),
+                null,
+                dict("alert_level", "2", "二级预警")));
+
+        assertEquals(Collections.singletonMap(2, "二级预警"), alert);
+        // 标签缺失仍按兜底口径,而不是把空串当作名字下发。
+        assertEquals("一级预警", CockpitEventLevelName.warningOf(1, alert));
+    }
+
+    @Test
+    void eachFamilyIsQueriedOncePerBatchNotPerEvent() {
+        SysDictDataMapper dictMapper = mock(SysDictDataMapper.class);
+        List<SysDictData> alertRows = Arrays.asList(
+                dict("alert_level", "1", "一级预警"), dict("alert_level", "4", "四级预警"));
+        when(dictMapper.selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT)).thenReturn(alertRows);
+        when(dictMapper.selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT))
+                .thenReturn(Collections.emptyList());
+
+        Map<Integer, String> alert = CockpitEventLevelName.labels(
+                dictMapper, CockpitEventLevelName.WARNING_LEVEL_DICT);
+        Map<Integer, String> alarm = CockpitEventLevelName.labels(
+                dictMapper, CockpitEventLevelName.ALARM_LEVEL_DICT);
+
+        // 反复取标签只读本地映射,不再回查字典。
+        for (int level = 1; level <= 4; level++) {
+            CockpitEventLevelName.warningOf(level, alert);
+            CockpitEventLevelName.alarmOf(level, alarm);
+        }
+        verify(dictMapper).selectDictDataByType(CockpitEventLevelName.WARNING_LEVEL_DICT);
+        verify(dictMapper).selectDictDataByType(CockpitEventLevelName.ALARM_LEVEL_DICT);
+        verifyNoMoreInteractions(dictMapper);
+        assertEquals("一级预警", CockpitEventLevelName.warningOf(1, alert));
+        assertEquals("四级预警", CockpitEventLevelName.warningOf(4, alert));
+        assertEquals("一级报警", CockpitEventLevelName.alarmOf(1, alarm));
+    }
+
+    private static SysDictData dict(String dictType, String value, String label) {
+        SysDictData data = new SysDictData();
+        data.setDictType(dictType);
+        data.setDictValue(value);
+        data.setDictLabel(label);
+        data.setStatus("0");
+        return data;
+    }
+}

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

@@ -0,0 +1,185 @@
+package com.zksy.cockpit.overview;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.zksy.cockpit.overview.mapper.CockpitOverviewModulesMapper;
+import org.apache.ibatis.builder.xml.XMLMapperBuilder;
+import org.apache.ibatis.mapping.BoundSql;
+import org.apache.ibatis.mapping.MappedStatement;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 预警研判统计排除草稿的 SQL 契约(维护者 2026-11-12)。
+ *
+ * <p>维护者原话:「预警统计要排除草稿状态的预警。例:当前的总体概览-运行监测-预警研判中的
+ * 统计没有排除草稿状态的预警。」</p>
+ *
+ * <p>断言的是 MyBatis **解析并展开后**的 SQL({@code BoundSql}),不是 XML 文本:
+ * 片段被挪进注释、或塞进恒不成立的 {@code <if>} 时,文本断言仍会绿(与
+ * {@code WorkOrderAlarmConflictMapperTest} 同一写法)。</p>
+ *
+ * <p>两条口径都有断言盯着:</p>
+ * <ul>
+ *   <li>计数(今日/昨日新增、区间总数、类型排行)排除草稿;</li>
+ *   <li><b>新鲜度</b>({@code source_updated_at})<b>不</b>排除草稿 —— 它是「源数据最后动过的时间」,
+ *       跟着排除会让编辑草稿后面的板误判数据过旧;</li>
+ *   <li>{@code status IS NULL} 的行保持改动前行为(仍计入),不因加筛选被默默丢掉。</li>
+ * </ul>
+ */
+class CockpitOverviewWarningStudyContractTest {
+
+    private static MybatisConfiguration configuration;
+
+    @BeforeAll
+    static void parseMapper() throws Exception {
+        configuration = new MybatisConfiguration();
+        // 直接读 **源码** mapper,不读 classpath 副本:`target/classes` 可能比源码旧
+        // (本仓库增量构建遇到过),拿旧副本解析会让本控制器假红/假绿。
+        java.nio.file.Path source = sourceMapper();
+        try (InputStream xml = java.nio.file.Files.newInputStream(source)) {
+            new XMLMapperBuilder(xml, configuration, source.toString(),
+                    configuration.getSqlFragments()).parse();
+        }
+    }
+
+    /** 模块目录与仓库根目录两种工作目录下都能定位到源码 mapper。 */
+    private static java.nio.file.Path sourceMapper() {
+        java.nio.file.Path cwd = java.nio.file.Path.of(System.getProperty("user.dir")).toAbsolutePath();
+        String relative = "src/main/resources/mapper/cockpit/CockpitOverviewModulesMapper.xml";
+        for (java.nio.file.Path candidate : new java.nio.file.Path[]{
+                cwd.resolve(relative),
+                cwd.resolve("zksy-system").resolve(relative),
+                cwd.resolve("pipe-network-service").resolve("zksy-system").resolve(relative)}) {
+            java.nio.file.Path normalized = candidate.normalize();
+            if (java.nio.file.Files.exists(normalized)) {
+                return normalized;
+            }
+        }
+        throw new AssertionError("找不到源码 mapper(工作目录 " + cwd + ")");
+    }
+
+    @Test
+    void todayAndYesterdayCountsExcludeDraftButKeepNullStatusRows() {
+        String sql = boundSql("selectWarningCounts");
+
+        // 每个计数分支都带排除条件(SUM 里两个 CASE,因此出现两次)
+        assertTrue(count(sql, draftExclusion()) == 2,
+                "今日/昨日新增两个计数分支都必须排除草稿:" + sql);
+        assertTrue(sql.contains("w.status IS NULL OR"), "NULL 行必须保留:那是加筛选前的既有行为");
+    }
+
+    @Test
+    void sourceUpdatedAtStillCoversDraftEdits() {
+        String sql = boundSql("selectWarningCounts");
+
+        // 新鲜度是整条查询唯一的 MAX,它在筛选之外:草稿更新也要刷新它。
+        assertTrue(sql.contains("MAX(w.update_time) AS source_updated_at"), sql);
+        // 只看主查询的 WHERE(前面的递归 CTE 也有 WHERE,不能拿首个 WHERE 就断)。
+        String where = sql.substring(sql.lastIndexOf(" FROM app_user.early_warning w WHERE"));
+        assertFalse(where.contains("DRAFT"),
+                "新鲜度不能被草稿筛选掉,否则编辑草稿后 freshness 会被误判过旧:" + where);
+    }
+
+    @Test
+    void warningCountInWindowExcludesDraft() {
+        assertTrue(boundSql("selectWarningCountInWindow").contains(draftExclusion()),
+                "类型排行的分母(区间总数)必须排除草稿");
+    }
+
+    @Test
+    void warningTypeRankingExcludesDraft() {
+        assertTrue(boundSql("selectWarningTypeCountsInWindow").contains(draftExclusion()),
+                "类型排行每一行都必须排除草稿");
+    }
+
+    /**
+     * 类型排行必须与标题「共 XX 起」同源(维护者 2026-11-12 要求审查本项)。
+     *
+     * <p>两数来自两条查询,只有 WHERE 条件完全一致时才可能相等。历史缺陷:空类型
+     * ({@code warning_type} 为 NOT NULL 但可为空串)被 SQL 分出一行、又被服务层丢弃,
+     * 于是行之和恒小于 total。</p>
+     */
+    @Test
+    void warningTypeRankingSharesTheSameWhereAsTheTotal() {
+        String ranking = boundSql("selectWarningTypeCountsInWindow");
+        String total = boundSql("selectWarningCountInWindow");
+
+        assertTrue(ranking.contains("CASE WHEN w.warning_type IS NULL OR TRIM(w.warning_type) = ''"),
+                "空类型必须归成命名占位码,不能留下会被服务层丢掉的行:" + ranking);
+        assertTrue(ranking.contains("COUNT(*) AS type_count") && total.contains("COUNT(*) AS warning_count"),
+                "两条查询都是逐条计数,口径可以直接相加比对");
+        assertEquals(whereOf(ranking), whereOf(total),
+                "排行与总数的 WHERE 必须逐字一致,否则「共 XX 起」与各行之和对不上");
+    }
+
+    /** 取主查询的 WHERE 子句(到 GROUP BY / ORDER BY 为止;跳过前面的递归 CTE)。 */
+    private static String whereOf(String sql) {
+        int from = sql.lastIndexOf(" FROM app_user.early_warning w ");
+        assertTrue(from >= 0, "找不到主查询:" + sql);
+        String tail = sql.substring(from);
+        int end = tail.length();
+        for (String stop : new String[]{" GROUP BY ", " ORDER BY "}) {
+            int at = tail.indexOf(stop);
+            if (at >= 0 && at < end) end = at;
+        }
+        return tail.substring(0, end);
+    }
+
+    @Test
+    void unresolvedStatusesKeepTheirOwnAllowList() {
+        String sql = boundSql("selectUnresolvedStatusLevelCounts");
+
+        assertTrue(sql.contains("IN ('PENDING', 'RECEIVED', 'PROCESSING', 'HANDLED')"),
+                "未解除集合保持白名单四态");
+        assertFalse(sql.contains("DRAFT"), "白名单已排除草稿,不应再叠一条条件");
+    }
+
+    private static String draftExclusion() {
+        return "(w.status IS NULL OR UPPER(TRIM(w.status)) <> 'DRAFT')";
+    }
+
+    private static int count(String text, String needle) {
+        int found = 0;
+        for (int at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length())) {
+            found += 1;
+        }
+        return found;
+    }
+
+    private static String boundSql(String id) {
+        MappedStatement statement = configuration
+                .getMappedStatement(CockpitOverviewModulesMapper.class.getName() + "." + id);
+        BoundSql bound = statement.getBoundSql(parameters());
+        return bound.getSql().replaceAll("\\s+", " ");
+    }
+
+    /** 全部可选条件都关掉:这里只看状态口径,不看片区/行业筛选。 */
+    private static Map<String, Object> parameters() {
+        ZoneId zone = ZoneId.systemDefault();
+        Date yesterday = Date.from(LocalDate.parse("2026-11-11").atStartOfDay(zone).toInstant());
+        Date today = Date.from(LocalDate.parse("2026-11-12").atStartOfDay(zone).toInstant());
+        Date tomorrow = Date.from(LocalDate.parse("2026-11-13").atStartOfDay(zone).toInstant());
+        Map<String, Object> params = new HashMap<>();
+        params.put("yesterdayStart", yesterday);
+        params.put("todayStart", today);
+        params.put("tomorrowStart", tomorrow);
+        params.put("startInclusive", yesterday);
+        params.put("endExclusive", tomorrow);
+        params.put("district", null);
+        params.put("unassigned", false);
+        params.put("industryRootTypeId", null);
+        return params;
+    }
+}

+ 87 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/video/VideoLiveSharingTest.java

@@ -0,0 +1,87 @@
+package com.zksy.cockpit.video;
+
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+/**
+ * Shared live generation: releasing one viewer must not stop another viewer's stream.
+ * The mapper stands in for the database's count answer; the sharing decision stays in production.
+ */
+class VideoLiveSharingTest {
+    private static final String VIDEO = "sharing-camera-ledger";
+    private static final String GENERATION = "5f2a7c1e-1111-4a2b-9c3d-000000000001";
+
+    private final VideoSessionMapper sessions = mock(VideoSessionMapper.class);
+    private final EquipmentVideoBindingMapper bindings = mock(EquipmentVideoBindingMapper.class);
+    private final VideoCollectorClient collector = mock(VideoCollectorClient.class);
+    private final Clock clock = Clock.fixed(Instant.parse("2026-11-12T01:00:00Z"), ZoneOffset.UTC);
+    private VideoLiveLifecycle lifecycle;
+
+    @BeforeEach void setUp() {
+        lifecycle = new VideoLiveLifecycle(sessions, bindings, collector, clock);
+        VideoDeviceRecord binding = new VideoDeviceRecord();
+        binding.setVideoId(VIDEO);
+        binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001");
+        binding.setGbChannelId("34020000001320000001");
+        when(bindings.find(VIDEO)).thenReturn(binding);
+        when(sessions.lockVideo(VIDEO)).thenReturn(VIDEO);
+        when(sessions.updateById(any(VideoSession.class))).thenReturn(1);
+    }
+
+    private VideoSession activeViewer(String sessionId) {
+        VideoSession row = new VideoSession();
+        row.setSessionId(sessionId);
+        row.setVideoId(VIDEO);
+        row.setMode("LIVE");
+        row.setStatus("ACTIVE");
+        row.setMediaGeneration(GENERATION);
+        row.setStartDeadline(LocalDateTime.now(clock).plusSeconds(30));
+        row.setCreateTime(LocalDateTime.now(clock));
+        row.setLastSeen(LocalDateTime.now(clock));
+        return row;
+    }
+
+    @Test void releasingOneOfTwoViewersKeepsTheSharedStreamRunning() {
+        VideoSession mine = activeViewer("viewer-1");
+        when(sessions.selectCount(any())).thenReturn(1L);
+
+        Map<String, Object> result = lifecycle.stop(() -> mine);
+
+        assertEquals("STOPPED", result.get("status"));
+        assertEquals("viewer-1", result.get("sessionId"));
+        assertNull(result.get("media"), "a shared viewer must not receive another session's media");
+        verify(collector, never()).post(anyString(), any());
+    }
+
+    @Test void releasingTheLastViewerReclaimsTheSharedStreamOnce() {
+        VideoSession mine = activeViewer("viewer-2");
+        when(sessions.selectCount(any())).thenReturn(0L);
+        when(collector.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+
+        Map<String, Object> result = lifecycle.stop(() -> mine);
+
+        assertEquals("STOPPED", result.get("status"));
+        verify(collector, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+}

+ 343 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/workorder/CockpitWorkOrderDetailFieldsTest.java

@@ -0,0 +1,343 @@
+package com.zksy.cockpit.workorder;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.zksy.base.alarm.domain.AlarmData;
+import com.zksy.base.alarm.service.AlarmDataService;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.service.EquipmentTypeService;
+import com.zksy.base.warning.mapper.AlarmWarningRelMapper;
+import com.zksy.base.warning.service.EarlyWarningService;
+import com.zksy.common.core.domain.entity.SysDictData;
+import com.zksy.common.core.domain.entity.SysUser;
+import com.zksy.ops.domain.WorkOrder;
+import com.zksy.ops.service.WorkOrderService;
+import com.zksy.system.mapper.SysDictDataMapper;
+import com.zksy.system.service.ISysUserService;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.apache.ibatis.session.Configuration;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.time.Instant;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 工单详情字段补齐(驾驶舱「工单信息」页签)。
+ *
+ * <p>断言三件事:有值时原样映射、缺值如实为 null/空数组、以及详情字段按整页批量取
+ * (设备一次 selectBatchIds、用户一次 selectEnabledUsersByIds、优先级字典一次 selectDictDataByType),
+ * 不随工单条数增长。</p>
+ */
+class CockpitWorkOrderDetailFieldsTest {
+    private static final String DEVICE_CODE = "21119740";
+    private static final String EQUIPMENT_ID = "equipment-id";
+
+    private WorkOrderService workOrderService;
+    private AlarmDataService alarmDataService;
+    private EquipmentBaseMapper equipmentBaseMapper;
+    private EquipmentTypeService equipmentTypeService;
+    private SysDictDataMapper sysDictDataMapper;
+    private ISysUserService sysUserService;
+    private BusinessCockpitWorkOrderReadAdapter adapter;
+
+    @BeforeEach
+    void setUp() {
+        for (Class<?> entity : Arrays.asList(EquipmentBase.class, WorkOrder.class, AlarmData.class)) {
+            TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new Configuration(), ""), entity);
+        }
+        workOrderService = mock(WorkOrderService.class);
+        alarmDataService = mock(AlarmDataService.class);
+        equipmentBaseMapper = mock(EquipmentBaseMapper.class);
+        equipmentTypeService = mock(EquipmentTypeService.class);
+        sysDictDataMapper = mock(SysDictDataMapper.class);
+        sysUserService = mock(ISysUserService.class);
+        adapter = new BusinessCockpitWorkOrderReadAdapter(
+                workOrderService,
+                mock(EarlyWarningService.class),
+                mock(AlarmWarningRelMapper.class),
+                alarmDataService,
+                equipmentBaseMapper,
+                equipmentTypeService,
+                sysDictDataMapper,
+                sysUserService);
+    }
+
+    @Test
+    void everyDetailFieldIsMappedFromItsAuthoritativeSource() {
+        stubCommon(Collections.singletonList(fullOrder()));
+        when(equipmentBaseMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(fullDevice()));
+        when(sysDictDataMapper.selectDictDataByType(CockpitWorkOrderLevelName.LEVEL_DICT))
+                .thenReturn(Arrays.asList(dict("0", "紧急"), dict("1", "一般"), dict("2", "低")));
+        when(sysUserService.selectEnabledUsersByIds(any()))
+                .thenReturn(Arrays.asList(user(11L, "张三", "zhangsan"), user(12L, "李四", "lisi")));
+
+        List<CockpitWorkOrderSummary> summaries = adapter.loadByDevice(DEVICE_CODE).getWorkOrders();
+
+        assertEquals(1, summaries.size());
+        CockpitWorkOrderSummary summary = summaries.get(0);
+        // 故障时间:ISO-8601 带 Asia/Shanghai 偏移
+        assertEquals("2026-10-10T07:11:30+08:00", summary.getFaultTime());
+        // 关联设备 / 设备位置取设备台账,不由工单表猜
+        assertEquals("测试泵站流量计", summary.getDeviceName());
+        assertEquals("太常片区泵站", summary.getDeviceLocation());
+        // 优先级中文名取 work_order_level 字典(0-紧急)
+        assertEquals("紧急", summary.getOrderLevelName());
+        // 处置人 / 核验人姓名(nick_name 优先)
+        assertEquals("张三", summary.getReceiveUserName());
+        assertEquals("李四", summary.getVerifyUserName());
+        // 维修前/后图片:库内逗号分隔串 → 数组
+        assertArrayEquals(new String[]{"https://img/a.jpg", "https://img/b.jpg"},
+                summary.getMaintenanceBeforeImages().toArray(new String[0]));
+        assertArrayEquals(new String[]{"https://img/c.jpg"},
+                summary.getMaintenanceAfterImages().toArray(new String[0]));
+        // 延期申请块
+        assertNotNull(summary.getDelayApply());
+        assertEquals(1, summary.getDelayApply().getStatus());
+        assertEquals("待延期审核", summary.getDelayApply().getStatusName());
+        assertEquals("配件未到货", summary.getDelayApply().getReason());
+        assertEquals("2026-10-15T18:00:00+08:00", summary.getDelayApply().getDeadline());
+        // 既有字段与行为不变
+        assertEquals("WO-279", summary.getWorkOrderCode());
+        assertEquals(DEVICE_CODE, summary.getDeviceCode());
+        assertEquals(0, summary.getOrderLevel());
+    }
+
+    @Test
+    void missingSourcesYieldNullAndEmptyCollectionsInsteadOfFabricatedValues() {
+        WorkOrder bare = new WorkOrder();
+        bare.setOrderId(279L);
+        bare.setOrderNo("WO-279");
+        bare.setDeviceId(EQUIPMENT_ID);
+        bare.setOrderLevel(1);
+        bare.setOrderStatus(0);
+        stubCommon(Collections.singletonList(bare));
+        // 设备台账查不到、字典为空、用户查不到:详情字段只能如实为 null / 空数组。
+        when(equipmentBaseMapper.selectBatchIds(any())).thenReturn(Collections.emptyList());
+        when(sysDictDataMapper.selectDictDataByType(CockpitWorkOrderLevelName.LEVEL_DICT))
+                .thenReturn(Collections.emptyList());
+        when(sysUserService.selectEnabledUsersByIds(any())).thenReturn(Collections.emptyList());
+
+        CockpitWorkOrderSummary summary = adapter.loadByDevice(DEVICE_CODE).getWorkOrders().get(0);
+
+        assertNull(summary.getFaultTime());
+        // 设备缺失时连编码也不拿工单里的 device_id 冒充
+        assertNull(summary.getDeviceCode());
+        assertNull(summary.getDeviceName());
+        assertNull(summary.getDeviceLocation());
+        // 字典缺项:不给中文名,也不内置「紧急/一般/低」词表
+        assertNull(summary.getOrderLevelName());
+        assertNull(summary.getReceiveUserName());
+        assertNull(summary.getVerifyUserName());
+        assertTrue(summary.getMaintenanceBeforeImages().isEmpty());
+        assertTrue(summary.getMaintenanceAfterImages().isEmpty());
+        // 无延期申请(delay_apply_status 缺省)时整块为 null,不造空对象
+        assertNull(summary.getDelayApply());
+        // 既有字段仍在
+        assertEquals(1, summary.getOrderLevel());
+        assertEquals("WO-279", summary.getWorkOrderCode());
+    }
+
+    @Test
+    void delayApplyStatusZeroIsNoApplicationAndImagesIgnoreBlankSegments() {
+        WorkOrder order = fullOrder();
+        order.setDelayApplyStatus(0);
+        order.setDelayedReason("应被忽略");
+        order.setDelayedDeadline(Date.from(Instant.parse("2026-10-15T10:00:00Z")));
+        order.setMaintenanceBeforeImg(" https://img/a.jpg , , https://img/b.jpg ,");
+        order.setMaintenanceAfterImg("   ");
+        stubCommon(Collections.singletonList(order));
+        when(equipmentBaseMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(fullDevice()));
+        when(sysDictDataMapper.selectDictDataByType(any())).thenReturn(Collections.emptyList());
+        when(sysUserService.selectEnabledUsersByIds(any())).thenReturn(Collections.emptyList());
+
+        CockpitWorkOrderSummary summary = adapter.loadByDevice(DEVICE_CODE).getWorkOrders().get(0);
+
+        // 状态 0 = 无延期申请:不因为残留的 reason/deadline 编出一块申请
+        assertNull(summary.getDelayApply());
+        // 逗号分隔里的空段被丢弃,不产出 "" 元素
+        assertArrayEquals(new String[]{"https://img/a.jpg", "https://img/b.jpg"},
+                summary.getMaintenanceBeforeImages().toArray(new String[0]));
+        assertTrue(summary.getMaintenanceAfterImages().isEmpty());
+    }
+
+    @Test
+    void userLookupFailureOnlyDegradesNamesInsteadOfFailingTheList() {
+        stubCommon(Collections.singletonList(fullOrder()));
+        when(equipmentBaseMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(fullDevice()));
+        when(sysDictDataMapper.selectDictDataByType(any())).thenReturn(Collections.emptyList());
+        when(sysUserService.selectEnabledUsersByIds(any()))
+                .thenThrow(new IllegalStateException("user table unavailable"));
+
+        CockpitWorkOrderSummary summary = adapter.loadByDevice(DEVICE_CODE).getWorkOrders().get(0);
+
+        assertNotNull(summary);
+        assertNull(summary.getReceiveUserName());
+        assertNull(summary.getVerifyUserName());
+        // 其它详情字段照旧可用:姓名查询失败不拖垮整份工单数据。
+        assertEquals("测试泵站流量计", summary.getDeviceName());
+    }
+
+    @Test
+    void detailSourcesAreFetchedOncePerRequestNotPerOrder() {
+        List<WorkOrder> orders = Arrays.asList(fullOrder(), secondOrder(), thirdOrder());
+        stubCommon(orders);
+        when(equipmentBaseMapper.selectBatchIds(any())).thenReturn(Collections.singletonList(fullDevice()));
+        when(sysDictDataMapper.selectDictDataByType(CockpitWorkOrderLevelName.LEVEL_DICT))
+                .thenReturn(Collections.singletonList(dict("0", "紧急")));
+        when(sysUserService.selectEnabledUsersByIds(any()))
+                .thenReturn(Collections.singletonList(user(11L, "张三", "zhangsan")));
+
+        List<CockpitWorkOrderSummary> summaries = adapter.loadByDevice(DEVICE_CODE).getWorkOrders();
+
+        assertEquals(3, summaries.size());
+        verify(equipmentBaseMapper, times(1)).selectBatchIds(any());
+        verify(sysUserService, times(1)).selectEnabledUsersByIds(any());
+        verify(sysDictDataMapper, times(1)).selectDictDataByType(CockpitWorkOrderLevelName.LEVEL_DICT);
+        assertEquals("紧急", summaries.get(0).getOrderLevelName());
+        assertEquals("张三", summaries.get(1).getReceiveUserName());
+    }
+
+    @Test
+    void newFieldsSerializeWithStableNamesAndArrays() throws Exception {
+        CockpitWorkOrderSummary summary = new CockpitWorkOrderSummary(
+                280L,
+                "WO-280",
+                DEVICE_CODE,
+                0,
+                "摄像头坏了",
+                0,
+                "待派单",
+                "2026-10-10T07:11:30+08:00",
+                "2026-10-10T07:11:30+08:00",
+                "2026-10-11T00:00:00+08:00",
+                null,
+                null,
+                false,
+                "2026-10-10T07:10:00+08:00",
+                "测试泵站流量计",
+                "太常片区泵站",
+                "紧急",
+                "张三",
+                "李四",
+                Arrays.asList("https://img/a.jpg", "https://img/b.jpg"),
+                Collections.emptyList(),
+                new CockpitWorkOrderDelayApply(1, "待延期审核", "配件未到货", "2026-10-15T18:00:00+08:00"));
+
+        JsonNode json = new ObjectMapper().readTree(new ObjectMapper().writeValueAsString(summary));
+
+        assertEquals("2026-10-10T07:10:00+08:00", json.get("faultTime").asText());
+        assertEquals("测试泵站流量计", json.get("deviceName").asText());
+        assertEquals("太常片区泵站", json.get("deviceLocation").asText());
+        assertEquals("紧急", json.get("orderLevelName").asText());
+        assertEquals("张三", json.get("receiveUserName").asText());
+        assertEquals("李四", json.get("verifyUserName").asText());
+        assertEquals(2, json.get("maintenanceBeforeImages").size());
+        assertEquals("https://img/b.jpg", json.get("maintenanceBeforeImages").get(1).asText());
+        assertTrue(json.get("maintenanceAfterImages").isArray());
+        assertEquals(0, json.get("maintenanceAfterImages").size());
+        assertEquals(1, json.get("delayApply").get("status").asInt());
+        assertEquals("待延期审核", json.get("delayApply").get("statusName").asText());
+        assertEquals("配件未到货", json.get("delayApply").get("reason").asText());
+        assertEquals("2026-10-15T18:00:00+08:00", json.get("delayApply").get("deadline").asText());
+        // 既有字段顺序/名称不变,且内部主键仍不进 JSON
+        assertEquals("WO-280", json.get("workOrderCode").asText());
+        assertEquals(false, json.get("associatedWithCurrentEvent").asBoolean());
+        assertTrue(!json.has("orderId"));
+    }
+
+    // --- fixtures ---
+
+    private void stubCommon(List<WorkOrder> orders) {
+        EquipmentBase equipment = new EquipmentBase();
+        equipment.setEquipmentId(EQUIPMENT_ID);
+        equipment.setEquipmentCode(DEVICE_CODE);
+        when(equipmentBaseMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(equipment);
+        when(workOrderService.list(any(LambdaQueryWrapper.class))).thenReturn(orders);
+        // 每次查询都返回空报警,聚焦工单自身的详情字段
+        when(alarmDataService.list(any(LambdaQueryWrapper.class))).thenReturn(Collections.emptyList());
+    }
+
+    private static WorkOrder fullOrder() {
+        WorkOrder order = new WorkOrder();
+        order.setOrderId(279L);
+        order.setOrderNo("WO-279");
+        order.setDeviceId(EQUIPMENT_ID);
+        order.setFaultTime(Date.from(Instant.parse("2026-10-09T23:11:30Z")));
+        order.setOrderLevel(0);
+        order.setOrderDesc("摄像头坏了");
+        order.setOrderStatus(4);
+        order.setReceiveUser(11L);
+        order.setVerifyUser(12L);
+        order.setMaintenanceBeforeImg("https://img/a.jpg,https://img/b.jpg");
+        order.setMaintenanceAfterImg("https://img/c.jpg");
+        order.setDelayApplyStatus(1);
+        order.setDelayedReason("配件未到货");
+        order.setDelayedDeadline(Date.from(Instant.parse("2026-10-15T10:00:00Z")));
+        order.setCreateTime(Date.from(Instant.parse("2026-10-10T07:11:30Z")));
+        order.setUpdateTime(Date.from(Instant.parse("2026-10-10T07:11:30Z")));
+        return order;
+    }
+
+    private static WorkOrder secondOrder() {
+        WorkOrder order = fullOrder();
+        order.setOrderId(280L);
+        order.setOrderNo("WO-280");
+        order.setDelayApplyStatus(0);
+        order.setReceiveUser(11L);
+        return order;
+    }
+
+    private static WorkOrder thirdOrder() {
+        WorkOrder order = fullOrder();
+        order.setOrderId(281L);
+        order.setOrderNo("WO-281");
+        order.setDelayApplyStatus(0);
+        order.setReceiveUser(null);
+        order.setVerifyUser(null);
+        return order;
+    }
+
+    private static EquipmentBase fullDevice() {
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(EQUIPMENT_ID);
+        device.setEquipmentCode(DEVICE_CODE);
+        device.setEquipmentName("测试泵站流量计");
+        device.setEquipmentLocation("太常片区泵站");
+        return device;
+    }
+
+    private static SysUser user(Long userId, String nickName, String userName) {
+        SysUser user = new SysUser();
+        user.setUserId(userId);
+        user.setNickName(nickName);
+        user.setUserName(userName);
+        return user;
+    }
+
+    private static SysDictData dict(String value, String label) {
+        SysDictData data = new SysDictData();
+        data.setDictType(CockpitWorkOrderLevelName.LEVEL_DICT);
+        data.setDictValue(value);
+        data.setDictLabel(label);
+        data.setStatus("0");
+        return data;
+    }
+}

+ 3 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IInviteStreamService.java

@@ -34,6 +34,9 @@ public interface IInviteStreamService {
      * 移除点播的状态信息
      * 移除点播的状态信息
      */
      */
     void removeInviteInfo(InviteInfo inviteInfo);
     void removeInviteInfo(InviteInfo inviteInfo);
+
+    /** Compare the original allocation, then atomically delete only the observed raw hash value. */
+    boolean removeInviteInfoIfSame(InviteInfo expected);
     /**
     /**
      * 移除点播的状态信息
      * 移除点播的状态信息
      */
      */

+ 11 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IPlayService.java

@@ -19,6 +19,17 @@ import com.ruoyi.wvp.common.InviteInfo;
  */
  */
 public interface IPlayService {
 public interface IPlayService {
 
 
+    SSRCInfo playManaged(MediaServer mediaServer, String deviceId, String channelId, String stream, ErrorCallback<StreamInfo> callback);
+
+    /** True only after both SIP termination and exact RTP close are confirmed. */
+    boolean stopManaged(MediaServer mediaServer, Device device, DeviceChannel channel, String stream);
+
+    /** Capture/revalidate an observed legacy dialog; never allocates or replaces media. */
+    String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle);
+
+    /** An opaque adoption handle binds node/device/channel/stream and Call-ID/SSRC/allocation token. */
+    boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle);
+
     SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback);
     SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback);
 
 
     StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel);
     StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel);

+ 11 - 3
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/DeviceServiceImpl.java

@@ -3,6 +3,7 @@ package com.ruoyi.wvp.gb28181.service.impl;
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSON;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.baomidou.dynamic.datasource.annotation.DS;
 import com.ruoyi.wvp.common.CommonCallback;
 import com.ruoyi.wvp.common.CommonCallback;
+import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.common.VideoManagerConstants;
 import com.ruoyi.wvp.common.VideoManagerConstants;
 import com.ruoyi.wvp.common.enums.ChannelDataType;
 import com.ruoyi.wvp.common.enums.ChannelDataType;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.DynamicTask;
@@ -19,6 +20,7 @@ import com.ruoyi.wvp.gb28181.transmit.event.request.impl.message.response.cmd.Ca
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.utils.DateUtil;
 import com.ruoyi.wvp.utils.DateUtil;
 import com.zksy.common.enums.ErrorCode;
 import com.zksy.common.enums.ErrorCode;
@@ -79,6 +81,9 @@ public class DeviceServiceImpl implements IDeviceService {
     @Autowired
     @Autowired
     private IMediaServerService mediaServerService;
     private IMediaServerService mediaServerService;
 
 
+    @Autowired
+    private RtpServerServiceImpl rtpServerService;
+
     private Device getDeviceByDeviceIdFromDb(String deviceId) {
     private Device getDeviceByDeviceIdFromDb(String deviceId) {
         return deviceMapper.getDeviceByDeviceId(deviceId);
         return deviceMapper.getDeviceByDeviceId(deviceId);
     }
     }
@@ -197,9 +202,12 @@ public class DeviceServiceImpl implements IDeviceService {
         List<SsrcTransaction> ssrcTransactions = sessionManager.getSsrcTransactionByDeviceId(deviceId);
         List<SsrcTransaction> ssrcTransactions = sessionManager.getSsrcTransactionByDeviceId(deviceId);
         if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
         if (ssrcTransactions != null && ssrcTransactions.size() > 0) {
             for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
             for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
-                mediaServerService.releaseSsrc(ssrcTransaction.getMediaServerId(), ssrcTransaction.getSsrc());
-                mediaServerService.closeRTPServer(ssrcTransaction.getMediaServerId(), ssrcTransaction.getStream());
-                sessionManager.removeByCallId(ssrcTransaction.getCallId());
+                InviteInfo invite = inviteStreamService.getInviteInfo(ssrcTransaction.getType(),
+                        ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
+                if (!rtpServerService.closeRTPServerForSession(ssrcTransaction, invite)) continue;
+                if (invite != null && !inviteStreamService.removeInviteInfoIfSame(invite)) continue;
+                // Local loss detection is not SIP completion; retain durable receipts and original dialog there.
+                sessionManager.removeIfSame(ssrcTransaction);
             }
             }
         }
         }
         // 移除订阅
         // 移除订阅

+ 32 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java

@@ -8,6 +8,7 @@ import com.ruoyi.wvp.gb28181.bean.Device;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceChannelMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.mapper.DeviceMapper;
 import com.ruoyi.wvp.gb28181.service.IInviteStreamService;
 import com.ruoyi.wvp.gb28181.service.IInviteStreamService;
+import com.ruoyi.wvp.gb28181.session.SipRedisCompareAndSet;
 import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
 import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
 import com.ruoyi.wvp.service.bean.ErrorCallback;
 import com.ruoyi.wvp.service.bean.ErrorCallback;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -53,6 +54,8 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
     @Async("taskExecutor")
     @Async("taskExecutor")
     @EventListener
     @EventListener
     public void onApplicationEvent(MediaDepartureEvent event) {
     public void onApplicationEvent(MediaDepartureEvent event) {
+        // Managed teardown owns this exact Invite until SIP/RTP termination is confirmed.
+        if (isManaged(event.getStream())) return;
         if ("rtsp".equals(event.getSchema()) && "rtp".equals(event.getApp())) {
         if ("rtsp".equals(event.getSchema()) && "rtp".equals(event.getApp())) {
             InviteInfo inviteInfo = getInviteInfoByStream(null, event.getStream());
             InviteInfo inviteInfo = getInviteInfoByStream(null, event.getStream());
             if (inviteInfo != null && (inviteInfo.getType() == InviteSessionType.PLAY || inviteInfo.getType() == InviteSessionType.PLAYBACK)) {
             if (inviteInfo != null && (inviteInfo.getType() == InviteSessionType.PLAY || inviteInfo.getType() == InviteSessionType.PLAYBACK)) {
@@ -209,6 +212,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
             return;
             return;
         }
         }
         InviteInfo inviteInfo = getInviteInfo(type, channelId, stream);
         InviteInfo inviteInfo = getInviteInfo(type, channelId, stream);
+        if (stream == null && inviteInfo != null && isManaged(inviteInfo.getStream())) return;
         if (inviteInfo != null) {
         if (inviteInfo != null) {
             String objectKey = inviteInfo.getType() +
             String objectKey = inviteInfo.getType() +
                     ":" + inviteInfo.getChannelId() +
                     ":" + inviteInfo.getChannelId() +
@@ -227,6 +231,29 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         removeInviteInfo(inviteInfo.getType(), inviteInfo.getChannelId(), inviteInfo.getStream());
         removeInviteInfo(inviteInfo.getType(), inviteInfo.getChannelId(), inviteInfo.getStream());
     }
     }
 
 
+    @Override
+    public boolean removeInviteInfoIfSame(InviteInfo expected) {
+        if (expected == null || expected.getType() == null || expected.getChannelId() == null
+                || expected.getStream() == null || expected.getSsrcInfo() == null) return false;
+        String key = VideoManagerConstants.INVITE_PREFIX;
+        String field = expected.getType() + ":" + expected.getChannelId() + ":" + expected.getStream();
+        // Status/StreamInfo may advance while the same allocation stops; never follow a new allocation.
+        for (int attempt = 0; attempt < 3; attempt++) {
+            Object raw = redisTemplate.opsForHash().get(key, field);
+            if (raw == null) return true;
+            if (!(raw instanceof InviteInfo)) return false;
+            InviteInfo current = (InviteInfo) raw;
+            if (expected.getType() != current.getType()
+                    || !java.util.Objects.equals(expected.getChannelId(), current.getChannelId())
+                    || !java.util.Objects.equals(expected.getDeviceId(), current.getDeviceId())
+                    || !java.util.Objects.equals(expected.getMediaServerId(), current.getMediaServerId())
+                    || !java.util.Objects.equals(expected.getStream(), current.getStream())
+                    || !expected.getSsrcInfo().equals(current.getSsrcInfo())) return false;
+            if (SipRedisCompareAndSet.apply(redisTemplate, new SipRedisCompareAndSet.Change(key, field, raw, null))) return true;
+        }
+        return false;
+    }
+
     @Override
     @Override
     public void once(InviteSessionType type, Integer channelId, String stream, ErrorCallback<StreamInfo> callback) {
     public void once(InviteSessionType type, Integer channelId, String stream, ErrorCallback<StreamInfo> callback) {
         String key = buildKey(type, channelId, stream);
         String key = buildKey(type, channelId, stream);
@@ -334,6 +361,10 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         return inviteInfoInDb;
         return inviteInfoInDb;
     }
     }
 
 
+    private static boolean isManaged(String stream) {
+        return stream != null && stream.matches("managed_[0-9a-f]{32}");
+    }
+
     @Scheduled(fixedRate = 10000)   //定时检测,清理错误的redis数据,防止因为错误数据导致的点播不可用
     @Scheduled(fixedRate = 10000)   //定时检测,清理错误的redis数据,防止因为错误数据导致的点播不可用
     public void execute(){
     public void execute(){
         String key = VideoManagerConstants.INVITE_PREFIX;
         String key = VideoManagerConstants.INVITE_PREFIX;
@@ -343,7 +374,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         List<Object> values = redisTemplate.opsForHash().values(key);
         List<Object> values = redisTemplate.opsForHash().values(key);
         for (Object value : values) {
         for (Object value : values) {
             InviteInfo inviteInfo = (InviteInfo)value;
             InviteInfo inviteInfo = (InviteInfo)value;
-            if (inviteInfo.getStreamInfo() != null) {
+            if (isManaged(inviteInfo.getStream()) || inviteInfo.getStreamInfo() != null) {
                 continue;
                 continue;
             }
             }
             if (inviteInfo.getCreateTime() == null || inviteInfo.getExpirationTime() == 0) {
             if (inviteInfo.getCreateTime() == null || inviteInfo.getExpirationTime() == 0) {

+ 487 - 15
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java

@@ -80,6 +80,10 @@ public class PlayServiceImpl implements IPlayService {
     @Autowired
     @Autowired
     private IMediaServerService mediaServerService;
     private IMediaServerService mediaServerService;
 
 
+    /** 观看代次墓碑:已取消的 stream 不得因“流未找到”被自动点播复活。 */
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
     @Autowired
     @Autowired
     private SipInviteSessionManager sessionManager;
     private SipInviteSessionManager sessionManager;
 
 
@@ -105,7 +109,12 @@ public class PlayServiceImpl implements IPlayService {
     @EventListener
     @EventListener
     public void onApplicationEvent(MediaDepartureEvent event) {
     public void onApplicationEvent(MediaDepartureEvent event) {
         if (!"rtp".equals(event.getApp())) return;
         if (!"rtp".equals(event.getApp())) return;
+        // The adapter owns adopted teardown; a departure hook must not enter channel-wide legacy stop.
+        SsrcTransaction departing = sessionManager.getSsrcTransactionByStream("rtp", event.getStream());
+        if (sessionManager.isAdopted(departing)) return;
         InviteInfo info = inviteStreamService.getInviteInfoByStream(null, event.getStream());
         InviteInfo info = inviteStreamService.getInviteInfoByStream(null, event.getStream());
+        if (info != null && info.getStream() != null && info.getStream().startsWith("managed_")
+                && (event.getMediaServer() == null || !java.util.Objects.equals(info.getMediaServerId(), event.getMediaServer().getId()))) return;
         if (info != null && info.getStatus() == InviteSessionStatus.ok
         if (info != null && info.getStatus() == InviteSessionStatus.ok
                 && info.getStreamInfo() != null && info.getSsrcInfo() != null) stop(info);
                 && info.getStreamInfo() != null && info.getSsrcInfo() != null) stop(info);
     }
     }
@@ -119,6 +128,12 @@ public class PlayServiceImpl implements IPlayService {
         if (!"rtp".equals(event.getApp())) {
         if (!"rtp".equals(event.getApp())) {
             return;
             return;
         }
         }
+        // The managed namespace is never a legacy device/channel identifier.
+        if (event.getStream() == null || event.getStream().startsWith("managed_")) return;
+        if (videoLifecycleStore != null && videoLifecycleStore.isStreamCancelled(event.getStream())) {
+            log.info("[ZLM HOOK] 该流已被取消,不自动点播:{}", event.getStream());
+            return;
+        }
         String[] s = event.getStream().split("_");
         String[] s = event.getStream().split("_");
         if ((s.length != 2 && s.length != 4)) {
         if ((s.length != 2 && s.length != 4)) {
             return;
             return;
@@ -156,6 +171,421 @@ public class PlayServiceImpl implements IPlayService {
     }
     }
 
 
 
 
+    @Autowired
+    private com.zksy.video.lifecycle.VideoStopReceipts stopReceipts;
+
+    /** Local callback ownership only; durable stop evidence lives in VideoStopReceipts. */
+    private final java.util.Map<String, ManagedPlay> managedPlays = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private static final class ManagedPlay {
+        private final MediaServer node;
+        private final Device device;
+        private final DeviceChannel channel;
+        private final String stream;
+        private SSRCInfo ssrc;
+        private boolean answered;
+        private ManagedPlay(MediaServer node, Device device, DeviceChannel channel, String stream) {
+            this.node = node; this.device = device; this.channel = channel; this.stream = stream;
+        }
+    }
+
+    private boolean managedCancelled(String stream) {
+        return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
+    }
+
+    @Override
+    public synchronized SSRCInfo playManaged(MediaServer node, String deviceId, String channelId, String stream,
+                                              ErrorCallback<StreamInfo> callback) {
+        if (node == null || node.getId() == null || !node.isRtpEnable() || stream == null
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || managedCancelled(stream) || stopReceipts == null) {
+            if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled or unsupported node/stream", null);
+            return null;
+        }
+        Device device = redisCatchStorage.getDevice(deviceId);
+        DeviceChannel channel = deviceChannelService.getOneForSource(deviceId, channelId);
+        if (device == null || channel == null) {
+            if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed device/channel missing", null);
+            return null;
+        }
+        // Never take over or stop a different stream, even when its media list is empty.
+        for (InviteInfo existing : inviteStreamService.getAllInviteInfo()) {
+            if (existing.getType() == InviteSessionType.PLAY && java.util.Objects.equals(channel.getId(), existing.getChannelId())
+                    && !stream.equals(existing.getStream())) {
+                if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Channel already belongs to another stream", null);
+                return null;
+            }
+        }
+        InviteInfo existing = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        if (existing != null) {
+            if (!node.getId().equals(existing.getMediaServerId()) || !deviceId.equals(existing.getDeviceId())) return null;
+            com.zksy.video.lifecycle.VideoStopReceipts.Snapshot receipt = stopReceipts.read(node.getId(), stream);
+            if (receipt == null || !receiptIdentity(receipt.plays.get(stream), device, channel)
+                    || receipt.plays.get(stream).cancelled || receipt.allocation == null
+                    || !receipt.allocation.matches(existing.getSsrcInfo())) return null;
+            ManagedPlay retained = managedPlays.get(stream);
+            if (retained == null) {
+                retained = new ManagedPlay(node, device, channel, stream); retained.ssrc = existing.getSsrcInfo();
+                managedPlays.put(stream, retained);
+            }
+            if (managedCancelled(stream)) return null;
+            if (existing.getStreamInfo() != null) {
+                if (callback != null) callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), existing.getStreamInfo());
+            } else if (callback != null) {
+                inviteStreamService.once(InviteSessionType.PLAY, channel.getId(), stream, callback);
+            }
+            return existing.getSsrcInfo();
+        }
+        // Same UUID is single-use even after a failure or a cache eviction.
+        if (managedPlays.containsKey(stream) || stopReceipts == null) return null;
+        if (stopReceipts.update(node.getId(), stream, snapshot -> {
+            if (!snapshot.plays.isEmpty() || snapshot.allocation != null) return null;
+            snapshot.plays.put(stream, playReceipt(device, channel)); return snapshot;
+        }) == null) return null;
+        ManagedPlay play = new ManagedPlay(node, device, channel, stream);
+        managedPlays.put(stream, play);
+        RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(node); param.setStreamId(stream);
+        param.setSsrcCheck(device.isSsrcCheck()); param.setDisableAudio(!channel.isHasAudio());
+        param.setTcpMode("TCP-ACTIVE".equalsIgnoreCase(device.getStreamMode()) ? 2 : "TCP-PASSIVE".equalsIgnoreCase(device.getStreamMode()) ? 1 : 0);
+        try {
+            if (managedCancelled(stream)) return null;
+            play.ssrc = receiveRtpServerService.openRTPServer(param, (code, msg, result) -> managedArrival(play, callback, code, msg, result));
+            if (play.ssrc == null || play.ssrc.getPort() <= 0 || managedCancelled(stream)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed allocation failed/cancelled");
+                return null;
+            }
+            InviteInfo invite = InviteInfo.getInviteInfo(deviceId, channel.getId(), stream, play.ssrc, node.getId(), node.getSdpIp(),
+                    play.ssrc.getPort(), device.getStreamMode(), InviteSessionType.PLAY, InviteSessionStatus.ready, userSetting.getRecordSip());
+            inviteStreamService.updateInviteInfo(invite);
+            if (managedCancelled(stream)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed generation cancelled");
+                return null;
+            }
+            // Persist BEFORE dispatch. Throw/timeout does not prove no INVITE left the process.
+            if (stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(stream);
+                if (receipt == null || receipt.cancelled || snapshot.allocation == null
+                        || !snapshot.allocation.matches(play.ssrc)) return null;
+                receipt.inviteSent = true; return snapshot;
+            }) == null) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed invite intent not retained");
+                return null;
+            }
+            cmder.playStreamCmd(node, play.ssrc, device, channel,
+                    event -> managedInviteOk(play, callback, event),
+                    event -> failManaged(play, callback, event.statusCode, event.msg), userSetting.getPlayTimeout().longValue());
+            return play.ssrc;
+        } catch (InvalidArgumentException | SipException | ParseException | RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(), ex.getMessage());
+            return null;
+        }
+    }
+
+    private synchronized void managedArrival(ManagedPlay play, ErrorCallback<StreamInfo> callback,
+                                             int code, String msg, OpenRTPServerResult result) {
+        if (result != null && result.getSsrcInfo() != null
+                && play.stream.equals(result.getSsrcInfo().getStream()) && "rtp".equals(result.getSsrcInfo().getApp())) {
+            play.ssrc = result.getSsrcInfo();
+        }
+        if (managedCancelled(play.stream) || code != InviteErrorCode.SUCCESS.getCode()) {
+            failManaged(play, callback, code == InviteErrorCode.SUCCESS.getCode() ? InviteErrorCode.FAIL.getCode() : code, msg);
+            return;
+        }
+        if (result == null || result.getHookData() == null || result.getHookData().getMediaServer() == null
+                || !play.node.getId().equals(result.getHookData().getMediaServer().getId())
+                || !play.stream.equals(result.getHookData().getStream())
+                || result.getHookData().getMediaInfo() == null
+                || !play.stream.equals(result.getHookData().getMediaInfo().getStream())
+                || !"rtp".equals(result.getHookData().getMediaInfo().getApp())) return;
+        StreamInfo info = onPublishHandlerForPlay(play.node, result.getHookData().getMediaInfo(), play.device, play.channel);
+        if (info == null || managedCancelled(play.stream)) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed arrival no longer owned");
+            return;
+        }
+        if (!play.answered) {
+            play.answered = true;
+            try { if (callback != null) callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), info); }
+            finally { inviteStreamService.call(InviteSessionType.PLAY, play.channel.getId(), play.stream,
+                    InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), info); }
+        }
+    }
+
+    private synchronized void managedInviteOk(ManagedPlay play, ErrorCallback<StreamInfo> callback, SipSubscribe.EventResult event) {
+        // Save the exact response dialog before cancellation can initiate BYE/delete its live registry entry.
+        SsrcTransaction expected = sessionManager.getSsrcTransactionByStream("rtp", play.stream);
+        try {
+            if (expected == null || !play.stream.equals(expected.getStream()) || !stopReceipts.retainDialog(expected)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Original managed dialog could not be retained");
+                return;
+            }
+        } catch (RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Original managed dialog receipt unavailable");
+            return;
+        }
+        // SIPCommander has retained the exact late dialog for ACK/BYE, but never republishes it.
+        if (managedCancelled(play.stream)) {
+            stopManaged(play.node, play.device, play.channel, play.stream);
+            return;
+        }
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, play.channel.getId(), play.stream);
+        if (invite == null || !play.node.getId().equals(invite.getMediaServerId())) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed invite no longer owned");
+            return;
+        }
+        try {
+            ResponseEvent response = (ResponseEvent) event.event;
+            String sdp = new String(response.getResponse().getRawContent(), java.nio.charset.StandardCharsets.UTF_8);
+            String responseSsrc = SipUtils.getSsrcFromSdp(sdp);
+            if (responseSsrc != null && !responseSsrc.equals(play.ssrc.getSsrc()) && play.device.isSsrcCheck()) {
+                if (!Boolean.TRUE.equals(mediaServerService.updateRtpServerSSRC(play.node, play.stream, responseSsrc))) {
+                    failManaged(play, callback, InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(), "Managed SSRC update failed");
+                    return;
+                }
+            }
+            if (managedCancelled(play.stream)) { stopManaged(play.node, play.device, play.channel, play.stream); return; }
+            if ("TCP-ACTIVE".equalsIgnoreCase(play.device.getStreamMode())) {
+                String body = sdp.contains("y=") ? sdp.substring(0, sdp.indexOf("y=")) : sdp;
+                SessionDescription description = SdpFactory.getInstance().createSessionDescription(body);
+                int port = -1;
+                for (Object value : description.getMediaDescriptions(true)) {
+                    Media media = ((MediaDescription)value).getMedia();
+                    if (media.getMediaFormats(false).contains("96")) { port = media.getMediaPort(); break; }
+                }
+                if (port <= 0 || !Boolean.TRUE.equals(mediaServerService.connectRtpServer(play.node, description.getConnection().getAddress(), port, play.stream))) {
+                    failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed TCP connect failed"); return;
+                }
+            }
+            if (managedCancelled(play.stream)) { stopManaged(play.node, play.device, play.channel, play.stream); return; }
+            // Arrival, not SIP 200, publishes StreamInfo. Only this precise Invite can be updated.
+            invite.setStatus(InviteSessionStatus.ok); inviteStreamService.updateInviteInfo(invite);
+        } catch (SdpException | RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(), ex.getMessage());
+        }
+    }
+
+    private synchronized void failManaged(ManagedPlay play, ErrorCallback<StreamInfo> callback, int code, String msg) {
+        try { stopManaged(play.node, play.device, play.channel, play.stream); }
+        finally {
+            if (!play.answered) {
+                play.answered = true;
+                try { if (callback != null) callback.run(code, msg, null); }
+                finally { inviteStreamService.call(InviteSessionType.PLAY, play.channel.getId(), play.stream, code, msg, null); }
+            }
+        }
+    }
+
+    private com.zksy.video.lifecycle.VideoStopReceipts.Play playReceipt(Device device, DeviceChannel channel) {
+        com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = new com.zksy.video.lifecycle.VideoStopReceipts.Play();
+        receipt.deviceId = device.getDeviceId(); receipt.channelId = channel.getId(); receipt.channelCode = channel.getDeviceId();
+        return receipt;
+    }
+
+    private boolean receiptIdentity(com.zksy.video.lifecycle.VideoStopReceipts.Play receipt, Device device, DeviceChannel channel) {
+        return receipt != null && device != null && channel != null
+                && java.util.Objects.equals(receipt.deviceId, device.getDeviceId())
+                && java.util.Objects.equals(receipt.channelId, channel.getId())
+                && java.util.Objects.equals(receipt.channelCode, channel.getDeviceId());
+    }
+
+    @Override
+    public synchronized boolean stopManaged(MediaServer node, Device device, DeviceChannel channel, String stream) {
+        if (node == null || node.getId() == null || device == null || channel == null || stream == null
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || stopReceipts == null || videoLifecycleStore == null) return false;
+        try {
+            com.zksy.video.lifecycle.VideoStopReceipts.Snapshot retained = stopReceipts.read(node.getId(), stream);
+            if (retained == null || !receiptIdentity(retained.plays.get(stream), device, channel)) return false;
+            InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if (invite != null && (!node.getId().equals(invite.getMediaServerId())
+                    || !device.getDeviceId().equals(invite.getDeviceId()) || retained.allocation == null
+                    || !retained.allocation.matches(invite.getSsrcInfo()))) return false;
+            if (current != null && (!node.getId().equals(current.getMediaServerId())
+                    || !"rtp".equals(current.getApp()) || !stream.equals(current.getStream())
+                    || !device.getDeviceId().equals(current.getDeviceId()) || !java.util.Objects.equals(channel.getId(), current.getChannelId())
+                    || retained.allocation == null || !java.util.Objects.equals(retained.allocation.ssrc, current.getSsrc()))) return false;
+            retained = stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(stream);
+                if (!receiptIdentity(receipt, device, channel)
+                        || (receipt.dialog != null && current != null && !SipInviteSessionManager.sameDialog(receipt.dialog, current))) return null;
+                receipt.cancelled = true;
+                if (receipt.dialog == null && current != null) receipt.dialog = current;
+                if (receipt.dialog != null) receipt.inviteSent = true;
+                return snapshot;
+            });
+            if (retained == null) return false;
+            videoLifecycleStore.markStreamCancelled(stream);
+            try { inviteStreamService.call(InviteSessionType.PLAY, channel.getId(), stream,
+                    InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", null); }
+            catch (RuntimeException ex) { log.warn("[Managed callback close] {}: {}", stream, ex.getMessage()); }
+            com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = retained.plays.get(stream);
+            SsrcTransaction expected = receipt.dialog;
+            boolean rtpClosed;
+            try {
+                // The persisted original dialog still lets a restart/offline cleanup send the exact
+                // BYE after the live index was removed; a different replacement is rejected earlier.
+                if (expected != null && !sessionManager.isSipTerminated(expected)) {
+                    // Only durable outgoing confirmation or a matched real peer BYE is protocol evidence.
+                    cmder.streamByeCmd(device, channel.getDeviceId(), expected.getSipTransactionInfo(), event -> { });
+                }
+            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+                log.warn("[Managed BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            } finally {
+                // Cancellation must fence the pool acquisition as well as RTP creation. Its
+                // single-use token is the managed stream even if the pool reply was lost.
+                rtpClosed = false;
+                if (retained.allocation == null && !receipt.inviteSent)
+                    rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, new SSRCInfo(0, null, "rtp", stream, stream));
+                if (retained.allocation != null) rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, retained.allocation.info(stream));
+            }
+            // A definitive INVITE refusal establishes that no dialog exists for this attempt.
+            // Timeouts, lost replies, 401/407 and unknown states stay pending.
+            String allocationToken = retained.allocation == null ? stream : retained.allocation.token;
+            boolean refused = !receipt.inviteSent
+                    || sessionManager.isInviteRejected(node.getId(), "rtp", stream, allocationToken);
+            if (!rtpClosed || (!refused && receipt.inviteSent && (expected == null || !sessionManager.isSipTerminated(expected)))) return false;
+            SsrcTransaction now = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if (now != null && !SipInviteSessionManager.sameDialog(expected, now)) return false;
+            // Delete by the original Invite snapshot, not by name: a same-name replacement may
+            // have appeared between the check above and this removal.
+            InviteInfo closing = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            if (closing != null && !inviteStreamService.removeInviteInfoIfSame(closing)) return false;
+            return true;
+        } catch (RuntimeException ex) {
+            log.warn("[Managed receipt] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            return false;
+        }
+    }
+
+    /** Adoption is a persisted capability for one observed dialog, never a reusable stream name. */
+
+    private static final class AdoptedPlay {
+        private final SsrcTransaction dialog;
+        private final SSRCInfo info;
+        private final String channelCode;
+        private boolean cancelled;
+        private AdoptedPlay(SsrcTransaction current, SSRCInfo ssrc, String channelCode) {
+            this.channelCode = channelCode;
+            info = new SSRCInfo(ssrc.getPort(), ssrc.getSsrc(), ssrc.getApp(), ssrc.getStream(), ssrc.getTimeOutTaskKey());
+            dialog = new SsrcTransaction();
+            dialog.setApp(current.getApp()); dialog.setStream(current.getStream()); dialog.setCallId(current.getCallId());
+            dialog.setSsrc(current.getSsrc()); dialog.setMediaServerId(current.getMediaServerId());
+            dialog.setDeviceId(current.getDeviceId()); dialog.setChannelId(current.getChannelId()); dialog.setType(current.getType());
+            SipTransactionInfo sip = new SipTransactionInfo(), source = current.getSipTransactionInfo();
+            sip.setCallId(source.getCallId()); sip.setFromTag(source.getFromTag()); sip.setToTag(source.getToTag());
+            sip.setViaBranch(source.getViaBranch()); sip.setAsSender(source.isAsSender()); dialog.setSipTransactionInfo(sip);
+        }
+    }
+
+    private AdoptedPlay restoredAdoption(MediaServer node, String stream, String handle) {
+        if (node == null || node.getId() == null || stream == null || handle == null || stopReceipts == null) return null;
+        com.zksy.video.lifecycle.VideoStopReceipts.Snapshot snapshot = stopReceipts.read(node.getId(), stream);
+        com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot == null ? null : snapshot.plays.get(handle);
+        if (receipt == null || receipt.dialog == null || receipt.allocation == null) return null;
+        AdoptedPlay restored = new AdoptedPlay(receipt.dialog, receipt.allocation.info(stream), receipt.channelCode);
+        restored.cancelled = receipt.cancelled; return restored;
+    }
+
+    private static boolean nonblank(String value) { return value != null && !value.isBlank(); }
+
+    private boolean adoptedIdentity(AdoptedPlay owned, MediaServer node, Device device, DeviceChannel channel, String stream) {
+        return owned != null && node != null && device != null && channel != null
+                && java.util.Objects.equals(owned.dialog.getMediaServerId(), node.getId())
+                && java.util.Objects.equals(owned.dialog.getDeviceId(), device.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getChannelId(), channel.getId())
+                && java.util.Objects.equals(owned.channelCode, channel.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getStream(), stream);
+    }
+
+    private boolean adoptedInvite(AdoptedPlay owned, InviteInfo invite) {
+        return invite != null && invite.getSsrcInfo() != null && invite.getType() == InviteSessionType.PLAY
+                && java.util.Objects.equals(owned.dialog.getMediaServerId(), invite.getMediaServerId())
+                && java.util.Objects.equals(owned.dialog.getDeviceId(), invite.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getChannelId(), invite.getChannelId())
+                && java.util.Objects.equals(owned.dialog.getStream(), invite.getStream())
+                && owned.info.equals(invite.getSsrcInfo());
+    }
+
+    @Override
+    public synchronized String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
+        if (node == null || !nonblank(node.getId()) || !node.isRtpEnable() || device == null || channel == null
+                || !nonblank(stream) || stream.startsWith("managed_") || stopReceipts == null) return null;
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+        if (handle != null) {
+            AdoptedPlay owned = restoredAdoption(node, stream, handle);
+            return adoptedIdentity(owned, node, device, channel, stream) && !owned.cancelled
+                    && adoptedInvite(owned, invite) && SipInviteSessionManager.sameDialog(owned.dialog, current)
+                    ? handle : null;
+        }
+        if (invite == null || invite.getSsrcInfo() == null || current == null || current.getType() != InviteSessionType.PLAY
+                || !nonblank(current.getCallId()) || !nonblank(current.getSsrc()) || !"rtp".equals(current.getApp())
+                || current.getSipTransactionInfo() == null
+                || !current.getCallId().equals(current.getSipTransactionInfo().getCallId())
+                || !nonblank(current.getSipTransactionInfo().getFromTag()) || !nonblank(current.getSipTransactionInfo().getToTag())
+                || !nonblank(invite.getSsrcInfo().getTimeOutTaskKey())
+                || !"rtp".equals(invite.getSsrcInfo().getApp()) || !stream.equals(invite.getSsrcInfo().getStream())
+                || !current.getSsrc().equals(invite.getSsrcInfo().getSsrc())) return null;
+        AdoptedPlay owned = new AdoptedPlay(current, invite.getSsrcInfo(), channel.getDeviceId());
+        if (!adoptedIdentity(owned, node, device, channel, stream) || !adoptedInvite(owned, invite)
+                || !sessionManager.retainAdopted(owned.dialog, owned.info)) return null;
+        String token = java.util.UUID.randomUUID().toString();
+        return stopReceipts.update(node.getId(), stream, snapshot -> {
+            com.zksy.video.lifecycle.VideoStopReceipts.Allocation allocation = snapshot.allocation;
+            if (allocation == null) {
+                // Migration/adoption is backed by the already validated Invite and SIP dialog, not absence.
+                allocation = new com.zksy.video.lifecycle.VideoStopReceipts.Allocation();
+                allocation.token = owned.info.getTimeOutTaskKey(); allocation.ssrc = owned.info.getSsrc();
+                allocation.port = owned.info.getPort(); allocation.state = com.zksy.video.lifecycle.VideoStopReceipts.RtpState.OPEN;
+                snapshot.allocation = allocation;
+            }
+            if (!allocation.matches(owned.info) || allocation.state != com.zksy.video.lifecycle.VideoStopReceipts.RtpState.OPEN
+                    || (allocation.callId != null && !allocation.callId.equals(owned.dialog.getCallId()))) return null;
+            if (snapshot.plays.values().stream().anyMatch(play -> java.util.Objects.equals(play.allocationToken, owned.info.getTimeOutTaskKey())
+                    && (play.cancelled || (play.dialog != null && !SipInviteSessionManager.sameDialog(play.dialog, owned.dialog))))) return null;
+            allocation.callId = owned.dialog.getCallId();
+            com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = playReceipt(device, channel);
+            receipt.allocationToken = allocation.token; receipt.allocation = allocation;
+            receipt.dialog = owned.dialog; receipt.inviteSent = true;
+            snapshot.plays.put(token, receipt); return snapshot;
+        }) == null ? null : token;
+    }
+
+    @Override
+    public synchronized boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
+        try {
+            AdoptedPlay owned = restoredAdoption(node, stream, handle);
+            if (!adoptedIdentity(owned, node, device, channel, stream)) return false;
+            InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            if ((invite != null && !adoptedInvite(owned, invite))
+                    || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))) return false;
+            if (stopReceipts.update(node.getId(), stream, snapshot -> {
+                com.zksy.video.lifecycle.VideoStopReceipts.Play receipt = snapshot.plays.get(handle);
+                if (receipt == null || snapshot.allocation == null || !snapshot.allocation.matches(owned.info)) return null;
+                receipt.cancelled = true; return snapshot;
+            }) == null) return false;
+            try {
+                if (!sessionManager.isSipTerminated(owned.dialog)) {
+                    // Explicit original dialog only; a peer termination is not an outgoing BYE confirmation.
+                    // It stays usable after offline removed the live session index.
+                    cmder.streamByeCmd(device, owned.channelCode, owned.dialog.getSipTransactionInfo(), event -> { });
+                }
+            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+                log.warn("[Adopted BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            }
+            boolean closed = receiveRtpServerService.closeAdoptedRTPServer(node, owned.info, owned.dialog.getCallId());
+            current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+            invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            if (!closed || !sessionManager.isSipTerminated(owned.dialog)
+                    || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
+                    || (invite != null && !adoptedInvite(owned, invite))) return false;
+            if (invite != null && !inviteStreamService.removeInviteInfoIfSame(invite)) return false;
+            return true;
+        } catch (RuntimeException ex) {
+            log.warn("[Adopted receipt] {}/{} remains pending: {}", node == null ? null : node.getId(), stream, ex.getMessage());
+            return false;
+        }
+    }
+
     @Override
     @Override
     public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback) {
     public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback) {
         if (mediaServerItem == null) {
         if (mediaServerItem == null) {
@@ -397,7 +827,23 @@ public class PlayServiceImpl implements IPlayService {
         }
         }
     }
     }
 
 
-    public StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel) {
+    public synchronized StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel) {
+        if (mediaInfo != null && mediaInfo.getStream() != null && mediaInfo.getStream().startsWith("managed_")) {
+            String stream = mediaInfo.getStream();
+            if (managedCancelled(stream) || mediaServerItem == null || !"rtp".equals(mediaInfo.getApp())
+                    || (mediaInfo.getMediaServer() != null && !java.util.Objects.equals(mediaServerItem.getId(), mediaInfo.getMediaServer().getId()))) return null;
+            InviteInfo exact = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            if (exact == null || !java.util.Objects.equals(exact.getMediaServerId(), mediaServerItem.getId())
+                    || !java.util.Objects.equals(exact.getDeviceId(), device.getDeviceId())) return null;
+            StreamInfo info = mediaServerService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", stream, mediaInfo, null);
+            if (info == null || !stream.equals(info.getStream()) || info.getMediaServer() == null
+                    || !mediaServerItem.getId().equals(info.getMediaServer().getId()) || managedCancelled(stream)) return null;
+            info.setDeviceId(device.getDeviceId()); info.setChannelId(channel.getId());
+            exact.setStatus(InviteSessionStatus.ok); exact.setStreamInfo(info);
+            inviteStreamService.updateInviteInfo(exact);
+            // Deliberately no channel-wide startPlay/stopPlay: the managed stream owns only its exact Invite.
+            return managedCancelled(stream) ? null : info;
+        }
         StreamInfo streamInfo = null;
         StreamInfo streamInfo = null;
         streamInfo = onPublishHandler(mediaServerItem, mediaInfo, device, channel);
         streamInfo = onPublishHandler(mediaServerItem, mediaInfo, device, channel);
         if (streamInfo != null) {
         if (streamInfo != null) {
@@ -627,6 +1073,16 @@ public class PlayServiceImpl implements IPlayService {
                                 "下级自定义了ssrc,重新设置收流信息失败", null);
                                 "下级自定义了ssrc,重新设置收流信息失败", null);
 
 
                     }else {
                     }else {
+                        // The legacy path changes only the device-facing SSRC. Its pool number must be
+                        // returned through the token-aware Factory: an unowned release is refused.
+                        if (stopReceipts != null) {
+                            try {
+                                String poolSsrc = ssrcInfo.getSsrc(), token = ssrcInfo.getTimeOutTaskKey();
+                                stopReceipts.recordNegotiatedSsrc(mediaServerItem.getId(), ssrcInfo.getStream(),
+                                        ssrcInfo, ssrcInResponse,
+                                        () -> ssrcFactory.releaseSsrc(mediaServerItem.getId(), poolSsrc, token));
+                            } catch (RuntimeException ex) { log.warn("[Invite 200OK] 协商 SSRC 保存失败: {}", ex.getMessage()); }
+                        }
                         ssrcInfo.setSsrc(ssrcInResponse);
                         ssrcInfo.setSsrc(ssrcInResponse);
                         inviteInfo.setSsrcInfo(ssrcInfo);
                         inviteInfo.setSsrcInfo(ssrcInfo);
                         inviteInfo.setStream(ssrcInfo.getStream());
                         inviteInfo.setStream(ssrcInfo.getStream());
@@ -967,6 +1423,13 @@ public class PlayServiceImpl implements IPlayService {
 
 
     @Override
     @Override
     public void stop(InviteSessionType type, Device device, DeviceChannel channel, String stream) {
     public void stop(InviteSessionType type, Device device, DeviceChannel channel, String stream) {
+        if (stream != null && stream.startsWith("managed_")) {
+            InviteInfo exact = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
+            ManagedPlay retained = managedPlays.get(stream);
+            MediaServer node = retained != null ? retained.node : exact == null ? null : mediaServerService.getOne(exact.getMediaServerId());
+            stopManaged(node, device, channel, stream);
+            return;
+        }
         InviteInfo inviteInfo = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
         InviteInfo inviteInfo = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
         if (inviteInfo == null) {
         if (inviteInfo == null) {
             if (type == InviteSessionType.PLAY) {
             if (type == InviteSessionType.PLAY) {
@@ -975,21 +1438,26 @@ public class PlayServiceImpl implements IPlayService {
             return;
             return;
         }
         }
         inviteStreamService.removeInviteInfo(inviteInfo);
         inviteStreamService.removeInviteInfo(inviteInfo);
-        if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
-            try {
-                log.info("[停止点播/回放/下载] {}/{}", device.getDeviceId(), channel.getDeviceId());
-                cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", inviteInfo.getStream(), null, null);
-            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
-                log.error("[命令发送失败] 停止点播/回放/下载, 发送BYE: {}", e.getMessage());
-                throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
+        try {
+            if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
+                try {
+                    log.info("[停止点播/回放/下载] {}/{}", device.getDeviceId(), channel.getDeviceId());
+                    cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", inviteInfo.getStream(), null, null);
+                } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
+                    log.error("[命令发送失败] 停止点播/回放/下载, 发送BYE: {}", e.getMessage());
+                    throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
+                }
+            }
+        } finally {
+            // BYE 失败也必须在本地结束本代接收资源,否则 RTP/SSRC/订阅会泄漏到下一代。
+            if (inviteInfo.getType() == InviteSessionType.PLAY) {
+                deviceChannelService.stopPlay(channel.getId());
+            }
+            MediaServer rtpServer = inviteInfo.getStreamInfo() != null ? inviteInfo.getStreamInfo().getMediaServer()
+                    : inviteInfo.getMediaServerId() == null ? null : mediaServerService.getOne(inviteInfo.getMediaServerId());
+            if (rtpServer != null && inviteInfo.getSsrcInfo() != null) {
+                receiveRtpServerService.closeRTPServer(rtpServer, inviteInfo.getSsrcInfo());
             }
             }
-        }
-
-        if (inviteInfo.getType() == InviteSessionType.PLAY) {
-            deviceChannelService.stopPlay(channel.getId());
-        }
-        if (inviteInfo.getStreamInfo() != null) {
-            receiveRtpServerService.closeRTPServer(inviteInfo.getStreamInfo().getMediaServer(), inviteInfo.getSsrcInfo());
         }
         }
     }
     }
 
 
@@ -1006,6 +1474,10 @@ public class PlayServiceImpl implements IPlayService {
             log.warn("[停止点播] 发现设备不存在");
             log.warn("[停止点播] 发现设备不存在");
             return;
             return;
         }
         }
+        if (inviteInfo.getStream() != null && inviteInfo.getStream().startsWith("managed_")) {
+            stopManaged(mediaServerService.getOne(inviteInfo.getMediaServerId()), device, channel, inviteInfo.getStream());
+            return;
+        }
         inviteStreamService.removeInviteInfo(inviteInfo);
         inviteStreamService.removeInviteInfo(inviteInfo);
         if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
         if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
             try {
             try {

+ 25 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/PendingSipInvite.java

@@ -0,0 +1,25 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import lombok.Data;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+
+/** Minimal pre-send snapshot. IDs identify the original source, never inferred from a response or SDP. */
+@Data
+public class PendingSipInvite {
+    private SipRequestBinding binding;
+    private String nodeId;
+    private String deviceId;
+    private Integer channelId;
+    private String channelSipId;
+    private String app;
+    private String stream;
+    private String ssrc;
+    private int port;
+    private String timeoutToken;
+    private String localIp;
+    private long deadlineMillis;
+
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    public boolean isExpired() { return deadlineMillis <= System.currentTimeMillis(); }
+    public SSRCInfo allocation() { return new SSRCInfo(port, ssrc, app, stream, timeoutToken); }
+}

+ 132 - 9
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SSRCFactory.java

@@ -4,9 +4,11 @@ import com.ruoyi.wvp.conf.SipConfig;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.conf.UserSetting;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
 import java.util.ArrayList;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.List;
 import java.util.Set;
 import java.util.Set;
 
 
@@ -26,6 +28,50 @@ public class SSRCFactory {
      */
      */
     private static final String SSRC_INFO_KEY = "CITY_VIDEO_VMP_SSRC_INFO_";
     private static final String SSRC_INFO_KEY = "CITY_VIDEO_VMP_SSRC_INFO_";
 
 
+    private static final DefaultRedisScript<String> ALLOCATE_OWNED = new DefaultRedisScript<>(
+            "local known = redis.call('HGET', KEYS[2], ARGV[2])\n"
+            + "if known and redis.call('HGET', KEYS[2], known) ~= ARGV[1] then return nil end\n"
+            + "if known then return known end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[3]) == 1 then return nil end\n"
+            + "local sn = redis.call('SPOP', KEYS[1])\n"
+            + "if not sn then return nil end\n"
+            + "redis.call('HSET', KEYS[2], sn, ARGV[1])\n"
+            + "redis.call('HSET', KEYS[2], ARGV[2], sn)\n"
+            + "return sn", String.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_OWNED = new DefaultRedisScript<>(
+            "if redis.call('HGET', KEYS[2], ARGV[1]) ~= ARGV[2] then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[3], ARGV[1])\n"
+            + "redis.call('HDEL', KEYS[2], ARGV[1], ARGV[4])\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
+    private static final DefaultRedisScript<Long> CANCEL_OWNED = new DefaultRedisScript<>(
+            "if redis.call('HEXISTS', KEYS[2], ARGV[3]) == 1 then return 1 end\n"
+            + "local sn = redis.call('HGET', KEYS[2], ARGV[2])\n"
+            + "if not sn then return redis.call('HSET', KEYS[2], ARGV[3], ARGV[4]) end\n"
+            + "if redis.call('HGET', KEYS[2], sn) ~= ARGV[1] then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[3], sn)\n"
+            + "redis.call('HDEL', KEYS[2], sn, ARGV[2])\n"
+            + "redis.call('SADD', KEYS[1], sn)\nreturn 1", Long.class);
+
+    private static final DefaultRedisScript<String> ALLOCATE_UNOWNED = new DefaultRedisScript<>(
+            "local sn = redis.call('SPOP', KEYS[1])\n"
+            + "if not sn then return nil end\n"
+            + "redis.call('HSET', KEYS[2], sn, ARGV[1])\n"
+            + "return sn", String.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_UNOWNED = new DefaultRedisScript<>(
+            "local owner = redis.call('HGET', KEYS[2], ARGV[1])\n"
+            + "if owner == ARGV[2] then redis.call('HDEL', KEYS[2], ARGV[1]) end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 0 end\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
+    private static final DefaultRedisScript<Long> RELEASE_OBSERVED_LEGACY = new DefaultRedisScript<>(
+            "if redis.call('HEXISTS', KEYS[2], ARGV[2]) == 1 then return 0 end\n"
+            + "if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 1 then return 0 end\n"
+            + "redis.call('HSET', KEYS[2], ARGV[2], ARGV[1])\n"
+            + "return redis.call('SADD', KEYS[1], ARGV[1])", Long.class);
+
     @Autowired
     @Autowired
     private StringRedisTemplate redisTemplate;
     private StringRedisTemplate redisTemplate;
 
 
@@ -65,6 +111,14 @@ public class SSRCFactory {
         return "0" + getSN(mediaServerId);
         return "0" + getSN(mediaServerId);
     }
     }
 
 
+    /**
+     * Allocate with a unique, non-empty token for this allocation attempt (never reuse the token).
+     * Persist nodeId, SSRC and token together so another Factory can release after a proven stop.
+     */
+    public String getPlaySsrc(String nodeId, String allocationToken) {
+        return "0" + getOwnedSN(nodeId, allocationToken);
+    }
+
     /**
     /**
      * 获取录像回放的SSRC值,第一位固定为1
      * 获取录像回放的SSRC值,第一位固定为1
      */
      */
@@ -72,6 +126,11 @@ public class SSRCFactory {
         return "1" + getSN(mediaServerId);
         return "1" + getSN(mediaServerId);
     }
     }
 
 
+    /** Playback uses the same node pool and allocation ownership as live play; only the prefix differs. */
+    public String getPlayBackSsrc(String nodeId, String allocationToken) {
+        return "1" + getOwnedSN(nodeId, allocationToken);
+    }
+
     /**
     /**
      * 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
      * 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
      *
      *
@@ -82,22 +141,85 @@ public class SSRCFactory {
             return;
             return;
         }
         }
         String sn = ssrc.substring(1);
         String sn = ssrc.substring(1);
-        String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        redisTemplate.opsForSet().add(redisKey, sn);
+        // An unowned legacy callback has no authority over a currently tracked allocation.
+        redisTemplate.execute(RELEASE_UNOWNED, allocationKeys(mediaServerId), sn, "__legacy__");
+    }
+
+    /**
+     * Return only this allocation's SN. The owner comparison, deletion and pool insertion execute
+     * in one Redis script; no process-local release flag is required. False means no SN was added
+     * (wrong/stale token or already released), not evidence that media has stopped.
+     */
+    public boolean releaseSsrc(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        if (ssrc == null || ssrc.length() < 2) {
+            return false;
+        }
+        return Long.valueOf(1).equals(redisTemplate.execute(RELEASE_OWNED, allocationKeys(nodeId),
+                ssrc.substring(1), allocationToken, "released:" + allocationToken, "allocated:" + allocationToken));
+    }
+
+    /** Cancels the pool acquisition itself, including a lost SPOP reply. A later allocation
+     * with this token cannot occur even if cancellation reached Redis before the allocation. */
+    public boolean cancelAllocation(String nodeId, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        return Long.valueOf(1).equals(redisTemplate.execute(CANCEL_OWNED, allocationKeys(nodeId), allocationToken,
+                "allocated:" + allocationToken, "released:" + allocationToken, "cancelled-before-allocation"));
+    }
+
+    /** Positive durable return receipt; checking it never inserts a number back into the pool. */
+    public boolean wasReleased(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        return ssrc != null && ssrc.length() > 1 && ssrc.substring(1).equals(
+                redisTemplate.opsForHash().get(allocationKeys(nodeId).get(1), "released:" + allocationToken));
+    }
+
+    /** Only for a pre-upgrade, untracked allocation whose exact close was observed. A newer
+     * tracked OR legacy owner blocks the return. The once-only receipt is atomic with SADD. */
+    public boolean releaseObservedLegacySsrc(String nodeId, String ssrc, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        if (ssrc == null || ssrc.length() < 2) return false;
+        return Long.valueOf(1).equals(redisTemplate.execute(RELEASE_OBSERVED_LEGACY, allocationKeys(nodeId),
+                ssrc.substring(1), "released:" + allocationToken));
+    }
+
+    private String getOwnedSN(String nodeId, String allocationToken) {
+        requireAllocationToken(allocationToken);
+        String sn = redisTemplate.execute(ALLOCATE_OWNED, allocationKeys(nodeId), allocationToken,
+                "allocated:" + allocationToken, "released:" + allocationToken);
+        if (sn == null) {
+            throw new RuntimeException("ssrc已经用完");
+        }
+        return sn;
+    }
+
+    /**
+     * Preserve the existing serverId/node pool and store SN -> token in its companion owner hash.
+     * No TTL: allocations must survive process restart. The hash tag uses the unchanged pool key
+     * (normal identifiers contain no braces); live Redis / Redis Cluster behavior is not verified
+     * by the offline command-boundary tests.
+     */
+    private List<String> allocationKeys(String nodeId) {
+        String poolKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + nodeId;
+        return Arrays.asList(poolKey, "{" + poolKey + "}_OWNERS");
+    }
+
+    private static void requireAllocationToken(String allocationToken) {
+        if (allocationToken == null || allocationToken.trim().isEmpty() || "__legacy__".equals(allocationToken)) {
+            throw new IllegalArgumentException("allocationToken不能为空");
+        }
     }
     }
 
 
     /**
     /**
      * 获取后四位数SN,随机数
      * 获取后四位数SN,随机数
      */
      */
     private String getSN(String mediaServerId) {
     private String getSN(String mediaServerId) {
-        String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        Long size = redisTemplate.opsForSet().size(redisKey);
-        if (size == null || size == 0) {
+        // Clear any prior owner while popping, including after an explicit legacy pool reset.
+        String sn = redisTemplate.execute(ALLOCATE_UNOWNED, allocationKeys(mediaServerId), "__legacy__");
+        if (sn == null) {
             throw new RuntimeException("ssrc已经用完");
             throw new RuntimeException("ssrc已经用完");
-        } else {
-            // 在集合中移除并返回一个随机成员。
-            return redisTemplate.opsForSet().pop(redisKey);
         }
         }
+        return sn;
     }
     }
 
 
     /**
     /**
@@ -116,7 +238,8 @@ public class SSRCFactory {
      */
      */
     public boolean hasMediaServerSSRC(String mediaServerId) {
     public boolean hasMediaServerSSRC(String mediaServerId) {
         String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
         String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
-        return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
+        return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))
+                || Boolean.TRUE.equals(redisTemplate.hasKey(allocationKeys(mediaServerId).get(1)));
     }
     }
 
 
 }
 }

+ 342 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java

@@ -25,7 +25,7 @@ public class SipInviteSessionManager {
 	/**
 	/**
 	 * 添加一个点播/回放的事务信息
 	 * 添加一个点播/回放的事务信息
 	 */
 	 */
-	public void put(SsrcTransaction ssrcTransaction){
+	public synchronized void put(SsrcTransaction ssrcTransaction){
 		redisTemplate.opsForHash().put(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId()
 		redisTemplate.opsForHash().put(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId()
 				, ssrcTransaction.getApp() + ssrcTransaction.getStream(), ssrcTransaction);
 				, ssrcTransaction.getApp() + ssrcTransaction.getStream(), ssrcTransaction);
 
 
@@ -67,6 +67,347 @@ public class SipInviteSessionManager {
 		}
 		}
 	}
 	}
 
 
+    /** Persist a minimal independent snapshot; no Device/MediaServer credentials are retained. */
+    public boolean retainAdopted(SsrcTransaction owned, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (owned == null || info == null) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)
+                || !java.util.Objects.equals(owned.getApp(), info.getApp())
+                || !java.util.Objects.equals(owned.getStream(), info.getStream())
+                || !java.util.Objects.equals(owned.getSsrc(), info.getSsrc())) return false;
+        String key = recoveryKey("adoption");
+        String field = dialogIdentity(owned);
+        Object previous = redisTemplate.opsForHash().get(key, field);
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("dialog", owned); snapshot.put("port", info.getPort());
+        snapshot.put("timeoutToken", info.getTimeOutTaskKey());
+        String update = snapshot.toJSONString();
+        if (previous != null && !previous.equals(update)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, field, previous, update));
+    }
+
+    public boolean isAdopted(SsrcTransaction owned) {
+        com.alibaba.fastjson2.JSONObject snapshot = adoption(owned);
+        return snapshot != null && sameDialog(owned, snapshot.getObject("dialog", SsrcTransaction.class));
+    }
+
+    public com.ruoyi.wvp.service.bean.SSRCInfo getAdoptedAllocation(SsrcTransaction owned) {
+        com.alibaba.fastjson2.JSONObject snapshot = adoption(owned);
+        if (snapshot == null || !sameDialog(owned, snapshot.getObject("dialog", SsrcTransaction.class))) return null;
+        return new com.ruoyi.wvp.service.bean.SSRCInfo(snapshot.getIntValue("port"), owned.getSsrc(), owned.getApp(),
+                owned.getStream(), snapshot.getString("timeoutToken"));
+    }
+
+    public boolean isAdoptedRtp(String nodeId, String callId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (info == null || callId == null) return false;
+        for (Object value : redisTemplate.opsForHash().values(recoveryKey("adoption"))) {
+            com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) value);
+            SsrcTransaction owned = snapshot.getObject("dialog", SsrcTransaction.class);
+            if (java.util.Objects.equals(nodeId, owned.getMediaServerId()) && java.util.Objects.equals(callId, owned.getCallId())
+                    && info.equals(allocation(snapshot, owned))) return true;
+        }
+        return false;
+    }
+
+    public boolean isAdoptedAllocation(String nodeId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (info == null) return false;
+        for (Object value : redisTemplate.opsForHash().values(recoveryKey("adoption"))) {
+            com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) value);
+            SsrcTransaction owned = snapshot.getObject("dialog", SsrcTransaction.class);
+            if (java.util.Objects.equals(nodeId, owned.getMediaServerId()) && info.equals(allocation(snapshot, owned))) return true;
+        }
+        return false;
+    }
+
+    private com.alibaba.fastjson2.JSONObject adoption(SsrcTransaction owned) {
+        if (owned == null || owned.getSipTransactionInfo() == null) return null;
+        Object value = redisTemplate.opsForHash().get(recoveryKey("adoption"), dialogIdentity(owned));
+        return value == null ? null : com.alibaba.fastjson2.JSON.parseObject((String) value);
+    }
+
+    private com.ruoyi.wvp.service.bean.SSRCInfo allocation(com.alibaba.fastjson2.JSONObject snapshot, SsrcTransaction owned) {
+        return new com.ruoyi.wvp.service.bean.SSRCInfo(snapshot.getIntValue("port"), owned.getSsrc(), owned.getApp(),
+                owned.getStream(), snapshot.getString("timeoutToken"));
+    }
+
+    private String recoveryKey(String kind) { return "SIP_RECOVERY_V1:" + userSetting.getServerId() + ":" + kind; }
+    private String streamKey() { return VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(); }
+    private String callKey() { return VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(); }
+
+    public static boolean sameDialog(SsrcTransaction expected, SsrcTransaction current) {
+        return expected != null && current != null
+                && java.util.Objects.equals(expected.getCallId(), current.getCallId())
+                && java.util.Objects.equals(expected.getSsrc(), current.getSsrc())
+                && java.util.Objects.equals(expected.getApp(), current.getApp())
+                && java.util.Objects.equals(expected.getStream(), current.getStream())
+                && java.util.Objects.equals(expected.getMediaServerId(), current.getMediaServerId())
+                && java.util.Objects.equals(expected.getDeviceId(), current.getDeviceId())
+                && java.util.Objects.equals(expected.getChannelId(), current.getChannelId())
+                && expected.getType() == current.getType()
+                && expected.getSipTransactionInfo() != null && current.getSipTransactionInfo() != null
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getCallId(), current.getSipTransactionInfo().getCallId())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getFromTag(), current.getSipTransactionInfo().getFromTag())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getToTag(), current.getSipTransactionInfo().getToTag())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getViaBranch(), current.getSipTransactionInfo().getViaBranch())
+                && expected.getSipTransactionInfo().isAsSender() == current.getSipTransactionInfo().isAsSender();
+    }
+
+    /** Persist before dispatch; failed persistence means no managed INVITE may be sent. */
+    public boolean rememberInvite(javax.sip.message.Request request, String nodeId, String deviceId, Integer channelId,
+                                  String channelSipId, com.ruoyi.wvp.service.bean.SSRCInfo allocation,
+                                  String localIp, long deadlineMillis) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.INVITE);
+        if (binding == null || allocation == null || allocation.getStream() == null
+                || !allocation.getStream().startsWith("managed_") || !SipRequestBinding.present(nodeId)
+                || !SipRequestBinding.present(deviceId) || channelId == null || !SipRequestBinding.present(channelSipId)
+                || !SipRequestBinding.present(localIp) || !SipRequestBinding.present(allocation.getTimeOutTaskKey())
+                || !SipRequestBinding.present(allocation.getSsrc()) || !SipRequestBinding.present(allocation.getApp())) return false;
+        PendingSipInvite pending = new PendingSipInvite(); pending.setBinding(binding); pending.setNodeId(nodeId);
+        pending.setDeviceId(deviceId); pending.setChannelId(channelId); pending.setChannelSipId(channelSipId);
+        pending.setApp(allocation.getApp()); pending.setStream(allocation.getStream()); pending.setSsrc(allocation.getSsrc());
+        pending.setPort(allocation.getPort()); pending.setTimeoutToken(allocation.getTimeOutTaskKey());
+        pending.setLocalIp(localIp); pending.setDeadlineMillis(deadlineMillis);
+        String json = com.alibaba.fastjson2.JSON.toJSONString(pending);
+        Object before = redisTemplate.opsForHash().get(recoveryKey("invite-request"), binding.key());
+        String streamField = allocation.getApp() + ":" + allocation.getStream();
+        Object streamBefore = redisTemplate.opsForHash().get(recoveryKey("invite-stream"), streamField);
+        if ((before != null && !before.equals(json)) || (streamBefore != null && !streamBefore.equals(json))) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-request"), binding.key(), before, json),
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-stream"), streamField, streamBefore, json));
+    }
+
+    public PendingSipInvite getPendingInviteByStream(String app, String stream) {
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-stream"), app + ":" + stream);
+        return raw == null ? null : com.alibaba.fastjson2.JSON.parseObject((String) raw, PendingSipInvite.class);
+    }
+
+    public boolean hasPendingInviteRequest(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        return field != null && redisTemplate.opsForHash().get(recoveryKey("invite-request"), field) != null;
+    }
+
+    public PendingSipInvite matchPendingInvite(gov.nist.javax.sip.message.SIPResponse response) {
+        return matchPendingInvite(response, false);
+    }
+
+    /** Final refusals are not 2xx, so rejection attribution validates correlation headers only. */
+    private PendingSipInvite matchPendingInvite(gov.nist.javax.sip.message.SIPResponse response, boolean rejection) {
+        String field = SipRequestBinding.key(response);
+        if (field == null) return null;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-request"), field);
+        if (raw == null) return null;
+        PendingSipInvite pending = com.alibaba.fastjson2.JSON.parseObject((String) raw, PendingSipInvite.class);
+        return rejection ? (pending.getBinding().matchesHeaders(response) ? pending : null)
+                : (pending.getBinding().matches(response) ? pending : null);
+    }
+
+    /** Restore the actual To-tag and transaction from headers; malformed/absent SDP cannot erase a SIP dialog. */
+    public SsrcTransaction restoreManagedInvite(gov.nist.javax.sip.message.SIPResponse response) {
+        PendingSipInvite pending = matchPendingInvite(response);
+        if (pending == null) return null;
+        SsrcTransaction owned = SsrcTransaction.buildForDevice(pending.getDeviceId(), pending.getChannelId(),
+                pending.getBinding().getCallId(), pending.getApp(), pending.getStream(), pending.getSsrc(), pending.getNodeId(),
+                response, com.ruoyi.wvp.common.InviteSessionType.PLAY);
+        String identity = dialogIdentity(owned);
+        if (isSipTerminated(owned)) return null; // INVITE retransmissions cannot revive either kind of real termination.
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if ((stream != null && !sameDialog(owned, stream)) || (call != null && !sameDialog(owned, call))) return null;
+        // A real dialog supersedes any earlier provisional refusal of the same attempt.
+        Object rejected = redisTemplate.opsForHash().get(recoveryKey("invite-rejected"), owned.getApp() + ":" + owned.getStream());
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, owned),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, owned),
+                new SipRedisCompareAndSet.Change(recoveryKey("bye-confirmed"), identity, null, null),
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-rejected"), owned.getApp() + ":" + owned.getStream(), rejected, null),
+                new SipRedisCompareAndSet.Change(recoveryKey("peer-bye"), identity, null, null)) ? owned : null;
+    }
+
+    /** Persist the actual outgoing request before the transport is allowed to send it. */
+    public boolean rememberBye(javax.sip.message.Request request, SsrcTransaction owned) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.BYE);
+        if (binding == null || owned == null || owned.getSipTransactionInfo() == null
+                || !java.util.Objects.equals(binding.getCallId(), owned.getCallId())
+                || !java.util.Objects.equals(binding.getFromTag(), owned.getSipTransactionInfo().getFromTag())
+                || !java.util.Objects.equals(binding.getToTag(), owned.getSipTransactionInfo().getToTag())
+                || !SipRequestBinding.present(binding.getToTag())) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", binding); snapshot.put("dialog", owned);
+        String key = recoveryKey("bye-request");
+        Object before = redisTemplate.opsForHash().get(key, binding.key());
+        String update = snapshot.toJSONString();
+        if (before != null && !before.equals(update)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, binding.key(), before, update));
+    }
+
+    public boolean hasByeRequest(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        return field != null && redisTemplate.opsForHash().get(recoveryKey("bye-request"), field) != null;
+    }
+
+    /** Returns the original dialog only after a matching real BYE 2xx is durably recorded. */
+    public SsrcTransaction confirmBye(gov.nist.javax.sip.message.SIPResponse response) {
+        String field = SipRequestBinding.key(response);
+        if (field == null || !javax.sip.message.Request.BYE.equals(response.getCSeqHeader().getMethod())) return null;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("bye-request"), field);
+        if (raw == null) return null;
+        com.alibaba.fastjson2.JSONObject request = com.alibaba.fastjson2.JSON.parseObject((String) raw);
+        if (!request.getObject("binding", SipRequestBinding.class).matches(response)) return null;
+        SsrcTransaction owned = request.getObject("dialog", SsrcTransaction.class);
+        String identity = dialogIdentity(owned), key = recoveryKey("bye-confirmed");
+        Object before = redisTemplate.opsForHash().get(key, identity);
+        String update = com.alibaba.fastjson2.JSON.toJSONString(owned);
+        if (before != null) return sameDialog(owned, com.alibaba.fastjson2.JSON.parseObject((String) before, SsrcTransaction.class)) ? owned : null;
+        if (SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(recoveryKey("bye-request"), field, raw, raw),
+                new SipRedisCompareAndSet.Change(key, identity, null, update))) return owned;
+        return isByeConfirmed(owned) ? owned : null;
+    }
+
+    /** Explicit final INVITE rejection means no dialog was established; timeouts and lost replies are NOT evidence. */
+    public boolean rememberInviteRejection(gov.nist.javax.sip.message.SIPResponse response) {
+        PendingSipInvite pending = matchPendingInvite(response, true);
+        if (pending == null) return false;
+        int status = response.getStatusCode();
+        // Only a final refusal (>=300) is evidence that no dialog was established. 1xx/2xx are
+        // progress or success; 401/407 are retryable challenges of the same attempt.
+        if (status < 300 || status == javax.sip.message.Response.UNAUTHORIZED
+                || status == javax.sip.message.Response.PROXY_AUTHENTICATION_REQUIRED) return false;
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", pending.getBinding()); snapshot.put("pending", pending); snapshot.put("status", status);
+        String key = recoveryKey("invite-rejected"), field = pending.getApp() + ":" + pending.getStream();
+        Object before = redisTemplate.opsForHash().get(key, field);
+        if (before != null) {
+            com.alibaba.fastjson2.JSONObject existing = com.alibaba.fastjson2.JSON.parseObject((String) before);
+            PendingSipInvite prior = existing.getObject("pending", PendingSipInvite.class);
+            // A different attempt on the same stream must not be overwritten by a stale rejection.
+            return prior != null && java.util.Objects.equals(prior.getBinding().getCallId(), pending.getBinding().getCallId())
+                    && java.util.Objects.equals(prior.getTimeoutToken(), pending.getTimeoutToken());
+        }
+        if (SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(key, field, null, snapshot.toJSONString()))) return true;
+        return isInviteRejected(pending.getNodeId(), pending.getApp(), pending.getStream(), pending.getTimeoutToken());
+    }
+
+    /** Read-only: this exact allocation attempt was definitively refused before any dialog existed. */
+    public boolean isInviteRejected(String nodeId, String app, String stream, String allocationToken) {
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-rejected"), app + ":" + stream);
+        if (raw == null) return false;
+        PendingSipInvite prior = com.alibaba.fastjson2.JSON.parseObject((String) raw).getObject("pending", PendingSipInvite.class);
+        return prior != null && java.util.Objects.equals(prior.getNodeId(), nodeId)
+                && java.util.Objects.equals(prior.getApp(), app) && java.util.Objects.equals(prior.getStream(), stream)
+                && java.util.Objects.equals(prior.getTimeoutToken(), allocationToken);
+    }
+
+    /** A receipt proves this exact dialog, not a successful send or another allocation with the same Call-ID. */
+    public boolean isByeConfirmed(SsrcTransaction expected) {
+        if (expected == null || expected.getSipTransactionInfo() == null) return false;
+        Object value = redisTemplate.opsForHash().get(recoveryKey("bye-confirmed"), dialogIdentity(expected));
+        return value != null && sameDialog(expected, com.alibaba.fastjson2.JSON.parseObject((String) value, SsrcTransaction.class));
+    }
+
+    /** Called only after replying 200 to an actual peer BYE; not an outgoing-BYE confirmation. */
+    public boolean rememberPeerBye(javax.sip.message.Request request, SsrcTransaction owned) {
+        SipRequestBinding binding = SipRequestBinding.from(request, javax.sip.message.Request.BYE);
+        if (!matchesPeerBye(binding, owned)) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        String key = recoveryKey("peer-bye"), field = dialogIdentity(owned);
+        Object before = redisTemplate.opsForHash().get(key, field);
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", binding); snapshot.put("dialog", owned);
+        if (before != null && !matchedPeerBye(owned, before)) return false;
+        // Keep the first actual request as evidence; retransmits must still own both original indexes.
+        Object update = before == null ? snapshot.toJSONString() : before;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, stream),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, call),
+                new SipRedisCompareAndSet.Change(key, field, before, update));
+    }
+
+    private static boolean matchesPeerBye(SipRequestBinding binding, SsrcTransaction owned) {
+        return binding != null && owned != null && owned.getSipTransactionInfo() != null
+                && javax.sip.message.Request.BYE.equals(binding.getMethod())
+                && org.springframework.util.StringUtils.hasText(binding.getCallId())
+                && org.springframework.util.StringUtils.hasText(binding.getFromTag())
+                && org.springframework.util.StringUtils.hasText(binding.getToTag())
+                && org.springframework.util.StringUtils.hasText(binding.getViaBranch())
+                && java.util.Objects.equals(binding.getCallId(), owned.getCallId())
+                && java.util.Objects.equals(binding.getCallId(), owned.getSipTransactionInfo().getCallId())
+                && java.util.Objects.equals(binding.getFromTag(), owned.getSipTransactionInfo().getToTag())
+                && java.util.Objects.equals(binding.getToTag(), owned.getSipTransactionInfo().getFromTag());
+    }
+
+    /** Whether this real Request belongs to the same dialog, independent of receipt persistence. */
+    public boolean matchesPeerByeRequest(javax.sip.message.Request request, SsrcTransaction owned) {
+        return matchesPeerBye(SipRequestBinding.from(request, javax.sip.message.Request.BYE), owned);
+    }
+
+    private static boolean matchedPeerBye(SsrcTransaction expected, Object raw) {
+        com.alibaba.fastjson2.JSONObject snapshot = com.alibaba.fastjson2.JSON.parseObject((String) raw);
+        return sameDialog(expected, snapshot.getObject("dialog", SsrcTransaction.class))
+                && matchesPeerBye(snapshot.getObject("binding", SipRequestBinding.class), expected);
+    }
+
+    /** Read-only protocol evidence for this exact original dialog, independent of live index deletion. */
+    public boolean isSipTerminated(SsrcTransaction expected) {
+        if (expected == null || expected.getSipTransactionInfo() == null) return false;
+        if (isByeConfirmed(expected)) return true;
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("peer-bye"), dialogIdentity(expected));
+        return raw != null && matchedPeerBye(expected, raw);
+    }
+
+    private static String dialogIdentity(SsrcTransaction tx) {
+        com.ruoyi.wvp.gb28181.bean.SipTransactionInfo sip = tx.getSipTransactionInfo();
+        String identity = com.alibaba.fastjson2.JSON.toJSONString(java.util.Arrays.asList(tx.getMediaServerId(),
+                tx.getDeviceId(), tx.getChannelId(), tx.getApp(), tx.getStream(), tx.getCallId(), tx.getSsrc(), tx.getType(),
+                sip.getCallId(), sip.getFromTag(), sip.getToTag(), sip.getViaBranch(), sip.isAsSender()));
+        try {
+            byte[] digest = java.security.MessageDigest.getInstance("SHA-256")
+                    .digest(identity.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+            return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+        } catch (java.security.NoSuchAlgorithmException impossible) {
+            throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible);
+        }
+    }
+
+    public boolean removeAdoptedIfSame(SsrcTransaction owned) {
+        return isAdopted(owned) && removeConfirmedIfSame(owned);
+    }
+
+    /** Real termination is required here; offline cleanup uses removeIfSame without claiming SIP completion. */
+    public boolean removeManagedIfSame(SsrcTransaction owned) {
+        return owned != null && owned.getStream() != null && owned.getStream().startsWith("managed_")
+                && removeConfirmedIfSame(owned);
+    }
+
+    private boolean removeConfirmedIfSame(SsrcTransaction owned) {
+        return isSipTerminated(owned) && removeIfSame(owned);
+    }
+
+    /** Compare the caller's original snapshot and atomically delete both indexes, never a replacement. */
+    public boolean removeIfSame(SsrcTransaction owned) {
+        if (owned == null || owned.getApp() == null || owned.getStream() == null || owned.getCallId() == null) return false;
+        SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
+        if (!sameDialog(owned, stream) || !sameDialog(owned, call)) return false;
+        return SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, null),
+                new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, null));
+    }
+
 	public void removeByCallId(String callId) {
 	public void removeByCallId(String callId) {
 		SsrcTransaction ssrcTransaction = getSsrcTransactionByCallId(callId);
 		SsrcTransaction ssrcTransaction = getSsrcTransactionByCallId(callId);
 		if (ssrcTransaction == null ) {
 		if (ssrcTransaction == null ) {

+ 46 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRedisCompareAndSet.java

@@ -0,0 +1,46 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.core.RedisCallback;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.RedisSerializer;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Compare every observed hash value before changing any index; atomic across service instances. */
+public final class SipRedisCompareAndSet {
+    private static final byte[] SCRIPT = ("-- sip-recovery-cas-v1\n"
+            + "for i=1,#KEYS do local a=(i-1)*5; local v=redis.call('HGET',KEYS[i],ARGV[a+1]); "
+            + "if ARGV[a+2]=='0' then if v then return 0 end "
+            + "elseif not v or v~=ARGV[a+3] then return 0 end end; "
+            + "for i=1,#KEYS do local a=(i-1)*5; if ARGV[a+4]=='1' then "
+            + "redis.call('HSET',KEYS[i],ARGV[a+1],ARGV[a+5]) else redis.call('HDEL',KEYS[i],ARGV[a+1]) end end; return 1")
+            .getBytes(StandardCharsets.UTF_8);
+    public static final class Change {
+        final String key, field;
+        final Object before, after;
+        public Change(String key, String field, Object before, Object after) {
+            this.key = key; this.field = field; this.before = before; this.after = after;
+        }
+    }
+    @SuppressWarnings("unchecked")
+    public static boolean apply(RedisTemplate<Object,Object> redis, Change... changes) {
+        RedisSerializer<Object> keys = (RedisSerializer<Object>) redis.getKeySerializer();
+        RedisSerializer<Object> fields = (RedisSerializer<Object>) redis.getHashKeySerializer();
+        RedisSerializer<Object> values = (RedisSerializer<Object>) redis.getHashValueSerializer();
+        List<byte[]> args = new ArrayList<>();
+        for (Change c : changes) args.add(keys.serialize(c.key));
+        for (Change c : changes) {
+            args.add(fields.serialize(c.field));
+            args.add(flag(c.before != null)); args.add(c.before == null ? new byte[0] : values.serialize(c.before));
+            args.add(flag(c.after != null)); args.add(c.after == null ? new byte[0] : values.serialize(c.after));
+        }
+        Long result = redis.execute((RedisCallback<Long>) connection -> connection.eval(
+                SCRIPT, ReturnType.INTEGER, changes.length, args.toArray(new byte[0][])));
+        return Long.valueOf(1).equals(result);
+    }
+    private static byte[] flag(boolean value) { return new byte[]{ (byte) (value ? '1' : '0') }; }
+    private SipRedisCompareAndSet() { }
+}

+ 55 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRequestBinding.java

@@ -0,0 +1,55 @@
+package com.ruoyi.wvp.gb28181.session;
+
+import gov.nist.javax.sip.message.SIPResponse;
+import lombok.Data;
+import javax.sip.header.*;
+import javax.sip.message.Request;
+import java.util.Objects;
+
+/** Only correlation headers, never a SIP message, SDP, authorization or credentials. */
+@Data
+public class SipRequestBinding {
+    private String callId;
+    private long cseq;
+    private String method;
+    private String fromTag;
+    private String toTag;
+    private String viaBranch;
+
+    static SipRequestBinding from(Request request, String method) {
+        if (request == null || !method.equals(request.getMethod())) return null;
+        CallIdHeader call = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
+        CSeqHeader seq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
+        FromHeader from = (FromHeader) request.getHeader(FromHeader.NAME);
+        ToHeader to = (ToHeader) request.getHeader(ToHeader.NAME);
+        ViaHeader via = (ViaHeader) request.getHeader(ViaHeader.NAME);
+        if (call == null || seq == null || from == null || via == null || to == null
+                || !method.equals(seq.getMethod()) || !present(call.getCallId())
+                || !present(from.getTag()) || !present(via.getBranch())) return null;
+        SipRequestBinding result = new SipRequestBinding(); result.callId = call.getCallId();
+        result.cseq = seq.getSeqNumber(); result.method = method; result.fromTag = from.getTag();
+        result.toTag = to.getTag(); result.viaBranch = via.getBranch(); return result;
+    }
+
+    boolean matches(SIPResponse response) {
+        return response != null && response.getStatusCode() >= 200 && response.getStatusCode() < 300
+                && matchesHeaders(response) && present(response.getToTag())
+                && (Request.INVITE.equals(method) || Objects.equals(toTag, response.getToTag()));
+    }
+
+    /** Correlation only: used to attribute a final rejection, which by definition is not 2xx. */
+    boolean matchesHeaders(SIPResponse response) {
+        return response != null
+                && response.getCallIdHeader() != null && response.getCSeqHeader() != null
+                && response.getTopmostViaHeader() != null && Objects.equals(callId, response.getCallIdHeader().getCallId())
+                && cseq == response.getCSeqHeader().getSeqNumber() && Objects.equals(method, response.getCSeqHeader().getMethod())
+                && Objects.equals(fromTag, response.getFromTag()) && Objects.equals(viaBranch, response.getTopmostViaHeader().getBranch());
+    }
+    String key() { return callId.length() + ":" + callId + ":" + cseq; }
+    static String key(SIPResponse response) {
+        if (response == null || response.getCallIdHeader() == null || response.getCSeqHeader() == null) return null;
+        String call = response.getCallIdHeader().getCallId();
+        return call == null ? null : call.length() + ":" + call + ":" + response.getCSeqHeader().getSeqNumber();
+    }
+    static boolean present(String value) { return value != null && !value.isEmpty(); }
+}

+ 35 - 7
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/SIPProcessorObserver.java

@@ -36,6 +36,9 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
     @Autowired
     @Autowired
     private EventPublisher eventPublisher;
     private EventPublisher eventPublisher;
 
 
+    @Autowired
+    private com.ruoyi.wvp.gb28181.session.SipInviteSessionManager sessionManager;
+
     /**
     /**
      * 添加 request订阅
      * 添加 request订阅
      * @param method 方法名
      * @param method 方法名
@@ -81,9 +84,28 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
     public void processResponse(ResponseEvent responseEvent) {
     public void processResponse(ResponseEvent responseEvent) {
         SIPResponse response = (SIPResponse)responseEvent.getResponse();
         SIPResponse response = (SIPResponse)responseEvent.getResponse();
         int status = response.getStatusCode();
         int status = response.getStatusCode();
+        if (response.getCSeqHeader() == null) return;
+        if (status >= 200 && status < 300 && javax.sip.message.Request.BYE.equals(response.getCSeqHeader().getMethod())
+                && sessionManager != null) {
+            com.ruoyi.wvp.gb28181.bean.SsrcTransaction confirmed = sessionManager.confirmBye(response);
+            if (confirmed != null) {
+                // Also runs after SipSubscribe expiry or process reconstruction; receipt precedes deletion.
+                if (sessionManager.isAdopted(confirmed)) sessionManager.removeAdoptedIfSame(confirmed);
+                else sessionManager.removeManagedIfSame(confirmed);
+                if (responseEvent.getDialog() != null) responseEvent.getDialog().delete();
+            } else if (sessionManager.hasByeRequest(response)) {
+                return;
+            }
+        }
 
 
         // Success
         // Success
         if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
         if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
+            ISIPResponseProcessor processor = responseProcessorMap.get(response.getCSeqHeader().getMethod());
+            boolean invite = javax.sip.message.Request.INVITE.equals(response.getCSeqHeader().getMethod());
+            // ACK and retain before a downstream SDP callback can reject the response body.
+            if (invite && processor != null) processor.process(responseEvent);
+            if (invite && status >= 200 && status < 300 && sessionManager != null
+                    && sessionManager.hasPendingInviteRequest(response) && sessionManager.matchPendingInvite(response) == null) return;
             if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
             if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
@@ -94,20 +116,23 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             sipEvent.getOkEvent().response(eventResult);
                             sipEvent.getOkEvent().response(eventResult);
                         }
                         }
-                        sipSubscribe.removeSubscribe(callIdHeader.getCallId());
+                        sipSubscribe.removeSubscribe(callIdHeader.getCallId() + cSeqHeader.getSeqNumber());
                     }
                     }
                 }
                 }
             }
             }
-            ISIPResponseProcessor sipRequestProcessor = responseProcessorMap.get(response.getCSeqHeader().getMethod());
-            if (sipRequestProcessor != null) {
-                sipRequestProcessor.process(responseEvent);
-            }
+            if (!invite && processor != null) processor.process(responseEvent);
         } else if ((status >= Response.TRYING) && (status < Response.OK)) {
         } else if ((status >= Response.TRYING) && (status < Response.OK)) {
             // 增加其它无需回复的响应,如101、180等
             // 增加其它无需回复的响应,如101、180等
             // 更新sip订阅的时间
             // 更新sip订阅的时间
 //            sipSubscribe.updateTimeout(response.getCallIdHeader().getCallId());
 //            sipSubscribe.updateTimeout(response.getCallIdHeader().getCallId());
         } else {
         } else {
             log.warn("接收到失败的response响应!status:" + status + ",message:" + response.getReasonPhrase());
             log.warn("接收到失败的response响应!status:" + status + ",message:" + response.getReasonPhrase());
+            // Persist a final INVITE refusal BEFORE the error callback runs: stopManaged may
+            // consult it immediately. Timeouts and lost replies are never recorded this way.
+            if (sessionManager != null && javax.sip.message.Request.INVITE.equals(response.getCSeqHeader().getMethod())) {
+                try { sessionManager.rememberInviteRejection(response); }
+                catch (RuntimeException ex) { log.warn("[INVITE rejection] evidence not durable: {}", ex.getMessage()); }
+            }
             if (responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
             if (responseEvent.getResponse() != null && !sipSubscribe.isEmpty() ) {
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CallIdHeader callIdHeader = response.getCallIdHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
                 CSeqHeader cSeqHeader = response.getCSeqHeader();
@@ -118,11 +143,14 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             SipSubscribe.EventResult<ResponseEvent> eventResult = new SipSubscribe.EventResult<>(responseEvent);
                             sipEvent.getErrorEvent().response(eventResult);
                             sipEvent.getErrorEvent().response(eventResult);
                         }
                         }
-                        sipSubscribe.removeSubscribe(callIdHeader.getCallId());
+                        // Remove by the same correlation the success branch used: a bare callId can
+                        // never remove this entry, so a later timeout would fire the error again.
+                        sipSubscribe.removeSubscribe(callIdHeader.getCallId() + cSeqHeader.getSeqNumber());
                     }
                     }
                 }
                 }
             }
             }
-            if (responseEvent.getDialog() != null) {
+            if (responseEvent.getDialog() != null
+                    && (sessionManager == null || !sessionManager.hasByeRequest(response))) {
                 responseEvent.getDialog().delete();
                 responseEvent.getDialog().delete();
             }
             }
         }
         }

+ 101 - 8
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java

@@ -46,6 +46,14 @@ import java.text.ParseException;
 @Slf4j
 @Slf4j
 public class SIPCommander implements ISIPCommander {
 public class SIPCommander implements ISIPCommander {
 
 
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
+    private boolean managedCancelled(String stream) {
+        return stream != null && stream.startsWith("managed_")
+                && (videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream));
+    }
+
     @Autowired
     @Autowired
     private SipConfig sipConfig;
     private SipConfig sipConfig;
 
 
@@ -255,6 +263,7 @@ public class SIPCommander implements ISIPCommander {
     public void playStreamCmd(MediaServer mediaServerItem, SSRCInfo ssrcInfo, Device device, DeviceChannel channel,
     public void playStreamCmd(MediaServer mediaServerItem, SSRCInfo ssrcInfo, Device device, DeviceChannel channel,
                               SipSubscribe.Event okEvent, SipSubscribe.Event errorEvent, Long timeout) throws InvalidArgumentException, SipException, ParseException {
                               SipSubscribe.Event okEvent, SipSubscribe.Event errorEvent, Long timeout) throws InvalidArgumentException, SipException, ParseException {
         String stream = ssrcInfo.getStream();
         String stream = ssrcInfo.getStream();
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE");
 
 
         if (device == null) {
         if (device == null) {
             return;
             return;
@@ -327,19 +336,43 @@ public class SIPCommander implements ISIPCommander {
 //			content.append("f=v/2/5/25/1/4000a/1/8/1" + "\r\n"); // 未发现支持此特性的设备
 //			content.append("f=v/2/5/25/1/4000a/1/8/1" + "\r\n"); // 未发现支持此特性的设备
 
 
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
-        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), request, (e -> {
-            sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
-            mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
-            errorEvent.response(e);
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE dispatch");
+        String inviteLocalIp = sipLayer.getLocalIp(device.getLocalIp());
+        if (stream.startsWith("managed_") && !sessionManager.rememberInvite(request, mediaServerItem.getId(),
+                device.getDeviceId(), channel.getId(), channel.getDeviceId(), ssrcInfo, inviteLocalIp,
+                System.currentTimeMillis() + (timeout == null ? sipConfig.getTimeout() : timeout))) {
+            throw new SipException("Managed INVITE correlation could not be persisted");
+        }
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled after INVITE persistence");
+        sipSender.transmitRequest(inviteLocalIp, request, (e -> {
+            if (!stream.startsWith("managed_")) {
+                sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
+                mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
+            }
+            // A managed timeout/error cannot destroy a dialog retained for BYE retry.
+            if (errorEvent != null) errorEvent.response(e);
         }), e -> {
         }), e -> {
+            if (!(e.event instanceof ResponseEvent)) return;
             ResponseEvent responseEvent = (ResponseEvent) e.event;
             ResponseEvent responseEvent = (ResponseEvent) e.event;
+            if (!(responseEvent.getResponse() instanceof SIPResponse)) return;
             SIPResponse response = (SIPResponse) responseEvent.getResponse();
             SIPResponse response = (SIPResponse) responseEvent.getResponse();
+            if (stream.startsWith("managed_")) {
+                com.ruoyi.wvp.gb28181.session.PendingSipInvite pending = sessionManager.matchPendingInvite(response);
+                if (pending == null || !stream.equals(pending.getStream())
+                        || !mediaServerItem.getId().equals(pending.getNodeId())
+                        || !device.getDeviceId().equals(pending.getDeviceId())
+                        || !java.util.Objects.equals(channel.getId(), pending.getChannelId())) return;
+                SsrcTransaction actual = sessionManager.restoreManagedInvite(response);
+                if (actual == null || pending.isExpired() || managedCancelled(stream)) return;
+                if (okEvent != null) okEvent.response(e);
+                return;
+            }
             String callId = response.getCallIdHeader().getCallId();
             String callId = response.getCallIdHeader().getCallId();
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     InviteSessionType.PLAY);
                     InviteSessionType.PLAY);
             sessionManager.put(ssrcTransaction);
             sessionManager.put(ssrcTransaction);
-            okEvent.response(e);
+            if (okEvent != null) okEvent.response(e);
         }, timeout);
         }, timeout);
     }
     }
 
 
@@ -554,13 +587,73 @@ public class SIPCommander implements ISIPCommander {
         }
         }
 
 
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
-        sessionManager.removeByCallId(ssrcTransaction.getCallId());
-        Request byteRequest = headerProvider.createByteRequest(device, channelId, ssrcTransaction.getSipTransactionInfo());
-        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
+        final SsrcTransaction owned = ssrcTransaction;
+        if ((app != null && !java.util.Objects.equals(app, owned.getApp()))
+                || (stream != null && !java.util.Objects.equals(stream, owned.getStream())))
+            throw new SipException("BYE source does not match the retained dialog");
+        sendObservedBye(device, channelId, owned, okEvent);
+    }
+
+    private void sendObservedBye(Device device, String channelId, SsrcTransaction owned,
+                                 SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException {
+        boolean managed = owned.getStream() != null && owned.getStream().startsWith("managed_");
+        boolean adopted = sessionManager.isAdopted(owned);
+        if (!managed && !adopted) sessionManager.removeByCallId(owned.getCallId());
+        Device byeDevice = device;
+        String byeLocalIp = sipLayer.getLocalIp(device.getLocalIp());
+        if (managed || adopted) {
+            if (!java.util.Objects.equals(device.getDeviceId(), owned.getDeviceId())) {
+                throw new SipException("BYE source does not match the retained dialog");
+            }
+            if (managed) {
+                com.ruoyi.wvp.gb28181.session.PendingSipInvite pending = sessionManager.getPendingInviteByStream(owned.getApp(), owned.getStream());
+                if (pending != null && java.util.Objects.equals(pending.getBinding().getCallId(), owned.getCallId())
+                        && java.util.Objects.equals(pending.getNodeId(), owned.getMediaServerId())
+                        && java.util.Objects.equals(pending.getDeviceId(), owned.getDeviceId())
+                        && java.util.Objects.equals(pending.getChannelId(), owned.getChannelId())) {
+                    if (!java.util.Objects.equals(channelId, pending.getChannelSipId())) throw new SipException("BYE channel source changed");
+                    byeLocalIp = pending.getLocalIp();
+                    byeDevice = new Device();
+                    org.springframework.beans.BeanUtils.copyProperties(device, byeDevice);
+                    byeDevice.setLocalIp(byeLocalIp);
+                }
+            }
+        }
+        Request byteRequest = headerProvider.createByteRequest(byeDevice, channelId, owned.getSipTransactionInfo());
+        if ((managed || adopted) && !sessionManager.rememberBye(byteRequest, owned)) {
+            throw new SipException("BYE correlation could not be persisted for the owned dialog");
+        }
+        SipSubscribe.Event response = !managed && !adopted ? okEvent : event -> {
+            if (!(event.event instanceof ResponseEvent)) return;
+            ResponseEvent actual = (ResponseEvent) event.event;
+            if (!(actual.getResponse() instanceof SIPResponse)) return;
+            SsrcTransaction confirmed = sessionManager.confirmBye((SIPResponse) actual.getResponse());
+            if (!SipInviteSessionManager.sameDialog(owned, confirmed)) return;
+            // A matching durable receipt must precede both dialog deletion and the caller callback.
+            if (adopted) sessionManager.removeAdoptedIfSame(owned);
+            else sessionManager.removeManagedIfSame(owned);
+            if (okEvent != null) okEvent.response(event);
+        };
+        // Managed transport errors leave the actual dialog available for retry.
+        sipSender.transmitRequest(byeLocalIp, byteRequest, null, response);
     }
     }
 
 
     @Override
     @Override
     public void streamByeCmd(Device device, String channelId, SipTransactionInfo sipTransactionInfo, SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException, SsrcTransactionNotFoundException {
     public void streamByeCmd(Device device, String channelId, SipTransactionInfo sipTransactionInfo, SipSubscribe.Event okEvent) throws InvalidArgumentException, SipException, ParseException, SsrcTransactionNotFoundException {
+        if (device == null || sipTransactionInfo == null || sipTransactionInfo.getCallId() == null)
+            throw new SipException("Original BYE dialog is required");
+        SsrcTransaction owned = sessionManager.getSsrcTransactionByCallId(sipTransactionInfo.getCallId());
+        if (owned != null) {
+            SsrcTransaction expected = new SsrcTransaction();
+            org.springframework.beans.BeanUtils.copyProperties(owned, expected);
+            expected.setSipTransactionInfo(sipTransactionInfo);
+            if (!SipInviteSessionManager.sameDialog(owned, expected))
+                throw new SipException("Original BYE tags no longer match the live dialog");
+            if ((owned.getStream() != null && owned.getStream().startsWith("managed_")) || sessionManager.isAdopted(owned)) {
+                sendObservedBye(device, channelId, expected, okEvent);
+                return;
+            }
+        }
         Request byteRequest = headerProvider.createByteRequest(device, channelId, sipTransactionInfo);
         Request byteRequest = headerProvider.createByteRequest(device, channelId, sipTransactionInfo);
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
     }
     }

+ 20 - 8
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/request/impl/ByeRequestProcessor.java

@@ -11,6 +11,7 @@ import com.ruoyi.wvp.gb28181.transmit.cmd.ISIPCommander;
 import com.ruoyi.wvp.gb28181.transmit.event.request.ISIPRequestProcessor;
 import com.ruoyi.wvp.gb28181.transmit.event.request.ISIPRequestProcessor;
 import com.ruoyi.wvp.gb28181.transmit.event.request.SIPRequestProcessorParent;
 import com.ruoyi.wvp.gb28181.transmit.event.request.SIPRequestProcessorParent;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import com.ruoyi.wvp.storager.IRedisCatchStorage;
 import gov.nist.javax.sip.message.SIPRequest;
 import gov.nist.javax.sip.message.SIPRequest;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -52,6 +53,9 @@ public class ByeRequestProcessor extends SIPRequestProcessorParent implements In
 	@Autowired
 	@Autowired
 	private IMediaServerService mediaServerService;
 	private IMediaServerService mediaServerService;
 
 
+    @Autowired
+    private RtpServerServiceImpl rtpServerService;
+
 	@Autowired
 	@Autowired
 	private SIPProcessorObserver sipProcessorObserver;
 	private SIPProcessorObserver sipProcessorObserver;
 
 
@@ -77,21 +81,29 @@ public class ByeRequestProcessor extends SIPRequestProcessorParent implements In
 	@Override
 	@Override
 	public void process(RequestEvent evt) {
 	public void process(RequestEvent evt) {
         SIPRequest request = (SIPRequest) evt.getRequest();
         SIPRequest request = (SIPRequest) evt.getRequest();
+        CallIdHeader callId = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
+        SsrcTransaction transaction = callId == null ? null : sessionManager.getSsrcTransactionByCallId(callId.getCallId());
         try {
         try {
             responseAck(request, Response.OK);
             responseAck(request, Response.OK);
         } catch (SipException | InvalidArgumentException | ParseException e) {
         } catch (SipException | InvalidArgumentException | ParseException e) {
             log.error("[BYE] Reply failed", e);
             log.error("[BYE] Reply failed", e);
+            return;
         }
         }
-        CallIdHeader callId = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
-        SsrcTransaction transaction = sessionManager.getSsrcTransactionByCallId(callId.getCallId());
-        if (transaction == null) return;
-        // Match the exact stream and session type; playback must not remove a live session.
+        // The request must match the pre-reply snapshot and both indexes at the durable write.
+        // A persistence failure must not skip media cleanup for a genuinely matching dialog; it
+        // only means the SIP termination stays unconfirmed, so the Invite/dialog is retained.
+        boolean recorded;
+        try { recorded = sessionManager.rememberPeerBye(request, transaction); }
+        catch (RuntimeException unavailable) { recorded = false; }
+        if (!recorded && !sessionManager.matchesPeerByeRequest(request, transaction)) return;
+        // Freeze original evidence before any Invite/dialog removal; unknown close stays retryable.
         InviteInfo info = inviteStreamService.getInviteInfo(transaction.getType(), transaction.getChannelId(), transaction.getStream());
         InviteInfo info = inviteStreamService.getInviteInfo(transaction.getType(), transaction.getChannelId(), transaction.getStream());
-        if (info != null) inviteStreamService.removeInviteInfo(info);
+        if (!rtpServerService.closeRTPServerForSession(transaction, info)) return;
+        // Media is reclaimed; without durable peer evidence this is not a confirmed SIP termination.
+        if (!recorded) return;
+        if (info != null && !inviteStreamService.removeInviteInfoIfSame(info)) return;
+        if (!sessionManager.removeIfSame(transaction)) return;
         if (transaction.getType() == InviteSessionType.PLAY) deviceChannelService.stopPlay(transaction.getChannelId());
         if (transaction.getType() == InviteSessionType.PLAY) deviceChannelService.stopPlay(transaction.getChannelId());
-        mediaServerService.closeRTPServer(transaction.getMediaServerId(), transaction.getStream());
-        mediaServerService.releaseSsrc(transaction.getMediaServerId(), transaction.getSsrc());
-        sessionManager.removeByCallId(transaction.getCallId());
 
 
     }
     }
 }
 }

+ 100 - 62
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/event/response/impl/InviteResponseProcessor.java

@@ -1,89 +1,127 @@
 package com.ruoyi.wvp.gb28181.transmit.event.response.impl;
 package com.ruoyi.wvp.gb28181.transmit.event.response.impl;
 
 
-import com.ruoyi.wvp.gb28181.bean.Gb28181Sdp;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
+import com.ruoyi.wvp.gb28181.service.IPlayService;
+import com.ruoyi.wvp.gb28181.session.PendingSipInvite;
+import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
 import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
 import com.ruoyi.wvp.gb28181.transmit.SIPSender;
 import com.ruoyi.wvp.gb28181.transmit.SIPSender;
 import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
 import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
 import com.ruoyi.wvp.gb28181.transmit.event.response.SIPResponseProcessorAbstract;
 import com.ruoyi.wvp.gb28181.transmit.event.response.SIPResponseProcessorAbstract;
 import com.ruoyi.wvp.gb28181.utils.SipUtils;
 import com.ruoyi.wvp.gb28181.utils.SipUtils;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.storager.IRedisCatchStorage;
+import com.zksy.video.lifecycle.VideoLifecycleStore;
 import gov.nist.javax.sip.ResponseEventExt;
 import gov.nist.javax.sip.ResponseEventExt;
 import gov.nist.javax.sip.message.SIPResponse;
 import gov.nist.javax.sip.message.SIPResponse;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
-import javax.sdp.SdpParseException;
-import javax.sdp.SessionDescription;
-import javax.sip.InvalidArgumentException;
 import javax.sip.ResponseEvent;
 import javax.sip.ResponseEvent;
-import javax.sip.SipException;
 import javax.sip.SipFactory;
 import javax.sip.SipFactory;
 import javax.sip.address.SipURI;
 import javax.sip.address.SipURI;
 import javax.sip.message.Request;
 import javax.sip.message.Request;
 import javax.sip.message.Response;
 import javax.sip.message.Response;
-import java.text.ParseException;
+import java.nio.charset.StandardCharsets;
+import java.util.Objects;
 
 
-
-/**
- * @description: 处理INVITE响应
- * @author: panlinlin
- * @date: 2021年11月5日 16:40
- */
+/** ACK all INVITE 200s as before; recover managed dialogs only through the durable outgoing binding. */
 @Slf4j
 @Slf4j
 @Component
 @Component
 public class InviteResponseProcessor extends SIPResponseProcessorAbstract {
 public class InviteResponseProcessor extends SIPResponseProcessorAbstract {
+    @Autowired private SIPProcessorObserver sipProcessorObserver;
+    @Autowired private SIPSender sipSender;
+    @Autowired private SIPRequestHeaderProvider headerProvider;
+    @Autowired private SipInviteSessionManager sessionManager;
+    @Autowired private VideoLifecycleStore videoLifecycleStore;
+    @Autowired private IMediaServerService mediaServerService;
+    @Autowired private IRedisCatchStorage redisCatchStorage;
+    @Autowired private IDeviceChannelService deviceChannelService;
+    @Lazy @Autowired private IPlayService playService;
 
 
-	private final String method = "INVITE";
-
-	@Autowired
-	private SIPProcessorObserver sipProcessorObserver;
-
-	@Autowired
-	private SIPSender sipSender;
-
-	@Autowired
-	private SIPRequestHeaderProvider headerProvider;
-
-	@Override
-	public void afterPropertiesSet() throws Exception {
-		// 添加消息处理的订阅
-		sipProcessorObserver.addResponseProcessor(method, this);
-	}
-
-
-
-	/**
-	 * 处理invite响应
-	 *
-	 * @param evt 响应消息
-	 * @throws ParseException
-	 */
-	@Override
-	public void process(ResponseEvent evt ){
-		log.debug("接收到消息:" + evt.getResponse());
-		try {
-			SIPResponse response = (SIPResponse)evt.getResponse();
-			int statusCode = response.getStatusCode();
-			// trying不会回复
-			if (statusCode == Response.TRYING) {
-			}
-			// 成功响应
-			// 下发ack
-			if (statusCode == Response.OK) {
-				ResponseEventExt event = (ResponseEventExt)evt;
+    @Override public void afterPropertiesSet() { sipProcessorObserver.addResponseProcessor(Request.INVITE, this); }
 
 
-				String contentString = new String(response.getRawContent());
-				Gb28181Sdp gb28181Sdp = SipUtils.parseSDP(contentString);
-				SessionDescription sdp = gb28181Sdp.getBaseSdb();
-				SipURI requestUri = SipFactory.getInstance().createAddressFactory().createSipURI(sdp.getOrigin().getUsername(), event.getRemoteIpAddress() + ":" + event.getRemotePort());
-				Request reqAck = headerProvider.createAckRequest(response.getLocalAddress().getHostAddress(), requestUri, response);
+    @Override public void process(ResponseEvent event) {
+        if (!(event.getResponse() instanceof SIPResponse)) return;
+        SIPResponse response = (SIPResponse) event.getResponse();
+        if (response.getStatusCode() != Response.OK || response.getCSeqHeader() == null
+                || !Request.INVITE.equals(response.getCSeqHeader().getMethod())) return;
+        PendingSipInvite pending = null;
+        SsrcTransaction restored = null;
+        // Retention and ACK are separate: persistence outages or malformed SDP must not suppress legacy ACK.
+        try {
+            if (sessionManager != null) {
+                pending = sessionManager.matchPendingInvite(response);
+                if (pending != null) restored = sessionManager.restoreManagedInvite(response);
+            }
+        } catch (RuntimeException ex) {
+            log.warn("[INVITE recovery] persistence unavailable; ACK still required");
+        }
+        try {
+            ResponseEventExt remote = (ResponseEventExt) event;
+            String localIp = pending == null ? response.getLocalAddress().getHostAddress() : pending.getLocalIp();
+            String user = pending == null ? ackUser(response) : pending.getChannelSipId();
+            SipURI target = SipFactory.getInstance().createAddressFactory().createSipURI(user, remote.getRemoteIpAddress());
+            target.setPort(remote.getRemotePort());
+            Request ack = headerProvider.createAckRequest(localIp, target, response);
+            sipSender.transmitRequest(localIp, ack);
+        } catch (Exception ex) {
+            // Never log complete SIP/SDP bodies or credential-bearing source objects.
+            log.warn("[INVITE ACK] send failed; retained dialog remains retryable");
+            return;
+        }
+        if (pending != null && restored != null) cleanupLate(pending, restored);
+    }
 
 
-				log.info("[回复ack] {}-> {}:{} ", sdp.getOrigin().getUsername(), event.getRemoteIpAddress(), event.getRemotePort());
-				sipSender.transmitRequest( response.getLocalAddress().getHostAddress(), reqAck);
-			}
-		} catch (InvalidArgumentException | ParseException | SipException | SdpParseException e) {
-			log.info("[点播回复ACK],异常:", e );
-		}
-	}
+    private String ackUser(SIPResponse response) {
+        // Preserve the SDP-origin username used by legacy devices when parsable.
+        try {
+            if (response.getRawContent() != null) {
+                String user = SipUtils.parseSDP(new String(response.getRawContent(), StandardCharsets.UTF_8))
+                        .getBaseSdb().getOrigin().getUsername();
+                if (user != null && !user.isEmpty()) return user;
+            }
+        } catch (Exception ignored) { /* Established dialog headers remain usable without SDP. */ }
+        if (response.getToHeader() != null && response.getToHeader().getAddress().getURI() instanceof SipURI)
+            return ((SipURI) response.getToHeader().getAddress().getURI()).getUser();
+        return null;
+    }
 
 
+    private void cleanupLate(PendingSipInvite pending, SsrcTransaction restored) {
+        try {
+            if (videoLifecycleStore == null) return;
+            boolean cancelled = videoLifecycleStore.isStreamCancelled(pending.getStream());
+            if (!cancelled) {
+                String compact = pending.getStream().substring("managed_".length());
+                if (!compact.matches("[0-9a-fA-F]{32}")) return;
+                String generation = compact.substring(0, 8) + "-" + compact.substring(8, 12) + "-"
+                        + compact.substring(12, 16) + "-" + compact.substring(16, 20) + "-" + compact.substring(20);
+                com.zksy.video.lifecycle.VideoLifecycleRecord current = videoLifecycleStore.find(generation.toLowerCase(java.util.Locale.ROOT));
+                if (current == null) return; // Lost ownership evidence is not an instruction to stop a live camera.
+                cancelled = current.isCancelled() || "CLEANUP_PENDING".equals(current.getStatus())
+                        || "STOPPED".equals(current.getStatus()) || "FAILED".equals(current.getStatus());
+                // INVITE retransmissions can arrive long after healthy playback began. The
+                // original start deadline does not expire ACTIVE generations or their viewers.
+                if (!cancelled && !("STARTING".equals(current.getStatus()) && current.getDeadline() != null
+                        && current.getDeadline() <= System.currentTimeMillis())) return;
+            }
+            videoLifecycleStore.markStreamCancelled(pending.getStream());
+            // No default node, SDP-derived source or unscoped channel lookup is permitted here.
+            MediaServer node = mediaServerService.getOne(pending.getNodeId());
+            Device device = redisCatchStorage.getDevice(pending.getDeviceId());
+            DeviceChannel channel = deviceChannelService.getOneForSource(pending.getDeviceId(), pending.getChannelSipId());
+            if (node == null || device == null || channel == null || !Objects.equals(pending.getNodeId(), node.getId())
+                    || !Objects.equals(pending.getDeviceId(), device.getDeviceId())
+                    || !Objects.equals(pending.getChannelId(), channel.getId())
+                    || !Objects.equals(pending.getChannelSipId(), channel.getDeviceId())
+                    || !SipInviteSessionManager.sameDialog(restored, sessionManager.getSsrcTransactionByStream(pending.getApp(), pending.getStream()))) return;
+            playService.stopManaged(node, device, channel, pending.getStream());
+        } catch (RuntimeException ex) {
+            log.warn("[INVITE recovery] original-source cleanup remains pending");
+        }
+    }
 }
 }

+ 22 - 6
video-service/src/main/java/com/ruoyi/wvp/media/event/hook/Hook.java

@@ -1,6 +1,7 @@
 package com.ruoyi.wvp.media.event.hook;
 package com.ruoyi.wvp.media.event.hook;
 
 
 import lombok.Data;
 import lombok.Data;
+import java.util.Objects;
 
 
 /**
 /**
  * zlm hook事件的参数
  * zlm hook事件的参数
@@ -15,6 +16,9 @@ public class Hook {
 
 
     private String stream;
     private String stream;
 
 
+    /** null preserves the historical all-node subscription. */
+    private String mediaServerId;
+
     private Long expireTime;
     private Long expireTime;
 
 
 
 
@@ -28,24 +32,36 @@ public class Hook {
     }
     }
 
 
     public static Hook getInstance(HookType hookType, String app, String stream, String mediaServer) {
     public static Hook getInstance(HookType hookType, String app, String stream, String mediaServer) {
-        // TODO 后续修改所有方法
-        return Hook.getInstance(hookType, app, stream);
+        Hook hook = Hook.getInstance(hookType, app, stream);
+        hook.setMediaServerId(mediaServer);
+        return hook;
     }
     }
 
 
     @Override
     @Override
     public boolean equals(Object obj) {
     public boolean equals(Object obj) {
         if (obj instanceof Hook) {
         if (obj instanceof Hook) {
             Hook param = (Hook) obj;
             Hook param = (Hook) obj;
-            return param.getHookType().equals(this.hookType)
-                    && param.getApp().equals(this.app)
-                    && param.getStream().equals(this.stream);
+            return Objects.equals(param.getHookType(), this.hookType)
+                    && Objects.equals(param.getApp(), this.app)
+                    && Objects.equals(param.getStream(), this.stream)
+                    && Objects.equals(param.getMediaServerId(), this.mediaServerId);
         }else {
         }else {
             return false;
             return false;
         }
         }
     }
     }
 
 
+    @Override
+    public int hashCode() {
+        return Objects.hash(hookType, app, stream, mediaServerId);
+    }
+
     @Override
     @Override
     public String toString() {
     public String toString() {
-        return this.getHookType() + this.getApp() + this.getStream();
+        // Length framing prevents app/stream/node boundary collisions.
+        return hookType + ":" + part(app) + part(stream) + part(mediaServerId);
+    }
+
+    private static String part(String value) {
+        return value == null ? "-1:" : value.length() + ":" + value;
     }
     }
 }
 }

+ 50 - 24
video-service/src/main/java/com/ruoyi/wvp/media/event/hook/HookSubscribe.java

@@ -69,46 +69,72 @@ public class HookSubscribe {
         sendNotify(HookType.on_record_mp4, event);
         sendNotify(HookType.on_record_mp4, event);
     }
     }
 
 
-    private final Map<String, Event> allSubscribes = new ConcurrentHashMap<>();
-    private final Map<String, Hook> allHook = new ConcurrentHashMap<>();
+    /** Opaque owner identity; expiry and removal compare this exact registration. */
+    public static final class Subscription {
+        private final String key;
+        private final Hook hook;
+        private final Event event;
+        private final long expires;
+
+        private Subscription(Hook hook, Event event, long expires) {
+            this.key = hook.toString();
+            this.hook = hook;
+            this.event = event;
+            this.expires = expires;
+        }
+    }
+
+    private final Map<String, Subscription> allSubscribes = new ConcurrentHashMap<>();
 
 
     private void sendNotify(HookType hookType, MediaEvent event) {
     private void sendNotify(HookType hookType, MediaEvent event) {
-        Hook paramHook = Hook.getInstance(hookType, event.getApp(), event.getStream());
-        Event hookSubscribeEvent = allSubscribes.get(paramHook.toString());
-        if (hookSubscribeEvent != null) {
-            HookData data = HookData.getInstance(event);
-            hookSubscribeEvent.response(data);
+        String node = event.getMediaServer() == null ? null : event.getMediaServer().getId();
+        Subscription exact = node == null ? null : allSubscribes.get(
+                Hook.getInstance(hookType, event.getApp(), event.getStream(), node).toString());
+        Subscription wildcard = allSubscribes.get(Hook.getInstance(hookType, event.getApp(), event.getStream()).toString());
+        HookData data = HookData.getInstance(event);
+        notifyOwner(exact, data);
+        notifyOwner(wildcard, data);
+    }
+
+    private void notifyOwner(Subscription owner, HookData data) {
+        if (owner == null || allSubscribes.get(owner.key) != owner) return;
+        if (owner.expires < System.currentTimeMillis()) {
+            removeOwnedSubscribe(owner);
+            return;
         }
         }
+        owner.event.response(data);
     }
     }
 
 
     public void addSubscribe(Hook hook, Event event) {
     public void addSubscribe(Hook hook, Event event) {
-        if (hook.getExpireTime() == null) {
-            hook.setExpireTime(System.currentTimeMillis() + subscribeExpire);
-        }
-        allSubscribes.put(hook.toString(), event);
-        allHook.put(hook.toString(), hook);
+        addOwnedSubscribe(hook, event);
+    }
+
+    public Subscription addOwnedSubscribe(Hook hook, Event event) {
+        long expires = hook.getExpireTime() == null ? System.currentTimeMillis() + subscribeExpire : hook.getExpireTime();
+        Subscription owner = new Subscription(hook, event, expires);
+        allSubscribes.put(owner.key, owner);
+        return owner;
+    }
+
+    public boolean removeOwnedSubscribe(Subscription owner) {
+        return owner != null && allSubscribes.remove(owner.key, owner);
     }
     }
 
 
     public void removeSubscribe(Hook hook) {
     public void removeSubscribe(Hook hook) {
         allSubscribes.remove(hook.toString());
         allSubscribes.remove(hook.toString());
-        allHook.remove(hook.toString());
     }
     }
 
 
-    /**
-     * 对订阅数据进行过期清理
-     */
-    @Scheduled(fixedRate=subscribeExpire)   //每5分钟执行一次
+    @Scheduled(fixedRate=subscribeExpire)
     public void execute(){
     public void execute(){
-        long expireTime = System.currentTimeMillis();
-        for (Hook hook : allHook.values()) {
-            if (hook.getExpireTime() < expireTime) {
-                allSubscribes.remove(hook.toString());
-                allHook.remove(hook.toString());
-            }
+        long now = System.currentTimeMillis();
+        for (Subscription owner : allSubscribes.values()) {
+            if (owner.expires < now) removeOwnedSubscribe(owner);
         }
         }
     }
     }
 
 
     public List<Hook> getAll() {
     public List<Hook> getAll() {
-        return new ArrayList<>(allHook.values());
+        List<Hook> result = new ArrayList<>();
+        for (Subscription owner : allSubscribes.values()) result.add(owner.hook);
+        return result;
     }
     }
 }
 }

+ 10 - 0
video-service/src/main/java/com/ruoyi/wvp/service/IReceiveRtpServerService.java

@@ -10,4 +10,14 @@ public interface IReceiveRtpServerService {
     SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback);
     SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback);
 
 
     void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo);
     void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo);
+
+    /** Legacy names are reusable: close evidence belongs to this allocation and dialog, never the name. */
+    default boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) {
+        return false;
+    }
+
+    /** A void close or an empty media list is not positive close evidence. */
+    default boolean closeManagedRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
+        return false;
+    }
 }
 }

+ 380 - 26
video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java

@@ -1,8 +1,10 @@
 package com.ruoyi.wvp.service.impl;
 package com.ruoyi.wvp.service.impl;
 
 
+import com.ruoyi.wvp.common.InviteInfo;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.DynamicTask;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.conf.UserSetting;
 import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
 import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
+import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SSRCFactory;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.bean.MediaServer;
@@ -17,13 +19,19 @@ import com.ruoyi.wvp.service.bean.ErrorCallback;
 import com.ruoyi.wvp.service.bean.InviteErrorCode;
 import com.ruoyi.wvp.service.bean.InviteErrorCode;
 import com.ruoyi.wvp.service.bean.RTPServerParam;
 import com.ruoyi.wvp.service.bean.RTPServerParam;
 import com.ruoyi.wvp.service.bean.SSRCInfo;
 import com.ruoyi.wvp.service.bean.SSRCInfo;
+import com.zksy.video.lifecycle.VideoStopReceipts;
+import com.zksy.video.lifecycle.VideoStopReceipts.Allocation;
+import com.zksy.video.lifecycle.VideoStopReceipts.RtpState;
+import com.zksy.video.lifecycle.VideoStopReceipts.Snapshot;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.event.EventListener;
 import org.springframework.context.event.EventListener;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import java.util.Objects;
 import java.util.UUID;
 import java.util.UUID;
+import java.util.function.Predicate;
 
 
 @Slf4j
 @Slf4j
 @Service
 @Service
@@ -65,8 +73,303 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
 
 
     }
     }
 
 
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
+    @Autowired
+    private VideoStopReceipts stopReceipts;
+
+    // Only callback/timer ownership is local. No field here is stop evidence.
+    private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> managedRtp = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private static final class ManagedRtp {
+        private final SSRCInfo info;
+        private HookSubscribe.Subscription owner;
+        private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
+        private ManagedRtp(SSRCInfo info) { this.info = info; }
+    }
+
+    private String managedKey(MediaServer node, String stream) {
+        return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString();
+    }
+
+    private boolean reserveAllocation(MediaServer node, SSRCInfo info, boolean externalSsrc) {
+        if (stopReceipts == null) return false;
+        return stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+            if (!snapshot.canReplaceAllocation()) return null;
+            if (info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
+            Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
+            allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.INTENT;
+            allocation.poolTracked = !externalSsrc; allocation.externalSsrc = externalSsrc;
+            snapshot.allocation = allocation;
+            VideoStopReceipts.Play play = snapshot.plays.get(info.getStream());
+            if (play != null) play.allocationToken = allocation.token;
+            return snapshot;
+        }) != null;
+    }
+
+    private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next) {
+        return allocationState(node, info, expected, next, snapshot -> true);
+    }
+
+    private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next,
+                                    Predicate<Snapshot> actorGuard) {
+        if (stopReceipts == null) return false;
+        for (int attempt = 0; attempt < 4; attempt++) {
+            Snapshot updated = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+                Allocation allocation = snapshot.allocation;
+                if (allocation == null || !allocation.matches(info) || allocation.state != expected || !actorGuard.test(snapshot)) return null;
+                if (next == RtpState.CREATING && info.getStream().startsWith("managed_")
+                        && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
+                allocation.state = next; allocation.port = info.getPort(); return snapshot;
+            });
+            if (updated != null) return true;
+            Snapshot latest = stopReceipts.read(node.getId(), info.getStream());
+            if (latest == null || latest.allocation == null || !latest.allocation.matches(info)
+                    || latest.allocation.state != expected) return false;
+        }
+        return false;
+    }
+
+    private boolean closeAllocation(MediaServer node, SSRCInfo info) {
+        return closeAllocation(node, info, snapshot -> true);
+    }
+
+    private boolean closeAllocation(MediaServer node, SSRCInfo info, Predicate<Snapshot> actorGuard) {
+        if (stopReceipts == null || info == null || info.getStream() == null || info.getTimeOutTaskKey() == null
+                || info.getSsrc() == null || !"rtp".equals(info.getApp())) return false;
+        Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
+        if ((retained == null || retained.allocation == null) && !info.getStream().startsWith("managed_")) {
+            // Pre-upgrade legacy callers retain the original typed allocation. Never replace a newer token,
+            // reconstruct a managed/adopted receipt, or treat absence as a positive stop acknowledgement.
+            retained = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
+                if (snapshot.allocation != null || !snapshot.plays.isEmpty() || !actorGuard.test(snapshot)
+                        || (sessionManager != null && sessionManager.isAdoptedAllocation(node.getId(), info))) return null;
+                Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
+                allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.OPEN;
+                snapshot.allocation = allocation; return snapshot;
+            });
+        }
+        if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !actorGuard.test(retained)) return false;
+        if (retained.allocation.terminal()) return true;
+        if (retained.allocation.state == RtpState.INTENT) {
+            // CAS competes with the creator's INTENT -> CREATING, so this is positive never-created evidence.
+            return allocationState(node, info, RtpState.INTENT, RtpState.NEVER_CREATED, actorGuard);
+        }
+        // A process lost during create/close cannot infer completion or send another name-based command.
+        if (!allocationState(node, info, RtpState.OPEN, RtpState.CLOSING, actorGuard)) return false;
+        try {
+            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
+                // Boolean true is the ZLM adapter's code=0/hit=1 receipt, not a request-send result.
+                // Retry only shared state CAS inside allocationState, never the external name-close.
+                if (!Boolean.TRUE.equals(closed)) return;
+                if (!allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED)) return;
+                // A late positive receipt must finish pool cleanup even when the caller already
+                // returned and no second stop is ever issued.
+                try { releaseClosedSsrc(node, info); }
+                catch (RuntimeException ex) { log.warn("[RTP close return] {}/{}: {}", node.getId(), info.getStream(), ex.getMessage()); }
+            });
+        } catch (RuntimeException ex) {
+            log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage());
+        }
+        Snapshot after = stopReceipts.read(node.getId(), info.getStream());
+        return after != null && after.allocation != null && after.allocation.matches(info)
+                && after.allocation.state == RtpState.CLOSED;
+    }
+
+    private boolean cancelled(String stream) {
+        // Managed resource creation fails closed without the cancellation persistence seam.
+        return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
+    }
+
+    private SSRCInfo openManagedRtp(RTPServerParam param, ErrorCallback<OpenRTPServerResult> callback) {
+        MediaServer node = param.getMediaServerItem();
+        String stream = param.getStreamId();
+        if (callback == null || node == null || node.getId() == null || !node.isRtpEnable()
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || cancelled(stream)) {
+            if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null);
+            return null;
+        }
+        // The stream is a single-use generation identity; use it for the pool request too,
+        // so cancellation can fence/recover an acquisition whose reply was lost before RTP registration.
+        ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, stream));
+        if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
+            callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
+            return null;
+        }
+        try {
+            entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId(), entry.info.getTimeOutTaskKey()));
+            if (!reserveAllocation(node, entry.info, false)) {
+                Snapshot current = stopReceipts.read(node.getId(), stream);
+                if (current == null || current.allocation == null || !current.allocation.matches(entry.info))
+                    releaseManagedSsrc(node, entry);
+                callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation is already retained", null);
+                return null;
+            }
+            if (cancelled(stream)) {
+                closeManagedRTPServer(node, entry.info);
+                return null;
+            }
+            if (!allocationState(node, entry.info, RtpState.INTENT, RtpState.CREATING)) {
+                closeManagedRTPServer(node, entry.info); return null;
+            }
+            int port = mediaServerService.createRTPServer(node, stream,
+                    param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0,
+                    0, false, param.isDisableAudio(), false, param.getTcpMode());
+            entry.info.setPort(port);
+            // Only the creator knows create returned. Restart during create remains CREATING.
+            if (!allocationState(node, entry.info, RtpState.CREATING, RtpState.OPEN)) {
+                // The port was already created above. A failed receipt transition must not leak it:
+                // close the exact allocation instead of returning silently.
+                closeManagedRTPServer(node, entry.info);
+                callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP receipt not acknowledged", null);
+                return null;
+            }
+            if (port <= 0 || cancelled(stream) || entry.terminal.get()) {
+                closeManagedRTPServer(node, entry.info);
+                callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null);
+                return null;
+            }
+            OpenRTPServerResult result = new OpenRTPServerResult(); result.setSsrcInfo(entry.info);
+            Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId());
+            entry.owner = subscribe.addOwnedSubscribe(hook, data -> {
+                if (data.getMediaServer() == null || !node.getId().equals(data.getMediaServer().getId())
+                        || !stream.equals(data.getStream()) || !"rtp".equals(data.getApp())
+                        || data.getMediaInfo() == null || !stream.equals(data.getMediaInfo().getStream())
+                        || !"rtp".equals(data.getMediaInfo().getApp())
+                        || (data.getMediaInfo().getMediaServer() != null
+                        && !node.getId().equals(data.getMediaInfo().getMediaServer().getId()))) return;
+                if (!entry.terminal.compareAndSet(false, true)) return;
+                try {
+                    dynamicTask.stop(entry.info.getTimeOutTaskKey());
+                    if (cancelled(stream)) {
+                        closeManagedRTPServer(node, entry.info);
+                        callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
+                        return;
+                    }
+                    result.setHookData(data);
+                    callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), result);
+                } finally {
+                    subscribe.removeOwnedSubscribe(entry.owner);
+                }
+            });
+            if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
+            dynamicTask.startDelay(entry.info.getTimeOutTaskKey(), () -> {
+                if (!entry.terminal.compareAndSet(false, true)) return;
+                try { closeManagedRTPServer(node, entry.info); }
+                finally { callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), "Managed RTP timed out", result); }
+            }, userSetting.getPlayTimeout());
+            // Cancellation may have raced creation/registration. Never hand out that resource.
+            if (cancelled(stream)) {
+                closeManagedRTPServer(node, entry.info);
+                callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
+                return null;
+            }
+            if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey());
+            return entry.info;
+        } catch (RuntimeException ex) {
+            // An ambiguous create/receipt write is not proof that the port never existed.
+            closeManagedRTPServer(node, entry.info);
+            callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null);
+            return null;
+        }
+    }
+
+    private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) {
+        if (entry.info.getSsrc() != null) {
+            ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc(), entry.info.getTimeOutTaskKey());
+        }
+    }
+
+    /** A completed port close is not full cleanup until its pool allocation was returned.
+     * The Factory receipt is atomic with SADD and remains valid after the SN is reused. */
+    private boolean releaseClosedSsrc(MediaServer node, SSRCInfo info) {
+        Snapshot snapshot = stopReceipts.read(node.getId(), info.getStream());
+        if (snapshot == null || snapshot.allocation == null || !snapshot.allocation.matches(info)
+                || !snapshot.allocation.terminal()) return false;
+        Allocation allocation = snapshot.allocation;
+        if (allocation.externalSsrc || allocation.poolSsrc() == null || allocation.poolReturned) return true;
+        String poolSsrc = allocation.poolSsrc(), token = allocation.token;
+        if (ssrcFactory.wasReleased(node.getId(), poolSsrc, token)) return true;
+        // Return the originally allocated number, never a device-negotiated SSRC.
+        boolean released = allocation.poolTracked
+                ? ssrcFactory.releaseSsrc(node.getId(), poolSsrc, token)
+                : ssrcFactory.releaseObservedLegacySsrc(node.getId(), poolSsrc, token);
+        return released || ssrcFactory.wasReleased(node.getId(), poolSsrc, token);
+    }
+
+    @Override
+    public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) {
+        if (node == null || node.getId() == null || info == null || info.getStream() == null
+                || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false;
+        if (stopReceipts != null) {
+            Snapshot pending = stopReceipts.read(node.getId(), info.getStream());
+            VideoStopReceipts.Play intent = pending == null ? null : pending.plays.get(info.getStream());
+            if (pending != null && pending.allocation == null && intent != null && intent.cancelled
+                    && !intent.inviteSent && info.getStream().equals(info.getTimeOutTaskKey()))
+                return ssrcFactory.cancelAllocation(node.getId(), info.getStream());
+        }
+        ManagedRtp entry = managedRtp.get(managedKey(node, info.getStream()));
+        if (entry != null) {
+            entry.terminal.set(true);
+            try {
+                if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey());
+            } catch (RuntimeException ex) {
+                log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage());
+            } finally { subscribe.removeOwnedSubscribe(entry.owner); }
+        }
+        boolean closed = closeAllocation(node, info);
+        return closed && releaseClosedSsrc(node, info);
+    }
+
+    /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
+    private final java.util.Map<String, LegacyRtp> legacyRtp = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private static final class LegacyRtp {
+        private final SSRCInfo info;
+        private HookSubscribe.Subscription owner;
+        private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
+        private LegacyRtp(SSRCInfo info) { this.info = info; }
+    }
+
+    @Override
+    public synchronized boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) {
+        if (node == null || node.getId() == null || !node.isRtpEnable() || info == null
+                || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp())
+                || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null
+                || sessionManager == null || stopReceipts == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false;
+        String key = managedKey(node, info.getStream());
+        LegacyRtp entry = legacyRtp.get(key);
+        if (entry != null && !entry.info.equals(info)) entry = null; // stale local timer owner is not allocation evidence
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream());
+        if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc())
+                || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false;
+        Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
+        if (retained == null || retained.allocation == null || !retained.allocation.matches(info)
+                || !callId.equals(retained.allocation.callId)) return false;
+        com.ruoyi.wvp.gb28181.bean.SsrcTransaction expected = retained.plays.values().stream()
+                .filter(play -> java.util.Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
+                        && play.dialog != null && callId.equals(play.dialog.getCallId()))
+                .map(play -> play.dialog).findFirst().orElse(null);
+        if (expected == null || !sessionManager.isAdopted(expected)
+                || (current != null && !SipInviteSessionManager.sameDialog(expected, current))) return false;
+        if (entry != null) entry.terminal.set(true);
+        try { dynamicTask.stop(info.getTimeOutTaskKey()); }
+        catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
+        finally { if (entry != null) subscribe.removeOwnedSubscribe(entry.owner); }
+        boolean closed = closeAllocation(node, info, snapshot -> originalActor(snapshot, info, expected));
+        return closed && releaseClosedSsrc(node, info);
+    }
+
     @Override
     @Override
     public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
     public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
+        if (rtpServerParam.getStreamId() != null && rtpServerParam.getStreamId().startsWith("managed_")) {
+            return openManagedRtp(rtpServerParam, callback);
+        }
+        return openLegacyRtp(rtpServerParam, callback);
+    }
+
+    private synchronized SSRCInfo openLegacyRtp(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
         if (callback == null) {
         if (callback == null) {
             log.warn("[开启RTP收流] 失败,回调为NULL");
             log.warn("[开启RTP收流] 失败,回调为NULL");
             return null;
             return null;
@@ -77,14 +380,15 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         }
         }
 
 
         // 获取mediaServer可用的ssrc
         // 获取mediaServer可用的ssrc
+        final String timeOutTaskKey = UUID.randomUUID().toString();
         final String ssrc;
         final String ssrc;
         if (rtpServerParam.getPresetSsrc() != null) {
         if (rtpServerParam.getPresetSsrc() != null) {
             ssrc = rtpServerParam.getPresetSsrc();
             ssrc = rtpServerParam.getPresetSsrc();
         }else {
         }else {
             if (rtpServerParam.isPlayback()) {
             if (rtpServerParam.isPlayback()) {
-                ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId());
+                ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
             }else {
             }else {
-                ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId());
+                ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
             }
             }
         }
         }
         final String streamId;
         final String streamId;
@@ -97,6 +401,19 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
             // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
         }
         }
+        // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
+        SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
+        LegacyRtp entry = new LegacyRtp(ssrcInfo);
+        String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
+        if (!reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) {
+            if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
+            callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
+            return null;
+        }
+        legacyRtp.put(allocationKey, entry);
+        if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.INTENT, RtpState.CREATING)) {
+            closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); return null;
+        }
         int rtpServerPort;
         int rtpServerPort;
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
@@ -105,58 +422,95 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         } else {
         } else {
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
         }
         }
+        ssrcInfo.setPort(rtpServerPort);
+        if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.CREATING, RtpState.OPEN)) {
+            // A created port must be closed even when the receipt transition did not commit.
+            closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo);
+            callback.run(InviteErrorCode.FAIL.getCode(), "RTP receipt not acknowledged", null);
+            return null;
+        }
         if (rtpServerPort == 0) {
         if (rtpServerPort == 0) {
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             // 释放ssrc
             // 释放ssrc
             if (rtpServerParam.getPresetSsrc() == null) {
             if (rtpServerParam.getPresetSsrc() == null) {
-                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
+                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
             }
             }
             return null;
             return null;
         }
         }
 
 
-        // 设置流超时的定时任务
-        String timeOutTaskKey = UUID.randomUUID().toString();
-
-        SSRCInfo ssrcInfo = new SSRCInfo(rtpServerPort, ssrc, "rtp", streamId, timeOutTaskKey);
         OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
         OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
         openRTPServerResult.setSsrcInfo(ssrcInfo);
         openRTPServerResult.setSsrcInfo(ssrcInfo);
 
 
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         dynamicTask.startDelay(timeOutTaskKey, () -> {
         dynamicTask.startDelay(timeOutTaskKey, () -> {
-            // 收流超时
-            // 释放ssrc
-            if (rtpServerParam.getPresetSsrc() == null) {
-                ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
-            }
-            // 关闭收流端口
-            mediaServerService.closeRTPServer(rtpServerParam.getMediaServerItem(), streamId);
-            subscribe.removeSubscribe(rtpHook);
+            if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
+            // Close through the shared allocation fence; never release an unknown allocation's SSRC early.
+            closeRTPServer(rtpServerParam.getMediaServerItem(), ssrcInfo);
+            subscribe.removeOwnedSubscribe(entry.owner);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
         }, userSetting.getPlayTimeout());
         }, userSetting.getPlayTimeout());
         // 开启流到来的监听
         // 开启流到来的监听
-        subscribe.addSubscribe(rtpHook, (hookData) -> {
+        entry.owner = subscribe.addOwnedSubscribe(rtpHook, (hookData) -> {
+            if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
             dynamicTask.stop(timeOutTaskKey);
             dynamicTask.stop(timeOutTaskKey);
             // hook响应
             // hook响应
             openRTPServerResult.setHookData(hookData);
             openRTPServerResult.setHookData(hookData);
-            callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult);
-            subscribe.removeSubscribe(rtpHook);
+            try {
+                callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult);
+            } finally {
+                subscribe.removeOwnedSubscribe(entry.owner);
+            }
         });
         });
+        if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
 
 
         return ssrcInfo;
         return ssrcInfo;
     }
     }
 
 
+    /** Peer BYE/offline must use the original Invite and dialog, never the name's current allocation. */
+    public boolean closeRTPServerForSession(SsrcTransaction original, InviteInfo invite) {
+        if (original == null || sessionManager == null || stopReceipts == null
+                || !SipInviteSessionManager.sameDialog(original,
+                sessionManager.getSsrcTransactionByStream(original.getApp(), original.getStream()))) return false;
+        SSRCInfo info = invite == null ? sessionManager.getAdoptedAllocation(original) : invite.getSsrcInfo();
+        if (info == null || !Objects.equals(original.getApp(), info.getApp())
+                || !Objects.equals(original.getStream(), info.getStream()) || !Objects.equals(original.getSsrc(), info.getSsrc())
+                || (invite != null && (!Objects.equals(original.getMediaServerId(), invite.getMediaServerId())
+                || !Objects.equals(original.getDeviceId(), invite.getDeviceId()) || !Objects.equals(original.getChannelId(), invite.getChannelId())
+                || original.getType() != invite.getType() || !Objects.equals(original.getStream(), invite.getStream())))) return false;
+        MediaServer node = mediaServerService.getOne(original.getMediaServerId());
+        if (node == null || !Objects.equals(original.getMediaServerId(), node.getId())) return false;
+        if (info.getStream().startsWith("managed_")) {
+            if (!stopReceipts.retainDialog(original)) return false;
+            return closeManagedRTPServer(node, info);
+        }
+        if (sessionManager.isAdopted(original)) return closeAdoptedRTPServer(node, info, original.getCallId());
+        return closeLegacyRtp(node, info, snapshot -> originalActor(snapshot, info, original));
+    }
+
+    private boolean originalActor(Snapshot snapshot, SSRCInfo info, SsrcTransaction original) {
+        return (snapshot.allocation == null || snapshot.allocation.callId == null
+                || Objects.equals(snapshot.allocation.callId, original.getCallId()))
+                && snapshot.plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
+                && play.dialog != null && !SipInviteSessionManager.sameDialog(original, play.dialog));
+    }
+
     @Override
     @Override
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
-        if (mediaServer == null) {
+        if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
+            closeManagedRTPServer(mediaServer, ssrcInfo);
             return;
             return;
         }
         }
-        if (ssrcInfo.getTimeOutTaskKey() != null) {
-            dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
-        }
-        if (ssrcInfo.getSsrc() != null) {
-            // 释放ssrc
-            ssrcFactory.releaseSsrc(mediaServer.getId(), ssrcInfo.getSsrc());
+        closeLegacyRtp(mediaServer, ssrcInfo, snapshot -> true);
+    }
+
+    private boolean closeLegacyRtp(MediaServer mediaServer, SSRCInfo ssrcInfo, Predicate<Snapshot> actorGuard) {
+        if (mediaServer == null || mediaServer.getId() == null || ssrcInfo == null || ssrcInfo.getStream() == null) return false;
+        if (ssrcInfo.getTimeOutTaskKey() != null) dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
+        LegacyRtp entry = legacyRtp.get(managedKey(mediaServer, ssrcInfo.getStream()));
+        if (entry != null && entry.info.equals(ssrcInfo)) {
+            entry.terminal.set(true); subscribe.removeOwnedSubscribe(entry.owner);
         }
         }
-        mediaServerService.closeRTPServer(mediaServer, ssrcInfo.getStream());
+        boolean closed = closeAllocation(mediaServer, ssrcInfo, actorGuard);
+        return closed && releaseClosedSsrc(mediaServer, ssrcInfo);
     }
     }
 }
 }

+ 9 - 1
video-service/src/main/java/com/zksy/video/ManualVideoController.java

@@ -10,5 +10,13 @@ public class ManualVideoController {
     private final ManualVideoService service;
     private final ManualVideoService service;
     public ManualVideoController(ManualVideoService service) {this.service=service;}
     public ManualVideoController(ManualVideoService service) {this.service=service;}
     @PostMapping("/start") public AjaxResult start(@RequestBody Map<String,String> input) {return AjaxResult.success(service.start(input.get("id"),input.get("url")));}
     @PostMapping("/start") public AjaxResult start(@RequestBody Map<String,String> input) {return AjaxResult.success(service.start(input.get("id"),input.get("url")));}
-    @PostMapping("/stop") public AjaxResult stop(@RequestBody Map<String,String> input) {service.stop(input.get("key"));return AjaxResult.success();}
+    @PostMapping("/stop") public AjaxResult stop(@RequestBody Map<String,String> input) {
+        if (input.containsKey("mediaServerId")) {
+            return service.stop(input.get("mediaServerId"), input.get("key"))
+                    ? AjaxResult.success() : AjaxResult.error("代理节点未知或尚未确认回收");
+        }
+        // Key-only compatibility is limited to handles this process actually received; no default-node guess.
+        try { service.stop(input.get("key")); return AjaxResult.success(); }
+        catch (IllegalStateException unknown) { return AjaxResult.error(unknown.getMessage()); }
+    }
 }
 }

+ 100 - 17
video-service/src/main/java/com/zksy/video/ManualVideoService.java

@@ -9,6 +9,9 @@ import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.StreamInfo;
+import com.ruoyi.wvp.media.bean.MediaInfo;
+import com.zksy.video.lifecycle.VideoLifecycleMedia;
 
 
 @Service
 @Service
 public class ManualVideoService {
 public class ManualVideoService {
@@ -16,25 +19,105 @@ public class ManualVideoService {
     private final ZLMRESTfulUtils zlm;
     private final ZLMRESTfulUtils zlm;
     private final ObjectMapper json;
     private final ObjectMapper json;
     public ManualVideoService(IMediaServerService servers,ZLMRESTfulUtils zlm,ObjectMapper json) {this.servers=servers;this.zlm=zlm;this.json=json;}
     public ManualVideoService(IMediaServerService servers,ZLMRESTfulUtils zlm,ObjectMapper json) {this.servers=servers;this.zlm=zlm;this.json=json;}
+    /** 旧入口仅记本进程亲自收到的 actual key -> 节点;重启后未知 key 拒绝猜测。 */
+    private final Map<String, String> legacyNodes = new java.util.concurrent.ConcurrentHashMap<>();
+    private final Map<String, LegacyProxy> legacyProxies = new java.util.concurrent.ConcurrentHashMap<>();
+    private static final class LegacyProxy {
+        private final String id, url, stream, node, key;
+        private LegacyProxy(String id, String url, String stream, String node, String key) {
+            this.id = id; this.url = url; this.stream = stream; this.node = node; this.key = key;
+        }
+    }
+    public synchronized Map<String, Object> start(String id, String url) { return start(id, url, "manual_" + id); }
+
+    public synchronized Map<String, Object> start(String id, String url, String stream) {
+        LegacyProxy confirmed = legacyProxies.get(stream);
+        String node = confirmed == null ? selectMediaServer() : confirmed.node;
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("stream", stream); result.put("mediaServerId", node);
+        if (confirmed != null && (!Objects.equals(id, confirmed.id) || !Objects.equals(url, confirmed.url))) {
+            result.put("status", "CLEANUP_PENDING");
+            return result;
+        }
+        String key = confirmed == null ? start(node, id, url, stream) : confirmed.key;
+        if (key != null) {
+            result.put("proxyKey", key); legacyNodes.put(key, node);
+            legacyProxies.put(stream, new LegacyProxy(id, url, stream, node, key));
+        }
+        try {
+            Map<String, Object> media = key == null ? null : status(node, stream, url);
+            if (media != null) result.putAll(media);
+            result.put("status", key == null ? "CLEANUP_PENDING" : media == null ? "STARTING" : "ACTIVE");
+        } catch (RuntimeException unknown) { result.put("status", "CLEANUP_PENDING"); }
+        return result;
+    }
+
+    /** 受管入口:节点和流已持久化;只返回 add 的真实 key,绝不拼接代理句柄。 */
+    public String start(String mediaServerId, String id, String url, String stream) {
+        if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("视频设备编号无效");
+        if (stream == null || !stream.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("拉流名称无效");
+        URI uri = URI.create(url);
+        if (uri.getHost() == null || !Set.of("rtsp", "rtsps", "rtmp", "rtmps").contains(uri.getScheme().toLowerCase(Locale.ROOT)))
+            throw new IllegalArgumentException("拉流地址必须使用 RTSP 或 RTMP");
+        MediaServer server = recordedServer(mediaServerId);
+        if (VideoLifecycleMedia.findMedia(zlm, server, "city_video", stream) != null) return null;
+        JSONObject response = zlm.addStreamProxy(server, "city_video", stream, url, true, false, "0", 15);
+        if (response == null || !Integer.valueOf(0).equals(response.getInteger("code")))
+            throw new IllegalStateException("手动拉流结果未知或失败");
+        JSONObject data = response.getJSONObject("data");
+        Object key = data == null ? null : data.get("key");
+        return key instanceof String && !((String) key).isBlank() ? (String) key : null;
+    }
+    public String selectMediaServer() {
+        MediaServer server = servers.getDefaultMediaServer();
+        if (server == null || server.getId() == null || !server.isStatus() || !"zlm".equals(server.getType()))
+            throw new IllegalArgumentException("媒体节点未上线");
+        return server.getId();
+    }
+
+    /** 只定位持久化节点;这里绝不选择默认节点。 */
+    public MediaServer recordedServer(String mediaServerId) {
+        MediaServer server = mediaServerId == null ? null : servers.getOne(mediaServerId);
+        if (server == null || !mediaServerId.equals(server.getId()) || !server.isStatus()
+                || !"zlm".equals(server.getType())) throw new IllegalStateException("记录的媒体节点不可用");
+        return server;
+    }
+
     @SuppressWarnings("unchecked")
     @SuppressWarnings("unchecked")
-    public synchronized Map<String,Object> start(String id,String url) {
-        if(id==null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("视频设备编号无效");
-        URI uri=URI.create(url);
-        if(uri.getHost()==null || !Set.of("rtsp","rtsps","rtmp","rtmps").contains(uri.getScheme())) throw new IllegalArgumentException("拉流地址必须使用 RTSP 或 RTMP");
-        MediaServer server=servers.getDefaultMediaServer();
-        if(server==null) throw new IllegalArgumentException("媒体节点未上线");
-        String stream="manual_"+id,key="__defaultVhost__/city_video/"+stream;
-        if(servers.getStreamInfoByAppAndStreamWithCheck("city_video",stream,server.getId(),false)==null) {
-            JSONObject result=zlm.addStreamProxy(server,"city_video",stream,url,true,false,"0",15);
-            if(result==null || result.getIntValue("code")!=0) throw new IllegalArgumentException("手动设备拉流失败,请检查视频地址与设备网络");
-            JSONObject data=result.getJSONObject("data"); if(data!=null && data.getString("key")!=null) key=data.getString("key");
+    public Map<String, Object> status(String mediaServerId, String stream, String url) {
+        MediaServer server = recordedServer(mediaServerId);
+        JSONObject live = VideoLifecycleMedia.findMedia(zlm, server, "city_video", stream);
+        if (live == null) return null;
+        if (!Integer.valueOf(4).equals(live.getInteger("originType")) || !url.equals(live.getString("originUrl")))
+            throw new IllegalStateException("实际媒体与手动拉流来源不匹配");
+        StreamInfo info = servers.getStreamInfoByAppAndStream(server, "city_video", stream,
+                MediaInfo.getInstance(live, server, null), null);
+        if (info == null) throw new IllegalStateException("无法生成已确认媒体的播放信息");
+        Map<String, Object> result = json.convertValue(new StreamContent(info), Map.class);
+        result.put("app", "city_video"); result.put("stream", stream); result.put("mediaServerId", mediaServerId);
+        return result;
+    }
+
+    /** 只能用真实 add 响应的 key,在已记录节点上确认删除成功。 */
+    public synchronized boolean stop(String mediaServerId, String key) {
+        if (mediaServerId == null || mediaServerId.isBlank() || key == null || key.isBlank()) return false;
+        try {
+            MediaServer server = recordedServer(mediaServerId);
+            JSONObject result = zlm.delStreamProxy(server, key);
+            if (result == null || !Integer.valueOf(0).equals(result.getInteger("code"))) return false;
+            JSONObject data = result.getJSONObject("data");
+            if (data == null || !Boolean.TRUE.equals(data.get("flag"))) return false;
+            legacyNodes.remove(key, mediaServerId);
+            legacyProxies.entrySet().removeIf(entry -> mediaServerId.equals(entry.getValue().node) && key.equals(entry.getValue().key));
+            return true;
+        } catch (RuntimeException unavailable) {
+            return false;
         }
         }
-        Map<String,Object> result=json.convertValue(new StreamContent(servers.getStreamInfoByAppAndStream(server,"city_video",stream,null,null)),Map.class);
-        result.put("proxyKey",key);return result;
     }
     }
-    public void stop(String key) {
-        if(key==null || !key.startsWith("__defaultVhost__/city_video/manual_")) throw new IllegalArgumentException("无效拉流会话");
-        MediaServer server=servers.getDefaultMediaServer();
-        if(server!=null) zlm.delStreamProxy(server,key);
+
+    public synchronized void stop(String key) {
+        String node = key == null ? null : legacyNodes.get(key);
+        if (node == null || !stop(node, key)) throw new IllegalStateException("代理节点未知或尚未确认回收");
+        legacyNodes.remove(key, node);
     }
     }
 }
 }

+ 5 - 1
video-service/src/main/java/com/zksy/video/VideoApplication.java

@@ -13,7 +13,11 @@ import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
 import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
 
 
 @EnableScheduling
 @EnableScheduling
-@MapperScan(basePackages={"com.zksy.video","com.ruoyi.wvp.mapper"})
+// Scan only interfaces annotated with @Mapper. Declaring @MapperScan at all disables the
+// starter's automatic scan, so both packages must be listed; the annotation filter keeps
+// ordinary interfaces (e.g. VideoLifecycleStore) from being registered as mappers.
+@MapperScan(basePackages = {"com.zksy.video", "com.ruoyi.wvp.mapper"},
+        annotationClass = org.apache.ibatis.annotations.Mapper.class)
 @SpringBootApplication(scanBasePackages = {"com.zksy.video", "com.ruoyi.wvp"}, exclude = {DataSourceAutoConfiguration.class,UserDetailsServiceAutoConfiguration.class})
 @SpringBootApplication(scanBasePackages = {"com.zksy.video", "com.ruoyi.wvp"}, exclude = {DataSourceAutoConfiguration.class,UserDetailsServiceAutoConfiguration.class})
 public class VideoApplication {
 public class VideoApplication {
     public static void main(String[] args) { SpringApplication.run(VideoApplication.class, args); }
     public static void main(String[] args) { SpringApplication.run(VideoApplication.class, args); }

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä