فهرست منبع

1.设备新增批量导入 2.pom版本统一

zengy 3 هفته پیش
والد
کامیت
daf869eada
32فایلهای تغییر یافته به همراه716 افزوده شده و 523 حذف شده
  1. 1 1
      environment-service/pom.xml
  2. 3 3
      environment-service/src/main/java/com/zksy/environment/config/RSServerService.java
  3. 3 4
      environment-service/src/main/java/com/zksy/environment/utils/DeviceOfflineCheckTask.java
  4. 1 1
      firefighting-pressure-service/pom.xml
  5. 1 1
      flammable-gas-service/pom.xml
  6. 1 1
      manhole-service/pom.xml
  7. 27 81
      pipe-network-service/README.md
  8. 9 4
      pipe-network-service/pom.xml
  9. 1 5
      pipe-network-service/zksy-admin/pom.xml
  10. 46 0
      pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/EquipmentBaseController.java
  11. 1 5
      pipe-network-service/zksy-common/pom.xml
  12. 1 5
      pipe-network-service/zksy-framework/pom.xml
  13. 1 5
      pipe-network-service/zksy-generator/pom.xml
  14. 1 5
      pipe-network-service/zksy-quartz/pom.xml
  15. 1 5
      pipe-network-service/zksy-system/pom.xml
  16. 52 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateDTO.java
  17. 21 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateFailure.java
  18. 35 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateResult.java
  19. 18 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/EquipmentBatchCreateService.java
  20. 245 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/impl/EquipmentBatchCreateServiceImpl.java
  21. 114 0
      pipe-network-service/zksy-system/src/main/java/com/zksy/base/util/EquipmentImportTemplateWriter.java
  22. 9 0
      pom.xml
  23. 1 1
      radar-service/pom.xml
  24. 1 1
      telemetry-service/pom.xml
  25. 120 28
      video-service/pom.xml
  26. 1 1
      water-level-service/pom.xml
  27. 1 1
      zk-api-service/pom.xml
  28. 0 102
      zk-api-service/src/main/java/com/zksy/api/enums/EquipmentTypeEnum.java
  29. 0 20
      zk-api-service/src/test/java/com/zksy/api/enums/AlarmLogOperTypeEnumTest.java
  30. 0 33
      zk-api-service/src/test/java/com/zksy/api/service/AlarmLifecycleMapperTest.java
  31. 0 135
      zk-api-service/src/test/java/com/zksy/api/service/CollectionAlarmLifecycleTest.java
  32. 0 75
      zk-api-service/src/test/java/com/zksy/api/service/CollectionAlarmNumberTest.java

+ 1 - 1
environment-service/pom.xml

@@ -32,7 +32,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>com.zksy</groupId>

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

@@ -1,7 +1,5 @@
 package com.zksy.environment.config;
 
-import static com.zksy.common.utils.CollectionSideEffects.*;
-
 import com.zksy.api.domain.WarningThreshold;
 import com.zksy.api.service.WarningThresholdService;
 import com.zksy.environment.domain.ERealTimeData;
@@ -25,13 +23,15 @@ import java.text.SimpleDateFormat;
 import java.time.LocalDateTime;
 import java.util.Date;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 
+import static com.zksy.common.utils.CollectionSideEffects.requireSaved;
+import static com.zksy.common.utils.CollectionSideEffects.run;
+
 @Component
 @Slf4j
 

+ 3 - 4
environment-service/src/main/java/com/zksy/environment/utils/DeviceOfflineCheckTask.java

@@ -1,19 +1,18 @@
 package com.zksy.environment.utils;
 
+import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
+import com.zksy.api.service.CollectionLastReceiptService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
-import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
 import org.springframework.stereotype.Component;
-import com.zksy.api.service.CollectionLastReceiptService;
 import org.springframework.web.client.RestTemplate;
 
-import java.util.Date;
 import java.util.Arrays;
+import java.util.Date;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;

+ 1 - 1
firefighting-pressure-service/pom.xml

@@ -37,7 +37,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <!-- mybatis-spring-boot-starter-test 已由 mybatis-plus-boot-starter 提供兼容版本,无需单独引入 -->
         <dependency>

+ 1 - 1
flammable-gas-service/pom.xml

@@ -32,7 +32,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>com.zksy</groupId>

+ 1 - 1
manhole-service/pom.xml

@@ -29,7 +29,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>com.zksy</groupId>

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 27 - 81
pipe-network-service/README.md


+ 9 - 4
pipe-network-service/pom.xml

@@ -11,14 +11,12 @@
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.zksy</groupId>
     <artifactId>pipe-network-service</artifactId>
-    <version>3.9.0</version>
+    <version>1.0.0</version>
 
     <name>pipe-network-service</name>
-    <url>http://www.ruoyi.vip</url>
-    <description>若依管理系统</description>
 
     <properties>
-        <zksy.version>3.9.0</zksy.version>
+        <zksy.version>1.0.0</zksy.version>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
         <java.version>11</java.version>
@@ -267,6 +265,13 @@
                     <encoding>${project.build.sourceEncoding}</encoding>
                 </configuration>
             </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <skipTests>true</skipTests>
+                </configuration>
+            </plugin>
         </plugins>
     </build>
 

+ 1 - 5
pipe-network-service/zksy-admin/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <packaging>jar</packaging>
     <artifactId>zksy-admin</artifactId>
 
-    <description>
-        web服务入口
-    </description>
-
     <dependencies>
 
         <!-- spring-boot-devtools -->

+ 46 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/base/EquipmentBaseController.java

@@ -3,19 +3,27 @@ package com.zksy.web.controller.base;
 
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.dto.EquipmentBatchCreateDTO;
+import com.zksy.base.domain.dto.EquipmentBatchCreateResult;
 import com.zksy.base.domain.vo.EquipmentBaseVO;
 import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.service.EquipmentBatchCreateService;
+import com.zksy.base.util.EquipmentImportTemplateWriter;
 import com.zksy.common.annotation.Anonymous;
 import com.zksy.common.annotation.Log;
 import com.zksy.common.core.domain.AjaxResult;
 import com.zksy.common.enums.BusinessType;
+import com.zksy.common.utils.file.FileUtils;
+import com.zksy.common.utils.poi.ExcelUtil;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
 import java.util.Map;
 
