فهرست منبع

feat(cockpit): 采集记录增加逐指标阈值评估

- 新增 CollectionRecordAssessmentService 与 CollectionMetricBinding,按设备阈值只读评估采集记录
- 响应结构增加 Assessment(状态、等级、等级颜色、原因),数值颜色与等级点互不替代
- 阈值读取失败只隔离数据访问异常,保留原采集记录并明确日志
- 补充采集评估单测与规则模块打包测试
Kazerin 2 هفته پیش
والد
کامیت
41f87175fc

+ 25 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/collectionRecords/CockpitCollectionRecordsResponse.java

@@ -79,15 +79,40 @@ public class CockpitCollectionRecordsResponse {
         private final String value;
         private final String display;
         private final boolean alarm;
+        private final Assessment assessment;
         public Cell(String key, String value, String display, boolean alarm) {
+            this(key, value, display, alarm, null);
+        }
+        public Cell(String key, String value, String display, boolean alarm, Assessment assessment) {
             this.key = key;
             this.value = value;
             this.display = display;
             this.alarm = alarm;
+            this.assessment = assessment;
         }
         public String getKey() { return key; }
         public String getValue() { return value; }
         public String getDisplay() { return display; }
         public boolean isAlarm() { return alarm; }
+        public Assessment getAssessment() { return assessment; }
+    }
+
+    /** 数值颜色取status,等级点取levelColor,二者互不替代。 */
+    public static class Assessment {
+        private final String status;
+        private final Integer level;
+        private final String levelColor;
+        private final String reason;
+
+        public Assessment(String status, Integer level, String reason) {
+            this.status = status;
+            this.level = level;
+            this.levelColor = level == null ? null : new String[]{"RED", "YELLOW", "BLUE", "GREEN"}[level - 1];
+            this.reason = reason;
+        }
+        public String getStatus() { return status; }
+        public Integer getLevel() { return level; }
+        public String getLevelColor() { return levelColor; }
+        public String getReason() { return reason; }
     }
 }

+ 22 - 2
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/collectionRecords/CockpitCollectionRecordsService.java

@@ -2,12 +2,16 @@ package com.zksy.cockpit.collectionRecords;
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.alarm.domain.WarningThreshold;
 import com.zksy.base.mapper.EquipmentBaseMapper;
 import com.zksy.base.perception.domain.vo.EquipmentProfileVO;
 import com.zksy.base.perception.service.PerceptionService;
 import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
 import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
 import org.springframework.stereotype.Service;
+import org.springframework.dao.DataAccessException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.util.ArrayList;
 import java.util.Comparator;
