41 Commits
2026-05 ... dev

Author SHA1 Message Date
caozehui
0cd8e454fc 完善暂存功能 2026-07-15 16:23:15 +08:00
caozehui
95005d2462 暂存功能 2026-07-15 11:01:49 +08:00
caozehui
16ace94f8d 开始检测接口参数调整 2026-07-13 16:25:31 +08:00
caozehui
ca9885c5dc 被检设备上传图片功能 2026-07-09 16:35:32 +08:00
caozehui
78b52fa336 归档 2026-07-09 09:16:09 +08:00
caozehui
da08271f76 暂态写入写出时间 2026-07-08 15:50:38 +08:00
caozehui
75bc44172b 相角180度时特殊处理 2026-07-08 10:50:00 +08:00
caozehui
95544f1dc6 补充三相功率因数 2026-07-08 08:34:11 +08:00
7a8071c9d7 feat(report): 优化报告生成工具中的文档处理功能
- 在Docx4jUtil中添加enableUpdateFieldsOnOpen方法,确保Word打开时自动刷新页码等域
- 移除ItemAnchorAssembler中不必要的导入包,精简代码结构
- 重构谐波数据处理逻辑,添加谐波衍生值计算功能
- 实现固定占位符替换机制,支持谐波电压和功率表的动态填充
- 优化表格结构分离逻辑,使用空段落而非可见标题分隔多表
- 增强错误范围处理,移除单位后缀并优化谐波电流计算逻辑
- 添加全面的单元测试验证各种谐波检测场景的功能正确性
2026-07-07 22:49:46 +08:00
75b19eb6ab feat(report): 新增指标锚点模板支持及数据库连接配置更新
- 更新数据库连接URL从pqs910到pqs91001
- 在BaseReportKeyEnum中新增ARRIVED_DATE_C、TEST_DATE_C和YEAR_MONTH_DAY_UP枚举值
- 在ItemReportKeyEnum中新增标准电压电流功率等指标锚点相关枚举值
- 新增ItemAnchorAssembler工具类实现指标锚点模板的表格装配功能
- 实现云南检定报告的指标锚点新型模板处理流程
- 添加中文数字日期格式化功能支持
- 实现有功功率特例的数据映射处理
- 支持不平衡度类表格数据的生成处理
2026-07-07 10:10:49 +08:00
caozehui
efb379d6a4 补充三相功率因数 2026-07-06 20:05:29 +08:00
caozehui
cf2dcf8ff4 补充三相总有功功率、三相总无功功率、三相总视在功率 2026-07-06 16:28:24 +08:00
caozehui
4d52e9c820 补充功率因数 2026-07-06 08:43:07 +08:00
caozehui
be318b2b54 三项不平衡补充序分量 2026-07-02 15:00:09 +08:00
e3478e71d5 feat(detection): 更新影响量枚举和测试结果排序逻辑
- 在 AffectEnum 中添加 sort 字段用于报告小节排序,分为额定=1、单影响量=2、多影响量=3
- 添加多个新的多影响量组合类型枚举值,如电压和谐波间谐波影响等
- 移除硬编码的影响量文案映射,改为从 AffectEnum 统一获取描述信息
- 使用大小写不敏感的比较方式处理脚本子类型匹配
- 实现按影响量类型排序的逻辑,在最终内容生成时保持固定顺序
- 更新过滤条件使用忽略大小写的字符串比较方法
- 在 .gitignore 中添加对 Windows 保留设备名 nul 文件的忽略规则
2026-06-30 15:55:37 +08:00
88d3e00559 feat(report): 更新数据库配置并完善检测报告功能
- 修改application.yml中的数据库连接URL从pqs910切换到pqs9100_jx
- 在BaseReportKeyEnum中新增装置名称和检测源名称枚举项
- 在PqReportServiceImpl中注入IAdPlanSourceService并实现检测源名称获取
- 添加装置名称到报告基础数据映射中
- 优化测量回路标题格式,统一显示回路编号
- 在ResultServiceImpl中增强表格数据生成逻辑,添加空数据检查和日志记录
- 修改数据填充方法返回布尔值以支持数据有效性验证
- 重构电压相位数据填充逻辑,提高数据处理准确性
- 增强异常处理机制,确保报告生成过程更加稳定可靠
2026-06-29 19:12:23 +08:00
caozehui
1de66ce4dc 检测开始、结束时间补充 2026-06-29 16:32:45 +08:00
caozehui
597f70edd1 闪变调整 2026-06-26 13:56:46 +08:00
caozehui
6f8acd3fb5 数据校验接口返回值优化 2026-06-26 09:11:09 +08:00
caozehui
3c0d7a6268 微调 2026-06-25 10:51:49 +08:00
caozehui
7fd1563f3a 微调 2026-06-25 09:35:08 +08:00
caozehui
4fd813f476 程控源-关源指令调整 2026-06-24 14:39:04 +08:00
caozehui
9dfb42f917 谐波、间谐波对电压的影响
调用数据校验接口调整
2026-06-24 09:15:20 +08:00
caozehui
9990183c5d 修复2次关源指令bug
完善数据校验结果接口调用
pqdif功补充
2026-06-23 10:04:16 +08:00
caozehui
d746e68d63 调用第三方数据校验接口 2026-06-22 09:47:06 +08:00
caozehui
1ff2d373f5 Revert "docs: add formal test third-party checksquare design"
This reverts commit f298a7bb56.
2026-06-18 14:54:41 +08:00
caozehui
f298a7bb56 docs: add formal test third-party checksquare design 2026-06-18 14:53:44 +08:00
caozehui
aafa38000d 程控源调整 2026-06-18 10:01:05 +08:00
caozehui
287ca2cddc icd调整 2026-06-17 19:32:27 +08:00
caozehui
82fdd7664b icd调整 2026-06-16 19:25:43 +08:00
caozehui
547d40ce99 微调 2026-06-16 13:21:04 +08:00
caozehui
49599582ba 多影响量 2026-06-16 10:56:59 +08:00
caozehui
31a956a1fc 记录设备检测开始&结束时间 2026-06-15 10:45:40 +08:00
caozehui
55fe1fe05f 微调 2026-06-15 09:10:37 +08:00
366d1fadfa test(detection): 添加检测锁管理器的单元测试
- 为 DetectionLockManager 添加完整的单元测试覆盖
- 测试空状态下的获取操作返回成功结果
- 测试被其他用户持有时的获取操作返回忙状态
- 测试同用户重入时刷新页面和过期时间功能
- 测试过期后任意用户可获取锁的功能
- 测试匹配用户时释放锁的操作
- 测试非匹配用户时释放锁的无操作行为
- 测试匹配页面时释放锁的功能
- 测试强制释放锁的操作
- 添加并发获取锁的竞态条件测试确保线程安全
2026-06-12 19:09:00 +08:00
caozehui
b35bbf11f7 报告模版新增pattern字段 2026-06-12 13:29:35 +08:00
e2c7e745c8 feat(report): 优化文档模板中数据行插入的分页处理
- 在数据行锚点后有内容时自动添加分页符,确保剩余内容另起新页
- 新增 hasContentAfterBookmark 方法判断锚点后是否存在有意义内容
- 避免锚点在文档末尾时产生多余空白页,保持存量模板兼容性
- 实现智能分页逻辑,仅对非空文本段落和表格等有效内容进行分页处理
2026-06-11 18:12:46 +08:00
caozehui
29ddc8c2de webSocket清除 2026-06-09 14:48:12 +08:00
caozehui
212f1295eb 微调 2026-06-08 08:53:56 +08:00
caozehui
7366e7815f 微调 2026-06-08 08:47:12 +08:00
caozehui
a4858a818e sntp 2026-06-04 17:35:16 +08:00
134 changed files with 8844 additions and 1794 deletions

6
.gitignore vendored
View File

@@ -52,4 +52,8 @@ rebel.xml
# 个人工作文档,不与团队共享
CLAUDE.md
docs/
data/
data/
.m2
# Windows 保留设备名误生成的真实文件(在 Git Bash 里把 2>nul 当成丢弃报错的写法,会真的建出名为 nul 的文件)
nul

View File

@@ -145,7 +145,12 @@
<artifactId>activate-tool</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
</project>

View File

