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

feat(cockpit): 新增设备采集记录只读端点

Kazerin 4 недель назад
Родитель
Сommit
3a6e2d41f6

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

@@ -0,0 +1,54 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.collectionRecords.CockpitCollectionRecordsResponse;
+import com.zksy.cockpit.collectionRecords.CockpitCollectionRecordsService;
+import com.zksy.cockpit.foundation.CockpitDeviceNotFoundException;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.common.core.domain.AjaxResult;
+import com.zksy.common.utils.uuid.IdUtils;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.util.UriUtils;
+
+import java.nio.charset.StandardCharsets;
+
+/** 驾驶舱公开只读入口,不改变管理端档案接口的授权。 */
+@RestController
+public class CockpitCollectionRecordsController {
+    private final CockpitCollectionRecordsService service;
+
+    public CockpitCollectionRecordsController(CockpitCollectionRecordsService service) {
+        this.service = service;
+    }
+
+    @GetMapping("/api/cockpit/v1/equipments/{deviceCode}/collection-records")
+    public ResponseEntity<AjaxResult> collectionRecords(
+            @PathVariable("deviceCode") String deviceCode,
+            @RequestHeader(value = "X-Request-Id", required = false) String requestId) {
+        String traceId = requestId == null || requestId.trim().isEmpty() ? IdUtils.fastSimpleUUID() : requestId;
+        try {
+            String decoded;
+            try {
+                decoded = UriUtils.decode(deviceCode, StandardCharsets.UTF_8);
+            } catch (IllegalArgumentException exception) {
+                throw new CockpitInvalidRequestException("设备编码不合法");
+            }
+            return ResponseEntity.ok(AjaxResult.success(service.load(traceId, decoded)));
+        } catch (CockpitInvalidRequestException exception) {
+            return failure(400, traceId, deviceCode, exception.getMessage());
+        } catch (CockpitDeviceNotFoundException exception) {
+            return failure(404, traceId, deviceCode, "设备不存在");
+        } catch (RuntimeException exception) {
+            return failure(500, traceId, deviceCode, "驾驶舱采集记录读取失败,暂不可用");
+        }
+    }
+
+    private ResponseEntity<AjaxResult> failure(int status, String requestId, String deviceCode, String message) {
+        CockpitCollectionRecordsResponse response = new CockpitCollectionRecordsResponse(
+                requestId, deviceCode, "FAILED", message, CockpitCollectionRecordsResponse.emptyView());
+        return ResponseEntity.status(status).body(new AjaxResult(status, message, response));
+    }
+}

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