@@ -18,12 +22,16 @@ import java.util.Map;
 @Service
 public class CockpitCollectionRecordsService {
     private static final int MAX_RECORDS = 50;
+    private static final Logger log = LoggerFactory.getLogger(CockpitCollectionRecordsService.class);
     private final EquipmentBaseMapper equipmentMapper;
     private final PerceptionService perceptionService;
+    private final CollectionRecordAssessmentService assessmentService;
 
-    public CockpitCollectionRecordsService(EquipmentBaseMapper equipmentMapper, PerceptionService perceptionService) {
+    public CockpitCollectionRecordsService(EquipmentBaseMapper equipmentMapper, PerceptionService perceptionService,
+                                           CollectionRecordAssessmentService assessmentService) {
         this.equipmentMapper = equipmentMapper;
         this.perceptionService = perceptionService;
+        this.assessmentService = assessmentService;
     }
 
     public CockpitCollectionRecordsResponse load(String requestId, String deviceCode) {
@@ -52,6 +60,17 @@ public class CockpitCollectionRecordsService {
             columns.add(new CockpitCollectionRecordsResponse.Column(column.getKey(), column.getLabel(),
                     column.getUnit(), column.isAlarm()));
         }
+        Map<String, WarningThreshold> thresholds = java.util.Collections.emptyMap();
+        boolean rulesAvailable = true;
+        if (!source.getRows().isEmpty()) {
+            try {
+                thresholds = assessmentService.loadThresholds(deviceCode);
+            } catch (DataAccessException exception) {
+                // 阈值是附加信息:只隔离明确的数据访问失败,不吞程序错误,也不伪装为未配置。
+                log.warn("采集记录阈值读取失败,保留原采集记录: deviceCode={}", deviceCode, exception);
+                rulesAvailable = false;
+            }
+        }
         List<CockpitCollectionRecordsResponse.Row> rows = new ArrayList<>();
         int rowIndex = 0;
         for (EquipmentProfileVO.RecordRow row : source.getRows()) {
@@ -66,7 +85,8 @@ public class CockpitCollectionRecordsService {
                         && cell.getDisplay() != null && cell.getDisplay().endsWith(":—");
                 cells.add(new CockpitCollectionRecordsResponse.Cell(cell.getKey(),
                         missing || unknownFactor || "—".equals(cell.getValue()) ? null : cell.getValue(),
-                        missing ? "—" : indicatorDisplay(cell.getKey(), cell.getDisplay()), !missing && cell.isAlarm()));
+                        missing ? "—" : indicatorDisplay(cell.getKey(), cell.getDisplay()), !missing && cell.isAlarm(),
+                        assessmentService.assess(profile.getOrigCollTable(), cell.getKey(), raw, thresholds, rulesAvailable)));
             }
             rows.add(new CockpitCollectionRecordsResponse.Row(
                     row.getCreateTime() == null || row.getCreateTime().trim().isEmpty() ? null : row.getCreateTime(), cells));

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

@@ -0,0 +1,60 @@
+package com.zksy.cockpit.collectionRecords;
+
+import java.util.Map;
+
+/** 原始采集表/字段 -> 采集服务使用的warning_code;不使用展示label或设备总体状态。 */
+final class CollectionMetricBinding {
+    final String valueKey;
+    final String warningCode;
+    final String statusKey;
+
+    private CollectionMetricBinding(String valueKey, String warningCode, String statusKey) {
+        this.valueKey = valueKey;
+        this.warningCode = warningCode;
+        this.statusKey = statusKey;
+    }
+
+    static CollectionMetricBinding resolve(String table, String key, Map<String, Object> raw) {
+        if ("e_real_time_data".equals(table) && "indicator".equals(key)) {
+            // RSServerService:node 1取float_value,2..5取已换算并入库的hum,不再重复换算。
+            String node = nodeId(raw);
+            switch (node) {
+                case "1": return numeric("float_value", "WARN-SUSPENDED-SOLIDS");
+                case "2": return numeric("hum", "WARN-COD");
+                case "3": return numeric("hum", "WARN-AMMONIA-NITROGEN");
+                case "4": return numeric("hum", "WARN-CONDUCTIVITY");
+                case "5": return numeric("hum", "WARN-PH");
+                default: return numeric("hum", null);
+            }
+        }
+        if ("jg_device_data".equals(table)) {
+            // ManholeDataServiceImpl:三项分别取自己的上报状态,报警固定一级。
+            if ("tilt_angle".equals(key)) return new CollectionMetricBinding(key, "WARN-TILT", "alarm_status");
+            if ("water_infiltration_alarm_status".equals(key)) return new CollectionMetricBinding(key, "WARN-WATER-INFILTRATION", key);
+            if ("water_level_alarm_status".equals(key)) return new CollectionMetricBinding(key, "WARN-WATER-MANHOLE-LEVEL", key);
+        }
+        if ("firefighting_pressure".equals(table) && "pressure_value".equals(key)) return numeric(key, "WARN-FIRE-PRESSURE");
+        if ("gas_monitor_data".equals(table) && "gas_concentration".equals(key)) return numeric(key, "WARN-GAS-CONCENTRATION");
+        if ("radar_data".equals(table)) {
+            if ("meter1_instant_flow".equals(key)) return numeric(key, "WARN-INSTANT-FLOW");
+            if ("flow_speed".equals(key)) return numeric(key, "WARN-FLOW-SPEED");
+            if ("water_level".equals(key)) return numeric(key, "WARN-WATER-LEVEL");
+        }
+        if ("telemetry_data".equals(table)) {
+            if ("meter1_instant_flow".equals(key)) return numeric(key, "WARN-INSTANT-FLOW-SUPPLY");
+            if ("flow_speed".equals(key)) return numeric(key, "WARN-FLOW-SPEED-SUPPLY");
+            if ("pressure".equals(key)) return numeric(key, "WARN-PRESSURE");
+        }
+        return numeric(key, null);
+    }
+
+    private static String nodeId(Map<String, Object> raw) {
+        if (raw == null || raw.get("node_id") == null) return "";
+        try { return String.valueOf(new java.math.BigDecimal(raw.get("node_id").toString().trim()).intValueExact()); }
+        catch (NumberFormatException | ArithmeticException exception) { return ""; }
+    }
+
+    private static CollectionMetricBinding numeric(String key, String code) {
+        return new CollectionMetricBinding(key, code, null);
+    }
+}

+ 126 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/collectionRecords/CollectionRecordAssessmentService.java

@@ -0,0 +1,126 @@
+package com.zksy.cockpit.collectionRecords;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.zksy.api.utils.AlarmLevelUtil;
+import com.zksy.api.utils.EarlyWarningLevelUtil;
+import com.zksy.base.alarm.domain.WarningThreshold;
+import com.zksy.base.alarm.mapper.WarningThresholdMapper;
+import com.zksy.cockpit.collectionRecords.CockpitCollectionRecordsResponse.Assessment;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** 只读逐指标评估;不依赖历史事件、设备总体状态或会产生写入的采集服务。 */
+@Service
+public class CollectionRecordAssessmentService {
+    private final WarningThresholdMapper thresholdMapper;
+
+    public CollectionRecordAssessmentService(WarningThresholdMapper thresholdMapper) {
+        this.thresholdMapper = thresholdMapper;
+    }
+
+    /** 每次请求只查一次该设备的所有配置;一次捕获当前服务端时间,不按历史采集时间回放。 */
+    public Map<String, WarningThreshold> loadThresholds(String deviceCode) {
+        List<WarningThreshold> thresholds = thresholdMapper.selectList(new QueryWrapper<WarningThreshold>()
+                .eq("device_code", deviceCode));
+        return selectThresholds(thresholds, LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm")));
+    }
+
+    /** 与zk-api WarningThresholdServiceImpl一致:分时(含两端) > 全天 > 第一条。
+     *  保留其未命中时回退第一条以及不特殊处理跨午夜的既有口径,不在只读接口另创规则。 */
+    static Map<String, WarningThreshold> selectThresholds(List<WarningThreshold> thresholds, String now) {
+        if (thresholds == null) return Collections.emptyMap();
+        Map<String, List<WarningThreshold>> byCode = new LinkedHashMap<>();
+        for (WarningThreshold threshold : thresholds) {
+            byCode.computeIfAbsent(threshold.getWarningCode(), key -> new ArrayList<>()).add(threshold);
+        }
+        Map<String, WarningThreshold> selected = new LinkedHashMap<>();
+        byCode.forEach((code, candidates) -> {
+            WarningThreshold fullDay = null;
+            WarningThreshold active = null;
+            for (WarningThreshold threshold : candidates) {
+                boolean hasPeriod = threshold.getPeriodStart() != null && !threshold.getPeriodStart().isEmpty()
+                        && threshold.getPeriodEnd() != null && !threshold.getPeriodEnd().isEmpty();
+                if (!hasPeriod) {
+                    if (fullDay == null) fullDay = threshold;
+                } else if (now.compareTo(threshold.getPeriodStart()) >= 0 && now.compareTo(threshold.getPeriodEnd()) <= 0) {
+                    active = threshold;
+                    break;
+                }
+            }
+            selected.put(code, active != null ? active : fullDay != null ? fullDay : candidates.get(0));
+        });
+        return selected;
+    }
+
+    public Assessment assess(String table, String key, Map<String, Object> raw,
+                             Map<String, WarningThreshold> thresholds) {
+        return assess(table, key, raw, thresholds, true);
+    }
+
+    public Assessment assess(String table, String key, Map<String, Object> raw,
+                             Map<String, WarningThreshold> thresholds, boolean rulesAvailable) {
+        table = table == null ? "" : table.trim();
+        if ("filepath".equals(key) || "create_time".equals(key)) return unknown("NOT_APPLICABLE");
+        CollectionMetricBinding binding = CollectionMetricBinding.resolve(table, key, raw);
+        if (raw == null) return unknown("MISSING_VALUE");
+        if (binding.statusKey != null) return reportedStatus(raw.get(binding.statusKey));
+        Object value = raw.get(binding.valueKey);
+        if (value == null || value.toString().trim().isEmpty()) return unknown("MISSING_VALUE");
+        BigDecimal actual = decimal(value);
+        if (actual == null) return unknown("INVALID_VALUE");
+        // 漏失RMS/频率由NoiseLeakAlarmService联合频段、恢复滞回与确认次数判断,不能套普通双侧门限。
+        if ("noise_info".equals(table) && ("rms".equals(key) || "center_frequency".equals(key))) {
+            return unknown("COMPOSITE_RULE_REQUIRED");
+        }
+        if (binding.warningCode == null) return unknown("METRIC_UNMAPPED");
+        if (!rulesAvailable) return unknown("RULE_UNAVAILABLE");
+        WarningThreshold threshold = thresholds == null ? null : thresholds.get(binding.warningCode);
+        if (threshold == null) return unknown("NO_THRESHOLD");
+        return numeric(binding.warningCode, actual, threshold);
+    }
+
+    private Assessment reportedStatus(Object value) {
+        if (value == null || value.toString().trim().isEmpty()) return unknown("MISSING_STATUS");
+        String flag = value.toString().trim();
+        if ("1".equals(flag)) return new Assessment("ALARM", 1, "REPORTED_ALARM");
+        if ("0".equals(flag)) return new Assessment("NORMAL", null, "REPORTED_NORMAL");
+        return unknown("INVALID_STATUS");
+    }
+
+    private Assessment numeric(String code, BigDecimal actual, WarningThreshold threshold) {
+        boolean gas = "WARN-GAS-CONCENTRATION".equals(code);
+        boolean pressure = "WARN-FIRE-PRESSURE".equals(code);
+        BigDecimal min = gas ? null : decimal(threshold.getMinValue());
+        BigDecimal max = decimal(threshold.getMaxValue());
+        if ((!gas && threshold.getMinValue() != null && min == null)
+                || (threshold.getMaxValue() != null && max == null)) return unknown("INVALID_THRESHOLD");
+        if (min == null && max == null) return unknown("NO_THRESHOLD");
+        if (min != null && max != null && min.compareTo(max) > 0) return unknown("INVALID_THRESHOLD");
+        // 与各MessageHandler的参数完全一致:气体仅max;消防压力单侧补齐分级及预警区基线。
+        BigDecimal levelMin = (gas || pressure) && min == null ? BigDecimal.ZERO : min;
+        BigDecimal levelMax = pressure && max == null ? min.multiply(BigDecimal.valueOf(2)) : max;
+        if (EarlyWarningLevelUtil.isOverThreshold(actual, min, max)) {
+            return new Assessment("ALARM", AlarmLevelUtil.calculateLevel(actual, levelMin, levelMax), "THRESHOLD_REACHED");
+        }
+        EarlyWarningLevelUtil.EarlyWarningLevelResult warning = EarlyWarningLevelUtil.calculate(actual,
+                pressure ? levelMin : min, pressure ? levelMax : max);
+        if (warning != null) return new Assessment("WARNING", warning.getLevel(), "NEAR_THRESHOLD");
+        return new Assessment("NORMAL", null, "WITHIN_THRESHOLD");
+    }
+
+    private static BigDecimal decimal(Object value) {
+        if (value == null) return null;
+        try { return new BigDecimal(value.toString().trim()); }
+        catch (NumberFormatException exception) { return null; }
+    }
+
+    private static Assessment unknown(String reason) { return new Assessment("UNKNOWN", null, reason); }
+}

+ 172 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/collectionRecords/CollectionRecordAssessmentServiceTest.java

@@ -0,0 +1,172 @@
+package com.zksy.cockpit.collectionRecords;
+
+import com.zksy.base.alarm.domain.WarningThreshold;
+import com.zksy.base.alarm.mapper.WarningThresholdMapper;
+import com.zksy.cockpit.collectionRecords.CockpitCollectionRecordsResponse.Assessment;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+class CollectionRecordAssessmentServiceTest {
+    private final WarningThresholdMapper mapper = mock(WarningThresholdMapper.class);
+    private final CollectionRecordAssessmentService service = new CollectionRecordAssessmentService(mapper);
+
+    @Test
+    void inclusiveAlarmBoundaryAndEveryDeviationLevelKeepStatusAndLevelColorsSeparate() {
+        double[] values = {100, 109.99, 110, 130, 160};
+        int[] levels = {4, 4, 3, 2, 1};
+        String[] colors = {"GREEN", "GREEN", "BLUE", "YELLOW", "RED"};
+        for (int i = 0; i < values.length; i++) {
+            Assessment a = assess("radar_data", "water_level", values[i], "WARN-WATER-LEVEL", 0.0, 100.0);
+            assertAssessment(a, "ALARM", levels[i], "THRESHOLD_REACHED");
+            assertEquals(colors[i], a.getLevelColor());
+        }
+        assertAssessment(assess("radar_data", "water_level", 0, "WARN-WATER-LEVEL", 0.0, 100.0), "ALARM", 4, "THRESHOLD_REACHED");
+    }
+
+    @Test
+    void warningBandAndApproachLevelsMatchSharedRuleIncludingLowerSide() {
+        double[] values = {70, 82, 89.5, 95.5};
+        int[] levels = {4, 3, 2, 1};
+        for (int i = 0; i < values.length; i++) {
+            assertAssessment(assess("radar_data", "water_level", values[i], "WARN-WATER-LEVEL", 0.0, 100.0), "WARNING", levels[i], "NEAR_THRESHOLD");
+            assertAssessment(assess("radar_data", "water_level", 100 - values[i], "WARN-WATER-LEVEL", 0.0, 100.0), "WARNING", levels[i], "NEAR_THRESHOLD");
+        }
+        assertAssessment(assess("radar_data", "water_level", 50, "WARN-WATER-LEVEL", 0.0, 100.0), "NORMAL", null, "WITHIN_THRESHOLD");
+    }
+
+    @Test
+    void gasIgnoresConfiguredLowerBoundAndUsesZeroOnlyForAlarmLevel() {
+        assertAssessment(assess("gas_monitor_data", "gas_concentration", 0, "WARN-GAS-CONCENTRATION", 10.0, 100.0), "NORMAL", null, "WITHIN_THRESHOLD");
+        assertAssessment(assess("gas_monitor_data", "gas_concentration", 130, "WARN-GAS-CONCENTRATION", 10.0, 100.0), "ALARM", 2, "THRESHOLD_REACHED");
+        assertAssessment(assess("gas_monitor_data", "gas_concentration", 95.5, "WARN-GAS-CONCENTRATION", 10.0, 100.0), "WARNING", 1, "NEAR_THRESHOLD");
+        assertAssessment(assess("gas_monitor_data", "gas_concentration", 1, "WARN-GAS-CONCENTRATION", 10.0, null), "UNKNOWN", null, "NO_THRESHOLD");
+    }
+
+    @Test
+    void firePressureSingleSideUsesCollectorBaselinesButTelemetryDoesNotInventThem() {
+        assertAssessment(assess("firefighting_pressure", "pressure_value", 160, "WARN-FIRE-PRESSURE", null, 100.0), "ALARM", 1, "THRESHOLD_REACHED");
+        assertAssessment(assess("firefighting_pressure", "pressure_value", 4, "WARN-FIRE-PRESSURE", 10.0, null), "ALARM", 1, "THRESHOLD_REACHED");
+        assertAssessment(assess("firefighting_pressure", "pressure_value", 10.45, "WARN-FIRE-PRESSURE", 10.0, null), "WARNING", 1, "NEAR_THRESHOLD");
+        assertAssessment(assess("telemetry_data", "pressure", 160, "WARN-PRESSURE", null, 100.0), "ALARM", 4, "THRESHOLD_REACHED");
+    }
+
+    @Test
+    void nullMalformedAndAbsentThresholdValuesNeverBecomeNormal() {
+        assertAssessment(assess("radar_data", "water_level", null, "WARN-WATER-LEVEL", 0.0, 100.0), "UNKNOWN", null, "MISSING_VALUE");
+        for (Object value : new Object[]{"bad", "NaN", Double.POSITIVE_INFINITY, "1 MPa"}) {
+            assertAssessment(assess("radar_data", "water_level", value, "WARN-WATER-LEVEL", 0.0, 100.0), "UNKNOWN", null, "INVALID_VALUE");
+        }
+        assertAssessment(assess("radar_data", "water_level", 1, "WARN-WATER-LEVEL", null, null), "UNKNOWN", null, "NO_THRESHOLD");
+        assertAssessment(assess("radar_data", "water_level", 1, "WARN-WATER-LEVEL", 100.0, 0.0), "UNKNOWN", null, "INVALID_THRESHOLD");
+        assertAssessment(assess("radar_data", "water_level", 1, "WARN-WATER-LEVEL", 0.0, Double.NaN), "UNKNOWN", null, "INVALID_THRESHOLD");
+        assertAssessment(service.assess("radar_data", "water_level", Collections.singletonMap("water_level", 1), Collections.emptyMap()), "UNKNOWN", null, "NO_THRESHOLD");
+    }
+
+    @Test
+    void environmentNodeBindsTheRealRawValueNotDisplayOrOtherChannels() {
+        Map<String, WarningThreshold> thresholds = new HashMap<>();
+        thresholds.put("WARN-SUSPENDED-SOLIDS", threshold("WARN-SUSPENDED-SOLIDS", 0.0, 100.0));
+        thresholds.put("WARN-COD", threshold("WARN-COD", 0.0, 100.0));
+        thresholds.put("WARN-AMMONIA-NITROGEN", threshold("WARN-AMMONIA-NITROGEN", 0.0, 200.0));
+        Map<String, Object> raw = new HashMap<>();
+        raw.put("node_id", 1); raw.put("float_value", 160); raw.put("hum", 50); raw.put("temperature", 999);
+        assertAssessment(service.assess("e_real_time_data", "indicator", raw, thresholds), "ALARM", 1, "THRESHOLD_REACHED");
+        raw.put("node_id", new java.math.BigDecimal("2.0")); raw.put("hum", 95.5);
+        assertAssessment(service.assess("e_real_time_data", "indicator", raw, thresholds), "WARNING", 1, "NEAR_THRESHOLD");
+        raw.put("node_id", 3);
+        assertAssessment(service.assess("e_real_time_data", "indicator", raw, thresholds), "NORMAL", null, "WITHIN_THRESHOLD");
+        raw.put("node_id", 99);
+        assertAssessment(service.assess("e_real_time_data", "indicator", raw, thresholds), "UNKNOWN", null, "METRIC_UNMAPPED");
+    }
+
+    @Test
+    void manholeFlagsAreIndependentAndTiltUsesItsOwnFlagNotItsAngle() {
+        Map<String, Object> raw = new HashMap<>();
+        raw.put("tilt_angle", 0); raw.put("alarm_status", "1");
+        raw.put("water_infiltration_alarm_status", 0); raw.put("water_level_alarm_status", 2);
+        assertAssessment(service.assess("jg_device_data", "tilt_angle", raw, Collections.emptyMap()), "ALARM", 1, "REPORTED_ALARM");
+        assertAssessment(service.assess("jg_device_data", "water_infiltration_alarm_status", raw, Collections.emptyMap()), "NORMAL", null, "REPORTED_NORMAL");
+        assertAssessment(service.assess("jg_device_data", "water_level_alarm_status", raw, Collections.emptyMap()), "UNKNOWN", null, "INVALID_STATUS");
+        raw.remove("alarm_status");
+        assertAssessment(service.assess("jg_device_data", "tilt_angle", raw, Collections.emptyMap()), "UNKNOWN", null, "MISSING_STATUS");
+    }
+
+    @Test
+    void unrelatedNumericAndAudioCellsAreExplicitlyUnknown() {
+        assertAssessment(assess("gas_monitor_data", "temperature", 99, "WARN-GAS-CONCENTRATION", 0.0, 10.0), "UNKNOWN", null, "METRIC_UNMAPPED");
+        assertAssessment(service.assess("noise_info", "filepath", Collections.emptyMap(), Collections.emptyMap()), "UNKNOWN", null, "NOT_APPLICABLE");
+        assertAssessment(assess("noise_info", "rms", 99, "WARN-LEAK", 1.0, 10.0), "UNKNOWN", null, "COMPOSITE_RULE_REQUIRED");
+    }
+
+    @Test
+    void timeSelectionKeepsCurrentCollectorPrecedenceAndFirstRowFallback() {
+        WarningThreshold full = threshold("x", 0.0, 100.0);
+        WarningThreshold morning = threshold("x", 0.0, 10.0);
+        morning.setPeriodStart("08:00"); morning.setPeriodEnd("10:00");
+        for (String time : new String[]{"08:00", "09:00", "10:00"}) {
+            assertSame(morning, CollectionRecordAssessmentService.selectThresholds(Arrays.asList(full, morning), time).get("x"));
+        }
+        assertSame(full, CollectionRecordAssessmentService.selectThresholds(Arrays.asList(morning, full), "12:00").get("x"));
+        assertSame(morning, CollectionRecordAssessmentService.selectThresholds(Collections.singletonList(morning), "12:00").get("x"));
+    }
+
+    @Test
+    void oneBatchReadFeedsFiftyRowsWithoutAnyWritesOrPerCellQueries() {
+        when(mapper.selectList(any())).thenReturn(Collections.singletonList(threshold("WARN-WATER-LEVEL", 0.0, 100.0)));
+        Map<String, WarningThreshold> thresholds = service.loadThresholds("device-1");
+        for (int i = 0; i < 50; i++) service.assess("radar_data", "water_level", Collections.singletonMap("water_level", i), thresholds);
+        verify(mapper).selectList(any());
+        verifyNoMoreInteractions(mapper);
+    }
+
+    @Test
+    void unavailableRulesAreDistinctFromEmptyConfigurationAndCannotReuseThresholdValues() {
+        Map<String, Object> raw = Collections.singletonMap("water_level", 100);
+        Map<String, WarningThreshold> configured = Collections.singletonMap("WARN-WATER-LEVEL", threshold("WARN-WATER-LEVEL", 0.0, 100.0));
+        assertAssessment(service.assess("radar_data", "water_level", raw, configured, false), "UNKNOWN", null, "RULE_UNAVAILABLE");
+        assertAssessment(service.assess("radar_data", "water_level", raw, Collections.emptyMap(), true), "UNKNOWN", null, "NO_THRESHOLD");
+        assertAssessment(service.assess("radar_data", "water_level", raw, null, true), "UNKNOWN", null, "NO_THRESHOLD");
+    }
+
+    @Test
+    void configurationOutageDoesNotAffectReportedStatusesOrNonApplicableAudio() {
+        Map<String, Object> raw = new HashMap<>();
+        raw.put("alarm_status", "1"); raw.put("water_infiltration_alarm_status", "0");
+        assertAssessment(service.assess("jg_device_data", "tilt_angle", raw, Collections.emptyMap(), false), "ALARM", 1, "REPORTED_ALARM");
+        assertAssessment(service.assess("jg_device_data", "water_infiltration_alarm_status", raw, Collections.emptyMap(), false), "NORMAL", null, "REPORTED_NORMAL");
+        assertAssessment(service.assess("noise_info", "filepath", raw, Collections.emptyMap(), false), "UNKNOWN", null, "NOT_APPLICABLE");
+    }
+
+    @Test
+    void nullOrEmptyConfigurationAndUnknownNodeNeverDereferenceNullKeys() {
+        when(mapper.selectList(any())).thenReturn(null);
+        assertTrue(service.loadThresholds("device-1").isEmpty());
+        assertTrue(CollectionRecordAssessmentService.selectThresholds(Collections.emptyList(), "12:00").isEmpty());
+        Map<String, Object> raw = new HashMap<>(); raw.put("hum", 1);
+        for (Object node : new Object[]{null, 99, "bad", "2.5"}) {
+            raw.put("node_id", node);
+            assertAssessment(service.assess("e_real_time_data", "indicator", raw, Collections.emptyMap()), "UNKNOWN", null, "METRIC_UNMAPPED");
+        }
+    }
+
+    private Assessment assess(String table, String key, Object value, String code, Double min, Double max) {
+        return service.assess(table, key, Collections.singletonMap(key, value), Collections.singletonMap(code, threshold(code, min, max)));
+    }
+
+    private static WarningThreshold threshold(String code, Double min, Double max) {
+        WarningThreshold t = new WarningThreshold(); t.setWarningCode(code); t.setMinValue(min); t.setMaxValue(max); return t;
+    }
+
+    private static void assertAssessment(Assessment actual, String status, Integer level, String reason) {
+        assertEquals(status, actual.getStatus()); assertEquals(level, actual.getLevel()); assertEquals(reason, actual.getReason());
+        if (level == null) assertNull(actual.getLevelColor());
+    }
+}

+ 46 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/collectionRecords/CollectionThresholdRulesPackagingTest.java

@@ -0,0 +1,46 @@
+package com.zksy.cockpit.collectionRecords;
+
+import com.zksy.api.utils.AlarmLevelUtil;
+import com.zksy.api.utils.EarlyWarningLevelUtil;
+import org.junit.jupiter.api.Test;
+
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Set;
+import java.util.jar.JarFile;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class CollectionThresholdRulesPackagingTest {
+    @Test
+    void sharedModuleContainsOnlyPureRulesIncludingNestedResultClass() throws Exception {
+        URL source = AlarmLevelUtil.class.getProtectionDomain().getCodeSource().getLocation();
+        Path location = Paths.get(source.toURI());
+        assertTrue(source.toString().contains("monitoring-threshold-rules"), source.toString());
+        assertEquals(source, EarlyWarningLevelUtil.class.getProtectionDomain().getCodeSource().getLocation());
+        Set<String> entries;
+        if (Files.isDirectory(location)) {
+            // Maven test 阶段引用 reactor 的 target/classes,而 install 后引用共享规则 jar。
+            try (Stream<Path> files = Files.walk(location)) {
+                entries = files.filter(Files::isRegularFile)
+                        .map(file -> location.relativize(file).toString().replace('\\', '/'))
+                        .collect(Collectors.toSet());
+            }
+        } else {
+            try (JarFile jar = new JarFile(location.toFile())) {
+                entries = jar.stream().filter(entry -> !entry.isDirectory())
+                        .map(java.util.jar.JarEntry::getName).filter(name -> !name.startsWith("META-INF/"))
+                        .collect(Collectors.toSet());
+            }
+        }
+        assertEquals(Set.of("com/zksy/api/utils/AlarmLevelUtil.class",
+                "com/zksy/api/utils/EarlyWarningLevelUtil.class",
+                "com/zksy/api/utils/EarlyWarningLevelUtil$EarlyWarningLevelResult.class"), entries);
+        assertThrows(ClassNotFoundException.class,
+                () -> Class.forName("com.zksy.api.service.impl.EarlyWarningAutoServiceImpl"));
+    }
+}