@@ -0,0 +1,54 @@
package com.njcn.gather.detection.controller;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.detection.lock.DetectionLock;
import com.njcn.gather.detection.lock.DetectionLockManager;
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import com.njcn.web.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 检测互斥锁管理接口。
* - GET /detection/lock/current 查询当前持锁状态;空闲返回 data=null
* - POST /detection/lock/forceRelease 管理员强制释放
*
* 鉴权:默认由 AuthGlobalFilter 做 JWT 校验,登录用户均可访问;
* 强释操作通过 @OperateInfo 落审计日志,谁操作谁担责。
*/
@Slf4j
@Api(tags = "检测互斥锁")
@RestController
@RequestMapping("/detection/lock")
@RequiredArgsConstructor
public class LockController extends BaseController {
@GetMapping("/current")
@ApiOperation("查询当前持锁状态;空闲返回 data=null")
public HttpResult<DetectionLockHolderVO> current() {
String methodDescribe = getMethodDescribe("current");
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
DetectionLockHolderVO data = cur == null ? null : DetectionLockManager.toHolderVO(cur);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, data, methodDescribe);
}
@PostMapping("/forceRelease")
@OperateInfo
@ApiOperation("管理员强制释放检测锁")
public HttpResult<?> forceRelease() {
String methodDescribe = getMethodDescribe("forceRelease");
String operator = RequestUtil.getUserId();
DetectionLockManager.getInstance().forceRelease(operator, "ADMIN_FORCE");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -12,9 +12,11 @@ import com.njcn.gather.detection.lock.DetectionLockManager;
import com.njcn.gather.detection.lock.DetectionLockManager.AcquireResult;
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
import com.njcn.gather.detection.pojo.param.FormalProgressParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
import com.njcn.gather.detection.pojo.vo.FormalProgressVO;
import com.njcn.gather.detection.service.PreDetectionService;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.user.user.pojo.po.SysUser;
@@ -105,13 +107,25 @@ public class PreDetectionController extends BaseController {
@ApiOperation("启动")
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
public HttpResult<?> startTestSimulate(@RequestBody @Validated SimulateDetectionParam param) {
String methodDescribe = getMethodDescribe("startTestSimulate");
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
String methodDescribe = getMethodDescribe("startSimulateTest");
// ContrastDetectionParam 无 userPageId 字段,用 loginName 作为会话标识(与 WS 会话 key 一致)
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getUserPageId());
if (busy != null) {
return busy;
}
preDetectionService.sendScript(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
// 同步阶段抛异常时回滚锁,理由同 startPreTest
boolean keepLock = false;
try {
FormalTestManager.stopTime = 0;
FormalTestManager.hasStopFlag = false;
preDetectionService.sendScript(param);
keepLock = true;
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
} finally {
if (!keepLock) {
releaseLockSelf("START_SIMULATE_TEST_SYNC_FAILED");
}
}
}
/**
@@ -190,6 +204,36 @@ public class PreDetectionController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@PostMapping("/saveFormalProgress")
@OperateInfo
@ApiOperation("保存正式检测暂存进度")
public HttpResult<?> saveFormalProgress(@RequestBody @Validated FormalProgressParam param) {
String methodDescribe = getMethodDescribe("saveFormalProgress");
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
if (busy != null) {
return busy;
}
try {
preDetectionService.saveFormalProgress(param);
} finally {
releaseLockSelf("SAVE_FORMAL_PROGRESS");
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@PostMapping("/formalProgress")
@OperateInfo
@ApiOperation("查询正式检测暂存进度并放行续检")
public HttpResult<?> formalProgress(@RequestBody @Validated FormalProgressParam param) {
String methodDescribe = getMethodDescribe("formalProgress");
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
if (busy != null) {
return busy;
}
FormalProgressVO data = preDetectionService.formalProgress(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, data, methodDescribe);
}
/**
* 开始比对检测(包括预检测、正式检测)通用入口

View File

@@ -0,0 +1,44 @@
package com.njcn.gather.detection.controller;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.detection.sntp.SntpServerManager;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@Api(tags = "SNTP对时")
@RestController
@RequestMapping("/sntp")
@RequiredArgsConstructor
public class SntpController extends BaseController {
private final SntpServerManager sntpServerManager;
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/start")
@ApiOperation("启动SNTP对时服务")
public HttpResult<?> start() {
String methodDescribe = getMethodDescribe("start");
sntpServerManager.start();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/stop")
@ApiOperation("停止SNTP对时服务")
public HttpResult<?> stop() {
String methodDescribe = getMethodDescribe("stop");
sntpServerManager.stop();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -41,6 +41,7 @@ import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.storage.pojo.po.ContrastHarmonicResult;
import com.njcn.gather.storage.pojo.po.ContrastNonHarmonicResult;
import com.njcn.gather.storage.service.DetectionDataDealService;
@@ -132,17 +133,17 @@ public class SocketContrastResponseService {
private final PathConfig pathConfig;
public static final Map<String, List<String>> testItemCodeMap = new HashMap() {{
put("FREQ", Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
put("V", Arrays.asList(DetectionCodeEnum.VRMS.getCode(), DetectionCodeEnum.PVRMS.getCode()));
put("HV", Arrays.asList(DetectionCodeEnum.V2_50.getCode(), DetectionCodeEnum.PV2_50.getCode()));
put("HI", Arrays.asList(DetectionCodeEnum.I2_50.getCode()));
put("HP", Arrays.asList(DetectionCodeEnum.P2_50.getCode()));
put("HSV", Arrays.asList(DetectionCodeEnum.SV_1_49.getCode(), DetectionCodeEnum.PSV_1_49.getCode()));
put("HSI", Arrays.asList(DetectionCodeEnum.SI_1_49.getCode()));
put("I", Arrays.asList(DetectionCodeEnum.IRMS.getCode()));
put("IMBV", Arrays.asList(DetectionCodeEnum.V_UNBAN.getCode()));
put("IMBA", Arrays.asList(DetectionCodeEnum.I_UNBAN.getCode()));
put("F", Arrays.asList(DetectionCodeEnum.PST.getCode()));
put(PowerIndexEnum.FREQ.getKey(), Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
put(PowerIndexEnum.V.getKey(), Arrays.asList(DetectionCodeEnum.VRMS.getCode(), DetectionCodeEnum.PVRMS.getCode()));
put(PowerIndexEnum.HV.getKey(), Arrays.asList(DetectionCodeEnum.V2_50.getCode(), DetectionCodeEnum.PV2_50.getCode()));
put(PowerIndexEnum.HI.getKey(), Arrays.asList(DetectionCodeEnum.I2_50.getCode()));
put(PowerIndexEnum.HP.getKey(), Arrays.asList(DetectionCodeEnum.P2_50.getCode()));
put(PowerIndexEnum.HSV.getKey(), Arrays.asList(DetectionCodeEnum.SV_1_49.getCode(), DetectionCodeEnum.PSV_1_49.getCode()));
put(PowerIndexEnum.HSI.getKey(), Arrays.asList(DetectionCodeEnum.SI_1_49.getCode()));
put(PowerIndexEnum.I.getKey(), Arrays.asList(DetectionCodeEnum.IRMS.getCode()));
put(PowerIndexEnum.IMBV.getKey(), Arrays.asList(DetectionCodeEnum.V_UNBAN.getCode()));
put(PowerIndexEnum.IMBA.getKey(), Arrays.asList(DetectionCodeEnum.I_UNBAN.getCode()));
put(PowerIndexEnum.F.getKey(), Arrays.asList(DetectionCodeEnum.PST.getCode()));
}};
/**
@@ -307,7 +308,7 @@ public class SocketContrastResponseService {
FormalTestManager.numMap.clear();
FormalTestManager.numMap.putAll(numMap);
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
if (param.getTestItemList().get(2)) {
if (param.isFormalTestSelected()) {
numMap.forEach((devMonitorId, num) -> {
if (oneConfig.getMaxTime() < num) {
throw new BusinessException(DetectionResponseEnum.EXCEED_MAX_TIME);
@@ -356,6 +357,7 @@ public class SocketContrastResponseService {
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_SBTXJY;
FormalTestManager.checkStartTime = LocalDateTime.now();
}
public void deal(PreDetectionParam param, String msg) throws Exception {
@@ -554,7 +556,6 @@ public class SocketContrastResponseService {
this.sendAlignData(s, requestOperateCode);
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_ALIGN;
// if (FormalTestManager.isWaveCheck) {
// System.out.println("(仅有闪变、录波)模型一致性校验成功!》》》》》》》》》》》》》》》》》》》》》》》》》》》》》开始相序校验》》》》》》》》》》》》》》》》");
// this.sendXu(s);
@@ -1154,7 +1155,7 @@ public class SocketContrastResponseService {
private void sendFormalTest(String s, PreDetectionParam param, SourceOperateCodeEnum requestOperateCode, SourceOperateCodeEnum quitOperateCode) {
// 后续做正式检测
if (param.getTestItemList().get(2)) {
if (param.isFormalTestSelected()) {
System.out.println("开始正式检测!");
if (ObjectUtil.isNotNull(FormalTestManager.nonWaveDataSourceEnum)) {
SocketMsg<String> socketMsg = new SocketMsg<>();

View File

@@ -28,7 +28,8 @@ import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.device.service.IPqDevSubService;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.result.service.IResultService;
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.po.SourceIssue;
@@ -44,8 +45,8 @@ import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
import com.njcn.gather.system.dictionary.pojo.po.DictData;
import com.njcn.gather.system.dictionary.service.IDictDataService;
import com.njcn.gather.system.pojo.enums.DicDataEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
@@ -67,7 +68,7 @@ public class SocketDevResponseService {
private List<String> icdTypeList;
private final List<String> nonHarmonicList = Stream.of(DicDataEnum.FREQ.getCode(), DicDataEnum.V.getCode(), DicDataEnum.I.getCode(), DicDataEnum.IMBV.getCode(), DicDataEnum.IMBA.getCode(), DicDataEnum.VOLTAGE.getCode(), DicDataEnum.F.getCode()).collect(Collectors.toList());
private final List<String> nonHarmonicList = Stream.of(PowerIndexEnum.FREQ.getKey(), PowerIndexEnum.V.getKey(), PowerIndexEnum.I.getKey(), PowerIndexEnum.IMBV.getKey(), PowerIndexEnum.IMBA.getKey(), PowerIndexEnum.VOLTAGE.getKey(), PowerIndexEnum.F.getKey()).collect(Collectors.toList());
private final IPqDevService iPqDevService;
private final IPqDevSubService iPqDevSubService;
@@ -80,6 +81,10 @@ public class SocketDevResponseService {
private final IAdPlanService adPlanService;
private final IDictDataService dictDataService;
private final IPqSourceService pqSourceService;
private final IResultService resultService;
@Value("${dataCheck.enable}")
private Boolean dataCheck;
/**
* 存储的装置相序数据
@@ -392,72 +397,8 @@ public class SocketDevResponseService {
sendWebSocket(param.getUserPageId(), SourceOperateCodeEnum.Coefficient_Check.getValue(), SourceOperateCodeEnum.small_comp_end.getValue(), XiNumberManager.devParameterList.get(1));
System.out.println("-------------------------已经全部结束----------------------");
if (param.getTestItemList().get(2)) {
//如果后续做正式检测
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
//不合格项复检
Set<Integer> indexes = new HashSet<>();
StorageParam storageParam = new StorageParam();
storageParam.setCode(param.getCode());
storageParam.setScriptId(param.getScriptId());
param.getDevIds().forEach(devId -> {
storageParam.setDevId(devId);
indexes.addAll(adHarmonicService.getIndex(storageParam));
});
issueParam.setIndexList(indexes.stream().collect(Collectors.toList()));
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
} else {
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
}
SocketMsg<String> socketMsg = new SocketMsg<>();
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
List<SourceIssue> sourceIssues;
//正式检测
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
sourceIssues = sourceIssues.stream().sorted(Comparator.comparing(SourceIssue::getIndex)).collect(Collectors.toList());
// 使用 LinkedHashMap 保持分组顺序
Map<String, List<SourceIssue>> groupedIssues = sourceIssues.stream()
.collect(Collectors.groupingBy(
SourceIssue::getType,
LinkedHashMap::new,
Collectors.toList()
));
// 将分组后的元素合并成一个新的集合,保持原有顺序
sourceIssues = groupedIssues.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
// 存放所有检测小项
SocketManager.addSourceList(sourceIssues);
// 按照大项分组。key为大项codevalue为小项个数
Map<String, Long> sourceIssueMap = sourceIssues.stream().collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
SocketManager.initMap(sourceIssueMap);
//告诉前端当前项开始了
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
FormalTestManager.currentIssue = sourceIssues.get(0);
String type = sourceIssues.get(0).getType();
if (ResultUnitEnum.P.getCode().equals(type)) {
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
webSocketVO.setRequestId(ResultUnitEnum.P.getCode() + CnSocketUtil.START_TAG);
} else {
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
}
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
if (param.isFormalTestSelected()) {
startFormalScripts(param, null, param.isResumeFormal());
} else {
//后续什么都不做
CnSocketUtil.quitSend(param);
@@ -609,7 +550,7 @@ public class SocketDevResponseService {
private BigDecimal rangeNum(double num1, double num2, String type) {
double diff = Math.abs(num1 - num2);
double larger = Math.max(num1, num2);
if (DicDataEnum.V.getCode().equals(type)) {
if (PowerIndexEnum.V.getKey().equals(type)) {
return BigDecimal.valueOf(num1 - num2).setScale(4, RoundingMode.HALF_UP);
} else {
return BigDecimal.valueOf(diff / larger).multiply(BigDecimal.valueOf(100)).setScale(4, RoundingMode.HALF_UP);
@@ -672,12 +613,12 @@ public class SocketDevResponseService {
coefficientVO.setBIeXi(isWithinTenPercent(optionalIB, devParameter.getDevCurr(), iLimit) ? "合格" : "不合格");
coefficientVO.setCIeXi(isWithinTenPercent(optionalIC, devParameter.getDevCurr(), iLimit) ? "合格" : "不合格");
coefficientVO.setAV(rangeNum(optionalA, devParameter.getDevVolt(), DicDataEnum.V.getCode()).toString());
coefficientVO.setBV(rangeNum(optionalB, devParameter.getDevVolt(), DicDataEnum.V.getCode()).toString());
coefficientVO.setCV(rangeNum(optionalC, devParameter.getDevVolt(), DicDataEnum.V.getCode()).toString());
coefficientVO.setAI(rangeNum(optionalIA, devParameter.getDevCurr(), DicDataEnum.I.getCode()).toString());
coefficientVO.setBI(rangeNum(optionalIB, devParameter.getDevCurr(), DicDataEnum.I.getCode()).toString());
coefficientVO.setCI(rangeNum(optionalIC, devParameter.getDevCurr(), DicDataEnum.I.getCode()).toString());
coefficientVO.setAV(rangeNum(optionalA, devParameter.getDevVolt(), PowerIndexEnum.V.getKey()).toString());
coefficientVO.setBV(rangeNum(optionalB, devParameter.getDevVolt(), PowerIndexEnum.V.getKey()).toString());
coefficientVO.setCV(rangeNum(optionalC, devParameter.getDevVolt(), PowerIndexEnum.V.getKey()).toString());
coefficientVO.setAI(rangeNum(optionalIA, devParameter.getDevCurr(), PowerIndexEnum.I.getKey()).toString());
coefficientVO.setBI(rangeNum(optionalIB, devParameter.getDevCurr(), PowerIndexEnum.I.getKey()).toString());
coefficientVO.setCI(rangeNum(optionalIC, devParameter.getDevCurr(), PowerIndexEnum.I.getKey()).toString());
if ("不合格".equals(coefficientVO.getAVuXi()) || "不合格".equals(coefficientVO.getBVuXi()) || "不合格".equals(coefficientVO.getCVuXi()) || "不合格".equals(coefficientVO.getAIeXi()) || "不合格".equals(coefficientVO.getBIeXi()) || "不合格".equals(coefficientVO.getCIeXi())) {
coefficientVO.setResultFlag(0);
@@ -906,68 +847,70 @@ public class SocketDevResponseService {
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
List<SourceIssue> sourceIssues;
// 做预检测、后续做系数校准
if (param.getTestItemList().get(0) || param.getTestItemList().get(1)) {
issueParam.setIsPhaseSequence(CommonEnum.PHASE_TEST.getValue());
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
} else if (param.getTestItemList().get(2)) {
// 后续做正式检测
if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
//不合格项复检
Set<Integer> indexes = new HashSet<>();
StorageParam storageParam = new StorageParam();
storageParam.setCode(param.getCode());
storageParam.setScriptId(param.getScriptId());
param.getDevIds().forEach(devId -> {
storageParam.setDevId(devId);
indexes.addAll(adHarmonicService.getIndex(storageParam));
});
issueParam.setIndexList(indexes.stream().collect(Collectors.toList()));
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
} else {
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
}
//正式检测
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
sourceIssues = sourceIssues.stream().sorted(Comparator.comparing(SourceIssue::getIndex)).collect(Collectors.toList());
// 使用 LinkedHashMap 保持分组顺序
Map<String, List<SourceIssue>> groupedIssues = sourceIssues.stream()
.collect(Collectors.groupingBy(
SourceIssue::getType,
LinkedHashMap::new,
Collectors.toList()
));
// 将分组后的元素合并成一个新的集合,保持原有顺序
sourceIssues = groupedIssues.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
// 存放所有检测小项
SocketManager.addSourceList(sourceIssues);
// 按照大项分组。key为大项codevalue为小项个数
Map<String, Long> sourceIssueMap = sourceIssues.stream().collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
SocketManager.initMap(sourceIssueMap);
//告诉前端当前项开始了
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
String type = sourceIssues.get(0).getType();
if (ResultUnitEnum.P.getCode().equals(type)) {
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
webSocketVO.setRequestId(ResultUnitEnum.P.getCode() + CnSocketUtil.START_TAG);
} else {
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
}
FormalTestManager.currentIssue = sourceIssues.get(0);
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
}
// if (param.isPreTestSelected() || param.isCoefficientSelected() || param.isFormalTestSelected()) {
issueParam.setIsPhaseSequence(CommonEnum.PHASE_TEST.getValue());
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
// }
// else if (param.isFormalTestSelected()) {
// // 后续做正式检测
// if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
// //不合格项复检
// Set<Integer> indexes = new HashSet<>();
// StorageParam storageParam = new StorageParam();
// storageParam.setCode(param.getCode());
// storageParam.setScriptId(param.getScriptId());
// param.getDevIds().forEach(devId -> {
// storageParam.setDevId(devId);
// indexes.addAll(adHarmonicService.getIndex(storageParam));
// });
// issueParam.setIndexList(indexes.stream().collect(Collectors.toList()));
// issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
// } else {
// issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
// }
// //正式检测
// sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
// sourceIssues = sourceIssues.stream().sorted(Comparator.comparing(SourceIssue::getIndex)).collect(Collectors.toList());
// // 使用 LinkedHashMap 保持分组顺序
// Map<String, List<SourceIssue>> groupedIssues = sourceIssues.stream()
// .collect(Collectors.groupingBy(
// SourceIssue::getType,
// LinkedHashMap::new,
// Collectors.toList()
// ));
//
// // 将分组后的元素合并成一个新的集合,保持原有顺序
// sourceIssues = groupedIssues.values().stream()
// .flatMap(List::stream)
// .collect(Collectors.toList());
// // 存放所有检测小项
// SocketManager.addSourceList(sourceIssues);
// // 按照大项分组。key为大项codevalue为小项个数
// Map<String, Long> sourceIssueMap = sourceIssues.stream().collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
// SocketManager.initMap(sourceIssueMap);
//
// //告诉前端当前项开始了
// WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
// String type = sourceIssues.get(0).getType();
// if (StrUtil.isNotBlank(sourceIssues.get(0).getOtherType())) {
// sourceIssues.get(0).setType(PowerIndexEnum.V.getKey());
// webSocketVO.setRequestId(sourceIssues.get(0).getOtherType() + CnSocketUtil.START_TAG);
// type = sourceIssues.get(0).getOtherType();
// } else {
// webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
// }
// FormalTestManager.currentIssue = sourceIssues.get(0);
// socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
// socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
// socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
// SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
//
// webSocketVO.setDesc(null);
// WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
// }
} else {
// 发送下一个脚本与icd校验
String icdType = icdTypeList.stream().filter(it -> !icdCheckDataMap.containsKey(it)).findFirst().orElse(null);
@@ -1140,7 +1083,7 @@ public class SocketDevResponseService {
}
// 后续做系数校准
if (param.getTestItemList().get(1)) {
if (param.isCoefficientSelected()) {
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.big_start.getValue());
@@ -1164,67 +1107,8 @@ public class SocketDevResponseService {
XiNumberManager.smallDevXiNumDataMap.clear();
System.out.println("开始系数校准》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
} else if (param.getTestItemList().get(2)) {
// 后续做正式检测
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
//不合格项复检
Set<Integer> indexes = new HashSet<>();
StorageParam storageParam = new StorageParam();
storageParam.setCode(param.getCode());
storageParam.setScriptId(param.getScriptId());
param.getDevIds().forEach(devId -> {
storageParam.setDevId(devId);
indexes.addAll(adHarmonicService.getIndex(storageParam));
});
issueParam.setIndexList(indexes.stream().collect(Collectors.toList()));
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
} else {
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
}
//正式检测
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
sourceIssues = sourceIssues.stream().sorted(Comparator.comparing(SourceIssue::getIndex)).collect(Collectors.toList());
// 使用 LinkedHashMap 保持分组顺序
Map<String, List<SourceIssue>> groupedIssues = sourceIssues.stream()
.collect(Collectors.groupingBy(
SourceIssue::getType,
LinkedHashMap::new,
Collectors.toList()
));
// 将分组后的元素合并成一个新的集合,保持原有顺序
sourceIssues = groupedIssues.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
// 存放所有检测小项
SocketManager.addSourceList(sourceIssues);
// 按照大项分组。key为大项codevalue为小项个数
Map<String, Long> sourceIssueMap = sourceIssues.stream().collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
SocketManager.initMap(sourceIssueMap);
//告诉前端当前项开始了
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
String type = sourceIssues.get(0).getType();
if (ResultUnitEnum.P.getCode().equals(type)) {
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
webSocketVO.setRequestId(ResultUnitEnum.P.getCode() + CnSocketUtil.START_TAG);
} else {
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
}
FormalTestManager.currentIssue = sourceIssues.get(0);
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
} else if (param.isFormalTestSelected()) {
startFormalScripts(param, null, param.isResumeFormal());
} else {
//后续什么都不做
System.out.println("预检测流程结束-----------------关闭源");
@@ -1269,6 +1153,97 @@ public class SocketDevResponseService {
// key为 检测大项对应的codevalue为当前大项的检测结果
Map<String, List<DevLineTestResult>> targetTestMap = new HashMap<>();
public void startFormalAfterProgressRestore(PreDetectionParam param, Integer nextSort) {
FormalTestManager.resumeFormalPending = false;
FormalTestManager.resumeNextSort = nextSort;
if (nextSort == null) {
WebServiceManager.sendDetectionMessage(param.getUserPageId(), "formal_progress_no_next", null, null, null);
return;
}
startFormalScripts(param, nextSort, false);
}
private void startFormalScripts(PreDetectionParam param, Integer startSort, boolean waitForProgressRestore) {
List<SourceIssue> sourceIssues = buildFormalIssues(param);
if (ObjectUtil.isNotNull(startSort)) {
sourceIssues = sourceIssues.stream()
.filter(issue -> issue.getIndex() >= startSort)
.collect(Collectors.toList());
}
sourceIssues = sourceIssues.stream()
.sorted(Comparator.comparing(SourceIssue::getIndex))
.collect(Collectors.toList());
Map<String, List<SourceIssue>> groupedIssues = sourceIssues.stream()
.collect(Collectors.groupingBy(SourceIssue::getType, LinkedHashMap::new, Collectors.toList()));
sourceIssues = groupedIssues.values().stream().flatMap(List::stream).collect(Collectors.toList());
if (!param.isResumeFormal() && CollUtil.isNotEmpty(sourceIssues)) {
iPqDevService.clearFormalProgressForNewRun(param.getDevIds());
}
SocketManager.addSourceList(sourceIssues);
Map<String, Long> sourceIssueMap = sourceIssues.stream()
.collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
SocketManager.initMap(sourceIssueMap);
if (waitForProgressRestore) {
FormalTestManager.resumeFormalPending = true;
WebServiceManager.sendDetectionMessage(param.getUserPageId(), "formal_progress_required", null, null, null);
return;
}
sendFirstFormalIssue(param, sourceIssues);
}
private List<SourceIssue> buildFormalIssues(PreDetectionParam param) {
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
if (!param.isResumeFormal() && SourceOperateCodeEnum.RE_ERROR_TEST.getValue().equals(param.getReCheckType())) {
Set<Integer> indexes = new HashSet<>();
StorageParam storageParam = new StorageParam();
storageParam.setCode(param.getCode());
storageParam.setScriptId(param.getScriptId());
param.getDevIds().forEach(devId -> {
storageParam.setDevId(devId);
indexes.addAll(adHarmonicService.getIndex(storageParam));
});
issueParam.setIndexList(indexes.stream().collect(Collectors.toList()));
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
} else {
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
}
return pqScriptDtlsService.listSourceIssue(issueParam);
}
private void sendFirstFormalIssue(PreDetectionParam param, List<SourceIssue> sourceIssues) {
if (CollUtil.isEmpty(sourceIssues)) {
WebServiceManager.sendDetectionMessage(param.getUserPageId(), "formal_progress_no_next", null, null, null);
return;
}
SourceIssue firstIssue = sourceIssues.get(0);
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
String type = firstIssue.getType();
if (StrUtil.isNotBlank(firstIssue.getOtherType())) {
firstIssue.setType(PowerIndexEnum.V.getKey());
webSocketVO.setRequestId(firstIssue.getOtherType() + CnSocketUtil.START_TAG);
type = firstIssue.getOtherType();
} else {
webSocketVO.setRequestId(firstIssue.getType() + CnSocketUtil.START_TAG);
}
FormalTestManager.currentIssue = firstIssue;
FormalTestManager.resumeFormalStartTime = LocalDateTime.now();
SocketMsg<String> socketMsg = new SocketMsg<>();
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
socketMsg.setData(JSON.toJSONString(firstIssue));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
}
/**
* 正式检测
*/
@@ -1310,9 +1285,9 @@ public class SocketDevResponseService {
//小项检测完后小项数减一并更新map
long residueCount = 0;
if (sourceIssue.getIsP()) {
residueCount = SocketManager.getSourceTarget(ResultUnitEnum.P.getCode()) - 1;
SocketManager.addTargetMap(ResultUnitEnum.P.getCode(), residueCount);
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
residueCount = SocketManager.getSourceTarget(sourceIssue.getOtherType()) - 1;
SocketManager.addTargetMap(sourceIssue.getOtherType(), residueCount);
} else {
residueCount = SocketManager.getSourceTarget(sourceIssue.getType()) - 1;
SocketManager.addTargetMap(sourceIssue.getType(), residueCount);
@@ -1356,14 +1331,15 @@ public class SocketDevResponseService {
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
if (CollUtil.isNotEmpty(sourceIssueList)) {
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
String type = sourceIssues.getType();
if (StrUtil.isNotBlank(sourceIssues.getOtherType())) {
sourceIssues.setType(PowerIndexEnum.V.getKey());
type = sourceIssues.getOtherType();
}
// 如果上一个大项检测完成,则检测下一个大项,并向前端推送消息
if (residueCount == 0) {
WebServiceManager.sendDetectionMessage(param.getUserPageId(), sourceIssues.getType() + CnSocketUtil.START_TAG, null, new ArrayList<>(), null);
}
String type = sourceIssues.getType();
if (sourceIssues.getIsP()) {
sourceIssues.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
type = ResultUnitEnum.P.getCode();
WebServiceManager.sendDetectionMessage(param.getUserPageId(), type + CnSocketUtil.START_TAG, null, new ArrayList<>(), null);
}
//控源下发下一个小项脚本
@@ -1380,6 +1356,9 @@ public class SocketDevResponseService {
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
if (Boolean.TRUE.equals(dataCheck)) {
resultService.tryNotifyThirdPartyAfterFormalTest(param);
}
CnSocketUtil.quitSend(param);
// 数模式检测全部小项完成 → 释放锁,避免用户必须点"停止"才能让出
DetectionLockManager.getInstance()
@@ -1562,6 +1541,7 @@ public class SocketDevResponseService {
}
/**
* @param issue
* @return key为V或Ivalue为对应的源下发信息
@@ -1800,11 +1780,13 @@ public class SocketDevResponseService {
//字典树
SocketManager.valueTypeMap = iPqScriptCheckDataService.getValueTypeMap(param.getScriptId());
if (param.getTestItemList().get(1)) {
if (param.isCoefficientSelected()) {
initXiManager(param);
}
FormalTestManager.overload = getOverloadResult(param);
FormalTestManager.checkStartTime = LocalDateTime.now();
FormalTestManager.reCheckType = param.getReCheckType();
}
@@ -1862,29 +1844,17 @@ public class SocketDevResponseService {
// 谐波判断
if (channelListDTO.getHarmFlag()) {
List<SourceIssue.ChannelListDTO.HarmModel> harmList = channelListDTO.getHarmList();
double sum = harmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
if (channelType.contains("U")) {
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + sum) * fAmp)) < 0) {
return 1;
}
} else {
if (maxCurrent.compareTo(BigDecimal.valueOf(Math.sqrt(1 + sum) * fAmp)) < 0) {
return 2;
}
double thd = harmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + thd) * fAmp)) < 0) {
return channelType.contains("U") ? 1 : 2;
}
}
// 间谐波判断
if (channelListDTO.getInHarmFlag()) {
List<SourceIssue.ChannelListDTO.InharmModel> inharmList = channelListDTO.getInharmList();
double sum = inharmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
if (channelType.contains("U")) {
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + sum) * fAmp)) < 0) {
return 1;
}
} else {
if (maxCurrent.compareTo(BigDecimal.valueOf(Math.sqrt(1 + sum) * fAmp)) < 0) {
return 2;
}
double thd = inharmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + thd) * fAmp)) < 0) {
return channelType.contains("U") ? 1 : 2;
}
}
}
@@ -1967,9 +1937,6 @@ public class SocketDevResponseService {
if (nonHarmonicList.contains(sourceIssue.getType())) {
for (DevData.SqlDataDTO sqlDataDTO : data.getSqlData()) {
if (sqlDataDTO.getDesc().equals("PF")) {
continue;
}
DevData.SqlDataDTO.ListDTO listDTO = sqlDataDTO.getList();
SimAndDigNonHarmonicResult adNonHarmonicResult = new SimAndDigNonHarmonicResult();
adNonHarmonicResult.setTimeId(localDateTime);
@@ -2012,7 +1979,7 @@ public class SocketDevResponseService {
adHarmonicResult.setAdType(checkDataMap.get(sqlDataDTO.getDesc()));
adHarmonicResult.setDataType(sourceIssue.getDataType());
if (!DicDataEnum.HSV.getCode().equals(sourceIssue.getType()) && !DicDataEnum.HSI.getCode().equals(sourceIssue.getType()) && !DicDataEnum.HP.getCode().equals(sourceIssue.getType())) {
if (!PowerIndexEnum.HSV.getKey().equals(sourceIssue.getType()) && !PowerIndexEnum.HSI.getKey().equals(sourceIssue.getType()) && !PowerIndexEnum.HP.getKey().equals(sourceIssue.getType())) {
if (CollUtil.isNotEmpty(data.getSqlData())) {
DevData.SqlDataDTO.ListDTO vvv = data.getSqlData().stream().filter(it -> it.getDesc().equals(dui)).collect(Collectors.toList()).get(0).getList();
Double aV = vvv.getA();
@@ -2037,7 +2004,7 @@ public class SocketDevResponseService {
List<String> c = tem.getC();
Class<SimAndDigHarmonicResult> example = (Class<SimAndDigHarmonicResult>) adHarmonicResult.getClass();
if (DicDataEnum.HSV.getCode().equals(sourceIssue.getType()) || DicDataEnum.HSI.getCode().equals(sourceIssue.getType())) {
if (PowerIndexEnum.HSV.getKey().equals(sourceIssue.getType()) || PowerIndexEnum.HSI.getKey().equals(sourceIssue.getType())) {
for (int i = 1; i < a.size() + 1; i++) {
try {
Field aField = example.getDeclaredField("aValue" + i);

View File

@@ -17,11 +17,10 @@ import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.plan.pojo.po.AdPlanSource;
import com.njcn.gather.plan.service.IAdPlanSourceService;
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.source.pojo.po.SourceInitialize;
import com.njcn.gather.source.service.IPqSourceService;
import com.njcn.gather.system.pojo.enums.DicDataEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
@@ -121,6 +120,15 @@ public class SocketSourceResponseService {
sendErrorAndQuit(param, socketDataMsg, errorCode.getMessage());
}
private void sendSimulateInitFailure(PreDetectionParam param, String errorMessage) {
SocketDataMsg socketDataMsg = new SocketDataMsg();
socketDataMsg.setRequestId(SourceOperateCodeEnum.YJC_YTXJY.getValue());
socketDataMsg.setOperateCode(SourceOperateCodeEnum.INIT_GATHER.getValue());
socketDataMsg.setCode(SourceResponseCodeEnum.UNKNOWN_ERROR.getCode());
socketDataMsg.setData(errorMessage);
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
}
/**
* 当前检测会话中的设备列表
@@ -214,12 +222,12 @@ public class SocketSourceResponseService {
break;
default:
// TODO: 记录未知操作码到日志,并向前端发送友好提示
sendSimulateInitFailure(param, "未知操作码");
break;
}
} else {
// TODO: 向前端发送错误提示
log.error("程控源响应消息操作码解析失败,原始消息: {}, 解析结果: {}", msg, enumByCode);
sendSimulateInitFailure(param, "未知操作码");
}
}
@@ -272,10 +280,11 @@ public class SocketSourceResponseService {
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
break;
default:
// 未识别的响应码:发送通用错误消息
WebServiceManager.sendUnknownErrorMessage(param.getUserPageId());
sendSimulateInitFailure(param, "未知状态码");
break;
}
} else {
sendSimulateInitFailure(param, "未知状态码");
}
}
@@ -376,8 +385,8 @@ public class SocketSourceResponseService {
//重新下发脚本
String type = FormalTestManager.currentIssue.getType();
if (ResultUnitEnum.P.getCode().equals(type)) {
FormalTestManager.currentIssue.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
if (PowerIndexEnum.P.getKey().equals(type)) {
FormalTestManager.currentIssue.setType(PowerIndexEnum.V.getKey());
}
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
socketMsg.setData(JSON.toJSONString(FormalTestManager.currentIssue));
@@ -528,14 +537,14 @@ public class SocketSourceResponseService {
int ignoreCount;
int readData;
if (DicDataEnum.F.getCode().equals(sourceIssue.getType())) {
if (PowerIndexEnum.F.getKey().equals(sourceIssue.getType())) {
// 闪变检测:数据变化较慢,只需少量预热和读取
// 闪变测量稳定性好预热1次即可
ignoreCount = 1;
// 读取2次数据计算闪变值
readData = 2;
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_01.getValue());
} else if (DicDataEnum.VOLTAGE.getCode().equals(sourceIssue.getType())) {
} else if (PowerIndexEnum.VOLTAGE.getKey().equals(sourceIssue.getType())) {
// 暂态电压检测:需要更多预热时间,但只读取一次快照
// 暂态事件需要5次预热确保触发稳定
ignoreCount = 5;
@@ -565,9 +574,6 @@ public class SocketSourceResponseService {
DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
// 设置监测点ID列表
phaseSequenceParam.setMoniterIdList(monitorIdList);
if (socketDataMsg.getRequestId().equals(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + "P")) {
comm.add("real$PF");
}
// 设置数据类型列表
phaseSequenceParam.setDataType(comm);
// 设置读取次数

View File

@@ -33,13 +33,19 @@ public enum DetectionCodeEnum {
IA("IA", "电流相角"),
I1A("I1A", "电流基波角度值"),
V_UNBAN("V_UNBAN", "三相电压负序不平衡度"),
SeqV("SeqV", "电压序分量"),
I_UNBAN("I_UNBAN", "三相电流负序不平衡度"),
SeqA("SeqA", "电流序分量"),
PST("PST", "短时间闪变"),
W("W", "有功功率"),
VARW("VARW", "无功功率"),
VAW("VAW", "视在功率"),
// PF("PF", "功率因数"),
// P_FUND("P_FUND", "基波有功功率"),
W("W", "有功功率"),
VARW("VARW", "无功功率"),
VAW("VAW", "视在功率"),
PF("PF", "功率因数"),
TOTW("TotW", "三相总有功功率"),
TOTVA("TotVA", "三相总视在功率"),
TOTVAR("TotVAr", "三相总无功功率"),
TOTPF("TotPF","三相功率因数"),
// P_FUND("P_FUND", "基波有功功率"),
// P_HVAR("P_HVAR", "基波无功功率"),
// P_HVA("P_HVA", "基波视在功率"),
I1("I1", "基波电流"),

View File

@@ -38,10 +38,31 @@ public class ContrastDetectionParam {
@NotEmpty(message = DetectionValidMessage.PAIRS_NOT_EMPTY)
private Map<String, String> pairs;
/**
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为正式检测
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为守时校验、第四个元素为正式检测
* 比对场景暂不支持系数校准和守时校验,第二、第三个元素固定为 false。
*/
private List<Boolean> testItemList;
public boolean isPreTestSelected() {
return isTestItemSelected(0);
}
public boolean isCoefficientSelected() {
return isTestItemSelected(1);
}
public boolean isTimeCheckSelected() {
return isTestItemSelected(2);
}
public boolean isFormalTestSelected() {
return isTestItemSelected(3);
}
private boolean isTestItemSelected(int index) {
return testItemList != null && testItemList.size() > index && Boolean.TRUE.equals(testItemList.get(index));
}
private String userId;
/**

View File

@@ -0,0 +1,25 @@
package com.njcn.gather.detection.pojo.param;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Data
public class FormalProgressParam {
@NotBlank(message = "计划id不可为空")
private String planId;
@NotEmpty(message = "装置不能为空")
private List<String> devIds;
private String userPageId;
private String userId;
/**
* 保存暂存进度时必传;查询/放行续检时以后端设备表为准。
*/
private Integer formalCheckTime;
}

View File

@@ -5,7 +5,6 @@ import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
/**
* @author wr
@@ -76,7 +75,36 @@ public class PreDetectionParam {
private Float humidity;
/**
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为正式检测
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为守时校验、第四个元素为正式检测
*/
private List<Boolean> testItemList;
/**
* 是否从正式检测暂存进度续检
*/
private Boolean resumeFormal;
public boolean isPreTestSelected() {
return isTestItemSelected(0);
}
public boolean isCoefficientSelected() {
return isTestItemSelected(1);
}
public boolean isTimeCheckSelected() {
return isTestItemSelected(2);
}
public boolean isFormalTestSelected() {
return isTestItemSelected(3);
}
public boolean isResumeFormal() {
return Boolean.TRUE.equals(resumeFormal);
}
private boolean isTestItemSelected(int index) {
return testItemList != null && testItemList.size() > index && Boolean.TRUE.equals(testItemList.get(index));
}
}

View File

@@ -0,0 +1,30 @@
package com.njcn.gather.detection.pojo.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class FormalProgressVO {
private Integer formalCheckTime;
private Integer minMaxSort;
private Integer nextSort;
private Double process;
private List<TableRow> tableRows = new ArrayList<>();
@Data
public static class TableRow {
private String scriptType;
private String scriptCode;
private String scriptName;
private List<DeviceResult> devices = new ArrayList<>();
}
@Data
public static class DeviceResult {
private String deviceId;
private String deviceName;
private List<Integer> chnResult = new ArrayList<>();
}
}

View File

@@ -0,0 +1,11 @@
package com.njcn.gather.detection.service;
import com.njcn.gather.detection.pojo.param.FormalProgressParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.vo.FormalProgressVO;
public interface FormalProgressService {
FormalProgressVO restoreAndRelease(FormalProgressParam param);
Integer calculateNextSort(PreDetectionParam param);
}

View File

@@ -1,8 +1,10 @@
package com.njcn.gather.detection.service;
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
import com.njcn.gather.detection.pojo.param.FormalProgressParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
import com.njcn.gather.detection.pojo.vo.FormalProgressVO;
import java.util.List;
import java.util.Map;
@@ -33,6 +35,10 @@ public interface PreDetectionService {
boolean restartTemTest(PreDetectionParam param);
void saveFormalProgress(FormalProgressParam param);
FormalProgressVO formalProgress(FormalProgressParam param);
/**
* 模拟测试-源通讯校验
*

View File

@@ -28,7 +28,7 @@ import com.njcn.gather.monitor.pojo.po.PqMonitor;
import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
import com.njcn.gather.script.mapper.PqScriptMapper;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
@@ -73,6 +73,7 @@ public class DetectionServiceImpl {
private final IPqMonitorService pqMonitorService;
private final IPqDevService pqDevService;
private final IPqStandardDevGainRecordService pqStandardDevGainRecordService;
private final PqScriptMapper pqScriptMapper;
public static final String TYPE_A = "A";
public static final String TYPE_B = "B";
@@ -80,7 +81,6 @@ public class DetectionServiceImpl {
public static final String TYPE_T = "T";
private final String U = "U";
private final String I = "I";
private final String F = "F";
private final String HP = "HP";
private final String P = "P";
private final String MAG = "MAG";
@@ -161,30 +161,31 @@ public class DetectionServiceImpl {
param.setIn(sourceIssue.getFIn());
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
List<ErrDtlsCheckDataVO> errDtlsCheckData = pqErrSysDtlsService.listByPqErrSysIdAndTypes(param);
ResultUnitEnum resultUnitEnumByCode = ResultUnitEnum.getResultUnitEnumByCode(sourceIssue.getType());
if (sourceIssue.getIsP()) {
resultUnitEnumByCode = ResultUnitEnum.P;
PowerIndexEnum powerIndexEnum = PowerIndexEnum.getByKey(sourceIssue.getType());
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
powerIndexEnum = PowerIndexEnum.getByKey(sourceIssue.getOtherType());
}
switch (resultUnitEnumByCode) {
switch (powerIndexEnum) {
/**
* 频率
*/
case FREQ:
return isQualified(dev, devIdMapComm, errDtlsCheckData, F, sourceIssue, dataRule, code, oneConfig.getScale());
return isQualified(dev, devIdMapComm, errDtlsCheckData, PowerIndexEnum.FREQ.getKey(), sourceIssue, dataRule, code, oneConfig.getScale());
case P:
return isQualified(dev, devIdMapComm, errDtlsCheckData, P, sourceIssue, dataRule, code, oneConfig.getScale());
return isQualified(dev, devIdMapComm, errDtlsCheckData, PowerIndexEnum.P.getKey(), sourceIssue, dataRule, code, oneConfig.getScale());
case ANGLE:
return isQualified(dev, devIdMapComm, errDtlsCheckData, PowerIndexEnum.ANGLE.getKey(), sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 电压
*/
case V_RELATIVE:
case V_ABSOLUTELY:
return isQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, code, oneConfig.getScale());
case V:
return isQualified(dev, devIdMapComm, errDtlsCheckData, PowerIndexEnum.V.getKey(), sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 电流
*/
case I_RELATIVE:
case I_ABSOLUTELY:
return isQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, code, oneConfig.getScale());
case I:
return isQualified(dev, devIdMapComm, errDtlsCheckData, PowerIndexEnum.I.getKey(), sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 谐波
*/
@@ -205,22 +206,12 @@ public class DetectionServiceImpl {
* 三相电压不平衡度
*/
case IMBV:
SimAndDigNonHarmonicResult vUnban = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, "V_UNBAN", oneConfig.getScale());
if (ObjectUtil.isNotNull(vUnban)) {
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(vUnban), code);
return vUnban.getResultFlag();
}
return 4;
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 三相电流不平衡度
*/
case IMBA:
SimAndDigNonHarmonicResult iUnban = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, "I_UNBAN", oneConfig.getScale());
if (ObjectUtil.isNotNull(iUnban)) {
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(iUnban), code);
return iUnban.getResultFlag();
}
return 4;
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 谐波有功功率
*/
@@ -235,17 +226,11 @@ public class DetectionServiceImpl {
* 闪变
*/
case F:
SimAndDigNonHarmonicResult pst = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, null, sourceIssue, dataRule, "PST", oneConfig.getScale());
if (ObjectUtil.isNotNull(pst)) {
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(pst), code);
return pst.getResultFlag();
}
return 4;
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, DetectionCodeEnum.PST.getCode(), sourceIssue, dataRule, code, oneConfig.getScale());
/**
* 暂态
*/
case VOLTAGE_MAG:
case VOLTAGE_DUR:
case VOLTAGE:
return isVoltageQualified(dev, devIdMapComm, errDtlsCheckData, sourceIssue, dataRule, code, oneConfig.getScale());
default:
return isUnknownQualified(dev, devIdMapComm, errDtlsCheckData, sourceIssue, dataRule, code, oneConfig.getScale());
@@ -430,26 +415,36 @@ public class DetectionServiceImpl {
List<SimAndDigNonHarmonicResult> info = new ArrayList<>();
List<String> devValueTypeList = sourceIssue.getDevValueTypeList();
for (String s : devValueTypeList) {
if ((DetectionCodeEnum.REAL_PREFIX.getCode() + "PF").equals(s)) {
continue;
}
String[] splitArr = s.split("\\$");
// 根据数据处理规则取值。key为相别value为值列表
Map<String, List<Double>> map = devListMap(dev, dataRule, s.split("\\$")[1]);
Map<String, List<Double>> map = devListMap(dev, dataRule, splitArr[1]);
List<ErrDtlsCheckDataVO> dtlsCheckData = null;
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(splitArr[1])).collect(Collectors.toList());
}
Double fData = 1.0;
if (U.equals(type)) {
if (PowerIndexEnum.V.getKey().equals(type)) {
fData = sourceIssue.getFUn();
}
if (I.equals(type)) {
if (PowerIndexEnum.I.getKey().equals(type)) {
fData = sourceIssue.getFIn();
}
if (F.equals(type)) {
if (PowerIndexEnum.FREQ.getKey().equals(type)) {
fData = sourceIssue.getFFreq();
}
if (P.equals(type)) {
fData = sourceIssue.getFUn() * sourceIssue.getFIn() * 0.01;
Double finalFData = fData;
errDtlsCheckData.stream().forEach(x -> x.setValue(x.getValue() * finalFData));
if (PowerIndexEnum.P.getKey().equals(type)) {
if (!DetectionCodeEnum.PF.getCode().equals(splitArr[1]) && !DetectionCodeEnum.TOTPF.getCode().equals(splitArr[1])) {
Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
if (valueType) {
fData = sourceIssue.getFUn() * sourceIssue.getFIn() / 100;
}
Double finalFData = fData;
dtlsCheckData.stream().forEach(x -> x.setValue(x.getValue() * finalFData));
}
}
// if (ResultUnitEnum.ANGLE.getCode().equals(type)) {
// fData = null;
// }
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
String[] split = dev.get(0).getId().split("_");
String devID = devIdMapComm.get(split[0]);
@@ -459,52 +454,63 @@ public class DetectionServiceImpl {
result.setDataType(sourceIssue.getDataType());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
List<ErrDtlsCheckDataVO> dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(s.split("\\$")[1])).collect(Collectors.toList());
if (CollUtil.isNotEmpty(dtlsCheckData)) {
result.setAdType(dtlsCheckData.get(0).getValueType());
isQualified = dtlsCheckData.get(0).getIsQualified();
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
}
if (CollUtil.isNotEmpty(dtlsCheckData)) {
result.setAdType(dtlsCheckData.get(0).getValueType());
isQualified = dtlsCheckData.get(0).getIsQualified();
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
}
if (map.containsKey(TYPE_T)) {
List<ErrDtlsCheckDataVO> checkDataT = dtlsCheckData.stream().filter(x -> TYPE_T.equals(x.getPhase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkDataT)) {
DetectionData t = rangeComparisonList(map.get(TYPE_T), isQualified, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule, scale);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(t.getIsData());
}
} else {
List<DetectionData> resultFlag = new ArrayList<>();
Map<String, BiConsumer<SimAndDigNonHarmonicResult, DetectionData>> setters = new HashMap<>();
setters.put(TYPE_A, (r, d) -> r.setAValue(JSON.toJSONString(d)));
setters.put(TYPE_B, (r, d) -> r.setBValue(JSON.toJSONString(d)));
setters.put(TYPE_C, (r, d) -> r.setCValue(JSON.toJSONString(d)));
}
result.setResultFlag(isQualified);
if (map.containsKey(TYPE_T)) {
List<ErrDtlsCheckDataVO> checkDataT = dtlsCheckData.stream().filter(x -> TYPE_T.equals(x.getPhase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkDataT)) {
DetectionData t = rangeComparisonList(map.get(TYPE_T), isQualified, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule, scale);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(t.getIsData());
}
} else {
List<DetectionData> resultFlag = new ArrayList<>();
Map<String, BiConsumer<SimAndDigNonHarmonicResult, DetectionData>> setters = new HashMap<>();
setters.put(TYPE_A, (r, d) -> r.setAValue(JSON.toJSONString(d)));
setters.put(TYPE_B, (r, d) -> r.setBValue(JSON.toJSONString(d)));
setters.put(TYPE_C, (r, d) -> r.setCValue(JSON.toJSONString(d)));
List<String> phases = Arrays.asList(TYPE_A, TYPE_B, TYPE_C);
for (String phase : phases) {
List<ErrDtlsCheckDataVO> checkData = dtlsCheckData.stream()
.filter(x -> phase.equals(x.getPhase()))
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkData)) {
List<Double> phaseValue = map.get(phase);
// 注意如果map中不存在该phase的键phaseValue可能为null需确保map包含该键
DetectionData detectionData = rangeComparisonList(phaseValue, isQualified, pqErrSysDtls, fData, checkData.get(0).getValue(), dataRule, scale);
resultFlag.add(detectionData);
BiConsumer<SimAndDigNonHarmonicResult, DetectionData> setter = setters.get(phase);
if (setter != null) {
setter.accept(result, detectionData);
} else {
// 处理未定义的setter的情况
throw new IllegalArgumentException("Setter not defined for phase: " + phase);
}
List<String> phases = Arrays.asList(TYPE_A, TYPE_B, TYPE_C);
for (String phase : phases) {
List<ErrDtlsCheckDataVO> checkData = dtlsCheckData.stream()
.filter(x -> phase.equals(x.getPhase()))
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkData)) {
List<Double> phaseValue = map.get(phase);
if (PowerIndexEnum.ANGLE.getKey().equals(type)) {
phaseValue = phaseValue.stream().map(x -> {
// 原始误差值
double originDiff = x - checkData.get(0).getValue();
// 转换误差值
double translateDiff = Math.abs(originDiff) - 360;
if (Math.abs(translateDiff) <= 10) {
return Math.abs(x);
} else {
return x;
}
}).collect(Collectors.toList());
}
// 注意如果map中不存在该phase的键phaseValue可能为null需确保map包含该键
DetectionData detectionData = rangeComparisonList(phaseValue, isQualified, pqErrSysDtls, fData, checkData.get(0).getValue(), dataRule, scale);
resultFlag.add(detectionData);
BiConsumer<SimAndDigNonHarmonicResult, DetectionData> setter = setters.get(phase);
if (setter != null) {
setter.accept(result, detectionData);
} else {
// 处理未定义的setter的情况
throw new IllegalArgumentException("Setter not defined for phase: " + phase);
}
}
result.setResultFlag(setResultFlag(resultFlag));
}
info.add(result);
result.setResultFlag(setResultFlag(resultFlag));
}
info.add(result);
}
if (CollUtil.isNotEmpty(info)) {
detectionDataDealService.acceptNonHarmonicResult(info, code);
@@ -532,11 +538,15 @@ public class DetectionServiceImpl {
SourceIssue sourceIssue,
DictDataEnum dataRule,
Integer num, Integer scale) {
Double fData = 1.0;
Double fDataA = 1.0;
Double fDataB = 1.0;
Double fDataC = 1.0;
String fundCode = "";
String harmCode = "";
if (U.equals(type)) {
fData = sourceIssue.getFUn();
fDataA = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Ua")).findFirst().get().getFAmp();
fDataB = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Ub")).findFirst().get().getFAmp();
fDataC = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Uc")).findFirst().get().getFAmp();
fundCode = DetectionCodeEnum.U1.getCode();
if (num == 1) {
harmCode = DetectionCodeEnum.SV_1_49.getCode();
@@ -545,7 +555,9 @@ public class DetectionServiceImpl {
}
}
if (I.equals(type)) {
fData = sourceIssue.getFIn();
fDataA = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Ia")).findFirst().get().getFAmp();
fDataB = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Ib")).findFirst().get().getFAmp();
fDataC = sourceIssue.getChannelList().stream().filter(x -> x.getChannelType().contains("Ic")).findFirst().get().getFAmp();
fundCode = DetectionCodeEnum.I1.getCode();
if (num == 1) {
harmCode = DetectionCodeEnum.SI_1_49.getCode();
@@ -554,7 +566,9 @@ public class DetectionServiceImpl {
}
}
if (HP.equals(type)) {
fData = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
fDataA = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
fDataB = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
fDataC = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
harmCode = DetectionCodeEnum.P2_50.getCode();
}
// if (P.equals(type)) {
@@ -580,9 +594,9 @@ public class DetectionServiceImpl {
pqErrSysDtls = adDtlsCheckData.get(0).getErrSysDtls();
}
}
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_A, sourceIssue, dataRule, devMap.get(TYPE_A), fData, num, scale);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_B, sourceIssue, dataRule, devMap.get(TYPE_B), fData, num, scale);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_C, sourceIssue, dataRule, devMap.get(TYPE_C), fData, num, scale);
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_A, sourceIssue, dataRule, devMap.get(TYPE_A), fDataA, num, scale);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_B, sourceIssue, dataRule, devMap.get(TYPE_B), fDataB, num, scale);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_C, sourceIssue, dataRule, devMap.get(TYPE_C), fDataC, num, scale);
harmonicResult.setDataType(sourceIssue.getDataType());
reflectHarmonic(false, "a", integerBooleanA, harmonicResult, num);
reflectHarmonic(false, "b", integerBooleanB, harmonicResult, num);
@@ -607,74 +621,110 @@ public class DetectionServiceImpl {
* @param dataRule 数据处理原则
* @return
*/
public SimAndDigNonHarmonicResult isUnBalanceOrFlickerQualified(List<DevData> dev,
Map<String, String> devIdMapComm,
List<ErrDtlsCheckDataVO> errDtlsCheckData,
String type,
SourceIssue sourceIssue,
DictDataEnum dataRule,
String code, Integer scale) {
public Integer isUnBalanceOrFlickerQualified(List<DevData> dev,
Map<String, String> devIdMapComm,
List<ErrDtlsCheckDataVO> errDtlsCheckData,
String type,
SourceIssue sourceIssue,
DictDataEnum dataRule,
String code, Integer scale) {
List<SimAndDigNonHarmonicResult> info = new ArrayList<>();
List<PqScriptCheckData> checkData = pqScriptCheckDataService.list(new MPJLambdaWrapper<PqScriptCheckData>()
.eq(PqScriptCheckData::getScriptIndex, sourceIssue.getIndex())
.eq(PqScriptCheckData::getScriptId, sourceIssue.getScriptId())
);
Map<String, List<Double>> map = devListMap(dev, dataRule, code);
if (CollUtil.isNotEmpty(map)) {
Double fData = 1.0;
if (U.equals(type)) {
fData = sourceIssue.getFUn();
}
if (I.equals(type)) {
fData = sourceIssue.getFIn();
}
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
String[] split = dev.get(0).getId().split("_");
String devID = devIdMapComm.get(split[0]);
result.setDevMonitorId(devID + "_" + split[1]);
result.setScriptId(sourceIssue.getScriptId());
result.setSort(sourceIssue.getIndex());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
result.setAdType(errDtlsCheckData.get(0).getValueType());
isQualified = errDtlsCheckData.get(0).getIsQualified();
if (CollUtil.isNotEmpty(errDtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = errDtlsCheckData.get(0).getErrSysDtls();
List<String> devValueTypeList = sourceIssue.getDevValueTypeList();
for (String s : devValueTypeList) {
String[] splitArr = s.split("\\$");
Map<String, List<Double>> map = devListMap(dev, dataRule, splitArr[1]);
if (CollUtil.isNotEmpty(map)) {
List<ErrDtlsCheckDataVO> dtlsCheckData = null;
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(s.split("\\$")[1])).collect(Collectors.toList());
}
Double fData = 1.0;
if (U.equals(type)) {
fData = sourceIssue.getFUn();
}
if (I.equals(type)) {
fData = sourceIssue.getFIn();
}
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
String[] split = dev.get(0).getId().split("_");
String devID = devIdMapComm.get(split[0]);
result.setDevMonitorId(devID + "_" + split[1]);
result.setScriptId(sourceIssue.getScriptId());
result.setSort(sourceIssue.getIndex());
result.setDataType(sourceIssue.getDataType());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
if (CollUtil.isNotEmpty(dtlsCheckData)) {
result.setAdType(dtlsCheckData.get(0).getValueType());
isQualified = dtlsCheckData.get(0).getIsQualified();
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
}
}
result.setResultFlag(isQualified);
// 闪变
if (DetectionCodeEnum.PST.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
//取出源所对应的相别信息
List<PqScriptCheckData> channelTypeAList = checkData.stream()
.filter(x -> TYPE_A.equals(x.getPhase()))
.collect(Collectors.toList());
Double channelDataA = channelTypeAList.get(0).getValue();
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
channelDataA = BigDecimal.valueOf(channelDataA / 100 * fData)
.setScale(scale, RoundingMode.HALF_UP)
.doubleValue();
}
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, pqErrSysDtls, fData, channelDataA, dataRule, scale);
result.setAValue(JSON.toJSONString(a));
List<PqScriptCheckData> channelTypeBList = checkData.stream()
.filter(x -> TYPE_B.equals(x.getPhase()))
.collect(Collectors.toList());
Double channelDataB = channelTypeBList.get(0).getValue();
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
channelDataB = BigDecimal.valueOf(channelDataB / 100 * fData)
.setScale(scale, RoundingMode.HALF_UP)
.doubleValue();
}
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelDataB, dataRule, scale);
result.setBValue(JSON.toJSONString(b));
List<PqScriptCheckData> channelTypeCList = checkData.stream()
.filter(x -> TYPE_C.equals(x.getPhase()))
.collect(Collectors.toList());
Double channelDataC = channelTypeCList.get(0).getValue();
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
channelDataC = BigDecimal.valueOf(channelDataC / 100 * fData)
.setScale(scale, RoundingMode.HALF_UP)
.doubleValue();
}
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, pqErrSysDtls, fData, channelDataC, dataRule, scale);
result.setCValue(JSON.toJSONString(c));
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
} else {
// 三项不平衡
List<PqScriptCheckData> channelTypeBList = checkData.stream()
.filter(x -> TYPE_T.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(setResultFlag(Arrays.asList(t)));
}
info.add(result);
}
result.setDataType(sourceIssue.getDataType());
if (StrUtil.isBlank(type)) {
//取出源所对应的相别信息
List<PqScriptCheckData> channelTypeAList = checkData.stream()
.filter(x -> TYPE_A.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, pqErrSysDtls, fData, channelTypeAList.get(0).getValue(), dataRule, scale);
result.setAValue(JSON.toJSONString(a));
List<PqScriptCheckData> channelTypeBList = checkData.stream()
.filter(x -> TYPE_B.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
result.setBValue(JSON.toJSONString(b));
List<PqScriptCheckData> channelTypeCList = checkData.stream()
.filter(x -> TYPE_C.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, pqErrSysDtls, fData, channelTypeCList.get(0).getValue(), dataRule, scale);
result.setCValue(JSON.toJSONString(c));
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
} else {
List<PqScriptCheckData> channelTypeBList = checkData.stream()
.filter(x -> TYPE_T.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(setResultFlag(Arrays.asList(t)));
}
return result;
}
return null;
if (CollUtil.isNotEmpty(info)) {
detectionDataDealService.acceptNonHarmonicResult(info, code);
List<Integer> resultFlag = info.stream().map(SimAndDigNonHarmonicResult::getResultFlag).distinct().collect(Collectors.toList());
return StorageUtil.getInteger(resultFlag);
}
return 4;
}

View File

@@ -0,0 +1,218 @@
package com.njcn.gather.detection.service.impl;
import cn.hutool.core.collection.CollUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.handler.SocketDevResponseService;
import com.njcn.gather.detection.pojo.param.FormalProgressParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.vo.FormalProgressVO;
import com.njcn.gather.detection.service.FormalProgressService;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import com.njcn.gather.device.pojo.enums.CommonEnum;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.storage.pojo.po.SimAndDigBaseResult;
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
import com.njcn.gather.system.dictionary.service.IDictTreeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class FormalProgressServiceImpl implements FormalProgressService {
private static final long RESUME_RELEASE_DELAY_MILLIS = 300L;
private final IPqDevService pqDevService;
private final IPqScriptDtlsService pqScriptDtlsService;
private final IDictTreeService dictTreeService;
private final SimAndDigHarmonicService harmonicService;
private final SimAndDigNonHarmonicService nonHarmonicService;
private final SocketDevResponseService socketDevResponseService;
@Override
public FormalProgressVO restoreAndRelease(FormalProgressParam param) {
PreDetectionParam preParam = WebServiceManager.getPreDetectionParam(param.getUserPageId());
if (preParam == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "未找到续检上下文,请重新开始检测");
}
FormalProgressVO vo = buildSnapshot(preParam, param.getDevIds());
releaseResumeAfterSnapshotApplied(preParam, vo.getNextSort());
return vo;
}
@Override
public Integer calculateNextSort(PreDetectionParam param) {
return buildSnapshot(param, param.getDevIds()).getNextSort();
}
private FormalProgressVO buildSnapshot(PreDetectionParam param, List<String> devIds) {
FormalProgressVO vo = new FormalProgressVO();
vo.setFormalCheckTime(pqDevService.getMinFormalCheckTime(devIds));
Map<String, Integer> harmonicMax = harmonicService.maxSortByDevIds(param.getCode(), param.getScriptId(), devIds);
Map<String, Integer> nonHarmonicMax = nonHarmonicService.maxSortByDevIds(param.getCode(), param.getScriptId(), devIds);
Integer minMaxSort = devIds.stream()
.map(devId -> Math.max(harmonicMax.getOrDefault(devId, -1), nonHarmonicMax.getOrDefault(devId, -1)))
.min(Integer::compareTo)
.orElse(-1);
vo.setMinMaxSort(minMaxSort);
List<SourceIssue> allIssues = buildAllFormalIssues(param);
List<Integer> allSorts = allIssues.stream()
.map(SourceIssue::getIndex)
.filter(sort -> sort != null && sort >= 0)
.sorted()
.collect(Collectors.toList());
Integer nextSort = allSorts.stream()
.filter(sort -> sort > minMaxSort)
.findFirst()
.orElse(null);
vo.setNextSort(nextSort);
Set<String> completedTypes = completedBigTypes(allIssues, minMaxSort);
long totalBigTypes = allIssues.stream().map(SourceIssue::getType).distinct().count();
vo.setProcess(totalBigTypes == 0 ? 0D : completedTypes.size() * 100D / totalBigTypes);
vo.setTableRows(buildRows(param, devIds, allIssues, completedTypes));
return vo;
}
private void releaseResumeAfterSnapshotApplied(PreDetectionParam preParam, Integer nextSort) {
CompletableFuture.runAsync(() -> {
try {
Thread.sleep(RESUME_RELEASE_DELAY_MILLIS);
socketDevResponseService.startFormalAfterProgressRestore(preParam, nextSort);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("正式检测续检放行等待被中断", e);
} catch (Exception e) {
log.error("正式检测续检放行失败", e);
}
});
}
private List<SourceIssue> buildAllFormalIssues(PreDetectionParam param) {
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceName());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
return pqScriptDtlsService.listSourceIssue(issueParam)
.stream()
.sorted(Comparator.comparing(SourceIssue::getIndex))
.collect(Collectors.toList());
}
private Set<String> completedBigTypes(List<SourceIssue> issues, Integer minMaxSort) {
return issues.stream()
.collect(Collectors.groupingBy(SourceIssue::getType, LinkedHashMap::new, Collectors.toList()))
.entrySet()
.stream()
.filter(entry -> entry.getValue().stream().allMatch(issue -> issue.getIndex() <= minMaxSort))
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
private List<FormalProgressVO.TableRow> buildRows(PreDetectionParam param,
List<String> devIds,
List<SourceIssue> issues,
Set<String> completedTypes) {
Map<String, List<SourceIssue>> byType = issues.stream()
.collect(Collectors.groupingBy(SourceIssue::getType, LinkedHashMap::new, Collectors.toList()));
if (byType.isEmpty()) {
return Collections.emptyList();
}
Map<String, DictTree> dictTreeByCode = dictTreeService.lambdaQuery()
.in(DictTree::getCode, byType.keySet())
.list()
.stream()
.collect(Collectors.toMap(DictTree::getCode, dictTree -> dictTree, (left, right) -> left));
return byType.entrySet().stream().map(entry -> {
List<SourceIssue> typeIssues = entry.getValue();
boolean completed = completedTypes.contains(entry.getKey());
DictTree dictTree = dictTreeByCode.get(entry.getKey());
FormalProgressVO.TableRow row = new FormalProgressVO.TableRow();
row.setScriptCode(entry.getKey());
row.setScriptName(dictTree.getName());
row.setScriptType(dictTree.getId());
row.setDevices(completed
? buildCompletedDeviceResults(param, devIds, typeIssues)
: buildUnknownDeviceResults(devIds));
return row;
}).collect(Collectors.toList());
}
private List<FormalProgressVO.DeviceResult> buildUnknownDeviceResults(List<String> devIds) {
return pqDevService.getDevInfo(devIds).stream().map(dev -> {
FormalProgressVO.DeviceResult item = new FormalProgressVO.DeviceResult();
item.setDeviceId(dev.getDevId());
item.setDeviceName(dev.getDevName());
item.setChnResult(dev.getMonitorList().stream().map(monitor -> -1).collect(Collectors.toList()));
return item;
}).collect(Collectors.toList());
}
private List<FormalProgressVO.DeviceResult> buildCompletedDeviceResults(PreDetectionParam param,
List<String> devIds,
List<SourceIssue> typeIssues) {
List<Integer> sorts = typeIssues.stream().map(SourceIssue::getIndex).distinct().collect(Collectors.toList());
List<SimAndDigBaseResult> rows = new ArrayList<>();
rows.addAll(harmonicService.listByDevIdsAndSorts(param.getCode(), param.getScriptId(), devIds, sorts));
rows.addAll(nonHarmonicService.listByDevIdsAndSorts(param.getCode(), param.getScriptId(), devIds, sorts));
Map<String, List<Integer>> flagMap = rows.stream()
.filter(row -> row.getResultFlag() != null)
.collect(Collectors.groupingBy(SimAndDigBaseResult::getDevMonitorId,
Collectors.mapping(SimAndDigBaseResult::getResultFlag, Collectors.toList())));
return pqDevService.getDevInfo(devIds).stream().map(dev -> {
FormalProgressVO.DeviceResult item = new FormalProgressVO.DeviceResult();
item.setDeviceId(dev.getDevId());
item.setDeviceName(dev.getDevName());
item.setChnResult(dev.getMonitorList().stream()
.map(monitor -> mergeResultFlags(resolveResultFlags(flagMap, dev, monitor)))
.collect(Collectors.toList()));
return item;
}).collect(Collectors.toList());
}
private List<Integer> resolveResultFlags(Map<String, List<Integer>> flagMap, PreDetection dev, PreDetection.MonitorListDTO monitor) {
List<Integer> flags = new ArrayList<>();
List<Integer> byDevLine = flagMap.get(dev.getDevId() + "_" + monitor.getLine());
if (CollUtil.isNotEmpty(byDevLine)) {
flags.addAll(byDevLine);
}
List<Integer> byLineId = flagMap.get(monitor.getLineId());
if (CollUtil.isNotEmpty(byLineId)) {
flags.addAll(byLineId);
}
return flags;
}
private Integer mergeResultFlags(List<Integer> flags) {
if (CollUtil.isEmpty(flags)) {
return -1;
}
List<Integer> effective = flags.stream()
.filter(flag -> flag != null && flag != 4 && flag != 5)
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(effective)) {
return effective.stream().max(Integer::compareTo).orElse(1);
}
return flags.get(0);
}
}