@@ -0,0 +1,293 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentStatusMapper;
+import com.zksy.base.mapper.EquipmentTypeMapper;
+import com.zksy.base.perception.mapper.PerceptionMapper;
+import com.zksy.base.perception.service.impl.PerceptionServiceImpl;
+import com.zksy.base.warning.mapper.EquipmentWarningTypeMapper;
+import com.zksy.cockpit.collectionRecords.CockpitCollectionRecordsService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.time.LocalDateTime;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/** 公开HTTP seam + 真实Service/profile,仅数据库读取边界使用fixture。 */
+class CockpitCollectionRecordsControllerTest {
+    static final String CODE = "TC-GS-202609020001";
+    static final String ID = "internal-equipment-uuid";
+    private EquipmentBaseMapper equipmentMapper;
+    private EquipmentTypeMapper typeMapper;
+    private PerceptionMapper recordsMapper;
+    private MockMvc mvc;
+
+    @BeforeEach
+    void setup() {
+        equipmentMapper = mock(EquipmentBaseMapper.class);
+        typeMapper = mock(EquipmentTypeMapper.class);
+        recordsMapper = mock(PerceptionMapper.class);
+        EquipmentBase base = new EquipmentBase();
+        base.setEquipmentId(ID);
+        base.setEquipmentCode(CODE);
+        base.setEquipmentTypeId(10);
+        when(equipmentMapper.selectOne(any())).thenAnswer(invocation -> {
+            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<?> query = invocation.getArgument(0);
+            query.getSqlSegment();
+            return query.getParamNameValuePairs().containsValue(CODE) ? base : null;
+        });
+        when(equipmentMapper.selectById(ID)).thenReturn(base);
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("firefighting_pressure");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        EquipmentWarningTypeMapper indicators = mock(EquipmentWarningTypeMapper.class);
+        when(indicators.selectList(any())).thenReturn(Collections.emptyList());
+        PerceptionServiceImpl profile = new PerceptionServiceImpl();
+        ReflectionTestUtils.setField(profile, "equipmentBaseMapper", equipmentMapper);
+        ReflectionTestUtils.setField(profile, "equipmentTypeMapper", typeMapper);
+        ReflectionTestUtils.setField(profile, "equipmentStatusMapper", mock(EquipmentStatusMapper.class));
+        ReflectionTestUtils.setField(profile, "perceptionMapper", recordsMapper);
+        ReflectionTestUtils.setField(profile, "equipmentWarningTypeMapper", indicators);
+        mvc = MockMvcBuilders.standaloneSetup(new CockpitCollectionRecordsController(
+                new CockpitCollectionRecordsService(equipmentMapper, profile)))
+                .setMessageConverters(new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter())
+                .build();
+    }
+
+    @Test
+    void pressureRecordsExposeReferenceColumnsAndCreateTimeWithoutInternalId() throws Exception {
+        when(recordsMapper.selectLatestRecords("firefighting_pressure", "telemetering_station", CODE, 50))
+                .thenReturn(Collections.singletonList(record("2026-11-04T10:20:00", "pressure_value", 0)));
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records")
+                        .header("X-Request-Id", "collection-001"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.requestId").value("collection-001"))
+                .andExpect(jsonPath("$.data.apiVersion").value("v1"))
+                .andExpect(jsonPath("$.data.readOnly").value(true))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.state").value("READY"))
+                .andExpect(jsonPath("$.data.equipmentId").doesNotExist())
+                .andExpect(jsonPath("$.data.recordView.layout").value("wide"))
+                .andExpect(jsonPath("$.data.recordView.columns[1].key").value("pressure_value"))
+                .andExpect(jsonPath("$.data.recordView.columns[1].label").value("压力"))
+                .andExpect(jsonPath("$.data.recordView.columns[1].unit").value("MPa"))
+                .andExpect(jsonPath("$.data.recordView.columns[1].isAlarm").value(false))
+                .andExpect(jsonPath("$.data.recordView.rows[0].createTime").value("2026-11-04 10:20:00"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].value").value("0"));
+    }
+
+    @Test
+    void invalidCodeIsBadRequestWithoutReadingDatabase() throws Exception {
+        mvc.perform(get("/api/cockpit/v1/equipments/%20/collection-records")
+                        .header("X-Request-Id", "invalid-001"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.stateReason").value("设备编码不能为空"))
+                .andExpect(jsonPath("$.data.requestId").value("invalid-001"));
+        org.mockito.Mockito.verifyNoInteractions(equipmentMapper, recordsMapper);
+    }
+
+    @Test
+    void unknownBusinessCodeIsNotFoundNotEmpty() throws Exception {
+        org.mockito.Mockito.doReturn(null).when(equipmentMapper).selectOne(any());
+        mvc.perform(get("/api/cockpit/v1/equipments/MISSING/collection-records"))
+                .andExpect(status().isNotFound())
+                .andExpect(jsonPath("$.data.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.stateReason").value("设备不存在"));
+        org.mockito.Mockito.verifyNoInteractions(recordsMapper);
+    }
+
+    @Test
+    void databaseFailureIsUnavailableNotSuccessfulEmpty() throws Exception {
+        org.mockito.Mockito.doThrow(new IllegalStateException("password secret database"))
+                .when(equipmentMapper).selectOne(any());
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.data.state").value("FAILED"))
+                .andExpect(jsonPath("$.data.stateReason").value("驾驶舱采集记录读取失败,暂不可用"))
+                .andExpect(jsonPath("$.data.recordView.rows").isEmpty());
+    }
+
+    @Test
+    void configuredCollectionWithNoRowsIsEmpty() throws Exception {
+        when(recordsMapper.selectLatestRecords("firefighting_pressure", "telemetering_station", CODE, 50))
+                .thenReturn(Collections.emptyList());
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("EMPTY"))
+                .andExpect(jsonPath("$.data.stateReason").value("暂无采集记录"))
+                .andExpect(jsonPath("$.data.recordView.columns[0].key").value("create_time"))
+                .andExpect(jsonPath("$.data.recordView.rows").isEmpty());
+    }
+
+    @Test
+    void unsupportedCollectionTableIsUnavailableNotEmpty() throws Exception {
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("not_a_whitelisted_collection");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.state").value("UNAVAILABLE"))
+                .andExpect(jsonPath("$.data.stateReason").value("设备采集表未配置或暂不支持"))
+                .andExpect(jsonPath("$.data.recordView.rows").isEmpty());
+        org.mockito.Mockito.verifyNoInteractions(recordsMapper);
+    }
+
+    @Test
+    void missingSampleTimeAndNullValueRemainUnknownInsteadOfReportTimeOrZero() throws Exception {
+        when(recordsMapper.selectLatestRecords("firefighting_pressure", "telemetering_station", CODE, 50))
+                .thenReturn(Collections.singletonList(record(null, "pressure_value", null)));
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.rows[0].createTime").value(org.hamcrest.Matchers.nullValue()))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].value").value(org.hamcrest.Matchers.nullValue()))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].display").value("—"));
+    }
+
+    @Test
+    void environmentHistoryKeepsOnlyWaterQualityFactorsAndAllSampleTimes() throws Exception {
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("e_real_time_data");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        Map<String, Object> cod = record("2026-11-04T10:20:00", "hum", 0);
+        cod.put("node_id", 2);
+        cod.put("temperature", 99);
+        Map<String, Object> ammonia = record("2026-11-04T10:20:00", "hum", 2);
+        ammonia.put("node_id", 3);
+        Map<String, Object> older = record("2026-11-04T10:19:00", "hum", 7);
+        older.put("node_id", 5);
+        when(recordsMapper.selectLatestRecords("e_real_time_data", "device_id", CODE, 50))
+                .thenReturn(java.util.Arrays.asList(cod, ammonia, older));
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.layout").value("long"))
+                .andExpect(jsonPath("$.data.recordView.columns.length()").value(2))
+                .andExpect(jsonPath("$.data.recordView.rows.length()").value(3))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells.length()").value(1))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].key").value("indicator"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].display").value("化学需氧量(COD):0mg/L"))
+                .andExpect(jsonPath("$.data.recordView.rows[1].cells[0].display").value("氨氮:2mg/L"))
+                .andExpect(jsonPath("$.data.recordView.rows[2].createTime").value("2026-11-04 10:19:00"))
+                .andExpect(jsonPath("$.data.recordView.rows[2].cells[0].display").value("酸碱度(pH):7"));
+    }
+
+    @Test
+    void endpointCapsHistoryAtNewestFiftyCreateTimes() throws Exception {
+        java.util.List<Map<String, Object>> records = new java.util.ArrayList<>();
+        for (int minute = 0; minute < 55; minute++) {
+            records.add(record(LocalDateTime.parse("2026-11-04T10:00:00").plusMinutes(minute).toString(),
+                    "pressure_value", minute));
+        }
+        when(recordsMapper.selectLatestRecords("firefighting_pressure", "telemetering_station", CODE, 50))
+                .thenReturn(records);
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.rows.length()").value(50))
+                .andExpect(jsonPath("$.data.recordView.rows[0].createTime").value("2026-11-04 10:54:00"))
+                .andExpect(jsonPath("$.data.recordView.rows[49].createTime").value("2026-11-04 10:05:00"));
+    }
+
+    @Test
+    void unknownAlarmStatusIsNotFabricatedAsNormalWhileZeroRemainsNormal() throws Exception {
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("jg_device_data");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        Map<String, Object> record = record("2026-11-04T10:20:00", "water_infiltration_alarm_status", null);
+        record.put("water_level_alarm_status", 0);
+        record.put("battery_level", 0);
+        when(recordsMapper.selectLatestRecords("jg_device_data", "imei_card_number", CODE, 50))
+                .thenReturn(Collections.singletonList(record));
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.columns[2].isAlarm").value(true))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[1].value").value(org.hamcrest.Matchers.nullValue()))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[1].display").value("—"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[1].alarm").value(false))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[2].value").value("正常"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[4].value").value("0"));
+    }
+
+    @Test
+    void internalIdCannotReplaceBusinessCodeAndMutationsAreRejected() throws Exception {
+        mvc.perform(get("/api/cockpit/v1/equipments/" + ID + "/collection-records"))
+                .andExpect(status().isNotFound());
+        mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post(
+                "/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isMethodNotAllowed());
+        org.mockito.Mockito.verifyNoInteractions(recordsMapper);
+    }
+
+    @Test
+    void noiseAudioPathAndReferenceColumnsArePassedThroughWithoutPrivateRecords() throws Exception {
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("noise_info");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        Map<String, Object> record = record("2026-11-04T10:20:00", "filepath", "/device-audio/noise-001.wav");
+        record.put("rms", 0);
+        record.put("gain", 2);
+        record.put("center_frequency", 99);
+        when(recordsMapper.selectLatestRecords("noise_info", "encode", CODE, 50))
+                .thenReturn(Collections.singletonList(record));
+        String response = mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.columns.length()").value(5))
+                .andExpect(jsonPath("$.data.recordView.columns[4].key").value("filepath"))
+                .andExpect(jsonPath("$.data.recordView.columns[4].label").value("音频文件"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].value").value("0"))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[3].value").value("/device-audio/noise-001.wav"))
+                .andExpect(jsonPath("$.data.base").doesNotExist())
+                .andExpect(jsonPath("$.data.records").doesNotExist())
+                .andReturn().getResponse().getContentAsString();
+        org.junit.jupiter.api.Assertions.assertFalse(response.contains("private-record-id"));
+        org.junit.jupiter.api.Assertions.assertFalse(response.contains(ID));
+    }
+
+    @Test
+    void missingLongFactorRemainsNullWithChineseDisplay() throws Exception {
+        EquipmentType type = new EquipmentType();
+        type.setOrigCollTable("e_real_time_data");
+        when(typeMapper.selectById(10)).thenReturn(type);
+        Map<String, Object> record = record(null, "hum", null);
+        record.put("node_id", 3);
+        when(recordsMapper.selectLatestRecords("e_real_time_data", "device_id", CODE, 50))
+                .thenReturn(Collections.singletonList(record));
+        mvc.perform(get("/api/cockpit/v1/equipments/" + CODE + "/collection-records"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].value").value(org.hamcrest.Matchers.nullValue()))
+                .andExpect(jsonPath("$.data.recordView.rows[0].cells[0].display").value("氨氮:—"));
+    }
+
+    @Test
+    void malformedEncodingAndEmbeddedControlCharacterAreInvalidBeforeDatabaseRead() throws Exception {
+        mvc.perform(get("/api/cockpit/v1/equipments/%ZZ/collection-records"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.stateReason").value("设备编码不合法"));
+        mvc.perform(get("/api/cockpit/v1/equipments/TC%0AGS/collection-records"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.stateReason").value("设备编码不合法"));
+        org.mockito.Mockito.verifyNoInteractions(equipmentMapper, recordsMapper);
+    }
+
+    static Map<String, Object> record(String time, String key, Object value) {
+        Map<String, Object> record = new LinkedHashMap<>();
+        record.put("create_time", time == null ? null : LocalDateTime.parse(time));
+        record.put(key, value);
+        record.put("report_time", LocalDateTime.parse("2027-01-01T00:00:00"));
+        record.put("id", "private-record-id");
+        return record;
+    }
+}

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

@@ -0,0 +1,93 @@
+package com.zksy.cockpit.collectionRecords;
+
+import java.util.Collections;
+import java.util.List;
+
+/** 驾驶舱采集记录专用契约:不包含设备档案、原始记录或内部主键。 */
+public class CockpitCollectionRecordsResponse {
+    private final String requestId;
+    private final String deviceCode;
+    private final String state;
+    private final String stateReason;
+    private final RecordView recordView;
+
+    public CockpitCollectionRecordsResponse(String requestId, String deviceCode, String state,
+                                           String stateReason, RecordView recordView) {
+        this.requestId = requestId;
+        this.deviceCode = deviceCode;
+        this.state = state;
+        this.stateReason = stateReason;
+        this.recordView = recordView;
+    }
+
+    public String getRequestId() { return requestId; }
+    public String getApiVersion() { return "v1"; }
+    public boolean isReadOnly() { return true; }
+    public String getDeviceCode() { return deviceCode; }
+    public String getState() { return state; }
+    public String getStateReason() { return stateReason; }
+    public RecordView getRecordView() { return recordView; }
+
+    public static RecordView emptyView() {
+        return new RecordView("wide", Collections.emptyList(), Collections.emptyList());
+    }
+
+    public static class RecordView {
+        private final String layout;
+        private final List<Column> columns;
+        private final List<Row> rows;
+        public RecordView(String layout, List<Column> columns, List<Row> rows) {
+            this.layout = layout;
+            this.columns = columns;
+            this.rows = rows;
+        }
+        public String getLayout() { return layout; }
+        public List<Column> getColumns() { return columns; }
+        public List<Row> getRows() { return rows; }
+    }
+
+    public static class Column {
+        private final String key;
+        private final String label;
+        private final String unit;
+        private final boolean isAlarm;
+        public Column(String key, String label, String unit, boolean isAlarm) {
+            this.key = key;
+            this.label = label;
+            this.unit = unit;
+            this.isAlarm = isAlarm;
+        }
+        public String getKey() { return key; }
+        public String getLabel() { return label; }
+        public String getUnit() { return unit; }
+        public boolean getIsAlarm() { return isAlarm; }
+    }
+
+    public static class Row {
+        private final String createTime;
+        private final List<Cell> cells;
+        public Row(String createTime, List<Cell> cells) {
+            this.createTime = createTime;
+            this.cells = cells;
+        }
+        public String getCreateTime() { return createTime; }
+        public List<Cell> getCells() { return cells; }
+    }
+
+    public static class Cell {
+        private final String key;
+        private final String value;
+        private final String display;
+        private final boolean alarm;
+        public Cell(String key, String value, String display, boolean alarm) {
+            this.key = key;
+            this.value = value;
+            this.display = display;
+            this.alarm = alarm;
+        }
+        public String getKey() { return key; }
+        public String getValue() { return value; }
+        public String getDisplay() { return display; }
+        public boolean isAlarm() { return alarm; }
+    }
+}

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

@@ -0,0 +1,87 @@
+package com.zksy.cockpit.collectionRecords;
+
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.zksy.base.domain.EquipmentBase;
+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 java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+
+/** 复用感知档案的展示边界,不复制各原始采集表的字段或单位定义。 */
+@Service
+public class CockpitCollectionRecordsService {
+    private static final int MAX_RECORDS = 50;
+    private final EquipmentBaseMapper equipmentMapper;
+    private final PerceptionService perceptionService;
+
+    public CockpitCollectionRecordsService(EquipmentBaseMapper equipmentMapper, PerceptionService perceptionService) {
+        this.equipmentMapper = equipmentMapper;
+        this.perceptionService = perceptionService;
+    }
+
+    public CockpitCollectionRecordsResponse load(String requestId, String deviceCode) {
+        if (deviceCode == null || deviceCode.trim().isEmpty()) {
+            throw new CockpitInvalidRequestException("设备编码不能为空");
+        }
+        deviceCode = deviceCode.trim();
+        if (deviceCode.length() > 128 || deviceCode.matches(".*[\\x00-\\x20/\\\\%].*")) {
+            throw new CockpitInvalidRequestException("设备编码不合法");
+        }
+        EquipmentBase equipment = equipmentMapper.selectOne(new QueryWrapper<EquipmentBase>()
+                .eq("equipment_code", deviceCode));
+        if (equipment == null) {
+            throw new CockpitDeviceNotFoundException("设备不存在");
+        }
+        EquipmentProfileVO profile = perceptionService.getProfile(equipment.getEquipmentId());
+        if (profile.getIdColumn() == null || profile.getIdColumn().trim().isEmpty()) {
+            return new CockpitCollectionRecordsResponse(requestId, deviceCode, "UNAVAILABLE",
+                    "设备采集表未配置或暂不支持", CockpitCollectionRecordsResponse.emptyView());
+        }
+        EquipmentProfileVO.RecordView source = profile.getRecordView();
+        List<CockpitCollectionRecordsResponse.Column> columns = new ArrayList<>();
+        for (EquipmentProfileVO.RecordColumn column : source.getColumns()) {
+            columns.add(new CockpitCollectionRecordsResponse.Column(column.getKey(), column.getLabel(),
+                    column.getUnit(), column.isAlarm()));
+        }
+        List<CockpitCollectionRecordsResponse.Row> rows = new ArrayList<>();
+        int rowIndex = 0;
+        for (EquipmentProfileVO.RecordRow row : source.getRows()) {
+            Map<String, Object> raw = profile.getRecords() != null && rowIndex < profile.getRecords().size()
+                    ? profile.getRecords().get(rowIndex) : null;
+            rowIndex++;
+            List<CockpitCollectionRecordsResponse.Cell> cells = new ArrayList<>();
+            for (EquipmentProfileVO.RecordCell cell : row.getCells()) {
+                // 原profile将缺失报警值显示成正常;仅按已有列key恢复未知,不另建字段映射。
+                boolean missing = "wide".equals(source.getLayout()) && raw != null && raw.get(cell.getKey()) == null;
+                boolean unknownFactor = "long".equals(source.getLayout()) && "indicator".equals(cell.getKey())
+                        && 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()));
+            }
+            rows.add(new CockpitCollectionRecordsResponse.Row(
+                    row.getCreateTime() == null || row.getCreateTime().trim().isEmpty() ? null : row.getCreateTime(), cells));
+        }
+        // 查询本身按create_time倒序取50条;契约再次封顶,不合并相同时刻。
+        rows.sort(Comparator.comparing(CockpitCollectionRecordsResponse.Row::getCreateTime,
+                Comparator.nullsLast(Comparator.reverseOrder())));
+        if (rows.size() > MAX_RECORDS) { rows = new ArrayList<>(rows.subList(0, MAX_RECORDS)); }
+        return new CockpitCollectionRecordsResponse(requestId, deviceCode,
+                rows.isEmpty() ? "EMPTY" : "READY", rows.isEmpty() ? "暂无采集记录" : "采集记录读取成功",
+                new CockpitCollectionRecordsResponse.RecordView(source.getLayout(), columns, rows));
+    }
+
+    private String indicatorDisplay(String key, String display) {
+        if (!"indicator".equals(key) || display == null) { return display; }
+        if (display.startsWith("COD:")) { return "化学需氧量(COD):" + display.substring(4); }
+        if (display.startsWith("PH:")) { return "酸碱度(pH):" + display.substring(3); }
+        return display;
+    }
+}