@@ -28,6 +36,9 @@ public class EquipmentBaseController {
     @Autowired
     private EquipmentBaseService service;
 
+    @Autowired
+    private EquipmentBatchCreateService equipmentBatchCreateService;
+
     @GetMapping
     @ApiOperation(value = "设备基础信息分页")
     @Anonymous
@@ -77,6 +88,41 @@ public class EquipmentBaseController {
     }
 
 
+    @PostMapping("/batch-create")
+    @ApiOperation(value = "批量创建设备(按设备类型名称、所属片区名称)")
+    @Log(title = "设备批量创建", businessType = BusinessType.INSERT)
+    public AjaxResult batchCreate(@RequestBody List<EquipmentBatchCreateDTO> rows) {
+        EquipmentBatchCreateResult result = equipmentBatchCreateService.batchCreate(rows);
+        return AjaxResult.success(result.getMessage(), result);
+    }
+
+    @PostMapping("/importTemplate")
+    @ApiOperation(value = "下载设备导入模板")
+    public void importTemplate(HttpServletResponse response) throws Exception {
+        FileUtils.setAttachmentResponseHeader(response, "设备台账导入模板.xlsx");
+        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+        response.setCharacterEncoding("utf-8");
+        EquipmentImportTemplateWriter.write(response.getOutputStream());
+    }
+
+    @PostMapping("/importData")
+    @ApiOperation(value = "导入设备数据")
+    @Log(title = "设备台账导入", businessType = BusinessType.IMPORT)
+    public AjaxResult importData(@RequestParam("file") MultipartFile file) {
+        if (file == null || file.isEmpty()) {
+            return AjaxResult.error("导入文件不能为空");
+        }
+        List<EquipmentBatchCreateDTO> rows;
+        try {
+            rows = new ExcelUtil<>(EquipmentBatchCreateDTO.class).importExcel(file.getInputStream());
+        } catch (Exception e) {
+            log.error("设备导入文件解析失败", e);
+            return AjaxResult.error("导入文件解析失败,请使用下载的模板填写:" + e.getMessage());
+        }
+        EquipmentBatchCreateResult result = equipmentBatchCreateService.batchCreate(rows);
+        return AjaxResult.success(result.getMessage(), result);
+    }
+
     @PostMapping
     @ApiOperation(value = "新增设备基础信息")
     @Log(title = "新增设备基础信息", businessType = BusinessType.INSERT)

+ 1 - 5
pipe-network-service/zksy-common/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>zksy-common</artifactId>
 
-    <description>
-        common通用工具
-    </description>
-
     <dependencies>
 
         <!-- Spring框架基本的核心工具 -->

+ 1 - 5
pipe-network-service/zksy-framework/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>zksy-framework</artifactId>
 
-    <description>
-        framework框架核心
-    </description>
-
     <dependencies>
 
         <!-- SpringBoot Web容器 -->

+ 1 - 5
pipe-network-service/zksy-generator/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>zksy-generator</artifactId>
 
-    <description>
-        generator代码生成
-    </description>
-
     <dependencies>
 
         <!-- velocity代码生成使用模板 -->

+ 1 - 5
pipe-network-service/zksy-quartz/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>zksy-quartz</artifactId>
 
-    <description>
-        quartz定时任务
-    </description>
-
     <dependencies>
 
         <!-- 定时任务 -->

+ 1 - 5
pipe-network-service/zksy-system/pom.xml

@@ -5,16 +5,12 @@
     <parent>
         <artifactId>pipe-network-service</artifactId>
         <groupId>com.zksy</groupId>
-        <version>3.9.0</version>
+        <version>1.0.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>zksy-system</artifactId>
 
-    <description>
-        system系统模块
-    </description>
-
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 52 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateDTO.java

@@ -0,0 +1,52 @@
+package com.zksy.base.domain.dto;
+
+import com.zksy.common.annotation.Excel;
+import lombok.Data;
+
+/**
+ * 设备批量创建行,同时作为 Excel 导入模板的列定义。
+ *
+ * <p>设备类型、所属片区传中文名称,由后端按 {@code equipment_type.type_name}
+ * 与 {@code DistrictEnum} 查表/枚举转换成 {@code equipmentTypeId}、{@code district},
+ * 不依赖任何硬编码的设备类型枚举。所有列用 String 接收,便于逐行给出失败原因。</p>
+ *
+ * <p>列名以 {@code *} 开头表示必填,{@code EquipmentImportTemplateWriter} 会把该星号渲染成红色;
+ * 导入时表头名与 {@code @Excel(name)} 保持一致,因此必填列的表头同样带 {@code *}。</p>
+ */
+@Data
+public class EquipmentBatchCreateDTO {
+
+    @Excel(name = "*设备编码", sort = 1, width = 22)
+    private String equipmentCode;
+
+    @Excel(name = "*设备名称", sort = 2, width = 22)
+    private String equipmentName;
+
+    @Excel(name = "*设备类型", sort = 3, width = 26,
+            combo = {
+                    "平升压力流量终端",
+                    "消火栓压力监测终端",
+                    "漏失监测仪",
+                    "视频监控(排口+内涝点)",
+                    "平升液位流量终端",
+                    "视频监控(场站)",
+                    "可燃气体检测仪",
+                    "排水窨井盖监测"
+            },
+            prompt = "必填,请从下拉框中选择设备类型")
+    private String equipmentTypeName;
+
+    @Excel(name = "*所属片区", sort = 4, width = 16,
+            combo = {"城南", "城北", "太常"},
+            prompt = "必填,请从下拉框中选择所属片区")
+    private String districtName;
+
+    @Excel(name = "安装位置", sort = 5, width = 32)
+    private String equipmentLocation;
+
+    @Excel(name = "经度", sort = 6, width = 16)
+    private String longitude;
+
+    @Excel(name = "纬度", sort = 7, width = 16)
+    private String latitude;
+}

+ 21 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateFailure.java

@@ -0,0 +1,21 @@
+package com.zksy.base.domain.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * 设备批量创建失败明细:按「设备编码、失败原因」输出。
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class EquipmentBatchCreateFailure {
+
+    @ApiModelProperty("设备编码")
+    private String equipmentCode;
+
+    @ApiModelProperty("失败原因")
+    private String reason;
+}

+ 35 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/domain/dto/EquipmentBatchCreateResult.java

@@ -0,0 +1,35 @@
+package com.zksy.base.domain.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 设备批量创建结果:成功数、失败数及失败明细。
+ */
+@Data
+public class EquipmentBatchCreateResult {
+
+    @ApiModelProperty("创建成功条数")
+    private int successCount;
+
+    @ApiModelProperty("创建失败条数")
+    private int failureCount;
+
+    @ApiModelProperty("失败明细(设备编码、失败原因)")
+    private List<EquipmentBatchCreateFailure> failures = new ArrayList<>();
+
+    @ApiModelProperty("结果提示")
+    private String message;
+
+    public void addFailure(String equipmentCode, String reason) {
+        failures.add(new EquipmentBatchCreateFailure(equipmentCode, reason));
+    }
+
+    public void finish() {
+        failureCount = failures.size();
+        message = String.format("创建完成:成功 %d 条,失败 %d 条", successCount, failureCount);
+    }
+}

+ 18 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/service/EquipmentBatchCreateService.java

@@ -0,0 +1,18 @@
+package com.zksy.base.service;
+
+import com.zksy.base.domain.dto.EquipmentBatchCreateDTO;
+import com.zksy.base.domain.dto.EquipmentBatchCreateResult;
+
+import java.util.List;
+
+/**
+ * 设备批量创建:独立于单个新增接口,按名称解析类型与片区。
+ */
+public interface EquipmentBatchCreateService {
+
+    /**
+     * 设备类型按 equipment_type.type_name 查表转换,所属片区按 DistrictEnum 转换;
+     * 逐行创建并初始化设备状态,单行失败只记录原因,不影响其余行。
+     */
+    EquipmentBatchCreateResult batchCreate(List<EquipmentBatchCreateDTO> rows);
+}

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

@@ -0,0 +1,245 @@
+package com.zksy.base.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.domain.EquipmentStatus;
+import com.zksy.base.domain.EquipmentType;
+import com.zksy.base.domain.dto.EquipmentBatchCreateDTO;
+import com.zksy.base.domain.dto.EquipmentBatchCreateResult;
+import com.zksy.base.enums.AlarmStatusEnum;
+import com.zksy.base.enums.CurrentStatusEnum;
+import com.zksy.base.enums.DistrictEnum;
+import com.zksy.base.enums.OnlineStatusEnum;
+import com.zksy.base.mapper.EquipmentStatusMapper;
+import com.zksy.base.service.EquipmentBaseService;
+import com.zksy.base.service.EquipmentBatchCreateService;
+import com.zksy.base.service.EquipmentTypeService;
+import com.zksy.common.exception.ServiceException;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * 设备批量创建实现。
+ *
+ * <p>不复用单个新增的 {@code saveWithCheck}:单新增按 {@code equipment_type_id} 校验,
+ * 批量创建入参是中文类型名,按 {@code equipment_type.type_name} 查表转换后直接落库。
+ * 校验口径与单新增保持一致(类型必须存在、编码唯一、初始化 equipment_status),
+ * 且不开启整体事务,单行失败不影响其余行。</p>
+ */
+@Slf4j
+@Service
+public class EquipmentBatchCreateServiceImpl implements EquipmentBatchCreateService {
+
+    /** 已存在编码的统一提示:不做任何修改。 */
+    private static final String DUPLICATE_REASON = "设备编码已存在,未做任何修改";
+
+    private static final int CODE_QUERY_BATCH = 500;
+
+    @Autowired
+    private EquipmentBaseService equipmentBaseService;
+
+    @Autowired
+    private EquipmentTypeService equipmentTypeService;
+
+    @Autowired
+    private EquipmentStatusMapper equipmentStatusMapper;
+
+    @Override
+    public EquipmentBatchCreateResult batchCreate(List<EquipmentBatchCreateDTO> rows) {
+        EquipmentBatchCreateResult result = new EquipmentBatchCreateResult();
+        if (rows == null || rows.isEmpty()) {
+            result.finish();
+            return result;
+        }
+
+        Map<String, Integer> typeIndex = loadTypeIndex();
+        Set<String> existingCodes = loadExistingCodes(rows);
+        Set<String> createdCodes = new HashSet<>();
+
+        for (EquipmentBatchCreateDTO row : rows) {
+            String code = trim(row == null ? null : row.getEquipmentCode());
+            String reason = validate(row, code, typeIndex, existingCodes, createdCodes);
+            if (reason != null) {
+                result.addFailure(code, reason);
+                continue;
+            }
+            try {
+                EquipmentBase entity = buildEntity(row, code, typeIndex);
+                if (!equipmentBaseService.save(entity)) {
+                    result.addFailure(code, "设备保存失败");
+                    continue;
+                }
+                initEquipmentStatus(entity.getEquipmentId());
+                result.setSuccessCount(result.getSuccessCount() + 1);
+                createdCodes.add(code);
+            } catch (DataIntegrityViolationException e) {
+                result.addFailure(code, DUPLICATE_REASON);
+            } catch (ServiceException e) {
+                result.addFailure(code, e.getMessage() == null ? "设备保存失败" : e.getMessage());
+            } catch (Exception e) {
+                log.error("设备批量创建失败,设备编码={}", code, e);
+                result.addFailure(code, e.getMessage() == null ? "设备保存失败" : e.getMessage());
+            }
+        }
+
+        result.finish();
+        return result;
+    }
+
+    /** 以 equipment_type.type_name 为唯一权威建立「名称 -> 主键 id」索引。 */
+    private Map<String, Integer> loadTypeIndex() {
+        Map<String, Integer> index = new HashMap<>();
+        List<EquipmentType> types = equipmentTypeService.list();
+        if (types == null) {
+            return index;
+        }
+        for (EquipmentType type : types) {
+            if (type == null || type.getId() == null || isBlank(type.getTypeName())) {
+                continue;
+            }
+            index.putIfAbsent(normalize(type.getTypeName()), type.getId());
+        }
+        return index;
+    }
+
+    /** 一次性预查库中已存在的设备编码,避免逐行查询。 */
+    private Set<String> loadExistingCodes(List<EquipmentBatchCreateDTO> rows) {
+        List<String> codes = rows.stream()
+                .filter(Objects::nonNull)
+                .map(row -> trim(row.getEquipmentCode()))
+                .filter(code -> !code.isEmpty())
+                .distinct()
+                .collect(Collectors.toList());
+        Set<String> existing = new HashSet<>();
+        for (int i = 0; i < codes.size(); i += CODE_QUERY_BATCH) {
+            List<String> batch = codes.subList(i, Math.min(i + CODE_QUERY_BATCH, codes.size()));
+            equipmentBaseService.list(new LambdaQueryWrapper<EquipmentBase>()
+                            .select(EquipmentBase::getEquipmentCode)
+                            .in(EquipmentBase::getEquipmentCode, batch))
+                    .forEach(item -> existing.add(item.getEquipmentCode()));
+        }
+        return existing;
+    }
+
+    private String validate(EquipmentBatchCreateDTO row, String code,
+                            Map<String, Integer> typeIndex,
+                            Set<String> existingCodes, Set<String> createdCodes) {
+        if (row == null) {
+            return "数据行不能为空";
+        }
+        if (code.isEmpty()) {
+            return "设备编码不能为空";
+        }
+        if (isBlank(row.getEquipmentName())) {
+            return "设备名称不能为空";
+        }
+        if (isBlank(row.getEquipmentTypeName())) {
+            return "设备类型不能为空";
+        }
+        String typeName = trim(row.getEquipmentTypeName());
+        if (resolveTypeId(typeName, typeIndex) == null) {
+            return "设备类型「" + typeName + "」在 equipment_type.type_name 中不存在";
+        }
+        if (isBlank(row.getDistrictName())) {
+            return "所属片区不能为空";
+        }
+        String districtName = trim(row.getDistrictName());
+        if (resolveDistrict(districtName) == null) {
+            return "所属片区「" + districtName + "」无效,仅支持城南、城北、太常";
+        }
+        String longitude = trim(row.getLongitude());
+        if (!longitude.isEmpty() && !isNumber(longitude)) {
+            return "经度格式不正确,应为数字";
+        }
+        String latitude = trim(row.getLatitude());
+        if (!latitude.isEmpty() && !isNumber(latitude)) {
+            return "纬度格式不正确,应为数字";
+        }
+        if (existingCodes.contains(code) || createdCodes.contains(code)) {
+            return DUPLICATE_REASON;
+        }
+        return null;
+    }
+
+    private EquipmentBase buildEntity(EquipmentBatchCreateDTO row, String code,
+                                      Map<String, Integer> typeIndex) {
+        EquipmentBase entity = new EquipmentBase();
+        entity.setEquipmentCode(code);
+        entity.setEquipmentName(trim(row.getEquipmentName()));
+        entity.setEquipmentTypeId(resolveTypeId(trim(row.getEquipmentTypeName()), typeIndex));
+        entity.setDistrict(resolveDistrict(trim(row.getDistrictName())));
+        entity.setEquipmentLocation(nullIfBlank(row.getEquipmentLocation()));
+        String longitude = trim(row.getLongitude());
+        if (!longitude.isEmpty()) {
+            entity.setLongitude(new BigDecimal(longitude));
+        }
+        String latitude = trim(row.getLatitude());
+        if (!latitude.isEmpty()) {
+            entity.setLatitude(new BigDecimal(latitude));
+        }
+        return entity;
+    }
+
+    private Integer resolveTypeId(String typeName, Map<String, Integer> typeIndex) {
+        return typeIndex.get(normalize(typeName));
+    }
+
+    private Integer resolveDistrict(String districtName) {
+        for (DistrictEnum item : DistrictEnum.values()) {
+            if (item.getDesc().equals(districtName)) {
+                return item.getCode();
+            }
+        }
+        return null;
+    }
+
+    /** 与单个新增一致:新增设备后初始化一条「在用 / 正常 / 离线」状态记录。 */
+    private void initEquipmentStatus(String equipmentId) {
+        EquipmentStatus status = new EquipmentStatus();
+        status.setEquipmentId(equipmentId);
+        status.setCurrentStatus(CurrentStatusEnum.IN_USE.getCode());
+        status.setAlarmStatus(AlarmStatusEnum.NORMAL.getCode());
+        status.setOnlineStatus(OnlineStatusEnum.OFFLINE.getCode());
+        status.setStatusUpdateTime(LocalDateTime.now());
+        equipmentStatusMapper.insert(status);
+    }
+
+    private static boolean isNumber(String value) {
+        try {
+            new BigDecimal(value);
+            return true;
+        } catch (NumberFormatException e) {
+            return false;
+        }
+    }
+
+    /** 仅归一化全角括号、加号与空白,兼容填写写法差异,不做名称猜测映射。 */
+    private static String normalize(String value) {
+        return trim(value).replace("(", "(").replace(")", ")")
+                .replace("+", "+").replaceAll("\\s+", "");
+    }
+
+    private static String trim(String value) {
+        return value == null ? "" : value.trim();
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    private static String nullIfBlank(String value) {
+        return isBlank(value) ? null : value.trim();
+    }
+}

+ 114 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/util/EquipmentImportTemplateWriter.java

@@ -0,0 +1,114 @@
+package com.zksy.base.util;
+
+import com.zksy.base.domain.dto.EquipmentBatchCreateDTO;
+import com.zksy.common.annotation.Excel;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.DataValidation;
+import org.apache.poi.ss.usermodel.DataValidationConstraint;
+import org.apache.poi.ss.usermodel.DataValidationHelper;
+import org.apache.poi.ss.usermodel.FillPatternType;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.RichTextString;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.VerticalAlignment;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.util.CellRangeAddressList;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * 设备导入模板生成。
+ *
+ * <p>不使用 {@code ExcelUtil.importTemplateExcel}:它基于 SXSSFWorkbook,写出时会丢失
+ * 富文本格式,必填列的红色 {@code *} 无法保留。这里用 XSSFWorkbook 生成,表头文字、
+ * 列宽与下拉字典统一从 {@link EquipmentBatchCreateDTO} 的 {@code @Excel} 注解读取,
+ * 保证模板表头与导入解析时的列名完全一致。</p>
+ */
+public final class EquipmentImportTemplateWriter {
+
+    /** 下拉校验覆盖的数据行数。 */
+    private static final int VALIDATION_LAST_ROW = 1000;
+
+    private EquipmentImportTemplateWriter() {
+    }
+
+    public static void write(OutputStream os) throws IOException {
+        try (Workbook wb = new XSSFWorkbook()) {
+            Sheet sheet = wb.createSheet("设备台账");
+            CellStyle headerStyle = createHeaderStyle(wb);
+            List<Field> fields = excelFields();
+            Row header = sheet.createRow(0);
+            header.setHeightInPoints(24);
+
+            for (int column = 0; column < fields.size(); column++) {
+                Excel attr = fields.get(column).getAnnotation(Excel.class);
+                Cell cell = header.createCell(column);
+                cell.setCellStyle(headerStyle);
+                cell.setCellValue(buildHeaderText(wb, attr.name()));
+                sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
+                if (attr.combo().length > 0) {
+                    addCombo(sheet, attr.combo(), column);
+                }
+            }
+            wb.write(os);
+        }
+    }
+
+    /** 列名以 {@code *} 开头表示必填:首字符渲染成红色,其余字符沿用表头样式。 */
+    private static RichTextString buildHeaderText(Workbook wb, String name) {
+        RichTextString text = wb.getCreationHelper().createRichTextString(name);
+        if (!name.startsWith("*")) {
+            return text;
+        }
+        Font requiredFont = wb.createFont();
+        requiredFont.setBold(true);
+        requiredFont.setColor(IndexedColors.RED.getIndex());
+        text.applyFont(0, 1, requiredFont);
+        return text;
+    }
+
+    private static void addCombo(Sheet sheet, String[] options, int column) {
+        DataValidationHelper helper = sheet.getDataValidationHelper();
+        DataValidationConstraint constraint = helper.createExplicitListConstraint(options);
+        DataValidation validation = helper.createValidation(constraint,
+                new CellRangeAddressList(1, VALIDATION_LAST_ROW, column, column));
+        validation.setSuppressDropDownArrow(true);
+        validation.setShowErrorBox(true);
+        sheet.addValidationData(validation);
+    }
+
+    private static CellStyle createHeaderStyle(Workbook wb) {
+        Font font = wb.createFont();
+        font.setBold(true);
+        font.setColor(IndexedColors.WHITE.getIndex());
+        CellStyle style = wb.createCellStyle();
+        style.setFont(font);
+        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
+        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+        style.setAlignment(HorizontalAlignment.CENTER);
+        style.setVerticalAlignment(VerticalAlignment.CENTER);
+        return style;
+    }
+
+    /** 与 ExcelUtil 相同的排序口径,保证模板列顺序与 DTO 定义一致。 */
+    private static List<Field> excelFields() {
+        List<Field> fields = new ArrayList<>();
+        for (Field field : EquipmentBatchCreateDTO.class.getDeclaredFields()) {
+            if (field.isAnnotationPresent(Excel.class)) {
+                fields.add(field);
+            }
+        }
+        fields.sort(Comparator.comparingInt(field -> field.getAnnotation(Excel.class).sort()));
+        return fields;
+    }
+}

+ 9 - 0
pom.xml

@@ -163,6 +163,15 @@
                         <target>11</target> <!-- depending on your project -->
                     </configuration>
                 </plugin>
+                <plugin>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-compiler-plugin</artifactId>
+                    <version>3.8.1</version>
+                    <configuration>
+                        <source>11</source> <!-- depending on your project -->
+                        <target>11</target> <!-- depending on your project -->
+                    </configuration>
+                </plugin>
             </plugins>
         </pluginManagement>
     </build>

+ 1 - 1
radar-service/pom.xml

@@ -37,7 +37,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 1 - 1
telemetry-service/pom.xml

@@ -37,7 +37,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 120 - 28
video-service/pom.xml

@@ -1,29 +1,121 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
-  <modelVersion>4.0.0</modelVersion>
-  <parent><groupId>com.zksy</groupId><artifactId>pipe-ner-server</artifactId><version>1.0.0</version></parent>
-  <artifactId>video-service</artifactId>
-  <description>独立 GB28181 信令、设备采集及媒体控制服务</description>
-  <dependencies>
-    <dependency><groupId>com.zksy</groupId><artifactId>zksy-common</artifactId><version>3.9.0</version><exclusions><exclusion><groupId>com.zksy</groupId><artifactId>minioutil</artifactId></exclusion></exclusions></dependency>
-    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
-    <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.6.1</version></dependency>
-    <dependency><groupId>cn.com.kingbase</groupId><artifactId>kingbase8</artifactId></dependency>
-    <dependency><groupId>javax.sip</groupId><artifactId>jain-sip-ri</artifactId><version>1.2.307</version></dependency>
-    <dependency><groupId>org.slf4j</groupId><artifactId>log4j-over-slf4j</artifactId></dependency>
-    <dependency><groupId>org.dom4j</groupId><artifactId>dom4j</artifactId><version>2.1.3</version></dependency>
-    <dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>32.1.3-jre</version></dependency>
-    <dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2-extension</artifactId><version>2.0.17</version></dependency>
-    <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version></dependency>
-    <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>logging-interceptor</artifactId><version>4.10.0</version></dependency>
-    <dependency><groupId>io.github.rburgst</groupId><artifactId>okhttp-digest</artifactId><version>2.7</version></dependency>
-    <dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>6.2.2</version></dependency>
-    <dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-core</artifactId></dependency>
-    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.34</version><scope>provided</scope></dependency>
-    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
-    <!-- 与其他采集服务一致:bootstrap 配置、Nacos 配置中心和服务注册。 -->
-    <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency>
-    <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency>
-    <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
-  </dependencies>
-  <build><finalName>video-service</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.zksy.video.VideoApplication</mainClass></configuration></plugin></plugins></build>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.zksy</groupId>
+        <artifactId>pipe-ner-server</artifactId>
+        <version>1.0.0</version>
+    </parent>
+    <artifactId>video-service</artifactId>
+    <description>独立 GB28181 信令、设备采集及媒体控制服务</description>
+    <dependencies>
+        <dependency>
+            <groupId>com.zksy</groupId>
+            <artifactId>zksy-common</artifactId>
+            <version>1.0.0</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>com.zksy</groupId>
+                    <artifactId>minioutil</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-websocket</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
+            <version>3.6.1</version>
+        </dependency>
+        <dependency>
+            <groupId>cn.com.kingbase</groupId>
+            <artifactId>kingbase8</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>javax.sip</groupId>
+            <artifactId>jain-sip-ri</artifactId>
+            <version>1.2.307</version>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>log4j-over-slf4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.dom4j</groupId>
+            <artifactId>dom4j</artifactId>
+            <version>2.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>32.1.3-jre</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2-extension</artifactId>
+            <version>2.0.17</version>
+        </dependency>
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>okhttp</artifactId>
+            <version>4.10.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>logging-interceptor</artifactId>
+            <version>4.10.0</version>
+        </dependency>
+        <dependency>
+            <groupId>io.github.rburgst</groupId>
+            <artifactId>okhttp-digest</artifactId>
+            <version>2.7</version>
+        </dependency>
+        <dependency>
+            <groupId>com.github.oshi</groupId>
+            <artifactId>oshi-core</artifactId>
+            <version>6.2.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.session</groupId>
+            <artifactId>spring-session-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.18.34</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <!-- 与其他采集服务一致:bootstrap 配置、Nacos 配置中心和服务注册。 -->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-bootstrap</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
+        </dependency>
+    </dependencies>
+    <build>
+        <finalName>video-service</finalName>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <configuration>
+                    <mainClass>com.zksy.video.VideoApplication</mainClass>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 </project>

+ 1 - 1
water-level-service/pom.xml

@@ -36,7 +36,7 @@
         <dependency>
             <groupId>com.zksy</groupId>
             <artifactId>zksy-system</artifactId>
-            <version>3.9.0</version>
+            <version>1.0.0</version>
         </dependency>
         <dependency>
             <groupId>com.zksy</groupId>

+ 1 - 1
zk-api-service/pom.xml

@@ -7,7 +7,6 @@
         <artifactId>pipe-ner-server</artifactId>
         <version>1.0.0</version>
     </parent>
-<!--    <groupId>org.example</groupId>-->
     <artifactId>zk-api-service</artifactId>
 
     <properties>
@@ -97,6 +96,7 @@
     </dependencies>
 
     <build>
+        <finalName>${project.artifactId}</finalName>
         <plugins>
             <plugin>
                 <groupId>org.springframework.boot</groupId>

+ 0 - 102
zk-api-service/src/main/java/com/zksy/api/enums/EquipmentTypeEnum.java

@@ -1,102 +0,0 @@
-package com.zksy.api.enums;
-
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * 设备类型枚举
- *
- * @author zengy
- */
-@Getter
-@AllArgsConstructor
-public enum EquipmentTypeEnum {
-    // ========== 一级根节点 parentId = 0 ==========
-    ROOT_WATER_SUPPLY_DEVICE(1, 0, "供水设备"),
-    ROOT_DRAINAGE_DEVICE(2, 0, "排水设备"),
-    ROOT_GAS_DEVICE(3, 0, "燃气设备"),
-    ROOT_MANHOLE_DEVICE(4, 0, "窨井设备"),
-
-    // ========== 二级子设备 ==========
-    ULTRASONIC_FLOWMETER(11, 1, "超声波外夹流量计"),
-    PRESSURE_GAUGE(12, 1, "压力计"),
-    LEAK_MONITOR(13, 1, "漏失在线监测仪"),
-    FIRE_HYDRANT_PRESSURE_TERMINAL(14, 1, "消火栓压力监测终端"),
-
-    RENKE_4G_COLLECTOR(15, 2, "仁科4G采集器"),
-    RADAR_LEVEL_GAUGE(16, 2, "雷达液位计"),
-    FLOWMETER(17, 2, "流量计"),
-    TELEMETRY_TERMINAL_GENERAL(18, 2, "遥测终端机(通用)"),
-    WATER_LEVEL_GAUGE_FLOOD(19, 2, "水位计(易涝点)"),
-    VIDEO_MONITOR_OUT_WL(20, 2, "视频监控(排口+内涝点)"),
-
-    ELECTRIC_CONTROL_VALVE(21, 3, "电动控制阀"),
-    COMBUSTIBLE_GAS_DETECTOR(22, 3, "可燃气体检测仪"),
-    VIDEO_MONITOR_STATION(23, 3, "视频监控(场站)"),
-
-    MANHOLE_COVER_MONITOR(24, 4, "窨井盖监测");
-
-    /**
-     * 设备类型ID(主键id)
-     */
-    private final Integer id;
-    /**
-     * 父节点ID(parent_id)
-     */
-    private final Integer parentId;
-    /**
-     * 设备名称
-     */
-    private final String desc;
-
-    /**
-     * 按 id 获取枚举
-     */
-    public static EquipmentTypeEnum getById(Integer id) {
-        if (id == null) {
-            return null;
-        }
-        for (EquipmentTypeEnum item : values()) {
-            if (Objects.equals(item.id, id)) {
-                return item;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 按 id 获取描述,未知返回空字符串
-     */
-    public static String getDescById(Integer id) {
-        EquipmentTypeEnum item = getById(id);
-        return item == null ? "" : item.getDesc();
-    }
-
-    /**
-     * 判断是否为根节点
-     */
-    public boolean isRoot() {
-        return Objects.equals(this.parentId, 0);
-    }
-
-    /**
-     * 根据父节点id,查询其下所有子设备
-     */
-    public static List<EquipmentTypeEnum> getChildrenByParentId(Integer parentId) {
-        List<EquipmentTypeEnum> children = new ArrayList<>();
-        if (parentId == null) {
-            return children;
-        }
-        for (EquipmentTypeEnum item : values()) {
-            if (!item.isRoot() && Objects.equals(item.parentId, parentId)) {
-                children.add(item);
-            }
-        }
-        return children;
-    }
-}

+ 0 - 20
zk-api-service/src/test/java/com/zksy/api/enums/AlarmLogOperTypeEnumTest.java

@@ -1,20 +0,0 @@
-package com.zksy.api.enums;
-
-import org.junit.jupiter.api.Test;
-import java.util.Arrays;
-import static org.junit.jupiter.api.Assertions.*;
-
-class AlarmLogOperTypeEnumTest {
-    @Test void exposesTheCompleteAlarmLogDictionaryWithoutWorkOrderTypes() {
-        assertArrayEquals(new int[]{0, 1, 2, 3}, Arrays.stream(AlarmLogOperTypeEnum.values())
-                .mapToInt(AlarmLogOperTypeEnum::getCode).toArray());
-        assertArrayEquals(new String[]{"报警触发", "确认报警", "误报警", "报警处理"},
-                Arrays.stream(AlarmLogOperTypeEnum.values()).map(AlarmLogOperTypeEnum::getLabel).toArray(String[]::new));
-        for (AlarmLogOperTypeEnum type : AlarmLogOperTypeEnum.values()) {
-            assertSame(type, AlarmLogOperTypeEnum.fromCode(type.getCode()));
-        }
-        assertNull(AlarmLogOperTypeEnum.fromCode(null));
-        assertNull(AlarmLogOperTypeEnum.fromCode(4));
-        assertNull(AlarmLogOperTypeEnum.fromCode(5));
-    }
-}

+ 0 - 33
zk-api-service/src/test/java/com/zksy/api/service/AlarmLifecycleMapperTest.java

@@ -1,33 +0,0 @@
-package com.zksy.api.service;
-
-import com.baomidou.mybatisplus.core.MybatisConfiguration;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.zksy.api.mapper.AlarmDataMapper;
-import com.zksy.api.mapper.AlarmLogMapper;
-import org.junit.jupiter.api.Test;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.*;
-import static org.junit.jupiter.api.Assertions.*;
-
-class AlarmLifecycleMapperTest {
-    @Test void renderActualLifecycleStatementsForDatabaseTests() throws Exception {
-        MybatisConfiguration config = new MybatisConfiguration();
-        config.addMapper(AlarmDataMapper.class); config.addMapper(AlarmLogMapper.class);
-        Map<String, Object> result=new LinkedHashMap<>();
-        Map<Class<?>,List<String>> methods=new LinkedHashMap<>();
-        methods.put(AlarmDataMapper.class,Arrays.asList("lockAlarmNumberGeneration","existsAlarmNo","selectRecoverableAlarmIdsForUpdate","markAlarmRecovered"));
-        methods.put(AlarmLogMapper.class,Arrays.asList("insertLifecycleIfAbsent","existsLifecycle","latestLogId"));
-        for (Map.Entry<Class<?>,List<String>> entry: methods.entrySet()) {
-            for (String name:entry.getValue()) {
-                var bound=config.getMappedStatement(entry.getKey().getName()+"."+name).getBoundSql(new HashMap<>());
-                List<String> params=new ArrayList<>();
-                bound.getParameterMappings().forEach(p->params.add(p.getProperty()));
-                result.put(name,Map.of("sql",bound.getSql(),"params",params));
-            }
-        }
-        assertFalse(result.get("selectRecoverableAlarmIdsForUpdate").toString().contains("alarm_time"));
-        Files.createDirectories(Paths.get("target"));
-        new ObjectMapper().writeValue(Paths.get("target/alarm-lifecycle-queries.json").toFile(),result);
-    }
-}

+ 0 - 135
zk-api-service/src/test/java/com/zksy/api/service/CollectionAlarmLifecycleTest.java

@@ -1,135 +0,0 @@
-package com.zksy.api.service;
-
-import com.zksy.api.domain.AlarmData;
-import com.zksy.api.mapper.AlarmDataMapper;
-import com.zksy.api.mapper.AlarmLogMapper;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.support.SimpleTransactionStatus;
-import java.math.BigDecimal;
-import java.util.Arrays;
-import java.util.Collections;
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class CollectionAlarmLifecycleTest {
-    private final AlarmDataMapper mapper = mock(AlarmDataMapper.class);
-    private final AlarmLogMapper logs = mock(AlarmLogMapper.class);
-    private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
-    private final CollectionAlarmWriter writer = new CollectionAlarmWriter(mapper, logs, manager);
-
-    @BeforeEach void setup() {
-        when(manager.getTransaction(any())).thenReturn(new SimpleTransactionStatus());
-        when(mapper.lockAlarmKey("D1", "PRESSURE")).thenReturn(1);
-        when(mapper.lockAlarmNumberGeneration()).thenReturn(1);
-        when(mapper.markAlarmRecovered(anyString())).thenReturn(1);
-        when(mapper.selectWarningName("PRESSURE")).thenReturn("压力越界");
-        when(mapper.selectRecoverableAlarmIdsForUpdate("D1", "PRESSURE")).thenReturn(Collections.singletonList("a1"));
-        when(logs.insertLifecycleIfAbsent(anyString(),anyInt(),anyString(),anyString(),any(),anyLong())).thenReturn(1);
-        when(mapper.insert(any(AlarmData.class))).thenAnswer(call -> {
-            ((AlarmData)call.getArgument(0)).setId("a1"); return 1;
-        });
-    }
-    @Test void creationWritesDescriptionDirectlyWithoutAnyTrigger() {
-        AlarmData alarm = alarm(); alarm.setActualValue(BigDecimal.ZERO); alarm.setMaxValue(BigDecimal.TEN);
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        assertEquals("压力越界\n实际值:0;阈值:上限 10", alarm.getAlarmContent());
-        var ordered = inOrder(mapper,logs,manager);
-        ordered.verify(mapper).insert(alarm);
-        ordered.verify(logs).insertLifecycleIfAbsent(eq("a1"),eq(0),
-                eq("系统触发报警;报警单号:"+alarm.getAlarmNo()+";报警描述:"+alarm.getAlarmContent()+";实际值:0;触发时上限:10"),eq("监测系统"),any(),anyLong());
-        ordered.verify(manager).commit(any());
-    }
-    @Test void absentActualValueDoesNotIncludeThresholdPlaceholders() {
-        AlarmData alarm=alarm(); alarm.setMaxValue(BigDecimal.ZERO);
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        verify(logs).insertLifecycleIfAbsent(eq("a1"),eq(0),
-                eq("系统触发报警;报警单号:"+alarm.getAlarmNo()+";报警描述:压力越界"),eq("监测系统"),any(),anyLong());
-    }
-    @Test void contentMatchesFrontendThresholdDescriptionRule() {
-        AlarmData alarm=alarm(); alarm.setActualValue(BigDecimal.ZERO); alarm.setMinValue(BigDecimal.ZERO);
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        assertEquals("压力越界达到或低于下限\n实际值:0;阈值:下限 0", alarm.getAlarmContent());
-    }
-    @Test void contentIncludesUpperThresholdAndUnit() {
-        when(mapper.selectWarningUnit("PRESSURE")).thenReturn("mg/L");
-        AlarmData alarm = alarm();
-        alarm.setActualValue(new BigDecimal("60.750"));
-        alarm.setMaxValue(new BigDecimal("60.00"));
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        assertEquals("压力越界达到或超过上限\n实际值:60.75 mg/L;阈值:上限 60 mg/L", alarm.getAlarmContent());
-    }
-    @Test void contentIncludesLowerThresholdAndUnit() {
-        when(mapper.selectWarningUnit("PRESSURE")).thenReturn("mg/L");
-        AlarmData alarm = alarm();
-        alarm.setActualValue(new BigDecimal("25.78"));
-        alarm.setMinValue(new BigDecimal("5"));
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        assertEquals("压力越界\n实际值:25.78 mg/L;阈值:下限 5 mg/L", alarm.getAlarmContent());
-    }
-    @Test void contentIncludesRangeAndZeroValue() {
-        when(mapper.selectWarningUnit("PRESSURE")).thenReturn("μS/cm");
-        AlarmData alarm = alarm();
-        alarm.setActualValue(BigDecimal.ZERO);
-        alarm.setMinValue(new BigDecimal("100"));
-        alarm.setMaxValue(new BigDecimal("5000"));
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        assertEquals("压力越界达到或低于下限\n实际值:0 μS/cm;阈值:100 ~ 5000 μS/cm", alarm.getAlarmContent());
-    }
-    @Test void everyRecoveredRowGetsLogBeforeCommit() {
-        when(mapper.selectRecoverableAlarmIdsForUpdate("D1", "PRESSURE")).thenReturn(Arrays.asList("a1","a2"));
-        assertEquals(2, writer.markRecovered("D1", "PRESSURE"));
-        var ordered = inOrder(manager, mapper, logs);
-        ordered.verify(mapper).selectRecoverableAlarmIdsForUpdate("D1", "PRESSURE");
-        for (String id : Arrays.asList("a1","a2")) {
-            ordered.verify(mapper).markAlarmRecovered(id);
-            ordered.verify(logs).insertLifecycleIfAbsent(eq(id),eq(3),eq("监测恢复,报警自动解除"),eq("系统自动"),any(),anyLong());
-        }
-        ordered.verify(manager).commit(any());
-    }
-    @Test void repeatedRecoveryDoesNotWriteLogs() {
-        when(mapper.selectRecoverableAlarmIdsForUpdate("D1", "PRESSURE")).thenReturn(Collections.emptyList());
-        assertEquals(0, writer.markRecovered("D1", "PRESSURE"));
-        verifyNoInteractions(logs); verify(mapper,never()).markAlarmRecovered(anyString());
-    }
-    @Test void recoveryLogFailureRollsBackStatusUpdate() {
-        DataIntegrityViolationException failure = new DataIntegrityViolationException("alarm_log insert failed");
-        when(logs.insertLifecycleIfAbsent(eq("a1"),eq(3),anyString(),anyString(),any(),anyLong())).thenThrow(failure);
-        assertSame(failure, assertThrows(DataIntegrityViolationException.class, () -> writer.markRecovered("D1", "PRESSURE")));
-        verify(mapper).markAlarmRecovered("a1");
-        verify(manager).rollback(any()); verify(manager,never()).commit(any());
-    }
-    @Test void creationLogFailureRollsBackAlarmInsert() {
-        when(logs.insertLifecycleIfAbsent(eq("a1"),eq(0),anyString(),anyString(),any(),anyLong())).thenReturn(0);
-        assertThrows(IllegalStateException.class, () -> writer.saveOrUpdateUnhandled(alarm()));
-        verify(mapper).insert(any(AlarmData.class));
-        verify(manager).rollback(any()); verify(manager,never()).commit(any());
-    }
-    @Test void existingEventLogIsAcceptedWithoutDuplicate() {
-        when(logs.insertLifecycleIfAbsent(eq("a1"),eq(0),anyString(),anyString(),any(),anyLong())).thenReturn(0);
-        when(logs.existsLifecycle("a1",0,0L)).thenReturn(true);
-        assertTrue(writer.saveOrUpdateUnhandled(alarm())); verify(manager).commit(any());
-    }
-    @Test void reusedAlarmDoesNotWriteAnotherCreatedLog() {
-        AlarmData existing=alarm(); existing.setId("existing");
-        when(mapper.selectUnhandledAlarmForUpdate("D1","PRESSURE")).thenReturn(existing);
-        assertFalse(writer.saveOrUpdateUnhandled(alarm())); verifyNoInteractions(logs);
-    }
-    @Test void failedStatusUpdateDoesNotWriteRecoveryLog() {
-        when(mapper.markAlarmRecovered("a1")).thenReturn(0);
-        assertThrows(IllegalStateException.class, () -> writer.markRecovered("D1","PRESSURE"));
-        verify(logs,never()).insertLifecycleIfAbsent(anyString(),anyInt(),anyString(),anyString(),any(),anyLong());
-        verify(manager).rollback(any());
-    }
-    @Test void oldHandledLogDoesNotSuppressANewTransition() {
-        when(logs.latestLogId("a1")).thenReturn(42L);
-        assertEquals(1,writer.markRecovered("D1","PRESSURE"));
-        verify(logs).insertLifecycleIfAbsent(eq("a1"),eq(3),eq("监测恢复,报警自动解除"),eq("系统自动"),any(),eq(42L));
-    }
-    private AlarmData alarm() {
-        AlarmData alarm=new AlarmData(); alarm.setDeviceCode("D1"); alarm.setWarningCode("PRESSURE");
-        return alarm;
-    }
-}

+ 0 - 75
zk-api-service/src/test/java/com/zksy/api/service/CollectionAlarmNumberTest.java

@@ -1,75 +0,0 @@
-package com.zksy.api.service;
-
-import com.baomidou.mybatisplus.annotation.FieldStrategy;
-import com.baomidou.mybatisplus.annotation.TableField;
-import com.zksy.api.domain.AlarmData;
-import com.zksy.api.mapper.AlarmDataMapper;
-import com.zksy.api.mapper.AlarmLogMapper;
-import org.junit.jupiter.api.*;
-import org.mockito.InOrder;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.support.SimpleTransactionStatus;
-import java.time.LocalDate;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
-import static org.junit.jupiter.api.Assertions.*;
-import static org.mockito.Mockito.*;
-
-class CollectionAlarmNumberTest {
-    private final AlarmDataMapper mapper = mock(AlarmDataMapper.class);
-    private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
-    private final AlarmLogMapper logs = mock(AlarmLogMapper.class);
-    private final CollectionAlarmWriter writer = new CollectionAlarmWriter(mapper,logs,manager);
-    @BeforeEach void setup() {
-        when(manager.getTransaction(any())).thenReturn(new SimpleTransactionStatus());
-        when(mapper.lockAlarmKey("D1","WARN-PRESSURE")).thenReturn(1);
-        when(mapper.lockAlarmNumberGeneration()).thenReturn(1);
-        when(logs.insertLifecycleIfAbsent(anyString(),anyInt(),anyString(),anyString(),any(),anyLong())).thenReturn(1);
-    }
-    private AlarmData alarm() {
-        AlarmData alarm = new AlarmData(); alarm.setDeviceCode("D1"); alarm.setWarningCode("WARN-PRESSURE");
-        alarm.setAlarmLevel(1); return alarm;
-    }
-    @Test void collectionInsertReceivesProgramNumberBeforeCommitting() {
-        AlarmData alarm = alarm(); alarm.setAlarmNo("caller-number");
-        when(mapper.insert(any(AlarmData.class))).thenAnswer(call -> {
-            AlarmData saved = call.getArgument(0);
-            String date=LocalDate.now(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.BASIC_ISO_DATE);
-            assertTrue(saved.getAlarmNo().matches("BJ"+date+"[0-9]{10}")); saved.setId("new-alarm"); return 1;
-        });
-        assertTrue(writer.saveOrUpdateUnhandled(alarm));
-        InOrder ordered = inOrder(mapper,manager);
-        ordered.verify(mapper).insert(alarm); ordered.verify(manager).commit(any());
-    }
-    @Test void existingUnhandledAlarmIsNotRenumberedOrInserted() {
-        AlarmData existing=alarm(); existing.setId("existing"); existing.setAlarmNo("BJ2026092400000001");
-        when(mapper.selectUnhandledAlarmForUpdate("D1","WARN-PRESSURE")).thenReturn(existing);
-        AlarmData incoming=alarm(); assertFalse(writer.saveOrUpdateUnhandled(incoming));
-        assertNull(incoming.getAlarmNo()); assertEquals("BJ2026092400000001",existing.getAlarmNo());
-        verify(mapper,never()).insert(any(AlarmData.class));
-    }
-    @Test void failedInsertRollsBackRatherThanReportingSuccess() {
-        when(mapper.insert(any(AlarmData.class))).thenReturn(0);
-        assertThrows(IllegalStateException.class,()->writer.saveOrUpdateUnhandled(alarm()));
-        verify(manager).rollback(any()); verify(manager,never()).commit(any());
-    }
-    @Test void numberIsWrittenOnInsertAndIgnoredOnUpdate() throws Exception {
-        TableField field=AlarmData.class.getDeclaredField("alarmNo").getAnnotation(TableField.class);
-        assertEquals(FieldStrategy.NOT_NULL,field.insertStrategy()); assertEquals(FieldStrategy.NEVER,field.updateStrategy());
-    }
-    @Test void collisionRetriesBeforeInserting() {
-        when(mapper.existsAlarmNo(anyString())).thenReturn(true, false);
-        when(mapper.insert(any(AlarmData.class))).thenAnswer(call -> {
-            ((AlarmData) call.getArgument(0)).setId("collision-retried"); return 1;
-        });
-        assertTrue(writer.saveOrUpdateUnhandled(alarm()));
-        verify(mapper,times(2)).existsAlarmNo(anyString());
-        verify(mapper,times(1)).insert(any(AlarmData.class));
-    }
-    @Test void repeatedNumberCollisionsFailWithoutInserting() {
-        when(mapper.existsAlarmNo(anyString())).thenReturn(true);
-        assertThrows(IllegalStateException.class,()->writer.saveOrUpdateUnhandled(alarm()));
-        verify(mapper,never()).insert(any(AlarmData.class));
-        verify(manager).rollback(any());
-    }
-}

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است