View File

@@ -3,8 +3,11 @@ package com.njcn.gather.detection.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.handler.SocketContrastResponseService;
import com.njcn.gather.detection.handler.SocketDevResponseService;
@@ -13,9 +16,12 @@ import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
import com.njcn.gather.detection.pojo.param.FormalProgressParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
import com.njcn.gather.detection.pojo.vo.FormalProgressVO;
import com.njcn.gather.detection.pojo.vo.SocketMsg;
import com.njcn.gather.detection.service.FormalProgressService;
import com.njcn.gather.detection.service.PreDetectionService;
import com.njcn.gather.detection.util.business.DetectionCommunicateUtil;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
@@ -24,15 +30,20 @@ import com.njcn.gather.detection.util.socket.SocketManager;
import com.njcn.gather.detection.util.socket.XiNumberManager;
import com.njcn.gather.detection.util.socket.cilent.NettyContrastClientHandler;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import com.njcn.gather.device.pojo.enums.CheckResultEnum;
import com.njcn.gather.device.pojo.enums.CheckStateEnum;
import com.njcn.gather.device.pojo.enums.CommonEnum;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.device.pojo.po.PqDevSub;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.device.service.IPqDevSubService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.po.AdPlanSource;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.plan.service.IAdPlanSourceService;
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.po.SourceIssue;
@@ -40,6 +51,8 @@ import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.source.pojo.po.SourceInitialize;
import com.njcn.gather.source.service.IPqSourceService;
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
@@ -49,7 +62,6 @@ import com.njcn.web.utils.RequestUtil;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
@@ -81,9 +93,13 @@ public class PreDetectionServiceImpl implements PreDetectionService {
private final IPqScriptCheckDataService iPqScriptCheckDataService;
private final SocketManager socketManager;
private final ISysTestConfigService sysTestConfigService;
private final FormalProgressService formalProgressService;
private final IPqDevSubService pqDevSubService;
private final SimAndDigHarmonicService harmonicService;
private final SimAndDigNonHarmonicService nonHarmonicService;
// @Value("${report.reportDir}")
// @Value("${report.reportDir}")
// private String alignDataFilePath;
private final PathConfig pathConfig;
@@ -102,6 +118,28 @@ public class PreDetectionServiceImpl implements PreDetectionService {
param.setScriptId(plan.getScriptId());
param.setErrorSysId(plan.getErrorSysId());
param.setCode(String.valueOf(plan.getCode()));
if (param.isFormalTestSelected()) {
List<PqDevSub> devSubs = pqDevSubService.lambdaQuery()
.in(PqDevSub::getDevId, param.getDevIds())
.list();
boolean hasSaved = devSubs.stream().anyMatch(this::isSavedFormalProgress);
if (param.isResumeFormal() && !hasSaved) {
throw new BusinessException(CommonResponseEnum.FAIL, "未找到正式检测暂存进度");
}
}
if (param.isFormalTestSelected() && !param.isResumeFormal()) {
FormalTestManager.resumeBaseFormalCheckTime = null;
FormalTestManager.resumeFormalStartTime = null;
FormalTestManager.resumeNextSort = null;
FormalTestManager.resumeFormalPending = false;
}
if (param.isFormalTestSelected() && param.isResumeFormal()) {
FormalTestManager.resumeBaseFormalCheckTime = iPqDevService.getMinFormalCheckTime(param.getDevIds());
pqDevSubService.lambdaUpdate()
.set(PqDevSub::getCheckState, CheckStateEnum.CHECKING.getValue())
.in(PqDevSub::getDevId, param.getDevIds())
.update();
}
if (ObjectUtil.isNotNull(plan)) {
String code = dictDataService.getDictDataById(plan.getPattern()).getCode();
DictDataEnum dictDataEnumByCode = DictDataEnum.getDictDataEnumByCode(code);
@@ -223,6 +261,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
private void sendYtxSocketSimulate(PreDetectionParam param) {
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
param.setSourceId(sourceParam.getSourceId());
param.setSourceName(sourceParam.getSourceId());
String loginName = RequestUtil.getLoginNameByToken();
WebServiceManager.addPreDetectionParam(loginName, param);
if (ObjectUtil.isNotNull(sourceParam)) {
@@ -245,33 +284,254 @@ public class PreDetectionServiceImpl implements PreDetectionService {
@Override
public boolean restartTemTest(PreDetectionParam param) {
PreDetectionParam runtimeParam = WebServiceManager.getPreDetectionParam(param.getUserPageId());
if (runtimeParam == null) {
if (StrUtil.isBlank(param.getSourceId()) || StrUtil.isBlank(param.getScriptId()) || StrUtil.isBlank(param.getCode())) {
throw new BusinessException(CommonResponseEnum.FAIL, "未找到暂停检测上下文,请重新开始检测");
}
runtimeParam = param;
}
FormalTestManager.stopFlag = false;
socketDevResponseService.initRestart();
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
param.setSourceName(sourceInitialize.getSourceId());
if (StrUtil.isBlank(runtimeParam.getSourceName()) && StrUtil.isNotBlank(runtimeParam.getSourceId())) {
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(runtimeParam.getSourceId());
if (sourceInitialize == null) {
throw new BusinessException(DetectionResponseEnum.SOURCE_INFO_NOT);
}
runtimeParam.setSourceName(sourceInitialize.getSourceId());
}
if (CollUtil.isNotEmpty(sourceIssueList)) {
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
String type = resolveFormalIssueType(sourceIssues);
sendBigItemStartIfFirstFormalIssue(runtimeParam, sourceIssues, type);
if (StrUtil.isNotBlank(sourceIssues.getOtherType())) {
sourceIssues.setType(PowerIndexEnum.V.getKey());
}
SocketMsg<String> xuMsg = new SocketMsg<>();
xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
xuMsg.setData(JSON.toJSONString(sourceIssues));
xuMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + "&&" + sourceIssues.getType());
SocketManager.sendMsg(param.getUserPageId() + DetectionCommunicateConstant.SOURCE, JSON.toJSONString(xuMsg));
xuMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + "&&" + type);
SocketManager.sendMsg(runtimeParam.getUserPageId() + DetectionCommunicateConstant.SOURCE, JSON.toJSONString(xuMsg));
// Resume_Success
} else {
//TODO 是否最终检测完成需要推送给用户 检测完成
PqScriptCheckDataParam checkDataParam = new PqScriptCheckDataParam();
checkDataParam.setScriptId(param.getScriptId());
checkDataParam.setScriptId(runtimeParam.getScriptId());
checkDataParam.setIsValueTypeName(false);
List<String> adType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), adType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
CnSocketUtil.quitSend(param);
iPqDevService.updateResult(runtimeParam.getDevIds(), adType, runtimeParam.getCode(), runtimeParam.getUserId(), runtimeParam.getTemperature(), runtimeParam.getHumidity(), true);
CnSocketUtil.quitSend(runtimeParam);
}
return true;
}
@Override
public void saveFormalProgress(FormalProgressParam param) {
if (param.getFormalCheckTime() == null) {
throw new BusinessException(CommonResponseEnum.FAIL, "正式检测耗时不能为空");
}
PreDetectionParam preParam = WebServiceManager.getPreDetectionParam(param.getUserPageId());
Map<String, Integer> checkResultMap = summarizeSavedFormalCheckResult(param, preParam);
Integer formalCheckTime = Math.max(param.getFormalCheckTime(), 1);
Map<Integer, List<String>> devIdsByResult = param.getDevIds().stream()
.collect(Collectors.groupingBy(devId -> checkResultMap.getOrDefault(devId, CheckResultEnum.UNCHECKED.getValue())));
devIdsByResult.forEach((checkResult, devIds) -> pqDevSubService.update(new LambdaUpdateWrapper<PqDevSub>()
.set(PqDevSub::getCheckState, CheckStateEnum.CHECKING.getValue())
.set(PqDevSub::getFormalCheckTime, formalCheckTime)
.set(PqDevSub::getCheckResult, checkResult)
.in(PqDevSub::getDevId, devIds)));
refreshPlanTestState(param.getPlanId());
if (preParam != null) {
CnSocketUtil.quitSend(preParam);
}
SocketManager.clearFormalRuntime();
FormalTestManager.clearFormalRuntime();
WebServiceManager.removePreDetectionParam(param.getUserPageId());
}
@Override
public FormalProgressVO formalProgress(FormalProgressParam param) {
return formalProgressService.restoreAndRelease(param);
}
private Map<String, Integer> summarizeSavedFormalCheckResult(FormalProgressParam param, PreDetectionParam preParam) {
Map<String, Integer> result = new HashMap<>();
if (CollUtil.isEmpty(param.getDevIds())) {
return result;
}
param.getDevIds().forEach(devId -> result.put(devId, CheckResultEnum.UNCHECKED.getValue()));
AdPlan plan = iAdPlanService.getById(param.getPlanId());
String code = preParam != null && StrUtil.isNotBlank(preParam.getCode())
? preParam.getCode()
: plan != null && plan.getCode() != null ? String.valueOf(plan.getCode()) : null;
String scriptId = preParam != null && StrUtil.isNotBlank(preParam.getScriptId())
? preParam.getScriptId()
: plan != null ? plan.getScriptId() : null;
if (StrUtil.isBlank(code) || StrUtil.isBlank(scriptId)) {
return result;
}
List<Integer> completedSorts = resolveCompletedFormalSorts(preParam);
if (completedSorts != null && CollUtil.isEmpty(completedSorts)) {
return result;
}
Map<String, List<Integer>> resultFlags = new HashMap<>();
mergeResultFlags(resultFlags, nonHarmonicService.resultFlagsByDevIdsAndSorts(code, scriptId, param.getDevIds(), completedSorts));
mergeResultFlags(resultFlags, harmonicService.resultFlagsByDevIdsAndSorts(code, scriptId, param.getDevIds(), completedSorts));
param.getDevIds().forEach(devId -> result.put(devId, toCheckResult(resultFlags.get(devId))));
return result;
}
private List<Integer> resolveCompletedFormalSorts(PreDetectionParam preParam) {
if (preParam == null) {
return null;
}
List<SourceIssue> allIssues = buildAllFormalIssues(preParam);
if (CollUtil.isEmpty(allIssues)) {
return Collections.emptyList();
}
List<SourceIssue> remainingIssues = SocketManager.getSourceList();
Set<Integer> remainingSorts = CollUtil.isEmpty(remainingIssues)
? Collections.emptySet()
: remainingIssues.stream()
.map(SourceIssue::getIndex)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
return allIssues.stream()
.map(SourceIssue::getIndex)
.filter(Objects::nonNull)
.filter(sort -> !remainingSorts.contains(sort))
.distinct()
.sorted()
.collect(Collectors.toList());
}
private List<SourceIssue> buildAllFormalIssues(PreDetectionParam param) {
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceName());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
return pqScriptDtlsService.listSourceIssue(issueParam);
}
private void sendBigItemStartIfFirstFormalIssue(PreDetectionParam param, SourceIssue currentIssue, String type) {
if (param == null || currentIssue == null || currentIssue.getIndex() == null || StrUtil.isBlank(type)) {
return;
}
List<SourceIssue> allIssues = buildAllFormalIssues(param);
if (isFirstFormalIssueOfBigItem(allIssues, currentIssue, type)) {
WebServiceManager.sendDetectionMessage(param.getUserPageId(), type + CnSocketUtil.START_TAG, null, new ArrayList<>(), null);
}
}
static boolean isFirstFormalIssueOfBigItem(List<SourceIssue> allIssues, SourceIssue currentIssue, String type) {
if (CollUtil.isEmpty(allIssues) || currentIssue == null || currentIssue.getIndex() == null || StrUtil.isBlank(type)) {
return false;
}
Integer firstSort = allIssues.stream()
.filter(issue -> type.equals(resolveFormalIssueType(issue)))
.map(SourceIssue::getIndex)
.filter(Objects::nonNull)
.min(Integer::compareTo)
.orElse(null);
return Objects.equals(firstSort, currentIssue.getIndex());
}
static String resolveFormalIssueType(SourceIssue issue) {
if (issue == null) {
return null;
}
return StrUtil.isNotBlank(issue.getOtherType()) ? issue.getOtherType() : issue.getType();
}
private void mergeResultFlags(Map<String, List<Integer>> target, Map<String, List<Integer>> source) {
if (CollUtil.isEmpty(source)) {
return;
}
source.forEach((devId, flags) -> target.computeIfAbsent(devId, key -> new ArrayList<>()).addAll(flags));
}
private Integer toCheckResult(List<Integer> resultFlags) {
if (CollUtil.isEmpty(resultFlags)) {
return CheckResultEnum.UNCHECKED.getValue();
}
List<Integer> effectiveFlags = resultFlags.stream()
.filter(flag -> flag != null && flag != 4 && flag != 5)
.collect(Collectors.toList());
if (CollUtil.isEmpty(effectiveFlags)) {
return CheckResultEnum.ACCORD.getValue();
}
boolean hasFailed = effectiveFlags.stream().anyMatch(flag -> !Objects.equals(flag, 1));
return hasFailed ? CheckResultEnum.NOT_ACCORD.getValue() : CheckResultEnum.ACCORD.getValue();
}
private boolean isSavedFormalProgress(PqDevSub dev) {
return CheckStateEnum.CHECKING.getValue().equals(dev.getCheckState())
&& ObjectUtil.isNotNull(dev.getFormalCheckTime())
&& dev.getFormalCheckTime() > 0;
}
private void refreshPlanTestState(String planId) {
if (StrUtil.isBlank(planId)) {
return;
}
List<String> planDevIds = iPqDevService.lambdaQuery()
.eq(PqDev::getPlanId, planId)
.list()
.stream()
.map(PqDev::getId)
.collect(Collectors.toList());
if (CollUtil.isEmpty(planDevIds)) {
iAdPlanService.lambdaUpdate()
.set(AdPlan::getTestState, CheckStateEnum.UNCHECKED.getValue())
.set(AdPlan::getResult, CheckResultEnum.UNCHECKED.getValue())
.eq(AdPlan::getId, planId)
.update();
return;
}
List<PqDevSub> devSubs = pqDevSubService.lambdaQuery()
.in(PqDevSub::getDevId, planDevIds)
.list();
boolean allUnchecked = devSubs.stream()
.allMatch(dev -> CheckStateEnum.UNCHECKED.getValue().equals(dev.getCheckState()));
boolean allArchived = CollUtil.isNotEmpty(devSubs) && devSubs.stream()
.allMatch(dev -> dev.getCheckState() != null && dev.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
Integer testState = allUnchecked
? CheckStateEnum.UNCHECKED.getValue()
: allArchived ? CheckStateEnum.CHECKED.getValue() : CheckStateEnum.CHECKING.getValue();
Integer planResult = resolvePlanCheckResult(devSubs);
iAdPlanService.lambdaUpdate()
.set(AdPlan::getTestState, testState)
.set(AdPlan::getResult, planResult)
.eq(AdPlan::getId, planId)
.update();
}
private Integer resolvePlanCheckResult(List<PqDevSub> devSubs) {
if (CollUtil.isEmpty(devSubs)) {
return CheckResultEnum.UNCHECKED.getValue();
}
Set<Integer> resultSet = devSubs.stream()
.map(PqDevSub::getCheckResult)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (resultSet.contains(CheckResultEnum.NOT_ACCORD.getValue())) {
return CheckResultEnum.NOT_ACCORD.getValue();
}
if (resultSet.contains(CheckResultEnum.UNCHECKED.getValue()) || CollUtil.isEmpty(resultSet)) {
return CheckResultEnum.UNCHECKED.getValue();
}
return CheckResultEnum.ACCORD.getValue();
}
@Override
public void ytxCheckSimulate(SimulateDetectionParam param) {
PreDetectionParam preDetectionParam = new PreDetectionParam();
@@ -309,9 +569,9 @@ public class PreDetectionServiceImpl implements PreDetectionService {
SourceIssue sourceIssue = sourceIssues.get(0);
String type = sourceIssue.getType();
if (sourceIssue.getIsP()) {
sourceIssue.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
type = ResultUnitEnum.P.getCode();
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
sourceIssue.setType(PowerIndexEnum.V.getKey());
type = sourceIssue.getOtherType();
}
List<String> comm = sourceIssue.getDevValueTypeList();
@@ -333,6 +593,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
PreDetectionParam preDetectionParam = new PreDetectionParam();
preDetectionParam.setSourceId(sourceParam.getSourceId());
preDetectionParam.setSourceName(sourceParam.getSourceId());
preDetectionParam.setUserPageId(param.getUserPageId());
CnSocketUtil.quitSendSource(preDetectionParam);
WebServiceManager.removePreDetectionParam();
@@ -459,4 +720,4 @@ public class PreDetectionServiceImpl implements PreDetectionService {
}
}
}
}

View File

@@ -0,0 +1,20 @@
package com.njcn.gather.detection.sntp;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.net.InetSocketAddress;
import java.time.Instant;
@Data
@AllArgsConstructor
public class SntpExchange {
private InetSocketAddress clientAddress;
private int version;
private Instant deviceInstant;
private byte[] clientTransmitTimestamp;
}

View File

@@ -0,0 +1,110 @@
package com.njcn.gather.detection.sntp;
import org.springframework.stereotype.Service;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
@Service
public class SntpPacketService {
private static final int MIN_PACKET_LENGTH = 48;
private static final int CLIENT_MODE = 3;
private static final int SERVER_MODE = 4;
// NTP纪元偏移量2208988800秒1900年到1970年的秒数差
private static final long NTP_EPOCH_OFFSET = 2208988800L;
private static final ZoneId SHANGHAI_ZONE = ZoneId.of("Asia/Shanghai");
private static final byte[] REFERENCE_ID = "LOCL".getBytes(StandardCharsets.US_ASCII);
public SntpExchange parseRequest(byte[] request, InetSocketAddress clientAddress) {
if (request == null || request.length < MIN_PACKET_LENGTH) {
return null;
}
int mode = request[0] & 0x07;
if (mode != CLIENT_MODE) {
return null;
}
int version = (request[0] >> 3) & 0x07;
byte[] clientTransmitTimestamp = Arrays.copyOfRange(request, 40, 48);
Instant deviceInstant = fromNtpTimestamp(clientTransmitTimestamp);
return new SntpExchange(clientAddress, version == 0 ? 3 : version, deviceInstant, clientTransmitTimestamp);
}
public byte[] buildResponse(SntpExchange exchange, Instant receiveInstant, Instant transmitInstant) {
byte[] response = new byte[MIN_PACKET_LENGTH];
int version = exchange.getVersion() == 0 ? 3 : exchange.getVersion();
response[0] = (byte) ((version << 3) | SERVER_MODE);
response[1] = 0x01;
response[2] = 0x04;
response[3] = (byte) 0xEC;
System.arraycopy(REFERENCE_ID, 0, response, 12, REFERENCE_ID.length);
byte[] receiveTimestamp = toNtpTimestamp(receiveInstant);
byte[] transmitTimestamp = toNtpTimestamp(transmitInstant);
System.arraycopy(receiveTimestamp, 0, response, 16, receiveTimestamp.length);
System.arraycopy(exchange.getClientTransmitTimestamp(), 0, response, 24, exchange.getClientTransmitTimestamp().length);
System.arraycopy(receiveTimestamp, 0, response, 32, receiveTimestamp.length);
System.arraycopy(transmitTimestamp, 0, response, 40, transmitTimestamp.length);
return response;
}
public SntpPushMessage toPushMessage(String deviceIp, Instant computerInstant, Instant deviceInstant) {
long computerTimestampMs = computerInstant.toEpochMilli();
long deviceTimestampMs = deviceInstant.toEpochMilli();
return new SntpPushMessage(
"sntp_time_update",
deviceIp,
formatShanghaiTime(computerInstant),
formatShanghaiTime(deviceInstant),
computerTimestampMs,
deviceTimestampMs,
computerTimestampMs - deviceTimestampMs
);
}
public static byte[] toNtpTimestamp(Instant instant) {
long ntpSeconds = instant.getEpochSecond() + NTP_EPOCH_OFFSET;
long fraction = ((long) instant.getNano() << 32) / 1_000_000_000L;
byte[] bytes = new byte[8];
writeUnsignedInt(bytes, 0, ntpSeconds);
writeUnsignedInt(bytes, 4, fraction);
return bytes;
}
private static Instant fromNtpTimestamp(byte[] bytes) {
long seconds = readUnsignedInt(bytes, 0);
long fraction = readUnsignedInt(bytes, 4);
long epochSeconds = seconds - NTP_EPOCH_OFFSET;
long nanos = ((fraction * 1_000_000_000L) + 0x80000000L) >>> 32;
if (nanos >= 1_000_000_000L) {
epochSeconds += 1;
nanos -= 1_000_000_000L;
}
return Instant.ofEpochSecond(epochSeconds, nanos);
}
private String formatShanghaiTime(Instant instant) {
return LocalDateTime.ofInstant(instant, SHANGHAI_ZONE).toString().replace('T', ' ');
}
private static long readUnsignedInt(byte[] bytes, int offset) {
return ((long) bytes[offset] & 0xFF) << 24
| ((long) bytes[offset + 1] & 0xFF) << 16
| ((long) bytes[offset + 2] & 0xFF) << 8
| ((long) bytes[offset + 3] & 0xFF);
}
private static void writeUnsignedInt(byte[] target, int offset, long value) {
target[offset] = (byte) ((value >>> 24) & 0xFF);
target[offset + 1] = (byte) ((value >>> 16) & 0xFF);
target[offset + 2] = (byte) ((value >>> 8) & 0xFF);
target[offset + 3] = (byte) (value & 0xFF);
}
}

View File

@@ -0,0 +1,25 @@
package com.njcn.gather.detection.sntp;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SntpPushMessage {
private String type = "sntp_time_update";
private String deviceIp;
private String computerTime;
private String deviceTime;
private Long computerTimestampMs;
private Long deviceTimestampMs;
private Long errorMs;
}

View File

@@ -0,0 +1,168 @@
package com.njcn.gather.detection.sntp;
import com.alibaba.fastjson.JSON;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.time.Instant;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
@Service
@RequiredArgsConstructor
public class SntpServerManager {
private final SntpServerProperties sntpServerProperties;
private final SntpPacketService sntpPacketService;
private final AtomicBoolean running = new AtomicBoolean(false);
private final Object lifecycleMonitor = new Object();
private volatile DatagramSocket datagramSocket;
private volatile ExecutorService executorService;
public void start() {
// 使用同步锁和原子变量防止重复启动
synchronized (lifecycleMonitor) {
if (running.get()) {
return;
}
int port = resolvePort();
DatagramSocket socket = createSocket(port);
ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> {
Thread thread = new Thread(runnable, "sntp-server");
thread.setDaemon(true);
return thread;
});
datagramSocket = socket;
executorService = executor;
running.set(true);
executor.submit(this::receiveLoop);
log.info("SNTP服务已启动监听端口: {}", port);
}
}
public void stop() {
synchronized (lifecycleMonitor) {
if (!running.get()) {
return;
}
running.set(false);
closeSocketQuietly(datagramSocket);
datagramSocket = null;
if (executorService != null) {
executorService.shutdownNow();
executorService = null;
}
log.info("SNTP服务已停止");
}
}
public boolean isRunning() {
return running.get();
}
@PreDestroy
public void destroy() {
stop();
}
private void receiveLoop() {
byte[] buffer = new byte[512];
while (running.get()) {
DatagramSocket socket = datagramSocket;
if (socket == null || socket.isClosed()) {
break;
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
handlePacket(socket, packet);
log.info("SNTP服务接收报文: {}", Arrays.toString(packet.getData()));
} catch (SocketException e) {
if (running.get()) {
log.error("SNTP服务接收报文失败", e);
}
break;
} catch (Exception e) {
log.error("SNTP服务处理报文失败", e);
}
}
synchronized (lifecycleMonitor) {
if (running.get()) {
running.set(false);
closeSocketQuietly(datagramSocket);
datagramSocket = null;
if (executorService != null) {
executorService.shutdownNow();
executorService = null;
}
}
}
}
private void handlePacket(DatagramSocket socket, DatagramPacket packet) throws IOException {
Instant receiveInstant = Instant.now(); //T2服务器接收请求时间
byte[] request = Arrays.copyOf(packet.getData(), packet.getLength());
InetSocketAddress clientAddress = new InetSocketAddress(packet.getAddress(), packet.getPort());
SntpExchange exchange = sntpPacketService.parseRequest(request, clientAddress);
if (exchange == null) {
return;
}
Instant transmitInstant = Instant.now(); //T3服务器发送响应时间
byte[] response = sntpPacketService.buildResponse(exchange, receiveInstant, transmitInstant);
DatagramPacket responsePacket = new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
socket.send(responsePacket);
String deviceIp = clientAddress.getAddress().getHostAddress();
// SntpPushMessage pushMessage = sntpPacketService.toPushMessage(deviceIp, transmitInstant, exchange.getDeviceInstant());
SntpPushMessage pushMessage = sntpPacketService.toPushMessage(deviceIp, receiveInstant, exchange.getDeviceInstant());
WebServiceManager.broadcast(JSON.toJSONString(pushMessage));
}
private DatagramSocket createSocket(int port) {
try {
DatagramSocket socket = new DatagramSocket(port);
socket.setReuseAddress(true);
return socket;
} catch (SocketException e) {
throw new BusinessException(CommonResponseEnum.FAIL, "SNTP服务启动失败端口绑定异常");
}
}
private int resolvePort() {
Integer port = sntpServerProperties.getPort();
if (port == null || port < 1 || port > 65535) {
throw new BusinessException(CommonResponseEnum.FAIL, "SNTP服务启动失败端口配置无效");
}
return port;
}
/**
* 关闭UDP Socket
*
* @param socket
*/
private void closeSocketQuietly(DatagramSocket socket) {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}

View File

@@ -0,0 +1,13 @@
package com.njcn.gather.detection.sntp;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "sntp")
public class SntpServerProperties {
private Integer port = 123;
}

View File

@@ -49,7 +49,11 @@ public class CnSocketUtil {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sourceId", param.getSourceName());
socketMsg.setData(jsonObject.toJSONString());
SocketManager.sendMsg(param.getUserPageId() + SOURCE_TAG, JSON.toJSONString(socketMsg));
String sourceKey = param.getUserPageId() + SOURCE_TAG;
if (SocketManager.isChannelActive(sourceKey)) {
SocketManager.markActiveClose(sourceKey);
}
SocketManager.sendMsg(sourceKey, JSON.toJSONString(socketMsg));
WebServiceManager.removePreDetectionParam(param.getUserPageId());
}

View File

@@ -13,6 +13,7 @@ import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -213,4 +214,35 @@ public class FormalTestManager {
* 过载信息如果检测到电压过载overload=1如果检测到电流过载overload=2如果检测到电压&&电流过载overload=3反之overload=4
*/
public static int overload;
/**
* 检测开始时间
*/
public static LocalDateTime checkStartTime;
public static boolean resumeFormalPending;
public static Integer resumeNextSort;
public static Integer resumeBaseFormalCheckTime;
public static LocalDateTime resumeFormalStartTime;
/**
* 数模式 检测类型"1"-"全部检测" , "2"-"不合格项复检"
*/
public static String reCheckType;
public static void clearFormalRuntime() {
stopFlag = false;
hasStopFlag = false;
stopTime = 0;
resumeFormalPending = false;
resumeNextSort = null;
resumeBaseFormalCheckTime = null;
resumeFormalStartTime = null;
realDataXiList.clear();
currentIssue = null;
}
}

View File

@@ -55,6 +55,11 @@ public class SocketManager {
*/
private static final Map<String, NioEventLoopGroup> socketGroup = new ConcurrentHashMap<>();
/**
* 主动关闭中的连接。用于区分业务主动 close 和对端异常断线。
*/
private static final Map<String, Boolean> activeClosingUsers = new ConcurrentHashMap<>();
public static void addUser(String userId, Channel channel) {
socketSessions.put(userId, channel);
}
@@ -65,20 +70,31 @@ public class SocketManager {
public static void removeUser(String userId) {
Channel channel = socketSessions.get(userId);
removeMapping(userId, false);
if (ObjectUtil.isNotNull(channel)) {
try {
markActiveClose(userId);
channel.close().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
NioEventLoopGroup eventExecutors = socketGroup.get(userId);
if (ObjectUtil.isNotNull(eventExecutors)) {
eventExecutors.shutdownGracefully();
System.out.println(userId + "__" + channel.id() + "关闭了客户端");
}
System.out.println(userId + "__" + channel.id() + "关闭了客户端");
}
}
public static void removeMapping(String userId) {
removeMapping(userId, true);
}
private static void removeMapping(String userId, boolean clearActiveClose) {
socketSessions.remove(userId);
socketGroup.remove(userId);
NioEventLoopGroup eventExecutors = socketGroup.remove(userId);
if (clearActiveClose) {
consumeActiveClose(userId);
}
if (ObjectUtil.isNotNull(eventExecutors)) {
eventExecutors.shutdownGracefully();
}
}
public static Channel getChannelByUserId(String userId) {
@@ -89,6 +105,20 @@ public class SocketManager {
return socketGroup.get(userId);
}
public static void markActiveClose(String userId) {
if (StrUtil.isNotBlank(userId)) {
activeClosingUsers.put(userId, Boolean.TRUE);
}
}
public static boolean consumeActiveClose(String userId) {
return StrUtil.isNotBlank(userId) && activeClosingUsers.remove(userId) != null;
}
public static boolean isActiveClosing(String userId) {
return StrUtil.isNotBlank(userId) && activeClosingUsers.containsKey(userId);
}
public static void sendMsg(String userId, String msg) {
Channel channel = socketSessions.get(userId);
if (ObjectUtil.isNotNull(channel)) {
@@ -313,6 +343,11 @@ public class SocketManager {
return targetMap.get(scriptType);
}
public static void clearFormalRuntime() {
sourceIssueList.clear();
targetMap.clear();
valueTypeMap.clear();
clockMap.clear();
}
}

View File

@@ -15,8 +15,8 @@ import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.detection.util.socket.SocketManager;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.system.pojo.enums.DicDataEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@@ -55,19 +55,19 @@ import java.util.stream.Collectors;
public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
/**
* 闪检测超时时间20分钟1300秒
* 闪检测超时时间20分钟+100秒1300秒
*/
private static final long FLICKER_TIMEOUT = 1300L;
private static final long SHORT_FLICKER_TIMEOUT = 1300L;
/**
* 统计数据检测超时时间3分钟180秒
* 统计数据检测超时时间3分钟+100秒190秒
*/
private static final long STATISTICS_TIMEOUT = 180L;
private static final long STATISTICS_TIMEOUT = 190L;
/**
* 实时数据检测超时时间1分钟60秒
* 实时数据检测超时时间1分钟*3
*/
private static final long REALTIME_TIMEOUT = 60L;
private static final long REALTIME_TIMEOUT = 60 * 3L;
/**
* 暂停操作超时时间10分钟600秒
@@ -115,7 +115,11 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.warn("设备通讯客户端断线");
ctx.close();
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.DEV_TAG);
String key = param.getUserPageId() + CnSocketUtil.DEV_TAG;
if (SocketManager.consumeActiveClose(key)) {
return;
}
SocketManager.removeUser(key);
CnSocketUtil.quitSendSource(param);
// 设备主动断开 → 本次检测视为结束,释放检测锁
DetectionLockManager.getInstance()
@@ -301,10 +305,10 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
String type = sourceIssue.getType();
// 根据不同检测类型使用不同的超时阈值
if (DicDataEnum.F.getCode().equals(type)) {
if (PowerIndexEnum.F.getKey().equals(type)) {
// 闪变检测需要更长时间20分钟超时
return currentTime >= FLICKER_TIMEOUT;
} else if (DicDataEnum.VOLTAGE.getCode().equals(type) || DicDataEnum.HP.getCode().equals(type)) {
return currentTime >= SHORT_FLICKER_TIMEOUT;
} else if (PowerIndexEnum.VOLTAGE.getKey().equals(type) || PowerIndexEnum.HP.getKey().equals(type)) {
// 统计数据类型电压、谐波中等时间3分钟超时
return currentTime >= STATISTICS_TIMEOUT;
} else {

View File

@@ -70,7 +70,12 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
ctx.close();
// 从Socket管理器中移除用户通道映射
if (webUser != null && StrUtil.isNotBlank(userId)) {
SocketManager.removeUser(userId + CnSocketUtil.SOURCE_TAG);
String key = userId + CnSocketUtil.SOURCE_TAG;
if (SocketManager.isActiveClosing(key)) {
SocketManager.removeMapping(key);
return;
}
SocketManager.removeUser(key);
// 源端主动断开 → 本次检测视为结束,释放检测锁
DetectionLockManager.getInstance()
.releaseIfMatchPage(userId, "SOURCE_CHANNEL_INACTIVE");
@@ -90,7 +95,7 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
}
String userId = webUser.getUserPageId();
log.debug("源设备接收服务端数据, userId: {}, message: {}", userId, msg);
log.info("source接收server端数据, userId: {}, message: {}", userId, msg);
try {
// 委托给专门的响应处理服务处理业务逻辑
@@ -120,6 +125,11 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
String userId = webUser != null ? webUser.getUserPageId() : "unknown";
String channelId = ctx.channel().id().toString();
if (StrUtil.isNotBlank(userId) && SocketManager.isActiveClosing(userId + CnSocketUtil.SOURCE_TAG)) {
log.debug("ignore source exception during active close, channelId: {}, userId: {}", channelId, userId);
ctx.close();
return;
}
// 根据异常类型进行分类处理和日志记录
if (cause instanceof ConnectException) {

View File

@@ -87,6 +87,16 @@ public class WebServiceManager {
return userSessions.remove(userId);
}
/**
* 仅当当前会话仍绑定到指定通道时才移除,避免旧连接误删新连接映射。
*/
public static boolean removeByUserId(String userId, Channel channel) {
if (userId == null || channel == null) {
return false;
}
return userSessions.remove(userId, channel);
}
/**
* 根据channelId移除会话兼容老版本
* 时间复杂度O(n)建议使用removeByUserId替代
@@ -143,6 +153,19 @@ public class WebServiceManager {
}
}
public static void broadcast(String msg) {
for (Map.Entry<String, Channel> entry : userSessions.entrySet()) {
String userId = entry.getKey();
Channel channel = entry.getValue();
if (Objects.nonNull(channel) && channel.isActive()) {
channel.writeAndFlush(new TextWebSocketFrame(msg));
} else {
log.error("WebSocket broadcast failed, disconnected user, time: {}, userId: {}", LocalDateTime.now(), userId);
WebSocketHandler.cleanupSocketResources(userId);
}
}
}
/**
* 存储检测参数基于用户ID
* 支持多用户并发检测,每个用户的检测参数独立存储
@@ -337,4 +360,4 @@ public class WebServiceManager {
.releaseIfMatchPage(userId, "WS_ERROR_PUSH:" + errorType.name());
}
}

View File

@@ -111,7 +111,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
public void handlerRemoved(ChannelHandlerContext ctx) {
log.info("webSocket客户端退出channelId: {}, userId: {}", ctx.channel().id(), this.userId);
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
} else {
// 备用方案如果userId为空使用传统方法
WebServiceManager.removeChannel(ctx.channel().id().toString());
@@ -168,7 +168,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
log.error("客户端心跳检测空闲次数超过{}次关闭连接channelId: {}, userId: {}", MAX_HEARTBEAT_MISS_COUNT, ctx.channel().id(), this.userId);
ctx.channel().close();
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
} else {
WebServiceManager.removeChannel(ctx.channel().id().toString());
}
@@ -326,7 +326,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
// 清理会话
if (this.userId != null) {
WebServiceManager.removeByUserId(this.userId);
WebServiceManager.removeByUserId(this.userId, ctx.channel());
log.debug("已清理WebSocket会话userId: {}, channelId: {}", this.userId, channelId);
} else {
WebServiceManager.removeChannel(channelId);
@@ -427,4 +427,4 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
}
// ================================ URL解析工具已移至WebSocketPreprocessor ================================
}
}

View File

@@ -9,6 +9,7 @@ import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
import com.njcn.gather.device.pojo.param.PqDevParam;
import com.njcn.gather.device.pojo.vo.PqDevVO;
import com.njcn.gather.device.service.IPqDevService;
@@ -22,6 +23,7 @@ import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -68,10 +70,10 @@ public class PqDevController extends BaseController {
}
@OperateInfo(operateType = OperateType.ADD)
@PostMapping("/add")
@PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation("新增被检设备")
@ApiImplicitParam(name = "pqDevParam", value = "被检设备", required = true)
public HttpResult<Boolean> add(@RequestBody @Validated PqDevParam pqDevParam) {
public HttpResult<Boolean> add(@ModelAttribute @Validated PqDevParam pqDevParam) {
String methodDescribe = getMethodDescribe("add");
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, pqDevParam);
boolean result = pqDevService.addPqDev(pqDevParam);
@@ -83,10 +85,10 @@ public class PqDevController extends BaseController {
}
@OperateInfo(operateType = OperateType.UPDATE)
@PostMapping("/update")
@PostMapping(value = "/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation("修改被检设备")
@ApiImplicitParam(name = "updateParam", value = "被检设备", required = true)
public HttpResult<Boolean> update(@RequestBody @Validated PqDevParam.UpdateParam updateParam) {
public HttpResult<Boolean> update(@ModelAttribute @Validated PqDevParam.UpdateParam updateParam) {
String methodDescribe = getMethodDescribe("update");
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, updateParam);
boolean result = pqDevService.updatePqDev(updateParam);
@@ -97,6 +99,14 @@ public class PqDevController extends BaseController {
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
@GetMapping("/image/download")
@ApiOperation("下载设备图片")
@ApiImplicitParam(name = "id", value = "被检设备id", required = true)
public void downloadImage(@RequestParam("id") String id, HttpServletResponse response) {
pqDevService.downloadImage(id, response);
}
@OperateInfo(operateType = OperateType.DELETE)
@PostMapping("/delete")
@ApiOperation("删除被检设备")
@@ -170,23 +180,14 @@ public class PqDevController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPLOAD)
@PostMapping(value = "/ttt")
@ApiOperation("批量导入被检设备")
@ApiImplicitParams({
@ApiImplicitParam(name = "file", value = "被检设备数据文件", required = true),
@ApiImplicitParam(name = "patternId", value = "模式id", required = true)
})
public HttpResult ttt(@RequestParam("file") MultipartFile file, @RequestParam("patternId") String patternId, @RequestParam("planId") String planId, @RequestParam(value = "cover", defaultValue = "0") Integer cover, HttpServletResponse response) {
String methodDescribe = getMethodDescribe("ttt");
LogUtil.njcnDebug(log, "{},上传文件为:{}", methodDescribe, file.getOriginalFilename());
boolean fileType = FileUtil.judgeFileIsExcel(file.getOriginalFilename());
if (!fileType) {
throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR);
}
if ("null".equals(planId)) {
planId = null;
}
return pqDevService.importDev(file, patternId, planId, response, cover);
@OperateInfo
@GetMapping("/getDataCheckRes")
@ApiOperation("获取接入测试-数据校验结果")
@ApiImplicitParam(name = "monitorId", value = "监测点id", required = true)
public HttpResult<DataCheckResDTO> getDataCheckRes(@RequestParam("monitorId") String monitorId) {
String methodDescribe = getMethodDescribe("getDataCheckRes");
DataCheckResDTO dataCheckRes = pqDevService.getDataCheckRes(monitorId);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dataCheckRes, methodDescribe);
}
}

View File

@@ -86,8 +86,45 @@
WHERE id = #{planId}
</select>
<sql id="DevColumnsNoImage">
dev.Id,
dev.Name,
dev.Pattern,
dev.Dev_Type,
dev.Manufacturer,
dev.Create_Date,
dev.Create_Id,
dev.Hardware_Version,
dev.Software_Version,
dev.Protocol,
dev.IP,
dev.Port,
dev.Encryption_Flag,
dev.Series,
dev.Dev_Key,
dev.Sample_Id,
dev.Arrived_Date,
dev.City_Name,
dev.Gd_Name,
dev.Sub_Name,
dev.Report_Path,
dev.Plan_Id,
dev.Factor_Flag,
dev.Preinvestment_Plan,
dev.Delegate,
dev.Inspect_Channel,
dev.Inspect_Date,
dev.Harm_Sys_Id,
dev.Import_Flag,
dev.State,
dev.Create_By,
dev.Create_Time,
dev.Update_By,
dev.Update_Time
</sql>
<select id="selectByQueryParam" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
SELECT dev.*,dev_sub.* FROM pq_dev dev
SELECT <include refid="DevColumnsNoImage"/>, dev_sub.* FROM pq_dev dev
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
<where>
dev.state = 1
@@ -124,7 +161,7 @@
</select>
<select id="listByDevIds" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
SELECT dev.*, dev_sub.*
SELECT <include refid="DevColumnsNoImage"/>, dev_sub.*
FROM pq_dev dev
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
WHERE dev.state = 1

View File

@@ -0,0 +1,8 @@
package com.njcn.gather.device.pojo.dto;
/**
* @author caozehui
* @data 2026-06-15
*/
public class DataCheckResDTO {
}

View File

@@ -12,7 +12,7 @@ public enum CheckStateEnum {
CHECKING("检测中", 1),
CHECKED("检测完成", 2),
/**
* 检测计划没有状态,只有未检、检测中、检测完成三种状态。被检设备有这种状态
* 检测计划没有归档状态,只有未检、检测中、检测完成三种状态。被检设备有归档状态
*/
DOCUMENTED("归档", 3);

View File

@@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Range;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.*;
@@ -136,6 +137,9 @@ public class PqDevParam {
@ApiModelProperty("是否为导入设备")
private Integer importFlag;
@ApiModelProperty("设备图片")
private MultipartFile image;
/**
* 更新操作实体
*/

View File

@@ -3,6 +3,7 @@ package com.njcn.gather.device.pojo.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@@ -184,6 +185,9 @@ public class PqDev extends BaseEntity implements Serializable {
*/
private Integer importFlag;
@JsonIgnore
private byte[] image;
/**
* 状态0-删除 1-正常
*/

View File

@@ -56,10 +56,16 @@ public class PqDevSub {
private String checkBy;
/**
* 检测时间
* 检测开始时间
*/
@TableField("Check_Time")
private LocalDateTime checkTime;
@TableField("Check_Start_Time")
private LocalDateTime checkStartTime;
/**
* 检测结束时间
*/
@TableField("Check_End_Time")
private LocalDateTime checkEndTime;
/**
* 预检测耗时

View File

@@ -1,5 +1,6 @@
package com.njcn.gather.device.pojo.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.monitor.pojo.po.PqMonitor;
import lombok.Data;
@@ -73,9 +74,14 @@ public class PqDevVO extends PqDev {
private String checkBy;
/**
* 检测时间
* 检测开始时间
*/
private LocalDateTime checkTime;
private LocalDateTime checkStartTime;
/**
* 检测结束时间
*/
private LocalDateTime checkEndTime;
/**
* 预检测耗时
@@ -116,4 +122,10 @@ public class PqDevVO extends PqDev {
* 检测点结果
*/
private List<Integer> monitorResults;
private Boolean hasImage;
private String imageBase64;
private String imageContentType;
}

View File

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.common.pojo.poi.PullDown;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
import com.njcn.gather.device.pojo.enums.TimeCheckResultEnum;
import com.njcn.gather.device.pojo.param.PqDevParam;
import com.njcn.gather.device.pojo.po.PqDev;
@@ -95,6 +96,14 @@ public interface IPqDevService extends IService<PqDev> {
*/
PqDevVO getPqDevById(String id);
/**
* 下载设备图片
*
* @param id 设备id
* @param response 响应
*/
void downloadImage(String id, HttpServletResponse response);
/**
* 获取装置信息和装置下监测点信息
*
@@ -120,6 +129,13 @@ public interface IPqDevService extends IService<PqDev> {
*/
boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum);
/**
* 新一轮正式检测真正开始前,仅清理原检测中设备的暂存耗时,并把本次设备置为检测中。
*/
void clearFormalProgressForNewRun(List<String> devIds);
Integer getMinFormalCheckTime(List<String> devIds);
/**
* 比对式-修改设备状态
*
@@ -289,4 +305,11 @@ public interface IPqDevService extends IService<PqDev> {
* @return
*/
List<ContrastDevExcel> getExportContrastDevData(List<PqDevVO> pqDevVOList);
/**
* 获取接入测试-数据校验结果
* @param monitorId
* @return
*/
DataCheckResDTO getDataCheckRes(String monitorId);
}

View File

@@ -3,10 +3,14 @@ package com.njcn.gather.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.device.pojo.po.PqDevSub;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author caozehui
* @date 2025-07-04
*/
public interface IPqDevSubService extends IService<PqDevSub> {
LocalDateTime resolveBatchMaxCheckEndTime(List<String> devIds);
}

View File

@@ -5,6 +5,7 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
@@ -26,7 +27,10 @@ import com.njcn.common.pojo.poi.PullDown;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.EncryptionUtil;
import com.njcn.db.mybatisplus.constant.DbConstant;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.device.mapper.PqDevMapper;
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
import com.njcn.gather.device.pojo.enums.*;
import com.njcn.gather.device.pojo.param.PqDevParam;
import com.njcn.gather.device.pojo.po.PqDev;
@@ -34,11 +38,12 @@ import com.njcn.gather.device.pojo.po.PqDevSub;
import com.njcn.gather.device.pojo.vo.*;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.device.service.IPqDevSubService;
import com.njcn.gather.device.util.PqDevImageSupport;
import com.njcn.gather.monitor.pojo.po.PqMonitor;
import com.njcn.gather.monitor.pojo.vo.PqMonitorExcel;
import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.mapper.AdPlanMapper;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
@@ -54,6 +59,7 @@ import com.njcn.gather.type.pojo.po.DevType;
import com.njcn.gather.type.service.IDevTypeService;
import com.njcn.gather.user.user.pojo.po.SysUser;
import com.njcn.gather.user.user.service.ISysUserService;
import com.njcn.http.util.RestTemplateUtil;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.ExcelUtil;
import com.njcn.web.utils.HttpResultUtil;
@@ -67,6 +73,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
@@ -92,6 +99,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
private final IPqDevSubService pqDevSubService;
private final AdPlanMapper adPlanMapper;
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
private final RestTemplateUtil restTemplateUtil;
@Override
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
@@ -133,7 +141,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.checkRepeat(pqDevParam, false);
PqDev pqDev = new PqDev();
BeanUtil.copyProperties(pqDevParam, pqDev);
BeanUtil.copyProperties(pqDevParam, pqDev, CopyOptions.create().setIgnoreProperties("image"));
fillImage(pqDev, pqDevParam);
String currrentScene = sysTestConfigService.getCurrrentScene();
this.checkParams(pqDev, currrentScene);
@@ -164,6 +173,19 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return this.save(pqDev);
}
private void fillImage(PqDev pqDev, PqDevParam pqDevParam) {
try {
byte[] image = PqDevImageSupport.processUpload(pqDevParam.getImage());
if (image != null) {
pqDev.setImage(image);
}
} catch (IllegalArgumentException e) {
throw new BusinessException(CommonResponseEnum.FAIL, e.getMessage());
} catch (IOException e) {
throw new BusinessException(CommonResponseEnum.FAIL, "图片处理失败");
}
}
/**
* 校验参数
*
@@ -206,7 +228,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.checkRepeat(updateParam, true);
PqDev pqDev = new PqDev();
BeanUtil.copyProperties(updateParam, pqDev);
BeanUtil.copyProperties(updateParam, pqDev, CopyOptions.create().setIgnoreProperties("image"));
fillImage(pqDev, updateParam);
String currrentScene = sysTestConfigService.getCurrrentScene();
this.checkParams(pqDev, currrentScene);
@@ -273,6 +296,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
public List<Map<String, Object>> listUnbound(String pattern) {
List<PqDev> pqDevList = this.lambdaQuery()
.select(PqDev::getId, PqDev::getName, PqDev::getDevType, PqDev::getManufacturer,
PqDev::getCityName, PqDev::getGdName, PqDev::getSubName)
.eq(PqDev::getPattern, pattern)
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
.isNull(PqDev::getPlanId)
@@ -342,24 +367,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
List<String> notUnchecked = list.stream().filter(x -> !CheckStateEnum.UNCHECKED.getValue().equals(x.getCheckState())).map(PqDevSub::getDevId).distinct().collect(Collectors.toList());
if (CollUtil.isNotEmpty(notUnchecked)) {
List<String> unchecked = list.stream().filter(x -> CheckStateEnum.UNCHECKED.getValue().equals(x.getCheckState())).map(PqDevSub::getDevId).distinct().collect(Collectors.toList());
//计划未检测
if (CollUtil.isNotEmpty(unchecked)) {
return CheckStateEnum.CHECKING.getValue();
}
//计划检测中
List<String> checking = list.stream().filter(x -> x.getCheckState().equals(CheckStateEnum.CHECKED.getValue()) &&
!CheckStateEnum.DOCUMENTED.getValue().equals(x.getCheckState())
).map(PqDevSub::getDevId).distinct().collect(Collectors.toList());
if (checking.size() == notUnchecked.size()) {
return CheckStateEnum.CHECKING.getValue();
}
//检测完成
List<String> checked = list.stream().filter(x -> CheckStateEnum.DOCUMENTED.getValue().equals(x.getCheckState())).map(PqDevSub::getDevId).distinct().collect(Collectors.toList());
if (checked.size() == notUnchecked.size()) {
return CheckStateEnum.CHECKED.getValue();
}
boolean allArchived = list.stream().allMatch(x -> x.getCheckState() != null && x.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
return allArchived ? CheckStateEnum.CHECKED.getValue() : CheckStateEnum.CHECKING.getValue();
}
}
return CheckStateEnum.UNCHECKED.getValue();
@@ -387,6 +396,10 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
public PqDevVO getPqDevById(String id) {
PqDevVO pqDevVO = this.baseMapper.selectByDevId(id);
if (ObjectUtil.isNull(pqDevVO)) {
return null;
}
setImageEchoFields(pqDevVO);
if (StrUtil.isNotBlank(pqDevVO.getSeries())) {
pqDevVO.setSeries(EncryptionUtil.decoderString(1, pqDevVO.getSeries()));
}
@@ -415,6 +428,37 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return pqDevVO;
}
@Override
public void downloadImage(String id, HttpServletResponse response) {
PqDev pqDev = this.getById(id);
if (ObjectUtil.isNull(pqDev) || pqDev.getImage() == null || pqDev.getImage().length == 0) {
throw new BusinessException(CommonResponseEnum.FAIL, "设备图片不存在");
}
String contentType = PqDevImageSupport.detectContentType(pqDev.getImage());
String filename = "device-image-" + id + "." + PqDevImageSupport.getExtension(contentType);
response.setContentType(contentType);
response.setContentLength(pqDev.getImage().length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
try {
response.getOutputStream().write(pqDev.getImage());
response.flushBuffer();
} catch (IOException e) {
throw new BusinessException(CommonResponseEnum.FAIL, "设备图片下载失败");
}
}
private void setImageEchoFields(PqDevVO pqDevVO) {
try {
PqDevImageSupport.ImageEchoPayload payload = PqDevImageSupport.buildEchoPayload(pqDevVO.getImage());
pqDevVO.setHasImage(payload.isHasImage());
pqDevVO.setImageBase64(payload.getImageBase64());
pqDevVO.setImageContentType(payload.getImageContentType());
pqDevVO.setImage(null);
} catch (IllegalArgumentException e) {
throw new BusinessException(CommonResponseEnum.FAIL, e.getMessage());
}
}
/**
* 获取查询条件wrapper
@@ -424,6 +468,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
*/
private Wrapper getQueryWrapper(PqDevParam.QueryParam queryParam) {
QueryWrapper<PqDev> queryWrapper = new QueryWrapper<>();
queryWrapper.select("pq_dev.Id");
if (ObjectUtil.isNotNull(queryParam)) {
queryWrapper
.like(StrUtil.isNotBlank(queryParam.getName()), "pq_dev.name", queryParam.getName())
@@ -486,6 +531,45 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return preDetections;
}
@Override
public void clearFormalProgressForNewRun(List<String> devIds) {
if (CollUtil.isEmpty(devIds)) {
return;
}
List<PqDevSub> devSubs = pqDevSubService.lambdaQuery()
.in(PqDevSub::getDevId, devIds)
.list();
List<String> resetFormalCheckIds = devSubs.stream()
.filter(dev -> CheckStateEnum.CHECKING.getValue().equals(dev.getCheckState()))
.map(PqDevSub::getDevId)
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(resetFormalCheckIds)) {
pqDevSubService.lambdaUpdate()
.set(PqDevSub::getFormalCheckTime, 0)
.in(PqDevSub::getDevId, resetFormalCheckIds)
.update();
}
pqDevSubService.lambdaUpdate()
.set(PqDevSub::getCheckState, CheckStateEnum.CHECKING.getValue())
.in(PqDevSub::getDevId, devIds)
.update();
}
@Override
public Integer getMinFormalCheckTime(List<String> devIds) {
if (CollUtil.isEmpty(devIds)) {
return 0;
}
return pqDevSubService.lambdaQuery()
.in(PqDevSub::getDevId, devIds)
.list()
.stream()
.map(PqDevSub::getFormalCheckTime)
.filter(Objects::nonNull)
.min(Integer::compareTo)
.orElse(0);
}
@Override
public boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum) {
@@ -505,7 +589,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
LambdaUpdateWrapper<PqDevSub> wrapper = new LambdaUpdateWrapper<PqDevSub>()
.set(PqDevSub::getCheckResult, result.get(pqDevVo.getId()))
.set(StrUtil.isNotBlank(userId), PqDevSub::getCheckBy, userId)
.set(PqDevSub::getCheckTime, LocalDateTime.now())
.set(updateCheckNum && SourceOperateCodeEnum.ALL_TEST.getValue().equals(FormalTestManager.reCheckType), PqDevSub::getCheckEndTime, LocalDateTime.now())
.set(updateCheckNum && SourceOperateCodeEnum.ALL_TEST.getValue().equals(FormalTestManager.reCheckType) && ObjectUtil.isNotNull(FormalTestManager.checkStartTime), PqDevSub::getCheckStartTime, FormalTestManager.checkStartTime)
.eq(PqDevSub::getDevId, pqDevVo.getId());
String currrentScene = sysTestConfigService.getCurrrentScene();
if (SceneEnum.PROVINCE_PLATFORM.getValue().equals(currrentScene)) {
@@ -528,6 +613,21 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
}
wrapper.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
}
if (ObjectUtil.isNotNull(FormalTestManager.resumeBaseFormalCheckTime)
&& ObjectUtil.isNotNull(FormalTestManager.resumeFormalStartTime)) {
int elapsedSeconds = (int) java.time.Duration.between(
FormalTestManager.resumeFormalStartTime,
LocalDateTime.now()
).getSeconds();
wrapper.set(PqDevSub::getFormalCheckTime,
FormalTestManager.resumeBaseFormalCheckTime + Math.max(elapsedSeconds, 0));
} else if (updateCheckNum && ObjectUtil.isNotNull(FormalTestManager.checkStartTime)) {
int elapsedSeconds = (int) java.time.Duration.between(
FormalTestManager.checkStartTime,
LocalDateTime.now()
).getSeconds();
wrapper.set(PqDevSub::getFormalCheckTime, Math.max(elapsedSeconds, 0));
}
wrapper.set(PqDevSub::getRecheckNum, i)
.set(PqDevSub::getCheckState, checkState);
pqDevSubService.update(wrapper);
@@ -546,19 +646,14 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.baseMapper.updatePlanCheckResult(pqDevVo.getPlanId(), CheckResultEnum.ACCORD.getValue());
}
set = pqDevVOList.stream().map(PqDevVO::getCheckState).collect(Collectors.toSet());
if (set.contains(CheckStateEnum.UNCHECKED.getValue())) {
this.baseMapper.updatePlanTestState(pqDevVo.getPlanId(), CheckStateEnum.CHECKING.getValue());
boolean allUnchecked = pqDevVOList.stream().allMatch(obj -> CheckStateEnum.UNCHECKED.getValue().equals(obj.getCheckState()));
boolean allArchived = pqDevVOList.stream().allMatch(obj -> obj.getCheckState() != null && obj.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allUnchecked) {
this.baseMapper.updatePlanTestState(pqDevVo.getPlanId(), CheckStateEnum.UNCHECKED.getValue());
} else if (allArchived) {
this.baseMapper.updatePlanTestState(pqDevVo.getPlanId(), CheckStateEnum.CHECKED.getValue());
} else {
if (checkState.equals(CheckStateEnum.DOCUMENTED.getValue())) {
long count = pqDevVOList.stream().filter(obj -> !CheckStateEnum.DOCUMENTED.getValue().equals(obj.getCheckState())).count();
if (count == 0) {
// 如果非归档状态的设备数量为0则更新计划已完成
this.baseMapper.finishPlan(pqDevVo.getPlanId());
}
} else {
this.baseMapper.updatePlanTestState(pqDevVo.getPlanId(), CheckStateEnum.CHECKING.getValue());
}
this.baseMapper.updatePlanTestState(pqDevVo.getPlanId(), CheckStateEnum.CHECKING.getValue());
}
}
}
@@ -583,13 +678,23 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
SysUser user = userService.getById(userId);
// 查询当前设备的检测时间
PqDevSub currentDevSub = pqDevSubService.lambdaQuery()
.eq(PqDevSub::getDevId, devId)
.one();
LambdaUpdateChainWrapper<PqDevSub> w = pqDevSubService.lambdaUpdate()
.set(PqDevSub::getCheckState, checkState)
.set(PqDevSub::getCheckResult, checkResult)
.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue())
.set(PqDevSub::getCheckTime, LocalDateTime.now())
.eq(PqDevSub::getDevId, devId);
// 只有当checkTime为空时才设置为当前时间
if (currentDevSub != null && currentDevSub.getCheckEndTime() == null) {
w.set(PqDevSub::getCheckEndTime, LocalDateTime.now());
w.set(ObjectUtil.isNotNull(FormalTestManager.checkStartTime), PqDevSub::getCheckStartTime, currentDevSub.getCheckStartTime());
}
if (ObjectUtil.isNotNull(user)) {
w.set(PqDevSub::getCheckBy, user.getName());
}
@@ -605,7 +710,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
List<PqDevVO> pqDevVOList = this.baseMapper.selectByQueryParam(param);
if (CollUtil.isNotEmpty(pqDevVOList)) {
Set<Integer> set = pqDevVOList.stream().filter(obj -> CheckStateEnum.CHECKED.getValue().equals(obj.getCheckState()) || CheckStateEnum.DOCUMENTED.getValue().equals(obj.getCheckState())).map(PqDevVO::getCheckResult).collect(Collectors.toSet());
Set<Integer> set = pqDevVOList.stream().filter(obj -> obj.getCheckState() != null && obj.getCheckState() >= CheckStateEnum.CHECKED.getValue()).map(PqDevVO::getCheckResult).collect(Collectors.toSet());
if (checkState == CheckStateEnum.CHECKED.getValue()) {
set.add(checkResult);
}
@@ -622,20 +727,22 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
}
set = pqDevVOList.stream().map(PqDevVO::getCheckState).collect(Collectors.toSet());
if (set.contains(CheckStateEnum.UNCHECKED.getValue())) {
this.baseMapper.updatePlanTestState(planId, CheckStateEnum.CHECKING.getValue());
} else if (set.contains(CheckStateEnum.CHECKING.getValue())) {
this.baseMapper.updatePlanTestState(planId, CheckStateEnum.CHECKING.getValue());
} else {
boolean allUnchecked = pqDevVOList.stream().allMatch(obj -> CheckStateEnum.UNCHECKED.getValue().equals(obj.getCheckState()));
boolean allArchived = pqDevVOList.stream().allMatch(obj -> obj.getCheckState() != null && obj.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allUnchecked) {
this.baseMapper.updatePlanTestState(planId, CheckStateEnum.UNCHECKED.getValue());
} else if (allArchived) {
this.baseMapper.updatePlanTestState(planId, CheckStateEnum.CHECKED.getValue());
} else {
this.baseMapper.updatePlanTestState(planId, CheckStateEnum.CHECKING.getValue());
}
}
}
private void saveCheckHistory(PqDevVO pqDevVo, Integer recheckNum, Integer checkState, String userId) {
if (ObjectUtil.isNull(pqDevVo)
|| (!CheckStateEnum.CHECKED.getValue().equals(checkState) && !CheckStateEnum.DOCUMENTED.getValue().equals(checkState))) {
|| checkState == null
|| checkState < CheckStateEnum.CHECKED.getValue()) {
return;
}
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
@@ -644,14 +751,15 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
}
pqDevVo.setRecheckNum(recheckNum);
pqDevVo.setCheckBy(userId);
pqDevVo.setCheckTime(LocalDateTime.now());
pqDevVo.setCheckEndTime(LocalDateTime.now());
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
}
private void saveCheckHistory(String devId, String userId) {
PqDevVO pqDevVo = this.baseMapper.selectByDevId(devId);
if (ObjectUtil.isNull(pqDevVo)
|| (!CheckStateEnum.CHECKED.getValue().equals(pqDevVo.getCheckState()) && !CheckStateEnum.DOCUMENTED.getValue().equals(pqDevVo.getCheckState()))) {
|| pqDevVo.getCheckState() == null
|| pqDevVo.getCheckState() < CheckStateEnum.CHECKED.getValue()) {
return;
}
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
@@ -1643,7 +1751,10 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
public Map<String, List<String>> listSelectOptions(String pattern) {
List<PqDev> pqDevList = this.lambdaQuery().eq(PqDev::getPattern, pattern)
List<PqDev> pqDevList = this.lambdaQuery()
.select(PqDev::getCityName, PqDev::getGdName, PqDev::getSubName,
PqDev::getHardwareVersion, PqDev::getSoftwareVersion)
.eq(PqDev::getPattern, pattern)
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
.list();
String[] devKeyArray = new String[]{"cityName", "gdName", "subName", "hardwareVersion", "softwareVersion"};
@@ -1667,4 +1778,11 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
}
return result;
}
@Override
public DataCheckResDTO getDataCheckRes(String monitorId) {
// restTemplateUtil.postJson();
DataCheckResDTO dataCheckResDTO = restTemplateUtil.postJson("http://localhost:8080/api/v1/dataCheck/getDataCheckRes", monitorId, DataCheckResDTO.class);
return dataCheckResDTO;
}
}

View File

@@ -1,13 +1,20 @@
package com.njcn.gather.device.service.impl;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.device.pojo.po.PqDevSub;
import com.njcn.gather.device.mapper.PqDevSubMapper;
import com.njcn.gather.device.pojo.po.PqDevSub;
import com.njcn.gather.device.service.IPqDevSubService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/**
* @author caozehui
* @date 2025-07-04
@@ -16,5 +23,19 @@ import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class PqDevSubServiceImpl extends ServiceImpl<PqDevSubMapper, PqDevSub> implements IPqDevSubService {
@Override
public LocalDateTime resolveBatchMaxCheckEndTime(List<String> devIds) {
if (CollUtil.isEmpty(devIds)) {
return null;
}
return this.list(new LambdaQueryWrapper<PqDevSub>()
.in(PqDevSub::getDevId, devIds)
.isNotNull(PqDevSub::getCheckEndTime))
.stream()
.map(PqDevSub::getCheckEndTime)
.filter(Objects::nonNull)
.max(Comparator.naturalOrder())
.orElse(null);
}
}

View File

@@ -0,0 +1,181 @@
package com.njcn.gather.device.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Iterator;
import java.util.Locale;
public final class PqDevImageSupport {
private static final long MAX_FILE_SIZE = 10L * 1024L * 1024L;
private static final int MAX_EDGE = 1600;
private static final float JPEG_QUALITY = 0.82f;
private PqDevImageSupport() {
}
public static ImageEchoPayload buildEchoPayload(byte[] imageBytes) {
if (imageBytes == null || imageBytes.length == 0) {
return new ImageEchoPayload(false, null, null);
}
return new ImageEchoPayload(true, Base64.getEncoder().encodeToString(imageBytes), detectContentType(imageBytes));
}
public static String detectContentType(byte[] imageBytes) {
if (imageBytes == null || imageBytes.length < 4) {
throw new IllegalArgumentException("图片内容无效");
}
if (isPng(imageBytes)) {
return "image/png";
}
if (isJpeg(imageBytes)) {
return "image/jpeg";
}
throw new IllegalArgumentException("仅支持 JPG、PNG 图片");
}
public static byte[] processUpload(MultipartFile image) throws IOException {
if (image == null || image.isEmpty()) {
return null;
}
if (image.getSize() > MAX_FILE_SIZE) {
throw new IllegalArgumentException("图片大小不能超过 10MB");
}
String normalizedName = normalize(image.getOriginalFilename());
String normalizedContentType = normalize(image.getContentType());
boolean allowedType = normalizedContentType.equals("image/jpeg")
|| normalizedContentType.equals("image/png")
|| normalizedName.endsWith(".jpg")
|| normalizedName.endsWith(".jpeg")
|| normalizedName.endsWith(".png");
if (!allowedType) {
throw new IllegalArgumentException("仅支持 JPG、PNG 图片");
}
byte[] originalBytes = image.getBytes();
String contentType = detectContentType(originalBytes);
BufferedImage source;
try (InputStream inputStream = image.getInputStream()) {
source = ImageIO.read(inputStream);
}
if (source == null) {
throw new IllegalArgumentException("图片内容无效");
}
BufferedImage target = scaleIfNeeded(source);
if ("image/png".equals(contentType)) {
return writePng(target);
}
return writeJpeg(target);
}
public static String getExtension(String contentType) {
return "image/png".equals(contentType) ? "png" : "jpg";
}
private static BufferedImage scaleIfNeeded(BufferedImage source) {
int width = source.getWidth();
int height = source.getHeight();
int max = Math.max(width, height);
if (max <= MAX_EDGE) {
return source;
}
double scale = (double) MAX_EDGE / max;
int targetWidth = Math.max(1, (int) Math.round(width * scale));
int targetHeight = Math.max(1, (int) Math.round(height * scale));
int type = source.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_ARGB : source.getType();
BufferedImage target = new BufferedImage(targetWidth, targetHeight, type);
Graphics2D graphics = target.createGraphics();
try {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.drawImage(source, 0, 0, targetWidth, targetHeight, null);
} finally {
graphics.dispose();
}
return target;
}
private static byte[] writePng(BufferedImage image) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
return outputStream.toByteArray();
}
private static byte[] writeJpeg(BufferedImage image) throws IOException {
BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = rgbImage.createGraphics();
try {
graphics.drawImage(image, 0, 0, null);
} finally {
graphics.dispose();
}
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext()) {
throw new IOException("未找到 JPG 图片编码器");
}
ImageWriter writer = writers.next();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream)) {
writer.setOutput(imageOutputStream);
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if (writeParam.canWriteCompressed()) {
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(JPEG_QUALITY);
}
writer.write(null, new IIOImage(rgbImage, null, null), writeParam);
} finally {
writer.dispose();
}
return outputStream.toByteArray();
}
private static boolean isPng(byte[] imageBytes) {
return imageBytes.length >= 8
&& (imageBytes[0] & 0xFF) == 0x89
&& imageBytes[1] == 0x50
&& imageBytes[2] == 0x4E
&& imageBytes[3] == 0x47
&& imageBytes[4] == 0x0D
&& imageBytes[5] == 0x0A
&& imageBytes[6] == 0x1A
&& imageBytes[7] == 0x0A;
}
private static boolean isJpeg(byte[] imageBytes) {
return imageBytes.length >= 3
&& (imageBytes[0] & 0xFF) == 0xFF
&& (imageBytes[1] & 0xFF) == 0xD8
&& (imageBytes[2] & 0xFF) == 0xFF;
}
private static String normalize(String value) {
return value == null ? "" : value.toLowerCase(Locale.ROOT);
}
@Data
@AllArgsConstructor
public static class ImageEchoPayload {
private boolean hasImage;
private String imageBase64;
private String imageContentType;
}
}

View File

@@ -1,13 +1,16 @@
package com.njcn.gather.icd.controller;
import com.alibaba.fastjson.JSON;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import com.njcn.gather.icd.service.IPqIcdPathService;
@@ -18,12 +21,20 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import javax.validation.Valid;
import java.time.LocalDate;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @author caozehui
* @date 2025-02-10
@@ -38,7 +49,7 @@ public class PqIcdPathController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/listAll")
@ApiOperation("获取所有icd")
@ApiOperation("获取全部icd")
public HttpResult<List<PqIcdPath>> listAll() {
String methodDescribe = getMethodDescribe("listAll");
List<PqIcdPath> result = pqIcdPathService.listAll();
@@ -60,7 +71,7 @@ public class PqIcdPathController extends BaseController {
@PostMapping("/add")
@ApiOperation("新增icd")
@ApiImplicitParam(name = "param", value = "icd新增参数", required = true)
public HttpResult<Boolean> add(PqIcdPathParam param) {
public HttpResult<Boolean> add(@Validated PqIcdPathParam.CreateParam param) {
String methodDescribe = getMethodDescribe("add");
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, param);
@@ -72,11 +83,27 @@ public class PqIcdPathController extends BaseController {
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@PostMapping("/external/add")
@ApiOperation("外部系统新增icd")
@ApiImplicitParam(name = "param", value = "外部系统icd新增参数", required = true)
public HttpResult<Boolean> externalAdd(@RequestBody List<PqIcdPathParam.ExternalCreateParam> param) {
String methodDescribe = getMethodDescribe("externalAdd");
LogUtil.njcnDebug(log, "{},外部新增数据为:{}", methodDescribe, param);
boolean result = pqIcdPathService.addUpstreamIcd(param);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
@PostMapping("/update")
@ApiOperation("修改icd")
@ApiImplicitParam(name = "param", value = "icd修改参数", required = true)
public HttpResult<Boolean> update(PqIcdPathParam.UpdateParam param) {
public HttpResult<Boolean> update(@Validated PqIcdPathParam.UpdateParam param) {
String methodDescribe = getMethodDescribe("update");
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, param);
@@ -88,6 +115,24 @@ public class PqIcdPathController extends BaseController {
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/standard-list")
@ApiOperation("获取标准ICD列表")
public HttpResult<List<PqIcdPath>> standardList() {
String methodDescribe = getMethodDescribe("standardList");
List<PqIcdPath> result = pqIcdPathService.listStandardIcd();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getById")
@ApiOperation("根据id获取ICD详情")
public HttpResult<PqIcdPath> getById(@RequestParam String id) {
String methodDescribe = getMethodDescribe("getById");
PqIcdPath result = pqIcdPathService.getIcdById(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
@PostMapping("/delete")
@ApiOperation("删除icd")
@@ -103,5 +148,70 @@ public class PqIcdPathController extends BaseController {
}
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/export/{id}")
@ApiOperation("导出icd")
public ResponseEntity<ByteArrayResource> export(@PathVariable String id) {
PqIcdPath detail = pqIcdPathService.getIcdById(id);
byte[] body = pqIcdPathService.exportIcd(id);
String fileName = UriUtils.encode(detail.getName() + ".zip", StandardCharsets.UTF_8);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(body.length)
.body(new ByteArrayResource(body));
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/export/json")
@ApiOperation("导出icd json")
@ApiImplicitParam(name = "ids", value = "id集合", required = true)
public ResponseEntity<ByteArrayResource> exportJson(@RequestBody List<String> ids) {
byte[] body = pqIcdPathService.exportIcdJson(ids);
String fileName = UriUtils.encode(LocalDate.now() + ".json", StandardCharsets.UTF_8);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
.contentType(MediaType.APPLICATION_JSON)
.contentLength(body.length)
.body(new ByteArrayResource(body));
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@PostMapping("/import/json")
@ApiOperation("导入icd json")
@ApiImplicitParam(name = "file", value = "json文件", required = true)
public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
String methodDescribe = getMethodDescribe("importJson");
LogUtil.njcnDebug(log, "{},导入文件为:{}", methodDescribe, file == null ? null : file.getOriginalFilename());
List<PqIcdPathParam.ExternalCreateParam> param = parseExternalCreateParams(file);
boolean result = pqIcdPathService.addUpstreamIcd(param);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
}
private List<PqIcdPathParam.ExternalCreateParam> parseExternalCreateParams(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
}
String fileName = file.getOriginalFilename();
if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
}
try {
String content = new String(file.getBytes(), StandardCharsets.UTF_8);
List<PqIcdPathParam.ExternalCreateParam> params = JSON.parseArray(content, PqIcdPathParam.ExternalCreateParam.class);
if (params == null) {
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
}
return params;
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
}
}
}

View File

@@ -1,9 +1,13 @@
package com.njcn.gather.icd.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author caozehui
* @date 2025-02-10
@@ -17,5 +21,21 @@ public interface PqIcdPathMapper extends MPJBaseMapper<PqIcdPath> {
* @return
*/
PqIcdPath selectIcdByDevType(@Param("devTypeId") String devTypeId);
List<PqIcdPath> selectPageList(Page<PqIcdPath> page, @Param("name") String name);
List<PqIcdPath> selectStandardList();
PqIcdPath selectStandardByName(@Param("name") String name);
List<PqIcdPath> selectByIdsWithoutBlob(@Param("ids") List<String> ids);
Long countActiveReferencesToStandards(@Param("standardIds") List<String> standardIds);
PqIcdPath selectDetailById(@Param("id") String id);
PqIcdPath selectExportById(@Param("id") String id);
List<PqIcdExportJsonVO> selectExportJsonByIds(@Param("ids") List<String> ids);
}

View File

@@ -4,10 +4,135 @@
<select id="selectIcdByDevType" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select *
select path.*
from pq_icd_path path
inner join pq_dev_type type on path.id = type.icd
where type.id = #{devTypeId}
</select>
<select id="selectPageList" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select p.id,
p.name,
p.state,
p.angle,
p.use_phase_index as usePhaseIndex,
p.Json_Str as jsonStr,
p.Xml_Str as xmlStr,
p.Result as result,
p.Msg as msg,
p.Type as type,
p.Reference_Icd_Id as referenceIcdId,
ref.name as referenceIcdName,
case when p.Icd is null then false else true end as hasIcdFile,
p.create_by as createBy,
p.create_time as createTime,
p.update_by as updateBy,
p.update_time as updateTime
from pq_icd_path p
left join pq_icd_path ref on p.Reference_Icd_Id = ref.id
and ref.state = 1
and ref.Type in (1, 3)
where p.state = 1
<if test="name != null and name != ''">
and p.name like concat('%', #{name}, '%')
</if>
order by p.create_time desc
</select>
<select id="selectStandardList" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select id, name, Type as type
from pq_icd_path
where state = 1
and Type in (1, 3)
order by create_time desc
</select>
<select id="selectStandardByName" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select id, name, Type as type, state
from pq_icd_path
where state = 1
and Type in (1, 3)
and name = #{name}
limit 1
</select>
<select id="selectByIdsWithoutBlob" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select id, name, Type as type, state
from pq_icd_path
where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
and state = 1
</select>
<select id="countActiveReferencesToStandards" resultType="java.lang.Long">
select count(1)
from pq_icd_path
where state = 1
and Type in (2, 4)
and Reference_Icd_Id in
<foreach collection="standardIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<select id="selectDetailById" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select p.id,
p.name,
p.state,
p.angle,
p.use_phase_index as usePhaseIndex,
p.Json_Str as jsonStr,
p.Xml_Str as xmlStr,
p.Result as result,
p.Msg as msg,
p.Type as type,
p.Reference_Icd_Id as referenceIcdId,
ref.name as referenceIcdName,
case when p.Icd is null then false else true end as hasIcdFile,
p.create_by as createBy,
p.create_time as createTime,
p.update_by as updateBy,
p.update_time as updateTime
from pq_icd_path p
left join pq_icd_path ref on p.Reference_Icd_Id = ref.id
and ref.state = 1
and ref.Type in (1, 3)
where p.id = #{id}
and p.state = 1
</select>
<select id="selectExportById" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select id,
name,
state,
Json_Str as jsonStr,
Xml_Str as xmlStr,
Icd as icd
from pq_icd_path
where id = #{id}
and state = 1
</select>
<select id="selectExportJsonByIds" resultType="com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO">
select id,
name,
Icd as rawIcd,
angle,
use_phase_index as usePhaseIndex,
Json_Str as jsonStr,
Xml_Str as xmlStr,
Result as result,
Msg as msg,
Type as type,
Reference_Icd_Id as referenceIcdId
from pq_icd_path
where state = 1
and id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
</mapper>

View File

@@ -1,16 +1,45 @@
package com.njcn.gather.icd.pojo.enums;
import lombok.Getter;
/**
* @author caozehui
* @data 2025-11-11
*/
@Getter
public enum IcdResponseEnum {
FILE_NOT_NULL("A018001", "映射文件不能为空"),
FILE_TYPE_ERROR("A018002", "映射文件类型错误"),
FILE_SIZE_ERROR("A018003", "映射文件大小超出限制");
FILE_SIZE_ERROR("A018003", "映射文件大小超出限制"),
ICD_FILE_NOT_NULL("A018004", "ICD原始文件不能为空"),
ICD_FILE_TYPE_ERROR("A018005", "ICD原始文件类型错误"),
ICD_FILE_READ_ERROR("A018006", "ICD原始文件读取失败"),
JSON_FORMAT_ERROR("A018007", "JSON格式错误"),
XML_FORMAT_ERROR("A018008", "XML格式错误"),
STANDARD_ICD_IN_USE("A018009", "该标准ICD已被非标准ICD引用禁止删除"),
ICD_FILE_NOT_FOUND("A018010", "ICD原始文件不存在"),
ICD_EXPORT_FAILED("A018011", "ICD导出失败"),
ICD_NOT_FOUND("A018012", "ICD不存在"),
RESULT_NOT_NULL("A018013", "结论不能为空"),
MSG_NOT_BLANK("A018014", "当结论为否时,描述不能为空"),
TYPE_NOT_NULL("A018015", "ICD类型不能为空"),
TYPE_VALUE_ERROR("A018016", "ICD类型取值错误"),
REFERENCE_ICD_NOT_BLANK("A018017", "非标准ICD必须选择参照标准ICD"),
REFERENCE_ICD_INVALID("A018018", "参照标准ICD无效"),
GENERATE_FILE("A018019", "文件生成失败"),
ICD_TXT_SYNC_FAILED("A018020", "ICD txt文件同步失败"),
REFERENCE_STANDARD_ICD_NAME_NOT_FOUND("A018021", "参照标准ICD名称不存在"),
EXTERNAL_ICD_ITEM_NOT_NULL("A018022", "导入数据项不能为空"),
EXTERNAL_ICD_ID_REPEAT("A018023", "导入数据中存在重复id"),
EXTERNAL_ICD_DELETED_NOT_ALLOW_OVERWRITE("A018024", "该ICD已删除不允许通过导入覆盖"),
EXTERNAL_ICD_IMPORT_FAILED("A018025", "ICD导入失败"),
ANGLE_NOT_NULL("A018026", "是否支持相角不能为空"),
ANGLE_VALUE_ERROR("A018027", "是否支持相角取值错误"),
USE_PHASE_INDEX_NOT_NULL("A018028", "是否使用相别指标不能为空"),
USE_PHASE_INDEX_VALUE_ERROR("A018029", "是否使用相别指标取值错误");
private String code;
private String message;
private final String code;
private final String message;
IcdResponseEnum(String code, String message) {
this.code = code;

View File

@@ -17,39 +17,63 @@ import javax.validation.constraints.Pattern;
*/
@Data
public class PqIcdPathParam {
@ApiModelProperty(value = "名称", required = true)
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
@Pattern(regexp = PatternRegex.ICD_NAME_REGEX, message = DetectionValidMessage.ICD_NAME_FORMAT_ERROR)
private String name;
@ApiModelProperty(value = "存储路径", required = true)
@NotBlank(message = DetectionValidMessage.ICD_PATH_NOT_BLANK)
@Pattern(regexp = PatternRegex.ICD_PATH_REGEX, message = DetectionValidMessage.ICD_PATH_FORMAT_ERROR)
private String path;
@ApiModelProperty(value = "是否支持电压相角、电流相角指标0表示否1表示是", required = true)
@ApiModelProperty(value = "angle", required = true)
private Integer angle;
@ApiModelProperty(value = "角型接线时是否使用相别的指标来进行检测0表示否1表示是", required = true)
@ApiModelProperty(value = "usePhaseIndex", required = true)
private Integer usePhaseIndex;
@ApiModelProperty(value = "映射文件", required = true)
private MultipartFile mappingFile;
@ApiModelProperty(value = "jsonStr")
private String jsonStr;
@ApiModelProperty(value = "xmlStr")
private String xmlStr;
@ApiModelProperty(value = "result")
private Integer result;
@ApiModelProperty(value = "msg")
private String msg;
@ApiModelProperty(value = "type")
private Integer type;
@ApiModelProperty(value = "referenceIcdId")
private String referenceIcdId;
/**
* 分页查询实体
*/
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty(value = "名称", required = true)
@ApiModelProperty(value = "name", required = true)
private String name;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class CreateParam extends PqIcdPathParam {
@ApiModelProperty(value = "icdFile", required = true)
private MultipartFile icdFile;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ExternalCreateParam extends PqIcdPathParam {
@ApiModelProperty(value = "id", required = true)
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
private String id;
@ApiModelProperty(value = "name", required = true)
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
@Pattern(regexp = PatternRegex.SCRIPT_NAME_REGEX, message = DetectionValidMessage.ICD_NAME_FORMAT_ERROR)
private String name;
@ApiModelProperty(value = "icd", required = true)
@NotBlank(message = IcdExternalValidMessage.ICD_FILE_NOT_BLANK)
private String icd;
}
/**
* 更新参数
*/
@Data
@EqualsAndHashCode(callSuper = true)
public static class UpdateParam extends PqIcdPathParam {
@@ -57,5 +81,12 @@ public class PqIcdPathParam {
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
private String id;
@ApiModelProperty(value = "icdFile")
private MultipartFile icdFile;
}
private interface IcdExternalValidMessage {
String ICD_FILE_NOT_BLANK = "ICD原始文件不能为空";
}
}

View File

@@ -28,11 +28,6 @@ public class PqIcdPath extends BaseEntity implements Serializable {
*/
private String name;
/**
* icd存储地址
*/
private String path;
/**
* 状态0-删除 1-正常
*/
@@ -46,19 +41,55 @@ public class PqIcdPath extends BaseEntity implements Serializable {
/**
* 角型接线时是否使用相别的指标来进行检测0表示否1表示是
*/
@TableField("use_phase_index")
private Integer usePhaseIndex;
/**
* 映射文件路径
* 解析后的json字符串
*/
@TableField("Json_Str")
private String jsonStr;
/**
* 解析后的xml字符串
*/
@TableField("Xml_Str")
private String xmlStr;
/**
* ICD原始文件二进制
*/
@TableField("Icd")
private byte[] icd;
/**
* 结论
*/
@TableField("Result")
private Integer result;
/**
* 结论描述
*/
@TableField("Msg")
private String msg;
/**
* ICD类型
*/
@TableField("Type")
private Integer type;
/**
* 参照标准ICD
*/
@TableField("Reference_Icd_Id")
private String referenceIcdId;
@TableField(exist = false)
private FileVO mappingFile;
private String referenceIcdName;
@Data
public static class FileVO{
private String name;
private String url;
}
@TableField(exist = false)
private Boolean hasIcdFile;
}

View File

@@ -0,0 +1,38 @@
package com.njcn.gather.icd.pojo.vo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
/**
* ICD JSON export item.
*
* @author caozehui
* @date 2026-06-17
*/
@Data
public class PqIcdExportJsonVO {
private String id;
private String name;
@JSONField(serialize = false)
private byte[] rawIcd;
private String icd;
private Integer angle;
private Integer usePhaseIndex;
private String jsonStr;
private String xmlStr;
private Integer result;
private String msg;
private Integer type;
private String referenceIcdId;
}

View File

@@ -28,13 +28,22 @@ public interface IPqIcdPathService extends IService<PqIcdPath> {
*/
Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param);
/**
* 获取所有标准ICD
*
* @return 标准ICD列表
*/
List<PqIcdPath> listStandardIcd();
/**
* 新增Icd
*
* @param param 新增Icd参数
* @return 成功返回true失败返回false
*/
boolean addIcd(PqIcdPathParam param);
boolean addIcd(PqIcdPathParam.CreateParam param);
boolean addUpstreamIcd(List<PqIcdPathParam.ExternalCreateParam> param);
/**
* 修改Icd
@@ -52,6 +61,24 @@ public interface IPqIcdPathService extends IService<PqIcdPath> {
*/
boolean deleteIcd(List<String> ids);
/**
* 根据id获取ICD详情
*
* @param id ICD id
* @return ICD详情
*/
PqIcdPath getIcdById(String id);
/**
* 导出ICD压缩包
*
* @param id ICD id
* @return zip字节数组
*/
byte[] exportIcd(String id);
byte[] exportIcdJson(List<String> ids);
/**
* 根据设备类型id获取Icd
*

View File

@@ -1,34 +1,42 @@
package com.njcn.gather.icd.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.gather.icd.mapper.PqIcdPathMapper;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO;
import com.njcn.gather.pojo.constant.DetectionValidMessage;
import com.njcn.gather.icd.service.IPqIcdPathService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.pojo.enums.ReportResponseEnum;
import com.njcn.gather.icd.service.support.IcdArchiveBuilder;
import com.njcn.gather.icd.service.support.IcdPayloadAssembler;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author caozehui
@@ -38,174 +46,165 @@ import java.util.List;
@Service
@RequiredArgsConstructor
public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath> implements IPqIcdPathService {
// 手动录入标准ICD
private static final int TYPE_STANDARD = 1;
// 手动录入非标准ICD
private static final int TYPE_NON_STANDARD = 2;
// 上游录入的标准ICD
private static final int TYPE_UPSTREAM_STANDARD = 3;
// 上游录入的非标准ICD
private static final int TYPE_UPSTREAM_NON_STANDARD = 4;
private static final int RESULT_NO = 0;
private static final int RESULT_YES = 1;
@Value("${icd.txt-dir}")
private String icdTxtDir;
private final IcdPayloadAssembler icdPayloadAssembler;
private final IcdArchiveBuilder icdArchiveBuilder;
@Override
public List<PqIcdPath> listAll() {
return this.lambdaQuery().eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode()).list();
return this.lambdaQuery()
.select(PqIcdPath::getId, PqIcdPath::getName, PqIcdPath::getType, PqIcdPath::getReferenceIcdId)
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
.orderByDesc(PqIcdPath::getCreateTime)
.list();
}
@Override
public List<PqIcdPath> listStandardIcd() {
return this.baseMapper.selectStandardList();
}
@Override
public Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param) {
LambdaQueryWrapper<PqIcdPath> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
.like(StrUtil.isNotBlank(param.getName()), PqIcdPath::getName, param.getName())
.orderByDesc(PqIcdPath::getCreateTime);
Page<PqIcdPath> page = this.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), wrapper);
String commInstallPath = this.getCommInstallPath();
page.getRecords().forEach(pqIcdPath -> {
PqIcdPath.FileVO fileVO = new PqIcdPath.FileVO();
fileVO.setUrl(commInstallPath + "\\DeviceControl\\Config\\" + pqIcdPath.getName() + ".txt");
fileVO.setName(pqIcdPath.getName() + ".txt");
pqIcdPath.setMappingFile(fileVO);
});
Page<PqIcdPath> page = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param));
page.setRecords(this.baseMapper.selectPageList(page, StrUtil.trim(param.getName())));
return page;
}
@Override
@Transactional
public boolean addIcd(PqIcdPathParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, false);
PqIcdPath pqIcdPath = new PqIcdPath();
BeanUtils.copyProperties(param, pqIcdPath);
pqIcdPath.setState(DataStateEnum.ENABLE.getCode());
String commInstallPath = this.getCommInstallPath();
System.out.println("commInstallPath = " + commInstallPath);
long FILE_SIZE_LIMIT = 1 * 1024 * 1024;
MultipartFile mappingFile = param.getMappingFile();
System.out.println("mappingFile = " + ObjectUtil.isNotNull(mappingFile) + " " + !mappingFile.isEmpty());
if (ObjectUtil.isNotNull(mappingFile) && !mappingFile.isEmpty()) {
String mappingFilename = mappingFile.getOriginalFilename();
if (!mappingFilename.endsWith(".txt")) {
throw new BusinessException(IcdResponseEnum.FILE_TYPE_ERROR);
}
if (mappingFile.getSize() > FILE_SIZE_LIMIT) {
throw new BusinessException(IcdResponseEnum.FILE_SIZE_ERROR);
}
try {
// 如果文件存在,则先删除
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + mappingFilename;
System.out.println("mappingFilePath = " + mappingFilePath);
Path path = Paths.get(mappingFilePath);
File file = path.toFile();
if (file.exists()) {
file.delete();
}
// 保存文件
byte[] bytes = mappingFile.getBytes();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(mappingFilePath));
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();
bufferedOutputStream.close();
System.out.println("File saved successfully");
} catch (IOException e) {
throw new BusinessException(ReportResponseEnum.FILE_UPLOAD_FAILED);
}
} else {
System.out.println("mappingFile is null or empty");
throw new BusinessException(IcdResponseEnum.FILE_NOT_NULL);
public boolean addIcd(PqIcdPathParam.CreateParam param) {
validateBusinessFields(param, null);
PqIcdPath pqIcdPath = icdPayloadAssembler.fromCreate(param);
validateReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), null);
boolean saved = this.save(pqIcdPath);
if (saved) {
writeIcdTextFile(resolveIcdTxtDir(), pqIcdPath.getName(), pqIcdPath.getJsonStr());
}
this.executeRestartCmd(commInstallPath);
return this.save(pqIcdPath);
return saved;
}
/**
* 执行重启通讯服务脚本
*
* @param commInstallPath
*/
private void executeRestartCmd(String commInstallPath) {
// 以管理员身份运行bat脚本
String batFilePath = commInstallPath + "\\重启所有服务.bat";
try {
Runtime.getRuntime().exec(batFilePath);
} catch (IOException e) {
log.error("重启通讯服务失败", e);
@Override
@Transactional
public boolean addUpstreamIcd(List<PqIcdPathParam.ExternalCreateParam> param) {
if (CollUtil.isEmpty(param)) {
return true;
}
}
private String getCommInstallPath() {
String workDir = System.getProperty("user.dir");
// String workDir = "D:\\program\\CN_Gather";
// 获取映射文件存放文件夹
String dirPath = workDir + "\\9100";
int index = workDir.indexOf("\\resources\\extraResources\\java");
if (index != -1) {
dirPath = workDir.substring(0, workDir.indexOf("\\resources\\extraResources\\java")) + "\\9100";
validateExternalItems(param);
Set<String> requestStandardIds = collectRequestStandardIds(param);
Path directory = resolveIcdTxtDir();
for (PqIcdPathParam.ExternalCreateParam item : param) {
validateBusinessFields(item, null);
PqIcdPath current = this.baseMapper.selectById(item.getId());
if (current != null && !ObjectUtil.equals(current.getState(), DataStateEnum.ENABLE.getCode())) {
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_DELETED_NOT_ALLOW_OVERWRITE);
}
PqIcdPath pqIcdPath = icdPayloadAssembler.fromExternalCreate(item, item.getType(), item.getAngle(), item.getUsePhaseIndex());
String currentId = current == null ? null : current.getId();
String oldName = current == null ? null : current.getName();
validateExternalReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), currentId, requestStandardIds);
boolean saved = current == null ? this.save(pqIcdPath) : this.updateById(pqIcdPath);
if (!saved) {
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_IMPORT_FAILED);
}
if (current == null) {
writeIcdTextFile(directory, pqIcdPath.getName(), pqIcdPath.getJsonStr());
} else {
syncUpdatedIcdTextFile(directory, oldName, pqIcdPath.getName(), pqIcdPath.getJsonStr());
}
}
return dirPath;
return true;
}
@Override
@Transactional
public boolean updateIcd(PqIcdPathParam.UpdateParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, true);
PqIcdPath pqIcdPath = new PqIcdPath();
BeanUtils.copyProperties(param, pqIcdPath);
String commInstallPath = this.getCommInstallPath();
long FILE_SIZE_LIMIT = 1 * 1024 * 1024;
MultipartFile mappingFile = param.getMappingFile();
if (ObjectUtil.isNotNull(mappingFile) && !mappingFile.isEmpty()) {
String mappingFilename = mappingFile.getOriginalFilename();
if (!mappingFilename.endsWith(".txt")) {
throw new BusinessException(IcdResponseEnum.FILE_TYPE_ERROR);
}
if (mappingFile.getSize() > FILE_SIZE_LIMIT) {
throw new BusinessException(IcdResponseEnum.FILE_SIZE_ERROR);
}
try {
// 如果文件存在,则先删除
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + mappingFilename;
Path path = Paths.get(mappingFilePath);
File file = path.toFile();
if (file.exists()) {
file.delete();
}
// 保存文件
byte[] bytes = mappingFile.getBytes();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(mappingFilePath));
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException e) {
throw new BusinessException(ReportResponseEnum.FILE_UPLOAD_FAILED);
}
PqIcdPath current = getActiveEntity(param.getId());
String oldName = current.getName();
validateBusinessFields(param, current.getId());
PqIcdPath pqIcdPath = icdPayloadAssembler.merge(current, param);
validateReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), current.getId());
boolean updated = this.updateById(pqIcdPath);
if (updated) {
syncUpdatedIcdTextFile(resolveIcdTxtDir(), oldName, pqIcdPath.getName(), pqIcdPath.getJsonStr());
}
this.executeRestartCmd(commInstallPath);
return this.updateById(pqIcdPath);
return updated;
}
@Override
@Transactional
public boolean deleteIcd(List<String> ids) {
List<PqIcdPath> pqIcdPaths = this.listByIds(ids);
String commInstallPath = this.getCommInstallPath();
pqIcdPaths.forEach(pqIcdPath -> {
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + pqIcdPath.getName() + ".txt";
Path path = Paths.get(mappingFilePath);
File file = path.toFile();
if (file.exists()) {
file.delete();
if (CollUtil.isEmpty(ids)) {
return true;
}
List<PqIcdPath> pqIcdPaths = this.baseMapper.selectByIdsWithoutBlob(ids);
List<String> standardIds = pqIcdPaths.stream()
.filter(pqIcdPath -> ObjectUtil.equals(pqIcdPath.getType(), TYPE_STANDARD))
.map(PqIcdPath::getId)
.collect(Collectors.toList());
if (!standardIds.isEmpty()) {
Long count = this.baseMapper.countActiveReferencesToStandards(standardIds);
if (ObjectUtil.isNotNull(count) && count > 0) {
throw new BusinessException(IcdResponseEnum.STANDARD_ICD_IN_USE);
}
});
}
return this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
boolean deleted = this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
if (deleted) {
Path directory = resolveIcdTxtDir();
for (PqIcdPath pqIcdPath : pqIcdPaths) {
deleteIcdTextFile(directory, pqIcdPath.getName());
}
}
return deleted;
}
@Override
public PqIcdPath getIcdById(String id) {
PqIcdPath detail = this.baseMapper.selectDetailById(id);
if (ObjectUtil.isNull(detail)) {
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
}
return detail;
}
@Override
public byte[] exportIcd(String id) {
PqIcdPath detail = this.baseMapper.selectExportById(id);
if (ObjectUtil.isNull(detail)) {
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
}
return icdArchiveBuilder.build(detail);
}
@Override
public byte[] exportIcdJson(List<String> ids) {
if (CollUtil.isEmpty(ids)) {
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
}
List<PqIcdExportJsonVO> details = this.baseMapper.selectExportJsonByIds(ids);
if (CollUtil.isEmpty(details)) {
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
}
for (PqIcdExportJsonVO detail : details) {
detail.setIcd(encodeIcdFile(detail.getRawIcd()));
normalizeExportDetail(detail);
}
return JSON.toJSONString(details).getBytes(StandardCharsets.UTF_8);
}
@Override
@@ -213,18 +212,188 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
return this.baseMapper.selectIcdByDevType(devTypeId);
}
private void checkRepeat(PqIcdPathParam param, boolean isExcludeSelf) {
LambdaQueryWrapper<PqIcdPath> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PqIcdPath::getName, param.getName())
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode());
if (isExcludeSelf) {
if (param instanceof PqIcdPathParam.UpdateParam) {
wrapper.ne(PqIcdPath::getId, ((PqIcdPathParam.UpdateParam) param).getId());
}
private void validateBusinessFields(PqIcdPathParam param, String currentId) {
if (ObjectUtil.isNull(param.getResult())) {
throw new BusinessException(IcdResponseEnum.RESULT_NOT_NULL);
}
int count = this.count(wrapper);
if (count > 0) {
throw new BusinessException(DetectionResponseEnum.ICD_PATH_NAME_REPEAT);
if (ObjectUtil.equals(param.getResult(), RESULT_NO) && StrUtil.isBlank(param.getMsg())) {
throw new BusinessException(IcdResponseEnum.MSG_NOT_BLANK);
}
if (ObjectUtil.isNull(param.getType())) {
throw new BusinessException(IcdResponseEnum.TYPE_NOT_NULL);
}
if (!ObjectUtil.equals(param.getType(), TYPE_STANDARD)
&& !ObjectUtil.equals(param.getType(), TYPE_NON_STANDARD)
&& !ObjectUtil.equals(param.getType(), TYPE_UPSTREAM_STANDARD)
&& !ObjectUtil.equals(param.getType(), TYPE_UPSTREAM_NON_STANDARD)) {
throw new BusinessException(IcdResponseEnum.TYPE_VALUE_ERROR);
}
if (requiresReferenceIcd(param.getType()) && StrUtil.isBlank(param.getReferenceIcdId())) {
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_NOT_BLANK);
}
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, StrUtil.trim(param.getReferenceIcdId()))) {
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
}
}
private void validateReferenceIcd(Integer type, String referenceIcdId, String currentId) {
if (!requiresReferenceIcd(type)) {
return;
}
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, referenceIcdId)) {
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
}
long count = this.lambdaQuery()
.eq(PqIcdPath::getId, referenceIcdId)
.in(PqIcdPath::getType, TYPE_STANDARD, TYPE_UPSTREAM_STANDARD)
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
.count();
if (count <= 0L) {
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
}
}
private void validateExternalReferenceIcd(Integer type, String referenceIcdId, String currentId, Set<String> requestStandardIds) {
if (!requiresReferenceIcd(type)) {
return;
}
String trimmedReferenceId = StrUtil.trim(referenceIcdId);
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, trimmedReferenceId)) {
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
}
if (StrUtil.isNotBlank(trimmedReferenceId) && requestStandardIds.contains(trimmedReferenceId)) {
return;
}
validateReferenceIcd(type, trimmedReferenceId, currentId);
}
private Set<String> collectRequestStandardIds(List<PqIcdPathParam.ExternalCreateParam> params) {
Set<String> ids = new HashSet<>();
for (PqIcdPathParam.ExternalCreateParam param : params) {
if (isStandardType(param.getType()) && StrUtil.isNotBlank(param.getId())) {
ids.add(StrUtil.trim(param.getId()));
}
}
return ids;
}
private void validateExternalItems(List<PqIcdPathParam.ExternalCreateParam> params) {
Set<String> ids = new HashSet<>();
for (PqIcdPathParam.ExternalCreateParam param : params) {
if (param == null) {
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_ITEM_NOT_NULL);
}
validateExternalItem(param);
String trimmedId = StrUtil.trim(param.getId());
if (!ids.add(trimmedId)) {
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_ID_REPEAT);
}
}
}
private void validateExternalItem(PqIcdPathParam.ExternalCreateParam param) {
if (StrUtil.isBlank(param.getId())) {
throw new BusinessException(DetectionValidMessage.ID_NOT_BLANK);
}
if (!ReUtil.isMatch(PatternRegex.SYSTEM_ID, StrUtil.trim(param.getId()))) {
throw new BusinessException(DetectionValidMessage.ID_FORMAT_ERROR);
}
if (StrUtil.isBlank(param.getName())) {
throw new BusinessException(DetectionValidMessage.NAME_NOT_BLANK);
}
if (!ReUtil.isMatch(PatternRegex.SCRIPT_NAME_REGEX, StrUtil.trim(param.getName()))) {
throw new BusinessException(DetectionValidMessage.ICD_NAME_FORMAT_ERROR);
}
if (StrUtil.isBlank(param.getIcd())) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
}
if (ObjectUtil.isNull(param.getAngle())) {
throw new BusinessException(IcdResponseEnum.ANGLE_NOT_NULL);
}
if (!ObjectUtil.equals(param.getAngle(), 0) && !ObjectUtil.equals(param.getAngle(), 1)) {
throw new BusinessException(IcdResponseEnum.ANGLE_VALUE_ERROR);
}
if (ObjectUtil.isNull(param.getUsePhaseIndex())) {
throw new BusinessException(IcdResponseEnum.USE_PHASE_INDEX_NOT_NULL);
}
if (!ObjectUtil.equals(param.getUsePhaseIndex(), 0) && !ObjectUtil.equals(param.getUsePhaseIndex(), 1)) {
throw new BusinessException(IcdResponseEnum.USE_PHASE_INDEX_VALUE_ERROR);
}
}
private boolean requiresReferenceIcd(Integer type) {
return ObjectUtil.equals(type, TYPE_NON_STANDARD) || ObjectUtil.equals(type, TYPE_UPSTREAM_NON_STANDARD);
}
private boolean isStandardType(Integer type) {
return ObjectUtil.equals(type, TYPE_STANDARD) || ObjectUtil.equals(type, TYPE_UPSTREAM_STANDARD);
}
private PqIcdPath getActiveEntity(String id) {
PqIcdPath current = this.lambdaQuery()
.eq(PqIcdPath::getId, id)
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
.one();
if (ObjectUtil.isNull(current)) {
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
}
return current;
}
Path resolveIcdTxtDir() {
if (StrUtil.isBlank(icdTxtDir)) {
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
}
return Paths.get(icdTxtDir.trim());
}
void writeIcdTextFile(Path directory, String name, String jsonStr) {
try {
Files.createDirectories(directory);
Files.write(resolveTxtFile(directory, name), StrUtil.nullToDefault(jsonStr, "").getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
} catch (IOException ex) {
log.error("sync icd txt file failed, name={}", name, ex);
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
}
}
void syncUpdatedIcdTextFile(Path directory, String oldName, String newName, String jsonStr) {
if (StrUtil.isNotBlank(oldName) && !StrUtil.equals(oldName, newName)) {
deleteIcdTextFile(directory, oldName);
}
writeIcdTextFile(directory, newName, jsonStr);
}
void deleteIcdTextFile(Path directory, String name) {
try {
Files.deleteIfExists(resolveTxtFile(directory, name));
} catch (IOException ex) {
log.error("delete icd txt file failed, name={}", name, ex);
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
}
}
private Path resolveTxtFile(Path directory, String name) {
return directory.resolve(name + ".txt");
}
private String encodeIcdFile(byte[] rawValue) {
if (rawValue == null || rawValue.length == 0) {
return null;
}
return Base64.getEncoder().encodeToString(rawValue);
}
private void normalizeExportDetail(PqIcdExportJsonVO detail) {
detail.setRawIcd(null);
detail.setAngle(detail.getAngle() == null ? 0 : detail.getAngle());
detail.setUsePhaseIndex(detail.getUsePhaseIndex() == null ? 1 : detail.getUsePhaseIndex());
if (isStandardType(detail.getType())) {
detail.setType(TYPE_UPSTREAM_STANDARD);
detail.setReferenceIcdId(null);
return;
}
detail.setType(TYPE_UPSTREAM_NON_STANDARD);
}
}

View File

@@ -0,0 +1,62 @@
package com.njcn.gather.icd.service.support;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Component
public class IcdArchiveBuilder {
public byte[] build(PqIcdPath item) {
if (item == null || item.getIcd() == null || item.getIcd().length == 0) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_FOUND);
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
writeTextEntry(zos, item.getName() + ".json", item.getJsonStr());
writeTextEntry(zos, item.getName() + ".xml", item.getXmlStr());
writeBinaryEntry(zos, item.getName() + ".icd", item.getIcd());
zos.finish();
return bos.toByteArray();
} catch (IOException ex) {
throw new BusinessException(IcdResponseEnum.ICD_EXPORT_FAILED);
}
}
/**
* 向ZIP流中写入文本条目
*
* @param zos ZIP输出流
* @param name 条目名称(文件路径)
* @param value 文本内容如果为null则写入空字节数组
* @throws IOException 写入异常
*/
private void writeTextEntry(ZipOutputStream zos, String name, String value) throws IOException {
// 将文本转换为UTF-8编码的字节数组null值转换为空数组
writeBinaryEntry(zos, name, value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8));
}
/**
* 向ZIP流中写入二进制条目
*
* @param zos ZIP输出流
* @param name 条目名称(文件路径)
* @param data 二进制数据
* @throws IOException 写入异常
*/
private void writeBinaryEntry(ZipOutputStream zos, String name, byte[] data) throws IOException {
// 创建新的ZIP条目并设置文件名
zos.putNextEntry(new ZipEntry(name));
// 写入二进制数据
zos.write(data);
// 关闭当前条目,准备写入下一个条目
zos.closeEntry();
}
}

View File

@@ -0,0 +1,90 @@
package com.njcn.gather.icd.service.support;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class IcdPayloadAssembler {
private final IcdPayloadValidator validator;
public PqIcdPath fromCreate(PqIcdPathParam.CreateParam param) {
MultipartFile file = validator.validateIcdFile(param.getIcdFile(), true);
validator.validateJson(param.getJsonStr());
validator.validateXml(param.getXmlStr());
PqIcdPath entity = new PqIcdPath();
applyCommonFields(entity, param);
entity.setName(validator.extractName(file.getOriginalFilename()));
entity.setIcd(getBytes(file));
entity.setState(DataStateEnum.ENABLE.getCode());
return entity;
}
public PqIcdPath fromExternalCreate(PqIcdPathParam.ExternalCreateParam param, int type, int angle, int usePhaseIndex) {
byte[] fileBytes = validator.decodeExternalIcdFile(param.getIcd());
validator.validateJson(param.getJsonStr());
validator.validateXml(param.getXmlStr());
PqIcdPath entity = new PqIcdPath();
entity.setId(normalizeNullableText(param.getId()));
param.setType(type);
param.setAngle(angle);
param.setUsePhaseIndex(usePhaseIndex);
applyCommonFields(entity, param);
entity.setName(normalizeNullableText(param.getName()));
entity.setIcd(fileBytes);
entity.setState(DataStateEnum.ENABLE.getCode());
return entity;
}
public PqIcdPath merge(PqIcdPath current, PqIcdPathParam.UpdateParam param) {
MultipartFile file = validator.validateIcdFile(param.getIcdFile(), false);
validator.validateJson(param.getJsonStr());
validator.validateXml(param.getXmlStr());
applyCommonFields(current, param);
if (file != null && !file.isEmpty()) {
current.setName(validator.extractName(file.getOriginalFilename()));
current.setIcd(getBytes(file));
}
return current;
}
private void applyCommonFields(PqIcdPath entity, PqIcdPathParam param) {
entity.setAngle(param.getAngle());
entity.setUsePhaseIndex(param.getUsePhaseIndex());
entity.setJsonStr(param.getJsonStr());
entity.setXmlStr(param.getXmlStr());
entity.setResult(param.getResult());
entity.setMsg(param.getResult() != null && param.getResult() == 1 ? null : normalizeNullableText(param.getMsg()));
entity.setType(param.getType());
entity.setReferenceIcdId(requiresReferenceIcd(param.getType()) ? normalizeNullableText(param.getReferenceIcdId()) : null);
}
private String normalizeNullableText(String value) {
return StrUtil.emptyToNull(StrUtil.trim(value));
}
private boolean requiresReferenceIcd(Integer type) {
return type != null && (type == 2 || type == 4);
}
private byte[] getBytes(MultipartFile file) {
try {
return file.getBytes();
} catch (IOException ex) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_READ_ERROR);
}
}
}

View File

@@ -0,0 +1,66 @@
package com.njcn.gather.icd.service.support;
import com.alibaba.fastjson.JSON;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.Base64;
import java.util.Locale;
@Component
public class IcdPayloadValidator {
public MultipartFile validateIcdFile(MultipartFile file, boolean required) {
if ((file == null || file.isEmpty()) && required) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
}
if (file == null || file.isEmpty()) {
return null;
}
String originalName = file.getOriginalFilename();
if (originalName == null || !originalName.toLowerCase(Locale.ROOT).endsWith(".icd")) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_TYPE_ERROR);
}
return file;
}
public String extractName(String originalName) {
int suffixIndex = originalName.toLowerCase(Locale.ROOT).lastIndexOf(".icd");
return suffixIndex >= 0 ? originalName.substring(0, suffixIndex) : originalName;
}
public byte[] decodeExternalIcdFile(String base64Content) {
if (base64Content == null || base64Content.trim().isEmpty()) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
}
try {
return Base64.getDecoder().decode(base64Content.trim());
} catch (IllegalArgumentException ex) {
throw new BusinessException(IcdResponseEnum.ICD_FILE_READ_ERROR);
}
}
public void validateJson(String jsonStr) {
try {
JSON.parse(jsonStr);
} catch (Exception ex) {
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
}
}
public void validateXml(String xmlStr) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 禁用 DOCTYPE 声明
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
} catch (Exception ex) {
throw new BusinessException(IcdResponseEnum.XML_FORMAT_ERROR);
}
}
}

View File

@@ -99,7 +99,7 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
this.baseMapper.updateDeviceReportRState(devId, DevReportStateEnum.NOT_GENERATED.getValue());
}
if (enableCheckMonitorList.size() > checkedMonitorList.size() && checkedMonitorList.size() > 0) {
this.baseMapper.updateDeviceCheckState(devId, CheckStateEnum.CHECKING.getValue());
this.baseMapper.updateDeviceCheckState(devId, CheckStateEnum.UNCHECKED.getValue());
this.baseMapper.updateDeviceReportRState(devId, DevReportStateEnum.NOT_GENERATED.getValue());
}
if (enableCheckMonitorList.size() > 0 && checkedMonitorList.size() == 0) {
@@ -142,13 +142,14 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
List<PqDevSub> devSubList = this.baseMapper.listDevSubByPlanId(plan.getId());
List<PqDevSub> checkedDevSubList = devSubList.stream().filter(pqDevSub -> pqDevSub.getCheckState() == CheckStateEnum.CHECKED.getValue()).collect(Collectors.toList());
List<PqDevSub> checkingDevSubList = devSubList.stream().filter(pqDevSub -> pqDevSub.getCheckState() == CheckStateEnum.CHECKING.getValue()).collect(Collectors.toList());
if (checkedDevSubList.size() == devSubList.size() && devSubList.size() > 0) {
boolean allUnchecked = devSubList.stream().allMatch(pqDevSub -> CheckStateEnum.UNCHECKED.getValue().equals(pqDevSub.getCheckState()));
boolean allArchived = devSubList.stream().allMatch(pqDevSub -> pqDevSub.getCheckState() != null && pqDevSub.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allArchived && CollUtil.isNotEmpty(devSubList)) {
this.baseMapper.updatePlanCheckState(plan.getId(), CheckStateEnum.CHECKED.getValue());
} else if (checkedDevSubList.size() > 0 || checkingDevSubList.size() > 0) {
this.baseMapper.updatePlanCheckState(plan.getId(), CheckStateEnum.CHECKING.getValue());
} else {
} else if (allUnchecked) {
this.baseMapper.updatePlanCheckState(plan.getId(), CheckStateEnum.UNCHECKED.getValue());
} else {
this.baseMapper.updatePlanCheckState(plan.getId(), CheckStateEnum.CHECKING.getValue());
}
List<PqDevSub> accordDevSubList = checkedDevSubList.stream().filter(pqDevSub -> pqDevSub.getCheckResult() == CheckResultEnum.ACCORD.getValue()).collect(Collectors.toList());
@@ -372,10 +373,6 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
if (checkedNumList.containsAll(allNumList)) {
return CheckStateEnum.CHECKED.getValue();
} else {
if (checkedNumList.size() > 0) {
return CheckStateEnum.CHECKING.getValue();
}
}
}
return CheckStateEnum.UNCHECKED.getValue();

View File

@@ -29,13 +29,4 @@ public interface AdPlanMapper extends MPJBaseMapper<AdPlan> {
* @return
*/
PqReport getPqReportById(String id);
/**
* 获取所有报告模板名称
*
* @return
*/
List<String> listAllReportTemplateName();
}

View File

@@ -2,7 +2,6 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.plan.mapper.AdPlanMapper">
<select id="getReportIdByNameAndVersion" resultType="java.lang.String">
SELECT id
FROM pq_report
@@ -17,10 +16,4 @@
WHERE id = #{id}
and state = 1
</select>
<select id="listAllReportTemplateName" resultType="java.lang.String">
SELECT concat(name, '_', version) as name
FROM pq_report
WHERE state = 1
</select>
</mapper>

View File

@@ -40,6 +40,9 @@ public class PqDevCheckHistory {
@TableField("Result")
private Integer result;
/**
* 检测结束时间
*/
@TableField("Check_Time")
private LocalDateTime checkTime;

View File

@@ -36,6 +36,11 @@ public class PlanStatisticsVO {
*/
private Integer uncheckedDeviceCount;
/**
* 检测中设备总数。
*/
private Integer checkingDeviceCount;
/**
* 第一次检测合格的设备数量。
*/

View File

@@ -436,20 +436,14 @@ public class AsyncPlanHandler {
planIds.add(planId);
List<String> devIds = pqDevService.lambdaQuery().in(PqDev::getPlanId, planIds).list().stream().map(PqDev::getId).collect(Collectors.toList());
List<PqDevSub> devSubs = pqDevSubService.lambdaQuery().in(PqDevSub::getDevId, devIds).list();
long checkedCount = devSubs.stream().filter(sub -> sub.getCheckState().equals(CheckStateEnum.CHECKED.getValue())).count();
if (checkedCount > 0) {
plan.setTestState(CheckStateEnum.CHECKING.getValue());
// 都已检测完成
if (checkedCount == devSubs.size()) {
plan.setTestState(CheckStateEnum.CHECKED.getValue());
}
} else {
boolean allUnchecked = devSubs.stream().allMatch(sub -> CheckStateEnum.UNCHECKED.getValue().equals(sub.getCheckState()));
boolean allArchived = devSubs.stream().allMatch(sub -> sub.getCheckState() != null && sub.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allUnchecked) {
plan.setTestState(CheckStateEnum.UNCHECKED.getValue());
// 是否有检测中
long checkingCount = devSubs.stream().filter(sub -> sub.getCheckState().equals(CheckStateEnum.CHECKING.getValue())).count();
if (checkingCount > 0) {
plan.setTestState(CheckStateEnum.CHECKING.getValue());
}
} else if (allArchived && !devSubs.isEmpty()) {
plan.setTestState(CheckStateEnum.CHECKED.getValue());
} else {
plan.setTestState(CheckStateEnum.CHECKING.getValue());
}
adPlanService.updateById(plan);
LocalDateTime endTime = LocalDateTime.now();

View File

@@ -216,7 +216,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
List<PqDevVO> pqDevVOList = pqDevMapper.selectByQueryParam(queryParam1);
if (CollUtil.isNotEmpty(pqDevVOList)) {
long count = pqDevVOList.stream().filter(pqDev -> CheckStateEnum.CHECKED.getValue().equals(pqDev.getCheckState()) || CheckStateEnum.DOCUMENTED.getValue().equals(pqDev.getCheckState())).count();
long count = pqDevVOList.stream().filter(pqDev -> pqDev.getCheckState() != null && pqDev.getCheckState() >= CheckStateEnum.CHECKED.getValue()).count();
adPlanVO.setProgress((float) count / pqDevVOList.size());
} else {
adPlanVO.setProgress(0.0f);
@@ -405,10 +405,13 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
PqDevParam.QueryParam queryParam = new PqDevParam.QueryParam();
queryParam.setPlanIdList(Collections.singletonList(plan1.getId()));
List<PqDevVO> pqDevVOS = pqDevService.listByPlanId(queryParam);
long checkedCount = pqDevVOS.stream().filter(pqDevVO -> pqDevVO.getCheckState().equals(CheckStateEnum.CHECKED.getValue())).count();
if (checkedCount == pqDevVOS.size()) {
boolean allUnchecked = pqDevVOS.stream().allMatch(pqDevVO -> CheckStateEnum.UNCHECKED.getValue().equals(pqDevVO.getCheckState()));
boolean allArchived = pqDevVOS.stream().allMatch(pqDevVO -> pqDevVO.getCheckState() != null && pqDevVO.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allUnchecked) {
plan1.setTestState(CheckStateEnum.UNCHECKED.getValue());
} else if (allArchived && !pqDevVOS.isEmpty()) {
plan1.setTestState(CheckStateEnum.CHECKED.getValue());
} else if (checkedCount > 0) {
} else {
plan1.setTestState(CheckStateEnum.CHECKING.getValue());
}
}
@@ -832,12 +835,19 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
List<PqDevVO> checkedDevices = planDevices.stream()
.filter(this::isCheckedDevice)
.collect(Collectors.toList());
int uncheckedDeviceCount = (int) planDevices.stream()
.filter(dev -> Objects.equals(dev.getCheckState(), CheckStateEnum.UNCHECKED.getValue()))
.count();
int checkingDeviceCount = (int) planDevices.stream()
.filter(dev -> Objects.equals(dev.getCheckState(), CheckStateEnum.CHECKING.getValue()))
.count();
PlanStatisticsVO statistics = new PlanStatisticsVO();
statistics.setPlanId(plan.getId());
statistics.setPlanName(plan.getName());
statistics.setManufacturerOptions(buildManufacturerOptions(allPlanDevices, param.getDevType()));
statistics.setDevTypeOptions(buildDevTypeOptions(allPlanDevices, param.getManufacturer()));
statistics.setUncheckedDeviceCount(planDevices.size() - checkedDevices.size());
statistics.setUncheckedDeviceCount(uncheckedDeviceCount);
statistics.setCheckingDeviceCount(checkingDeviceCount);
statistics.setCheckedDeviceCount(checkedDevices.size());
statistics.setTotalCheckCount(checkedDevices.stream().mapToInt(dev -> defaultZero(dev.getRecheckNum())).sum());
@@ -935,9 +945,8 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
private boolean isCheckedDevice(PqDevVO dev) {
return (Objects.equals(dev.getCheckState(), CheckStateEnum.CHECKED.getValue())
|| Objects.equals(dev.getCheckState(), CheckStateEnum.DOCUMENTED.getValue()))
&& !Objects.equals(dev.getCheckResult(), CheckResultEnum.UNCHECKED.getValue());
Integer checkState = dev.getCheckState();
return checkState != null && checkState >= CheckStateEnum.CHECKED.getValue();
}
private List<PlanStatisticsItemVO> buildItemDistributions(AdPlan plan, List<PqDevVO> checkedDevices) {
@@ -1235,26 +1244,22 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
// 0-解绑、1-绑定
if (param.getBindFlag().equals(1)) {
pqDevService.lambdaUpdate().set(PqDev::getPlanId, plan.getId()).in(PqDev::getId, param.getDevIds()).update();
// 绑定被检设备,若检测计划已检测完成,则修改为检测中
if (plan.getTestState().equals(CheckStateEnum.CHECKED.getValue())) {
plan.setTestState(CheckStateEnum.CHECKING.getValue());
this.updateById(plan);
}
} else {
pqDevService.lambdaUpdate().set(PqDev::getPlanId, plan.getFatherPlanId()).in(PqDev::getId, param.getDevIds()).update();
// 解绑被检设备,若检测计划检测中,且所有设备已检测完成,则修改为检测完成
if (plan.getTestState().equals(CheckStateEnum.CHECKING.getValue())) {
PqDevParam.QueryParam queryParam = new PqDevParam.QueryParam();
queryParam.setPlanIdList(Collections.singletonList(plan.getId()));
List<PqDevVO> pqDevVOS = pqDevService.listByPlanId(queryParam);
long checkedCount = pqDevVOS.stream().filter(pqDevVO -> pqDevVO.getCheckState().equals(CheckStateEnum.CHECKED.getValue())).count();
if (checkedCount == pqDevVOS.size()) {
plan.setTestState(CheckStateEnum.CHECKED.getValue());
this.updateById(plan);
}
}
}
PqDevParam.QueryParam queryParam = new PqDevParam.QueryParam();
queryParam.setPlanIdList(Collections.singletonList(plan.getId()));
List<PqDevVO> pqDevVOS = pqDevService.listByPlanId(queryParam);
boolean allUnchecked = pqDevVOS.stream().allMatch(pqDevVO -> CheckStateEnum.UNCHECKED.getValue().equals(pqDevVO.getCheckState()));
boolean allArchived = pqDevVOS.stream().allMatch(pqDevVO -> pqDevVO.getCheckState() != null && pqDevVO.getCheckState() >= CheckStateEnum.DOCUMENTED.getValue());
if (allUnchecked) {
plan.setTestState(CheckStateEnum.UNCHECKED.getValue());
} else if (allArchived && !pqDevVOS.isEmpty()) {
plan.setTestState(CheckStateEnum.CHECKED.getValue());
} else {
plan.setTestState(CheckStateEnum.CHECKING.getValue());
}
this.updateById(plan);
return true;
}
@@ -1906,7 +1911,9 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
pullDowns.add(pullDown);
// 报告模板
List<String> strings = this.baseMapper.listAllReportTemplateName();
List<String> strings = SpringUtil.getBean(IPqReportService.class).listOptions(patternId).stream()
.map(option -> option.getDisplayName())
.collect(Collectors.toList());
pullDown = new PullDown();
pullDown.setFirstCol(8);
pullDown.setLastCol(8);

View File

@@ -108,7 +108,7 @@ public class PqDevCheckHistoryServiceImpl extends ServiceImpl<PqDevCheckHistoryM
history.setManufacturer(device.getManufacturer());
history.setItemName(itemInfo.getItemName());
history.setResult(hasUnqualified ? 0 : 1);
history.setCheckTime(ObjectUtil.isNotNull(device.getCheckTime()) ? device.getCheckTime() : now);
history.setCheckTime(ObjectUtil.isNotNull(device.getCheckEndTime()) ? device.getCheckEndTime() : now);
history.setState(DataStateEnum.ENABLE.getCode());
history.setUpdateBy(device.getCheckBy());
history.setUpdateTime(now);

View File

@@ -75,7 +75,8 @@ public enum DetectionResponseEnum {
PLAN_REPEATED_IN_SAME_LEVEL("A02096", "该父计划下存在同名的子计划"),
PLEASE_UNASSIGN_STANDARD_DEV("A02097", "存在已分配给子计划的标准设备,请先解除分配"),
PLEASE_UNASSIGN_DEVICE("A02098", "存在已分配给计划的被检设备,请先解除分配"),
DEV_IP_PORT_EXIST("A02099", "存在重复被检设备");
DEV_IP_PORT_EXIST("A02099", "存在重复被检设备"),
PQDIF_NOT_EXIST("A02100", "PQDIF不存在");
private final String code;

View File

@@ -0,0 +1,94 @@
package com.njcn.gather.pqdif.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
import com.njcn.gather.pqdif.service.support.PqdifImportParser;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@Api(tags = "PQDIF管理")
@RestController
@RequestMapping("/pqdif")
@RequiredArgsConstructor
public class PqPqdifPathController extends BaseController {
private final IPqPqdifPathService pqPqdifPathService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/listAll")
@ApiOperation("获取全部PQDIF")
public HttpResult<List<PqPqdifPath>> listAll() {
String methodDescribe = getMethodDescribe("listAll");
List<PqPqdifPath> result = pqPqdifPathService.listAll();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo
@PostMapping("/list")
@ApiOperation("分页查询PQDIF")
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
public HttpResult<Page<PqPqdifPath>> list(@RequestBody @Validated PqPqdifPathParam.QueryParam param) {
String methodDescribe = getMethodDescribe("list");
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, param);
Page<PqPqdifPath> result = pqPqdifPathService.listPqdif(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@PostMapping("/import/json")
@ApiOperation("导入PQDIF json")
@ApiImplicitParam(name = "file", value = "json文件", required = true)
public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
String methodDescribe = getMethodDescribe("importJson");
LogUtil.njcnDebug(log, "{},导入文件为:{}", methodDescribe, file == null ? null : file.getOriginalFilename());
List<PqPqdifPathParam.ImportItem> items = parseImportItems(file);
boolean result = pqPqdifPathService.importPqdif(items);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
private List<PqPqdifPathParam.ImportItem> parseImportItems(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new BusinessException(PqdifResponseEnum.JSON_FILE_NOT_NULL);
}
String fileName = file.getOriginalFilename();
if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
}
try {
return PqdifImportParser.parse(new String(file.getBytes(), StandardCharsets.UTF_8));
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
}
}
}

View File

@@ -0,0 +1,12 @@
package com.njcn.gather.pqdif.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface PqPqdifPathMapper extends MPJBaseMapper<PqPqdifPath> {
List<PqPqdifPath> selectPageList(Page<PqPqdifPath> page, @Param("name") String name, @Param("result") Integer result);
}

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.pqdif.mapper.PqPqdifPathMapper">
<select id="selectPageList" resultType="com.njcn.gather.pqdif.pojo.po.PqPqdifPath">
select id,
Name as name,
File_Path as filePath,
Record_Count as recordCount,
Observation_Count as observationCount,
Sample_Value_Count as sampleValueCount,
Result as result,
Msg as msg,
State as state,
Create_By as createBy,
Create_Time as createTime,
Update_By as updateBy,
Update_Time as updateTime
from pq_pqdif_path
where State = 1
<if test="name != null and name != ''">
and Name like concat('%', #{name}, '%')
</if>
<if test="result != null">
and Result = #{result}
</if>
order by Update_Time desc, Create_Time desc
</select>
</mapper>

View File

@@ -0,0 +1,20 @@
package com.njcn.gather.pqdif.pojo.enums;
import lombok.Getter;
@Getter
public enum PqdifResponseEnum {
JSON_FILE_NOT_NULL("A019001", "JSON文件不能为空"),
JSON_FORMAT_ERROR("A019002", "JSON格式错误"),
IMPORT_ITEM_NOT_NULL("A019003", "导入数据项不能为空"),
IMPORT_ID_REPEAT("A019004", "导入数据中存在重复id"),
IMPORT_FAILED("A019005", "PQDIF导入失败");
private final String code;
private final String message;
PqdifResponseEnum(String code, String message) {
this.code = code;
this.message = message;
}
}

View File

@@ -0,0 +1,38 @@
package com.njcn.gather.pqdif.pojo.param;
import com.njcn.web.pojo.param.BaseParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
public class PqPqdifPathParam {
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty(value = "name")
private String name;
@ApiModelProperty(value = "result")
private Integer result;
}
@Data
public static class ImportItem {
private String id;
private String name;
private String filePath;
private Long recordCount;
private Long observationCount;
private Integer sampleValueCount;
private Integer result;
private String msg;
private Integer state;
private Object parseResult;
private String createBy;
private String createTime;
private String updateBy;
private String updateTime;
}
}

View File

@@ -0,0 +1,41 @@
package com.njcn.gather.pqdif.pojo.po;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.mybatisplus.bo.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("pq_pqdif_path")
public class PqPqdifPath extends BaseEntity implements Serializable {
private static final long serialVersionUID = 2536904714178389110L;
private String id;
private String name;
@TableField("File_Path")
private String filePath;
@TableField("Record_Count")
private Long recordCount;
@TableField("Observation_Count")
private Long observationCount;
@TableField("Sample_Value_Count")
private Integer sampleValueCount;
@TableField("Result")
private Integer result;
@TableField("Msg")
private String msg;
@TableField("State")
private Integer state;
}

View File

@@ -0,0 +1,16 @@
package com.njcn.gather.pqdif.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import java.util.List;
public interface IPqPqdifPathService extends IService<PqPqdifPath> {
List<PqPqdifPath> listAll();
Page<PqPqdifPath> listPqdif(PqPqdifPathParam.QueryParam param);
boolean importPqdif(List<PqPqdifPathParam.ImportItem> items);
}

View File

@@ -0,0 +1,114 @@
package com.njcn.gather.pqdif.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.pojo.constant.DetectionValidMessage;
import com.njcn.gather.pqdif.mapper.PqPqdifPathMapper;
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
import com.njcn.web.factory.PageFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Slf4j
@Service
public class PqPqdifPathServiceImpl extends ServiceImpl<PqPqdifPathMapper, PqPqdifPath> implements IPqPqdifPathService {
@Override
public List<PqPqdifPath> listAll() {
return this.lambdaQuery()
.select(PqPqdifPath::getId, PqPqdifPath::getName)
.eq(PqPqdifPath::getState, DataStateEnum.ENABLE.getCode())
.orderByDesc(PqPqdifPath::getCreateTime)
.list();
}
@Override
public Page<PqPqdifPath> listPqdif(PqPqdifPathParam.QueryParam param) {
Page<PqPqdifPath> page = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param));
page.setRecords(this.baseMapper.selectPageList(page, StrUtil.trim(param.getName()), param.getResult()));
return page;
}
@Override
@Transactional
public boolean importPqdif(List<PqPqdifPathParam.ImportItem> items) {
if (CollUtil.isEmpty(items)) {
return true;
}
validateItems(items);
for (PqPqdifPathParam.ImportItem item : items) {
PqPqdifPath entity = toEntity(item);
boolean saved = this.saveOrUpdate(entity);
if (!saved) {
throw new BusinessException(PqdifResponseEnum.IMPORT_FAILED);
}
}
return true;
}
private void validateItems(List<PqPqdifPathParam.ImportItem> items) {
Set<String> ids = new HashSet<>();
for (PqPqdifPathParam.ImportItem item : items) {
if (item == null) {
throw new BusinessException(PqdifResponseEnum.IMPORT_ITEM_NOT_NULL);
}
String id = StrUtil.trim(item.getId());
if (StrUtil.isBlank(id)) {
throw new BusinessException(DetectionValidMessage.ID_NOT_BLANK);
}
if (!ReUtil.isMatch(PatternRegex.SYSTEM_ID, id)) {
throw new BusinessException(DetectionValidMessage.ID_FORMAT_ERROR);
}
if (!ids.add(id)) {
throw new BusinessException(PqdifResponseEnum.IMPORT_ID_REPEAT);
}
if (StrUtil.isBlank(item.getName())) {
throw new BusinessException(DetectionValidMessage.NAME_NOT_BLANK);
}
}
}
private PqPqdifPath toEntity(PqPqdifPathParam.ImportItem item) {
PqPqdifPath entity = new PqPqdifPath();
entity.setId(StrUtil.trim(item.getId()));
entity.setName(StrUtil.trim(item.getName()));
entity.setFilePath(StrUtil.trim(item.getFilePath()));
entity.setRecordCount(item.getRecordCount());
entity.setObservationCount(item.getObservationCount());
entity.setSampleValueCount(item.getSampleValueCount());
entity.setResult(item.getResult());
entity.setMsg(item.getMsg());
entity.setState(item.getState() == null ? DataStateEnum.ENABLE.getCode() : item.getState());
entity.setCreateBy(StrUtil.trim(item.getCreateBy()));
entity.setUpdateBy(StrUtil.trim(item.getUpdateBy()));
entity.setCreateTime(parseDateTime(item.getCreateTime()));
entity.setUpdateTime(parseDateTime(item.getUpdateTime()));
return entity;
}
private LocalDateTime parseDateTime(String value) {
if (StrUtil.isBlank(value)) {
return null;
}
try {
return LocalDateTime.parse(StrUtil.trim(value));
} catch (Exception ex) {
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
}
}
}

View File

@@ -0,0 +1,52 @@
package com.njcn.gather.pqdif.service.support;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
import java.util.ArrayList;
import java.util.List;
public final class PqdifImportParser {
private PqdifImportParser() {
}
public static List<PqPqdifPathParam.ImportItem> parse(String content) {
try {
JSONArray jsonArray = JSON.parseArray(content);
if (jsonArray == null) {
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
}
List<PqPqdifPathParam.ImportItem> items = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject == null) {
throw new BusinessException(PqdifResponseEnum.IMPORT_ITEM_NOT_NULL);
}
PqPqdifPathParam.ImportItem item = jsonObject.toJavaObject(PqPqdifPathParam.ImportItem.class);
Object msg = jsonObject.get("msg");
item.setMsg(normalizeMsg(msg));
items.add(item);
}
return items;
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
}
}
private static String normalizeMsg(Object msg) {
if (msg == null) {
return null;
}
if (msg instanceof String) {
return (String) msg;
}
return JSON.toJSONString(msg);
}
}

View File

@@ -134,11 +134,12 @@ public class ReportController extends BaseController {
}
@OperateInfo
@GetMapping("/listAllName")
@GetMapping("/listOptions")
@ApiOperation("查询所有报告模板名称")
public HttpResult<List<String>> listAllName() {
String methodDescribe = getMethodDescribe("listAllName");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqReportService.listAllName(), methodDescribe);
public HttpResult<List<PqReportVO.OptionVO>> listOptions(@RequestParam("pattern") String pattern) {
String methodDescribe = getMethodDescribe("listOptions");
LogUtil.njcnDebug(log, "{}锛屾煡璇㈠弬鏁颁负锛歿}", methodDescribe, pattern);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqReportService.listOptions(pattern), methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)

View File

@@ -2,18 +2,17 @@ package com.njcn.gather.report.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.report.pojo.po.PqReport;
import com.njcn.gather.report.pojo.vo.PqReportVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author makejava
* @date 2025-03-19
*/
public interface PqReportMapper extends MPJBaseMapper<PqReport> {
/**
* 获取所有已被计划绑定的报告模板id
* @return
*/
List<String> getBoundReportIds();
}
List<PqReportVO.OptionVO> listOptionsByPattern(@Param("pattern") String pattern);
}

View File

@@ -2,9 +2,19 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.report.mapper.PqReportMapper">
<select id="getBoundReportIds" resultType="java.lang.String">
select distinct Report_Template_Id from ad_plan where state = 1
</select>
</mapper>
<select id="listOptionsByPattern" resultType="com.njcn.gather.report.pojo.vo.PqReportVO$OptionVO">
select
id,
name,
version,
concat(name, '_', version) as displayName
from pq_report
where state = 1
and pattern = #{pattern}
order by update_time desc
</select>
</mapper>

View File

@@ -0,0 +1,68 @@
package com.njcn.gather.report.pojo.constant;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* "指标锚点"新型模板的书签命名空间常量。
* 设计文档docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §3.1
*
* @author hongawen
*/
public interface ItemAnchorConstant {
/** 数据锚点书签前缀item_{scriptCode},锚点处按回路插入检测数据表 */
String ITEM_PREFIX = "item_";
/** 区段书签前缀sect_{scriptCode} / sect_{GRP_XXX},指标无数据时整段删除 */
String SECT_PREFIX = "sect_";
/**
* 父节 → 子节 scriptCode 映射;一个父节的全部子节都隐藏时,父节(组标题+组内公共文字)一并隐藏。
* key 与模板中 sect_GRP_* 书签名的 GRP_* 部分一致。
*/
Map<String, List<String>> GRP_CHILDREN = buildGrpChildren();
/**
* 已知指标 scriptCode 白名单(规范大写,即云南模板 11 个锚点)。
* 分流与锚点解析以此为准:白名单外的 item_* 书签一律视为无效,防止老模板中
* 作者手工遗留的同前缀书签(如 item_1把整份报告误路由进新路径。
*/
Set<String> KNOWN_SCRIPT_CODES = buildKnownScriptCodes();
static Map<String, List<String>> buildGrpChildren() {
Map<String, List<String>> map = new LinkedHashMap<>();
map.put("GRP_FUND", Arrays.asList("V", "I", "P", "ANGLE"));
map.put("GRP_UNB", Arrays.asList("IMBV", "IMBA"));
map.put("GRP_HARM", Arrays.asList("HV", "HI", "HP"));
return Collections.unmodifiableMap(map);
}
static Set<String> buildKnownScriptCodes() {
return Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(
"V", "I", "P", "ANGLE", "FREQ", "F", "IMBV", "IMBA", "HV", "HI", "HP")));
}
/**
* 从书签名解析指标锚点的 scriptCode。
*
* @param bookmarkName 书签名
* @return 规范大写 scriptCodescriptMap / 模板 H5 分组 key 均为大写);
* 非 item_ 前缀、空 code 或不在 {@link #KNOWN_SCRIPT_CODES} 白名单内返回 null
*/
static String resolveItemScriptCode(String bookmarkName) {
if (bookmarkName == null || bookmarkName.length() <= ITEM_PREFIX.length()) {
return null;
}
if (!bookmarkName.substring(0, ITEM_PREFIX.length()).equalsIgnoreCase(ITEM_PREFIX)) {
return null;
}
String code = bookmarkName.substring(ITEM_PREFIX.length()).toUpperCase();
return KNOWN_SCRIPT_CODES.contains(code) ? code : null;
}
}

View File

@@ -12,18 +12,32 @@ import lombok.Getter;
public enum AffectEnum {
BASE("base", "额定工作条件下的检测"),
VOL("vol", "电压对XX测量的影响"),
FREQ("freq", "频率对XX测量的影响"),
HARM("harm", "谐波对XX测量的影响");
// 第三个参数 sort 为报告小节排序档位:额定=1、单影响量=2、多影响量=3同档内再按 Script_Index 升序)
BASE("Base", "额定条件XX准确度测试", 1),
VOL("VOL", "电压幅值对XX测量的影响", 2),
FREQ("Freq", "频率变化对XX测量的影响", 2),
HARM("Harm", "谐波对XX测量的影响", 2),
// Single / Many 是检测树的分组标题,不会作为叶子 Script_SubType 落到设备数据上
SINGLE("Single", "单影响量下XX准确度测试", 2),
MANY("Many", "多影响量下XX准确度测试", 3),
// 以下为真实的多影响量组合 Script_SubType报告与检测树共用同一份文案
MANY_VOL_HARM_INHARM("Many-Vol-Harm-InHarm", "电压和谐波和间谐波对XX的影响", 3),
MANY_IMBV_HARM_INHARM("Many-IMBV-Harm-InHarm", "三项电压不平衡和谐波和间谐波对XX的影响", 3),
MANY_FREQ_HARM_INHARM("Many-Freq-Harm-InHarm", "频率和谐波和间谐波对XX的影响", 3);
private String key;
private String desc;
AffectEnum(String key, String desc) {
/**
* 报告小节排序档位:额定=1、单影响量=2、多影响量=3同档内再按 Script_Index 升序
*/
private int sort;
AffectEnum(String key, String desc, int sort) {
this.key = key;
this.desc = desc;
this.sort = sort;
}
/**

View File

@@ -17,19 +17,24 @@ public enum BaseReportKeyEnum {
DEV_TYPE("devType","设备型号、规格"),
DEV_CODE("createId","装置编号"),
DEV_NAME("devName","装置名称"),
POWER("power","工作电源"),
DEV_CURR("devCurr","额定电流"),
DEV_VOLT("devVolt","额定电压"),
SOURCE_NAME("sourceName","检测源名称"),
COUNT("count","通道数"),
MANUFACTURER("manufacturer","设备厂家、制造厂商"),
SAMPLE_ID("sampleId","样品编号"),
ARRIVED_DATE("arrivedDate","收样日期"),
ARRIVED_DATE_C("arrivedDateC","收样日期"),
TEST_DATE("testDate","检测日期"),
TEST_DATE_C("testDateC","检测日期"),
INSPECTOR("inspector","检测员"),
YEAR("year","年份"),
MONTH("month","月份"),
DAY("day",""),
YEAR_MONTH_DAY("year-month-day","年-月-日"),
YEAR_MONTH_DAY_UP("year-month-day-up","中文数字 年-月-日"),
REPORT_DATE("reportDate","年-月-日"),
GD_NAME("gdName","供电部门"),
SUB_NAME("subName","变电站"),

View File

@@ -45,7 +45,34 @@ public enum ItemReportKeyEnum {
RESULT_B("resultB", "结论 比如:合格/不合格"),
RESULT_C("resultC", "结论 比如:合格/不合格"),
RESULT_MAG("resultMag", "特征幅值结论 比如:合格/不合格"),
RESULT_DUR("resultDur", "持续时间结论 比如:合格/不合格");
RESULT_DUR("resultDur", "持续时间结论 比如:合格/不合格"),
// ===== 以下为"指标锚点"新型模板(云南检定报告)新增 key见 docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §5 =====
STANDARD_V("standardV", "P表基波电压设置值"),
STANDARD_I("standardI", "P表基波电流设置值"),
STANDARD_U_ANGLE("standardUAngle", "P表电压相角设置值"),
STANDARD_I_ANGLE("standardIAngle", "P表电流相角设置值"),
ACTIVE_POWER("activePower", "P表有功功率实测值三相之和"),
REACTIVE_POWER("reactivePower", "P表无功功率实测值数据侧暂无留空"),
APPARENT_POWER("apparentPower", "P表视在功率实测值数据侧暂无留空"),
POWER_FACTOR("powerFactor", "P表功率因数实测值数据侧暂无留空"),
POS_SEQ("posSeq", "不平衡表:基波正序(数据侧暂无,留空)"),
NEG_SEQ("negSeq", "不平衡表:基波负序(数据侧暂无,留空)"),
ZERO_SEQ("zeroSeq", "不平衡表:基波零序(数据侧暂无,留空)"),
BASE_CURRENT_A("baseCurrentA", "HI表A相基波电流幅值用于计算谐波电流含有率"),
BASE_CURRENT_B("baseCurrentB", "HI表B相基波电流幅值用于计算谐波电流含有率"),
BASE_CURRENT_C("baseCurrentC", "HI表C相基波电流幅值用于计算谐波电流含有率"),
STANDARD_RATE("standardRate", "HI表标准源输出含有率"),
TEST_RATE_A("testRateA", "HI表A相谐波电流含有率"),
TEST_RATE_B("testRateB", "HI表B相谐波电流含有率"),
TEST_RATE_C("testRateC", "HI表C相谐波电流含有率"),
ERROR_RATE_A("errorRateA", "HI表A相谐波电流含有率误差"),
ERROR_RATE_B("errorRateB", "HI表B相谐波电流含有率误差"),
ERROR_RATE_C("errorRateC", "HI表C相谐波电流含有率误差"),
STANDARD_THD("standardThd", "HV/HI表标准源总谐波畸变率"),
THD_A("thdA", "HV/HI表A相总谐波畸变率"),
THD_B("thdB", "HV/HI表B相总谐波畸变率"),
THD_C("thdC", "HV/HI表C相总谐波畸变率");
private String key;

View File

@@ -4,6 +4,7 @@ import lombok.Getter;
/**
* 电能质量测试大项枚举
*
* @author hongawen
* @version 1.0
* @data 2025/3/27 18:29
@@ -13,21 +14,21 @@ public enum PowerIndexEnum {
UNKNOWN("UNKNOWN", "未知指标"),
FREQ("FREQ", "频率"),
LINE_TITLE("LINE_TITLE", "测量回路"),
FREQ("FREQ", "频率"),
V("V", "电压"),
I("I", "电流"),
P("P", "功率"),
IMBV("IMBV", "负序电压不平衡度"),
IMBA("IMBA", "负序电流不平衡度"),
F("F", "短时电压闪变"),
HP("HP", "谐波有功功率"),
HV("HV", "谐波电压"),
HI("HI", "谐波电流"),
HP("HP", "谐波有功功率"),
HSV("HSV", "间谐波电压"),
HSI("HSI", "间谐波电流"),
VOLTAGE("VOLTAGE", "电压暂降、暂升及短时中断"),
PST("PST", "短时间闪变");
I("I", "电流"),
IMBV("IMBV", "负序电压不平衡度"),
IMBA("IMBA", "负序电流不平衡度"),
F("F", "短时电压闪变"),
P("P", "功率"),
ANGLE("Angle", "基波相位");
private String key;

View File

@@ -6,10 +6,6 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.web.multipart.MultipartFile;
/**
* @author caozehui
* @data 2025-03-19
*/
@Data
public class ReportParam {
@@ -19,23 +15,29 @@ public class ReportParam {
@ApiModelProperty(value = "版本号", required = true)
private String version;
@ApiModelProperty(value = "模式id", required = true)
private String pattern;
@ApiModelProperty(value = "描述信息", required = true)
private String description;
@ApiModelProperty(value = "基础模板文件", required = true)
private MultipartFile baseFile;
@ApiModelProperty(value = "检测项模文件", required = true)
@ApiModelProperty(value = "检测项模文件", required = true)
private MultipartFile detailFile;
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty(value = "报告模板名称", required = true)
@ApiModelProperty(value = "报告模板名称")
private String name;
@ApiModelProperty(value = "版本号", required = true)
@ApiModelProperty(value = "版本号")
private String version;
@ApiModelProperty(value = "模式id", required = true)
private String pattern;
}
@Data

View File

@@ -6,17 +6,13 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @author makejava
* @date 2025-03-19
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("pq_report")
public class PqReport extends BaseEntity implements Serializable {
private static final long serialVersionUID = 582972970946593407L;
/**
* 报告模板id
*/
@@ -32,13 +28,18 @@ public class PqReport extends BaseEntity implements Serializable {
*/
private String version;
/**
* 模式id
*/
private String pattern;
/**
* 基础模板文件路径
*/
private String basePath;
/**
* 检测项模文件路径
* 检测项模文件路径
*/
private String detailPath;
@@ -52,4 +53,3 @@ public class PqReport extends BaseEntity implements Serializable {
*/
private Integer state;
}

View File

@@ -9,60 +9,42 @@ import lombok.Data;
import java.time.LocalDateTime;
/**
* @author caozehui
* @data 2025-03-19
*/
@Data
public class PqReportVO {
/**
* 报告模板id
*/
private String id;
/**
* 报告模板名称
*/
private String name;
/**
* 版本号
*/
private String version;
private String pattern;
/**
* 基础模板文件路径
*/
private FileVO baseFileVO;
/**
* 检测项模版文件路径
*/
private FileVO detailFileVO;
/**
* 描述信息
*/
private String description;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createTime;
/**
* 状态0-删除 1-正常
*/
//private Integer state;
@Data
public static class FileVO{
public static class FileVO {
private String name;
private String url;
}
@Data
public static class OptionVO {
private String id;
private String name;
private String version;
private String displayName;
}
}

View File

@@ -55,19 +55,12 @@ public interface IPqReportService extends IService<PqReport> {
*/
boolean delete(List<String> ids);
/**
* 查询所有报告名称
*
* @return key为报告idvalue为报告名称
*/
List<String> listAllName();
List<PqReportVO.OptionVO> listOptions(String pattern);
void generateReport(DevReportParam devReportParam);
void downloadReport(DevReportParam devReportParam, HttpServletResponse response);
/**
* 设备归档操作
*
@@ -82,5 +75,4 @@ public interface IPqReportService extends IService<PqReport> {
* @param deviceIds 被检设备ID列表为空时上传所有已生成报告的设备
*/
void uploadReportToCloud(List<String> deviceIds);
}

View File

@@ -19,6 +19,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.images.ImageConverter;
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
@@ -46,10 +47,12 @@ import com.njcn.gather.plan.pojo.enums.PlanReportStateEnum;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.plan.service.IAdPlanSourceService;
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.mapper.PqReportMapper;
import com.njcn.gather.report.pojo.DevReportParam;
import com.njcn.gather.report.pojo.constant.ItemAnchorConstant;
import com.njcn.gather.report.pojo.constant.PowerConstant;
import com.njcn.gather.report.pojo.enums.*;
import com.njcn.gather.report.pojo.param.ReportParam;
@@ -58,9 +61,12 @@ import com.njcn.gather.report.pojo.result.ContrastTestResult;
import com.njcn.gather.report.pojo.result.SingleTestResult;
import com.njcn.gather.report.pojo.vo.PqReportVO;
import com.njcn.gather.report.service.IPqReportService;
import com.njcn.gather.report.util.ItemAnchorAssembler;
import com.njcn.gather.report.util.ItemAnchorSectionUtil;
import com.njcn.gather.result.service.IResultService;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.source.pojo.po.PqSource;
import com.njcn.gather.storage.pojo.param.SingleNonHarmParam;
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
@@ -114,6 +120,7 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@@ -141,6 +148,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
* 的真实业务取值撞车。
*/
private static final String RESULT_MAP_NO_DATA_FLAG = "__internal_no_data__";
private static final String[] CHINESE_DIGITS = {"O", "", "", "", "", "", "", "", "", ""};
// @Value("${report.template:D:\\template}")
// private String templatePath;
@@ -184,6 +192,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
private final IPqDevSubService iPqDevSubService;
private final IDictDataService dictDataService;
private final IAdPlanService adPlanService;
private final IAdPlanSourceService adPlanSourceService;
private final IPqScriptDtlsService pqScriptDtlsService;
private final SimAndDigNonHarmonicService adNonHarmonicService;
private final SimAndDigHarmonicService adHarmonicService;
@@ -206,6 +215,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
QueryWrapper<PqReport> wrapper = new QueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "name", queryParam.getName())
.eq(StrUtil.isNotBlank(queryParam.getVersion()), "version", queryParam.getVersion())
.eq("pattern", queryParam.getPattern())
.eq("state", DataStateEnum.ENABLE.getCode());
wrapper.orderByDesc("Update_Time");
Page<PqReport> page1 = this.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), wrapper);
@@ -307,11 +317,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
@Override
public List<String> listAllName() {
List<PqReport> reportList = this.lambdaQuery()
.eq(PqReport::getState, DataStateEnum.ENABLE.getCode()).list();
List<String> collect = reportList.stream().map(pqReport -> pqReport.getName() + "_" + pqReport.getVersion()).collect(Collectors.toList());
return collect;
public List<PqReportVO.OptionVO> listOptions(String pattern) {
return this.baseMapper.listOptionsByPattern(pattern);
}
/**
@@ -324,7 +331,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
private void uploadFile(ReportParam reportParam, PqReport pqReport, boolean isAdd) {
MultipartFile baseFile = reportParam.getBaseFile();
MultipartFile detailFile = reportParam.getDetailFile();
String relativePath = reportParam.getName() + File.separator + reportParam.getVersion() + File.separator;
String relativePath = this.buildReportTemplateRelativeDir(reportParam.getPattern(), reportParam.getName(), reportParam.getVersion());
String newDir = pathConfig.getReportTemplatePath() + File.separator + relativePath;
long FILE_SIZE_LIMIT = 5 * 1024 * 1024;
@@ -858,6 +865,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
Docx4jUtil.addWatermarkToDocument(baseModelDocument, "非正式");
}
Docx4jUtil.cleanBlankPagesAndRedundantPageBreaks(baseModelDocument);
Docx4jUtil.enableUpdateFieldsOnOpen(baseModelDocument);
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(fileName)));
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
} catch (NoSuchFileException e) {
@@ -914,18 +922,31 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
// 获取文档基础部分,并替换占位符
Map<String, String> baseModelDataMap = dealBaseModelData(pqDevVO, devType);
// 补充检测源名称:计划↔源走 ad_plan_source 中间表业务上单源datasourceId 是数据源类型枚举、不指向 pq_source
List<PqSource> planSources = adPlanSourceService.listPqSourceByPlanId(plan.getId());
baseModelDataMap.put(BaseReportKeyEnum.SOURCE_NAME.getKey(),
CollUtil.isNotEmpty(planSources) ? planSources.get(0).getName() : StrUtil.EMPTY);
InputStream wordFinishInputStream = wordReportService.replacePlaceholders(baseInputStream, baseModelDataMap);
WordprocessingMLPackage baseModelDocument = WordprocessingMLPackage.load(wordFinishInputStream);
MainDocumentPart baseDocumentPart = baseModelDocument.getMainDocumentPart();
// 获取数据模版页内容,根据脚本动态组装数据页内容
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
// 新旧模板分流base 含白名单内 item_ 前缀书签 → 指标锚点新型模板(云南检定报告类),走独立旁路;
// 否则走原路径,行为与改动前完全一致。设计文档 specs/2026-07-02-item-anchor-report-template-design.md §4.1
// 书签全文档扫描只做一次,分流判断与新路径共用;老路径方法签名不动,内部自扫
List<BookmarkUtil.BookmarkInfo> baseBookmarks = BookmarkUtil.findAllBookmarks(baseDocumentPart);
if (hasItemAnchor(baseBookmarks)) {
dealDataModelByItemAnchor(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO, baseBookmarks);
} else {
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
}
// 保存新的文档
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName()));
// 确保目录存在
ensureDirectoryExists(dirPath);
Docx4jUtil.enableUpdateFieldsOnOpen(baseModelDocument);
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX)));
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
} catch (NoSuchFileException e) {
@@ -1223,6 +1244,131 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
/**
* 判断 base 文档是否为"指标锚点"新型模板(含任一白名单内 item_ 前缀书签)。
* 白名单校验在 resolveItemScriptCode 内:老模板中手工遗留的同前缀书签(如 item_1
* 不会触发新路径,避免整份报告错路由导致 DATA_LINE / TEST_RESULT_* 全不填。
*
* @param bookmarks base 文档书签集合(调用方已扫,避免全文档重复扫描)
*/
private boolean hasItemAnchor(List<BookmarkUtil.BookmarkInfo> bookmarks) {
for (BookmarkUtil.BookmarkInfo info : bookmarks) {
if (ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName()) != null) {
return true;
}
}
return false;
}
/**
* "指标锚点"新型模板装配(云南检定报告类)。
* 流程:逐 item_* 锚点 → detail 池取 H5 模板表 → 按回路构造成品表插入锚点;
* 无数据/无模板的指标记入隐藏集合 → 区段删除 → 第 7 节编号重排 → 残留书签清理。
* 设计文档docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2
*/
private void dealDataModelByItemAnchor(MainDocumentPart baseDocumentPart, MainDocumentPart detailDocumentPart,
DevReportParam devReportParam, PqDevVO pqDevVO,
List<BookmarkUtil.BookmarkInfo> bookmarks) {
ObjectFactory factory = new ObjectFactory();
// 检测脚本明细按 scriptCode 分组
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream()
.collect(Collectors.groupingBy(item -> itemAnchorGroupKey(item.getScriptCode()), LinkedHashMap::new, Collectors.toList()));
// detail 模板池按 H5 分组
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(detailDocumentPart.getContent(), detailDocumentPart);
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream()
.collect(Collectors.groupingBy(item -> itemAnchorGroupKey(item.getHeadingText()), LinkedHashMap::new, Collectors.toList()));
int devChns = pqDevVO.getDevChns() == null ? 1 : pqDevVO.getDevChns();
Set<String> hiddenCodes = new LinkedHashSet<>();
for (BookmarkUtil.BookmarkInfo info : bookmarks) {
String scriptCode = ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName());
if (scriptCode == null) {
// 新路径按设计忽略老锚点互斥分流spec §4.1);发现 BookmarkEnum 残留提示模板可能混用
if (Objects.nonNull(BookmarkEnum.getByKey(info.bookmark.getName()))) {
log.warn("指标锚点模板中发现老模板锚点书签 {},新路径不处理该书签", info.bookmark.getName());
}
continue;
}
List<PqScriptDtlDataVO> itemDtls = scriptMap.get(scriptCode);
List<Docx4jUtil.HeadingContent> tpl = contentMap.get(scriptCode);
if (CollUtil.isEmpty(itemDtls) || CollUtil.isEmpty(tpl)) {
log.warn("指标锚点 {} 无脚本数据或无模板分组,整节隐藏", info.bookmark.getName());
hiddenCodes.add(scriptCode);
continue;
}
List<String> tableKeys = ItemAnchorAssembler.extractTableKeys(tpl);
// 有脚本明细且模板分组在keys 仍取不到属模板错误 → 显性中断,不得静默走"未测→整节隐藏"
ItemAnchorAssembler.requireTableKeys(scriptCode, tableKeys);
List<Object> todoInsertList = new ArrayList<>();
for (int line = 0; line < devChns; line++) {
List<SingleTestResult> results = new ArrayList<>();
if (PowerConstant.TIME.contains(scriptCode)) {
// 谐波类:一个 scriptIndex 一张表(与老路径语义一致)
Map<Integer, List<PqScriptDtlDataVO>> scriptIndexMap = itemDtls.stream()
.collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptIndex, TreeMap::new, Collectors.toList()));
for (List<PqScriptDtlDataVO> indexItem : scriptIndexMap.values()) {
SingleTestResult single = resultService.getFinalContent(indexItem, devReportParam.getPlanCode(), pqDevVO.getId(), line + 1, tableKeys);
if (Objects.nonNull(single)) {
results.add(single);
}
}
} else {
SingleTestResult single = resultService.getFinalContent(itemDtls, devReportParam.getPlanCode(), pqDevVO.getId(), line + 1, tableKeys);
if (Objects.nonNull(single)) {
results.add(single);
}
}
List<Object> lineTables = ItemAnchorAssembler.buildTables(scriptCode, results, tpl.get(0), tableKeys, factory);
if (lineTables.isEmpty()) {
// 该回路无数据,跳过;是否整节隐藏由所有回路汇总后判断
continue;
}
// 回路标题:单回路省略;多回路"测量回路{n}"从 1 起spec §4.2
if (devChns > 1) {
todoInsertList.add(buildItemLineTitle(contentMap, line, factory));
}
todoInsertList.addAll(lineTables);
}
if (todoInsertList.isEmpty()) {
log.warn("指标 {} 所有回路均无检测数据,整节隐藏", scriptCode);
hiddenCodes.add(scriptCode);
continue;
}
BookmarkUtil.insertElement(info, todoInsertList);
// 已填充节不再需要 item/sect 标记:空锚点段直接删除,避免表格前残留空行;
// 若未来模板把锚点放进非空段,则只清书签保留段落正文。
if (!ItemAnchorSectionUtil.removeEmptyItemAnchorParagraph(info)) {
BookmarkUtil.removeBookmark(info);
}
}
ItemAnchorSectionUtil.removeSectRanges(baseDocumentPart, hiddenCodes);
ItemAnchorSectionUtil.renumberChapter7(baseDocumentPart);
ItemAnchorSectionUtil.stripItemAnchorBookmarks(baseDocumentPart);
}
private static String itemAnchorGroupKey(String value) {
return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
}
/**
* 新型模板的回路标题(仅多回路时被调用):"测量回路{n}"n 从 1 起。
* 与老路径 getLineTitle 的差异(有意):不带 "n." 前缀、单回路由调用方直接省略。
*/
private P buildItemLineTitle(Map<String, List<Docx4jUtil.HeadingContent>> contentMap, int lineIndex, ObjectFactory factory) {
int lineNo = lineIndex + 1;
P titleParagraph = factory.createP();
PPr pPr = factory.createPPr();
PPrBase.Spacing spacing = factory.createPPrBaseSpacing();
spacing.setBefore(BigInteger.valueOf(60));
spacing.setAfter(BigInteger.valueOf(20));
spacing.setLine(BigInteger.valueOf(240));
spacing.setLineRule(STLineSpacingRule.AUTO);
pPr.setSpacing(spacing);
titleParagraph.setPPr(pPr);
Docx4jUtil.createTitle(factory, titleParagraph, "测量回路" + lineNo, 24, true);
return titleParagraph;
}
/**
* 通过提前在模板文档里埋下书签
* 1、目录信息
@@ -1270,6 +1416,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.DATA_LINE.getKey(), bookmarks);
todoInsertList = dealDataLine(detailDocumentPart, devReportParam, pqDevVO, resultMap);
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
// 锚点位于 base 模板中间(其后仍有有效内容)时,在数据块末尾补一个分页符,
// 让 base 剩余部分另起新页;锚点在文档末尾时不加,存量模板行为不变
if (hasContentAfterBookmark(bookmarkInfo)) {
todoInsertList.add(Docx4jUtil.getPageBreak());
}
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
BookmarkUtil.removeBookmark(bookmarkInfo);
}
@@ -1322,6 +1473,40 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
/**
* 判断书签段落之后是否还有有意义的内容(非空文本段落,或表格等非段落元素)。
* <p>
* 用于数模式 DATA_LINE 锚点位于 base 模板中间时,决定是否在插入的数据块末尾追加分页符,
* 使 base 剩余部分另起新页;书签在文档末尾(其后仅剩空段落)时返回 false不追加分页符
* 避免末尾凭空多出一页空白,存量模板(锚点在末尾)行为保持不变。
* <p>
* 注:仅以文本判断段落是否有意义,纯图片段落不会被识别为有效内容。
*
* @param bookmarkInfo 书签信息
* @return 书签之后存在有意义内容时返回 true
*/
private boolean hasContentAfterBookmark(BookmarkUtil.BookmarkInfo bookmarkInfo) {
List<Object> parentContent = bookmarkInfo.parentContainer.getContent();
int idx = parentContent.indexOf(bookmarkInfo.parentParagraph);
if (idx < 0) {
return false;
}
for (int i = idx + 1; i < parentContent.size(); i++) {
Object obj = parentContent.get(i);
Object realObj = (obj instanceof JAXBElement) ? ((JAXBElement<?>) obj).getValue() : obj;
if (realObj instanceof P) {
// 非空文本段落才算有意义,纯空段落不触发分页
if (StrUtil.isNotBlank(Docx4jUtil.getTextFromP((P) realObj))) {
return true;
}
} else {
// 表格等非段落元素一律视为有意义内容
return true;
}
}
return false;
}
/**
* 如何处理结果性数据进文档,各省级平台的结果表格不一致,如何做到一致
@@ -2035,7 +2220,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
queryParam.setPlanIdList(Arrays.asList(tempPqDevVO.getPlanId()));
List<PqDevVO> pqDevVOList1 = pqDevMapper.selectByQueryParam(queryParam);
long count = pqDevVOList1.stream().filter(obj -> !CheckStateEnum.DOCUMENTED.getValue().equals(obj.getCheckState())).count();
long count = pqDevVOList1.stream().filter(obj -> obj.getCheckState() == null || obj.getCheckState() < CheckStateEnum.DOCUMENTED.getValue()).count();
if (count == 0) {
// 如果非归档状态的设备数量为0则更新计划已完成
pqDevMapper.finishPlan(pqDevVO.getPlanId());
@@ -2078,13 +2263,14 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
// 软件版本
baseModelMap.put(BaseReportKeyEnum.SW_VERSION.getKey(), StrUtil.isNotBlank(pqDevVO.getSoftwareVersion()) ? pqDevVO.getSoftwareVersion() : StrUtil.EMPTY);
// 调试日期
if (pqDevVO.getCheckTime() != null) {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(pqDevVO.getCheckTime(), DatePattern.CHINESE_DATE_PATTERN));
if (pqDevVO.getCheckEndTime() != null) {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(pqDevVO.getCheckEndTime(), DatePattern.CHINESE_DATE_PATTERN));
} else {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
}
// 装置编码
baseModelMap.put(BaseReportKeyEnum.DEV_CODE.getKey(), pqDevVO.getCreateId());
baseModelMap.put(BaseReportKeyEnum.DEV_NAME.getKey(), StrUtil.isBlank(pqDevVO.getName()) ? StrPool.TAB : pqDevVO.getName());
// 工作电源
baseModelMap.put(BaseReportKeyEnum.POWER.getKey(), devType.getPower());
// 额定电流
@@ -2122,14 +2308,17 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
baseModelMap.put(BaseReportKeyEnum.SAMPLE_ID.getKey(), StrUtil.isEmpty(pqDevVO.getSampleId()) ? StrPool.TAB : pqDevVO.getSampleId());
// 收样日期
baseModelMap.put(BaseReportKeyEnum.ARRIVED_DATE.getKey(), Objects.isNull(pqDevVO.getArrivedDate()) ? StrPool.TAB : String.valueOf(pqDevVO.getArrivedDate()));
baseModelMap.put(BaseReportKeyEnum.ARRIVED_DATE_C.getKey(), Objects.isNull(pqDevVO.getArrivedDate()) ? StrPool.TAB : formatNumberChineseDate(pqDevVO.getArrivedDate()));
// 检测日期
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), Objects.isNull(pqDevVO.getCheckTime()) ? StrPool.TAB : String.valueOf(pqDevVO.getCheckTime()).substring(0, 10));
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), Objects.isNull(pqDevVO.getCheckEndTime()) ? StrPool.TAB : String.valueOf(pqDevVO.getCheckEndTime()).substring(0, 10));
baseModelMap.put(BaseReportKeyEnum.TEST_DATE_C.getKey(), Objects.isNull(pqDevVO.getCheckEndTime()) ? StrPool.TAB : formatNumberChineseDate(pqDevVO.getCheckEndTime().toLocalDate()));
baseModelMap.put(BaseReportKeyEnum.TEMPERATURE.getKey(), Objects.isNull(pqDevVO.getTemperature()) ? StrPool.TAB : pqDevVO.getTemperature().toString());
baseModelMap.put(BaseReportKeyEnum.HUMIDITY.getKey(), Objects.isNull(pqDevVO.getHumidity()) ? StrPool.TAB : pqDevVO.getHumidity().toString());
baseModelMap.put(BaseReportKeyEnum.YEAR.getKey(), DateUtil.format(new Date(), DatePattern.NORM_YEAR_PATTERN));
baseModelMap.put(BaseReportKeyEnum.MONTH.getKey(), DateUtil.format(new Date(), DatePattern.SIMPLE_MONTH_PATTERN).substring(4));
baseModelMap.put(BaseReportKeyEnum.DAY.getKey(), DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN).substring(6));
baseModelMap.put(BaseReportKeyEnum.YEAR_MONTH_DAY.getKey(), DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
baseModelMap.put(BaseReportKeyEnum.YEAR_MONTH_DAY_UP.getKey(), formatChineseReportDate(LocalDate.now()));
baseModelMap.put(BaseReportKeyEnum.REPORT_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
return baseModelMap;
}
@@ -2196,9 +2385,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
// 检测日期
PqDevSub devSub = iPqDevSubService.lambdaQuery().eq(PqDevSub::getDevId, pqDevVO.getId()).one();
if (Objects.nonNull(devSub)) {
LocalDateTime checkTime = devSub.getCheckTime();
if (Objects.nonNull(checkTime)) {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(checkTime, DatePattern.NORM_DATE_PATTERN));
LocalDateTime checkEndTime = devSub.getCheckEndTime();
if (Objects.nonNull(checkEndTime)) {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(checkEndTime, DatePattern.NORM_DATE_PATTERN));
} else {
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), StrPool.TAB);
}
@@ -2434,6 +2623,40 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
return String.format("%.4f", bp.setScale(i, RoundingMode.HALF_UP).doubleValue());
}
static String formatChineseReportDate(LocalDate date) {
Objects.requireNonNull(date, "date");
return formatChineseYear(date.getYear()) + ""
+ formatChineseMonthDayNumber(date.getMonthValue()) + ""
+ formatChineseMonthDayNumber(date.getDayOfMonth()) + "";
}
static String formatNumberChineseDate(LocalDate date) {
Objects.requireNonNull(date, "date");
return date.getYear() + "" + date.getMonthValue() + "" + date.getDayOfMonth() + "";
}
private static String formatChineseYear(int year) {
String yearValue = String.valueOf(year);
StringBuilder builder = new StringBuilder(yearValue.length());
for (int i = 0; i < yearValue.length(); i++) {
builder.append(CHINESE_DIGITS[yearValue.charAt(i) - '0']);
}
return builder.toString();
}
private static String formatChineseMonthDayNumber(int value) {
if (value < 10) {
return CHINESE_DIGITS[value];
}
if (value == 10) {
return "";
}
if (value < 20) {
return "" + CHINESE_DIGITS[value % 10];
}
return CHINESE_DIGITS[value / 10] + "" + (value % 10 == 0 ? "" : CHINESE_DIGITS[value % 10]);
}
private void ensureDirectoryExists(String directoryPath) {
File directory = new File(directoryPath);
@@ -2455,7 +2678,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
*/
private void checkRepeat(ReportParam reportParam, boolean isExcludeSelf) {
QueryWrapper<PqReport> wrapper = new QueryWrapper();
wrapper.eq("name", reportParam.getName())
wrapper.eq("pattern", reportParam.getPattern())
.eq("name", reportParam.getName())
.eq("version", reportParam.getVersion())
.eq("state", DataStateEnum.ENABLE.getCode());
if (isExcludeSelf) {
@@ -2469,6 +2693,21 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
}
private String sanitizePathSegment(String value) {
return StrUtil.blankToDefault(value, StrUtil.EMPTY).replaceAll("[\\\\/:*?\"<>|]", "_").trim();
}
private String buildReportTemplateRelativeDir(String patternId, String name, String version) {
DictData dictData = dictDataService.getDictDataById(patternId);
if (ObjectUtil.isNull(dictData) || StrUtil.isBlank(dictData.getName())) {
throw new BusinessException(CommonResponseEnum.FAIL, "模式不存在或字典名称缺失");
}
String patternName = this.sanitizePathSegment(dictData.getName());
String reportName = this.sanitizePathSegment(name);
String reportVersion = this.sanitizePathSegment(version);
return patternName + File.separator + reportName + File.separator + reportVersion + File.separator;
}
@Override
public void uploadReportToCloud(List<String> deviceIds) {
log.info("开始批量上传检测报告到云端设备ID列表{}", deviceIds);
@@ -2527,13 +2766,14 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
List<Docx4jUtil.HeadingContent> headingContents = contentMap.get(PowerIndexEnum.LINE_TITLE.getKey());
int lineNo = currentLine + 1;
// 如果contentMap中有指定内容创建大纲级别为2的标题
// 回路标题恒带回路号(单回路也显示"测量回路1"),与结论表头"测量回路N"保持一致
if (CollUtil.isNotEmpty(headingContents)) {
return Docx4jUtil.createTitle(factory, 2, totalLine > 1 ? lineNo + ".测量回路" + lineNo : lineNo + ".测量回路",
return Docx4jUtil.createTitle(factory, 2, lineNo + ".测量回路" + lineNo,
"SimSun", 30, true);
}
// 没有模板配置时,创建默认样式段落
P titleParagraph = factory.createP();
Docx4jUtil.createTitle(factory, titleParagraph, totalLine > 1 ? "测量回路" + lineNo : "测量回路",
Docx4jUtil.createTitle(factory, titleParagraph, "测量回路" + lineNo,
28, true);
return titleParagraph;
}

View File

@@ -0,0 +1,532 @@
package com.njcn.gather.report.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
import com.njcn.gather.report.pojo.result.SingleTestResult;
import com.njcn.gather.tools.report.util.Docx4jUtil;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RPr;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.TcPr;
import org.docx4j.wml.Text;
import org.docx4j.wml.Tr;
import org.docx4j.wml.TrPr;
import javax.xml.bind.JAXBElement;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* "指标锚点"模板的表格装配器:模板表(末行为 key 行)+ SingleTestResult → 成品表列表。
* 只服务新路径,不被老路径引用;对 Docx4jUtil 只调用不修改。
* 设计文档docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2 / §6
*
* @author hongawen
*/
public final class ItemAnchorAssembler {
private ItemAnchorAssembler() {
}
/**
* 构造成品表。results 每个有效元素产出一张表(谐波类调用方按 scriptIndex 拆分后传入)。
*
* @param scriptCode 指标编码P 走有功功率特例映射)
* @param results 检测结果列表null/空 detail 的元素跳过
* @param template detail 模板池中该指标的 H5 分组(取其中第一张表为模板)
* @param tableKeys key 行的占位符列表(调用方经 Docx4jUtil.getTableFillKeys 读出)
* @param factory docx4j 工厂
* @return 待插入锚点的表格元素列表JAXBElement&lt;Tbl&gt;
*/
@SuppressWarnings("unchecked")
public static List<Object> buildTables(String scriptCode, List<SingleTestResult> results,
Docx4jUtil.HeadingContent template, List<String> tableKeys,
ObjectFactory factory) {
List<Object> out = new ArrayList<>();
JAXBElement<Tbl> templateTbl = findFirstTable(template);
if (templateTbl == null || CollUtil.isEmpty(results) || CollUtil.isEmpty(tableKeys)) {
return out;
}
int tableNo = 0;
for (SingleTestResult result : results) {
List<Map<String, String>> rows = flattenRows(result, scriptCode);
if (rows.isEmpty()) {
continue;
}
tableNo++;
applyHarmonicDerivedValues(rows, scriptCode);
Map<String, String> fixedPlaceholders = buildHarmonicFixedPlaceholders(rows, scriptCode);
JAXBElement<Tbl> copied;
try {
copied = Docx4jUtil.deepCopyTbl(templateTbl);
} catch (Exception e) {
throw new RuntimeException("指标锚点模板表深拷贝失败: " + scriptCode, e);
}
Tbl tbl = copied.getValue();
replaceFixedPlaceholders(tbl, fixedPlaceholders);
applyHarmonicPowerHeader(tbl, scriptCode, tableNo, rows);
List<Object> trs = tbl.getContent();
// 模板规范约定:最后一行是 key 行(不走 judgeTableCross新路径自带定位依据
// 从尾部找最后一个真正的 Tr——Word 重存可能把 bookmarkStart/End 漏成 w:tbl 直接子节点(本仓 _GoBack 先例)
Tr keyRow = findLastRow(trs);
if (keyRow == null) {
throw new BusinessException("指标 " + scriptCode + " 的模板表无有效行,请检查 detail 模板该分组表格");
}
TrPr trPr = keyRow.getTrPr();
List<TcPr> tcPrList = new ArrayList<>();
RPr templateRPr = null;
for (Object cellObj : keyRow.getContent()) {
if (cellObj instanceof JAXBElement) {
Tc cell = ((JAXBElement<Tc>) cellObj).getValue();
TcPr tcPr = cell.getTcPr() != null ? cell.getTcPr() : factory.createTcPr();
// 注意:不覆写 tcW老 fill 的 5000/n 均分会破坏客户模板列宽),沿用模板原宽
tcPrList.add(tcPr);
if (templateRPr == null && !cell.getContent().isEmpty() && cell.getContent().get(0) instanceof P) {
templateRPr = Docx4jUtil.getTcPrFromParagraph((P) cell.getContent().get(0));
}
}
}
trs.remove(keyRow);
for (Map<String, String> row : rows) {
// 缺失 key 一律补空串:"拿不到的先空着"spec §6 #2
for (String key : tableKeys) {
row.putIfAbsent(key, "");
}
Tr newRow = Docx4jUtil.createCustomRow(factory, row, tableKeys, trPr, tcPrList, templateRPr, true);
// Docx4jUtil.createCustomRow 产出的单元格是裸 Tc未包 JAXBElement
// 与模板行(真实 docx4j 解析结果 / deepCopy 而来)里统一的 JAXBElement<Tc> 不一致;
// 这里做一次归一化包装,避免下游按 JAXBElement 读取该行时 ClassCastException不改 createCustomRow 本身)
List<Object> normalized = new ArrayList<>();
for (Object cellObj : newRow.getContent()) {
if (cellObj instanceof Tc) {
normalized.add(factory.createTrTc((Tc) cellObj));
} else {
normalized.add(cellObj);
}
}
newRow.getContent().clear();
newRow.getContent().addAll(normalized);
trs.add(newRow);
}
out.add(copied);
}
// 多表(谐波类多 scriptIndex背靠背插入时OOXML 相邻 w:tbl 会被 Word 合并渲染成一张大表;
// 只插入空段落做结构分隔。测点号属于 HP 表内标题单元格,不能作为表外可见段落。
if (out.size() > 1) {
List<Object> withSeparators = new ArrayList<>(out.size() * 2 - 1);
for (int i = 0; i < out.size(); i++) {
withSeparators.add(out.get(i));
if (i < out.size() - 1) {
withSeparators.add(factory.createP());
}
}
return withSeparators;
}
return out;
}
/**
* 校验模板 key 行占位符已成功取出。调用方仅在"该指标有脚本明细且模板分组存在"时调用:
* 此时 keys 为空属模板错误key 行缺失或表结构不符合 getTableFillKeys 的识别规则),
* 必须显性中断报告生成,不得静默走"未测→整节隐藏"(否则有数据的节凭空消失,违反红线 2
*/
public static void requireTableKeys(String scriptCode, List<String> tableKeys) {
if (CollUtil.isEmpty(tableKeys)) {
throw new BusinessException("指标 " + scriptCode + " 的模板表 key 行占位符解析为空,请检查 detail 模板该分组的表格(表末行应为占位符 key 行),已中断报告生成");
}
}
/**
* 指标锚点模板专用 key 读取:按 spec 直接取 H5 分组第一张表的最后一个真实 Tr。
* 不复用旧 getTableFillKeys 的横/纵表启发式,避免 HV/HI/HP 标题区末格为数值时被误判。
*/
public static List<String> extractTableKeys(List<Docx4jUtil.HeadingContent> tempContent) {
List<String> keys = new ArrayList<>();
if (CollUtil.isEmpty(tempContent)) {
return keys;
}
JAXBElement<Tbl> table = findFirstTable(tempContent.get(0));
if (table == null) {
return keys;
}
Tr keyRow = findLastRow(table.getValue().getContent());
if (keyRow == null) {
return keys;
}
for (Object cellObj : keyRow.getContent()) {
Object value = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
if (value instanceof Tc) {
keys.add(Docx4jUtil.getTextFromCell((Tc) value));
}
}
return keys;
}
/** 从尾部向前找最后一个真正的 Tr含 JAXBElement 解包);无 Tr 返回 null */
private static Tr findLastRow(List<Object> content) {
for (int i = content.size() - 1; i >= 0; i--) {
Object v = content.get(i) instanceof JAXBElement
? ((JAXBElement<?>) content.get(i)).getValue() : content.get(i);
if (v instanceof Tr) {
return (Tr) v;
}
}
return null;
}
/**
* 把 SingleTestResult 的三层嵌套 detail 摊平成行列表,并做新模板专属的行级补充:
* errorScope 注入HV/HI/HP 的标准限值列、time 缺失时"测点{n}"兜底F/IMBV/IMBA、P 有功特例。
*/
static List<Map<String, String>> flattenRows(SingleTestResult result, String scriptCode) {
List<Map<String, String>> out = new ArrayList<>();
if (result == null || CollUtil.isEmpty(result.getDetail())) {
return out;
}
int seq = 0;
for (Map.Entry<String, List<Map<String, List<Map<String, String>>>>> influenceEntry : result.getDetail().entrySet()) {
if (influenceEntry.getValue() == null) {
continue;
}
for (Map<String, List<Map<String, String>>> byError : influenceEntry.getValue()) {
if (byError == null) {
continue;
}
for (Map.Entry<String, List<Map<String, String>>> errorEntry : byError.entrySet()) {
String errorScope = errorEntry.getKey();
if (errorEntry.getValue() == null) {
continue;
}
for (Map<String, String> raw : errorEntry.getValue()) {
seq++;
Map<String, String> row = new LinkedHashMap<>(raw);
applyErrorScope(row, scriptCode, errorScope);
if (StrUtil.isBlank(row.get(ItemReportKeyEnum.TIME.getKey()))) {
row.put(ItemReportKeyEnum.TIME.getKey(), "测点" + seq);
}
if ("P".equalsIgnoreCase(scriptCode)) {
applyPowerMapping(row);
}
out.add(row);
}
}
}
}
return out;
}
private static void applyErrorScope(Map<String, String> row, String scriptCode, String errorScope) {
String key = ItemReportKeyEnum.ERROR_SCOPE.getKey();
if ("HV".equalsIgnoreCase(scriptCode) || "HP".equalsIgnoreCase(scriptCode)) {
String value = StrUtil.isBlank(row.get(key)) ? errorScope : row.get(key);
row.put(key, stripTrailingUnit(value));
return;
}
row.putIfAbsent(key, errorScope);
}
private static String stripTrailingUnit(String value) {
if (StrUtil.isBlank(value)) {
return value;
}
return value.trim().replaceFirst("\\s*(?:(?:[%%‰°℃]|[a-zA-Z]+|[\\u4e00-\\u9fa5]+)\\s*)+$", "");
}
/**
* P有功功率特例activePower = 三相实测之和;设置类与无功/视在/功率因数数据侧暂无,留空。
* spec §6 #2 处置。
*/
static void applyPowerMapping(Map<String, String> row) {
BigDecimal sum = BigDecimal.ZERO;
boolean hasValue = false;
for (String key : Arrays.asList(ItemReportKeyEnum.TEST_A.getKey(),
ItemReportKeyEnum.TEST_B.getKey(), ItemReportKeyEnum.TEST_C.getKey())) {
String value = row.get(key);
if (StrUtil.isNotBlank(value)) {
try {
sum = sum.add(new BigDecimal(value.trim()));
hasValue = true;
} catch (NumberFormatException ignored) {
// 非数值(如"--")不参与求和
}
}
}
String activePower = row.get(ItemReportKeyEnum.ACTIVE_POWER.getKey());
if (hasValue && (StrUtil.isBlank(activePower) || "/".equals(activePower))) {
row.put(ItemReportKeyEnum.ACTIVE_POWER.getKey(), sum.toPlainString());
}
}
private static void applyHarmonicDerivedValues(List<Map<String, String>> rows, String scriptCode) {
if (!"HI".equalsIgnoreCase(scriptCode)) {
return;
}
for (Map<String, String> row : rows) {
String scriptStandardRate = row.get(ItemReportKeyEnum.STANDARD_RATE.getKey());
String standardRate = parseNumber(scriptStandardRate) == null ? "" : scriptStandardRate;
String testRateA = rate(row.get(ItemReportKeyEnum.TEST_A.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_A.getKey()));
String testRateB = rate(row.get(ItemReportKeyEnum.TEST_B.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_B.getKey()));
String testRateC = rate(row.get(ItemReportKeyEnum.TEST_C.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_C.getKey()));
String errorRateA = difference(testRateA, standardRate);
String errorRateB = difference(testRateB, standardRate);
String errorRateC = difference(testRateC, standardRate);
row.put(ItemReportKeyEnum.STANDARD_RATE.getKey(), standardRate);
row.put(ItemReportKeyEnum.TEST_RATE_A.getKey(), testRateA);
row.put(ItemReportKeyEnum.TEST_RATE_B.getKey(), testRateB);
row.put(ItemReportKeyEnum.TEST_RATE_C.getKey(), testRateC);
row.put(ItemReportKeyEnum.ERROR_RATE_A.getKey(), errorRateA);
row.put(ItemReportKeyEnum.ERROR_RATE_B.getKey(), errorRateB);
row.put(ItemReportKeyEnum.ERROR_RATE_C.getKey(), errorRateC);
row.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), harmonicCurrentErrorScope(standardRate));
}
}
private static String harmonicCurrentErrorScope(String standardRateText) {
Double standardRate = parseNumber(standardRateText);
if (standardRate == null) {
return "";
}
double limit = standardRate >= 3D ? standardRate * 0.05D : 0.15D;
return "±" + format4(limit);
}
private static Map<String, String> buildHarmonicFixedPlaceholders(List<Map<String, String>> rows, String scriptCode) {
Map<String, String> placeholders = new LinkedHashMap<>();
if ("HV".equalsIgnoreCase(scriptCode)) {
placeholders.put(ItemReportKeyEnum.STANDARD_THD.getKey(), thd(rows, ItemReportKeyEnum.STANDARD.getKey()));
placeholders.put(ItemReportKeyEnum.THD_A.getKey(), thd(rows, ItemReportKeyEnum.TEST_A.getKey()));
placeholders.put(ItemReportKeyEnum.THD_B.getKey(), thd(rows, ItemReportKeyEnum.TEST_B.getKey()));
placeholders.put(ItemReportKeyEnum.THD_C.getKey(), thd(rows, ItemReportKeyEnum.TEST_C.getKey()));
} else if ("HI".equalsIgnoreCase(scriptCode)) {
placeholders.put(ItemReportKeyEnum.STANDARD_THD.getKey(), thd(rows, ItemReportKeyEnum.STANDARD_RATE.getKey()));
placeholders.put(ItemReportKeyEnum.THD_A.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_A.getKey()));
placeholders.put(ItemReportKeyEnum.THD_B.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_B.getKey()));
placeholders.put(ItemReportKeyEnum.THD_C.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_C.getKey()));
}
return placeholders;
}
private static void applyHarmonicPowerHeader(Tbl tbl, String scriptCode, int pointNo, List<Map<String, String>> rows) {
if (!"HP".equalsIgnoreCase(scriptCode)) {
return;
}
Tr firstRow = findFirstRow(tbl.getContent());
if (firstRow == null) {
return;
}
Tc titleCell = cellAt(firstRow, 0);
if (titleCell == null) {
return;
}
String title = Docx4jUtil.getTextFromCell(titleCell);
String baseTitle = StrUtil.blankToDefault(title, StrUtil.EMPTY)
.replaceFirst("(测点\\s*\\d+$", "");
setCellText(titleCell, baseTitle + "(测点" + pointNo + "");
fillNextCellByLabel(tbl, "基波电压", firstDataValue(rows, ItemReportKeyEnum.STANDARD_V.getKey()));
fillNextCellByLabel(tbl, "基波电流", firstDataValue(rows, ItemReportKeyEnum.STANDARD_I.getKey()));
}
private static String firstDataValue(List<Map<String, String>> rows, String key) {
if (CollUtil.isEmpty(rows)) {
return "";
}
for (Map<String, String> row : rows) {
String value = row.get(key);
if (StrUtil.isNotBlank(value) && !"/".equals(value.trim())) {
return value;
}
}
return "";
}
private static void fillNextCellByLabel(Tbl tbl, String label, String value) {
if (StrUtil.isBlank(value) || tbl == null || tbl.getContent() == null) {
return;
}
for (Object o : tbl.getContent()) {
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
if (v instanceof Tr && fillNextCellByLabel((Tr) v, label, value)) {
return;
}
}
}
private static boolean fillNextCellByLabel(Tr row, String label, String value) {
if (StrUtil.isBlank(value) || row == null || row.getContent() == null) {
return false;
}
List<Object> cells = row.getContent();
for (int i = 0; i < cells.size() - 1; i++) {
Tc labelCell = cellAt(row, i);
if (labelCell != null && Docx4jUtil.getTextFromCell(labelCell).contains(label)) {
Tc valueCell = cellAt(row, i + 1);
if (valueCell != null) {
setCellText(valueCell, value);
}
return true;
}
}
return false;
}
private static Tr findFirstRow(List<Object> content) {
for (Object o : content) {
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
if (v instanceof Tr) {
return (Tr) v;
}
}
return null;
}
private static Tc cellAt(Tr row, int index) {
if (row == null || row.getContent() == null || row.getContent().size() <= index) {
return null;
}
Object cellObj = row.getContent().get(index);
Object value = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
return value instanceof Tc ? (Tc) value : null;
}
private static String rate(String numeratorText, String denominatorText) {
Double numerator = parseNumber(numeratorText);
Double denominator = parseNumber(denominatorText);
if (numerator == null || denominator == null || denominator == 0D) {
return "";
}
return format4(numerator / denominator * 100D);
}
private static String difference(String minuendText, String subtrahendText) {
Double minuend = parseNumber(minuendText);
Double subtrahend = parseNumber(subtrahendText);
if (minuend == null || subtrahend == null) {
return "";
}
return format4(minuend - subtrahend);
}
private static String thd(List<Map<String, String>> rows, String key) {
double sum = 0D;
boolean hasValue = false;
for (Map<String, String> row : rows) {
Double value = parseNumber(row.get(key));
if (value != null) {
sum += value * value;
hasValue = true;
}
}
return hasValue ? format4(Math.sqrt(sum)) : "";
}
private static Double parseNumber(String text) {
if (StrUtil.isBlank(text) || "/".equals(text.trim()) || "--".equals(text.trim())) {
return null;
}
try {
return Double.parseDouble(text.trim());
} catch (NumberFormatException ignored) {
return null;
}
}
private static String format4(double value) {
return String.format(Locale.ROOT, "%.4f", value);
}
private static void replaceFixedPlaceholders(Tbl tbl, Map<String, String> values) {
if (values.isEmpty()) {
return;
}
for (Object rowObj : tbl.getContent()) {
Object rowValue = rowObj instanceof JAXBElement ? ((JAXBElement<?>) rowObj).getValue() : rowObj;
if (!(rowValue instanceof Tr)) {
continue;
}
for (Object cellObj : ((Tr) rowValue).getContent()) {
Object cellValue = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
if (cellValue instanceof Tc) {
Tc cell = (Tc) cellValue;
String replacement = values.get(Docx4jUtil.getTextFromCell(cell));
if (replacement != null) {
setCellText(cell, replacement);
}
}
}
}
}
private static void setCellText(Tc cell, String value) {
P firstParagraph = null;
for (Object content : cell.getContent()) {
if (content instanceof P) {
firstParagraph = (P) content;
break;
}
}
if (firstParagraph == null) {
firstParagraph = new P();
cell.getContent().add(firstParagraph);
}
boolean written = false;
for (Object paragraphObj : cell.getContent()) {
if (!(paragraphObj instanceof P)) {
continue;
}
P paragraph = (P) paragraphObj;
for (Object runObj : paragraph.getContent()) {
if (!(runObj instanceof R)) {
continue;
}
R run = (R) runObj;
for (Object textObj : run.getContent()) {
Text text = unwrapText(textObj);
if (text != null) {
text.setValue(written ? "" : value);
written = true;
}
}
}
}
if (!written) {
R run = new R();
Text text = new Text();
text.setValue(value);
run.getContent().add(text);
firstParagraph.getContent().add(run);
}
}
private static Text unwrapText(Object textObj) {
if (textObj instanceof Text) {
return (Text) textObj;
}
if (textObj instanceof JAXBElement && ((JAXBElement<?>) textObj).getValue() instanceof Text) {
return (Text) ((JAXBElement<?>) textObj).getValue();
}
return null;
}
@SuppressWarnings("unchecked")
private static JAXBElement<Tbl> findFirstTable(Docx4jUtil.HeadingContent template) {
if (template == null || CollUtil.isEmpty(template.getSubContent())) {
return null;
}
for (Object o : template.getSubContent()) {
if (o instanceof JAXBElement && ((JAXBElement<?>) o).getValue() instanceof Tbl) {
return (JAXBElement<Tbl>) o;
}
}
return null;
}
}

View File

@@ -0,0 +1,276 @@
package com.njcn.gather.report.util;
import com.njcn.gather.report.pojo.constant.ItemAnchorConstant;
import com.njcn.gather.tools.report.util.BookmarkUtil;
import com.njcn.gather.tools.report.util.Docx4jUtil;
import lombok.extern.slf4j.Slf4j;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.CTBookmark;
import org.docx4j.wml.CTMarkupRange;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.Text;
import javax.xml.bind.JAXBElement;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* "指标锚点"模板的区段隐藏 / 编号重排 / 书签清理工具。
* 只服务新路径 dealDataModelByItemAnchor不被老路径引用。
* 设计文档docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2
*
* @author hongawen
*/
@Slf4j
public final class ItemAnchorSectionUtil {
private ItemAnchorSectionUtil() {
}
/** 三级编号7.x.y半角点 */
private static final Pattern LEVEL3 = Pattern.compile("^7\\.(\\d+)\\.(\\d+)");
/** 二级编号7.x半角点排除 7.x.y */
private static final Pattern LEVEL2 = Pattern.compile("^7\\.(\\d+)(?![\\.\\d])");
/**
* 删除已填充 item_* 的空锚点段,避免插入表格前残留一行空段落。
* 只处理指标锚点新路径的白名单 item_*;段落内存在正文时保留,防止模板内容被误删。
*/
public static boolean removeEmptyItemAnchorParagraph(BookmarkUtil.BookmarkInfo info) {
if (info == null || info.bookmark == null || info.parentParagraph == null || info.parentContainer == null) {
return false;
}
if (ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName()) == null) {
return false;
}
String text = Docx4jUtil.getTextFromP(info.parentParagraph);
if (text != null && !text.trim().isEmpty()) {
return false;
}
return info.parentContainer.getContent().remove(info.parentParagraph);
}
/**
* 删除隐藏指标对应的 sect_{code} 区段body 块级整段删除)。
* GRP 折叠规则GRP_CHILDREN 中某组的子节全部在 hiddenCodes 中时,删父节区段(含组标题与组内公共文字),
* 不再单删子节;父区段定位失败时回退按子节各自删除,避免组和子节一个都删不掉(静默违反红线 2
*/
public static void removeSectRanges(MainDocumentPart part, Set<String> hiddenCodes) {
if (part == null || hiddenCodes == null || hiddenCodes.isEmpty()) {
return;
}
List<Object> body = part.getContent();
// 单遍扫描收集全部书签区段,后续按名 O(1) 取用
Map<String, int[]> allRanges = locateRanges(body);
List<int[]> ranges = new ArrayList<>();
Set<String> coveredByGrp = new HashSet<>();
for (Map.Entry<String, List<String>> entry : ItemAnchorConstant.GRP_CHILDREN.entrySet()) {
if (!hiddenCodes.containsAll(entry.getValue())) {
continue;
}
int[] grpRange = allRanges.get((ItemAnchorConstant.SECT_PREFIX + entry.getKey()).toLowerCase());
if (grpRange != null) {
ranges.add(grpRange);
coveredByGrp.addAll(entry.getValue());
} else {
log.warn("父区段书签 {}{} 定位失败,回退按子节区段各自删除,请检查模板书签是否完整",
ItemAnchorConstant.SECT_PREFIX, entry.getKey());
}
}
for (String code : hiddenCodes) {
if (coveredByGrp.contains(code)) {
continue;
}
int[] range = allRanges.get((ItemAnchorConstant.SECT_PREFIX + code).toLowerCase());
if (range != null) {
ranges.add(range);
} else {
log.warn("区段书签 {}{} 定位失败,该节无法隐藏,请检查模板书签是否完整",
ItemAnchorConstant.SECT_PREFIX, code);
}
}
// 起点降序删除,避免前面的删除让后面的索引失效
ranges.sort((a, b) -> Integer.compare(b[0], a[0]));
for (int[] range : ranges) {
for (int i = range[1]; i >= range[0]; i--) {
if (i < body.size()) {
body.remove(i);
}
}
}
}
/**
* 清理全文残留的 item_ / sect_ 书签start 与配对的 end其他书签不动。
* 已填充节的 sect end 会被 BookmarkUtil.removeBookmark 顺带清掉,留下无 end 的 start本方法兜底清理。
*/
public static void stripItemAnchorBookmarks(MainDocumentPart part) {
if (part == null) {
return;
}
Set<BigInteger> ourIds = new HashSet<>();
// 第一遍:删 start 并记 id
for (Object block : part.getContent()) {
P p = asP(block);
if (p == null) {
continue;
}
Iterator<Object> it = p.getContent().iterator();
while (it.hasNext()) {
Object v = unwrap(it.next());
if (v instanceof CTBookmark) {
String name = ((CTBookmark) v).getName();
if (isOurNamespace(name)) {
ourIds.add(((CTBookmark) v).getId());
it.remove();
}
}
}
}
// 第二遍:删配对 end
for (Object block : part.getContent()) {
P p = asP(block);
if (p == null) {
continue;
}
Iterator<Object> it = p.getContent().iterator();
while (it.hasNext()) {
Object v = unwrap(it.next());
if (v instanceof CTMarkupRange && !(v instanceof CTBookmark)
&& ourIds.contains(((CTMarkupRange) v).getId())) {
it.remove();
}
}
}
}
/**
* 第 7 节编号重排:区段删除后,把剩余的 7.x / 7.x.y 标题按出现顺序重写为连续编号。
* 顶级"7准确度检查"用全角点,正则天然不匹配,保持不动。
*/
public static void renumberChapter7(MainDocumentPart part) {
if (part == null) {
return;
}
int l2 = 0;
int l3 = 0;
for (Object block : part.getContent()) {
P p = asP(block);
if (p == null) {
continue;
}
String text = Docx4jUtil.getTextFromP(p);
if (text == null) {
continue;
}
Matcher m3 = LEVEL3.matcher(text);
if (m3.find()) {
l3++;
String newPrefix = "7." + l2 + "." + l3;
if (!m3.group().equals(newPrefix)) {
replacePrefix(p, m3.group().length(), newPrefix);
}
continue;
}
Matcher m2 = LEVEL2.matcher(text);
if (m2.find()) {
l2++;
l3 = 0;
String newPrefix = "7." + l2;
if (!m2.group().equals(newPrefix)) {
replacePrefix(p, m2.group().length(), newPrefix);
}
}
}
}
/**
* 单遍扫描 body收集全部段落内书签区段书签名小写→ [start块下标, end块下标]。
* 同名书签只记首个(与逐名定位"取第一处命中"语义一致);无配对 end 的 start 不产出条目。
*/
private static Map<String, int[]> locateRanges(List<Object> body) {
Map<String, int[]> out = new HashMap<>();
Map<BigInteger, String> openNames = new HashMap<>();
Map<BigInteger, Integer> openStarts = new HashMap<>();
for (int i = 0; i < body.size(); i++) {
P p = asP(body.get(i));
if (p == null) {
continue;
}
for (Object o : p.getContent()) {
Object v = unwrap(o);
// CTBookmark 继承 CTMarkupRange先判 startelse 分支天然排除 CTBookmark即 bookmarkEnd
if (v instanceof CTBookmark) {
CTBookmark start = (CTBookmark) v;
if (start.getName() != null && start.getId() != null) {
openNames.put(start.getId(), start.getName().toLowerCase());
openStarts.put(start.getId(), i);
}
} else if (v instanceof CTMarkupRange) {
BigInteger id = ((CTMarkupRange) v).getId();
String name = openNames.remove(id);
if (name != null) {
out.putIfAbsent(name, new int[]{openStarts.remove(id), i});
}
}
}
}
return out;
}
private static boolean isOurNamespace(String name) {
if (name == null) {
return false;
}
String lower = name.toLowerCase();
return lower.startsWith(ItemAnchorConstant.ITEM_PREFIX) || lower.startsWith(ItemAnchorConstant.SECT_PREFIX);
}
private static Object unwrap(Object o) {
return (o instanceof JAXBElement) ? ((JAXBElement<?>) o).getValue() : o;
}
private static P asP(Object block) {
Object v = unwrap(block);
return (v instanceof P) ? (P) v : null;
}
/** 跨 run 替换段首前 oldLen 个字符为 newPrefix编号可能被 Word 拆进多个 text 节点) */
private static void replacePrefix(P p, int oldLen, String newPrefix) {
List<Text> texts = new ArrayList<>();
collectTexts(p.getContent(), texts);
int remaining = oldLen;
boolean inserted = false;
for (Text t : texts) {
if (remaining <= 0) {
break;
}
String value = t.getValue() == null ? "" : t.getValue();
int cut = Math.min(remaining, value.length());
remaining -= cut;
String rest = value.substring(cut);
t.setValue(inserted ? rest : newPrefix + rest);
inserted = true;
}
}
private static void collectTexts(List<Object> content, List<Text> out) {
for (Object o : content) {
Object v = unwrap(o);
if (v instanceof R) {
collectTexts(((R) v).getContent(), out);
} else if (v instanceof Text) {
out.add((Text) v);
}
}
}
}

View File

@@ -163,6 +163,18 @@ public class ResultController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/createChecksquareTask")
@ApiOperation("调用第三方数模数据检测接口")
@ApiImplicitParam(name = "devId", value = "设备id", required = true)
public HttpResult<DataCheckResultVO> createChecksquareTask(@RequestParam("devId") String devId) {
String methodDescribe = getMethodDescribe("createChecksquareTask");
LogUtil.njcnDebug(log, "{}调用第三方数模数据检测接口设备id为{}", methodDescribe, devId);
DataCheckResultVO result = resultService.createChecksquareTaskByDevId(devId);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getMonitorDataSourceResult")

View File

@@ -26,6 +26,7 @@ public enum ResultUnitEnum {
IMBA("%", "电流不平衡度","IMBA"),
F("","闪变","F"),
P("W", "功率","P"),
ANGLE("°", "相角","Angle"),
UNKNOWN("","未知","UNKNOWN"),
;

View File

@@ -0,0 +1,13 @@
package com.njcn.gather.result.pojo.param;
import lombok.Data;
import java.util.List;
@Data
public class DataCheckRequest {
private List<String> lineIds;
private List<String> indicatorCodes;
private String timeStart;
private String timeEnd;
}

View File

@@ -0,0 +1,22 @@
package com.njcn.gather.result.pojo.vo;
import lombok.Builder;
import lombok.Value;
import java.time.LocalDateTime;
import java.util.List;
/**
* 数据校验通知 上下文
*/
@Value
@Builder
public class DataCheckNotifyContext {
String notifyKey;
String planId;
List<String> sortedDevIds;
List<String> lineIds;
LocalDateTime timeStart;
LocalDateTime timeEnd;
String reCheckType;
}

View File

@@ -0,0 +1,72 @@
package com.njcn.gather.result.pojo.vo;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author caozehui
* @data 2026-06-26
*/
@Data
public class DataCheckResultVO {
/**
* 任务 ID
*/
@JSONField(name = "taskId")
private String taskId;
/**
* 任务编号
*/
@JSONField(name = "taskNo")
private String taskNo;
/**
* 监测点Id集合
*/
@JSONField(name = "lineIds")
private List<String> lineIds;
/**
* 监测点名称;多监测点时为多个名称拼接结果
*/
@JSONField(name = "lineName")
private String lineName;
/**
* 开始时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timeStart;
/**
* 结束时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timeEnd;
/**
* 统计间隔,单位分钟
*/
private long intervalMinutes;
/**
* 任务状态RUNNING、SUCCESS、FAIL
*/
private String taskStatus;
/**
* 检测项数量
*/
private long itemCount;
/**
* 异常检测项数量
*/
private long abnormalItemCount;
/**
* 最低数据完整性0 到 1 的小数
*/
private long minDataIntegrity;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,75 @@
package com.njcn.gather.result.service;
import com.njcn.gather.result.pojo.param.DataCheckRequest;
import com.njcn.gather.result.pojo.vo.DataCheckNotifyContext;
import com.njcn.gather.result.service.impl.ResultServiceImpl;
import com.njcn.http.util.RestTemplateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Map;
@Slf4j
@Component
@RequiredArgsConstructor
public class DataCheckAsyncNotifier {
private final static String url="http://172.17.100.111:18091/steady/checksquare/create";
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final RestTemplateUtil restTemplateUtil;
@Async
public void notifyAsync(DataCheckNotifyContext context, Map<String, ResultServiceImpl.NotifyState> notifyStates) {
notifyDirect(context, notifyStates);
}
void notifyDirect(DataCheckNotifyContext context, Map<String, ResultServiceImpl.NotifyState> notifyStates) {
int maxRetries = 3;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
DataCheckRequest request = new DataCheckRequest();
request.setLineIds(context.getLineIds());
request.setIndicatorCodes(Collections.emptyList());
request.setTimeStart(FORMATTER.format(context.getTimeStart()));
request.setTimeEnd(FORMATTER.format(context.getTimeEnd()));
restTemplateUtil.postJson(url, request, String.class);
notifyStates.put(context.getNotifyKey(),
new ResultServiceImpl.NotifyState(ResultServiceImpl.NotifyStatus.SUCCESS, attempt - 1, null, LocalDateTime.now()));
log.info("checksquare notify success, key={}, planId={}, lineCount={}", context.getNotifyKey(), context.getPlanId(), context.getLineIds().size());
return;
} catch (Exception ex) {
int failCount = attempt;
if (failCount > maxRetries) {
notifyStates.put(context.getNotifyKey(),
new ResultServiceImpl.NotifyState(ResultServiceImpl.NotifyStatus.FAIL, maxRetries, ex.getMessage(), LocalDateTime.now()));
log.error("checksquare notify failed, key={}, failCount={}", context.getNotifyKey(), maxRetries, ex);
return;
}
if (!sleepBeforeRetry(context, failCount)) {
notifyStates.put(context.getNotifyKey(),
new ResultServiceImpl.NotifyState(ResultServiceImpl.NotifyStatus.FAIL, failCount, "retry interrupted", LocalDateTime.now()));
return;
}
}
}
}
private boolean sleepBeforeRetry(DataCheckNotifyContext context, int failCount) {
long delayMillis = (long) Math.pow(2, failCount) * 1000L;
log.warn("checksquare notify retry scheduled, key={}, failCount={}, delayMillis={}", context.getNotifyKey(), failCount, delayMillis);
try {
Thread.sleep(delayMillis);
return true;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
}

View File

@@ -1,5 +1,6 @@
package com.njcn.gather.result.service;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.device.pojo.vo.PqDevVO;
import com.njcn.gather.report.pojo.DevReportParam;
import com.njcn.gather.report.pojo.result.ContrastTestResult;
@@ -17,6 +18,16 @@ import java.util.Map;
* @data 2024-12-30
*/
public interface IResultService {
void tryNotifyThirdPartyAfterFormalTest(PreDetectionParam param);
/**
* 调用第三方数据校验结果
*
* @param devId
* @return
*/
DataCheckResultVO createChecksquareTaskByDevId(String devId);
/**
* 检测详情表单头
*

View File

@@ -0,0 +1,191 @@
package com.njcn.gather.result.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
import com.njcn.gather.detection.pojo.vo.DetectionData;
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* 基波相位报告结果行装配:云南模板以电压相角为 0 度基准,取 I1A 的 A/B/C 三相电流相角填表。
*/
public final class AngleResultAssembler {
private AngleResultAssembler() {
}
public static List<Map<String, String>> assembleRows(List<SimAndDigNonHarmonicResult> results) {
List<Map<String, String>> rows = new ArrayList<>();
if (CollUtil.isEmpty(results)) {
return rows;
}
Map<Integer, List<SimAndDigNonHarmonicResult>> bySort = results.stream()
.filter(result -> result.getSort() != null)
.collect(Collectors.groupingBy(SimAndDigNonHarmonicResult::getSort, TreeMap::new, Collectors.toList()));
for (List<SimAndDigNonHarmonicResult> sameSortResults : bySort.values()) {
SimAndDigNonHarmonicResult currentAngle = firstCurrentAngle(sameSortResults);
if (currentAngle == null) {
continue;
}
DetectionData[] phases = phases(currentAngle);
DetectionData primary = firstPresent(phases);
if (primary == null) {
continue;
}
Map<String, String> row = defaultAngleRow();
row.put(ItemReportKeyEnum.STANDARD.getKey(), valueOrSlash(primary.getResultData()));
putPhaseDetails(row, phases);
row.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope(primary));
row.put(ItemReportKeyEnum.RESULT.getKey(), overallResult(phases));
rows.add(row);
}
return rows;
}
private static SimAndDigNonHarmonicResult firstCurrentAngle(List<SimAndDigNonHarmonicResult> results) {
if (CollUtil.isEmpty(results)) {
return null;
}
for (SimAndDigNonHarmonicResult result : results) {
if (DetectionCodeEnum.I1A.getCode().equalsIgnoreCase(result.getAdType())) {
return result;
}
}
return null;
}
private static Map<String, String> defaultAngleRow() {
Map<String, String> row = new LinkedHashMap<>();
for (ItemReportKeyEnum key : Arrays.asList(
ItemReportKeyEnum.STANDARD,
ItemReportKeyEnum.TEST_A,
ItemReportKeyEnum.TEST_B,
ItemReportKeyEnum.TEST_C,
ItemReportKeyEnum.ERROR_A,
ItemReportKeyEnum.ERROR_B,
ItemReportKeyEnum.ERROR_C,
ItemReportKeyEnum.ERROR_SCOPE,
ItemReportKeyEnum.RESULT,
ItemReportKeyEnum.RESULT_A,
ItemReportKeyEnum.RESULT_B,
ItemReportKeyEnum.RESULT_C)) {
row.put(key.getKey(), "/");
}
return row;
}
private static DetectionData[] phases(SimAndDigNonHarmonicResult result) {
return new DetectionData[]{
parse(result.getAValue()),
parse(result.getBValue()),
parse(result.getCValue())
};
}
private static void putPhaseDetails(Map<String, String> row, DetectionData[] phases) {
List<String> tests = Arrays.asList(ItemReportKeyEnum.TEST_A.getKey(),
ItemReportKeyEnum.TEST_B.getKey(), ItemReportKeyEnum.TEST_C.getKey());
List<String> errors = Arrays.asList(ItemReportKeyEnum.ERROR_A.getKey(),
ItemReportKeyEnum.ERROR_B.getKey(), ItemReportKeyEnum.ERROR_C.getKey());
List<String> results = Arrays.asList(ItemReportKeyEnum.RESULT_A.getKey(),
ItemReportKeyEnum.RESULT_B.getKey(), ItemReportKeyEnum.RESULT_C.getKey());
for (int i = 0; i < phases.length; i++) {
DetectionData phase = phases[i];
row.put(tests.get(i), phase == null ? "/" : valueOrSlash(phase.getData()));
row.put(errors.get(i), phase == null || phase.getErrorData() == null ? "/" : format(phase.getErrorData()));
row.put(results.get(i), phase == null ? "/" : resultText(phase.getIsData()));
}
}
private static DetectionData firstPresent(DetectionData[] values) {
for (DetectionData value : values) {
if (value != null) {
return value;
}
}
return null;
}
private static DetectionData parse(String value) {
if (StrUtil.isBlank(value)) {
return null;
}
return JSONUtil.toBean(value, DetectionData.class);
}
private static String overallResult(DetectionData[] phases) {
boolean hasResult = false;
for (DetectionData phase : phases) {
if (phase == null || phase.getIsData() == null) {
continue;
}
hasResult = true;
if (phase.getIsData() == 2) {
return "不合格";
}
}
return hasResult ? "合格" : "/";
}
private static String resultText(Integer isData) {
if (isData == null) {
return "/";
}
if (isData == 1) {
return "合格";
}
if (isData == 2) {
return "不合格";
}
return "/";
}
private static String errorScope(DetectionData primary) {
String scope = dealErrorScope(primary.getRadius());
if (StrUtil.isNotBlank(primary.getUnit()) && !"/".equals(scope)) {
return scope + primary.getUnit();
}
return scope;
}
private static String dealErrorScope(String errorScope) {
if (StrUtil.isBlank(errorScope)) {
return "/";
}
if (errorScope.contains("~")) {
String[] split = errorScope.split("~");
String begin = split[0];
if (begin.startsWith("-")) {
begin = begin.substring(1);
}
if (split.length > 1 && split[1].equalsIgnoreCase(begin)) {
return "±" + begin;
}
}
return errorScope;
}
private static String valueOrSlash(Double value) {
return value == null ? "/" : format(value);
}
private static String format(Double value) {
return value == null ? "/" : BigDecimal.valueOf(value).setScale(4, RoundingMode.HALF_UP).toPlainString();
}
private static String format(BigDecimal value) {
return value == null ? "/" : value.setScale(4, RoundingMode.HALF_UP).toPlainString();
}
}

View File

@@ -0,0 +1,342 @@
package com.njcn.gather.result.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.njcn.gather.detection.pojo.vo.DetectionData;
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* 功率 P 报告结果行装配:同一 sort 下可能同时存在总有功、总无功、总视在等结果。
*/
public final class PowerResultAssembler {
private PowerResultAssembler() {
}
public static List<Map<String, String>> assembleRows(List<SimAndDigNonHarmonicResult> results) {
return assembleRows(results, Collections.emptyList());
}
public static List<Map<String, String>> assembleRows(List<SimAndDigNonHarmonicResult> results,
List<? extends PqScriptDtls> scriptDetails) {
if (CollUtil.isEmpty(results)) {
return new ArrayList<>();
}
Map<Integer, List<PqScriptDtls>> scriptDetailsBySort = groupScriptDetailsBySort(scriptDetails);
Map<Integer, List<SimAndDigNonHarmonicResult>> bySort = results.stream()
.filter(result -> result.getSort() != null)
.collect(Collectors.groupingBy(SimAndDigNonHarmonicResult::getSort, TreeMap::new, Collectors.toList()));
List<Map<String, String>> rows = new ArrayList<>();
for (Map.Entry<Integer, List<SimAndDigNonHarmonicResult>> sortEntry : bySort.entrySet()) {
List<SimAndDigNonHarmonicResult> sameSortResults = sortEntry.getValue();
Map<String, String> row = defaultPowerRow();
DetectionData primary = null;
boolean hasPowerValue = false;
for (SimAndDigNonHarmonicResult result : sameSortResults) {
String code = result.getAdType();
if (equalsCode(code, "TotW")) {
DetectionData data = parse(result.getTValue());
hasPowerValue |= putData(row, ItemReportKeyEnum.ACTIVE_POWER.getKey(), data);
primary = firstPresent(data, primary);
} else if (equalsCode(code, "TotVAr")) {
hasPowerValue |= putData(row, ItemReportKeyEnum.REACTIVE_POWER.getKey(), parse(result.getTValue()));
} else if (equalsCode(code, "TotVA")) {
hasPowerValue |= putData(row, ItemReportKeyEnum.APPARENT_POWER.getKey(), parse(result.getTValue()));
} else if (equalsCode(code, "TotPF")) {
DetectionData data = parse(result.getTValue());
hasPowerValue |= putData(row, ItemReportKeyEnum.POWER_FACTOR.getKey(), data);
} else if (equalsCode(code, "PF")) {
if (isBlankPowerValue(row, ItemReportKeyEnum.POWER_FACTOR.getKey())) {
DetectionData data = firstPresent(parse(result.getTValue()), phaseAverage(result));
hasPowerValue |= putData(row, ItemReportKeyEnum.POWER_FACTOR.getKey(), data);
}
} else if (equalsCode(code, "W")) {
DetectionData[] phases = phases(result);
if (isBlankPowerValue(row, ItemReportKeyEnum.ACTIVE_POWER.getKey())) {
hasPowerValue |= putSum(row, ItemReportKeyEnum.ACTIVE_POWER.getKey(), phases);
}
putPhaseDetails(row, phases);
primary = preferPrimary(primary, firstPresent(phases));
} else if (equalsCode(code, "VARW")) {
if (isBlankPowerValue(row, ItemReportKeyEnum.REACTIVE_POWER.getKey())) {
hasPowerValue |= putSum(row, ItemReportKeyEnum.REACTIVE_POWER.getKey(), phases(result));
}
} else if (equalsCode(code, "VAW")) {
if (isBlankPowerValue(row, ItemReportKeyEnum.APPARENT_POWER.getKey())) {
hasPowerValue |= putSum(row, ItemReportKeyEnum.APPARENT_POWER.getKey(), phases(result));
}
}
}
if (primary != null) {
putPrimary(row, primary);
}
if (hasPowerValue) {
putStandardSourceValues(row, sortEntry.getKey(), scriptDetailsBySort);
rows.add(row);
}
}
return rows;
}
private static Map<String, String> defaultPowerRow() {
Map<String, String> row = new LinkedHashMap<>();
List<ItemReportKeyEnum> defaultKeys = Arrays.asList(
ItemReportKeyEnum.SCRIPT_DETAIL,
ItemReportKeyEnum.STANDARD,
ItemReportKeyEnum.STANDARD_A,
ItemReportKeyEnum.STANDARD_B,
ItemReportKeyEnum.STANDARD_C,
ItemReportKeyEnum.STANDARD_V,
ItemReportKeyEnum.STANDARD_I,
ItemReportKeyEnum.STANDARD_U_ANGLE,
ItemReportKeyEnum.STANDARD_I_ANGLE,
ItemReportKeyEnum.TEST,
ItemReportKeyEnum.TEST_A,
ItemReportKeyEnum.TEST_B,
ItemReportKeyEnum.TEST_C,
ItemReportKeyEnum.ERROR,
ItemReportKeyEnum.ERROR_A,
ItemReportKeyEnum.ERROR_B,
ItemReportKeyEnum.ERROR_C,
ItemReportKeyEnum.ERROR_SCOPE,
ItemReportKeyEnum.RESULT,
ItemReportKeyEnum.RESULT_A,
ItemReportKeyEnum.RESULT_B,
ItemReportKeyEnum.RESULT_C,
ItemReportKeyEnum.ACTIVE_POWER,
ItemReportKeyEnum.REACTIVE_POWER,
ItemReportKeyEnum.APPARENT_POWER,
ItemReportKeyEnum.POWER_FACTOR
);
for (ItemReportKeyEnum key : defaultKeys) {
row.put(key.getKey(), "/");
}
return row;
}
private static Map<Integer, List<PqScriptDtls>> groupScriptDetailsBySort(List<? extends PqScriptDtls> scriptDetails) {
Map<Integer, List<PqScriptDtls>> bySort = new TreeMap<>();
if (CollUtil.isEmpty(scriptDetails)) {
return bySort;
}
for (PqScriptDtls detail : scriptDetails) {
if (detail == null || detail.getScriptIndex() == null) {
continue;
}
bySort.computeIfAbsent(detail.getScriptIndex(), key -> new ArrayList<>()).add(detail);
}
return bySort;
}
private static void putStandardSourceValues(Map<String, String> row, Integer sort,
Map<Integer, List<PqScriptDtls>> scriptDetailsBySort) {
List<PqScriptDtls> sameSortDetails = scriptDetailsBySort.get(sort);
if (CollUtil.isEmpty(sameSortDetails)) {
return;
}
PqScriptDtls voltage = pickPhaseDetail(sameSortDetails, "VOL");
PqScriptDtls current = pickPhaseDetail(sameSortDetails, "CUR");
putDouble(row, ItemReportKeyEnum.STANDARD_V.getKey(), voltage == null ? null : voltage.getValue());
putDouble(row, ItemReportKeyEnum.STANDARD_I.getKey(), current == null ? null : current.getValue());
putDouble(row, ItemReportKeyEnum.STANDARD_U_ANGLE.getKey(), voltage == null ? null : voltage.getAngle());
putDouble(row, ItemReportKeyEnum.STANDARD_I_ANGLE.getKey(), current == null ? null : current.getAngle());
}
private static PqScriptDtls pickPhaseDetail(List<PqScriptDtls> details, String valueType) {
for (String phase : Arrays.asList("A", "B", "C")) {
PqScriptDtls detail = firstMatchingDetail(details, valueType, phase);
if (detail != null) {
return detail;
}
}
return firstMatchingDetail(details, valueType, null);
}
private static PqScriptDtls firstMatchingDetail(List<PqScriptDtls> details, String valueType, String phase) {
for (PqScriptDtls detail : details) {
if (!equalsCode(detail.getValueType(), valueType)) {
continue;
}
if (phase != null && !equalsCode(detail.getPhase(), phase)) {
continue;
}
if (detail.getValue() != null || detail.getAngle() != null) {
return detail;
}
}
return null;
}
private static void putDouble(Map<String, String> row, String key, Double value) {
if (value != null) {
row.put(key, format(value));
}
}
private static boolean putData(Map<String, String> row, String key, DetectionData data) {
if (data == null || data.getData() == null) {
return false;
}
row.put(key, format(data.getData()));
return true;
}
private static boolean putSum(Map<String, String> row, String key, DetectionData[] phases) {
BigDecimal sum = BigDecimal.ZERO;
boolean hasValue = false;
for (DetectionData phase : phases) {
if (phase != null && phase.getData() != null) {
sum = sum.add(BigDecimal.valueOf(phase.getData()));
hasValue = true;
}
}
if (hasValue) {
row.put(key, format(sum));
}
return hasValue;
}
private static boolean isBlankPowerValue(Map<String, String> row, String key) {
String value = row.get(key);
return StrUtil.isBlank(value) || "/".equals(value);
}
private static void putPrimary(Map<String, String> row, DetectionData primary) {
row.put(ItemReportKeyEnum.STANDARD.getKey(), valueOrSlash(primary.getResultData()));
row.put(ItemReportKeyEnum.TEST.getKey(), valueOrSlash(primary.getData()));
row.put(ItemReportKeyEnum.ERROR.getKey(), primary.getErrorData() == null ? "/" : format(primary.getErrorData()));
row.put(ItemReportKeyEnum.RESULT.getKey(), resultText(primary.getIsData()));
String errorScope = dealErrorScope(primary.getRadius());
if (StrUtil.isNotBlank(primary.getUnit()) && !"/".equals(errorScope)) {
errorScope = errorScope.concat(primary.getUnit());
}
row.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope);
}
private static void putPhaseDetails(Map<String, String> row, DetectionData[] phases) {
List<String> standards = Arrays.asList(ItemReportKeyEnum.STANDARD_A.getKey(),
ItemReportKeyEnum.STANDARD_B.getKey(), ItemReportKeyEnum.STANDARD_C.getKey());
List<String> tests = Arrays.asList(ItemReportKeyEnum.TEST_A.getKey(),
ItemReportKeyEnum.TEST_B.getKey(), ItemReportKeyEnum.TEST_C.getKey());
List<String> errors = Arrays.asList(ItemReportKeyEnum.ERROR_A.getKey(),
ItemReportKeyEnum.ERROR_B.getKey(), ItemReportKeyEnum.ERROR_C.getKey());
List<String> results = Arrays.asList(ItemReportKeyEnum.RESULT_A.getKey(),
ItemReportKeyEnum.RESULT_B.getKey(), ItemReportKeyEnum.RESULT_C.getKey());
for (int i = 0; i < phases.length; i++) {
DetectionData phase = phases[i];
row.put(standards.get(i), phase == null ? "/" : valueOrSlash(phase.getResultData()));
row.put(tests.get(i), phase == null ? "/" : valueOrSlash(phase.getData()));
row.put(errors.get(i), phase == null || phase.getErrorData() == null ? "/" : format(phase.getErrorData()));
row.put(results.get(i), phase == null ? "/" : resultText(phase.getIsData()));
}
}
private static DetectionData phaseAverage(SimAndDigNonHarmonicResult result) {
DetectionData[] phases = phases(result);
BigDecimal sum = BigDecimal.ZERO;
int count = 0;
for (DetectionData phase : phases) {
if (phase != null && phase.getData() != null) {
sum = sum.add(BigDecimal.valueOf(phase.getData()));
count++;
}
}
if (count == 0) {
return null;
}
DetectionData data = new DetectionData();
data.setData(sum.divide(BigDecimal.valueOf(count), 8, RoundingMode.HALF_UP).doubleValue());
return data;
}
private static DetectionData[] phases(SimAndDigNonHarmonicResult result) {
return new DetectionData[]{
parse(result.getAValue()),
parse(result.getBValue()),
parse(result.getCValue())
};
}
private static DetectionData firstPresent(DetectionData... values) {
if (values == null) {
return null;
}
for (DetectionData value : values) {
if (value != null) {
return value;
}
}
return null;
}
private static DetectionData preferPrimary(DetectionData current, DetectionData candidate) {
return current != null ? current : candidate;
}
private static DetectionData parse(String value) {
if (StrUtil.isBlank(value)) {
return null;
}
return JSONUtil.toBean(value, DetectionData.class);
}
private static boolean equalsCode(String actual, String expected) {
return expected.equalsIgnoreCase(actual);
}
private static String resultText(Integer isData) {
if (isData == null) {
return "/";
}
if (isData == 1) {
return "合格";
}
if (isData == 2) {
return "不合格";
}
return "/";
}
private static String valueOrSlash(Double value) {
return value == null ? "/" : format(value);
}
private static String format(Double value) {
return value == null ? "/" : format(BigDecimal.valueOf(value));
}
private static String format(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP).toPlainString();
}
private static String dealErrorScope(String errorScope) {
if (StrUtil.isBlank(errorScope)) {
return "/";
}
if (errorScope.contains("~")) {
String[] split = errorScope.split("~");
String begin = split[0];
if (begin.startsWith("-")) {
begin = begin.substring(1);
}
if (split.length > 1 && split[1].equalsIgnoreCase(begin)) {
return "±" + begin;
}
}
return errorScope;
}
}

View File

@@ -0,0 +1,165 @@
package com.njcn.gather.result.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.njcn.gather.detection.pojo.vo.DetectionData;
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* IMBV/IMBA 报告结果行装配:同一 sort 下的不平衡度 T 值与序分量 ABC 值合并为一行。
*/
public final class UnbalanceResultAssembler {
private UnbalanceResultAssembler() {
}
public static List<Map<String, String>> assembleRows(List<SimAndDigNonHarmonicResult> results) {
if (CollUtil.isEmpty(results)) {
return java.util.Collections.emptyList();
}
Map<Integer, List<SimAndDigNonHarmonicResult>> bySort = results.stream()
.filter(result -> result.getSort() != null)
.collect(Collectors.groupingBy(SimAndDigNonHarmonicResult::getSort, TreeMap::new, Collectors.toList()));
return bySort.values().stream()
.map(UnbalanceResultAssembler::assembleRow)
.filter(row -> row != null)
.collect(Collectors.toList());
}
private static Map<String, String> assembleRow(List<SimAndDigNonHarmonicResult> sameSortResults) {
Map<String, String> row = defaultRow();
boolean hasData = false;
for (SimAndDigNonHarmonicResult result : sameSortResults) {
String code = result.getAdType();
if (equalsAny(code, "V_UNBAN", "I_UNBAN")) {
DetectionData data = parse(result.getTValue());
if (data != null) {
putPrimary(row, data);
hasData = true;
}
} else if (equalsAny(code, "SeqV", "SeqA")) {
hasData |= putSequence(row, result);
}
}
return hasData ? row : null;
}
private static Map<String, String> defaultRow() {
Map<String, String> row = new LinkedHashMap<>();
for (ItemReportKeyEnum key : Arrays.asList(
ItemReportKeyEnum.STANDARD,
ItemReportKeyEnum.TEST,
ItemReportKeyEnum.ERROR,
ItemReportKeyEnum.ERROR_SCOPE,
ItemReportKeyEnum.POS_SEQ,
ItemReportKeyEnum.NEG_SEQ,
ItemReportKeyEnum.ZERO_SEQ,
ItemReportKeyEnum.RESULT)) {
row.put(key.getKey(), "/");
}
return row;
}
private static void putPrimary(Map<String, String> row, DetectionData data) {
row.put(ItemReportKeyEnum.STANDARD.getKey(), valueOrSlash(data.getResultData()));
row.put(ItemReportKeyEnum.TEST.getKey(), valueOrSlash(data.getData()));
row.put(ItemReportKeyEnum.ERROR.getKey(), data.getErrorData() == null ? "/" : format(data.getErrorData()));
String errorScope = dealErrorScope(data.getRadius());
if (StrUtil.isNotBlank(data.getUnit()) && !"/".equals(errorScope)) {
errorScope = errorScope.concat(data.getUnit());
}
row.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope);
row.put(ItemReportKeyEnum.RESULT.getKey(), resultText(data.getIsData()));
}
private static boolean putSequence(Map<String, String> row, SimAndDigNonHarmonicResult result) {
boolean hasData = false;
hasData |= putData(row, ItemReportKeyEnum.POS_SEQ.getKey(), parse(result.getAValue()));
hasData |= putData(row, ItemReportKeyEnum.NEG_SEQ.getKey(), parse(result.getBValue()));
hasData |= putData(row, ItemReportKeyEnum.ZERO_SEQ.getKey(), parse(result.getCValue()));
return hasData;
}
private static boolean putData(Map<String, String> row, String key, DetectionData data) {
if (data == null || data.getData() == null) {
return false;
}
row.put(key, format(data.getData()));
return true;
}
private static DetectionData parse(String value) {
if (StrUtil.isBlank(value)) {
return null;
}
return JSONUtil.toBean(value, DetectionData.class);
}
private static String resultText(Integer isData) {
if (isData == null) {
return "/";
}
if (isData == 1) {
return "合格";
}
if (isData == 2) {
return "不合格";
}
if (isData == 4) {
return "无法比较";
}
return "/";
}
private static String valueOrSlash(Double value) {
return value == null ? "/" : format(value);
}
private static String format(Double value) {
return value == null ? "/" : format(BigDecimal.valueOf(value));
}
private static String format(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP).toPlainString();
}
private static String dealErrorScope(String errorScope) {
if (StrUtil.isBlank(errorScope)) {
return "/";
}
if (errorScope.contains("~")) {
String[] split = errorScope.split("~");
String begin = split[0];
if (begin.startsWith("-")) {
begin = begin.substring(1);
}
if (split.length > 1 && split[1].equalsIgnoreCase(begin)) {
return "±" + begin;
}
}
return errorScope;
}
private static boolean equalsAny(String actual, String... expectedValues) {
if (actual == null) {
return false;
}
for (String expected : expectedValues) {
if (expected.equalsIgnoreCase(actual)) {
return true;
}
}
return false;
}
}

View File

@@ -104,6 +104,18 @@ public class PqScriptDtls implements Serializable {
@TableField("FAfterTime")
private Double fAfterTime;
/**
* 暂态写入时间S
*/
@TableField("FRampIn")
private Double fRampIn;
/**
* 暂态写出时间S
*/
@TableField("FRampOut")
private Double fRampOut;
/**
* 变动频度(次/min
*/

Some files were not shown because too many files have changed in this diff Show More