79 Commits

Author SHA1 Message Date
caozehui
744c72dea2 微调 2025-06-04 22:15:17 +08:00
caozehui
b4114f19de 微调 2025-06-03 19:53:17 +08:00
caozehui
b0dde94314 微调 2025-06-03 11:31:56 +08:00
caozehui
da7015fd89 微调 2025-05-30 16:26:32 +08:00
caozehui
9058c9081b 微调 2025-05-30 15:48:59 +08:00
caozehui
34f317780e 微调 2025-05-29 10:50:17 +08:00
caozehui
708b40880e 微调 2025-05-27 15:54:31 +08:00
caozehui
bf661b5c1c 微调 2025-05-26 16:24:21 +08:00
caozehui
57b08a99c6 1、检测计划、被检设备导入导出功能调整
2、多台设备类型同时进行脚本与ICD检验时Socket异常中断
2025-05-26 15:21:21 +08:00
8bc8a97e83 优化部分代码 2025-05-26 14:26:57 +08:00
caozehui
53548aec32 监测计划导出bug 2025-05-23 16:33:04 +08:00
caozehui
1380af6d50 复检测试项bug、设备连接异常提示信息、心跳空指针异常 2025-05-23 15:34:01 +08:00
caozehui
21dcd87be2 1、切换误差体系后报告生成bug
2、正式检测时,内外数据结果不一致
2025-05-23 10:04:35 +08:00
caozehui
fb97e421bb 1、暂态-电压幅值单位问题
2、脚本与ICD校验时10500错误码
3、前端断开WebSocket连接后,后台服务没有关闭和源、设备的Socket连接问题
2025-05-22 20:01:58 +08:00
caozehui
4f2ae176fa 微调 2025-05-21 15:11:42 +08:00
caozehui
06e21711f2 微调 2025-05-20 16:26:50 +08:00
caozehui
95c564595f 微调 2025-05-16 16:12:47 +08:00
caozehui
e725cd8a60 归档前如果设备没有生成报告则自动生成报告 2025-05-16 10:35:14 +08:00
caozehui
8507ad8378 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	detection/src/main/java/com/njcn/gather/detection/service/impl/DetectionServiceImpl.java
2025-05-15 15:25:10 +08:00
caozehui
cb8495fb0d 数据处理原则-所有值入库数据bug 2025-05-15 15:24:17 +08:00
caozehui
8f8d3d38cc 数据处理原则-所有值入库数据bug 2025-05-15 15:10:09 +08:00
caozehui
7eb80121a1 省级平台在正式检测时增加温度、相对湿度参数 2025-05-15 08:57:36 +08:00
caozehui
3736082096 区分楼下、省级平台场景的报告路径 2025-05-14 09:07:38 +08:00
caozehui
2f303e63a3 检测计划新增数据处理原则字段、全局配置中移除数据处理原则字段 2025-05-14 08:57:24 +08:00
caozehui
ab2e5c346e 微调 2025-05-13 14:41:50 +08:00
caozehui
ebb45238b0 楼下模板表格过宽bug 2025-05-13 11:23:31 +08:00
caozehui
6763721043 脚本检测大项启用/禁用功能 2025-05-12 16:34:42 +08:00
caozehui
e235c3ef66 预检测在相序校验不合格时没有关闭源bug 2025-05-12 14:36:27 +08:00
caozehui
40b0e535cb 不合格项复检bug 2025-05-09 08:51:14 +08:00
caozehui
9438301ebd 微调 2025-05-08 16:07:39 +08:00
caozehui
bfed1b3e93 复检bug 2025-05-08 15:27:52 +08:00
caozehui
a9515f42b3 微调 2025-05-07 14:04:26 +08:00
caozehui
bbb62586f9 微调 2025-05-07 11:33:57 +08:00
caozehui
6aef21797d 微调 2025-05-06 10:43:19 +08:00
caozehui
b7a90ebeb4 微调 2025-05-06 10:08:38 +08:00
caozehui
67665d3762 微调 2025-04-30 16:31:19 +08:00
caozehui
41252af4e9 复检时脚本查询结果错误bug 2025-04-30 10:27:11 +08:00
caozehui
2869f66154 闪变接收数据超时bug 2025-04-29 13:13:09 +08:00
wr
2bdaabac6e 优化数据源问题,删除检测脚本中值类型,由绑定检测计划中数据源来,获取是实时数据还是分钟数据 2025-04-29 11:36:04 +08:00
caozehui
4b41e2edd1 生成报告路径不包含设备类型 2025-04-29 09:07:36 +08:00
caozehui
5fa09bb41b 微调 2025-04-28 11:40:32 +08:00
caozehui
c96cadc5d1 暂态周波可以是小数 2025-04-25 14:34:00 +08:00
caozehui
b471a05181 微调 2025-04-24 11:39:18 +08:00
caozehui
e42a2c8309 微调 2025-04-23 15:30:24 +08:00
ea585a65ff 原始数据入库bug 2025-04-22 16:56:53 +08:00
wr
59ba5c0a0c 调整正式检测公式逻辑,优化绝对值,相对值信息 2025-04-22 15:02:38 +08:00
caozehui
99d43041cb 微调 2025-04-22 14:20:21 +08:00
wr
aa5f57a856 解决暂态下发幅值问题 2025-04-22 14:12:18 +08:00
caozehui
9fc0fbcbcf 微调 2025-04-21 19:22:25 +08:00
caozehui
434dc676ce 误差体系新增ValueType、errorUnit字段,并修改相关接口 2025-04-21 14:52:27 +08:00
ea83963d33 原始数据入库bug 2025-04-21 13:12:58 +08:00
caozehui
257df0a511 微调 2025-04-21 11:38:56 +08:00
496cff6c11 监测脚本排序调整 2025-04-21 11:31:08 +08:00
caozehui
484f9c9f4c 微调 2025-04-21 09:53:15 +08:00
wr
19b69eed0e Merge remote-tracking branch 'origin/master' 2025-04-21 09:08:45 +08:00
wr
b165365203 微调 2025-04-21 09:07:22 +08:00
caozehui
a42dcd1d4b 重新计算接口调整 2025-04-21 09:02:28 +08:00
caozehui
be3df5c497 微调 2025-04-18 15:59:05 +08:00
wr
7b951fa4b6 1.解决不可同时测试电压,电流问题 2025-04-18 15:34:49 +08:00
caozehui
89a7b5b8f6 微调 2025-04-18 14:25:50 +08:00
caozehui
102aa504e6 微调 2025-04-17 10:36:05 +08:00
d1cbfcedcc Merge remote-tracking branch 'origin/master' 2025-04-15 15:33:28 +08:00
116563f13e 优化部分代码 2025-04-15 15:33:19 +08:00
caozehui
55bf90d0af 日志导出csv功能、报告按照修改时间倒序排列 2025-04-15 10:14:52 +08:00
caozehui
7ac01b0f5e 微调 2025-04-14 19:12:59 +08:00
1a28d25026 优化部分代码 2025-04-14 18:38:08 +08:00
caozehui
92b0640f9c 微调 2025-04-14 14:47:51 +08:00
caozehui
4a2fb595d0 icd校验 2025-04-14 13:21:25 +08:00
56dd19b32e 调整方法名 2025-04-14 08:49:54 +08:00
caozehui
8460574f10 日志分页查询调整 2025-04-11 14:35:44 +08:00
6f890daad6 浙江报告与日志功能 2025-04-11 11:03:16 +08:00
caozehui
6727dee61e 建表语句调整 2025-04-10 16:08:21 +08:00
wr
3fcad5ff76 解决暂态测试项,icd分项和不分项功能优化 2025-04-10 15:25:02 +08:00
1fe7866970 监测脚本排序调整 2025-04-09 16:23:22 +08:00
caozehui
b96d0cdeb1 微调 2025-04-09 16:16:33 +08:00
0c30603f31 监测脚本排序调整 2025-04-09 15:04:19 +08:00
caozehui
64bdba9fa2 微调 2025-04-08 16:10:37 +08:00
caozehui
c7a45b5500 bug修复 2025-04-08 10:10:12 +08:00
42701db2d5 监测脚本排序调整 2025-04-07 10:23:24 +08:00
147 changed files with 5906 additions and 1935 deletions

View File

@@ -74,6 +74,44 @@
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j -->
<!-- <dependency>-->
<!-- <groupId>org.docx4j</groupId>-->
<!-- <artifactId>docx4j-core</artifactId>-->
<!-- <version>8.3.8</version>-->
<!-- </dependency>-->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version> <!-- 您可以根据需要选择其他版本 -->
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>

View File

@@ -21,6 +21,9 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author chendaofei
*/
@Slf4j
@Api(tags = "预检测")
@RestController
@@ -30,15 +33,6 @@ public class PreDetectionController extends BaseController {
private final PreDetectionService preDetectionService;
private final DetectionServiceImpl detectionServiceImpl;
private final IPqScriptDtlsService pqScriptDtlsService;
private final IPqDevService iPqDevService;
private final SocketDevResponseService socketDevResponseService;
/**
* 开始检测
*/

View File

@@ -1,41 +0,0 @@
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.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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wr
* @description
* @date 2024/12/10 14:25
*/
@Slf4j
@Api(tags = "守时检测")
@RestController
@RequestMapping("/punctuality")
@RequiredArgsConstructor
public class PunctualityController extends BaseController {
// private final PunctualityService punctualityService;
@OperateInfo
@PostMapping("/deliveryTime")
@ApiOperation("下发守时检测")
@ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
public HttpResult<?> list(@RequestBody Object param) {
String methodDescribe = getMethodDescribe("list");
// punctualityService.triggerTimeMark();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -7,10 +7,12 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.njcn.gather.detection.pojo.dto.DevXiNumData;
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.po.DevData;
import com.njcn.gather.detection.pojo.po.IcdCheckData;
import com.njcn.gather.detection.pojo.po.SourceCompareDev;
import com.njcn.gather.detection.pojo.vo.*;
import com.njcn.gather.detection.service.impl.DetectionServiceImpl;
@@ -18,20 +20,22 @@ import com.njcn.gather.detection.util.socket.*;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.storage.pojo.param.StorageParam;
import com.njcn.gather.storage.pojo.po.AdHarmonicResult;
import com.njcn.gather.storage.pojo.po.AdNonHarmonicResult;
import com.njcn.gather.storage.service.AdHarmonicService;
import com.njcn.gather.storage.service.DetectionDataDealService;
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
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 com.njcn.gather.system.reg.service.ISysRegResService;
import lombok.RequiredArgsConstructor;
@@ -52,6 +56,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.njcn.gather.detection.util.socket.FormalTestManager.harmonicRelationMap;
@Service
@RequiredArgsConstructor
@@ -67,6 +73,9 @@ public class SocketDevResponseService {
// ISO 8601格式
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
private List<String> dataTypeList;
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> harmonicList = Stream.of(DicDataEnum.HV.getCode(), DicDataEnum.HI.getCode(), DicDataEnum.HP.getCode(), DicDataEnum.HSV.getCode(), DicDataEnum.HSI.getCode()).collect(Collectors.toList());
@@ -82,6 +91,8 @@ public class SocketDevResponseService {
private final ISysTestConfigService sysTestConfigService;
private final AdHarmonicService adHarmonicService;
private final IAdPlanService adPlanService;
private final IPqScriptCheckDataService pqScriptCheckDataService;
private final IDictDataService dictDataService;
@Value("${phaseAngle.isEnable}")
private Boolean isPhaseAngle;
@@ -105,6 +116,11 @@ public class SocketDevResponseService {
*/
Set<String> failComm = new HashSet<>();
/**
* 存放从装置收到的icd校验数据。key为icdTypevalue为IcdCheckData
*/
Map<String, IcdCheckData> icdCheckDataMap = new HashMap<>();
/**
* 保存成功的协议
*/
@@ -761,83 +777,156 @@ public class SocketDevResponseService {
System.out.println(successComm.size() + "=====" + FormalTestManager.monitorIdListComm.size());
if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
SocketDataMsg temMsg = new SocketDataMsg();
temMsg.setCode(SourceResponseCodeEnum.DEV_COMM_ALL_SUCCESS.getCode());
temMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_03.getValue());
temMsg.setRequestId(SourceOperateCodeEnum.YJC_XYJY.getValue());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(temMsg));
//开始下源控制脚本
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
List<SourceIssue> sourceIssues;
if (SourceOperateCodeEnum.FORMAL_TEST.getValue().equals(param.getOperateType()) || SourceOperateCodeEnum.RE_ERROR_TEST.getValue().equals(param.getOperateType())) {
if (param.getOperateType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
//不合格项复检
StorageParam storageParam = new StorageParam();
storageParam.setCode(param.getCode());
storageParam.setScriptId(param.getScriptId());
List<Integer> indexes = adHarmonicService.getIndex(storageParam, true);
issueParam.setIndexList(indexes);
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.RE_ERROR_TEST.getValue());
} else {
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.FORMAL_TEST.getValue());
}
//正式检测
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
sourceIssues = sourceIssues.stream().sorted(Comparator.comparing(SourceIssue::getIndex)).collect(Collectors.toList());
// 存放所有检测小项
SocketManager.addSourceList(sourceIssues);
// 按照大项分组。key为大项codevalue为小项个数
Map<String, Long> sourceIssueMap = sourceIssues.stream().collect(Collectors.groupingBy(SourceIssue::getType, Collectors.counting()));
SocketManager.initMap(sourceIssueMap);
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssues.get(0).getType());
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
//告诉前端当前项开始了
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(sourceIssues.get(0).getType() + stepBegin);
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
} else if (SourceOperateCodeEnum.PRE_TEST.getValue().equals(param.getOperateType()) || SourceOperateCodeEnum.COEFFICIENT_TEST.getValue().equals(param.getOperateType())) {
//预检测的相序检测 以及系数校验都需要进行相序检测
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.PHASE_TEST.getValue());
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
} else if (SourceOperateCodeEnum.TEST_TEM_START.getValue().equals(param.getOperateType())) {
//暂停检测后的继续检测
System.out.println("进入暂停后的继续检测》》》》》》》》》》》》》》》》》》》》》》》》》》》" + "剩余检测小项" + SocketManager.getSourceList().size());
if (CollUtil.isNotEmpty(SocketManager.getSourceList())) {
SourceIssue sourceIssue = SocketManager.getSourceList().get(0);
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssue.getType());
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssue));
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
}
} else {
}
successComm.clear();
failComm.clear();
icdCheckDataMap.clear();
dataTypeList = pqScriptDtlsService.getScriptToIcdCheckInfo(param);
icdTypeList = FormalTestManager.devList.stream().map(PreDetection::getIcdType).distinct().collect(Collectors.toList());
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XYJY.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.VERIFY_MAPPING$01.getValue());
Map<String, Object> map = new HashMap<>(2);
map.put("dataType", dataTypeList);
map.put("icdType", icdTypeList.get(0));
socketMsg.setData(JSON.toJSONString(map));
System.out.println("开始脚本与icd校验:++++++++++");
SocketManager.sendMsg(s, JSON.toJSONString(socketMsg));
}
completeJudgment(param);
} else if (socketDataMsg.getOperateCode().equals(SourceOperateCodeEnum.VERIFY_MAPPING$01.getValue())) {
String data = socketDataMsg.getData();
IcdCheckData icdCheckData = JSON.parseObject(data, IcdCheckData.class);
boolean isContinue = true;
for (int i = 0; i < icdCheckData.getResultData().size(); i++) {
IcdCheckData.ResultData item = icdCheckData.getResultData().get(i);
Integer errorType = getErrorType(item.getDesc(), item.getPhaseResult());
// 校验脚本与icd校验失败
if (errorType.equals(0)) {
isContinue = false;
Map<String, Object> map = new HashMap<>(2);
map.put("icdType", icdCheckData.getIcdType());
DetectionCodeEnum anEnum = DetectionCodeEnum.getDetectionCodeByCode(item.getDesc());
map.put("dataType", anEnum.getMessage());
WebSocketVO<String> webSocketVO = new WebSocketVO<>();
webSocketVO.setData(JSON.toJSONString(map));
webSocketVO.setRequestId(SourceOperateCodeEnum.YJC_XYJY.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.VERIFY_MAPPING$01.getValue());
webSocketVO.setCode(SourceResponseCodeEnum.SUCCESS.getCode());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
CnSocketUtil.quitSend(param);
break;
}
}
icdCheckDataMap.put(icdCheckData.getIcdType(), icdCheckData);
if (isContinue) {
//System.out.println("icdCheckDataMap.size()="+icdCheckDataMap.size()+",icdTypeList.size()="+icdTypeList.size());
if (icdCheckDataMap.size() == icdTypeList.size()) {
SocketDataMsg temMsg = new SocketDataMsg();
temMsg.setCode(SourceResponseCodeEnum.DEV_COMM_ALL_SUCCESS.getCode());
temMsg.setOperateCode(SourceOperateCodeEnum.VERIFY_MAPPING$01.getValue());
temMsg.setRequestId(SourceOperateCodeEnum.YJC_XYJY.getValue());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(temMsg));
//开始下源控制脚本
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
List<SourceIssue> sourceIssues;
if (SourceOperateCodeEnum.FORMAL_TEST.getValue().equals(param.getOperateType()) || SourceOperateCodeEnum.RE_ERROR_TEST.getValue().equals(param.getOperateType())) {
if (param.getOperateType().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(SourceOperateCodeEnum.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);
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssues.get(0).getType());
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
//告诉前端当前项开始了
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(sourceIssues.get(0).getType() + stepBegin);
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
} else if (SourceOperateCodeEnum.PRE_TEST.getValue().equals(param.getOperateType()) || SourceOperateCodeEnum.COEFFICIENT_TEST.getValue().equals(param.getOperateType())) {
//预检测的相序检测 以及系数校验都需要进行相序检测
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.PHASE_TEST.getValue());
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
} else if (SourceOperateCodeEnum.TEST_TEM_START.getValue().equals(param.getOperateType())) {
//暂停检测后的继续检测
System.out.println("进入暂停后的继续检测》》》》》》》》》》》》》》》》》》》》》》》》》》》" + "剩余检测小项" + SocketManager.getSourceList().size());
if (CollUtil.isNotEmpty(SocketManager.getSourceList())) {
SourceIssue sourceIssue = SocketManager.getSourceList().get(0);
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssue.getType());
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
socketMsg.setData(JSON.toJSONString(sourceIssue));
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(socketMsg));
}
} else {
}
} else {
// 发送下一个脚本与icd校验
String icdType = icdTypeList.stream().filter(it -> !icdCheckDataMap.containsKey(it)).findFirst().orElse(null);
if (ObjectUtil.isNotNull(icdType)) {
Map<String, Object> map = new HashMap<>(2);
map.put("dataType", dataTypeList);
map.put("icdType", icdType);
socketMsg.setData(JSON.toJSONString(map));
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XYJY.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.VERIFY_MAPPING$01.getValue());
System.out.println("开始脚本与icd校验:++++++++++");
SocketManager.sendMsg(s, JSON.toJSONString(socketMsg));
}
}
}
}
break;
case UNPROCESSED_BUSINESS:
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(socketDataMsg));
@@ -858,12 +947,44 @@ public class SocketDevResponseService {
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(socketDataMsg));
CnSocketUtil.quitSend(param);
break;
case ICD_NOT_FOUND:
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(socketDataMsg));
CnSocketUtil.quitSend(param);
break;
default:
CnSocketUtil.sendUnSocket(param.getUserPageId());
break;
}
}
/**
* 获取错误类型
*
* @param desc
* @param list
* @return
*/
private Integer getErrorType(String desc, DevData.SqlDataDTO.ListDTO list) {
if (ObjectUtil.isNotNull(list)) {
if (DetectionCodeEnum.MAG.getCode().equals(desc) || DetectionCodeEnum.DUR.getCode().equals(desc)) {
if (ObjectUtil.isNull(list.getA()) && ObjectUtil.isNull(list.getB()) && ObjectUtil.isNull(list.getC()) && ObjectUtil.isNull(list.getT())) {
return 0;
} else {
return 1;
}
} else if (DetectionCodeEnum.I_UNBAN.getCode().equals(desc) || DetectionCodeEnum.V_UNBAN.getCode().equals(desc)) {
if (ObjectUtil.isNotNull(list.getA()) && list.getA().equals(0.0) && ObjectUtil.isNotNull(list.getB()) && list.getB().equals(1.0) && ObjectUtil.isNotNull(list.getC()) && list.getC().equals(1.0) || ObjectUtil.isNotNull(list.getT()) && list.getT().equals(1.0)) {
return 1;
}
} else {
if (ObjectUtil.isNotNull(list.getA()) && list.getA().equals(1.0) && ObjectUtil.isNotNull(list.getB()) && list.getB().equals(1.0) && ObjectUtil.isNotNull(list.getC()) && list.getC().equals(1.0) || ObjectUtil.isNotNull(list.getT()) && list.getT().equals(1.0)) {
return 1; // 装置上送错误
}
}
}
return 0; // icd文件与脚本不匹配
}
/**
* 相序校验
@@ -876,86 +997,92 @@ public class SocketDevResponseService {
if (ObjectUtil.isNotNull(dictDataEnumByCode)) {
switch (dictDataEnumByCode) {
case SUCCESS:
devInfo.add(devData);
successComm.add(devData.getId());
if (devData.getResult()) {
devInfo.add(devData);
successComm.add(devData.getId());
if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
System.out.println("相序校验接受数据完成---------" + successComm.size() + "__" + FormalTestManager.monitorIdListComm.size());
if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
System.out.println("相序校验接受数据完成---------" + successComm.size() + "__" + FormalTestManager.monitorIdListComm.size());
PqScriptIssueParam sourceParam = new PqScriptIssueParam();
sourceParam.setPlanId(param.getPlanId());
sourceParam.setDevIds(param.getDevIds());
sourceParam.setIsPhaseSequence(SourceOperateCodeEnum.PHASE_TEST.getValue());
sourceParam.setScriptId(param.getScriptId());
sourceParam.setSourceId(param.getSourceId());
List<SourceIssue> sourceIssues = scriptDtlsService.listSourceIssue(sourceParam);
List<SourceCompareDev> info = new ArrayList<>();
if (CollUtil.isNotEmpty(sourceIssues)) {
devInfo.stream().sorted(Comparator.comparing(DevData::getId));
info.addAll(devIsSource(devInfo, sourceIssues.get(0)));
}
if (CollUtil.isNotEmpty(info)) {
SocketDataMsg dataMsg = new SocketDataMsg();
dataMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
dataMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
dataMsg.setCode(SourceResponseCodeEnum.SUCCESS.getCode());
PqScriptIssueParam sourceParam = new PqScriptIssueParam();
sourceParam.setPlanId(param.getPlanId());
sourceParam.setDevIds(param.getDevIds());
sourceParam.setIsPhaseSequence(SourceOperateCodeEnum.PHASE_TEST.getValue());
sourceParam.setScriptId(param.getScriptId());
sourceParam.setSourceId(param.getSourceId());
List<SourceIssue> sourceIssues = scriptDtlsService.listSourceIssue(sourceParam);
List<SourceCompareDev> info = new ArrayList<>();
if (CollUtil.isNotEmpty(sourceIssues)) {
devInfo.stream().sorted(Comparator.comparing(DevData::getId));
info.addAll(devIsSource(devInfo, sourceIssues.get(0)));
}
if (CollUtil.isNotEmpty(info)) {
SocketDataMsg dataMsg = new SocketDataMsg();
dataMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
dataMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
dataMsg.setCode(SourceResponseCodeEnum.SUCCESS.getCode());
for (SourceCompareDev sourceCompareDev : info) {
dataMsg.setData(sourceCompareDev.getDevName() + splitTag + sourceCompareDev.getLineNum() + "校验结果:" + sourceCompareDev.getDesc());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(dataMsg));
for (SourceCompareDev sourceCompareDev : info) {
dataMsg.setData(sourceCompareDev.getDevName() + splitTag + sourceCompareDev.getLineNum() + "校验结果:" + sourceCompareDev.getDesc());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(dataMsg));
}
if (info.stream().anyMatch(it -> !it.getIsQualified())) {
WebSocketVO<String> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
webSocketVO.setCode(SourceResponseCodeEnum.PHASE_CHECK_FAIL.getCode());
webSocketVO.setData(SourceResponseCodeEnum.PHASE_CHECK_FAIL.getMessage());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
CnSocketUtil.quitSend(param);
return;
}
//向前端推送消息
SocketDataMsg temMsg = new SocketDataMsg();
temMsg.setCode(SourceResponseCodeEnum.DEV_COMM_ALL_SUCCESS.getCode());
temMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
temMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(temMsg));
successComm.clear();
}
if (info.stream().anyMatch(it -> !it.getIsQualified())) {
WebSocketVO<String> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
webSocketVO.setCode(SourceResponseCodeEnum.PHASE_CHECK_FAIL.getCode());
webSocketVO.setData(SourceResponseCodeEnum.PHASE_CHECK_FAIL.getMessage());
if (param.getOperateType().equals(SourceOperateCodeEnum.PRE_TEST.getValue())) {
System.out.println("预检测流程结束-----------------关闭源");
//同时关闭设备三个步骤
CnSocketUtil.quitSend(param);
} else if (param.getOperateType().equals(SourceOperateCodeEnum.COEFFICIENT_TEST.getValue())) {
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.big_start.getValue());
webSocketVO.setData(XiNumberManager.devParameterList.get(0));
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
return;
//下发命令获取所有装置通道系数,首先需要获取所有装置,通过所有装置下发获取系数命令,目前只支持单台装置获取系数
socketMsg.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.DATA_CHNFACTOR$01.getValue());
PreDetection preDetection = XiNumberManager.xiDevList.get(0);
Map<String, Object> map = new HashMap<>();
map.put("devIP", preDetection.getDevIP());
map.put("chnNum", preDetection.getDevChns());
socketMsg.setData(JSON.toJSONString(map));
SocketManager.sendMsg(param.getUserPageId() + handlerStr, JSON.toJSONString(socketMsg));
XiNumberManager.stepNumber = 0;
XiNumberManager.devXiList.clear();
XiNumberManager.devXiNumDataMap.clear();
XiNumberManager.smallDevXiNumDataMap.clear();
System.out.println("开始系数校准》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
}
//向前端推送消息
SocketDataMsg temMsg = new SocketDataMsg();
temMsg.setCode(SourceResponseCodeEnum.DEV_COMM_ALL_SUCCESS.getCode());
temMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
temMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(temMsg));
successComm.clear();
}
if (param.getOperateType().equals(SourceOperateCodeEnum.PRE_TEST.getValue())) {
System.out.println("预检测流程结束-----------------关闭源");
//同时关闭设备三个步骤
CnSocketUtil.quitSend(param);
} else if (param.getOperateType().equals(SourceOperateCodeEnum.COEFFICIENT_TEST.getValue())) {
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
webSocketVO.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
webSocketVO.setOperateCode(SourceOperateCodeEnum.big_start.getValue());
webSocketVO.setData(XiNumberManager.devParameterList.get(0));
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
//下发命令获取所有装置通道系数,首先需要获取所有装置,通过所有装置下发获取系数命令,目前只支持单台装置获取系数
socketMsg.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.DATA_CHNFACTOR$01.getValue());
PreDetection preDetection = XiNumberManager.xiDevList.get(0);
Map<String, Object> map = new HashMap<>();
map.put("devIP", preDetection.getDevIP());
map.put("chnNum", preDetection.getDevChns());
socketMsg.setData(JSON.toJSONString(map));
SocketManager.sendMsg(param.getUserPageId() + handlerStr, JSON.toJSONString(socketMsg));
XiNumberManager.stepNumber = 0;
XiNumberManager.devXiList.clear();
XiNumberManager.devXiNumDataMap.clear();
XiNumberManager.smallDevXiNumDataMap.clear();
System.out.println("开始系数校准》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
}
} else {
System.out.println("被抛除的数据:" + data);
}
break;
case UNPROCESSED_BUSINESS:
@@ -999,102 +1126,111 @@ public class SocketDevResponseService {
switch (Objects.requireNonNull(dictDataEnumByCode)) {
case SUCCESS:
FormalTestManager.realDataXiList.add(devData);
successComm.add(devData.getId());
if (devData.getResult()) {
FormalTestManager.realDataXiList.add(devData);
successComm.add(devData.getId());
if (SocketManager.clockMap.containsKey(sourceIssue.getIndex())) {
SocketManager.clockMap.put(sourceIssue.getIndex(), 0L);
}
if (SocketManager.clockMap.containsKey(sourceIssue.getIndex())) {
SocketManager.clockMap.put(sourceIssue.getIndex(), 0L);
}
if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
System.out.println(sourceIssue.getType() + splitTag + sourceIssue.getIndex() + "当前测试小项读取数据已经全部结束。。。。。。。。。");
//修改装置为监测中
if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
System.out.println(sourceIssue.getType() + splitTag + sourceIssue.getIndex() + "当前测试小项读取数据已经全部结束。。。。。。。。。");
//修改装置为监测中
// adPlanService.updateTestState(param.getPlanId(), param.getDevIds());
//开启线程进行入库原始数据操作
baseDataInsert(FormalTestManager.realDataXiList, sourceIssue, param, SocketManager.valueTypeMap);
//开启线程进行入库原始数据操作
baseDataInsert(FormalTestManager.realDataXiList, sourceIssue, param, SocketManager.valueTypeMap);
//调用判断方法
Map<String, Integer> textResult = detectionServiceImpl.processing(FormalTestManager.realDataXiList, param, FormalTestManager.devIdMapComm, sourceIssue, dataRule);
//调用判断方法
Map<String, Integer> textResult = detectionServiceImpl.processing(FormalTestManager.realDataXiList, param, FormalTestManager.devIdMapComm, sourceIssue, dataRule);
System.out.println(textResult);
//组装实体推送给前台
assWebJson(param, textResult, socketDataMsg, sourceIssue);
System.out.println(textResult);
//组装实体推送给前台
assWebJson(param, textResult, socketDataMsg, sourceIssue);
//当小项结束后需要删除集合中的小项
SocketManager.delSource(sourceIssue.getIndex());
System.out.println("当前小项结束进行删除============" + sourceIssue.getType() + splitTag + sourceIssue.getIndex());
//当小项结束后需要删除集合中的小项
SocketManager.delSource(sourceIssue.getIndex());
System.out.println("当前小项结束进行删除============" + sourceIssue.getType() + splitTag + sourceIssue.getIndex());
long residueCount = SocketManager.getSourceTarget(sourceIssue.getType()) - 1;
SocketManager.addTargetMap(sourceIssue.getType(), residueCount);
System.out.println("该大项还有" + residueCount + "个小项没有进行检测!!!!!!!!");
if (residueCount == 0) {
System.out.println(sourceIssue.getType() + sourceIssue.getIndex() + "当前测试大项已经全部结束》》》》》》》》");
//当residueCount为0则认为大项中的小项已经全部跑完开始组装信息推送给前端
List<DevLineTestResult> resultList = new ArrayList<>();
// 获取当前检测大项的所有设备的检测结果
List<DevLineTestResult> allDevTestList = targetTestMap.get(sourceIssue.getType());
Map<String, List<DevLineTestResult>> map = allDevTestList.stream().collect(Collectors.groupingBy(DevLineTestResult::getDeviceId));
map.forEach((dev, list) -> {
DevLineTestResult devTem = new DevLineTestResult();
devTem.setDeviceId(dev);
devTem.setDeviceName(list.get(0).getDeviceName());
Integer[] arr = list.get(0).getChnResult();
for (int i = 0; i < arr.length; i++) {
List<Integer[]> arrList = list.stream().map(DevLineTestResult::getChnResult).collect(Collectors.toList());
Integer[] resultArr = getMaxIntArray(arrList);
devTem.setChnResult(resultArr);
}
resultList.add(devTem);
});
allDevTestList.clear();
CnSocketUtil.sendToWebSocket(param.getUserPageId(), socketDataMsg.getRequestId().split(stepTag)[1] + stepEnd, null, resultList, null);
}
//在这一步判断是否已经触发暂停按钮
if (FormalTestManager.stopFlag && CollUtil.isNotEmpty(SocketManager.getSourceList())) {
FormalTestManager.stopTime = 0;
FormalTestManager.hasStopFlag = true;
successComm.clear();
FormalTestManager.realDataXiList.clear();
sendWebSocket(param.getUserPageId(), "preStopTest", "stop", null);
return;
}
//开始进行下一项检测
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
if (CollUtil.isNotEmpty(sourceIssueList)) {
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
// 如果上一个大项检测完成,则检测下一个大项,并向前端推送消息
long residueCount = SocketManager.getSourceTarget(sourceIssue.getType()) - 1;
SocketManager.addTargetMap(sourceIssue.getType(), residueCount);
System.out.println("该大项还有" + residueCount + "个小项没有进行检测!!!!!!!!");
if (residueCount == 0) {
CnSocketUtil.sendToWebSocket(param.getUserPageId(), sourceIssues.getType() + stepBegin, null, new ArrayList<>(), null);
System.out.println(sourceIssue.getType() + sourceIssue.getIndex() + "当前测试大项已经全部结束》》》》》》》》");
//当residueCount为0则认为大项中的小项已经全部跑完开始组装信息推送给前端
List<DevLineTestResult> resultList = new ArrayList<>();
// 获取当前检测大项的所有设备的检测结果
List<DevLineTestResult> allDevTestList = targetTestMap.get(sourceIssue.getType());
Map<String, List<DevLineTestResult>> map = allDevTestList.stream().collect(Collectors.groupingBy(DevLineTestResult::getDeviceId));
map.forEach((dev, list) -> {
DevLineTestResult devTem = new DevLineTestResult();
devTem.setDeviceId(dev);
devTem.setDeviceName(list.get(0).getDeviceName());
Integer[] arr = list.get(0).getChnResult();
for (int i = 0; i < arr.length; i++) {
List<Integer[]> arrList = list.stream().map(DevLineTestResult::getChnResult).collect(Collectors.toList());
Integer[] resultArr = getMaxIntArray(arrList);
devTem.setChnResult(resultArr);
}
resultList.add(devTem);
});
allDevTestList.clear();
CnSocketUtil.sendToWebSocket(param.getUserPageId(), socketDataMsg.getRequestId().split(stepTag)[1] + stepEnd, null, resultList, null);
}
//在这一步判断是否已经触发暂停按钮
if (FormalTestManager.stopFlag && CollUtil.isNotEmpty(SocketManager.getSourceList())) {
FormalTestManager.stopTime = 0;
FormalTestManager.hasStopFlag = true;
successComm.clear();
FormalTestManager.realDataXiList.clear();
sendWebSocket(param.getUserPageId(), "preStopTest", "stop", null);
return;
}
SocketMsg<String> xuMsg = new SocketMsg<>();
xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
xuMsg.setData(JSON.toJSONString(sourceIssues));
xuMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssues.getType());
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(xuMsg));
} else {
//TODO 是否最终检测完成需要推送给用户
PqScriptCheckDataParam checkDataParam = new PqScriptCheckDataParam();
checkDataParam.setScriptId(param.getScriptId());
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
//开始进行下一项检测
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
if (CollUtil.isNotEmpty(sourceIssueList)) {
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
// 如果上一个大项检测完成,则检测下一个大项,并向前端推送消息
if (residueCount == 0) {
CnSocketUtil.sendToWebSocket(param.getUserPageId(), sourceIssues.getType() + stepBegin, null, new ArrayList<>(), null);
}
SocketMsg<String> xuMsg = new SocketMsg<>();
xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
xuMsg.setData(JSON.toJSONString(sourceIssues));
xuMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssues.getType());
SocketManager.sendMsg(param.getUserPageId() + handlerSourceStr, JSON.toJSONString(xuMsg));
} else {
//TODO 是否最终检测完成需要推送给用户
PqScriptCheckDataParam checkDataParam = new PqScriptCheckDataParam();
checkDataParam.setScriptId(param.getScriptId());
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
CnSocketUtil.quitSend(param);
}
successComm.clear();
FormalTestManager.realDataXiList.clear();
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(),param.getUserId());
CnSocketUtil.quitSend(param);
}
successComm.clear();
FormalTestManager.realDataXiList.clear();
} else {
System.out.println("被抛除的数据:" + data);
}
break;
case UNPROCESSED_BUSINESS:
break;
case NORMAL_RESPONSE:
FormalTestManager.realDataXiList.add(devData);
if (devData.getResult()) {
if (SocketManager.clockMap.containsKey(sourceIssue.getIndex())) {
SocketManager.clockMap.put(sourceIssue.getIndex(), 0L);
}
FormalTestManager.realDataXiList.add(devData);
} else {
System.out.println("被抛除的数据:" + data);
}
break;
case DEV_ERROR:
@@ -1172,6 +1308,11 @@ public class SocketDevResponseService {
if (targetTestMap.containsKey(sourceIssue.getType())) {
List<DevLineTestResult> devLineTestResultList = targetTestMap.get(sourceIssue.getType());
// devListRes.forEach(it1 -> {
// devLineTestResultList.stream().filter(it2 -> it2.getDeviceId().equals(it1.getDeviceId())).findFirst().ifPresent(it2 -> {
// setNewChnResult(it2.getChnResult(), it1.getChnResult());
// });
// });
devLineTestResultList.addAll(devListRes);
} else {
targetTestMap.put(sourceIssue.getType(), devListRes);
@@ -1184,6 +1325,26 @@ public class SocketDevResponseService {
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
}
// private void setNewChnResult(Integer[] oldChnResult, Integer[] newChnResult) {
// for (int i = 0; i < oldChnResult.length; i++) {
// if (newChnResult[i] == 2) {
// oldChnResult[i] = 2;
// continue;
// }
// if (newChnResult[i] == 3 && oldChnResult[i] != 2) {
// oldChnResult[i] = 3;
// continue;
// }
// if (newChnResult[i] == 4 && oldChnResult[i] != 2) {
// oldChnResult[i] = 4;
// continue;
// }
// if (newChnResult[i] == 5 && oldChnResult[i] != 2 && oldChnResult[i] != 3 && oldChnResult[i] != 4) {
// oldChnResult[i] = 5;
// }
// }
// }
/**
* 返回大项检测结果,默认遇到 45时认为不参与计算
*/
@@ -1270,7 +1431,6 @@ public class SocketDevResponseService {
}
/**
*
* @param issue
* @return key为V或Ivalue为对应的源下发信息
*/
@@ -1298,8 +1458,8 @@ public class SocketDevResponseService {
List<DevData.SqlDataDTO> data,
List<DevData.SqlDataDTO> dataPhase) {
StringBuffer str = new StringBuffer();
if(isPhaseAngle){
if(CollUtil.isNotEmpty(data)&&CollUtil.isNotEmpty(dataPhase)){
if (isPhaseAngle) {
if (CollUtil.isNotEmpty(data) && CollUtil.isNotEmpty(dataPhase)) {
if (data.size() == dataPhase.size()) {
DevData.SqlDataDTO.ListDTO dto = data.get(0).getList();
DevData.SqlDataDTO.ListDTO phase = dataPhase.get(0).getList();
@@ -1309,11 +1469,11 @@ public class SocketDevResponseService {
str.append(")");
}
}
}else{
} else {
DevData.SqlDataDTO.ListDTO dto = data.get(0).getList();
str.append("装置(" + type + "a=" + String.format("%.4f", dto.getA()) +
type + "b=" + String.format("%.4f", dto.getB()) +
type + "c=" + String.format("%.4f", dto.getC()) );
type + "b=" + String.format("%.4f", dto.getB()) +
type + "c=" + String.format("%.4f", dto.getC()));
str.append(")");
}
return str.toString();
@@ -1389,11 +1549,11 @@ public class SocketDevResponseService {
Map<String, SourceIssue.ChannelListDTO> sourceMap = channelList.stream()
.collect(Collectors.toMap(x -> x.getChannelType(), Function.identity()));
Boolean a = getaBoolean(sourceMap.get(type + "a"), CollUtil.isNotEmpty(data) ? data.get(0).getList().getA() : null,
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getA(): null);
Boolean b = getaBoolean(sourceMap.get(type + "b"), CollUtil.isNotEmpty(data) ? data.get(0).getList().getB(): null,
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getB(): null);
Boolean c = getaBoolean(sourceMap.get(type + "c"), CollUtil.isNotEmpty(data) ? data.get(0).getList().getC(): null,
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getC(): null);
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getA() : null);
Boolean b = getaBoolean(sourceMap.get(type + "b"), CollUtil.isNotEmpty(data) ? data.get(0).getList().getB() : null,
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getB() : null);
Boolean c = getaBoolean(sourceMap.get(type + "c"), CollUtil.isNotEmpty(data) ? data.get(0).getList().getC() : null,
CollUtil.isNotEmpty(dataPhase) ? dataPhase.get(0).getList().getC() : null);
compareDev.setIsQualified(a && b && c);
compareDev.setDesc(name + (compareDev.getIsQualified() ? "合格->" : "不合格->") + stepTag + desc + stepTag + devMessage(type, data, dataPhase));
return compareDev;
@@ -1401,25 +1561,26 @@ public class SocketDevResponseService {
/**
* 相须校验-从幅值、相角两个维度判断是否合格
*
* @param channelListDTO
* @param devData
* @param devPhase
* @return
*/
private Boolean getaBoolean(SourceIssue.ChannelListDTO channelListDTO, Double devData, Double devPhase) {
private Boolean getaBoolean(SourceIssue.ChannelListDTO channelListDTO, Double devData, Double devPhase) {
Boolean isDev = false;
Boolean isPhase = false;
if(ObjectUtil.isNotNull(devData)){
isDev= NumberUtil.isIn(BigDecimal.valueOf(devData),
if (ObjectUtil.isNotNull(devData)) {
isDev = NumberUtil.isIn(BigDecimal.valueOf(devData),
BigDecimal.valueOf(channelListDTO.getFAmp() * 0.95),
BigDecimal.valueOf(channelListDTO.getFAmp() * 1.05));
}
if(isPhaseAngle){
if(ObjectUtil.isNotNull(devPhase)){
if (isPhaseAngle) {
if (ObjectUtil.isNotNull(devPhase)) {
isPhase = phaseBoolean(channelListDTO, devPhase);
}
}else{
isPhase=true;
} else {
isPhase = true;
}
return isDev && isPhase;
@@ -1433,7 +1594,7 @@ public class SocketDevResponseService {
* @param devPhase 装置返回角度
* @return
*/
private Boolean phaseBoolean(SourceIssue.ChannelListDTO channelListDTO, Double devPhase) {
private Boolean phaseBoolean(SourceIssue.ChannelListDTO channelListDTO, Double devPhase) {
Double phase = devPhase;
if (devPhase < -180) {
phase = devPhase + 360;
@@ -1497,11 +1658,13 @@ public class SocketDevResponseService {
//初始化有效数据数
//Map<String, SysRegResVO> sysRegResMap = iSysRegResService.listRegRes();
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
if (ObjectUtil.isNotNull(oneConfig)) {
dataRule = DictDataEnum.getDictDataEnumByCode(oneConfig.getDataRule());
//SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
AdPlan plan = adPlanService.getById(param.getPlanId());
DictData dictData = dictDataService.getDictDataById(plan.getDataRule());
if (ObjectUtil.isNotNull(dictData)) {
dataRule = DictDataEnum.getDictDataEnumByCode(dictData.getCode());
} else {
dataRule = DictDataEnum.AT_WILL_VALUE;
dataRule = DictDataEnum.SECTION_VALUE;
}
//字典树
SocketManager.valueTypeMap = iPqScriptCheckDataService.getValueTypeMap(param.getScriptId());
@@ -1509,6 +1672,9 @@ public class SocketDevResponseService {
if (param.getOperateType().equals(SourceOperateCodeEnum.COEFFICIENT_TEST.getValue())) {
initXiManager(param);
}
harmonicRelationMap.put(DetectionCodeEnum.V2_50.getCode(), DetectionCodeEnum.U1.getCode());
harmonicRelationMap.put(DetectionCodeEnum.I2_50.getCode(), DetectionCodeEnum.I1.getCode());
}
//初始化系数校验参数
@@ -1588,8 +1754,9 @@ public class SocketDevResponseService {
adNonHarmonicResult.setMonitorId(temId);
adNonHarmonicResult.setScriptId(param.getScriptId());
adNonHarmonicResult.setSort(sourceIssue.getIndex());
adNonHarmonicResult.setAdType(checkDataMap.get(sqlDataDTO.getDesc()));
adNonHarmonicResult.setDataType("avg");
adNonHarmonicResult.setDataType(sourceIssue.getDataType());
Double a = listDTO.getA();
Double b = listDTO.getB();
@@ -1610,7 +1777,10 @@ public class SocketDevResponseService {
adNonHarmonicResultList.add(adNonHarmonicResult);
}
} else {
for (DevData.SqlDataHarmDTO sqlDataDTO : data.getSqlDataHarm()) {
for (int j = 0; j < data.getSqlDataHarm().size(); j++) {
DevData.SqlDataHarmDTO sqlDataDTO = data.getSqlDataHarm().get(j);
String dui = harmonicRelationMap.get(sqlDataDTO.getDesc());
AdHarmonicResult adHarmonicResult = new AdHarmonicResult();
adHarmonicResult.setTimeId(localDateTime);
@@ -1618,11 +1788,11 @@ public class SocketDevResponseService {
adHarmonicResult.setScriptId(param.getScriptId());
adHarmonicResult.setSort(sourceIssue.getIndex());
adHarmonicResult.setAdType(checkDataMap.get(sqlDataDTO.getDesc()));
adHarmonicResult.setDataType("avg");
adHarmonicResult.setDataType(sourceIssue.getDataType());
if (!DicDataEnum.HSV.getCode().equals(sourceIssue.getType()) && !DicDataEnum.HSI.getCode().equals(sourceIssue.getType()) && !DicDataEnum.HP.getCode().equals(sourceIssue.getType())) {
if (CollUtil.isNotEmpty(data.getSqlData())) {
DevData.SqlDataDTO.ListDTO vvv = data.getSqlData().get(0).getList();
DevData.SqlDataDTO.ListDTO vvv = data.getSqlData().stream().filter(it -> it.getDesc().equals(dui)).collect(Collectors.toList()).get(0).getList();
Double aV = vvv.getA();
Double bV = vvv.getB();
Double cV = vvv.getC();
@@ -1682,10 +1852,7 @@ public class SocketDevResponseService {
}
adHarmonicResultList.add(adHarmonicResult);
}
}
}
}

View File

@@ -357,14 +357,10 @@ public class SocketSourceResponseService {
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + stepTag + sourceIssue.getType());
int ignoreCount;
int readData;
if (sourceIssue.getType().equals(DicDataEnum.F.getCode())) {
if (DicDataEnum.F.getCode().equals(sourceIssue.getType())) {
ignoreCount = 1;
readData = 2;
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_01.getValue());
} else if (sourceIssue.getType().equals(DicDataEnum.HP.getCode())) {
ignoreCount = 2;
readData = 5;
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_01.getValue());
} else if (DicDataEnum.VOLTAGE.getCode().equals(sourceIssue.getType())) {
ignoreCount = 5;
readData = 1;
@@ -372,9 +368,13 @@ public class SocketSourceResponseService {
} else {
ignoreCount = 5;
readData = 5;
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
//区分实时数据还是分钟数据
if ("real".equals(sourceIssue.getDataType())) {
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
} else {
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_01.getValue());
}
}
List<String> moniterIdList = devList.stream().flatMap(x -> x.getMonitorList().stream()).map(PreDetection.MonitorListDTO::getLineId).collect(Collectors.toList());
DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
phaseSequenceParam.setMoniterIdList(moniterIdList);

View File

@@ -0,0 +1,19 @@
package com.njcn.gather.detection.pojo.constant;
/**
* 通信相关的常量
*
* @author hongawen
* @version 1.0
* @data 2025/4/15 14:11
*/
public interface DetectionCommunicateConstant {
String SOURCE_CHANNEL_NAME = "AUTO_DETECTION_SOURCE";
String DEVICE_CHANNEL_NAME = "AUTO_DETECTION_DEV";
}

View File

@@ -38,6 +38,8 @@ public enum SourceOperateCodeEnum {
DATA_CHNFACTOR$01("DATA_CHNFACTOR$01","校验系数获取"),
DATA_CHNFACTOR$02("DATA_CHNFACTOR$02","校验系数下发"),
VERIFY_MAPPING$01("VERIFY_MAPPING$01","脚本与icd校验"),
/**
* 请求操作类型对应实体中 requestId
@@ -58,6 +60,7 @@ public enum SourceOperateCodeEnum {
SOCKET_TIMEOUT("socket_timeout","与源或者装置通讯等待超时"),
STOP_TIMEOUT("stop_timeout","暂停时间超过十分钟"),
SERVER_ERROR("server_error","服务端主动关闭连接,请稍后再试"),
DEVICE_ERROR("device_error","设备主动关闭连接,请稍后再试"),

View File

@@ -13,6 +13,7 @@ public enum SourceResponseCodeEnum {
SUCCESS(10200, "请求成功"),
UNPROCESSED_BUSINESS(10201, "立即响应,业务还未处理,类似肯定应答"),
NORMAL_RESPONSE(10202, "正常响应中间状态码"),
ICD_NOT_FOUND(10500, "未找到对应ICD"),
MESSAGE_PARSING_ERROR(10520, "报文解析有误"),
CONTROLLED_SOURCE_ERROR(10521, "程控源参数有误"),
TEST_ITEM_PARSING_ERROR(10522, "测试项解析有误"),

View File

@@ -65,4 +65,14 @@ public class PreDetectionParam {
private Boolean sendWebMsg;
private String userId;
/**
* 温度
*/
private Float temperature;
/**
* 相对湿度
*/
private Float humidity;
}

View File

@@ -0,0 +1,29 @@
package com.njcn.gather.detection.pojo.po;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author caozehui
* @data 2025-04-10
*/
@NoArgsConstructor
@Data
public class IcdCheckData {
private String icdType;
private List<ResultData> resultData;
@NoArgsConstructor
@Data
public static class ResultData {
private String type;
private String desc;
private DevData.SqlDataDTO.ListDTO phaseResult;
}
}

View File

@@ -20,7 +20,7 @@ public class DetectionData {
private Double num;
/**
* 是否是符合数据
* 1.合格 2.不合格 3.网络超时 4.无法处理 5.不参与误差比较
*/
private Integer isData;

View File

@@ -1,14 +0,0 @@
package com.njcn.gather.detection.service;
/**
* @Description: 守时检测流程
* @Author: wr
* @Date: 2024/12/10 14:23
*/
public interface PunctualityService {
/**
* 触发时间标识
*/
void triggerTimeMark();
}

View File

@@ -25,6 +25,7 @@ import com.njcn.gather.storage.pojo.po.AdNonHarmonicResult;
import com.njcn.gather.storage.service.DetectionDataDealService;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
@@ -32,11 +33,10 @@ import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.njcn.gather.detection.util.socket.UnitUtil.unit;
/**
* @author wr
@@ -115,45 +115,21 @@ public class DetectionServiceImpl {
case I_ABSOLUTELY:
return isQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, code);
/**
* 谐波电压
* 谐波
*/
case HV:
AdHarmonicResult harmV = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, 2);
if (ObjectUtil.isNotNull(harmV)) {
detectionDataDealService.acceptAdResult(Arrays.asList(harmV), code);
return harmV.getResultFlag();
}
return 4;
/**
* 谐波电流
*/
case HI:
AdHarmonicResult harmV = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, 2);
AdHarmonicResult harmI = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, 2);
if (ObjectUtil.isNotNull(harmI)) {
detectionDataDealService.acceptAdResult(Arrays.asList(harmI), code);
return harmI.getResultFlag();
}
return 4;
return resultFlag(harmV, harmI, code);
/**
* 间谐波电压
* 间谐波
*/
case HSV:
AdHarmonicResult harmInV = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, 1);
if (ObjectUtil.isNotNull(harmInV)) {
detectionDataDealService.acceptAdResult(Arrays.asList(harmInV), code);
return harmInV.getResultFlag();
}
return 4;
/**
* 间谐波电流
*/
case HSI:
AdHarmonicResult harmInV = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, 1);
AdHarmonicResult harmInI = isHarmQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, 1);
if (ObjectUtil.isNotNull(harmInI)) {
detectionDataDealService.acceptAdResult(Arrays.asList(harmInI), code);
return harmInI.getResultFlag();
}
return 4;
return resultFlag(harmInV, harmInI, code);
/**
* 三相电压不平衡度
*/
@@ -205,6 +181,21 @@ public class DetectionServiceImpl {
}
}
public Integer resultFlag(AdHarmonicResult v, AdHarmonicResult i, String code) {
List<AdHarmonicResult> info = new ArrayList<>();
if (ObjectUtil.isNotNull(v)) {
info.add(v);
}
if (ObjectUtil.isNotNull(i)) {
info.add(i);
}
if (CollUtil.isNotEmpty(info)) {
detectionDataDealService.acceptAdResult(info, code);
return getInteger(info.stream().map(x -> x.getResultFlag()).distinct().collect(Collectors.toList()));
}
return 4;
}
public Integer isUnknownQualified(List<DevData> dev,
Map<String, String> devIdMapComm,
List<ErrDtlsCheckDataVO> errDtlsCheckData,
@@ -229,17 +220,14 @@ public class DetectionServiceImpl {
result.setMonitorId(devID + "_" + split[1]);
result.setScriptId(sourceIssue.getScriptId());
result.setSort(sourceIssue.getIndex());
result.setDataType("avg");
result.setDataType(sourceIssue.getDataType());
Integer isQualified;
String valueTypeCode;
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();
valueTypeCode = dtlsCheckData.get(0).getValueTypeCode();
} else {
isQualified = 4;
valueTypeCode = "";
}
List<DetectionData> resultFlag = new ArrayList<>();
map.forEach((key, value) -> {
@@ -247,9 +235,9 @@ public class DetectionServiceImpl {
if (CollUtil.isNotEmpty(checkData)) {
DetectionData detectionData;
if (DUR.equals(devIndex)) {
detectionData = rangeDURComparisonList(value, isQualified, valueTypeCode, new ArrayList<>(), sourceIssue.getFFreq(), checkData.get(0).getValue(), dataRule);
detectionData = rangeDURComparisonList(value, isQualified, new ArrayList<>(), sourceIssue.getFFreq(), checkData.get(0).getValue(), dataRule);
} else {
detectionData = rangeComparisonList(value, isQualified, valueTypeCode, new ArrayList<>(), null, checkData.get(0).getValue(), dataRule);
detectionData = rangeComparisonList(value, isQualified, new ArrayList<>(), null, checkData.get(0).getValue(), dataRule);
}
if (key.equals(TYPE_T)) {
result.setTValue(JSON.toJSONString(detectionData));
@@ -290,7 +278,6 @@ public class DetectionServiceImpl {
}
if (devIndex.contains("I")) {
fundCode = DetectionCodeEnum.I1.getCode();
;
type = I;
fData = sourceIssue.getFIn();
if (devIndex.contains("50")) {
@@ -303,7 +290,7 @@ public class DetectionServiceImpl {
if (devIndex.contains("P")) {
type = P;
harmCode = DetectionCodeEnum.P2_50.getCode();
fData = sourceIssue.getFIn() * sourceIssue.getFUn() * 0.01;
fData = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
}
Map<String, Map<Double, List<Double>>> devHarmMap = devHarmListMap(dev, sourceIssue, dataRule, fundCode, harmCode, num);
if (CollUtil.isNotEmpty(devHarmMap)) {
@@ -319,16 +306,14 @@ public class DetectionServiceImpl {
if (CollUtil.isNotEmpty(dtlsCheckData)) {
harmonicResult.setAdType(dtlsCheckData.get(0).getValueType());
isQualified = dtlsCheckData.get(0).getIsQualified();
valueTypeCode = dtlsCheckData.get(0).getValueTypeCode();
} else {
isQualified = 4;
valueTypeCode = "";
}
//电压下百分比给百分比直接算 电流是是下百分比给的是幅值要转换算
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, valueTypeCode, new ArrayList<>(), type, TYPE_A, sourceIssue, dataRule, devHarmMap.get(TYPE_A), fData, num);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, valueTypeCode, new ArrayList<>(), type, TYPE_B, sourceIssue, dataRule, devHarmMap.get(TYPE_B), fData, num);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, valueTypeCode, new ArrayList<>(), type, TYPE_C, sourceIssue, dataRule, devHarmMap.get(TYPE_C), fData, num);
harmonicResult.setDataType("avg");
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, new ArrayList<>(), type, TYPE_A, sourceIssue, dataRule, devHarmMap.get(TYPE_A), fData, num);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, new ArrayList<>(), type, TYPE_B, sourceIssue, dataRule, devHarmMap.get(TYPE_B), fData, num);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, new ArrayList<>(), type, TYPE_C, sourceIssue, dataRule, devHarmMap.get(TYPE_C), fData, num);
harmonicResult.setDataType(sourceIssue.getDataType());
reflectHarmonic("a", integerBooleanA, harmonicResult, num);
reflectHarmonic("b", integerBooleanB, harmonicResult, num);
reflectHarmonic("c", integerBooleanC, harmonicResult, num);
@@ -391,16 +376,14 @@ public class DetectionServiceImpl {
result.setMonitorId(devID + "_" + split[1]);
result.setScriptId(sourceIssue.getScriptId());
result.setSort(sourceIssue.getIndex());
result.setDataType("avg");
result.setDataType(sourceIssue.getDataType());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
String valueTypeCode = "";
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();
valueTypeCode = dtlsCheckData.get(0).getValueTypeCode();
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
}
@@ -408,30 +391,35 @@ public class DetectionServiceImpl {
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, valueTypeCode, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule);
DetectionData t = rangeComparisonList(map.get(TYPE_T), isQualified, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(t.getIsData());
}
} else {
List<DetectionData> resultFlag = new ArrayList<>();
//取出源所对应的相别信息
List<ErrDtlsCheckDataVO> checkDataA = dtlsCheckData.stream().filter(x -> TYPE_A.equals(x.getPhase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkDataA)) {
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, valueTypeCode, pqErrSysDtls, fData, checkDataA.get(0).getValue(), dataRule);
resultFlag.add(a);
result.setAValue(JSON.toJSONString(a));
}
List<ErrDtlsCheckDataVO> checkDataB = dtlsCheckData.stream().filter(x -> TYPE_B.equals(x.getPhase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkDataB)) {
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, valueTypeCode, pqErrSysDtls, fData, checkDataB.get(0).getValue(), dataRule);
resultFlag.add(b);
result.setBValue(JSON.toJSONString(b));
}
List<ErrDtlsCheckDataVO> checkDataC = dtlsCheckData.stream().filter(x -> TYPE_C.equals(x.getPhase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(checkDataC)) {
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, valueTypeCode, pqErrSysDtls, fData, checkDataC.get(0).getValue(), dataRule);
resultFlag.add(c);
result.setCValue(JSON.toJSONString(c));
Map<String, BiConsumer<AdNonHarmonicResult, 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);
resultFlag.add(detectionData);
BiConsumer<AdNonHarmonicResult, 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));
}
@@ -479,7 +467,6 @@ public class DetectionServiceImpl {
if (I.equals(type)) {
fData = sourceIssue.getFIn();
fundCode = DetectionCodeEnum.I1.getCode();
;
if (num == 1) {
harmCode = DetectionCodeEnum.SI_1_49.getCode();
} else {
@@ -487,7 +474,7 @@ public class DetectionServiceImpl {
}
}
if (P.equals(type)) {
fData = sourceIssue.getFIn() * sourceIssue.getFUn() * 0.01;
fData = (sourceIssue.getFIn() * sourceIssue.getFUn()) * 0.01;
harmCode = DetectionCodeEnum.P2_50.getCode();
}
Map<String, Map<Double, List<Double>>> devMap = devHarmListMap(dev, sourceIssue, dataRule, fundCode, harmCode, num);
@@ -500,19 +487,19 @@ public class DetectionServiceImpl {
harmonicResult.setSort(sourceIssue.getIndex());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
String valueTypeCode = "";
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
harmonicResult.setAdType(errDtlsCheckData.get(0).getValueType());
isQualified = errDtlsCheckData.get(0).getIsQualified();
valueTypeCode = errDtlsCheckData.get(0).getValueTypeCode();
if (CollUtil.isNotEmpty(errDtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = errDtlsCheckData.get(0).getErrSysDtls();
String finalHarmCode = harmCode;
List<ErrDtlsCheckDataVO> adDtlsCheckData = errDtlsCheckData.stream().filter(x -> finalHarmCode.equals(x.getValueTypeCode())).collect(Collectors.toList());
harmonicResult.setAdType(adDtlsCheckData.get(0).getValueType());
isQualified = adDtlsCheckData.get(0).getIsQualified();
if (CollUtil.isNotEmpty(adDtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = adDtlsCheckData.get(0).getErrSysDtls();
}
}
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, valueTypeCode, pqErrSysDtls, type, TYPE_A, sourceIssue, dataRule, devMap.get(TYPE_A), fData, num);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, valueTypeCode, pqErrSysDtls, type, TYPE_B, sourceIssue, dataRule, devMap.get(TYPE_B), fData, num);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, valueTypeCode, pqErrSysDtls, type, TYPE_C, sourceIssue, dataRule, devMap.get(TYPE_C), fData, num);
harmonicResult.setDataType("avg");
List<DetectionData> integerBooleanA = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_A, sourceIssue, dataRule, devMap.get(TYPE_A), fData, num);
List<DetectionData> integerBooleanB = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_B, sourceIssue, dataRule, devMap.get(TYPE_B), fData, num);
List<DetectionData> integerBooleanC = harmRangeComparison(isQualified, pqErrSysDtls, type, TYPE_C, sourceIssue, dataRule, devMap.get(TYPE_C), fData, num);
harmonicResult.setDataType(sourceIssue.getDataType());
reflectHarmonic("a", integerBooleanA, harmonicResult, num);
reflectHarmonic("b", integerBooleanB, harmonicResult, num);
reflectHarmonic("c", integerBooleanC, harmonicResult, num);
@@ -565,34 +552,32 @@ public class DetectionServiceImpl {
result.setSort(sourceIssue.getIndex());
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
Integer isQualified = 4;
String valueTypeCode = "";
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
result.setAdType(errDtlsCheckData.get(0).getValueType());
isQualified = errDtlsCheckData.get(0).getIsQualified();
valueTypeCode = errDtlsCheckData.get(0).getValueTypeCode();
if (CollUtil.isNotEmpty(errDtlsCheckData.get(0).getErrSysDtls())) {
pqErrSysDtls = errDtlsCheckData.get(0).getErrSysDtls();
}
}
result.setDataType("avg");
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, valueTypeCode, pqErrSysDtls, fData, channelTypeAList.get(0).getValue(), dataRule);
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, pqErrSysDtls, fData, channelTypeAList.get(0).getValue(), dataRule);
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, valueTypeCode, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule);
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule);
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, valueTypeCode, pqErrSysDtls, fData, channelTypeCList.get(0).getValue(), dataRule);
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, pqErrSysDtls, fData, channelTypeCList.get(0).getValue(), dataRule);
result.setCValue(JSON.toJSONString(c));
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
@@ -600,7 +585,7 @@ public class DetectionServiceImpl {
List<PqScriptCheckData> channelTypeBList = checkData.stream()
.filter(x -> TYPE_T.equals(x.getPhase()))
.collect(Collectors.toList());
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, valueTypeCode, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule);
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule);
result.setTValue(JSON.toJSONString(t));
result.setResultFlag(setResultFlag(Arrays.asList(t)));
}
@@ -612,6 +597,14 @@ public class DetectionServiceImpl {
/**
* 判断值是否在误差范围内,有则进行判断否则则不进行计算(暂态)
* <p>
* (假如都符合,则选取最开始合格的,都不合格,取最开始不合格的)
* 方案一 分项问题
* 分别计算各个相别是否合格
* 不合格电压幅值的层级最高
* <p>
* 方案二 不分项问题
* 以电压幅值最低的作为比较相别
*
* @param dev 处理过后的数据
* @param errDtlsCheckData 误差体系
@@ -635,14 +628,80 @@ public class DetectionServiceImpl {
//暂态电压下多少就是多少
List<ErrDtlsCheckDataVO> magErrList = errDtlsCheckData.stream().filter(x -> MAG.equals(x.getValueTypeCode())).collect(Collectors.toList());
List<ErrDtlsCheckDataVO> durErrList = errDtlsCheckData.stream().filter(x -> DUR.equals(x.getValueTypeCode())).collect(Collectors.toList());
AdNonHarmonicResult magResult = voltageResult(dev.get(0).getId(), devIdMapComm, sourceIssue, dataRule, mag, magErrList, sourceIssue.getFUn(), MAG);
AdNonHarmonicResult durResult = voltageResult(dev.get(0).getId(), devIdMapComm, sourceIssue, dataRule, dur, durErrList, sourceIssue.getFFreq(), DUR);
if (CollUtil.isNotEmpty(mag.get(TYPE_B)) && CollUtil.isNotEmpty(mag.get(TYPE_C))) {
conclusion(magResult, durResult);
}
detectionDataDealService.acceptAdNonResult(Arrays.asList(magResult, durResult), code);
List<Integer> numbers = Arrays.asList(magResult.getResultFlag(), durResult.getResultFlag()).stream().distinct().collect(Collectors.toList());
return getInteger(numbers);
}
/**
* @param magResult 电压幅值结果
* @param durResult 持续时间结果
* @Description:
* @Author: wr
* @Date: 2025/4/9 18:54
*/
private void conclusion(AdNonHarmonicResult magResult, AdNonHarmonicResult durResult) {
if (magResult.getResultFlag() == 1) {
if (durResult.getResultFlag() != 2) {
setTValueBasedOnAValue(magResult, durResult);
} else {
setTValueBasedOnAValue(magResult, durResult, false);
}
} else if (magResult.getResultFlag() == 2) {
setTValueBasedOnAValue(magResult, durResult, true);
} else {
setTValueBasedOnAValue(magResult, durResult);
}
}
private void setTValueBasedOnAValue(AdNonHarmonicResult magResult, AdNonHarmonicResult durResult, Boolean isMag) {
DetectionData a;
DetectionData b;
DetectionData c;
if (isMag) {
a = JSON.parseObject(magResult.getAValue(), DetectionData.class);
b = JSON.parseObject(magResult.getBValue(), DetectionData.class);
c = JSON.parseObject(magResult.getCValue(), DetectionData.class);
} else {
a = JSON.parseObject(durResult.getAValue(), DetectionData.class);
b = JSON.parseObject(durResult.getBValue(), DetectionData.class);
c = JSON.parseObject(durResult.getCValue(), DetectionData.class);
}
if (a.getIsData() == 2) {
setTValueBasedOnAValue(magResult, durResult);
} else if (b.getIsData() == 2) {
setTValueBasedOnBValue(magResult, durResult);
} else if (c.getIsData() == 2) {
setTValueBasedOnCValue(magResult, durResult);
}
}
/**
* @param magResult 电压幅值结果
* @param durResult 持续时间结果
* @Description:
* @Author: wr
*/
private void setTValueBasedOnAValue(AdNonHarmonicResult magResult, AdNonHarmonicResult durResult) {
magResult.setTValue(magResult.getAValue());
durResult.setTValue(durResult.getAValue());
}
private void setTValueBasedOnBValue(AdNonHarmonicResult magResult, AdNonHarmonicResult durResult) {
magResult.setTValue(magResult.getBValue());
durResult.setTValue(durResult.getBValue());
}
private void setTValueBasedOnCValue(AdNonHarmonicResult magResult, AdNonHarmonicResult durResult) {
magResult.setTValue(magResult.getCValue());
durResult.setTValue(durResult.getCValue());
}
/**
* @param devId 装置监测点id(ip_通道)
* @param devIdMapComm ip_通道,装置名称
@@ -671,54 +730,69 @@ public class DetectionServiceImpl {
result.setMonitorId(devID + "_" + split[1]);
result.setScriptId(sourceIssue.getScriptId());
result.setSort(sourceIssue.getIndex());
result.setDataType("avg");
result.setDataType(sourceIssue.getDataType());
List<PqErrSysDtls> magErrList = new ArrayList<>();
Integer isQualified = 4;
String valueTypeCode = "";
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
result.setAdType(errDtlsCheckData.get(0).getValueType());
isQualified = errDtlsCheckData.get(0).getIsQualified();
valueTypeCode = errDtlsCheckData.get(0).getValueTypeCode();
if (CollUtil.isNotEmpty(errDtlsCheckData.get(0).getErrSysDtls())) {
magErrList = errDtlsCheckData.get(0).getErrSysDtls();
}
}
//取出源所对应的相别信息
List<SourceIssue.ChannelListDTO> channelTypeAList = sourceIssue.getChannelList().stream()
.filter(x -> ("Ua").equals(x.getChannelType()))
.collect(Collectors.toList());
DetectionData a = setDetectionData(isQualified, valueTypeCode, dataRule, mag, fData, dur, magErrList, channelTypeAList, TYPE_A);
result.setAValue(JSON.toJSONString(a));
List<SourceIssue.ChannelListDTO> channelTypeBList = sourceIssue.getChannelList().stream()
.filter(x -> ("Ub").equals(x.getChannelType()))
.collect(Collectors.toList());
DetectionData b = setDetectionData(isQualified, valueTypeCode, dataRule, mag, fData, dur, magErrList, channelTypeBList, TYPE_B);
DetectionData b = setDetectionData(isQualified, dataRule, mag, fData, dur, magErrList, channelTypeBList, TYPE_B);
result.setBValue(JSON.toJSONString(b));
List<SourceIssue.ChannelListDTO> channelTypeCList = sourceIssue.getChannelList().stream()
.filter(x -> ("Uc").equals(x.getChannelType()))
.collect(Collectors.toList());
DetectionData c = setDetectionData(isQualified, valueTypeCode, dataRule, mag, fData, dur, magErrList, channelTypeCList, TYPE_C);
DetectionData c = setDetectionData(isQualified, dataRule, mag, fData, dur, magErrList, channelTypeCList, TYPE_C);
result.setCValue(JSON.toJSONString(c));
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
if (CollUtil.isNotEmpty(mag.get(TYPE_B)) && CollUtil.isNotEmpty(mag.get(TYPE_C))) {
//取出源所对应的相别信息
List<SourceIssue.ChannelListDTO> channelTypeAList = sourceIssue.getChannelList().stream()
.filter(x -> ("Ua").equals(x.getChannelType()))
.collect(Collectors.toList());
DetectionData a = setDetectionData(isQualified, dataRule, mag, fData, dur, magErrList, channelTypeAList, TYPE_A);
result.setAValue(JSON.toJSONString(a));
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
} else {
List<SourceIssue.ChannelListDTO> channelTypeAList = sourceIssue.getChannelList().stream()
.filter(x -> x.getChannelType().contains("U"))
.sorted(Comparator.comparing(
x -> Optional.ofNullable(x.getDipData())
.map(SourceIssue.ChannelListDTO.DipDataDTO::getFTransValue)
.orElse(Double.NaN)
))
.collect(Collectors.toList());
DetectionData a = setDetectionData(isQualified, dataRule, mag, fData, dur, magErrList, channelTypeAList, TYPE_A);
result.setAValue(JSON.toJSONString(a));
result.setTValue(JSON.toJSONString(a));
result.setResultFlag(a.getIsData());
}
return result;
}
private DetectionData setDetectionData(Integer isQualified, String valueTypeCode, DictDataEnum dataRule, Map<String, List<Double>> mag, Double fData, String dur, List<PqErrSysDtls> magErrList, List<SourceIssue.ChannelListDTO> channelTypeCList, String typeC) {
DetectionData c;
private DetectionData setDetectionData(Integer isQualified,
DictDataEnum dataRule,
Map<String, List<Double>> mag,
Double fData,
String dur,
List<PqErrSysDtls> magErrList,
List<SourceIssue.ChannelListDTO> channelTypeCList,
String type) {
DetectionData data;
if (DUR.equals(dur)) {
c = rangeDURComparisonList(mag.get(typeC), isQualified, valueTypeCode, magErrList, fData, channelTypeCList.get(0).getDipData().getRetainTime(), dataRule);
data = rangeDURComparisonList(mag.get(type), isQualified, magErrList, fData, channelTypeCList.get(0).getDipData().getRetainTime(), dataRule);
} else {
List<Double> ampData = mag.get(typeC).stream()
.filter(x -> ObjectUtil.isNotNull(x))
.map(x -> x * channelTypeCList.get(0).getFAmp() * 0.01)
.collect(Collectors.toList());
c = rangeComparisonList(ampData, isQualified, valueTypeCode, magErrList, fData, channelTypeCList.get(0).getDipData().getFTransValue(), dataRule);
data = rangeComparisonList(mag.get(type), isQualified, magErrList, fData, channelTypeCList.get(0).getDipData().getFTransValue(), dataRule);
}
return c;
return data;
}
@@ -839,11 +913,10 @@ public class DetectionServiceImpl {
* @param sourceIssue 源下发的值(谐波)
* @param dataRule 数据处理原则
* @param devMap
* @param fData
* @param fData 额定值
* @return
*/
public List<DetectionData> harmRangeComparison(Integer isQualified,
String valueTypeCode,
List<PqErrSysDtls> pqErrSysDtls,
String type,
String phase,
@@ -874,12 +947,12 @@ public class DetectionServiceImpl {
issueHarmMap = sourceIssue.getChannelList().stream()
.filter(x -> (type + phase.toLowerCase()).equals(x.getChannelType()))
.flatMap(x -> x.getInharmList().stream())
.collect(Collectors.toMap(SourceIssue.ChannelListDTO.InharmModel::getInharm, x -> x.getFAmp() * percent));
.collect(Collectors.toMap(SourceIssue.ChannelListDTO.InharmModel::getInharm, x -> BigDecimal.valueOf(x.getFAmp()).multiply(BigDecimal.valueOf(percent)).doubleValue()));
} else {
issueHarmMap = sourceIssue.getChannelList().stream()
.filter(x -> (type + phase.toLowerCase()).equals(x.getChannelType()))
.flatMap(x -> x.getHarmList().stream())
.collect(Collectors.toMap(SourceIssue.ChannelListDTO.HarmModel::getHarm, x -> x.getFAmp() * percent));
.collect(Collectors.toMap(SourceIssue.ChannelListDTO.HarmModel::getHarm, x -> BigDecimal.valueOf(x.getFAmp()).multiply(BigDecimal.valueOf(percent)).doubleValue()));
}
}
Map<Double, PqErrSysDtls> errSysDtlMap = new LinkedHashMap<>();
@@ -905,17 +978,14 @@ public class DetectionServiceImpl {
if (CollUtil.isNotEmpty(harmDataList)) {
data.setData(harmDataList.get(0));
}
Double v = issueHarmMap.get(harm);
data.setResultData(v);
Double channelData = issueHarmMap.get(harm);
data.setResultData(channelData);
if (ObjectUtil.isNotNull(errSysDtl)) {
PqErrSysDtls errSys = BeanUtil.copyProperties(errSysDtl, PqErrSysDtls.class);
errSys.setMaxErrorValue(maxErrorMultiply(errSys.getMaxErrorValue(), fData, issueHarmMap.get(harm), errSys.getErrorValueType()));
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(6);
nf.setGroupingUsed(false);
data.setUnit(unit(valueTypeCode, errSysDtl.getErrorValueType()));
data.setRadius(nf.format(-errSys.getMaxErrorValue()) + "~" + nf.format(errSys.getMaxErrorValue()));
setDetection(dataRule, harmDataList, errSys, data, v);
errSys.setMaxErrorValue(maxErrorMultiply(errSys, fData, issueHarmMap.get(harm)));
data.setUnit(errSysDtl.getErrorUnit());
data.setRadius(-errSys.getMaxErrorValue() + "~" + errSys.getMaxErrorValue());
setDetection(dataRule, harmDataList, errSys, data, channelData, fData);
}
info.add(data);
});
@@ -928,26 +998,43 @@ public class DetectionServiceImpl {
* @param harmDataList 原始数据集合
* @param errSysDtl 误差体系
* @param data 初始化原始数据
* @param v 源下发的数据
* @param channelData 源下发的数据
* @param ratedValue 额定值
* @Description:
* @Author: wr
* @Date: 2024/12/29 18:10
*/
private void setDetection(DictDataEnum dataRule, List<Double> harmDataList, PqErrSysDtls errSysDtl, DetectionData data, Double v) {
private void setDetection(DictDataEnum dataRule, List<Double> harmDataList, PqErrSysDtls errSysDtl, DetectionData data, Double channelData, Double ratedValue) {
if (CollUtil.isNotEmpty(harmDataList)) {
// 存放合格的数据
List<Double> qualifiedList = harmDataList.stream()
.filter(x -> v == 0 ? NumberUtil.isIn(devSubtractChannelData(x, v, errSysDtl.getErrorValueType()),
.filter(x -> channelData == 0 ? NumberUtil.isIn(devSubtractChannelData(x, channelData, ratedValue, errSysDtl),
BigDecimal.valueOf(-errSysDtl.getMaxErrorValue()),
BigDecimal.valueOf(errSysDtl.getMaxErrorValue()))
:
x != 0 && NumberUtil.isIn(devSubtractChannelData(x, v, errSysDtl.getErrorValueType()),
x != 0 && NumberUtil.isIn(devSubtractChannelData(x, channelData, ratedValue, errSysDtl),
BigDecimal.valueOf(-errSysDtl.getMaxErrorValue()),
BigDecimal.valueOf(errSysDtl.getMaxErrorValue()))).collect(Collectors.toList());
if (CollUtil.isNotEmpty(qualifiedList)) {
data.setErrorData(devSubtractChannelData(qualifiedList.get(0), v, errSysDtl.getErrorValueType()));
switch (dataRule) {
case AT_WILL_VALUE:
case CP95_VALUE:
case AVG_VALUE:
data.setErrorData(devSubtractChannelData(qualifiedList.get(0), channelData, ratedValue, errSysDtl));
break;
case SECTION_VALUE:
case Own_value:
if (qualifiedList.size() == harmDataList.size()) {
data.setErrorData(devSubtractChannelData(qualifiedList.get(0), channelData, ratedValue, errSysDtl));
} else {
List<Double> subtract = CollectionUtils.subtract(harmDataList, qualifiedList).stream().collect(Collectors.toList());
data.setData(subtract.get(0));
data.setErrorData(devSubtractChannelData(subtract.get(0), channelData, ratedValue, errSysDtl));
}
break;
}
} else {
data.setErrorData(devSubtractChannelData(harmDataList.get(0), v, errSysDtl.getErrorValueType()));
data.setErrorData(devSubtractChannelData(harmDataList.get(0), channelData, ratedValue, errSysDtl));
}
isData(dataRule, harmDataList, data, qualifiedList);
}
@@ -971,6 +1058,8 @@ public class DetectionServiceImpl {
if (qualifiedList.size() == harmDataList.size()) {
data.setIsData(1);
} else {
List<Double> subtract = CollectionUtils.subtract(harmDataList, qualifiedList).stream().collect(Collectors.toList());
data.setData(subtract.get(0));
data.setIsData(2);
}
break;
@@ -1078,7 +1167,7 @@ public class DetectionServiceImpl {
* @param dataRule 数据处理原则
* @returnd
*/
public DetectionData rangeComparisonList(List<Double> list, Integer isQualified, String valueTypeCode, List<PqErrSysDtls> pqErrSysDtls, Double data, Double channelData, DictDataEnum dataRule) {
public DetectionData rangeComparisonList(List<Double> list, Integer isQualified, List<PqErrSysDtls> pqErrSysDtls, Double data, Double channelData, DictDataEnum dataRule) {
DetectionData detectionData = new DetectionData();
detectionData.setIsData(isQualified);
if (CollUtil.isNotEmpty(list)) {
@@ -1093,19 +1182,16 @@ public class DetectionServiceImpl {
channelData)).collect(Collectors.toList());
if (CollUtil.isNotEmpty(errSysDtls)) {
PqErrSysDtls errSysDtl = BeanUtil.copyProperties(errSysDtls.get(0), PqErrSysDtls.class);
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(6);
nf.setGroupingUsed(false);
detectionData.setUnit(unit(valueTypeCode, errSysDtl.getErrorValueType()));
errSysDtl.setMaxErrorValue(maxErrorMultiply(errSysDtl.getMaxErrorValue(), data, channelData, errSysDtl.getErrorValueType()));
detectionData.setRadius(nf.format(-errSysDtl.getMaxErrorValue()) + "~" + nf.format(errSysDtl.getMaxErrorValue()));
setDetection(dataRule, list, errSysDtl, detectionData, channelData);
detectionData.setUnit(errSysDtl.getErrorUnit());
errSysDtl.setMaxErrorValue(maxErrorMultiply(errSysDtl, data, channelData));
detectionData.setRadius(-errSysDtl.getMaxErrorValue() + "~" + errSysDtl.getMaxErrorValue());
setDetection(dataRule, list, errSysDtl, detectionData, channelData, data);
}
}
return detectionData;
}
public DetectionData rangeDURComparisonList(List<Double> list, Integer isQualified, String valueTypeCode, List<PqErrSysDtls> pqErrSysDtls, Double data, Double channelData, DictDataEnum dataRule) {
public DetectionData rangeDURComparisonList(List<Double> list, Integer isQualified, List<PqErrSysDtls> pqErrSysDtls, Double data, Double channelData, DictDataEnum dataRule) {
DetectionData detectionData = new DetectionData();
detectionData.setIsData(isQualified);
if (CollUtil.isNotEmpty(list)) {
@@ -1124,9 +1210,9 @@ public class DetectionServiceImpl {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(6);
nf.setGroupingUsed(false);
detectionData.setUnit(unit(valueTypeCode, errSysDtl.getErrorValueType()));
detectionData.setRadius(nf.format(BigDecimal.valueOf(1.0 / data * (channelData - errSysDtl.getMaxErrorValue())))
+ "~" + nf.format(BigDecimal.valueOf(1.0 / data * (channelData + errSysDtl.getMaxErrorValue()))));
detectionData.setUnit(errSysDtl.getErrorUnit());
detectionData.setRadius(nf.format(BigDecimal.valueOf(-1.0 / data))
+ "~" + nf.format(BigDecimal.valueOf(1.0 / data)));
List<Double> qualifiedList = list.stream()
.filter(x -> NumberUtil.isIn(BigDecimal.valueOf(x.doubleValue()),
BigDecimal.valueOf(1.0 / data * (channelData - errSysDtl.getMaxErrorValue())),
@@ -1134,14 +1220,14 @@ public class DetectionServiceImpl {
).collect(Collectors.toList());
if (CollUtil.isNotEmpty(qualifiedList)) {
BigDecimal subtract = BigDecimal.valueOf(qualifiedList.get(0))
.subtract(BigDecimal.valueOf(1.0 / data * (channelData - errSysDtl.getMaxErrorValue())));
.subtract(BigDecimal.valueOf(1.0 / data * (channelData)));
detectionData.setErrorData(subtract);
} else {
BigDecimal subtract = BigDecimal.valueOf(list.get(0))
.subtract(BigDecimal.valueOf(1.0 / data * (channelData - errSysDtl.getMaxErrorValue())));
.subtract(BigDecimal.valueOf(1.0 / data * (channelData)));
detectionData.setErrorData(subtract);
}
isData(dataRule, qualifiedList, detectionData, qualifiedList);
isData(dataRule, list, detectionData, qualifiedList);
}
}
return detectionData;
@@ -1157,7 +1243,8 @@ public class DetectionServiceImpl {
* @param devData 装置上送值
* @return
*/
public Boolean rangeComparison(Double startValue, Integer startFlag, Double endValue, Integer endFlag, Double devData) {
public Boolean rangeComparison(Double startValue, Integer startFlag, Double endValue, Integer endFlag, Double
devData) {
Boolean minBool = null;
Boolean maxBool = null;
if (ObjectUtil.isNotNull(startValue)) {
@@ -1189,39 +1276,36 @@ public class DetectionServiceImpl {
}
/**
* 技术数据误差值(装置返回的值 - 源通道下发的值)
* 计算数据误差值(装置返回的值 - 源通道下发的值)
*
* @param devData
* @param channelData
* @param errorValueType
* @param devData 装置返回值
* @param channelData 通道值
* @param ratedValue 额定值
* @param error
* @return
*/
public BigDecimal devSubtractChannelData(Double devData, Double channelData, Integer errorValueType) {
public BigDecimal devSubtractChannelData(Double devData, Double channelData, Double ratedValue, PqErrSysDtls error) {
//计算装置值返回值 - 源下发值的数据 = 差值
BigDecimal subtract = BigDecimal.valueOf(devData).subtract(BigDecimal.valueOf(channelData));
if (subtract.doubleValue() != 0) {
switch (errorValueType) {
case 2:
//下发的谐波电压幅值,返回的是谐波电压含有率,拿(含有率值*基波 - 源下发对应谐波值幅值)/下发的幅值
//只有相对值需要%比较,绝对值直接相减就行
if (2 == error.getValueType()) {
switch (error.getErrorValueType()) {
case 0:
//下发的谐波电压幅值,返回的是谐波电压含有率,拿(含有率值*基波 - 源下发对应谐波值幅值)/ 额定值
return subtract.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(ratedValue), 4, RoundingMode.HALF_UP);
case 1:
//todo 当谐波电压和间谐波电压默认都是按照相对值误差进行计算(用户关心的是含有率)
//下发的谐波电压幅值,返回的是谐波电压含有率,拿(含有率值*基波 - 源下发对应谐波值幅值)/ 下发的幅值
return subtract.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(channelData), 4, RoundingMode.HALF_UP);
case 3:
//下发的谐波电压幅值,返回的是谐波电压含有率,拿(含有率值*基波 - 源下发对应谐波值幅值)/装置返回值
return subtract.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(devData), 4, RoundingMode.HALF_UP);
}
return subtract;
}
return BigDecimal.valueOf(0);
}
public BigDecimal divide(Double devData, Double channelData) {
return BigDecimal.valueOf(devData)
.divide(BigDecimal.valueOf(channelData), 4, RoundingMode.HALF_UP);
return subtract;
}
/**
* 用于计算误差体系的范围的
* 用于计算误差体系的范围的0标称值 1谐波值 2值类型
*
* @param value 误差值
* @param ratedData 额定值
@@ -1248,27 +1332,37 @@ public class DetectionServiceImpl {
/**
* 用于计算最大误差值的范围的
* 2绝对值-值比较(默认) 0绝对值-标称值(额定电压) 1绝对值-标准值(源下发直谐波如:H2 0相对值-标称值 1相对值-标准值)
*
* @param errorValue 误差值
* @param ratedData 额定值
* @param harmData 谐波下发值(百分数->含油率)
* @param type 误差值类型
* @param error 最大误差值对象
* @param ratedData 额定值
* @param harmData 谐波下发值(百分数->含油率)
* @return
*/
public Double maxErrorMultiply(Double errorValue, Double ratedData, Double harmData, Integer type) {
if (ObjectUtil.isNotNull(errorValue)) {
switch (type) {
public Double maxErrorMultiply(PqErrSysDtls error, Double ratedData, Double harmData) {
Double errorValue = error.getMaxErrorValue();
//1绝对值
if (1 == error.getValueType()) {
switch (error.getErrorValueType()) {
//绝对值-标称值= 最大误差值 * 额定电压
case 0:
return BigDecimal.valueOf(errorValue).multiply(BigDecimal.valueOf(ratedData))
.setScale(4, RoundingMode.HALF_UP).doubleValue();
case 2:
case 3:
//绝对值-标准值 = 最大误差值 * 谐波下发值
case 1:
return BigDecimal.valueOf(errorValue).multiply(BigDecimal.valueOf(harmData))
.setScale(4, RoundingMode.HALF_UP).doubleValue();
}
}
//2相对值
if (2 == error.getValueType()) {
switch (error.getErrorValueType()) {
//相对值-标称值 | 相对值-标准值 = 最大误差值 * 100
case 0:
case 1:
return BigDecimal.valueOf(errorValue).multiply(BigDecimal.valueOf(100))
.setScale(4, RoundingMode.HALF_UP).doubleValue();
default:
return errorValue;
}
}
return errorValue;
}
@@ -1288,7 +1382,9 @@ public class DetectionServiceImpl {
* @param harm 基波信息
* @param fund 2-50次谐波信息
*/
public void harmPut(String type, Map<String, Map<Double, List<Double>>> map, List<Double> harmNum, DevData.SqlDataHarmDTO harm, String fund, Integer num) {
public void harmPut(String
type, Map<String, Map<Double, List<Double>>> map, List<Double> harmNum, DevData.SqlDataHarmDTO
harm, String fund, Integer num) {
if (map.containsKey(type)) {
Map<Double, List<Double>> integerListMap = map.get(type);
for (Double i : harmNum) {

View File

@@ -8,12 +8,14 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.handler.SocketDevResponseService;
import com.njcn.gather.detection.handler.SocketSourceResponseService;
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.PreDetectionParam;
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
import com.njcn.gather.detection.pojo.vo.SocketMsg;
import com.njcn.gather.detection.service.PreDetectionService;
import com.njcn.gather.detection.util.business.DetectionCommunicateUtil;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.detection.util.socket.SocketManager;
@@ -41,7 +43,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -52,8 +53,6 @@ import java.util.stream.Collectors;
@Slf4j
public class PreDetectionServiceImpl implements PreDetectionService {
private final String source = "_Source";
private final String dev = "_Dev";
private final String stepTag = "&&";
private final String handlerSourceStr = "_Source";
@@ -79,8 +78,9 @@ public class PreDetectionServiceImpl implements PreDetectionService {
@Override
public void sourceCommunicationCheck(PreDetectionParam param) {
commCheck(param);
specialDeal(param);
// 参数校验目前仅检查IP是否重复
checkDevIp(param);
DetectionCommunicateUtil.checkCommunicateChannel(param);
/*
先组装源通讯协议
查询计划什么模式的(除了对比式,其他都是一个计划对应一个源)
@@ -106,7 +106,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
@Override
public void coefficientCheck(PreDetectionParam param) {
specialDeal(param);
// 检测是否存在连接的通道,后期需要做成动态,如果组合中不是第一位,则不需要关闭,也不用初始化 todo....
DetectionCommunicateUtil.checkCommunicateChannel(param);
AdPlanSource planSource = adPlanSourceService.getOne(new LambdaQueryWrapper<AdPlanSource>()
.eq(AdPlanSource::getPlanId, param.getPlanId())
);
@@ -132,6 +133,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
private void sendYtxSocket(PreDetectionParam param) {
WebServiceManager.addPreDetectionParam(param);
AdPlan plan = iAdPlanService.getById(param.getPlanId());
AdPlanSource planSource = adPlanSourceService.getOne(new LambdaQueryWrapper<AdPlanSource>().eq(AdPlanSource::getPlanId, param.getPlanId()));
param.setSourceId(planSource.getSourceId());
@@ -189,7 +191,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
xuMsg.setData(JSON.toJSONString(sourceIssues));
xuMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + "&&" + sourceIssues.getType());
SocketManager.sendMsg(param.getUserPageId() + source, JSON.toJSONString(xuMsg));
SocketManager.sendMsg(DetectionCommunicateConstant.SOURCE_CHANNEL_NAME, JSON.toJSONString(xuMsg));
} else {
//TODO 是否最终检测完成需要推送给用户
PqScriptCheckDataParam checkDataParam = new PqScriptCheckDataParam();
@@ -197,7 +199,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(),param.getUserId());
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
CnSocketUtil.quitSend(param);
}
@@ -211,13 +213,13 @@ public class PreDetectionServiceImpl implements PreDetectionService {
preDetectionParam.setUserPageId(param.getUserPageId());
preDetectionParam.setSendWebMsg(true);
specialDealSimulate(preDetectionParam);
DetectionCommunicateUtil.checkCommunicateChannel(preDetectionParam);
sendYtxSocketSimulate(preDetectionParam);
}
@Override
public void sendScript(SimulateDetectionParam param) {
Channel channel = SocketManager.getChannelByUserId(param.getUserPageId() + source);
Channel channel = SocketManager.getChannelByUserId(DetectionCommunicateConstant.SOURCE_CHANNEL_NAME);
if (Objects.isNull(channel) || !channel.isActive()) {
// 进行源通信连接
PreDetectionParam preDetectionParam = new PreDetectionParam();
@@ -251,7 +253,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
@Override
public void closeTestSimulate(SimulateDetectionParam param) {
Channel channel = SocketManager.getChannelByUserId(param.getUserPageId() + source);
Channel channel = SocketManager.getChannelByUserId(DetectionCommunicateConstant.SOURCE_CHANNEL_NAME);
if (Objects.isNull(channel) || !channel.isActive()) {
throw new BusinessException(DetectionResponseEnum.SOURCE_NOT_CONNECT);
}
@@ -260,72 +262,14 @@ public class PreDetectionServiceImpl implements PreDetectionService {
preDetectionParam.setSourceId(sourceParam.getSourceId());
preDetectionParam.setUserPageId(param.getUserPageId());
CnSocketUtil.quitSendSource(preDetectionParam);
WebServiceManager.removePreDetectionParam();
}
/**
* 对重复发起或者异常发起的检测进行关闭源操作
*
* @param param
*/
private void specialDeal(PreDetectionParam param) {
Channel channel = SocketManager.getChannelByUserId(param.getUserPageId() + source);
Channel channelDev = SocketManager.getChannelByUserId(param.getUserPageId() + dev);
if (Objects.nonNull(channel) && channel.isActive()) {
System.out.println("发送关闭源指令。。。。。。。。");
CnSocketUtil.quitSendSource(param);
}
if (Objects.nonNull(channelDev) && channelDev.isActive()) {
System.out.println("发送关闭设备通讯指令。。。。。。。。");
CnSocketUtil.quitSend(param);
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
SocketManager.removeUser(param.getUserPageId() + source);
SocketManager.removeUser(param.getUserPageId() + dev);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
}
/**
* 对重复发起或者异常发起的检测进行关闭源操作-模拟检测
*
* @param param
* 校验被检设备中是否存在IP重复的
*/
private void specialDealSimulate(PreDetectionParam param) {
Channel channel = SocketManager.getChannelByUserId(param.getUserPageId() + source);
if (Objects.nonNull(channel) && channel.isActive()) {
System.out.println("发送关闭源指令。。。。。。。。");
CnSocketUtil.quitSendSource(param);
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
SocketManager.removeUser(param.getUserPageId() + source);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
}
/**
* 校验
*/
private void commCheck(PreDetectionParam param) {
private void checkDevIp(PreDetectionParam param) {
List<PqDev> pqDevList = iPqDevService.listByIds(param.getDevIds());
List<String> ipList = pqDevList.stream().map(PqDev::getIp).distinct().collect(Collectors.toList());
if (ipList.size() != param.getDevIds().size()) {

View File

@@ -0,0 +1,58 @@
package com.njcn.gather.detection.util.business;
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.SocketManager;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
/**
*
* 检测通讯工具类
*
* @author hongawen
* @version 1.0
* @data 2025/4/15 15:24
*/
@Slf4j
public class DetectionCommunicateUtil {
/**
* 检测是否存在连接的源、设备通讯的模块通道
* 有则强行关闭
*/
public static void checkCommunicateChannel(PreDetectionParam param) {
Channel channelSource = SocketManager.getChannelByUserId(DetectionCommunicateConstant.SOURCE_CHANNEL_NAME);
Channel channelDev = SocketManager.getChannelByUserId(DetectionCommunicateConstant.DEVICE_CHANNEL_NAME);
if (Objects.nonNull(channelSource) && channelSource.isActive()) {
System.out.println("发送关闭源指令。。。。。。。。");
CnSocketUtil.quitSendSource(param);
}
if (Objects.nonNull(channelDev) && channelDev.isActive()) {
System.out.println("发送关闭设备通讯指令。。。。。。。。");
CnSocketUtil.quitSend(param);
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
SocketManager.removeUser(DetectionCommunicateConstant.SOURCE_CHANNEL_NAME);
SocketManager.removeUser(DetectionCommunicateConstant.DEVICE_CHANNEL_NAME);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
}
}

View File

@@ -25,6 +25,7 @@ public class CnSocketUtil {
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.QUIT_INIT_03.getValue());
SocketManager.sendMsg(param.getUserPageId() + devTag, JSON.toJSONString(socketMsg));
WebServiceManager.removePreDetectionParam();
}
/**
@@ -38,6 +39,7 @@ public class CnSocketUtil {
jsonObject.put("sourceId", param.getSourceId());
socketMsg.setData(jsonObject.toJSONString());
SocketManager.sendMsg(param.getUserPageId() + sourceTag, JSON.toJSONString(socketMsg));
WebServiceManager.removePreDetectionParam();
}
/**

View File

@@ -66,4 +66,10 @@ public class FormalTestManager {
public static Integer stopTime = 0;
/**
* 强行赋值关系
*/
public static Map<String,String> harmonicRelationMap = new HashMap<>();
}

View File

@@ -1,7 +1,6 @@
package com.njcn.gather.detection.util.socket;
import cn.hutool.core.util.ObjectUtil;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.script.pojo.po.SourceIssue;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
@@ -19,10 +18,14 @@ import java.util.concurrent.CopyOnWriteArrayList;
*/
public class SocketManager {
// key为userIdxxx_Source、xxx_Devvalue为channel
/**
* key为userIdxxx_Source、xxx_Devvalue为channel
*/
private static final Map<String, Channel> socketSessions = new ConcurrentHashMap<>();
// key为userIdxxx_Source、xxx_Devvalue为group
/**
* key为userIdxxx_Source、xxx_Devvalue为group
*/
private static final Map<String, NioEventLoopGroup> socketGroup = new ConcurrentHashMap<>();
public static void addUser(String userId, Channel channel) {

View File

@@ -41,7 +41,7 @@ public class UnitUtil {
unit = "P";
}
if (DetectionCodeEnum.MAG.getCode().equals(code)) {
unit = "%";
unit = "V";
}
if (DetectionCodeEnum.DUR.getCode().equals(code)) {
unit = "s";

View File

@@ -55,6 +55,9 @@ public class WebServiceManager {
channel.writeAndFlush(wd);
}else {
log.error("{}-websocket推送消息失败;当前用户-{}-客户端已经断开连接", LocalDateTime.now(),userId);
// PreDetectionParam param = preDetectionParamMap.get("preDetectionParam");
// CnSocketUtil.quitSend(param);
// CnSocketUtil.quitSendSource(param);
}
}

View File

@@ -8,14 +8,11 @@ import com.njcn.gather.detection.pojo.vo.SocketMsg;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.MsgUtil;
import com.njcn.gather.detection.util.socket.SocketManager;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.RequiredArgsConstructor;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -42,7 +39,7 @@ public class HeartbeatHandler extends SimpleChannelInboundHandler<String> {
private int consecutiveHeartbeatMisses = 0;
public HeartbeatHandler(PreDetectionParam param,String type){
public HeartbeatHandler(PreDetectionParam param, String type) {
this.param = param;
this.handlerType = type;
}
@@ -70,13 +67,13 @@ public class HeartbeatHandler extends SimpleChannelInboundHandler<String> {
msg.setRequestId("yxt");
msg.setOperateCode(SourceOperateCodeEnum.HEARTBEAT.getValue());
msg.setData("");
ctx.channel().writeAndFlush(JSON.toJSONString(msg)+"\n");
ctx.channel().writeAndFlush(JSON.toJSONString(msg) + "\n");
System.out.println(handlerType+"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥send"+LocalDateTime.now());
System.out.println(handlerType + "♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥send" + LocalDateTime.now());
consecutiveHeartbeatMisses++;
if (consecutiveHeartbeatMisses >= MAX_HEARTBEAT_MISSES) {
// 连续三次未收到心跳响应,断开连接
System.out.println(handlerType+"连续三次未收到心跳响应,断开连接");
System.out.println(handlerType + "连续三次未收到心跳响应,断开连接");
if (dev.equals(handlerType)) {
//CnSocketUtil.sendToWebSocket(param.getUserPageId(),);
CnSocketUtil.quitSend(param);
@@ -98,12 +95,11 @@ public class HeartbeatHandler extends SimpleChannelInboundHandler<String> {
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 过滤心跳包,避免进入业务逻辑
if (isHeartbeatPacket(msg)) {
System.out.println(handlerType+"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥response"+LocalDateTime.now());
System.out.println(handlerType + "♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥response" + LocalDateTime.now());
consecutiveHeartbeatMisses = 0;
return;
}
@@ -115,6 +111,6 @@ public class HeartbeatHandler extends SimpleChannelInboundHandler<String> {
private boolean isHeartbeatPacket(String msg) {
// 判断是否为心跳包
SocketDataMsg socketDataMsg = MsgUtil.socketDataMsg(msg);
return socketDataMsg.getOperateCode().equals(SourceOperateCodeEnum.HEARTBEAT.getValue());
return !Objects.isNull(socketDataMsg.getOperateCode()) && socketDataMsg.getOperateCode().equals(SourceOperateCodeEnum.HEARTBEAT.getValue());
}
}

View File

@@ -146,6 +146,7 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
fly = true;
//为空则认为是常规步骤,设定一分钟超时
CnSocketUtil.quitSend(param);
CnSocketUtil.sendToWebSocket(param.getUserPageId(), SourceOperateCodeEnum.SOCKET_TIMEOUT.getValue(), SourceOperateCodeEnum.SOCKET_TIMEOUT.getValue(), SourceOperateCodeEnum.SOCKET_TIMEOUT.getMsg(), null);
}
if (fly) {
socketResponseService.backCheckState(param);
@@ -185,7 +186,7 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
} else if (cause instanceof IOException) {
// 处理I/O异常例如读写错误
System.out.println("IOException caught: There was an I/O error.");
CnSocketUtil.sendToWebSocket(param.getUserPageId(), SourceOperateCodeEnum.SERVER_ERROR.getValue(), SourceOperateCodeEnum.SERVER_ERROR.getValue(), SourceOperateCodeEnum.SERVER_ERROR.getMsg(), null);
CnSocketUtil.sendToWebSocket(param.getUserPageId(), SourceOperateCodeEnum.DEVICE_ERROR.getValue(), SourceOperateCodeEnum.DEVICE_ERROR.getValue(), SourceOperateCodeEnum.DEVICE_ERROR.getMsg(), null);
// 例如可以记录更详细的I/O错误信息
} else if (cause instanceof TimeoutException) {
@@ -199,9 +200,11 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
} else {
// 处理其他类型的异常
System.out.println("Unknown exception caught: " + cause.getMessage());
CnSocketUtil.sendToWebSocket(param.getUserPageId(), SourceOperateCodeEnum.DEVICE_ERROR.getValue(), SourceOperateCodeEnum.DEVICE_ERROR.getValue(), SourceOperateCodeEnum.DEVICE_ERROR.getMsg(), null);
// 可以记录未知异常信息
}
CnSocketUtil.quitSend(param);
CnSocketUtil.quitSendSource(param);
socketResponseService.backCheckState(param);
ctx.close();
}

View File

@@ -122,6 +122,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
PreDetectionParam preDetectionParam = WebServiceManager.getPreDetectionParam();
if (ObjectUtil.isNotNull(preDetectionParam)) {
CnSocketUtil.quitSendSource(preDetectionParam); // 能否在这里关闭源socket连接
CnSocketUtil.quitSend(preDetectionParam);
} else {
preDetectionParam = new PreDetectionParam();
preDetectionParam.setUserPageId("cdf");

View File

@@ -182,19 +182,4 @@ public class PqDevController extends BaseController {
});
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
@PostMapping("/documented")
@ApiOperation("设备归档")
@ApiImplicitParam(name = "id", value = "设备id", required = true)
public HttpResult<Boolean> documented(@RequestBody List<String> ids) {
String methodDescribe = getMethodDescribe("documented");
LogUtil.njcnDebug(log, "{}设备id为{}", methodDescribe, ids);
boolean result = pqDevService.documented(ids);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
}
}

View File

@@ -22,6 +22,7 @@ import java.util.List;
public class PqDevParam {
@ApiModelProperty(value = "名称", required = true)
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
private String name;
@ApiModelProperty(value = "设备模式,字典表(数字、模拟、比对)", required = true)
@@ -40,8 +41,9 @@ public class PqDevParam {
@ApiModelProperty(value = "出厂日期", required = true)
private String createDate;
@ApiModelProperty(value = "设备序列", required = true)
@ApiModelProperty(value = "装置编", required = true)
@NotBlank(message = DetectionValidMessage.FACTORYNO_NOT_BLANK)
@Pattern(regexp = PatternRegex.DEV_CREATE_ID_REGEX, message = DetectionValidMessage.DEV_CREATE_ID_FORMAT_ERROR)
private String createId;
@ApiModelProperty(value = "固件版本", required = true)
@@ -105,9 +107,7 @@ public class PqDevParam {
private Integer reCheckNum;
@ApiModelProperty("是否支持系数校准")
@Min(value = 0, message = DetectionValidMessage.FACTOR_FLAG_FORMAT_ERROR)
@Max(value = 1, message = DetectionValidMessage.FACTOR_FLAG_FORMAT_ERROR)
private String factorFlag;
private Integer factorFlag;
@ApiModelProperty("监测点台账列表")
@Valid
@@ -119,6 +119,9 @@ public class PqDevParam {
@ApiModelProperty("预投计划")
private String preinvestmentPlan;
@ApiModelProperty("委托方")
private String delegate;
/**
* 更新操作实体
*/

View File

@@ -201,5 +201,19 @@ public class PqDev extends BaseEntity implements Serializable {
@TableField("Preinvestment_Plan")
private String preinvestmentPlan;
/**
* 温度
*/
private Float temperature;
/**
* 相对湿度
*/
private Float humidity;
/**
* 委托方
*/
private String delegate;
}

View File

@@ -21,9 +21,9 @@ public class CNDevExcel {
@NotBlank(message = DetectionValidMessage.PREINVESTMENT_PLAN_NOT_BLANK)
private String preinvestmentPlan;
@Excel(name = "设备编号(开始编号-结束编号,编号为数字)*", width = 50, orderNum = "2")
@Excel(name = "装置编号(开始编号-结束编号,编号为数字)*", width = 50, orderNum = "2")
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
@Pattern(regexp = PatternRegex.CN_DEV_NAME_REGEX, message = DetectionValidMessage.NAME_FORMAT_ERROR)
@Pattern(regexp = PatternRegex.CN_DEV_NAME_REGEX_IMPORT, message = DetectionValidMessage.CN_DEV_NAME_FORMAT_ERROR)
private String name;
@Excel(name = "设备类型*", width = 20, orderNum = "3")

View File

@@ -39,7 +39,7 @@ public class ProvinceDevExcel implements Serializable {
@NotBlank(message = DetectionValidMessage.MANUFACTURER_NOT_BLANK)
private String manufacturer;
@Excel(name = "出厂日期*", width = 25, format = "yyyy-MM-dd", orderNum = "8")
@Excel(name = "出厂日期yyyy-MM-dd*", width = 25, format = "yyyy-MM-dd", orderNum = "8")
@NotNull(message = DetectionValidMessage.CREATEDATETIME_NOT_NULL)
private LocalDate createDate;
@@ -63,16 +63,25 @@ public class ProvinceDevExcel implements Serializable {
@Excel(name = "秘钥(当加密时必填)", width = 30, orderNum = "14")
private String devKey;
@Excel(name = "是否支持系数校准*", width = 25, replace = {"否_0", "是_1"}, orderNum = "15")
private Integer factorFlag;
// @Excel(name = "是否支持系数校准*", width = 25, replace = {"否_0", "是_1"}, orderNum = "15")
// private Integer factorFlag;
@Excel(name = "IP地址*", width = 20, orderNum = "16")
@Excel(name = "IP地址*", width = 20, orderNum = "15")
@NotBlank(message = DetectionValidMessage.IP_NOT_BLANK)
@Pattern(regexp = PatternRegex.IP_REGEX, message = DetectionValidMessage.IP_FORMAT_ERROR)
private String ip;
@Excel(name = "端口号*", width = 15, orderNum = "17")
@Excel(name = "端口号*", width = 15, orderNum = "16")
@NotNull(message = DetectionValidMessage.PORT_NOT_NULL)
@Range(min = 1, max = 65535, message = DetectionValidMessage.PORT_RANGE_ERROR)
private Integer port;
@Excel(name = "样品编号", width = 20, orderNum = "17")
private String sampleId;
@Excel(name = "送样日期yyyy-MM-dd", width = 25, format = "yyyy-MM-dd", orderNum = "18")
private String arrivedDate;
@Excel(name="委托方", width = 40, orderNum = "19")
private String delegate;
}

View File

@@ -137,13 +137,6 @@ public interface IPqDevService extends IService<PqDev> {
*/
List<PreDetection> getDevInfo(@Param("devIds") List<String> devIds);
/**
* 设备归档操作
*
* @param id 设备id
* @return 归档成功返回true否则返回false
*/
boolean documented(List<String> id);
/**
* 正式监测完成,修改中断状态
@@ -152,9 +145,11 @@ public interface IPqDevService extends IService<PqDev> {
* @param valueType
* @param code
* @param userId
* @param temperature
* @param humidity
* @return
*/
boolean updateResult(List<String> ids, List<String> valueType, String code,String userId);
boolean updateResult(List<String> ids, List<String> valueType, String code, String userId, Float temperature, Float humidity);
void updatePqDevReportState(String devId, int i);

View File

@@ -15,6 +15,7 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
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.common.pojo.poi.PullDown;
@@ -31,11 +32,7 @@ import com.njcn.gather.device.pojo.vo.ProvinceDevExcel;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.monitor.pojo.po.PqMonitor;
import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.pojo.DevReportParam;
import com.njcn.gather.report.service.IPqReportService;
import com.njcn.gather.storage.service.DetectionDataDealService;
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
@@ -46,10 +43,10 @@ import com.njcn.gather.system.dictionary.service.IDictDataService;
import com.njcn.gather.system.dictionary.service.IDictTypeService;
import com.njcn.gather.type.pojo.po.DevType;
import com.njcn.gather.type.service.IDevTypeService;
import com.njcn.gather.user.user.service.ISysUserService;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.ExcelUtil;
import com.njcn.web.utils.PoiUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
@@ -61,6 +58,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@@ -78,15 +76,16 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
private final IDevTypeService devTypeService;
private final ISysTestConfigService sysTestConfigService;
private final IDictTypeService dictTypeService;
private final ISysUserService userService;
@Override
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
Page<PqDev> page1 = this.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), this.getQueryWrapper(queryParam));
page1.getRecords().forEach(p -> {
if (ObjectUtil.isNotNull(p.getSeries())) {
if (StrUtil.isNotBlank(p.getSeries())) {
p.setSeries(EncryptionUtil.decoderString(1, p.getSeries()));
}
if (ObjectUtil.isNotNull(p.getDevKey())) {
if (StrUtil.isNotBlank(p.getDevKey())) {
p.setDevKey(EncryptionUtil.decoderString(1, p.getDevKey()));
}
});
@@ -109,19 +108,16 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
@Transactional
public boolean addPqDev(PqDevParam pqDevParam) {
pqDevParam.setName(pqDevParam.getName().trim());
pqDevParam.setCreateId(pqDevParam.getCreateId().trim());
this.checkRepeat(pqDevParam, false);
PqDev pqDev = new PqDev();
BeanUtil.copyProperties(pqDevParam, pqDev);
if (pqDevParam.getEncryptionFlag() == 1) {
if (StrUtil.isNotBlank(pqDevParam.getSeries()) && StrUtil.isNotBlank(pqDevParam.getDevKey())) {
pqDev.setSeries(EncryptionUtil.encodeString(1, pqDev.getSeries()));
pqDev.setDevKey(EncryptionUtil.encodeString(1, pqDev.getDevKey()));
} else {
throw new BusinessException(DetectionResponseEnum.SERIES_AND_DEVKEY_NOT_BLANK);
}
}
if ("1".equals(sysTestConfigService.getCurrrentScene())) {
String currrentScene = sysTestConfigService.getCurrrentScene();
this.checkParams(pqDev, currrentScene);
if (SceneEnum.LEAVE_FACTORY_TEST.getValue().equals(currrentScene)) {
pqDev.setManufacturer("8fa73802c9e1abab973adcbeb0d58567"); // 南京灿能字典项目对应的id
}
// 新增时默认设置
@@ -143,13 +139,14 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return this.save(pqDev);
}
@Override
@Transactional
public boolean updatePqDev(PqDevParam.UpdateParam updateParam) {
this.checkRepeat(updateParam, true);
PqDev pqDev = new PqDev();
BeanUtil.copyProperties(updateParam, pqDev);
/**
* 校验参数
*
* @param pqDev
* @param currrentScene
*/
private void checkParams(PqDev pqDev, String currrentScene) {
SceneEnum sceneEnum = SceneEnum.getSceneEnum(currrentScene);
if (pqDev.getEncryptionFlag() == 1) {
if (StrUtil.isNotBlank(pqDev.getSeries()) && StrUtil.isNotBlank(pqDev.getDevKey())) {
pqDev.setSeries(EncryptionUtil.encodeString(1, pqDev.getSeries()));
@@ -158,6 +155,36 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
throw new BusinessException(DetectionResponseEnum.SERIES_AND_DEVKEY_NOT_BLANK);
}
}
switch (sceneEnum) {
case PROVINCE_PLATFORM:
if (!Pattern.matches(PatternRegex.PROVINCE_DEV_NAME_REGEX, pqDev.getName())) {
throw new BusinessException(DetectionResponseEnum.PROVINCE_DEV_NAME_FORMAT_ERROR);
}
break;
case LEAVE_FACTORY_TEST:
if (!Pattern.matches(PatternRegex.CN_DEV_NAME_REGEX, pqDev.getName())) {
throw new BusinessException(DetectionResponseEnum.CN_DEV_NAME_FORMAT_ERROR);
}
break;
case SELF_TEST:
break;
default:
break;
}
}
@Override
@Transactional
public boolean updatePqDev(PqDevParam.UpdateParam updateParam) {
updateParam.setName(updateParam.getName().trim());
updateParam.setCreateId(updateParam.getCreateId().trim());
this.checkRepeat(updateParam, true);
PqDev pqDev = new PqDev();
BeanUtil.copyProperties(updateParam, pqDev);
String currrentScene = sysTestConfigService.getCurrrentScene();
this.checkParams(pqDev, currrentScene);
// 比对式设备修改监测点
if (PatternEnum.CONTRAST.getValue().equals(dictDataService.getDictDataById(updateParam.getPattern()).getCode())) {
if (ObjectUtil.isNotEmpty(updateParam.getMonitorList())) {
@@ -344,23 +371,22 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.lambdaUpdate().set(PqDev::getPlanId, planId).in(PqDev::getId, devIds).update();
List<PqDev> list = this.list(new LambdaQueryWrapper<PqDev>().in(PqDev::getId, devIds));
//判断是否有处了未检的其他设备
List<Integer> notUnchecked = list.stream().map(PqDev::getCheckState).filter(x -> !x.equals(CheckStateEnum.UNCHECKED.getValue())).distinct().collect(Collectors.toList());
List<String> notUnchecked = list.stream().filter(x -> !CheckStateEnum.UNCHECKED.getValue().equals(x.getCheckState())).map(PqDev::getId).distinct().collect(Collectors.toList());
if (CollUtil.isNotEmpty(notUnchecked)) {
List<Integer> unchecked = list.stream().map(PqDev::getCheckState).filter(x -> x.equals(CheckStateEnum.UNCHECKED.getValue())).distinct().collect(Collectors.toList());
List<String> unchecked = list.stream().filter(x -> CheckStateEnum.UNCHECKED.getValue().equals(x.getCheckState())).map(PqDev::getId).distinct().collect(Collectors.toList());
//计划未检测
if (CollUtil.isNotEmpty(unchecked)) {
return CheckStateEnum.CHECKING.getValue();
}
//计划检测中
List<String> checking = list.stream().filter(x -> CheckStateEnum.CHECKING.getValue().equals(x.getCheckState()) ||
CheckStateEnum.CHECKED.getValue().equals(x.getCheckState()) ||
!DevDocumentStateEnum.DOCUMENTED.getValue().equals(x.getReportState())
List<String> checking = list.stream().filter(x -> x.getCheckState().equals(CheckStateEnum.CHECKED.getValue()) &&
!CheckStateEnum.DOCUMENTED.getValue().equals(x.getCheckState())
).map(PqDev::getId).distinct().collect(Collectors.toList());
if (checking.size() == notUnchecked.size()) {
return CheckStateEnum.CHECKING.getValue();
}
//检测完成
List<Integer> checked = list.stream().map(PqDev::getCheckState).filter(x -> x.equals(CheckStateEnum.DOCUMENTED.getValue())).distinct().collect(Collectors.toList());
List<String> checked = list.stream().filter(x -> CheckStateEnum.DOCUMENTED.getValue().equals(x.getCheckState())).map(PqDev::getId).distinct().collect(Collectors.toList());
if (checked.size() == notUnchecked.size()) {
return CheckStateEnum.CHECKED.getValue();
}
@@ -370,6 +396,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return CheckStateEnum.UNCHECKED.getValue();
}
//
// @Override
// public List getPieData(String planId) {
// List<PqDev> pqDevList = this.lambdaQuery().eq(PqDev::getPlanId, planId).eq(PqDev::getState, DataStateEnum.ENABLE.getCode()).list();
@@ -391,6 +418,9 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
public PqDevVO getPqDevById(String id) {
PqDev pqDev = this.getById(id);
if (StrUtil.isNotBlank(pqDev.getCheckBy())) {
pqDev.setCheckBy(userService.getById(pqDev.getCheckBy()).getName());
}
PqDevVO pqDevVO = new PqDevVO();
BeanUtil.copyProperties(pqDev, pqDevVO);
@@ -459,47 +489,9 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
return preDetections;
}
@Override
@Transactional
public boolean documented(List<String> ids) {
if (CollUtil.isNotEmpty(ids)) {
for (String id : ids) {
// 只有检测完成的设备才可以进行归档
PqDev pqDev = this.getById(id);
if (ObjectUtil.isNotNull(pqDev)) {
if (!pqDev.getCheckState().equals(CheckStateEnum.CHECKED.getValue())) {
throw new BusinessException(DetectionResponseEnum.DEV_UN_CHECKED);
}
if (!pqDev.getReportState().equals(DevReportStateEnum.GENERATED.getValue())) {
throw new BusinessException(DetectionResponseEnum.DEV_UN_REPORT);
}
boolean update = this.lambdaUpdate()
.set(PqDev::getCheckState, CheckStateEnum.DOCUMENTED.getValue())
.eq(PqDev::getId, id)
.update();
if (update) {
// 判断计划下所有设备是否都已归档,如果是则将计划改为已完成
// 查询该计划下所有设备的检测状态,是否有不为归档的
LambdaQueryWrapper<PqDev> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(PqDev::getPlanId, pqDev.getPlanId())
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
.ne(PqDev::getCheckState, CheckStateEnum.DOCUMENTED.getValue());
int count = this.count(queryWrapper);
if (count == 0) {
// 如果非归档状态的设备数量为0则更新计划已完成
this.baseMapper.finishPlan(pqDev.getPlanId());
}
}
} else {
throw new BusinessException(DetectionResponseEnum.DEV_UN_CHECKED);
}
}
}
return true;
}
@Override
public boolean updateResult(List<String> ids, List<String> valueType, String code,String userId) {
public boolean updateResult(List<String> ids, List<String> valueType, String code, String userId, Float temperature, Float humidity) {
if (CollUtil.isNotEmpty(ids)) {
SysTestConfig config = sysTestConfigService.getOneConfig();
Map<String, Integer> result = detectionDataDealService.devResult(ids, valueType, code);
@@ -509,43 +501,36 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
if (result.containsKey(pqDev.getId())) {
Integer checkState;
int i;
LambdaUpdateWrapper<PqDev> wrapper = new LambdaUpdateWrapper<PqDev>()
.set(PqDev::getCheckResult, result.get(pqDev.getId()))
.set(StrUtil.isNotBlank(userId), PqDev::getCheckBy, userId)
.set(PqDev::getCheckTime, LocalDateTime.now())
.eq(PqDev::getId, pqDev.getId());
String currrentScene = sysTestConfigService.getCurrrentScene();
if (SceneEnum.PROVINCE_PLATFORM.getValue().equals(currrentScene)) {
wrapper.set(ObjectUtil.isNotNull(temperature), PqDev::getTemperature, temperature)
.set(ObjectUtil.isNotNull(humidity), PqDev::getHumidity, humidity);
}
if (pqDev.getReCheckNum() >= config.getMaxTime()) {
// 装置报告生成 todo...
this.baseMapper.updateReportState(pqDev.getId());
//this.baseMapper.updateReportState(pqDev.getId());
wrapper.set(PqDev::getReportState, DevReportStateEnum.GENERATED.getValue());
// 装置归档
checkState = CheckStateEnum.DOCUMENTED.getValue();
i = pqDev.getReCheckNum();
} else {
checkState = CheckStateEnum.CHECKED.getValue();
i = pqDev.getReCheckNum() + 1;
wrapper.set(PqDev::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
}
this.update(new LambdaUpdateWrapper<PqDev>()
.set(PqDev::getReCheckNum, i)
.set(PqDev::getCheckState, checkState)
.set(PqDev::getCheckResult, result.get(pqDev.getId()))
.set(PqDev::getCheckBy, userId)
.set(PqDev::getCheckTime, LocalDateTime.now())
.set(PqDev::getReportState, DevReportStateEnum.NOT_GENERATED.getValue())
.eq(PqDev::getId, pqDev.getId()));
if (checkState.equals(CheckStateEnum.DOCUMENTED.getValue())) {
// 判断计划下所有设备是否都已归档,如果是则将计划改为已完成
// 查询该计划下所有设备的检测状态,是否有不为归档的
LambdaQueryWrapper<PqDev> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(PqDev::getPlanId, pqDev.getPlanId())
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
.ne(PqDev::getCheckState, CheckStateEnum.DOCUMENTED.getValue());
int count = this.count(queryWrapper);
if (count == 0) {
// 如果非归档状态的设备数量为0则更新计划已完成
this.baseMapper.finishPlan(pqDev.getPlanId());
}
}
wrapper.set(PqDev::getReCheckNum, i)
.set(PqDev::getCheckState, checkState);
this.update(wrapper);
LambdaQueryWrapper<PqDev> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(PqDev::getPlanId, pqDev.getPlanId())
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode());
List<PqDev> pqDevList = this.list(queryWrapper);
if (CollUtil.isNotEmpty(pqDevList)) {
Set<Integer> set = pqDevList.stream().map(PqDev::getCheckResult).collect(Collectors.toSet());
@@ -557,15 +542,23 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.baseMapper.updatePlanCheckResult(pqDev.getPlanId(), CheckResultEnum.ACCORD.getValue());
}
// set = pqDevList.stream().map(PqDev::getCheckState).collect(Collectors.toSet());
// if (set.contains(CheckStateEnum.UNCHECKED.getValue())) {
// this.baseMapper.updatePlanTestState(pqDev.getPlanId(), CheckStateEnum.UNCHECKED.getValue());
// } else {
// this.baseMapper.updatePlanTestState(pqDev.getPlanId(), CheckStateEnum.CHECKED.getValue());
// }
set = pqDevList.stream().map(PqDev::getCheckState).collect(Collectors.toSet());
if (set.contains(CheckStateEnum.UNCHECKED.getValue())) {
this.baseMapper.updatePlanTestState(pqDev.getPlanId(), CheckStateEnum.CHECKING.getValue());
} else {
if (checkState.equals(CheckStateEnum.DOCUMENTED.getValue())) {
queryWrapper.ne(PqDev::getCheckState, CheckStateEnum.DOCUMENTED.getValue());
int count = this.count(queryWrapper);
if (count == 0) {
// 如果非归档状态的设备数量为0则更新计划已完成
this.baseMapper.finishPlan(pqDev.getPlanId());
}
} else {
this.baseMapper.updatePlanTestState(pqDev.getPlanId(), CheckStateEnum.CHECKING.getValue());
}
}
}
}
}
}
return true;
@@ -695,6 +688,9 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
} else {
throw new BusinessException(DetectionResponseEnum.SERIES_AND_DEVKEY_NOT_BLANK);
}
} else {
pqDev.setSeries(null);
pqDev.setDevKey(null);
}
String name = pqDev.getName();
@@ -737,9 +733,11 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
this.checkRepeat(param, false);
pqDev.setManufacturer("8fa73802c9e1abab973adcbeb0d58567"); // 南京灿能字典项目对应的id
long count = newDevList.stream().filter(dev -> dev.getName().equals(pqDev.getName())).count();
long count = newDevList.stream().filter(dev -> dev.getName().equals(pqDev.getName()) && dev.getCreateId().equals(pqDev.getCreateId())).count();
if (count == 0) {
newDevList.add(pqDev);
} else {
throw new BusinessException(DetectionResponseEnum.NAME_OR_CREATEID_REPEAT);
}
}
});
@@ -844,12 +842,17 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
// 是否支持系数校准
pullDown = new PullDown();
pullDown.setFirstCol(startCol + 11);
pullDown.setLastCol(startCol + 11);
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
// 委托方
dictType = dictTypeService.getByCode("Delegate");
if (ObjectUtil.isNotNull(dictType)) {
dictDataList = dictDataService.getDictDataByTypeId(dictType.getId());
pullDown = new PullDown();
pullDown.setFirstCol(startCol + 15);
pullDown.setLastCol(startCol + 15);
pullDown.setStrings(dictDataList.stream().map(DictData::getName).collect(Collectors.toList()));
pullDowns.add(pullDown);
}
return pullDowns;
}
@@ -903,8 +906,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
// 是否支持系数校准
pullDown = new PullDown();
pullDown.setFirstCol(startCol + 8);
pullDown.setLastCol(startCol + 8);
pullDown.setFirstCol(startCol + 7);
pullDown.setLastCol(startCol + 7);
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
@@ -932,11 +935,26 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
*/
public void reverseVisualizeCNDev(List<PqDev> pqDevs, String patternId) {
pqDevs.forEach(pqDev -> {
pqDev.setPreinvestmentPlan(dictDataService.getDictDataByName(pqDev.getPreinvestmentPlan()).getId());
DictData preinvestmentPlanDictData = dictDataService.getDictDataByName(pqDev.getPreinvestmentPlan());
if (ObjectUtil.isNull(preinvestmentPlanDictData)) {
throw new BusinessException(DetectionResponseEnum.PREINVESTMENT_PLAN_NOT_EXIST);
} else {
pqDev.setPreinvestmentPlan(preinvestmentPlanDictData.getId());
}
DevType devType = devTypeService.getByName(pqDev.getDevType());
pqDev.setDevType(devType.getId());
if (ObjectUtil.isNull(devType)) {
throw new BusinessException(DetectionResponseEnum.DEV_TYPE_NOT_EXIST);
} else {
pqDev.setDevType(devType.getId());
}
pqDev.setPattern(patternId);
pqDev.setProtocol(dictDataService.getDictDataByName(pqDev.getProtocol()).getId());
DictData protocolDictData = dictDataService.getDictDataByName(pqDev.getProtocol());
if (ObjectUtil.isNull(protocolDictData)) {
throw new BusinessException(DetectionResponseEnum.PROTOCOL_NOT_EXIST);
} else {
pqDev.setProtocol(protocolDictData.getId());
}
pqDev.setCreateDate(LocalDateTime.now().toLocalDate());
pqDev.setCreateId(pqDev.getName());
pqDev.setTimeCheckResult(TimeCheckResultEnum.UNKNOWN.getValue());
@@ -1017,6 +1035,9 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
} else {
throw new BusinessException(DetectionResponseEnum.SERIES_AND_DEVKEY_NOT_BLANK);
}
} else {
pqDev.setSeries(null);
pqDev.setDevKey(null);
}
String name = pqDev.getName();
@@ -1058,9 +1079,11 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
param.setDevType(pqDev.getDevType());
this.checkRepeat(param, false);
long count = newDevList.stream().filter(dev -> dev.getName().equals(pqDev.getName())).count();
long count = newDevList.stream().filter(dev -> dev.getName().equals(pqDev.getName()) || dev.getCreateId().equals(pqDev.getCreateId())).count();
if (count == 0) {
newDevList.add(pqDev);
} else {
throw new BusinessException(DetectionResponseEnum.NAME_OR_CREATEID_REPEAT);
}
}
});
@@ -1073,8 +1096,14 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
public void visualizeProvinceDev(List<PqDev> pqDevs) {
pqDevs.forEach(pqDev -> {
pqDev.setDevType(devTypeService.getById(pqDev.getDevType()).getName());
pqDev.setManufacturer(dictDataService.getDictDataById(pqDev.getManufacturer()).getName());
if (StrUtil.isNotBlank(pqDev.getManufacturer())) {
pqDev.setManufacturer(dictDataService.getDictDataById(pqDev.getManufacturer()).getName());
}
pqDev.setProtocol(dictDataService.getDictDataById(pqDev.getProtocol()).getName());
if (StrUtil.isNotBlank(pqDev.getDelegate())) {
pqDev.setDelegate(dictDataService.getDictDataById(pqDev.getDelegate()).getName());
}
});
}
@@ -1082,10 +1111,32 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
public void reverseVisualizeProvinceDev(List<PqDev> pqDevs, String patternId) {
pqDevs.forEach(pqDev -> {
DevType devType = devTypeService.getByName(pqDev.getDevType());
pqDev.setDevType(devType.getId());
if (ObjectUtil.isNull(devType)) {
throw new BusinessException(DetectionResponseEnum.DEV_TYPE_NOT_EXIST);
} else {
pqDev.setDevType(devType.getId());
}
pqDev.setPattern(patternId);
pqDev.setManufacturer(dictDataService.getDictDataByName(pqDev.getManufacturer()).getId());
pqDev.setProtocol(dictDataService.getDictDataByName(pqDev.getProtocol()).getId());
DictData manufacturerDictData = dictDataService.getDictDataByName(pqDev.getManufacturer());
if (ObjectUtil.isNull(manufacturerDictData)) {
throw new BusinessException(DetectionResponseEnum.MANUFACTURER_NOT_EXIST);
} else {
pqDev.setManufacturer(manufacturerDictData.getId());
}
DictData protocolDictData = dictDataService.getDictDataByName(pqDev.getProtocol());
if (ObjectUtil.isNull(protocolDictData)) {
throw new BusinessException(DetectionResponseEnum.PROTOCOL_NOT_EXIST);
} else {
pqDev.setProtocol(protocolDictData.getId());
}
if (StrUtil.isNotBlank(pqDev.getDelegate())) {
DictData delegateDictData = dictDataService.getDictDataByName(pqDev.getDelegate());
if (ObjectUtil.isNull(delegateDictData)) {
throw new BusinessException(DetectionResponseEnum.DELEGATE_NOT_EXIST);
} else {
pqDev.setDelegate(delegateDictData.getId());
}
}
pqDev.setTimeCheckResult(TimeCheckResultEnum.UNKNOWN.getValue());
pqDev.setFactorCheckResult(FactorCheckResultEnum.UNKNOWN.getValue());
pqDev.setCheckState(CheckStateEnum.UNCHECKED.getValue());

View File

@@ -38,11 +38,6 @@ public class PqErrSysDtlsParam {
@ApiModelProperty(value = "是否包含结束值", required = true)
private Integer endFlag;
// @ApiModelProperty(value = "单位", required = true)
// @NotBlank(message = DeviceValidMessage.UNIT_NOT_BLANK)
// @Pattern(regexp = PatternRegex.SYSTEM_ID, message = DeviceValidMessage.UNIT_FORMAT_ERROR)
// private String unit;
@ApiModelProperty(value = "判断条件值类型", required = true)
private Integer conditionType;
@@ -58,4 +53,10 @@ public class PqErrSysDtlsParam {
@NotNull(message = DetectionValidMessage.SORT_NOT_NULL)
private Integer sort;
@ApiModelProperty("1绝对值、2相对值")
private Integer valueType;
@ApiModelProperty("误差单位")
private String errorUnit;
}

View File

@@ -21,7 +21,7 @@ public class PqErrSysParam {
@ApiModelProperty(value = "参照标准名称", required = true)
@NotBlank(message = DetectionValidMessage.STANDARD_NAME_NOT_BLANK)
@Pattern(regexp = PatternRegex.ERR_SYS_NAME, message = DetectionValidMessage.STANDARD_NAME_FORMAT_ERROR)
@Pattern(regexp = PatternRegex.ERR_SYS_NAME_REGEX, message = DetectionValidMessage.STANDARD_NAME_FORMAT_ERROR)
private String standardName;
@ApiModelProperty(value = "标准实施年份", required = true)
@@ -41,7 +41,6 @@ public class PqErrSysParam {
private Integer enable;
@ApiModelProperty(value = "误差详情列表", required = true)
@Valid
private List<PqErrSysDtlsParam> pqErrSysDtlsList;
@Data

View File

@@ -60,10 +60,6 @@ public class PqErrSysDtls implements Serializable {
*/
private Integer endFlag;
/**
* 单位
*/
// private String unit;
/**
* 判断条件值类型(包括值类型,绝对值、相对值)
@@ -77,7 +73,7 @@ public class PqErrSysDtls implements Serializable {
private Double maxErrorValue;
/**
* 误差值类型
* 误差值类型(绝对值:0:标称值 1:标准值 2:值比较 相对值:0标称值 1:标准值)
*/
private Integer errorValueType;
@@ -86,5 +82,14 @@ public class PqErrSysDtls implements Serializable {
*/
private Integer sort;
/**
* 1绝对值、2相对值
*/
private Integer valueType;
/**
* 误差单位
*/
private String errorUnit;
}

View File

@@ -24,7 +24,6 @@ import com.njcn.gather.system.dictionary.service.IDictTreeService;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -68,6 +67,7 @@ public class PqErrSysServiceImpl extends ServiceImpl<PqErrSysMapper, PqErrSys> i
@Override
@Transactional
public boolean addPqErrSys(PqErrSysParam param) {
param.setStandardName(param.getStandardName().trim());
this.checkRepeat(param, false);
PqErrSys pqErrSys = new PqErrSys();
BeanUtils.copyProperties(param, pqErrSys);
@@ -85,6 +85,7 @@ public class PqErrSysServiceImpl extends ServiceImpl<PqErrSysMapper, PqErrSys> i
@Override
@Transactional
public boolean updatePqErrSys(PqErrSysParam.UpdateParam param) {
param.setStandardName(param.getStandardName().trim());
this.checkRepeat(param, true);
PqErrSys pqErrSys = new PqErrSys();
BeanUtils.copyProperties(param, pqErrSys);

View File

@@ -2,6 +2,7 @@ package com.njcn.gather.icd.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import org.apache.ibatis.annotations.Param;
/**
* @author caozehui
@@ -9,5 +10,12 @@ import com.njcn.gather.icd.pojo.po.PqIcdPath;
*/
public interface PqIcdPathMapper extends MPJBaseMapper<PqIcdPath> {
/**
* 根据设备类型id获取Icd
*
* @param devTypeId
* @return
*/
PqIcdPath selectIcdByDevType(@Param("devTypeId") String devTypeId);
}

View File

@@ -3,5 +3,11 @@
<mapper namespace="com.njcn.gather.icd.mapper.PqIcdPathMapper">
<select id="selectIcdByDevType" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
select *
from pq_icd_path path
inner join pq_dev_type type on path.id = type.icd
where type.id = #{devTypeId}
</select>
</mapper>

View File

@@ -51,4 +51,12 @@ public interface IPqIcdPathService extends IService<PqIcdPath> {
* @return 成功返回true失败返回false
*/
boolean deleteIcd(List<String> ids);
/**
* 根据设备类型id获取Icd
*
* @param devTypeId
* @return
*/
PqIcdPath getIcdByDevType(String devTypeId);
}

View File

@@ -47,6 +47,7 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
@Override
@Transactional
public boolean addIcd(PqIcdPathParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, false);
PqIcdPath pqIcdPath = new PqIcdPath();
BeanUtils.copyProperties(param, pqIcdPath);
@@ -57,6 +58,7 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
@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);
@@ -69,6 +71,11 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
return this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
}
@Override
public PqIcdPath getIcdByDevType(String devTypeId) {
return this.baseMapper.selectIcdByDevType(devTypeId);
}
private void checkRepeat(PqIcdPathParam param, boolean isExcludeSelf) {
LambdaQueryWrapper<PqIcdPath> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PqIcdPath::getName, param.getName())

View File

@@ -3,7 +3,6 @@ package com.njcn.gather.monitor.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.monitor.mapper.PqMonitorMapper;
import com.njcn.gather.monitor.pojo.param.PqMonitorParam;
import com.njcn.gather.monitor.pojo.po.PqMonitor;

View File

@@ -125,8 +125,8 @@ public class AdPlanController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
@PostMapping("/downloadTemplate")
@ApiOperation("下载检测计划导出模板")
public void downloadTemplate() {
adPlanService.downloadTemplate();
public void downloadTemplate(@RequestBody AdPlanParam.QueryParam queryParam) {
adPlanService.downloadTemplate(queryParam.getPatternId());
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPLOAD)
@@ -155,7 +155,7 @@ public class AdPlanController extends BaseController {
public HttpResult<List<Map<String, String>>> getBigTestItem(@RequestBody AdPlanParam.CheckParam checkParam) {
String methodDescribe = getMethodDescribe("getBigTestItem");
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, checkParam);
List<Map<String, String>> result = adPlanService.getBigTestItem(checkParam.getReCheckType(), checkParam.getPlanId(), checkParam.getDevId());
List<Map<String, String>> result = adPlanService.getBigTestItem(checkParam.getReCheckType(), checkParam.getPlanId(), checkParam.getDevIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}

View File

@@ -5,6 +5,8 @@ import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.report.pojo.po.PqReport;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author caozehui
* @date 2024-12-09
@@ -27,5 +29,13 @@ public interface AdPlanMapper extends MPJBaseMapper<AdPlan> {
* @return
*/
PqReport getPqReportById(String id);
/**
* 获取所有报告模板名称
*
* @return
*/
List<String> listAllReportTemplateName();
}

View File

@@ -17,5 +17,10 @@
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

@@ -8,13 +8,13 @@ import lombok.Getter;
*/
@Getter
public enum DataSourceEnum {
THREE_SENSE_ACTUAL_TIME_DATA("0", "3s实时数据"),
THREE_SENSE_ACTUAL_TIME_DATA("real", "3s实时数据"),
MINUTE_STATISTICS_MAX("1", "分钟统计数据-最大"),
MINUTE_STATISTICS_MIN("2", "分钟统计数据-最小"),
MINUTE_STATISTICS_AVG("3", "分钟统计数据-平均"),
MINUTE_STATISTICS_CP95("4", "分钟统计数据-CP95"),
RECORDED_DATA("5", "录播数据");
MINUTE_STATISTICS_MAX("max", "分钟统计数据-最大"),
MINUTE_STATISTICS_MIN("min", "分钟统计数据-最小"),
MINUTE_STATISTICS_AVG("avg", "分钟统计数据-平均"),
MINUTE_STATISTICS_CP95("cp95", "分钟统计数据-CP95"),
RECORDED_DATA("Recorded_data", "录播数据");
private String value;
private String msg;

View File

@@ -60,11 +60,16 @@ public class AdPlanParam {
private List<String> devIds;
@ApiModelProperty(value = "是否关联报告")
@NotNull(message = DetectionValidMessage.ASSOCIATE_REPORT_NOT_NULL)
private Integer associateReport;
@ApiModelProperty(value = "报告模板名称")
private String reportTemplateName;
@ApiModelProperty(value = "数据处理原则")
@NotBlank(message = DetectionValidMessage.DATA_RULE_NOT_BLANK)
private String dataRule;
/**
* 分页查询实体
*/
@@ -78,7 +83,7 @@ public class AdPlanParam {
@ApiModelProperty(value = "模式,字典表(数字、模拟、比对)")
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.PATTERN_FORMAT_ERROR)
@NotBlank(message = DetectionValidMessage.PATTERN_NOT_BLANK)
private String pattern;
private String patternId;
@ApiModelProperty(value = "检测状态")
@Min(value = 0, message = DetectionValidMessage.TEST_STATE_FORMAT_ERROR)
@@ -110,6 +115,6 @@ public class AdPlanParam {
// 0:不合格项复检 1:全部复检
private Integer reCheckType;
private String planId;
private String devId;
private List<String> devIds;
}
}

View File

@@ -1,8 +1,9 @@
package com.njcn.gather.plan.pojo.po;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.mybatisplus.bo.BaseEntity;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -86,11 +87,17 @@ public class AdPlan extends BaseEntity implements Serializable {
/**
* 报告模板ID关联PQ_Report表
*/
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String reportTemplateId;
/**
* 状态0-删除 1-正常
*/
private Integer state;
/**
* 数据处理原则。任意值、部分值、所有值、cp95值、平均值
*/
private String dataRule;
}

View File

@@ -25,27 +25,38 @@ public class AdPlanExcel {
@NotBlank(message = DetectionValidMessage.DATASOURCE_NOT_BLANK)
private String datasourceId;
@Excel(name = "脚本*", width = 100, needMerge = true, orderNum = "3")
@Excel(name = "脚本*", width = 40, needMerge = true, orderNum = "3")
@NotBlank(message = DetectionValidMessage.SCRIPT_NOT_BLANK)
private String scriptId;
@Excel(name = "误差体系*", width = 30, needMerge = true, orderNum = "4")
@Excel(name = "误差体系*", width = 40, needMerge = true, orderNum = "4")
@NotBlank(message = DetectionValidMessage.ERRORSYS_NOT_BLANK)
private String errorSysId;
@Excel(name = "是否做守时检测*", width = 15, replace = {"否_0", "是_1"}, needMerge = true, orderNum = "5")
@Excel(name = "数据处理原则*", width = 20, needMerge = true, orderNum = "5")
@NotBlank(message = DetectionValidMessage.DATA_RULE_NOT_BLANK)
private String dataRule;
@Excel(name = "是否做守时检测*", width = 20, replace = {"否_0", "是_1"}, needMerge = true, orderNum = "6")
@NotNull(message = DetectionValidMessage.TIMECHECK_NOT_NULL)
private Integer timeCheck;
@Excel(name = "检测状态*", width = 10, replace = {"未检_0", "检测中_1", "检测完成_2"}, needMerge = true, orderNum = "6")
@NotNull(message = DetectionValidMessage.TEST_STATE_NOT_NULL)
private Integer testState;
@Excel(name = "关联报告模版*", width = 20, replace = {"_0", "_1"}, needMerge = true, orderNum = "7")
@NotNull(message = DetectionValidMessage.ASSOCIATE_REPORT_NOT_NULL)
private Integer associateReport;
@Excel(name = "报告生成状态*", width = 15, replace = {"未生成_0", "部分生成_1", "全部生成_2"}, needMerge = true, orderNum = "7")
@NotNull(message = DetectionValidMessage.REPORT_STATE_NOT_NULL)
private Integer reportState;
@Excel(name = "报告模版(当关联报告模版为是时必填)", width = 40, needMerge = true, orderNum = "8")
private String reportTemplateId;
@Excel(name = "检测结果*", width = 10, replace = {"不符合_0", "符合_1", "未检_2"}, needMerge = true, orderNum = "8")
@NotNull(message = DetectionValidMessage.CHECK_RESULT_STATE_NOT_NULL)
private Integer result;
// @Excel(name = "检测状态*", width = 10, replace = {"未检_0", "检测中_1", "检测完成_2"}, needMerge = true, orderNum = "9")
// @NotNull(message = DetectionValidMessage.TEST_STATE_NOT_NULL)
// private Integer testState;
//
// @Excel(name = "报告生成状态*", width = 15, replace = {"未生成_0", "部分生成_1", "全部生成_2"}, needMerge = true, orderNum = "10")
// @NotNull(message = DetectionValidMessage.REPORT_STATE_NOT_NULL)
// private Integer reportState;
//
// @Excel(name = "检测结果*", width = 10, replace = {"不符合_0", "符合_1", "未检_2"}, needMerge = true, orderNum = "11")
// @NotNull(message = DetectionValidMessage.CHECK_RESULT_STATE_NOT_NULL)
// private Integer result;
}

View File

@@ -108,4 +108,6 @@ public class AdPlanVO {
* 报告模板名称
*/
private String reportTemplateName;
private String dataRule;
}

View File

@@ -1,5 +1,6 @@
package com.njcn.gather.plan.pojo.vo;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import com.njcn.gather.device.pojo.vo.ProvinceDevExcel;
import lombok.Data;

View File

@@ -70,10 +70,10 @@ public interface IAdPlanService extends IService<AdPlan> {
*
* @param reCheckType 0:不合格项复检 1:全部复检
* @param planId 检测计划Id
* @param devId 设备Id
* @param devIds 设备Id列表
* @return
*/
List<Map<String, String>> getBigTestItem(Integer reCheckType, String planId, String devId);
List<Map<String, String>> getBigTestItem(Integer reCheckType, String planId, List<String> devIds);
/**
* 修改计划状态
@@ -111,8 +111,10 @@ public interface IAdPlanService extends IService<AdPlan> {
/**
* 下载检测计划模板
*
* @param patternId
*/
void downloadTemplate();
void downloadTemplate(String patternId);
/**
* 导入检测计划数据

View File

@@ -38,6 +38,7 @@ import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.plan.service.IAdPlanSourceService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.pojo.po.PqReport;
import com.njcn.gather.script.pojo.po.PqScript;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.script.service.IPqScriptService;
@@ -142,6 +143,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
this.checkRepeat(param, false);
AdPlan adPlan = new AdPlan();
BeanUtil.copyProperties(param, adPlan);
adPlan.setName(param.getName().trim());
String planId = UUID.randomUUID().toString().replaceAll("-", "");
adPlan.setId(planId);
@@ -184,21 +186,26 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
@Override
@Transactional
public boolean updateAdPlan(AdPlanParam.UpdateParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, true);
AdPlan plan1 = this.getById(param.getId());
AdPlan plan2 = new AdPlan();
if (param.getAssociateReport() != null && param.getAssociateReport() == 1) {
String reportTemplateName = param.getReportTemplateName();
String[] split = reportTemplateName.split("_");
String reportId = this.baseMapper.getReportIdByNameAndVersion(split[0], split[1]);
if (plan1.getTestState() != CheckStateEnum.UNCHECKED.getValue()) {
if (!reportId.equals(plan1.getReportTemplateId())) {
throw new BusinessException(DetectionResponseEnum.CANNOT_CHANGE_REPORT_WHEN_CHECKING);
if (param.getAssociateReport() != null) {
if (param.getAssociateReport() == 1) {
String reportTemplateName = param.getReportTemplateName();
String[] split = reportTemplateName.split("_");
String reportId = this.baseMapper.getReportIdByNameAndVersion(split[0], split[1]);
// if (plan1.getTestState() != CheckStateEnum.UNCHECKED.getValue()) {
// if (!reportId.equals(plan1.getReportTemplateId())) {
// throw new BusinessException(DetectionResponseEnum.CANNOT_CHANGE_REPORT_WHEN_CHECKING);
// }
// }
if (StrUtil.isNotBlank(reportId)) {
plan2.setReportTemplateId(reportId);
}
}
if (StrUtil.isNotBlank(reportId)) {
plan2.setReportTemplateId(reportId);
} else {
plan2.setReportTemplateId(null);
}
}
@@ -209,9 +216,9 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
if (!plan1.getErrorSysId().equals(param.getErrorSysId())) {
throw new BusinessException(DetectionResponseEnum.CANNOT_CHANGE_ERROR_SYS_WHEN_CHECKING);
}
if (param.getAssociateReport() != null && param.getAssociateReport() != plan1.getAssociateReport()) {
throw new BusinessException(DetectionResponseEnum.CANNOT_CHANGE_REPORT_WHEN_CHECKING);
}
// if (param.getAssociateReport() != null && param.getAssociateReport() != plan1.getAssociateReport()) {
// throw new BusinessException(DetectionResponseEnum.CANNOT_CHANGE_REPORT_WHEN_CHECKING);
// }
}
BeanUtil.copyProperties(param, plan2);
@@ -300,11 +307,19 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
if (StrUtil.isNotBlank(adPlan.getErrorSysId())) {
adPlan.setErrorSysId(pqErrSysService.getPqErrSysById(adPlan.getErrorSysId()).getName());
}
if (StrUtil.isNotBlank(adPlan.getDataRule())) {
String dataRule = adPlan.getDataRule();
adPlan.setDataRule(dictDataService.getDictDataById(dataRule).getName());
}
if (StrUtil.isNotBlank(adPlan.getReportTemplateId())) {
PqReport report = this.baseMapper.getPqReportById(adPlan.getReportTemplateId());
adPlan.setReportTemplateId(report.getName() + "_" + report.getVersion());
}
});
}
@Override
public List<Map<String, String>> getBigTestItem(Integer reCheckType, String planId, String devId) {
public List<Map<String, String>> getBigTestItem(Integer reCheckType, String planId, List<String> devIds) {
List<Map<String, String>> result = new ArrayList<>();
AdPlan adPlan = this.getById(planId);
if (ObjectUtil.isNull(adPlan)) {
@@ -326,10 +341,14 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
//
// scriptDtlsList = scriptDtlsList.stream().filter(obj -> !sortSet.contains(obj.getScriptIndex())).collect(Collectors.toList());
// }
Set<Integer> indexes = new HashSet<>();
StorageParam storageParam = new StorageParam();
storageParam.setCode(adPlan.getCode() + "");
storageParam.setScriptId(adPlan.getScriptId());
List<Integer> indexes = adHarmonicService.getIndex(storageParam, true);
devIds.forEach(devId -> {
storageParam.setDevId(devId);
indexes.addAll(adHarmonicService.getIndex(storageParam));
});
scriptDtlsList = scriptDtlsList.stream().filter(obj -> indexes.contains(obj.getScriptIndex())).collect(Collectors.toList());
}
@@ -476,15 +495,15 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
@Override
public void downloadTemplate() {
public void downloadTemplate(String patternId) {
String currrentScene = sysTestConfigService.getCurrrentScene();
SceneEnum sceneEnum = SceneEnum.getSceneEnum(currrentScene);
switch (sceneEnum) {
case PROVINCE_PLATFORM:
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划模板.xlsx", 2, this.getPullDownList(SceneEnum.PROVINCE_PLATFORM), ProvincePlanExcel.class, Collections.emptyList());
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划模板.xlsx", 2, this.getPullDownList(SceneEnum.PROVINCE_PLATFORM, patternId), ProvincePlanExcel.class, Collections.emptyList());
break;
case LEAVE_FACTORY_TEST:
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划模板.xlsx", 2, this.getPullDownList(SceneEnum.LEAVE_FACTORY_TEST), CNPlanExcel.class, Collections.emptyList());
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划模板.xlsx", 2, this.getPullDownList(SceneEnum.LEAVE_FACTORY_TEST, patternId), CNPlanExcel.class, Collections.emptyList());
break;
case SELF_TEST:
break;
@@ -531,7 +550,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
List<ProvinceDevExcel> deviceExportData = BeanUtil.copyToList(pqDevs, ProvinceDevExcel.class);
planExcelList.get(i).setDevices(deviceExportData);
}
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划导出数据.xlsx", 2, this.getPullDownList(SceneEnum.PROVINCE_PLATFORM), ProvincePlanExcel.class, planExcelList);
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划导出数据.xlsx", 2, this.getPullDownList(SceneEnum.PROVINCE_PLATFORM, queryParam.getPatternId()), ProvincePlanExcel.class, planExcelList);
}
/**
@@ -554,7 +573,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
List<CNDevExcel> deviceExportData = BeanUtil.copyToList(pqDevs, CNDevExcel.class);
planExcelList.get(i).setDevices(deviceExportData);
}
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划导出数据.xlsx", 2, this.getPullDownList(SceneEnum.LEAVE_FACTORY_TEST), CNPlanExcel.class, planExcelList);
ExcelUtil.exportExcelPullDown(new ExportParams(), "检测计划导出数据.xlsx", 2, this.getPullDownList(SceneEnum.LEAVE_FACTORY_TEST, queryParam.getPatternId()), CNPlanExcel.class, planExcelList);
}
@Transactional
@@ -607,9 +626,6 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
Integer code = this.generateCode();
adPlans.get(i).setCode(code);
tableGenService.deleteTable(Arrays.asList(code.toString()));
tableGenService.genAdNonHarmonicTable(code.toString());
String source = planExcel.getSource();
String[] sourceNames = source.split(StrUtil.COMMA);
// 若非比对模式检测源、数据源有2个以上时不导入
@@ -623,12 +639,17 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
if (!PatternEnum.CONTRAST.getValue().equals(patternCode) && datasourceIds.length > 1) {
throw new BusinessException(DetectionResponseEnum.IMPORT_DATASOURCE_ERROR);
}
planExcel.setAssociateReport(0);
planExcel.setReportTemplateId(null);
List<String> sourceIds = pqSourceService.listPqSourceIdByName(sourceNames);
adPlanSourceService.addAdPlanSource(planId, sourceIds);
List<CNDevExcel> cnDevExcelList = planExcel.getDevices();
pqDevService.importCNDev(cnDevExcelList, patternId, planId);
tableGenService.deleteTable(Arrays.asList(code.toString()));
tableGenService.genAdNonHarmonicTable(code.toString());
}
// 逆向可视化
this.reverseVisualize(adPlans);
@@ -700,11 +721,18 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
if (!PatternEnum.CONTRAST.getValue().equals(patternCode) && datasourceIds.length > 1) {
throw new BusinessException(DetectionResponseEnum.IMPORT_DATASOURCE_ERROR);
}
if ((planExcel.getAssociateReport().equals(1) && "".equals(planExcel.getReportTemplateId()))) {
throw new BusinessException(DetectionResponseEnum.IMPORT_REPORT_TEMPLATE_ERROR);
}
List<String> sourceIds = pqSourceService.listPqSourceIdByName(sourceNames);
adPlanSourceService.addAdPlanSource(planId, sourceIds);
List<ProvinceDevExcel> cnDevExcelList = planExcel.getDevices();
ProvinceDevExcel provinceDevExcel = cnDevExcelList.get(0);
if (ObjectUtil.isNull(provinceDevExcel.getName())) {
cnDevExcelList.remove(0);
}
pqDevService.importProvinceDev(cnDevExcelList, patternId, planId);
}
// 逆向可视化
@@ -721,7 +749,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
private Wrapper getQueryWrapper(AdPlanParam.QueryParam queryParam) {
QueryWrapper<AdPlan> queryWrapper = new QueryWrapper<>();
if (ObjectUtil.isNotNull(queryParam)) {
queryWrapper.eq(StrUtil.isNotBlank(queryParam.getPattern()), "ad_plan.pattern", queryParam.getPattern())
queryWrapper.eq(StrUtil.isNotBlank(queryParam.getPatternId()), "ad_plan.pattern", queryParam.getPatternId())
.like(StrUtil.isNotBlank(queryParam.getName()), "ad_plan.name", queryParam.getName())
.eq(ObjectUtil.isNotNull(queryParam.getTestState()), "ad_plan.Test_State", queryParam.getTestState())
.eq(ObjectUtil.isNotNull(queryParam.getReportState()), "ad_plan.Report_State", queryParam.getReportState())
@@ -749,12 +777,9 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
});
PqErrSys errSys = pqErrSysService.getById(plan.getErrorSysId());
SysTestConfig config1 = sysTestConfigService.getConfig();
if (ObjectUtil.isNotNull(config1)) {
DictData dictData = dictDataService.getDictDataById(config1.getDataRule());
if (ObjectUtil.isNotNull(errSys) && ObjectUtil.isNotNull(dictData)) {
note.append("测试结果采用\"" + errSys.getName() + "\"误差体系结合\"" + dictData.getName() + "\"数据原则计算得出。");
}
DictData dictData1 = dictDataService.getDictDataById(plan.getDataRule());
if (ObjectUtil.isNotNull(dictData1) && ObjectUtil.isNotNull(errSys)) {
note.append("测试结果采用\"" + errSys.getName() + "\"误差体系结合\"" + dictData1.getName() + "\"数据原则计算得出。");
}
return note.toString();
}
@@ -817,13 +842,49 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
private void reverseVisualize(List<AdPlan> planList) {
planList.forEach(adPlan -> {
String[] datasourceIds = adPlan.getDatasourceId().split(StrUtil.COMMA);
adPlan.setDatasourceId(Arrays.stream(datasourceIds).map(id -> DataSourceEnum.getValueByMsg(id)).collect(Collectors.joining(StrUtil.COMMA)));
adPlan.setDatasourceId(Arrays.stream(datasourceIds).map(id -> {
String value = DataSourceEnum.getValueByMsg(id);
if (StrUtil.isBlank(value)) {
throw new BusinessException(DetectionResponseEnum.DATA_SOURCE_NOT_EXIST);
} else {
return value;
}
}).collect(Collectors.joining(StrUtil.COMMA)));
adPlan.setScriptId(pqScriptService.getPqScriptByName(adPlan.getScriptId()).getId());
PqScript pqScript = pqScriptService.getPqScriptByName(adPlan.getScriptId());
if (ObjectUtil.isNull(pqScript)) {
throw new BusinessException(DetectionResponseEnum.SCRIPT_NOT_EXIST);
} else {
adPlan.setScriptId(pqScript.getId());
}
adPlan.setErrorSysId(pqErrSysService.getPqErrSysByName(adPlan.getErrorSysId()).getId());
PqErrSys pqErrSys = pqErrSysService.getPqErrSysByName(adPlan.getErrorSysId());
if (ObjectUtil.isNull(pqErrSys)) {
throw new BusinessException(DetectionResponseEnum.ERROR_SYSTEM_NOT_EXIST);
} else {
adPlan.setErrorSysId(pqErrSys.getId());
}
DictData dataRuleDictData = dictDataService.getDictDataByName(adPlan.getDataRule());
if (ObjectUtil.isNull(dataRuleDictData)) {
throw new BusinessException(DetectionResponseEnum.DATA_RULE_NOT_EXIST);
} else {
adPlan.setDataRule(dataRuleDictData.getId());
}
if (adPlan.getAssociateReport().equals(0)) {
adPlan.setReportTemplateId(null);
}else if (StrUtil.isNotBlank(adPlan.getReportTemplateId())) {
String[] split = adPlan.getReportTemplateId().split("_");
String reportId = this.baseMapper.getReportIdByNameAndVersion(split[0], split[1]);
if (ObjectUtil.isNull(reportId)) {
throw new BusinessException(DetectionResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
} else {
adPlan.setReportTemplateId(reportId);
}
} else {
throw new BusinessException(DetectionResponseEnum.LACK_REPORT_TEMPLATE_ID);
}
adPlan.setCode(this.generateCode());
adPlan.setState(DataStateEnum.ENABLE.getCode());
// 默认为顶级检测计划
adPlan.setFatherPlanId(CommonEnum.FATHER_ID.getValue());
@@ -1019,10 +1080,19 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
}
private List<PullDown> getPullDownList(SceneEnum scene) {
private List<PullDown> getPullDownList(SceneEnum scene, String patternId) {
List<PullDown> pullDowns = new ArrayList<>();
PullDown pullDown = null;
List<Map<String, Object>> maps = pqSourceService.listAllPqSource(patternId);
if (ObjectUtil.isNotEmpty(maps)) {
pullDown = new PullDown();
pullDown.setFirstCol(1);
pullDown.setLastCol(1);
pullDown.setStrings(maps.stream().map(m -> (String) m.get("name")).collect(Collectors.toList()));
pullDowns.add(pullDown);
}
// 数据源
DictType dictType = dictTypeService.getByCode("Datasource");
if (ObjectUtil.isNotNull(dictType)) {
@@ -1052,34 +1122,61 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
pullDown.setStrings(errSysNameList);
pullDowns.add(pullDown);
// 是否做守时检测
pullDown = new PullDown();
pullDown.setFirstCol(5);
pullDown.setLastCol(5);
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
// 数据处理原则
dictType = dictTypeService.getByCode("Data_Rule");
if (ObjectUtil.isNotNull(dictType)) {
List<DictData> dictDataList = dictDataService.getDictDataByTypeId(dictType.getId());
// 检测状态
pullDown = new PullDown();
pullDown.setFirstCol(5);
pullDown.setLastCol(5);
pullDown.setStrings(dictDataList.stream().map(DictData::getName).collect(Collectors.toList()));
pullDowns.add(pullDown);
}
// 是否做守时检测
pullDown = new PullDown();
pullDown.setFirstCol(6);
pullDown.setLastCol(6);
pullDown.setStrings(Arrays.asList(CheckStateEnum.UNCHECKED.getMsg(), CheckStateEnum.CHECKING.getMsg(), CheckStateEnum.CHECKED.getMsg()));
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
// 报告生成状态
// 是否关联报告模板
pullDown = new PullDown();
pullDown.setFirstCol(7);
pullDown.setLastCol(7);
pullDown.setStrings(Arrays.asList(PlanReportStateEnum.REPORT_STATE_NOT_GENERATED.getMsg(), PlanReportStateEnum.REPORT_STATE_PARTIALLY_GENERATED.getMsg(), PlanReportStateEnum.REPORT_STATE_ALL_GENERATED.getMsg()));
pullDown.setStrings(Arrays.asList("", ""));
pullDowns.add(pullDown);
//检测结果
// 报告模板
List<String> strings = this.baseMapper.listAllReportTemplateName();
pullDown = new PullDown();
pullDown.setFirstCol(8);
pullDown.setLastCol(8);
pullDown.setStrings(Arrays.asList(CheckResultEnum.UNCHECKED.getMsg(), CheckResultEnum.ACCORD.getMsg(), CheckResultEnum.UNCHECKED.getMsg()));
pullDown.setStrings(strings);
pullDowns.add(pullDown);
// 检测状态
// pullDown = new PullDown();
// pullDown.setFirstCol(9);
// pullDown.setLastCol(9);
// pullDown.setStrings(Arrays.asList(CheckStateEnum.UNCHECKED.getMsg(), CheckStateEnum.CHECKING.getMsg(), CheckStateEnum.CHECKED.getMsg()));
// pullDowns.add(pullDown);
// 报告生成状态
// pullDown = new PullDown();
// pullDown.setFirstCol(10);
// pullDown.setLastCol(10);
// pullDown.setStrings(Arrays.asList(PlanReportStateEnum.REPORT_STATE_NOT_GENERATED.getMsg(), PlanReportStateEnum.REPORT_STATE_PARTIALLY_GENERATED.getMsg(), PlanReportStateEnum.REPORT_STATE_ALL_GENERATED.getMsg()));
// pullDowns.add(pullDown);
//检测结果
// pullDown = new PullDown();
// pullDown.setFirstCol(11);
// pullDown.setLastCol(11);
// pullDown.setStrings(Arrays.asList(CheckResultEnum.UNCHECKED.getMsg(), CheckResultEnum.ACCORD.getMsg(), CheckResultEnum.UNCHECKED.getMsg()));
// pullDowns.add(pullDown);
switch (scene) {
case PROVINCE_PLATFORM:
List<PullDown> provinceDevPullDownList = pqDevService.getProvinceDevPullDownList(9);

View File

@@ -10,9 +10,9 @@ public interface DetectionValidMessage {
String ID_NOT_BLANK = "id不能为空请检查id参数";
String ID_FORMAT_ERROR = "id格式错误请检查id参数";
String NAME_NOT_BLANK = "名称不能为空";
String ICD_NAME_FORMAT_ERROR = "名称格式错误只能包含字母、数字、中文、下划线、中划线、点号长度为1-50个字符";
String ICD_NAME_FORMAT_ERROR = "名称格式错误,只能包含字母、数字、中文、下划线、中划线、点号、空格、英文括号长度为1-32个字符";
String ICD_PATH_NOT_BLANK = "icd存储路径不能为空";
String ICD_PATH_FORMAT_ERROR = "ICD路径格式错误";
String ICD_PATH_FORMAT_ERROR = "ICD路径格式错误只能包含字母、数字、下划线、中划线、空格长度为1-50个字符";
String ICD_NOT_BLANK = "ICD不能为空";
String POWER_NOT_BLANK = "工作电源不能为空";
String VOLT_NOT_BLANK = "额定电压不能为空";
@@ -21,14 +21,14 @@ public interface DetectionValidMessage {
String DEV_CHNS_RANGE_ERROR = "通道数格式错误";
String INDEX_NOT_NULL = "index不能为空";
String VALUE_TYPE_NOT_BLANK = "脚本值类型不能为空";
String SCRIPT_NAME_FORMAT_ERROR = "脚本名称格式错误只能包含字母、数字、中文、下划线、中划线、点号长度为1-50个字符";
String SCRIPT_NAME_FORMAT_ERROR = "脚本名称格式错误,只能包含字母、数字、中文、下划线、中划线、点号、空格长度为1-32个字符";
String SCRIPT_VOLT_FORMAT_ERROR = "检测脚本额定电压格式错误请检查ratedVolt参数";
String SCRIPT_CURR_FORMAT_ERROR = "检测脚本额定电流格式错误请检查ratedCurr参数";
String PORT_RANGE_ERROR = "端口号范围错误请检查port参数";
String NAME_FORMAT_ERROR = "名称格式错误,请检查name参数";
String NAME_FORMAT_ERROR = "名称格式错误,只能包含字母、数字、中文、下划线、中划线、点号、空格长度为1-32个字符";
String PATTERN_NOT_BLANK = "模式不能为空请检查pattern参数";
String PATTERN_NOT_BLANK = "模式不能为空请检查patternId参数";
String DEV_TYPE_NOT_BLANK = "设备类型不能为空";
@@ -62,7 +62,7 @@ public interface DetectionValidMessage {
String RECHECK_NUM_FORMAT_ERROR = "检测次数格式错误请检查recheckNum参数";
String PATTERN_FORMAT_ERROR = "模式格式错误请检查pattern参数";
String PATTERN_FORMAT_ERROR = "模式格式错误请检查patternId参数";
String SOURCE_IDS_NOT_EMPTY = "检测源ID不能为空请检查sourceIds参数";
@@ -76,15 +76,15 @@ public interface DetectionValidMessage {
String PLAN_ID_FORMAT_ERROR = "检测计划ID格式错误请检查planId参数";
String STANDARD_TIME_FORMAT_ERROR = "标准推行时间格式错误请检查standardTime参数";
String STANDARD_TIME_FORMAT_ERROR = "标准推行年份格式错误请检查standardTime参数";
String SCRIPT_TYPE_NOT_BLANK = "检测脚本类型不能为空请检查scriptType参数";
String STANDARD_NAME_NOT_BLANK = "参照标准名称不能为空请检查standardName参数";
String STANDARD_NAME_NOT_BLANK = "标准号不能为空请检查standardName参数";
String STANDARD_NAME_FORMAT_ERROR = "参照标准名称格式错误请检查standardName参数";
String STANDARD_NAME_FORMAT_ERROR = "标准号格式错误只能包含字母、数字、中文、下划线、中划线、点号、空格、斜杠、反斜杠长度为1-32个字符";
String STANDARD_TIME_NOT_BLANK = "标准推行时间不能为空请检查standardTime参数";
String STANDARD_TIME_NOT_BLANK = "标准推行年份不能为空请检查standardTime参数";
String SCRIPT_TYPE_FORMAT_ERROR = "检测脚本类型格式错误请检查scriptType参数";
@@ -174,4 +174,11 @@ public interface DetectionValidMessage {
String SORT_NOT_NULL = "排序不能为空";
String PREINVESTMENT_PLAN_NOT_BLANK = "预投资计划不能为空";
String TIMECHECK_NOT_NULL = "是否做守时检测不能为空";
String CN_DEV_NAME_FORMAT_ERROR = "设备名称格式错误只能包含数字、中划线长度为1-32个字符";
String DEV_CREATE_ID_FORMAT_ERROR = "装置编号格式错误只能包含字母、数字、中文、下划线、中划线、空格长度为1-32位";
String DEV_TYPE_NAME_FORMAT_ERROR = "设备类型名称格式错误只能包含字母、数字、中文、下划线、中划线、点号、空格长度为1-32个字符";
String REPORT_NAME_NOT_BLANK = "报告模板不能为空";
String DATA_RULE_NOT_BLANK = "数据处理原则不能为空";
String ASSOCIATE_REPORT_NOT_NULL = "是否关联报告模板不能为空";
}

View File

@@ -26,6 +26,7 @@ public enum DetectionResponseEnum {
ICD_PATH_NAME_REPEAT("A02012", "icd名称重复"),
ERR_SYS_BOUND_NOT_DELETE("A02013", "误差体系已被计划所绑定,无法删除!"),
ERR_SYS_REPEAT("A02014", "已存在相同标准号、标准推行年份、适用设备等级的误差体系!"),
SCRIPT_NAME_REPEAT("A02015", "脚本名称重复"),
IMPORT_DATA_FAIL("A02040", "导入数据失败"),
@@ -46,7 +47,22 @@ public enum DetectionResponseEnum {
DEVICE_DIS_ERROR("A02055", "装置配置异常"),
DEVICE_DELETE("A02056", "设备无法删除,已绑定计划!"),
CREATE_DIRECTORY_FAILED("A02057", "创建目录失败"),
DELETE_DIRECTORY_FAILED("A02058", "删除目录失败");
DELETE_DIRECTORY_FAILED("A02058", "删除目录失败"),
CN_DEV_NAME_FORMAT_ERROR("A02059", "设备名称格式错误只能包含数字长度为1-32位"),
PROVINCE_DEV_NAME_FORMAT_ERROR("A02060", "设备名称格式错误只能包含字母、数字、下划线、中划线、空格长度为1-32位"),
IMPORT_REPORT_TEMPLATE_ERROR("A02061", "当关联报告模板为是时,报告模板不能为空"),
DEV_TYPE_NOT_EXIST("A02062", "设备类型不存在,请先添加设备类型"),
MANUFACTURER_NOT_EXIST("A02063", "该设备厂家不存在,请先在\"设备厂家\"字典中添加"),
PROTOCOL_NOT_EXIST("A02064", "该协议不存在,请先在\"通讯协议\"字典中添加"),
DELEGATE_NOT_EXIST("A02065", "该委托方不存在,请先在\"委托方\"字典中添加"),
PREINVESTMENT_PLAN_NOT_EXIST("A02066", "该预投计划不存在,请先在\"预投计划\"字典中添加"),
DATA_SOURCE_NOT_EXIST("A02067", "该数据源不存在,请先在\"数据源\"字典中添加"),
SCRIPT_NOT_EXIST("A02068", "该脚本不存在,请先添加该脚本"),
ERROR_SYSTEM_NOT_EXIST("A02069", "该误差体系不存在,请先添加该误差体系"),
DATA_RULE_NOT_EXIST("A02070", "该数据处理原则不存在,请先在\"数据处理原则\"字典中添加"),
REPORT_TEMPLATE_NOT_EXIST("A02071", "该报告模板不存在,请先添加该报告模板"),
LACK_REPORT_TEMPLATE_ID("A02072","当关联报告模板为\"\"时,报告模板不能为空" ),
NAME_OR_CREATEID_REPEAT("A02073","名称或装置编号重复" );
private final String code;

View File

@@ -3,6 +3,7 @@ package com.njcn.gather.report.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.response.HttpResult;
import com.njcn.common.utils.LogUtil;
@@ -21,7 +22,6 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
@@ -141,4 +141,19 @@ public class ReportController extends BaseController {
String methodDescribe = getMethodDescribe("listAllName");
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqReportService.listAllName(), methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
@PostMapping("/documented")
@ApiOperation("设备归档")
@ApiImplicitParam(name = "id", value = "设备id", required = true)
public HttpResult<Boolean> documented(@RequestBody List<String> ids) {
String methodDescribe = getMethodDescribe("documented");
LogUtil.njcnDebug(log, "{}设备id为{}", methodDescribe, ids);
boolean result = pqReportService.documented(ids);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
}
}

View File

@@ -3,6 +3,7 @@ package com.njcn.gather.report.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author hongawen
@@ -34,4 +35,5 @@ public class DevReportParam implements Serializable {
*/
private String devId;
private List<String> devIdList;
}

View File

@@ -0,0 +1,77 @@
package com.njcn.gather.report.pojo.constant;
import java.util.Arrays;
import java.util.List;
/**
* 电能质量指标常用的一些常量池
*
* @author hongawen
* @version 1.0
* @data 2025/3/27 11:11
*/
public interface PowerConstant {
/**
* 有三相的指标
*/
List<String> THREE_PHASE = Arrays.asList("V", "HV", "HI", "HP", "HSV", "HSI", "I", "P", "F");
/**
* T相指标
*/
List<String> T_PHASE = Arrays.asList("VOLTAGE", "IMBV", "IMBA", "FREQ");
/**
* 有次数的指标
*/
List<String> TIME = Arrays.asList("HV", "HI", "HP", "HSV", "HSI");
/**
* 没有次数的指标
*/
List<String> NO_TIME = Arrays.asList("V", "I", "P", "VOLTAGE", "IMBV", "IMBA", "F", "FREQ");
/**
* 有数据范围
*/
List<Integer> DATA_RANGE = Arrays.asList(1, 2);
/**
* 暂态符号
*/
String VOLTAGE = "VOLTAGE";
/**
* A相
*/
String PHASE_A = "A";
/**
* B相
*/
String PHASE_B = "B";
/**
* C相
*/
String PHASE_C = "C";
/**
* T相
*/
String PHASE_T = "T";
/**
* 电流单位
*/
String CURRENT_UNIT = "A";
/**
* 电压单位
*/
String VOLTAGE_UNIT = "V";
}

View File

@@ -0,0 +1,22 @@
package com.njcn.gather.report.pojo.constant;
/**
*
* 报告相关的一些常量
*
* @author hongawen
* @version 1.0
* @data 2025/4/3 13:44
*/
public interface ReportConstant {
/**
* docx文档后缀
*/
String DOCX = ".docx";
/**
* 报告模板中书签的起始标识
*/
String BOOKMARK_START = "#{";
}

View File

@@ -0,0 +1,43 @@
package com.njcn.gather.report.pojo.enums;
import lombok.Getter;
/**
* 影响量枚举
* @author hongawen
* @version 1.0
* @data 2025/3/27 21:07
*/
@Getter
public enum AffectEnum {
BASE("base", "额定工作条件下的检测"),
VOL("vol", "电压对XX测量的影响"),
FREQ("freq", "频率对XX测量的影响"),
HARM("harm", "谐波对XX测量的影响");
private String key;
private String desc;
AffectEnum(String key, String desc) {
this.key = key;
this.desc = desc;
}
/**
* 根据key找到适配的枚举
*
* @param key 枚举的key
* @return 匹配的枚举实例如果没有找到则返回null
*/
public static AffectEnum getByKey(String key) {
for (AffectEnum affectEnum : AffectEnum.values()) {
if (affectEnum.getKey().equalsIgnoreCase(key)) {
return affectEnum;
}
}
return null;
}
}

View File

@@ -0,0 +1,45 @@
package com.njcn.gather.report.pojo.enums;
import lombok.Getter;
/**
*
* 本枚举用于记录模板中关键字的含义
* 比如 ${manufacturer} 对应的设备厂家
*
* @author hongawen
* @version 1.0
* @data 2025/3/24 14:34
*
* */
@Getter
public enum BaseReportKeyEnum {
DEV_TYPE("devType","设备型号、规格"),
DEV_CODE("createId","装置编号"),
POWER("power","工作电源"),
DEV_CURR("devCurr","额定电流"),
DEV_VOLT("devVolt","额定电压"),
COUNT("count","通道数"),
MANUFACTURER("manufacturer","设备厂家、制造厂商"),
SAMPLE_ID("sampleId","样品编号"),
ARRIVED_DATE("arrivedDate","收样日期"),
TEST_DATE("testDate","检测日期"),
INSPECTOR("inspector","检测员"),
YEAR("year","年份"),
MONTH("month","月份"),
DAY("day",""),
YEAR_MONTH_DAY("year-month-day","年-月-日"),
TEMPERATURE("temp","温度"),
HUMIDITY("hum","相对湿度"),
DELEGATE("delegate","委托方");
private String key;
private String desc;
BaseReportKeyEnum(String key, String desc) {
this.key = key;
this.desc = desc;
}
}

View File

@@ -0,0 +1,56 @@
package com.njcn.gather.report.pojo.enums;
/**
* @author hongawen
* @version 1.0
* @data 2025/5/22 9:46
*/
import lombok.Getter;
/**
* 统计文档锚点类型
*
* @author hongawen
* @version 1.0
* @data 2025/3/24 18:42
*/
@Getter
public enum BookmarkEnum {
DATA_LINE("data_line", "准确度数据展示区域,以测试回路维度展示", 1),
DATA_SCRIPT("data_script", "准确度数据展示区域,以检测项维度展示", 1),
TEST_RESULT_DEV("testResult_dev", "检测结论,仅有设备结论", 2),
TEST_RESULT_LINE("testResult_line", "检测结论,仅有回路结论", 2),
TEST_RESULT_DETAIL("testResult_detail", "检测结论,包含回路、设备结论", 2),
CATALOG("catalog", "目录信息", 3);
private String key;
private String desc;
private Integer sort;
BookmarkEnum(String key, String desc, Integer sort) {
this.key = key;
this.desc = desc;
this.sort = sort;
}
/**
* 根据key找到适配的枚举
*
* @param key 枚举的key
* @return 匹配的枚举实例如果没有找到则返回null
*/
public static BookmarkEnum getByKey(String key) {
for (BookmarkEnum bookmarkEnum : BookmarkEnum.values()) {
if (bookmarkEnum.getKey().equalsIgnoreCase(key)) {
return bookmarkEnum;
}
}
return null;
}
}

View File

@@ -0,0 +1,50 @@
package com.njcn.gather.report.pojo.enums;
import lombok.Getter;
/**
* 统计文档锚点类型
*
* @author hongawen
* @version 1.0
* @data 2025/3/24 18:42
*/
@Getter
public enum DocAnchorEnum {
DATA_LINE("#{data:line}", "准确度数据展示区域,以测试回路维度展示", 1),
DATA_SCRIPT("#{data:script}", "准确度数据展示区域,以检测项维度展示", 1),
TEST_RESULT_DEV("#{testResult:dev}", "检测结论,仅有设备结论", 2),
TEST_RESULT_LINE("#{testResult:line}", "检测结论,仅有回路结论", 2),
TEST_RESULT_DETAIL("#{testResult:detail}", "检测结论,包含回路、设备结论", 2),
CATALOG("#{catalog}", "目录信息", 3);
private String key;
private String desc;
private Integer sort;
DocAnchorEnum(String key, String desc, Integer sort) {
this.key = key;
this.desc = desc;
this.sort = sort;
}
/**
* 根据key找到适配的枚举
*
* @param key 枚举的key
* @return 匹配的枚举实例如果没有找到则返回null
*/
public static DocAnchorEnum getByKey(String key) {
for (DocAnchorEnum docAnchorEnum : DocAnchorEnum.values()) {
if (docAnchorEnum.getKey().equalsIgnoreCase(key)) {
return docAnchorEnum;
}
}
return null;
}
}

View File

@@ -0,0 +1,70 @@
package com.njcn.gather.report.pojo.enums;
import lombok.Getter;
/**
* 检测项模版枚举
* @author hongawen
* @version 1.0
* @data 2025/3/27 10:24
*/
@Getter
public enum ItemReportKeyEnum {
NAME("name", "检测项,比如:频率"),
NAME_DETAIL("nameDetail", "检测项详细,比如:频率测量准确度"),
ERROR_SCOPE("errorScope", "误差范围,注:在段落中时需加上(),表格中无需添加"),
ERROR_SCOPE_MAG("errorScopeMag", "特征幅值:误差范围"),
ERROR_SCOPE_DUR("errorScopeDur", "持续时间:误差范围"),
SCRIPT_DETAIL("scriptDetail", "脚本输出明细。比如基波电压UN=57.74Vf=50Hz谐波含有率Uh=10%UN=5.774V"),
TIME("time", "次数"),
STANDARD("standard", "标准值"),
STANDARD_A("standardA", "A相标准值"),
STANDARD_B("standardB", "B相标准值"),
STANDARD_C("standardC", "C相标准值"),
STANDARD_MAG("standardMag", "特征幅值的标准值"),
STANDARD_DUR("standardDur_ms", "持续时间的标准值"),
TEST("test", "测试值"),
TEST_MAG("testMag", "特征幅值测试值"),
TEST_DUR("testDur_ms", "持续时间测试值"),
TEST_A("testA", "A相测试值"),
TEST_B("testB", "B相测试值"),
TEST_C("testC", "C相测试值"),
ERROR("error", "误差"),
ERROR_MAG("errorMag", "特征幅值误差"),
ERROR_DUR("errorDur_ms", "持续时间误差"),
ERROR_A("errorA", "A相误差"),
ERROR_B("errorB", "B相误差"),
ERROR_C("errorC", "C相误差"),
RESULT("result", "结论 比如:合格/不合格"),
RESULT_A("resultA", "结论 比如:合格/不合格"),
RESULT_B("resultB", "结论 比如:合格/不合格"),
RESULT_C("resultC", "结论 比如:合格/不合格"),
RESULT_MAG("resultMag", "特征幅值结论 比如:合格/不合格"),
RESULT_DUR("resultDur", "持续时间结论 比如:合格/不合格");
private String key;
private String desc;
ItemReportKeyEnum(String key, String desc) {
this.key = key;
this.desc = desc;
}
/**
* 根据key找到适配的枚举
*
* @param key 枚举的key
* @return 匹配的枚举实例如果没有找到则返回null
*/
public static ItemReportKeyEnum getByKey(String key) {
for (ItemReportKeyEnum itemReportKetEnum : ItemReportKeyEnum.values()) {
if (itemReportKetEnum.getKey().equalsIgnoreCase(key)) {
return itemReportKetEnum;
}
}
return null;
}
}

View File

@@ -0,0 +1,52 @@
package com.njcn.gather.report.pojo.enums;
import lombok.Getter;
/**
* 电能质量测试大项枚举
* @author hongawen
* @version 1.0
* @data 2025/3/27 18:29
*/
@Getter
public enum PowerIndexEnum {
UNKNOWN("UNKNOWN", "未知指标"),
FREQ("FREQ", "频率"),
V("V", "电压"),
I("I", "电流"),
IMBV("IMBV", "负序电压不平衡度"),
IMBA("IMBA", "负序电流不平衡度"),
F("F", "短时电压闪变"),
HP("HP", "谐波有功功率"),
HV("HV", "谐波电压"),
HI("HI", "谐波电流"),
HSV("HSV", "间谐波电压"),
HSI("HSI", "间谐波电流"),
VOLTAGE("VOLTAGE", "电压暂降、暂升及短时中断");
private String key;
private String desc;
PowerIndexEnum(String key, String desc) {
this.key = key;
this.desc = desc;
}
/**
* 根据key找到适配的枚举
*
* @param key 枚举的key
* @return 匹配的枚举实例如果没有找到则返回null
*/
public static PowerIndexEnum getByKey(String key) {
for (PowerIndexEnum powerIndexEnum : PowerIndexEnum.values()) {
if (powerIndexEnum.getKey().equalsIgnoreCase(key)) {
return powerIndexEnum;
}
}
return null;
}
}

View File

@@ -20,9 +20,11 @@ public enum ReportResponseEnum {
REPORT_TEMPLATE_NOT_EXIST("A012009", "报告模板缺失,请联系管理员!"),
NO_CHECK_DATA("A012010", "没有检测数据,无法生成报告!"),
FILE_RENAME_FAILED("A012011", "文件重命名失败"),
REPORT_NAME_PATTERN_ERROR("A012012","报告名称格式错误,可包含中文、字母、数字、中划线,长度不能超过50个字符"),
REPORT_VERSION_PATTERN_ERROR("A012013","报告版本号格式错误,可包含中文、字母、数字、中划线点号,长度不能超过50个字符"),
FILE_SIZE_ERROR("A012014","文件大小不能超过5MB" );
REPORT_NAME_PATTERN_ERROR("A012012","报告名称格式错误,可包含中文、字母、数字、中划线、点号、空格,长度不能超过32个字符"),
REPORT_VERSION_PATTERN_ERROR("A012013","报告版本号格式错误,可包含中文、字母、数字、中划线点号、空格,长度不能超过32个字符"),
FILE_SIZE_ERROR("A012014","文件大小不能超过5MB" ),
GENERATE_REPORT_ERROR("A012015","生成报告失败"),
;
private String code;
private String message;

View File

@@ -0,0 +1,40 @@
package com.njcn.gather.report.pojo.result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
*
* 测试大项的检测结果
*
* @author hongawen
* @version 1.0
* @data 2025/4/7 20:17
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SingleTestResult implements Serializable {
/**
* 大项名称
*/
private String scriptCode;
/**
* 是否合格
*/
private boolean qualified;
/**
* 细节集合
*/
private Map<String, List<Map<String, List<Map<String, String>>>>> detail;
}

View File

@@ -0,0 +1,39 @@
package com.njcn.gather.report.pojo.vo;
import com.njcn.gather.report.pojo.enums.DocAnchorEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author hongawen
* @version 1.0
* @data 2025/4/7 15:36
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bookmark implements Serializable,Comparable<Bookmark>{
/**
* 在文档中段落的索引
*/
private Integer index;
/**
* 对应枚举
*/
private DocAnchorEnum docAnchorEnum;
/**
* 根据书签的排序字段进行排序
* @param bookmark the object to be compared.
*/
@Override
public int compareTo(Bookmark bookmark) {
return Integer.compare(this.docAnchorEnum.getSort(), bookmark.docAnchorEnum.getSort());
}
}

View File

@@ -9,7 +9,6 @@ import com.njcn.gather.report.pojo.vo.PqReportVO;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* @author makejava
@@ -66,4 +65,12 @@ public interface IPqReportService extends IService<PqReport> {
void generateReport(DevReportParam devReportParam);
void downloadReport(DevReportParam devReportParam, HttpServletResponse response);
/**
* 设备归档操作
*
* @param id 设备id
* @return 归档成功返回true否则返回false
*/
boolean documented(List<String> id);
}

View File

@@ -0,0 +1,293 @@
package com.njcn.gather.report.utils;
import com.njcn.gather.report.pojo.enums.BookmarkEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;
import javax.xml.bind.JAXBElement;
import java.util.*;
/**
* 递归查找所有书签,并在书签处插入内容
*/
public class BookmarkUtil {
/**
* 书签信息
*/
public static class BookmarkInfo {
public CTBookmark bookmark;
public P parentParagraph;
public ContentAccessor parentContainer;
}
/**
* 递归查找所有书签
*/
public static List<BookmarkInfo> findAllBookmarks(ContentAccessor contentAccessor) {
List<BookmarkInfo> result = new ArrayList<>();
for (Object obj : contentAccessor.getContent()) {
Object realObj = (obj instanceof JAXBElement) ? ((JAXBElement<?>) obj).getValue() : obj;
if (realObj instanceof P) {
P p = (P) realObj;
for (Object o2 : p.getContent()) {
Object realO2 = (o2 instanceof JAXBElement) ? ((JAXBElement<?>) o2).getValue() : o2;
if (realO2 instanceof CTBookmark) {
BookmarkInfo info = new BookmarkInfo();
info.bookmark = (CTBookmark) realO2;
info.parentParagraph = p;
info.parentContainer = contentAccessor;
result.add(info);
}
}
} else if (realObj instanceof ContentAccessor) {
result.addAll(findAllBookmarks((ContentAccessor) realObj));
}
}
return result;
}
/**
* 在书签后插入段落
*/
public static void insertParagraphsAfter(BookmarkInfo info, P paragraph) {
List<Object> parentContent = info.parentContainer.getContent();
int idx = parentContent.indexOf(info.parentParagraph);
parentContent.add(idx + 1, paragraph);
}
/**
* 在书签后插入表格
*/
public static void insertTableAfter(BookmarkInfo info, Tbl table) {
List<Object> parentContent = info.parentContainer.getContent();
int idx = parentContent.indexOf(info.parentParagraph);
parentContent.add(idx + 1, table);
}
/**
* 在书签后插入元素,可能是段落、表格、图片、书签等
*/
public static void insertElement(BookmarkInfo info, List<Object> elements) {
List<Object> parentContent = info.parentContainer.getContent();
int idx = parentContent.indexOf(info.parentParagraph);
// 遍历元素,如果是通道回路这种大标题需要新起一个空的文档页
for (int i = 0; i < elements.size(); i++) {
Object element = elements.get(i);
if (element instanceof P) {
P p = (P) element;
String textFromP = Docx4jUtil.getTextFromP(p);
if (textFromP.contains("测量回路")) {
if (!textFromP.contains("1")) {
// 另起一页
P pagePara = Docx4jUtil.getPageBreak();
idx = idx + 1;
parentContent.add(idx, pagePara);
}
idx = idx + 1;
parentContent.add(idx, p);
} else if (textFromP.startsWith(PowerIndexEnum.IMBV.getDesc())
|| textFromP.startsWith(PowerIndexEnum.HV.getDesc())
|| textFromP.startsWith(PowerIndexEnum.HI.getDesc())
) {
// 另起一页
P pagePara = Docx4jUtil.getPageBreak();
idx = idx + 1;
parentContent.add(idx, pagePara);
idx = idx + 1;
parentContent.add(idx, element);
}else if(textFromP.startsWith("基波电流幅值5.000A基波频率50.0Hz,各次间谐波电流含有率均为3.0%。")){
idx = idx + 1;
parentContent.add(idx, element);
P pagePara = Docx4jUtil.getPageBreak();
idx = idx + 1;
parentContent.add(idx, pagePara);
} else {
idx = idx + 1;
parentContent.add(idx, element);
}
} else {
idx = idx + 1;
parentContent.add(idx, element);
}
}
}
/**
* 删除文档中的空白页
* @param docx 要处理的Word文档
*/
public static void removeBlankPages(MainDocumentPart mainDocumentPart) {
// 获取文档主体
Document document = mainDocumentPart.getJaxbElement();
Body body = document.getBody();
// 获取所有段落
List<Object> paragraphs = body.getContent();
// 用于标记是否在空白页中
boolean inBlankPage = false;
// 用于存储要删除的段落
List<P> paragraphsToRemove = new ArrayList<>();
for (Object paragraph : paragraphs) {
if (paragraph instanceof P){
P paragraphtemp = (P) paragraph;
// 检查段落是否为空
boolean isEmpty = isParagraphEmpty(paragraphtemp);
if (isEmpty) {
if (!inBlankPage) {
inBlankPage = true;
}
paragraphsToRemove.add(paragraphtemp);
} else {
inBlankPage = false;
}
}
}
// 删除空白段落
for (P paragraph : paragraphsToRemove) {
body.getContent().remove(paragraph);
}
}
/**
* 检查段落是否为空
* @param paragraph 要检查的段落
* @return 如果段落为空返回true否则返回false
*/
private static boolean isParagraphEmpty(P paragraph) {
// 检查段落是否包含分节符
if (paragraph.getPPr() != null && paragraph.getPPr().getSectPr() != null) {
return false;
}
// 检查段落中的文本内容
for (Object obj : paragraph.getContent()) {
if (obj instanceof R) {
R run = (R) obj;
// 在3.3.4版本中使用getContent()获取文本内容
for (Object runContent : run.getContent()) {
if (runContent instanceof Text) {
Text text = (Text) runContent;
if (text.getValue() != null && !text.getValue().trim().isEmpty()) {
return false;
}
}
}
}
}
return true;
}
/**
* 在插入前检查目标位置是否有分页符
*
* @param position 目标位置
* @return 是否包含分页符
*/
private static boolean hasPageBreak(Object position) {
if (position instanceof P) {
P paragraph = (P) position;
for (Object run : paragraph.getContent()) {
if (run instanceof R) {
R r = (R) run;
for (Object element : r.getContent()) {
if (element instanceof Br && ((Br) element).getType() != null
&& ((Br) element).getType().equals("page")) {
return true;
}
}
}
}
return false;
}
return false;
}
/**
* 删除书签
*
* @param bookmarkInfo 书签信息
*/
public static void removeBookmark(BookmarkUtil.BookmarkInfo bookmarkInfo) {
try {
// 获取书签所在的段落
P paragraph = bookmarkInfo.parentParagraph;
// 遍历段落内容,找到并删除书签开始和结束标记
List<Object> paragraphContent = new ArrayList<>(paragraph.getContent());
for (Object obj : paragraphContent) {
if (obj instanceof JAXBElement) {
JAXBElement<?> element = (JAXBElement<?>) obj;
Object value = element.getValue();
// 删除书签开始标记
if (value instanceof CTBookmark) {
paragraph.getContent().remove(obj);
}
// 删除书签结束标记
else if (value instanceof CTMarkupRange) {
paragraph.getContent().remove(obj);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 使用 ObjectFactory 创建表格
*
* @param factory ObjectFactory 实例
* @param data 二维数组,表格内容
* @return Tbl 表格对象
*/
public static Tbl createTable(ObjectFactory factory, String[][] data) {
Tbl table = factory.createTbl();
for (String[] rowData : data) {
Tr row = factory.createTr();
for (String cellData : rowData) {
Tc cell = factory.createTc();
P para = factory.createP();
R run = factory.createR();
Text text = factory.createText();
text.setValue(cellData);
run.getContent().add(text);
para.getContent().add(run);
cell.getContent().add(para);
row.getContent().add(cell);
}
table.getContent().add(row);
}
return table;
}
/**
* 获取指定标签的标签信息
*
* @param key 标签名
* @param bookmarks 所有标签信息
*/
public static BookmarkInfo getBookmarkInfo(String key, List<BookmarkInfo> bookmarks) {
BookmarkUtil.BookmarkInfo bookmarkInfo = null;
for (BookmarkUtil.BookmarkInfo info : bookmarks) {
String name = info.bookmark.getName();
if (key.equalsIgnoreCase(name)) {
bookmarkInfo = info;
}
}
return bookmarkInfo;
}
}

View File

@@ -0,0 +1,44 @@
package com.njcn.gather.report.utils;
/**
* @author hongawen
* @version 1.0
* @data 2025/3/25 19:37
*/
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;
import java.io.File;
import java.math.BigInteger;
import java.util.List;
public class Docx4jInsertParagraph {
public static void main(String[] args) throws Exception {
// 加载现有的 Word 文档
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(new File("C:\\Users\\hongawen\\Desktop\\base_template.docx"));
MainDocumentPart documentPart = wordPackage.getMainDocumentPart();
// 获取文档中的所有段落
List<Object> paragraphs = documentPart.getContent();
// 在中间插入一个新段落
int insertIndex = paragraphs.size() / 2;
P newParagraph = createParagraph("This is a new paragraph inserted in the middle.");
paragraphs.add(insertIndex, newParagraph);
// 保存修改后的文档
wordPackage.save(new File("example_modified.docx"));
}
private static P createParagraph(String text) {
ObjectFactory factory = new ObjectFactory();
P paragraph = factory.createP();
R run = factory.createR();
Text t = factory.createText();
t.setValue(text);
run.getContent().add(t);
paragraph.getContent().add(run);
return paragraph;
}
}

View File

@@ -0,0 +1,633 @@
package com.njcn.gather.report.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.njcn.gather.report.pojo.constant.ReportConstant;
import com.njcn.gather.report.pojo.enums.DocAnchorEnum;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;
import javax.xml.bind.JAXBElement;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author hongawen
* @version 1.0
* @data 2025/3/26 13:47
*/
public class Docx4jUtil {
/**
* 创建标题
*
* @param factory 工厂
* @param paragraph 段落容器
* @param content 标题内容
* @param fontSize 字体大小
* @param isBold 是否加粗
*/
public static void createTitle(ObjectFactory factory, P paragraph, String content, int fontSize, boolean isBold) {
R run = factory.createR();
Text text = factory.createText();
text.setValue(content);
// 创建运行属性
RPr rPr = factory.createRPr();
// 设置字体
RFonts fonts = factory.createRFonts();
fonts.setAscii("Arial");
// 宋体
fonts.setEastAsia("SimSun");
rPr.setRFonts(fonts);
// 设置字号
HpsMeasure size = new HpsMeasure();
// 12号字=24
size.setVal(new BigInteger("" + fontSize));
rPr.setSz(size);
rPr.setSzCs(size);
// 设置粗体
if (isBold) {
BooleanDefaultTrue b = new BooleanDefaultTrue();
rPr.setB(b);
}
run.setRPr(rPr);
run.getContent().add(text);
// 换行
// Br br = factory.createBr();
// run.getContent().add(br);
paragraph.getContent().add(run);
}
/**
* 提取Heading 5及其子内容
*
* @param allContent 文档内所有内容
*/
public static List<HeadingContent> extractHeading5Contents(List<Object> allContent) {
List<HeadingContent> result = new ArrayList<>();
boolean inHeading5Section = false;
HeadingContent currentHeading = null;
for (Object obj : allContent) {
if (obj instanceof P) {
P paragraph = (P) obj;
if (isHeading5(paragraph)) {
// 发现新的Heading 5保存前一个并创建新的
if (currentHeading != null) {
result.add(currentHeading);
}
currentHeading = new HeadingContent();
currentHeading.setHeadingText(getTextFromP(paragraph));
inHeading5Section = true;
} else if (inHeading5Section) {
// 当前内容属于Heading 5的子内容
currentHeading.addSubContent(paragraph);
}
} else if (obj instanceof JAXBElement && inHeading5Section) {
// 表格属于当前Heading 5的子内容
JAXBElement<?> jaxbElement = (JAXBElement<?>) obj;
if (jaxbElement.getValue() instanceof Tbl) {
currentHeading.addSubContent(obj);
}
} else if (isHigherLevelHeading(obj)) {
// 遇到更高级别的标题结束当前Heading 5的收集
if (currentHeading != null) {
result.add(currentHeading);
currentHeading = null;
}
inHeading5Section = false;
}
}
// 添加最后一个Heading 5
if (currentHeading != null) {
result.add(currentHeading);
}
return result;
}
// 判断段落是否为Heading 5
private static boolean isHeading5(P paragraph) {
PPr ppr = paragraph.getPPr();
if (ppr != null) {
PPrBase.PStyle pStyle = ppr.getPStyle();
if (pStyle != null && "5".equals(pStyle.getVal())) {
return true;
}
}
return false;
}
// 判断是否为更高级别的标题1-4
private static boolean isHigherLevelHeading(Object obj) {
if (obj instanceof P) {
PPr ppr = ((P) obj).getPPr();
if (ppr != null) {
PPrBase.PStyle pStyle = ppr.getPStyle();
if (pStyle != null) {
String style = pStyle.getVal();
return style != null && style.matches("[1-4]");
}
}
}
return false;
}
/**
* 判断表格是否横向
*
* @param obj row
*/
public static boolean judgeTableCross(Object obj) {
Tr row = (Tr) obj;
List<Object> content = row.getContent();
// 取最后一个单元格,判断是否包含汉字,有汉字就是横向的
Object cellObject = content.get(content.size() - 1);
JAXBElement<Tc> cellElement = (JAXBElement<Tc>) cellObject;
Tc cell = cellElement.getValue();
String text = getTextFromCell(cell);
if (StrUtil.isBlank(text)) {
return true;
}
// 遍历字符串中的每个字符存在中文就认为是横向的理论上设置的key全是英文
for (char c : text.toCharArray()) {
// 检查字符是否在中文Unicode范围内
if (c >= '\u4E00' && c <= '\u9FFF') {
// 发现中文字符,返回 false
return true;
}
}
return false;
}
/**
* 读取cell内的文本内容
*/
public static String getTextFromCell(Tc cell) {
List<Object> cellContent = cell.getContent();
StringBuilder cellText = new StringBuilder();
for (Object content : cellContent) {
if (content instanceof P) {
P paragraph = (P) content;
cellText.append(getTextFromP(paragraph));
}
}
return cellText.toString();
}
/**
* 从段落中提取纯文本
*
* @param paragraph 段落
* @return 段落内容
*/
public static String getTextFromP(P paragraph) {
StringBuilder textContent = new StringBuilder();
for (Object runObj : paragraph.getContent()) {
if (runObj instanceof R) {
R run = (R) runObj;
for (Object textObj : run.getContent()) {
if (textObj instanceof Text) {
textContent.append(((Text) textObj).getValue());
} else if (textObj instanceof JAXBElement) {
JAXBElement<?> jaxbElement = (JAXBElement<?>) textObj;
if (jaxbElement.getValue() instanceof Text) {
Text temp = (Text) jaxbElement.getValue();
textContent.append(temp.getValue());
}
}
}
}
}
return textContent.toString().trim();
}
/**
* 获取段落的样式
*
* @param paragraph 段落
*/
public static RPr getTcPrFromParagraph(P paragraph) {
// 1. 获取段落中的所有内容
List<Object> content = paragraph.getContent();
// 2. 清空原有内容但保留第一个Run的样式
RPr preservedRPr = null;
if (!content.isEmpty()) {
Object firstObj = content.get(0);
if (firstObj instanceof R) {
// 保存第一个Run的样式
preservedRPr = ((R) firstObj).getRPr();
}
}
return preservedRPr;
}
/**
* 段落中添加内容
*/
public static void addPContent(ObjectFactory factory, P paragraph, String content, RPr rPr,PPr ppr) {
R run = factory.createR();
Text text = factory.createText();
text.setValue(content);
run.setRPr(rPr);
run.getContent().add(text);
paragraph.getContent().add(run);
paragraph.setPPr(ppr);
}
/**
* 创建N个换行符
*/
public static void addBr(ObjectFactory factory, P paragraph, int n) {
R run = factory.createR();
for (int i = 0; i < n; i++) {
// 换行
Br br = factory.createBr();
run.getContent().add(br);
}
paragraph.getContent().add(run);
}
/**
* 根据表格行获取需要填的值的key
*/
public static List<String> getTableKey(Tr row) {
List<String> keys = new ArrayList<>();
// 横向的,最后一行为需要填充的数据后,前面的均是表头
// 遍历获取出该row的所有key
List<Object> content = row.getContent();
for (Object cellObject : content) {
if (cellObject instanceof JAXBElement) {
JAXBElement<Tc> cellElement = (JAXBElement<Tc>) cellObject;
Tc cell = cellElement.getValue();
keys.add(Docx4jUtil.getTextFromCell(cell));
}
}
return keys;
}
/**
* 获取内容中需要填充的keys
*
* @param tempContent 标题下配置的内容
*/
public static List<List<String>> getFillKeys(List<HeadingContent> tempContent) {
List<List<String>> keys = new ArrayList<>();
List<String> pKeys = new ArrayList<>();
List<String> tableKeys = new ArrayList<>();
if (CollUtil.isNotEmpty(tempContent)) {
// 读取该表下模板里面的内容,这整个内容需要跟随误差范围循环的,确保内容的数据比较用的一个误差范围
Docx4jUtil.HeadingContent headingContent = tempContent.get(0);
for (Object object : headingContent.getSubContent()) {
if (object instanceof P) {
// 如果是段落,渲染段落内容
P paragraph = (P) object;
String textFromP = getTextFromP(paragraph);
String[] splitKeys = textFromP.split(StrPool.DASHED);
pKeys.addAll(Arrays.asList(splitKeys));
} else if (object instanceof JAXBElement) {
// 复制表格元素
JAXBElement<Tbl> copiedTableElement = (JAXBElement<Tbl>) object;
// 解析表格并插入对应数据,最关键的是得知道表格是横向还是纵向以及表头占了几行
Tbl tbl = copiedTableElement.getValue();
// 获取表格的行
List<Object> rows = tbl.getContent();
boolean isRow = Docx4jUtil.judgeTableCross(rows.get(0));
if (isRow) {
// 获取需要填的值的key
List<String> cellKeys = Docx4jUtil.getTableKey((Tr) rows.get(rows.size() - 1));
tableKeys.addAll(cellKeys);
} else {
// 纵向表格暂不考虑
}
}
}
}
keys.add(pKeys);
keys.add(tableKeys);
return keys;
}
/**
* 根据已知信息创建新航
*
* @param factory 工厂
* @param valueMap 数据
* @param tableKeys keys
* @param trPr 行样式
* @param tcPr 单元格样式
*/
public static Tr createCustomRow(ObjectFactory factory, Map<String, String> valueMap, List<String> tableKeys, TrPr trPr, TcPr tcPr, boolean centerFlag) {
Tr row = factory.createTr();
for (String tableKey : tableKeys) {
Tc cell = factory.createTc();
P paragraph = factory.createP();
R run = factory.createR();
String value = valueMap.get(tableKey);
Text text = factory.createText();
text.setValue(value);
run.getContent().add(text);
paragraph.getContent().add(run);
// 字体
// 设置字体
RPr rPr = factory.createRPr();
RFonts rFonts = factory.createRFonts();
if (containsChinese(value)) {
rFonts.setEastAsia("宋体");
rFonts.setAscii("宋体");
rFonts.setHAnsi("宋体");
} else {
rFonts.setEastAsia("Arial");
rFonts.setAscii("Arial");
rFonts.setHAnsi("Arial");
}
rPr.setRFonts(rFonts);
// 设置段落居中
if (centerFlag) {
PPr pPr = factory.createPPr();
Jc jc = factory.createJc();
jc.setVal(JcEnumeration.CENTER);
pPr.setJc(jc);
paragraph.setPPr(pPr);
}
if (value.equals("不合格")) {
Color color = factory.createColor();
// 红色
color.setVal("FF0000");
rPr.setColor(color);
run.setRPr(rPr);
}
HpsMeasure sz = factory.createHpsMeasure();
// 10号字体 = 20 half-points
sz.setVal(new BigInteger("20"));
rPr.setSz(sz);
cell.getContent().add(paragraph);
cell.setTcPr(tcPr);
row.getContent().add(cell);
row.setTrPr(trPr);
}
return row;
}
/**
* 判断字符串是否包含中文
* @param str 需要判断的字符串
* @return 是否包含中文
*/
private static boolean containsChinese(String str) {
if (str == null) {
return false;
}
for (char c : str.toCharArray()) {
if (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
return true;
}
}
return false;
}
/**
* 根据已知信息创建新行
*
* @param factory 工厂
* @param cellValues 数据
* @param ascFontStyle 西文字体
* @param eastFontStyle 中文字体
* @param size 字体大小
* @param boldFlag 是否加粗
* @param centerFlag 是否居中
*/
public static Tr createCustomRow(ObjectFactory factory, List<String> cellValues, String ascFontStyle, String eastFontStyle, Integer size, boolean boldFlag, List<Integer> centerFlag) {
Tr row = factory.createTr();
for (int i = 0; i < cellValues.size(); i++) {
String value = cellValues.get(i);
Tc cell = factory.createTc();
P paragraph = factory.createP();
R run = factory.createR();
Text text = factory.createText();
text.setValue(value);
run.getContent().add(text);
paragraph.getContent().add(run);
// 设置段落居中
if (!centerFlag.contains(i)) {
PPr pPr = factory.createPPr();
Jc jc = factory.createJc();
jc.setVal(JcEnumeration.CENTER);
pPr.setJc(jc);
paragraph.setPPr(pPr);
}
RPr rPr = factory.createRPr();
if (value.equals("不合格")) {
Color color = factory.createColor();
// 红色
color.setVal("FF0000");
rPr.setColor(color);
}
if (boldFlag) {
BooleanDefaultTrue bold = factory.createBooleanDefaultTrue();
rPr.setB(bold);
}
RFonts fonts = factory.createRFonts();
// 西文字体
fonts.setAscii(ascFontStyle);
// 中文字体
fonts.setEastAsia(eastFontStyle);
rPr.setRFonts(fonts);
HpsMeasure fontSize = factory.createHpsMeasure();
fontSize.setVal(BigInteger.valueOf(size));
// 西文字号
rPr.setSz(fontSize);
// 中文字号
rPr.setSzCs(fontSize);
run.setRPr(rPr);
cell.getContent().add(paragraph);
// 设置单元格边距
TcPr cellProperties = factory.createTcPr();
cell.setTcPr(cellProperties);
// 设置单元格上下边距(单位:缇)
TcMar mar = factory.createTcMar();
TblWidth top = factory.createTblWidth();
top.setW(BigInteger.valueOf(100));
mar.setTop(top);
TblWidth bottom = factory.createTblWidth();
bottom.setW(BigInteger.valueOf(100));
mar.setBottom(bottom);
cellProperties.setTcMar(mar);
row.getContent().add(cell);
}
return row;
}
public static JAXBElement<Tbl> deepCopyTbl(JAXBElement<Tbl> original) throws Exception {
// 使用 docx4j 的 XmlUtils 进行深拷贝
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
Tbl clonedTbl = (Tbl) XmlUtils.deepCopy(original.getValue());
// 重新包装为 JAXBElement
return new JAXBElement<Tbl>(
original.getName(),
original.getDeclaredType(),
original.getScope(),
clonedTbl
);
}
// 存储Heading 5及其子内容的辅助类
public static class HeadingContent {
private String headingText;
private List<Object> subContent = new ArrayList<>();
public void setHeadingText(String text) {
this.headingText = text;
}
public String getHeadingText() {
return headingText;
}
public void addSubContent(Object obj) {
subContent.add(obj);
}
public List<Object> getSubContent() {
return subContent;
}
}
/**
* 获取指定书签在文档段落中的位置索引
*
* @param documentPart 主文档部分
* @param bookmarkName 书签名称
* @return 段落索引,找不到返回 -1
*/
public static int getParagraphPosition(MainDocumentPart documentPart, String bookmarkName) {
List<Object> content = documentPart.getContent();
for (int i = 0; i < content.size(); i++) {
Object obj = content.get(i);
// 只处理段落
if (obj instanceof P) {
P paragraph = (P) obj;
// 提取段落纯文本
String text = getTextFromP(paragraph).trim();
if (text.startsWith("#{") && text.endsWith("}")) {
// 提取书签名
String name = text.substring(2, text.length() - 1);
if (name.equals(bookmarkName)) {
// 返回段落索引
return i;
}
}
}
}
// 找不到返回 -1
return -1;
}
/**
* 获取段落在文档中的位置
*/
public static int getParagraphPosition(MainDocumentPart baseDocumentPart, DocAnchorEnum docAnchorEnum) {
List<Object> baseContent = baseDocumentPart.getContent();
for (int i = 0; i < baseContent.size(); i++) {
Object obj = baseContent.get(i);
if (obj instanceof P) {
P p = (P) obj;
String text = getTextFromP(p).trim();
if (text.startsWith(ReportConstant.BOOKMARK_START)) {
DocAnchorEnum anchorEnum = DocAnchorEnum.getByKey(text);
if (anchorEnum != null && anchorEnum.getKey().equalsIgnoreCase(docAnchorEnum.getKey())) {
return i;
}
}
}
}
return -1;
}
/**
* 获取表格样式
*/
public static TblPr getTblPr(ObjectFactory factory) {
// **关键步骤:设置黑色实线边框**
TblPr tblPr = factory.createTblPr();
TblBorders borders = factory.createTblBorders();
// 定义边框样式1磅黑色单实线
CTBorder border = new CTBorder();
// 实线类型
border.setVal(STBorder.SINGLE);
// 1磅=4单位1/8磅
border.setSz(BigInteger.valueOf(4));
// 黑色
border.setColor("000000");
// 应用边框到所有边
borders.setTop(border);
borders.setBottom(border);
borders.setLeft(border);
borders.setRight(border);
// 内部水平线
borders.setInsideH(border);
// 内部垂直线
borders.setInsideV(border);
tblPr.setTblBorders(borders);
// 设置表格宽度为96%
TblWidth tblWidth = factory.createTblWidth();
// 百分比类型
tblWidth.setType("pct");
// 96% = 4800/5000 (ISO标准)
tblWidth.setW(BigInteger.valueOf(5000));
tblPr.setTblW(tblWidth);
return tblPr;
}
/**
* 获取分页符
*/
public static P getPageBreak() {
try {
ObjectFactory factory = new ObjectFactory();
// 创建分页符
R run = factory.createR();
Br br = factory.createBr();
br.setType(STBrType.PAGE);
// 直接添加 br 对象
run.getContent().add(br);
// 创建包含分页符的段落
P pageBreakParagraph = factory.createP();
pageBreakParagraph.getContent().add(run);
return pageBreakParagraph;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -1,7 +1,13 @@
package com.njcn.gather.report.utils;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -45,54 +51,6 @@ public class WordUtil {
});
}
private static void insertPageBreak(XWPFDocument target) {
if(!isDocumentEmpty(target)){
// 获取最后一个页面的段落
XWPFParagraph pageBreakParagraph = getLastPageParagraph(target);
// 设置分页符
pageBreakParagraph.setPageBreak(true);
}
}
public static boolean isDocumentEmpty(XWPFDocument document) {
// 检查段落
List<XWPFParagraph> paragraphs = document.getParagraphs();
if (paragraphs != null && !paragraphs.isEmpty()) {
for (XWPFParagraph paragraph : paragraphs) {
if (paragraph.getText() != null && !paragraph.getText().trim().isEmpty()) {
return false;
}
}
}
// 检查表格
List<XWPFTable> tables = document.getTables();
if (tables != null && !tables.isEmpty()) {
return false;
}
return true;
}
public static XWPFParagraph getLastPageParagraph(XWPFDocument document) {
XWPFParagraph lastPageParagraph = null;
for (XWPFParagraph paragraph : document.getParagraphs()) {
lastPageParagraph = paragraph;
}
return lastPageParagraph;
}
private static boolean containsPageBreak(XWPFParagraph paragraph) {
for (XWPFRun run : paragraph.getRuns()) {
if (run.getText(0) != null && run.getText(0).contains("\f")) {
return true;
}
}
return false;
}
/**
* 替换表格中的占位符
@@ -145,6 +103,42 @@ public class WordUtil {
}
}
/**
* 替换文档中的占位符
* @param document 文档
* @param placeholders 待替换的占位符
*/
public static void replacePlaceholders(XWPFDocument document, Map<String, String> placeholders) {
replacePlaceholdersInParagraphs(document,placeholders);
replacePlaceholdersInTables(document,placeholders);
}
public static List<XWPFParagraph> findHeadingLevel5Paragraphs(XWPFDocument document) {
List<XWPFParagraph> headingLevel5Paragraphs = new ArrayList<>();
for (XWPFParagraph paragraph : document.getParagraphs()) {
String style = paragraph.getStyle();
if ("5".equals(style)) {
headingLevel5Paragraphs.add(paragraph);
}
}
return headingLevel5Paragraphs;
}
/**
* 获取段落的位置通过遍历bodyElements
*/
public static int getBodyElementPosition(XWPFDocument document, XWPFParagraph paragraph) {
List<IBodyElement> bodyElements = document.getBodyElements();
for (int i = 0; i < bodyElements.size(); i++) {
if (bodyElements.get(i) instanceof XWPFParagraph && bodyElements.get(i).equals(paragraph)) {
return i;
}
}
return -1;
}
}

View File

@@ -4,7 +4,6 @@ import com.njcn.gather.storage.pojo.vo.RawDataVO;
import com.njcn.gather.storage.pojo.vo.RawResultDataVO;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@@ -18,7 +17,7 @@ public class ResultVO {
/**
* 结果数据
*/
private Map<String, RawResultDataVO> resultData;
private Map<String, List<RawResultDataVO>> resultData;
/**

View File

@@ -1,11 +1,14 @@
package com.njcn.gather.result.service;
import com.njcn.gather.report.pojo.result.SingleTestResult;
import com.njcn.gather.result.pojo.param.ResultParam;
import com.njcn.gather.result.pojo.vo.FormContentVO;
import com.njcn.gather.result.pojo.vo.ResultVO;
import com.njcn.gather.result.pojo.vo.TreeDataVO;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import java.util.List;
import java.util.Map;
/**
* @author caozehui
@@ -75,4 +78,22 @@ public interface IResultService {
* @param param
*/
void reCalculate(ResultParam.ChangeErrorSystemParam param);
/**
* 获取某测试大项的检测项内容
*
* @param checkDataVOList 检测项脚本
* @param planCode 计划编号
* @param devId 被检设备id
* @param lineNo 回路号
* @param tableKeys 表格key
*/
SingleTestResult getFinalContent(List<PqScriptDtlDataVO> checkDataVOList, String planCode, String devId, Integer lineNo, List<String> tableKeys);
/**
* 获取段落中指定的key对应的值
* @param itemCode 测试大项code
* @param pKeys 待填充的值
*/
Map<String, String> getParagraphKeysValue(String itemCode, List<String> pKeys);
}

View File

@@ -4,20 +4,30 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.po.DevData;
import com.njcn.gather.detection.pojo.vo.DetectionData;
import com.njcn.gather.detection.service.impl.DetectionServiceImpl;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.pojo.constant.PowerConstant;
import com.njcn.gather.report.pojo.enums.AffectEnum;
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
import com.njcn.gather.report.pojo.result.SingleTestResult;
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
import com.njcn.gather.result.pojo.param.ResultParam;
import com.njcn.gather.result.pojo.vo.FormContentVO;
@@ -26,14 +36,17 @@ import com.njcn.gather.result.pojo.vo.ResultVO;
import com.njcn.gather.result.pojo.vo.TreeDataVO;
import com.njcn.gather.result.service.IResultService;
import com.njcn.gather.script.mapper.PqScriptMapper;
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.script.util.ScriptDtlsDesc;
import com.njcn.gather.storage.mapper.TableGenMapper;
import com.njcn.gather.storage.pojo.param.SingleNonHarmParam;
import com.njcn.gather.storage.pojo.param.StorageParam;
import com.njcn.gather.storage.pojo.po.AdBaseResult;
import com.njcn.gather.storage.pojo.po.AdHarmonicResult;
@@ -41,10 +54,11 @@ import com.njcn.gather.storage.pojo.po.AdNonHarmonicResult;
import com.njcn.gather.storage.pojo.vo.RawDataVO;
import com.njcn.gather.storage.service.AdHarmonicService;
import com.njcn.gather.storage.service.AdNonHarmonicService;
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
import com.njcn.gather.system.dictionary.pojo.po.DictData;
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
import com.njcn.gather.system.dictionary.service.IDictDataService;
import com.njcn.gather.system.dictionary.service.IDictTreeService;
import com.njcn.web.utils.ExcelUtil;
import lombok.RequiredArgsConstructor;
@@ -68,7 +82,6 @@ import java.util.stream.Collectors;
public class ResultServiceImpl implements IResultService {
private final IAdPlanService adPlanService;
private final ISysTestConfigService sysTestConfigService;
private final IPqDevService pqDevService;
private final AdNonHarmonicService adNonHarmonicService;
private final AdHarmonicService adHarmonicService;
@@ -78,6 +91,9 @@ public class ResultServiceImpl implements IResultService {
private final IPqScriptCheckDataService pqScriptCheckDataService;
private final TableGenMapper tableGenMapper;
private final DetectionServiceImpl detectionServiceImpl;
private final IDictDataService dictDataService;
private final IPqScriptCheckDataService iPqScriptCheckDataService;
private final IPqDevService iPqDevService;
/**
* 谐波类code取树形字典表中的code
@@ -96,7 +112,7 @@ public class ResultServiceImpl implements IResultService {
adPlanService.visualize(Collections.singletonList(plan));
}
formContentVO.setScriptName(plan.getScriptId());
formContentVO.setDataRule(sysTestConfigService.getConfig().getDataRule());
formContentVO.setDataRule(plan.getDataRule());
formContentVO.setDeviceName(pqDevService.getById(queryParam.getDeviceId()).getName());
List<Map<String, String>> chnList = new ArrayList<>();
@@ -299,7 +315,7 @@ public class ResultServiceImpl implements IResultService {
dlt = new TreeDataVO();
List<PqScriptDtls> scriptDtlIndexList = subValue.stream().filter(x -> dtls.getScriptIndex().equals(x.getScriptIndex())).collect(Collectors.toList());
//特征幅值=20%Un持续时间=1周波
dlt.setScriptTypeName("特征幅值=" + dtls.getTransValue() + "%Un持续时间=" + dtls.getRetainTime().intValue() + "周波");
dlt.setScriptTypeName("特征幅值=" + dtls.getTransValue() + "%Un持续时间=" + dtls.getRetainTime() + "周波");
dlt.setIndex(dtls.getScriptIndex());
dlt.setScriptType(scriptDtlIndexList.get(0).getScriptType());
dlt.setScriptTypeCode("Base_" + start + "_" + end);
@@ -374,7 +390,7 @@ public class ResultServiceImpl implements IResultService {
//叠加2~50次谐波电压含有率为GB/T
dtlType.setScriptTypeName("叠加" + harmNumMap.entrySet().iterator().next().getValue().get(0).getHarmNum().intValue() + "~" +
new ArrayList<>(harmNumMap.entrySet()).get(harmNumMap.size() - 1).getValue().get(0).getHarmNum().intValue()
+ "" + dictTree.getName() + "含有率为GB/T");
+ "" + dictTree.getName()); // + "含有率为GB/T"
} else {
//叠加5%的2次谐波电压
dtlType.setScriptTypeName("叠加" + hv.get(0).getValue().intValue() + ResultUnitEnum.HV.getUnit() + "" + hv.get(0).getHarmNum().intValue() + "" + dictTree.getName());
@@ -505,6 +521,8 @@ public class ResultServiceImpl implements IResultService {
case VOLTAGE_MAG:
case VOLTAGE_DUR:
break;
default:
break;
}
}
@@ -584,6 +602,8 @@ public class ResultServiceImpl implements IResultService {
case VOLTAGE_MAG:
case VOLTAGE_DUR:
break;
default:
break;
}
}
@@ -675,6 +695,8 @@ public class ResultServiceImpl implements IResultService {
case VOLTAGE_MAG:
case VOLTAGE_DUR:
break;
default:
break;
}
}
@@ -770,6 +792,8 @@ public class ResultServiceImpl implements IResultService {
List<PqScriptDtls> dip = dtls.stream().filter(x -> "Dip".equals(x.getValueType())).collect(Collectors.toList());
dtlType.setScriptTypeName("频率=" + dipf.get(0).getValue() + ResultUnitEnum.FREQ.getUnit() + ",特征幅值=" + dip.get(0).getTransValue().intValue() + "%Un持续时间=" + dip.get(0).getRetainTime().intValue() + "周波");
break;
default:
break;
}
}
@@ -910,6 +934,559 @@ public class ResultServiceImpl implements IResultService {
this.calculateResult(param.getPlanId(), param.getScriptId(), param.getCode(), param.getErrorSysId(), param.getDeviceId());
}
/**
* 获取某测试大项的检测项内容,主要针对表格需要填充的值
* 注:虽然测试项区是三相,他们的标准值可能不同,但是误差范围是一致的
* 1、区分额定条件、单影响量条件、单影响量条件
* 2、区分scriptIndex
* 3、区分谐波次数有必要的情况下
*
* @param dtlDataVOList 检测项脚本
* @param planCode 计划编号
* @param devId 被检设备id
* @param lineNo 回路号
* @param tableKeys 表格key
*/
@Override
public SingleTestResult getFinalContent(List<PqScriptDtlDataVO> dtlDataVOList, String planCode, String devId, Integer lineNo, List<String> tableKeys) {
SingleTestResult singleTestResult = new SingleTestResult();
Map<String/*subType影响量额定或某单影响量*/, List<Map<String/*误差范围*/, List<Map<String/*填充key*/, String/*实际值*/>>>>> finalContent = new HashMap<>();
if (CollUtil.isNotEmpty(dtlDataVOList)) {
// 首先区分测试条件
Map<String, List<PqScriptDtlDataVO>> subTypeMap = dtlDataVOList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptSubType));
subTypeMap.forEach((subType, scriptDtlDataVOList) -> {
AffectEnum affectEnum = AffectEnum.getByKey(subType);
if (Objects.nonNull(affectEnum)) {
String scriptCode = scriptDtlDataVOList.get(0).getScriptCode();
String scriptId = scriptDtlDataVOList.get(0).getScriptId();
PowerIndexEnum indexEnum = PowerIndexEnum.getByKey(scriptCode);
if (Objects.nonNull(indexEnum)) {
String affectName = affectEnum.getDesc().replaceAll("XX", indexEnum.getDesc());
// 同一个影响量下,获取出子脚本信息
List<Integer> indexList = scriptDtlDataVOList.stream().map(PqScriptDtlDataVO::getScriptIndex).distinct().collect(Collectors.toList());
List<PqScriptCheckData> scriptCheckDataList = pqScriptCheckDataService.listCheckData(scriptId, indexList);
List<String> valueTypeList = scriptCheckDataList.stream().map(PqScriptCheckData::getValueType).distinct().collect(Collectors.toList());
// 稍作区分暂态的脚本同一个scriptIndex可以有两个指标其余脚本每个checkData的valueType对应一个指标结果
if (PowerConstant.VOLTAGE.equalsIgnoreCase(scriptCode)) {
// 暂态的valueType通常只有2个一个特征幅值一个持续时间
List<Map<String, String>> keyFillMapList = new ArrayList<>();
for (Integer sort : indexList) {
SingleNonHarmParam param = new SingleNonHarmParam(planCode, devId, lineNo, valueTypeList, Collections.singletonList(sort));
List<AdNonHarmonicResult> nonHarmList = adNonHarmonicService.queryByCondition(param);
if (CollUtil.isNotEmpty(nonHarmList)) {
Map<String, String> keyFillMap = new HashMap<>(16);
fillVoltagePhaseData(nonHarmList, keyFillMap, tableKeys);
keyFillMapList.add(keyFillMap);
}
}
// 需要对所有填充进行按误差范围分组
Map<String, List<Map<String, String>>> errorScoperMap = keyFillMapList.stream()
.collect(Collectors.groupingBy(map -> map.get(ItemReportKeyEnum.ERROR_SCOPE.getKey())));
// 分组后,还需要针对特征幅值标准值进行一个升序
errorScoperMap.forEach((errorScope, maps) -> {
PubUtils.sortByDoubleValue(maps, ItemReportKeyEnum.STANDARD_MAG.getKey());
});
List<Map<String, List<Map<String, String>>>> errorList = new ArrayList<>();
errorList.add(errorScoperMap);
// 最后赋值返回
finalContent.put(affectName, errorList);
} else {
for (String valueType : valueTypeList) {
if (PowerConstant.TIME.contains(scriptCode)) {
// 查询结果数据经过上层处理谐波类此处的scriptIndex确保只有一个
if (indexList.size() == 1) {
// 获取谐波数据
SingleNonHarmParam param = new SingleNonHarmParam(planCode, devId, lineNo, valueType, indexList.get(0));
AdHarmonicResult singleResult = adHarmonicService.getSingleResult(param);
// 注如果ABC的标准值一致则同步到standard中
Map<Double, List<PqScriptCheckData>> checkDataHarmNumMap = scriptCheckDataList.stream().collect(Collectors.groupingBy(PqScriptCheckData::getHarmNum));
List<Map<String, String>> keyFillMapList = new ArrayList<>();
checkDataHarmNumMap.forEach((harmNum, dtlsList) -> {
Map<String, String> keyFillMap = new HashMap<>();
// 次数需要区分谐波&间谐波
String time;
if (harmNum % 1 == 0) {
// 谐波,需要转为正数字符串
time = String.valueOf(harmNum.intValue());
} else {
// 间谐波,保留小数位转为字符串
time = String.format("%.1f", harmNum);
}
keyFillMap.put(ItemReportKeyEnum.TIME.getKey(), time);
// 将间谐波次数取整1.5取22.5取3
double timeDouble = Math.round(harmNum);
int timeInt = (int) timeDouble;
// 填充结果数据
fillThreePhaseData(singleResult, timeInt, keyFillMap, scriptCode);
keyFillMapList.add(keyFillMap);
});
if (CollUtil.isNotEmpty(keyFillMapList)) {
// 按次数排序
PubUtils.sortByDoubleValue(keyFillMapList, ItemReportKeyEnum.TIME.getKey());
// 取出任意一次谐波数据的误差范围作为key
String titleScope = keyFillMapList.get(0).get(ItemReportKeyEnum.ERROR_SCOPE.getKey());
Map<String, List<Map<String, String>>> errorScoperMap = new HashMap<>();
errorScoperMap.put(titleScope, keyFillMapList);
List<Map<String, List<Map<String, String>>>> errorScoperMapList = new ArrayList<>();
errorScoperMapList.add(errorScoperMap);
finalContent.put(affectName, errorScoperMapList);
}
} else {
log.error("生成谐波类表格数据失败,脚本配置不支持,请核实。");
throw new BusinessException("生成谐波类表格数据失败,脚本配置不支持,请核实。");
}
} else {
// 非谐波的需要区分是否为ABC相还是T相
if (PowerConstant.THREE_PHASE.contains(scriptCode)) {
// 获取该三相的数据
SingleNonHarmParam param = new SingleNonHarmParam(planCode, devId, lineNo, Collections.singletonList(valueType), indexList);
List<AdNonHarmonicResult> nonHarmList = adNonHarmonicService.queryByCondition(param);
if (CollUtil.isNotEmpty(nonHarmList)) {
List<Map<String, String>> keyFillMapList = new ArrayList<>();
for (AdNonHarmonicResult adNonHarmonicResult : nonHarmList) {
Map<String, String> keyFillMap = new HashMap<>(16);
fillThreePhaseData(adNonHarmonicResult, null, keyFillMap, scriptCode);
keyFillMapList.add(keyFillMap);
}
if (CollUtil.isNotEmpty(keyFillMapList)) {
// 需要对所有的填充进行按误差范围分组
Map<String, List<Map<String, String>>> errorScoperMap = keyFillMapList.stream()
.collect(Collectors.groupingBy(map -> map.get(ItemReportKeyEnum.ERROR_SCOPE.getKey())));
// 分组后,还需要针对标准值进行一个升序
errorScoperMap.forEach((errorScope, maps) -> {
PubUtils.sortByDoubleValue(maps, ItemReportKeyEnum.STANDARD.getKey());
});
List<Map<String, List<Map<String, String>>>> errorList = new ArrayList<>();
errorList.add(errorScoperMap);
// 最后赋值返回
finalContent.put(affectName, errorList);
}
} else {
log.error("生成三相类表格数据失败,结果表数据丢失,请核实。");
}
} else {
// 非三相且非暂态,通常只有一个数据,所以直接赋值即可
List<Map<String, String>> keyFillMapList = new ArrayList<>();
SingleNonHarmParam param = new SingleNonHarmParam(planCode, devId, lineNo, Collections.singletonList(valueType), indexList);
List<AdNonHarmonicResult> nonHarmList = adNonHarmonicService.queryByCondition(param);
if (CollUtil.isNotEmpty(nonHarmList)) {
for (AdNonHarmonicResult adNonHarmonicResult : nonHarmList) {
Map<String, String> keyFillMap = new HashMap<>(8);
fillTPhaseData(adNonHarmonicResult, null, keyFillMap);
keyFillMapList.add(keyFillMap);
}
}
if (CollUtil.isNotEmpty(keyFillMapList)) {
// 需要对所有填充进行按误差范围分组
Map<String, List<Map<String, String>>> errorScoperMap = keyFillMapList.stream()
.collect(Collectors.groupingBy(map -> map.get(ItemReportKeyEnum.ERROR_SCOPE.getKey())));
// 分组后,还需要针对特征幅值标准值进行一个升序
errorScoperMap.forEach((errorScope, maps) -> {
PubUtils.sortByDoubleValue(maps, ItemReportKeyEnum.STANDARD.getKey());
});
List<Map<String, List<Map<String, String>>>> errorList = new ArrayList<>();
errorList.add(errorScoperMap);
// 最后赋值返回
finalContent.put(affectName, errorList);
}
}
}
}
}
} else {
log.error("未找到合适的脚本信息");
}
} else {
log.error("未找到合适的测量条件");
}
});
}
// 返回之前做下总结性判断
singleTestResult.setQualified(judgeQualified(finalContent));
singleTestResult.setDetail(finalContent);
return singleTestResult;
}
/**
* 三相的相关数据处理
* 包含:谐波、间谐波、电压、电流、功率、闪变
*
* @param singleResult 可能是谐波类,也有可能是电压电流,需要区分下结果
* @param timeInt 谐波类需要传指定次数
* @param keyFillMap 待填充的集合Map
*/
private void fillThreePhaseData(Object singleResult, Integer timeInt, Map<String, String> keyFillMap, String scriptCode) {
DetectionData tempA = getResultData(singleResult, timeInt, PowerConstant.PHASE_A);
DetectionData tempB = getResultData(singleResult, timeInt, PowerConstant.PHASE_B);
DetectionData tempC = getResultData(singleResult, timeInt, PowerConstant.PHASE_C);
// 待填充Key
String standard = "/", standardA = "/", standardB = "/", standardC = "/",
testA = "/", testB = "/", testC = "/",
errorA = "/", errorB = "/", errorC = "/",
resultA = "/", resultB = "/", resultC = "/", result = "/",
errorScope = "/", unit = "", scriptDetail = "/";
if (Objects.nonNull(tempA)) {
standardA = PubUtils.doubleRoundStr(4, tempA.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempA.getResultData());
testA = PubUtils.doubleRoundStr(4, tempA.getData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempA.getData());
if (Objects.nonNull(tempA.getErrorData())) {
errorA = PubUtils.doubleRoundStr(4, tempA.getErrorData().doubleValue());
}
resultA = tempA.getIsData() == 1 ? "合格" : tempA.getIsData() == 0 ? "不合格" : "/";
errorScope = tempA.getRadius() == null ? "/" : tempA.getRadius();
unit = tempA.getUnit() == null ? "" : tempA.getUnit();
standard = PubUtils.doubleRoundStr(4, tempA.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempA.getResultData());
}
if (Objects.nonNull(tempB)) {
standardB = PubUtils.doubleRoundStr(4, tempB.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempB.getResultData());
testB = PubUtils.doubleRoundStr(4, tempB.getData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempB.getData());
if (Objects.nonNull(tempB.getErrorData())) {
errorB = PubUtils.doubleRoundStr(4, tempB.getErrorData().doubleValue());
}
resultB = tempB.getIsData() == 1 ? "合格" : tempB.getIsData() == 0 ? "不合格" : "/";
if (errorScope.equals("/")) {
errorScope = tempB.getRadius() == null ? "/" : tempB.getRadius();
}
if (StrUtil.isBlank(unit)) {
unit = tempB.getUnit() == null ? "" : tempB.getUnit();
}
if (standard.equals("/")) {
standard = PubUtils.doubleRoundStr(4, tempB.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempB.getResultData());
}
}
if (Objects.nonNull(tempC)) {
standardC = PubUtils.doubleRoundStr(4, tempC.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempC.getResultData());
testC = PubUtils.doubleRoundStr(4, tempC.getData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempC.getData());
if (Objects.nonNull(tempC.getErrorData())) {
errorC = PubUtils.doubleRoundStr(4, tempC.getErrorData().doubleValue());
}
resultC = tempC.getIsData() == 1 ? "合格" : tempC.getIsData() == 0 ? "不合格" : "/";
if (errorScope.equals("/")) {
errorScope = tempC.getRadius() == null ? "/" : tempC.getRadius();
}
if (StrUtil.isBlank(unit)) {
unit = tempC.getUnit() == null ? "" : tempC.getUnit();
}
if (standard.equals("/")) {
standard = PubUtils.doubleRoundStr(4, tempC.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempC.getResultData());
}
}
if (scriptCode.equalsIgnoreCase("I")) {
resultA = "/";
resultB = "/";
resultC = "/";
}
if (standardA.equals(standardB) && standardA.equals(standardC)) {
standard = standardA;
}
// 处理脚本输出
scriptDetail = dealScriptDetail(scriptCode, standard);
keyFillMap.put(ItemReportKeyEnum.SCRIPT_DETAIL.getKey(), scriptDetail);
// 标准值
keyFillMap.put(ItemReportKeyEnum.STANDARD.getKey(), standard);
keyFillMap.put(ItemReportKeyEnum.STANDARD_A.getKey(), standardA);
keyFillMap.put(ItemReportKeyEnum.STANDARD_B.getKey(), standardB);
keyFillMap.put(ItemReportKeyEnum.STANDARD_C.getKey(), standardC);
// 测试值
keyFillMap.put(ItemReportKeyEnum.TEST_A.getKey(), testA);
keyFillMap.put(ItemReportKeyEnum.TEST_B.getKey(), testB);
keyFillMap.put(ItemReportKeyEnum.TEST_C.getKey(), testC);
// 误差值
keyFillMap.put(ItemReportKeyEnum.ERROR_A.getKey(), errorA);
keyFillMap.put(ItemReportKeyEnum.ERROR_B.getKey(), errorB);
keyFillMap.put(ItemReportKeyEnum.ERROR_C.getKey(), errorC);
// 结果
keyFillMap.put(ItemReportKeyEnum.RESULT_A.getKey(), resultA);
keyFillMap.put(ItemReportKeyEnum.RESULT_B.getKey(), resultB);
keyFillMap.put(ItemReportKeyEnum.RESULT_C.getKey(), resultC);
if (resultA.equals("不合格") || resultB.equals("不合格") || resultC.equals("不合格")) {
result = "不合格";
} else if (!resultA.equals("/") || !resultB.equals("/") || !resultC.equals("/")) {
result = "合格";
}
keyFillMap.put(ItemReportKeyEnum.RESULT.getKey(), result);
errorScope = dealErrorScope(errorScope).concat(unit);
keyFillMap.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope);
}
/**
* 针对浙江杭州处理脚本输出细节todo... 需要更改更合理的方式,现在算是写死的了部分
* 目前浙江这边就是(间)谐波电压/电流
*/
private String dealScriptDetail(String scriptCode, String standard) {
String scriptDetail = "";
PowerIndexEnum powerIndexEnum = PowerIndexEnum.getByKey(scriptCode);
if (powerIndexEnum != null) {
switch (powerIndexEnum) {
case HV:
case HSV:
// 注基波电压幅值57.74V基波频率50.0Hz。
scriptDetail = "基波电压幅值57.74V基波频率50.0Hz。";
break;
case HI:
// 电流是幅值需要与5A得出百分比
try {
String temp = PubUtils.doubleRoundStr(1, (Double.parseDouble(standard) / 5.0) * 100);
scriptDetail = "基波电流幅值5.000A基波频率50.0Hz,各次谐波电流含有率均为" + temp + "%。";
} catch (Exception e) {
log.error("dealScriptDetail error:{}", e);
}
break;
case HSI:
// 电流是幅值需要与5A得出百分比
try {
String temp = PubUtils.doubleRoundStr(1, (Double.parseDouble(standard) / 5.0) * 100);
scriptDetail = "基波电流幅值5.000A基波频率50.0Hz,各次间谐波电流含有率均为" + temp + "%。";
} catch (Exception e) {
log.error("dealScriptDetail error:{}", e);
}
break;
default:
break;
}
}
return scriptDetail;
}
/**
* T相的相关数据处理非暂态数据
* 包含:三相电压/电流不平衡度、频率,其中三相电压/电流实际ABC中存了正序/负序/零序电压
*
* @param singleResult 可能是谐波类,也有可能是电压电流,需要区分下结果
* @param timeInt 谐波类需要传指定次数
* @param keyFillMap 待填充的集合Map
*/
private void fillTPhaseData(Object singleResult, Integer timeInt, Map<String, String> keyFillMap) {
String standard = "/", test = "/", error = "/", result = "/", errorScope = "/", unit = "";
DetectionData tempT = getResultData(singleResult, timeInt, PowerConstant.PHASE_T);
if (Objects.nonNull(tempT)) {
standard = PubUtils.doubleRoundStr(4, tempT.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempT.getResultData());
test = PubUtils.doubleRoundStr(4, tempT.getData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempT.getData());
if (Objects.nonNull(tempT.getErrorData())) {
error = PubUtils.doubleRoundStr(4, tempT.getErrorData().doubleValue());
}
result = tempT.getIsData() == 1 ? "合格" : tempT.getIsData() == 0 ? "不合格" : "/";
unit = tempT.getUnit() == null ? "" : tempT.getUnit();
errorScope = tempT.getRadius() == null ? "/" : tempT.getRadius();
}
keyFillMap.put(ItemReportKeyEnum.STANDARD.getKey(), standard);
keyFillMap.put(ItemReportKeyEnum.TEST.getKey(), test);
keyFillMap.put(ItemReportKeyEnum.ERROR.getKey(), error);
keyFillMap.put(ItemReportKeyEnum.RESULT.getKey(), result);
errorScope = dealErrorScope(errorScope).concat(unit);
keyFillMap.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope);
}
/**
* 针对暂态的数据填充
*
* @param nonHarmList 暂态的结果集
* @param keyFillMap 待填充的集合Map
* @param tableKeys 模板表格中的key
*/
private void fillVoltagePhaseData(List<AdNonHarmonicResult> nonHarmList, Map<String, String> keyFillMap, List<String> tableKeys) {
String standardMag = "/", standardDur = "/",
testMag = "/", testDur = "/",
errorMag = "/", errorDur = "/",
resultMag = "/", resultDur = "/", result,
errorScope, errorScopeMag = "/", errorScopeDur = "/",
unitMag = "", unitDur = "";
for (AdNonHarmonicResult adNonHarmonicResult : nonHarmList) {
DetectionData tempT = getResultData(adNonHarmonicResult, null, PowerConstant.PHASE_T);
// 需要判断adNonHarmonicResult是特征幅值还是持续时间
String adType = adNonHarmonicResult.getAdType();
DictTree temp = dictTreeService.getById(adType);
if (temp.getCode().equalsIgnoreCase("MAG")) {
// 特征幅值
if (Objects.nonNull(tempT)) {
standardMag = PubUtils.doubleRoundStr(4, tempT.getResultData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempT.getResultData());
testMag = PubUtils.doubleRoundStr(4, tempT.getData()) == null ? "/" : PubUtils.doubleRoundStr(4, tempT.getData());
if (Objects.nonNull(tempT.getErrorData())) {
errorMag = PubUtils.doubleRoundStr(4, tempT.getErrorData().doubleValue());
}
resultMag = tempT.getIsData() == 1 ? "合格" : tempT.getIsData() == 0 ? "不合格" : "/";
unitMag = tempT.getUnit();
errorScopeMag = tempT.getRadius();
}
} else if (temp.getCode().equalsIgnoreCase("DUR")) {
// 持续时间,需要注意时间单位处理,默认是秒
String timeUnit = "s";
for (String tableKey : tableKeys) {
if (tableKey.contains(ItemReportKeyEnum.STANDARD_DUR.getKey())) {
//截取单位
String[] tempStr = tableKey.split(StrPool.UNDERLINE);
if (tempStr.length > 1) {
if (tempStr[1].equalsIgnoreCase("ms")) {
timeUnit = "ms";
}
}
}
}
if (Objects.nonNull(tempT.getResultData())) {
standardDur = PubUtils.doubleRoundStr(4, tempT.getResultData());
}
if (Objects.nonNull(tempT.getData())) {
testDur = PubUtils.doubleRoundStr(4, tempT.getData());
}
if (Objects.nonNull(tempT.getErrorData())) {
testDur = PubUtils.doubleRoundStr(4, tempT.getErrorData().doubleValue());
}
if (Objects.nonNull(tempT.getIsData())) {
resultDur = tempT.getIsData() == 1 ? "合格" : "不合格";
}
if (StrUtil.isNotBlank(tempT.getUnit())) {
unitDur = tempT.getUnit();
}
if (StrUtil.isNotBlank(tempT.getRadius())) {
errorScopeDur = tempT.getRadius();
}
if (timeUnit.equalsIgnoreCase("ms")) {
// 如果是ms上述的一些数据需要重新处理
if (!standardDur.equalsIgnoreCase("/")) {
standardDur = PubUtils.doubleRoundStr(4, Double.parseDouble(standardDur) * 1000);
}
if (!testDur.equalsIgnoreCase("/")) {
testDur = PubUtils.doubleRoundStr(4, Double.parseDouble(testDur) * 1000);
}
if (!errorDur.equalsIgnoreCase("/")) {
errorDur = PubUtils.doubleRoundStr(4, Double.parseDouble(errorDur) * 1000);
}
if (!errorScopeDur.equalsIgnoreCase("/")) {
if (errorScopeDur.contains("~")) {
String[] tempStr = errorScopeDur.split("~");
errorScopeDur = PubUtils.doubleRoundStr(0, Double.parseDouble(tempStr[0]) * 1000).concat("~").concat(PubUtils.doubleRoundStr(0, Double.parseDouble(tempStr[1]) * 1000));
}
}
unitDur = "ms";
}
}
}
errorScopeMag = dealErrorScope(errorScopeMag).concat(unitMag);
errorScopeDur = dealErrorScope(errorScopeDur).concat(unitDur);
errorScope = "特征幅值:".concat(errorScopeMag).concat(StrPool.COMMA).concat("持续时间:").concat(errorScopeDur);
keyFillMap.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), errorScope);
// 标准值
keyFillMap.put(ItemReportKeyEnum.STANDARD_MAG.getKey(), standardMag);
keyFillMap.put(ItemReportKeyEnum.STANDARD_DUR.getKey(), standardDur);
// 测试值
keyFillMap.put(ItemReportKeyEnum.TEST_MAG.getKey(), testMag);
keyFillMap.put(ItemReportKeyEnum.TEST_DUR.getKey(), testDur);
// 误差
keyFillMap.put(ItemReportKeyEnum.ERROR_MAG.getKey(), errorMag);
keyFillMap.put(ItemReportKeyEnum.ERROR_DUR.getKey(), errorDur);
// 结果
keyFillMap.put(ItemReportKeyEnum.RESULT_MAG.getKey(), resultMag);
keyFillMap.put(ItemReportKeyEnum.RESULT_DUR.getKey(), resultDur);
// 综合结果
result = resultMag;
if (!resultDur.equals("/") && result.equals("合格")) {
if (resultDur.equals("不合格")) {
result = "不合格";
}
}
keyFillMap.put(ItemReportKeyEnum.RESULT.getKey(), result);
}
/**
* 处理下误差范围,如果正负数一致时调整为±的形式
* 数据库中一般形式为:-0.1155~0.1155
*
* @param errorScope 误差范围
*/
private String dealErrorScope(String errorScope) {
if (errorScope.contains("~")) {
String[] split = errorScope.split("~");
String begin = split[0];
if (begin.contains(StrPool.DASHED)) {
begin = begin.substring(1);
}
String end = split[1];
if (end.equalsIgnoreCase(begin)) {
return "±" + begin;
}
}
return errorScope;
}
/**
* 遍历所有的结果是否存在不合格但凡有一个不合格就返回false
*
* @param finalContent 最终结果
*/
private boolean judgeQualified(Map<String, List<Map<String, List<Map<String, String>>>>> finalContent) {
List<String> results = finalContent.values().parallelStream()
.flatMap(List::stream)
.flatMap(m -> m.values().stream())
.flatMap(List::stream)
.filter(map -> map.containsKey(ItemReportKeyEnum.RESULT.getKey()))
.map(map -> map.get(ItemReportKeyEnum.RESULT.getKey()))
.collect(Collectors.toList());
List<String> qualifiedList = results.stream().filter("不合格"::equals).collect(Collectors.toList());
return CollUtil.isEmpty(qualifiedList);
}
/**
* 根据谐波结果数据获取局的测试数据
*
* @param singleResult 谐波数据
* @param timeInt 次数
* @param phaseA 相别
*/
private DetectionData getResultData(Object singleResult, Integer timeInt, String phaseA) {
String fieldName = phaseA.toLowerCase().concat("Value");
if (Objects.nonNull(timeInt)) {
fieldName = fieldName.concat(String.valueOf(timeInt));
}
String filedValue;
try {
filedValue = (String) ReflectUtil.getFieldValue(singleResult, fieldName);
} catch (Exception exception) {
throw new BusinessException("获取对象字段属性失败");
}
return JSONUtil.toBean(filedValue, DetectionData.class);
}
/**
* 获取段落中指定的key对应的值目前主要为测试大项名称服务通过code匹配
*
* @param itemCode 测试大项code
* @param pKeys 待填充的值
*/
@Override
public Map<String, String> getParagraphKeysValue(String itemCode, List<String> pKeys) {
Map<String, String> map = new HashMap<>();
if (CollUtil.isNotEmpty(pKeys)) {
for (String pKey : pKeys) {
ItemReportKeyEnum reportKeyEnum = ItemReportKeyEnum.getByKey(pKey);
if (Objects.nonNull(reportKeyEnum)) {
if (reportKeyEnum.getKey().equals(ItemReportKeyEnum.NAME.getKey())) {
PowerIndexEnum indexEnum = PowerIndexEnum.getByKey(itemCode);
if (Objects.nonNull(indexEnum)) {
map.put(reportKeyEnum.getKey(), indexEnum.getDesc());
} else {
log.error("电能指标枚举未找到测试项");
}
} else if (reportKeyEnum.getKey().equals(ItemReportKeyEnum.NAME_DETAIL.getKey())) {
PowerIndexEnum indexEnum = PowerIndexEnum.getByKey(itemCode);
if (Objects.nonNull(indexEnum)) {
map.put(reportKeyEnum.getKey(), indexEnum.getDesc().concat("测量准确度"));
} else {
log.error("电能指标枚举未找到测试项");
}
}
} else {
log.error("段落枚举未找到占用符");
}
}
}
return map;
}
private Integer conform(Set<Integer> numbers) {
if (CollUtil.isNotEmpty(numbers)) {
if (numbers.size() > 1) {
@@ -1000,18 +1577,25 @@ public class ResultServiceImpl implements IResultService {
// PqDev dev = pqDevService.getById(devId);
devIdMapComm.put(devId, devId);
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
DictDataEnum dataRule;
if (ObjectUtil.isNotNull(oneConfig)) {
dataRule = DictDataEnum.getDictDataEnumByCode(oneConfig.getDataRule());
// SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
// if (ObjectUtil.isNotNull(oneConfig)) {
// dataRule = DictDataEnum.getDictDataEnumByCode(oneConfig.getDataRule());
// } else {
// dataRule = DictDataEnum.SECTION_VALUE;
// }
AdPlan plan = adPlanService.getById(planId);
DictData dictData = dictDataService.getDictDataById(plan.getDataRule());
if (ObjectUtil.isNotNull(dictData)) {
dataRule = DictDataEnum.getDictDataEnumByCode(dictData.getCode());
} else {
dataRule = DictDataEnum.AT_WILL_VALUE;
dataRule = DictDataEnum.SECTION_VALUE;
}
List<AdNonHarmonicResult> allNonHarmonicRawData = adNonHarmonicService.listAll(scriptId, oldCode, devId);
List<AdNonHarmonicResult> allNonHarmonicRawData = adNonHarmonicService.listAllRawData(scriptId, oldCode, devId);
LinkedHashMap<Integer, List<AdNonHarmonicResult>> nonHarmonicMap = allNonHarmonicRawData.stream().sorted(Comparator.comparing(AdNonHarmonicResult::getSort))
.collect(Collectors.groupingBy(AdNonHarmonicResult::getSort, LinkedHashMap::new, Collectors.toList()));
List<AdHarmonicResult> allHarmonicRawData = adHarmonicService.listAll(scriptId, oldCode, devId);
List<AdHarmonicResult> allHarmonicRawData = adHarmonicService.listAllRawData(scriptId, oldCode, devId);
LinkedHashMap<Integer, List<AdHarmonicResult>> harmonicMap = allHarmonicRawData.stream().sorted(Comparator.comparing(AdHarmonicResult::getSort))
.collect(Collectors.groupingBy(AdHarmonicResult::getSort, LinkedHashMap::new, Collectors.toList()));
@@ -1034,18 +1618,22 @@ public class ResultServiceImpl implements IResultService {
realDataXiList.addAll(this.toList(nonHarmonicResults, null, true));
}
if (CollUtil.isNotEmpty(harmonicResults)) {
DictTree dictTree = dictTreeService.getById(harmonicResults.get(0).getAdType());
if (ObjectUtil.isNotNull(dictTree)) {
if (DetectionCodeEnum.V2_50.getCode().equals(dictTree.getCode()) || DetectionCodeEnum.I2_50.getCode().equals(dictTree.getCode()) || DetectionCodeEnum.P2_50.getCode().equals(dictTree.getCode())) {
realDataXiList.addAll(this.toList(null, harmonicResults, true));
} else {
realDataXiList.addAll(this.toList(null, harmonicResults, false));
}
if (DetectionCodeEnum.V2_50.getCode().equals(harmonicResults.get(0).getAdType()) || DetectionCodeEnum.I2_50.getCode().equals(harmonicResults.get(0).getAdType()) || DetectionCodeEnum.P2_50.getCode().equals(harmonicResults.get(0).getAdType())) {
realDataXiList.addAll(this.toList(null, harmonicResults, true));
} else {
realDataXiList.addAll(this.toList(null, harmonicResults, false));
}
}
detectionServiceImpl.processing(realDataXiList, param, devIdMapComm, sourceIssue, dataRule);
});
PqScriptCheckDataParam checkDataParam = new PqScriptCheckDataParam();
checkDataParam.setScriptId(scriptId);
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), null, param.getTemperature(), param.getHumidity());
}
private List<DevData> toList(List<AdNonHarmonicResult> nonHarm, List<AdHarmonicResult> harm, boolean containBaseHarm) {
@@ -1064,8 +1652,7 @@ public class ResultServiceImpl implements IResultService {
for (AdNonHarmonicResult result : value) {
sqlDataDTO = new DevData.SqlDataDTO();
sqlDataDTO.setType(result.getDataType());
DictTree dictTree = dictTreeService.getById(result.getAdType());
sqlDataDTO.setDesc(dictTree.getCode());
sqlDataDTO.setDesc(result.getAdType());
DevData.SqlDataDTO.ListDTO listDTO = new DevData.SqlDataDTO.ListDTO();
listDTO.setA(StrUtil.isNotBlank(result.getAValue()) ? Double.valueOf(result.getAValue()) : null);
listDTO.setB(StrUtil.isNotBlank(result.getBValue()) ? Double.valueOf(result.getBValue()) : null);
@@ -1088,16 +1675,15 @@ public class ResultServiceImpl implements IResultService {
List<DevData.SqlDataHarmDTO> sqlDataHarmDTOS = new ArrayList<>();
DevData.SqlDataHarmDTO dataHarmDTO;
for (AdHarmonicResult harmonicResult : value) {
DictTree dictTree = dictTreeService.getById(harmonicResult.getAdType());
if (containBaseHarm) {
sqlDataDTO = new DevData.SqlDataDTO();
sqlDataDTO.setType(harmonicResult.getDataType());
if (DetectionCodeEnum.V2_50.getCode().equals(dictTree.getCode())) {
if (DetectionCodeEnum.V2_50.getCode().equals(harmonicResult.getAdType())) {
sqlDataDTO.setDesc(DetectionCodeEnum.U1.getCode());
} else if (DetectionCodeEnum.I2_50.getCode().equals(dictTree.getCode())) {
} else if (DetectionCodeEnum.I2_50.getCode().equals(harmonicResult.getAdType())) {
sqlDataDTO.setDesc(DetectionCodeEnum.I1.getCode());
} else {
sqlDataDTO.setDesc(dictTree.getCode());
sqlDataDTO.setDesc(harmonicResult.getAdType());
}
DevData.SqlDataDTO.ListDTO listDTO = new DevData.SqlDataDTO.ListDTO();
listDTO.setA(StrUtil.isNotBlank(harmonicResult.getAValue1()) ? Double.valueOf(harmonicResult.getAValue1()) : null);
@@ -1109,7 +1695,7 @@ public class ResultServiceImpl implements IResultService {
dataHarmDTO = new DevData.SqlDataHarmDTO();
dataHarmDTO.setType(harmonicResult.getDataType());
dataHarmDTO.setDesc(dictTree.getCode());
dataHarmDTO.setDesc(harmonicResult.getAdType());
dataHarmDTO.setNum(containBaseHarm ? 49 : 50);
DevData.SqlDataHarmDTO.ListDTO listHarmDTO = new DevData.SqlDataHarmDTO.ListDTO();
listHarmDTO.setA(reflectHarmonicValue("a", harmonicResult, containBaseHarm));
@@ -1132,9 +1718,7 @@ public class ResultServiceImpl implements IResultService {
});
}
// }
return info;
}
private List<String> reflectHarmonicValue(String phase, AdHarmonicResult adHarmonicResult, boolean notContainBaseHarm) {

View File

@@ -59,15 +59,11 @@ public class PqScriptController extends BaseController {
@PostMapping("/add")
@ApiOperation("新增检测脚本")
@ApiImplicitParam(name = "pqDevParam", value = "检测脚本", required = true)
public HttpResult<Boolean> add(@RequestBody @Validated PqScriptParam param) {
public HttpResult<String> add(@RequestBody @Validated PqScriptParam param) {
String methodDescribe = getMethodDescribe("add");
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, param);
Boolean result = pqScriptService.addPqScript(param);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
} else {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
String id = pqScriptService.addPqScript(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, id, methodDescribe);
}
@OperateInfo(operateType = OperateType.UPDATE)
@@ -216,6 +212,5 @@ public class PqScriptController extends BaseController {
String checkData = pqScriptDtlsService.getScriptDtlsDesc(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, checkData, methodDescribe);
}
}

View File

@@ -2,6 +2,10 @@ package com.njcn.gather.script.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import com.njcn.gather.script.pojo.vo.PqScriptCheckDataVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Description:

View File

@@ -2,8 +2,12 @@ package com.njcn.gather.script.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.script.pojo.vo.PqScriptCheckDataVO;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author caozehui
* @date 2024-11-18
@@ -17,5 +21,7 @@ public interface PqScriptDtlsMapper extends MPJBaseMapper<PqScriptDtls> {
* @return
*/
Integer selectMaxIndex(@Param("scriptId") String scriptId);
List<PqScriptDtlDataVO> getScriptDtlsDataList(@Param("scriptId")String scriptId);
}

View File

@@ -2,6 +2,5 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.script.mapper.PqScriptCheckDataMapper">
</mapper>

View File

@@ -10,5 +10,21 @@
WHERE Script_Id = #{scriptId}
</select>
<select id="getScriptDtlsDataList" resultType="com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO" >
SELECT
t2.CODE scriptCode,
t2.NAME scriptName,
t1.*
FROM
pq_script_dtls t1,
sys_dict_tree t2
WHERE
t1.Script_Type = t2.Id
AND t1.Script_Id = #{scriptId}
AND t1.ENABLE = 1
ORDER BY
t1.Script_Index ASC,t1.HarmNum ASC
</select>
</mapper>

View File

@@ -22,6 +22,7 @@
</foreach>
</where>
</if>
AND State=1
</select>
</mapper>

View File

@@ -20,6 +20,12 @@ public class PqScriptCheckDataParam {
@ApiModelProperty("相别,字典表")
private String phase;
/**
* pq_script_checkdata 里dataType 删除,由根据计划中的数据源,来进行配置脚本增加扩展性
*/
@ApiModelProperty("数据类型,来源于字典表,包括实时数据(3s)、分钟统计数据(1min/3min/5min/10min)等")
private String dataType;
@ApiModelProperty("检测指标类型(true:code(I$real) false展示id 默认false)")
private Boolean isValueTypeName=false;

View File

@@ -84,11 +84,6 @@ public class PqScriptDtlsParam {
*/
private String pid;
/**
* 数据类型,来源于字典表,包括实时数据(3s)、分钟统计数据(1min/3min/5min/10min)等
*/
private String dataType;
/**
* 相别,字典表
*/

View File

@@ -23,7 +23,7 @@ public class PqScriptIssueParam {
@ApiModelProperty("终端id集合")
private List<String> devIds;
@ApiModelProperty()
@ApiModelProperty("校验步骤")
private String isPhaseSequence;
@ApiModelProperty("源id")

View File

@@ -39,10 +39,6 @@ public class PqScriptCheckData implements Serializable {
@TableField(exist = false)
private String valueTypeCode;
/**
* 数据类型,来源于字典表,包括实时数据(3s)、分钟统计数据(1min/3min/5min/10min)等
*/
private String dataType;
/**
* 相别,字典表

View File

@@ -50,6 +50,9 @@ public class SourceIssue {
@JSONField(serialize = false)
private List<String> devValueTypeList;
@JSONField(serialize = false)
private String dataType;
@JSONField(serialize = false)
private String desc;

View File

@@ -0,0 +1,24 @@
package com.njcn.gather.script.pojo.vo;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import lombok.Data;
/**
* @author hongawen
* @version 1.0
* @data 2025/3/26 14:45
*/
@Data
public class PqScriptCheckDataVO extends PqScriptCheckData {
/**
* 脚本项名称
*/
private String scriptName;
/**
* 脚本项Code
*/
private String scriptCode;
}

View File

@@ -1,23 +1,23 @@
package com.njcn.gather.script.pojo.vo;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import lombok.Data;
import java.io.Serializable;
@Data
public class PqScriptDtlDataVO implements Serializable {
public class PqScriptDtlDataVO extends PqScriptDtls implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 这条检测脚本的序号
* 脚本项名称
*/
private String index;
private String scriptName;
/**
* 脚本项Code
*/
private String scriptCode;
}

View File

@@ -36,4 +36,19 @@ public interface IPqScriptCheckDataService extends IService<PqScriptCheckData> {
List<PqScriptCheckData> listCheckDataCode(PqScriptCheckDataParam param);
Double getCheckDataValue(PqScriptCheckDataParam param);
/**
* 查询条件范围内的参与比较的脚本详情
* @param scriptId 脚本id
* @param indexList 脚本下标集合
*/
List<PqScriptCheckData> listCheckData(String scriptId, List<Integer> indexList);
/**
* 根据脚本id删除数据
*
* @param ids
* @return
*/
boolean deleteByScriptIds(List<String> ids);
}

View File

@@ -1,12 +1,14 @@
package com.njcn.gather.script.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.script.pojo.param.PqScriptDtlsParam;
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.script.pojo.param.ScriptParam;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import java.util.List;
@@ -114,11 +116,24 @@ public interface IPqScriptDtlsService extends IService<PqScriptDtls> {
List<PqScriptCheckData> checkDataList(ScriptParam param);
/**
* @Description: 获取脚本详情描述
* @param param
* @Description: 获取脚本详情描述
* @return: java.lang.String
* @Author: wr
* @Date: 2025/3/31 9:40
*/
String getScriptDtlsDesc(ScriptParam.Desc param);
/**
* 获取脚本与icd校验所需要的信息
*
* @param param
* @return
*/
List<String> getScriptToIcdCheckInfo(PreDetectionParam param);
/**
* 根据脚本id获取脚本详情数据
* @param scriptId 脚本id
*/
List<PqScriptDtlDataVO> getScriptDtlsDataList(String scriptId);
}

View File

@@ -34,9 +34,9 @@ public interface IPqScriptService extends IService<PqScript> {
* 新增检测脚本
*
* @param param 检测脚本
* @return 成功返回true, 失败返回false
* @return 成功返回ScriptId, 失败返回null
*/
Boolean addPqScript(PqScriptParam param);
String addPqScript(PqScriptParam param);
/**
* 删除检测脚本

View File

@@ -2,11 +2,11 @@ package com.njcn.gather.script.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
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.gather.detection.pojo.enums.DetectionCodeEnum;
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
@@ -20,7 +20,9 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -34,61 +36,68 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class PqScriptCheckDataServiceImpl extends ServiceImpl<PqScriptCheckDataMapper, PqScriptCheckData> implements IPqScriptCheckDataService {
private final String REAL="real$";
private final String SYMBOL = "$";
private final DictTreeMapper dictTreeMapper;
@Override
public List<String> getValueType(PqScriptCheckDataParam param) {
MPJLambdaWrapper<PqScriptCheckData> queryWrapper = new MPJLambdaWrapper<>();
queryWrapper.selectAll(PqScriptCheckData.class)
.leftJoin(DictTree.class, DictTree::getId, PqScriptCheckData::getValueType)
.eq(PqScriptCheckData::getScriptId, param.getScriptId())
.eq(ObjectUtil.isNotNull(param.getIndex()),PqScriptCheckData::getScriptIndex, param.getIndex())
.eq(PqScriptCheckData::getEnable, DataStateEnum.ENABLE.getCode());
if (param.getIsValueTypeName()) {
queryWrapper.selectAs(DictTree::getCode, PqScriptCheckData::getValueType);
}
List<PqScriptCheckData> pqScriptCheckData = this.getBaseMapper().selectJoinList(PqScriptCheckData.class, queryWrapper);
if(CollUtil.isNotEmpty(pqScriptCheckData)){
String dataType = param.getDataType();
if (StrUtil.isNotBlank(dataType)) {
String[] split = dataType.split(",");
if (split.length > 1) {
dataType = split[0];
}
MPJLambdaWrapper<PqScriptCheckData> queryWrapper = new MPJLambdaWrapper<>();
queryWrapper.selectAll(PqScriptCheckData.class)
.leftJoin(DictTree.class, DictTree::getId, PqScriptCheckData::getValueType)
.eq(PqScriptCheckData::getScriptId, param.getScriptId())
.eq(ObjectUtil.isNotNull(param.getIndex()), PqScriptCheckData::getScriptIndex, param.getIndex())
.eq(PqScriptCheckData::getEnable, DataStateEnum.ENABLE.getCode());
if (param.getIsValueTypeName()) {
List<String> checkData = pqScriptCheckData.stream().map(x -> x.getDataType() + "$" + x.getValueType()).distinct().collect(Collectors.toList());
String U = REAL + DetectionCodeEnum.U1.getCode();
if(!checkData.contains(U)){
if(checkData.contains(REAL+DetectionCodeEnum.V2_50.getCode())){
checkData.add(U);
queryWrapper.selectAs(DictTree::getCode, PqScriptCheckData::getValueType);
}
List<PqScriptCheckData> pqScriptCheckData = this.getBaseMapper().selectJoinList(PqScriptCheckData.class, queryWrapper);
if (CollUtil.isNotEmpty(pqScriptCheckData)) {
if (param.getIsValueTypeName()) {
final String finalDataType = dataType;
List<String> checkData = pqScriptCheckData.stream().map(x -> finalDataType + SYMBOL + x.getValueType()).distinct().collect(Collectors.toList());
String U = finalDataType + SYMBOL + DetectionCodeEnum.U1.getCode();
if (!checkData.contains(U)) {
if (checkData.contains(finalDataType + SYMBOL + DetectionCodeEnum.V2_50.getCode())) {
checkData.add(U);
}
}
}
String I = REAL + DetectionCodeEnum.I1.getCode();
if(!checkData.contains(I)){
if(checkData.contains(REAL+DetectionCodeEnum.I2_50.getCode())){
checkData.add(I);
String I = finalDataType + SYMBOL + DetectionCodeEnum.I1.getCode();
if (!checkData.contains(I)) {
if (checkData.contains(finalDataType + SYMBOL + DetectionCodeEnum.I2_50.getCode())) {
checkData.add(I);
}
}
return checkData.stream().distinct().collect(Collectors.toList());
} else {
return pqScriptCheckData.stream().map(PqScriptCheckData::getValueType).distinct().collect(Collectors.toList());
}
return checkData.stream().distinct().collect(Collectors.toList());
} else {
return pqScriptCheckData.stream().map(PqScriptCheckData::getValueType).distinct().collect(Collectors.toList());
}
}
return new ArrayList<>();
}
@Override
public Map<String,String> getValueTypeMap(String scriptId) {
public Map<String, String> getValueTypeMap(String scriptId) {
LambdaQueryWrapper<PqScriptCheckData> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.select(PqScriptCheckData::getValueType)
.eq(PqScriptCheckData::getScriptId, scriptId)
.eq(PqScriptCheckData::getEnable, DataStateEnum.ENABLE.getCode());
List<PqScriptCheckData> pqScriptCheckData = this.baseMapper.selectList(queryWrapper);
if(CollUtil.isEmpty(pqScriptCheckData)){
// throw new BusinessException(CommonResponseEnum.FAIL,"测试脚本项暂无配置");
if (CollUtil.isEmpty(pqScriptCheckData)) {
throw new BusinessException(DetectionResponseEnum.SCRIPT_CHECK_DATA_NOT_EXIST);
}
List<String> valueTypeList = pqScriptCheckData.stream().map(PqScriptCheckData::getValueType).distinct().collect(Collectors.toList());
LambdaQueryWrapper<DictTree> dictTreeLambdaQueryWrapper = new LambdaQueryWrapper<>();
dictTreeLambdaQueryWrapper.in(DictTree::getId,valueTypeList).eq(DictTree::getState,DataStateEnum.DELETED.getCode());
dictTreeLambdaQueryWrapper.in(DictTree::getId, valueTypeList).eq(DictTree::getState, DataStateEnum.DELETED.getCode());
List<DictTree> dictTreeList = dictTreeMapper.selectList(dictTreeLambdaQueryWrapper);
Map<String,String> map = dictTreeList.stream().collect(Collectors.toMap(DictTree::getCode,DictTree::getId));
Map<String, String> map = dictTreeList.stream().collect(Collectors.toMap(DictTree::getCode, DictTree::getId));
return map;
}
@@ -109,17 +118,31 @@ public class PqScriptCheckDataServiceImpl extends ServiceImpl<PqScriptCheckDataM
LambdaQueryWrapper<PqScriptCheckData> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper
.eq(PqScriptCheckData::getScriptId, param.getScriptId())
.eq(ObjectUtil.isNotNull(param.getIndex()),PqScriptCheckData::getScriptIndex, param.getIndex())
.eq(ObjectUtil.isNotNull(param.getIndex()), PqScriptCheckData::getScriptIndex, param.getIndex())
.eq(PqScriptCheckData::getValueType, param.getValueType())
.eq(PqScriptCheckData::getPhase, param.getPhase())
.eq(PqScriptCheckData::getEnable, DataStateEnum.ENABLE.getCode());
PqScriptCheckData data = this.getBaseMapper().selectOne(queryWrapper);
if(ObjectUtil.isNotNull(data)){
if (ObjectUtil.isNotNull(data)) {
return data.getValue();
}
return null;
return null;
}
@Override
public List<PqScriptCheckData> listCheckData(String scriptId, List<Integer> indexList) {
LambdaQueryWrapper<PqScriptCheckData> queryWrapper = new LambdaQueryWrapper<PqScriptCheckData>()
.eq(PqScriptCheckData::getScriptId, scriptId)
.eq(PqScriptCheckData::getEnable, DataStateEnum.ENABLE.getCode())
.eq(PqScriptCheckData::getErrorFlag, 1)
.in(PqScriptCheckData::getScriptIndex, indexList)
.orderByAsc(PqScriptCheckData::getHarmNum);
return this.list(queryWrapper);
}
@Override
public boolean deleteByScriptIds(List<String> ids) {
return this.remove(new LambdaQueryWrapper<PqScriptCheckData>().in(PqScriptCheckData::getScriptId, ids));
}
}

View File

@@ -10,9 +10,13 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.device.pojo.enums.CommonEnum;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.plan.mapper.AdPlanMapper;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.script.mapper.PqScriptCheckDataMapper;
import com.njcn.gather.script.mapper.PqScriptDtlsMapper;
import com.njcn.gather.script.mapper.PqScriptMapper;
@@ -24,12 +28,14 @@ import com.njcn.gather.script.pojo.po.PqScript;
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.script.pojo.po.SourceIssue;
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.script.util.ScriptDtlsDesc;
import com.njcn.gather.script.util.ThreePhaseUnbalance;
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
import com.njcn.gather.system.dictionary.service.IDictTreeService;
import com.njcn.gather.system.pojo.enums.DicDataEnum;
import com.njcn.gather.type.pojo.po.DevType;
import com.njcn.gather.type.service.IDevTypeService;
import lombok.RequiredArgsConstructor;
@@ -83,6 +89,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
private final PqScriptCheckDataMapper pqScriptCheckDataMapper;
private final IDevTypeService devTypeService;
private final IDictTreeService dictTreeService;
private final AdPlanMapper adPlanMapper;
@Override
@Transactional
@@ -125,6 +132,13 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
@Override
public List<SourceIssue> listSourceIssue(PqScriptIssueParam param) {
String dataType;
if (StrUtil.isNotBlank(param.getPlanId())) {
AdPlan plan = adPlanMapper.selectById(param.getPlanId());
dataType = plan.getDatasourceId();
} else {
dataType = "real";
}
List<SourceIssue> sourceIssues = new ArrayList<>();
Set<Double> voltSet = new HashSet<>(1);
Set<Double> currSet = new HashSet<>(1);
@@ -191,6 +205,13 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkDataParam.setScriptId(freqDtls.getScriptId());
checkDataParam.setIndex(freqDtls.getScriptIndex());
checkDataParam.setIsValueTypeName(true);
if (DicDataEnum.F.getCode().equals(issue.getType()) || DicDataEnum.VOLTAGE.getCode().equals(issue.getType())) {
checkDataParam.setDataType("avg");
issue.setDataType("avg");
} else {
checkDataParam.setDataType(dataType);
issue.setDataType(dataType);
}
issue.setDevValueTypeList(pqScriptCheckDataService.getValueType(checkDataParam));
issue.setDesc(ScriptDtlsDesc.getStringBuffer(value, true, isValueType).toString());
issue.setScriptId(freqDtls.getScriptId());
@@ -274,7 +295,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
data.setScriptId(sourceIssue.getScriptId());
data.setScriptIndex(i);
data.setValueType(checkData.getValueType());
data.setDataType(checkData.getDataType());
data.setPhase(checkData.getPhase());
data.setValue(checkData.getValue());
data.setHarmNum(checkData.getHarmNum());
@@ -430,10 +450,8 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
checkData.setPhase("T");
checkData.setDataType(channelListDTO.getDataType());
if (CollUtil.isNotEmpty(checkArchive)) {
checkData.setValue(checkArchive.get(0).getValue());
checkData.setDataType(checkArchive.get(0).getDataType());
} else {
checkData.setValue(sourceIssue.getFFreq());
}
@@ -463,7 +481,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
checkData.setValue(listDTO.getFPhase());
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
setCheckValue(checkArchive, checkData, listDTO);
@@ -601,7 +618,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
private void setCheck(List<PqScriptDtlsParam.CheckData> info, PqScriptDtlsParam.CheckData checkData, PqScriptDtlsParam.CheckData channelListDTO, List<PqScriptCheckData> checkArchive, PqScriptDtlsParam.ChannelListDTO listDTO) {
checkData.setPhase(listDTO.getChannelType().substring(1, 2).toUpperCase());
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
setCheckValue(checkArchive, checkData, listDTO);
@@ -625,7 +641,8 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
return this.update(new LambdaUpdateWrapper<PqScriptDtls>()
.set(PqScriptDtls::getEnable, param.getEnable())
.eq(PqScriptDtls::getScriptId, param.getScriptId())
.eq(PqScriptDtls::getScriptIndex, param.getIndex())
.eq(ObjectUtil.isNotNull(param.getIndex()), PqScriptDtls::getScriptIndex, param.getIndex())
.eq(ObjectUtil.isNotNull(param.getScriptType()), PqScriptDtls::getScriptType, param.getScriptType())
);
}
@@ -681,6 +698,30 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
return ScriptDtlsDesc.getStringBuffer(pqScriptDtls, true, isValueType).toString();
}
@Override
public List<String> getScriptToIcdCheckInfo(PreDetectionParam param) {
PqScriptIssueParam issueParam = new PqScriptIssueParam();
// issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.FORMAL_TEST.getValue());
List<SourceIssue> sourceIssues = this.listSourceIssue(issueParam);
Set<String> dataTypeSet = new HashSet<>();
sourceIssues.forEach(x -> {
dataTypeSet.addAll(x.getDevValueTypeList());
});
return dataTypeSet.stream().collect(Collectors.toList());
}
@Override
public List<PqScriptDtlDataVO> getScriptDtlsDataList(String scriptId) {
return this.baseMapper.getScriptDtlsDataList(scriptId);
}
private void unbanCheck(List<PqScriptDtlsParam.CheckData> info,
PqScriptDtlsParam.CheckData channelListDTO,
List<PqScriptDtlsParam.ChannelListDTO> list,
@@ -692,7 +733,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
checkData.setPhase("T");
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
List<PqScriptDtlsParam.ChannelListDTO> channelA = list.stream().filter(x -> x.getChannelType().contains("a")).collect(Collectors.toList());
@@ -706,7 +746,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
}
if (CollUtil.isNotEmpty(checkArchive)) {
checkData.setValue(checkArchive.get(0).getValue());
checkData.setDataType(checkArchive.get(0).getDataType());
}
info.add(checkData);
}
@@ -725,13 +764,11 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
checkData.setPhase(listDTO.getChannelType().substring(1, 2).toUpperCase());
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
List<PqScriptCheckData> collect = checkArchive.stream().filter(x -> x.getPhase().equals(listDTO.getChannelType().substring(1, 2).toUpperCase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(collect)) {
checkData.setValue(collect.get(0).getValue());
checkData.setDataType(collect.get(0).getDataType());
} else {
if (flyDeltaV) {
checkData.setValue(0.0);
@@ -761,7 +798,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setEnable(channelListDTO.getEnable());
checkData.setValue(inharmModel.getFAmp());
checkData.setHarmNum(inharmModel.getInharm());
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
setCheckValue(checkArchive, checkData, listDTO);
@@ -776,7 +812,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
List<PqScriptCheckData> collect = checkArchive.stream().filter(x -> x.getPhase().equals(listDTO.getChannelType().substring(1, 2).toUpperCase())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(collect)) {
checkData.setValue(collect.get(0).getValue());
checkData.setDataType(collect.get(0).getDataType());
}
checkData.setPhase(listDTO.getChannelType().substring(1, 2).toUpperCase());
}
@@ -798,7 +833,6 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setValue(harmModel.getFAmp());
checkData.setPhase(listDTO.getChannelType().substring(1, 2).toUpperCase());
checkData.setHarmNum(harmModel.getHarm());
checkData.setDataType(channelListDTO.getDataType());
checkData.setValueType(channelListDTO.getValueType());
checkData.setPid(channelListDTO.getPid());
setCheckValue(checkArchive, checkData, listDTO);
@@ -859,7 +893,8 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
pqScriptDtls = this.list(queryWrapper);
} else {
//先获取检测脚本类型是否相对值 true相对值 false绝对值相对值要乘额定值,绝对值不需要处理)
queryWrapper.eq(PqScriptDtls::getScriptId, param.getScriptId());
queryWrapper.eq(PqScriptDtls::getScriptId, param.getScriptId())
.in(CollUtil.isNotEmpty(param.getIndexList()), PqScriptDtls::getScriptIndex, param.getIndexList());
pqScriptDtls = this.getBaseMapper().selectJoinList(PqScriptDtls.class, queryWrapper);
if (CollUtil.isNotEmpty(param.getDevIds()) || (ObjectUtil.isNotNull(param.getType()) && param.getType() == 1)) {
Boolean isValueType = pqScriptMapper.selectScriptIsValueType(param.getScriptId());
@@ -981,9 +1016,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
dipDataDTO.setFTransValue(dip.getTransValue());
if (devFly) {
if (isValueType) {
dipDataDTO.setFTransValue(dip.getTransValue() * dtls.getValue() * 0.01);
} else {
dipDataDTO.setFTransValue(dip.getTransValue());
} else {
dipDataDTO.setFTransValue(NumberUtil.round(dip.getTransValue() / dtls.getValue(), 4).doubleValue());
}
}
// 1.0/频率*持续时间(周波)= 暂态持续时间s

View File

@@ -12,6 +12,7 @@ import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.script.mapper.PqScriptMapper;
import com.njcn.gather.script.pojo.param.PqScriptParam;
import com.njcn.gather.script.pojo.po.PqScript;
import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.script.service.IPqScriptService;
import com.njcn.web.factory.PageFactory;
@@ -37,6 +38,7 @@ import java.util.stream.Collectors;
public class PqScriptServiceImpl extends ServiceImpl<PqScriptMapper, PqScript> implements IPqScriptService {
private final IPqScriptDtlsService pqScriptDtlsService;
private final IPqScriptCheckDataService pqScriptCheckDataService;
@Override
public Page<PqScript> listPqScript(PqScriptParam.QueryParam param) {
@@ -58,17 +60,22 @@ public class PqScriptServiceImpl extends ServiceImpl<PqScriptMapper, PqScript> i
@Override
@Transactional
public Boolean addPqScript(PqScriptParam param) {
public String addPqScript(PqScriptParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, false);
PqScript pqScript = new PqScript();
BeanUtils.copyProperties(param, pqScript);
pqScript.setStandardTime(LocalDate.of(Integer.parseInt(param.getStandardTime()), 1, 1));
pqScript.setState(DataStateEnum.ENABLE.getCode());
return this.save(pqScript);
this.save(pqScript);
return pqScript.getId();
}
@Override
@Transactional
public boolean updatePqScript(PqScriptParam.UpdateParam param) {
param.setName(param.getName().trim());
this.checkRepeat(param, true);
PqScript pqScript = new PqScript();
BeanUtils.copyProperties(param, pqScript);
pqScript.setStandardTime(LocalDate.of(Integer.parseInt(param.getStandardTime()), 1, 1));
@@ -85,6 +92,8 @@ public class PqScriptServiceImpl extends ServiceImpl<PqScriptMapper, PqScript> i
}
//删除对应的脚本详情
pqScriptDtlsService.deletePqScriptDtlsByScriptId(ids);
//删除对应的checkdata
pqScriptCheckDataService.deleteByScriptIds(ids);
LambdaUpdateWrapper<PqScript> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.set(PqScript::getState, DataStateEnum.DELETED.getCode())
.in(PqScript::getId, ids);
@@ -118,4 +127,25 @@ public class PqScriptServiceImpl extends ServiceImpl<PqScriptMapper, PqScript> i
public PqScript getPqScriptByName(String name) {
return this.lambdaQuery().eq(PqScript::getName, name).eq(PqScript::getState, DataStateEnum.ENABLE.getCode()).one();
}
/**
* 检查脚本是否重复
*
* @param param 计划参数
* @param isExcludeSelf 是否排除自己
*/
private void checkRepeat(PqScriptParam param, boolean isExcludeSelf) {
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("state", DataStateEnum.ENABLE.getCode());
wrapper.eq("name", param.getName());
if (isExcludeSelf) {
if(param instanceof PqScriptParam.UpdateParam){
wrapper.ne("id", ((PqScriptParam.UpdateParam) param).getId());
}
}
int count = this.count(wrapper);
if (count > 0) {
throw new BusinessException(DetectionResponseEnum.SCRIPT_NAME_REPEAT);
}
}
}

View File

@@ -96,7 +96,7 @@ public class PqSourceServiceImpl extends ServiceImpl<PqSourceMapper, PqSource> i
@Override
public List<Map<String, Object>> listAllPqSource(String patternId) {
List<PqSource> pqSourceList = this.lambdaQuery().eq(PqSource::getPattern, patternId).eq(PqSource::getState, DataStateEnum.ENABLE.getCode()).list();
List<PqSource> pqSourceList = this.lambdaQuery().eq(PqSource::getPattern, patternId).orderByAsc(PqSource::getCreateTime).eq(PqSource::getState, DataStateEnum.ENABLE.getCode()).list();
List<Map<String, Object>> result = pqSourceList.stream().map(pqSource -> {
Map<String, Object> map = new HashMap<>();
map.put("id", pqSource.getId());

View File

@@ -20,6 +20,7 @@ import javax.validation.constraints.Pattern;
public class DevTypeParam {
@ApiModelProperty(value = "名称", required = true)
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
@Pattern(regexp = PatternRegex.DEV_TYPE_NAME_REGEX, message = DetectionValidMessage.DEV_TYPE_NAME_FORMAT_ERROR)
private String name;
@ApiModelProperty(value = "设备关联的ICD", required = true)
@@ -44,7 +45,6 @@ public class DevTypeParam {
private Integer devChns;
@ApiModelProperty(value = "报告模板")
// @NotBlank(message = "报告模板不能为空")
private String reportName;
/**

View File

@@ -73,6 +73,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
@Override
@Transactional
public boolean addDevType(DevTypeParam addParam) {
addParam.setName(addParam.getName().trim());
this.checkRepeat(addParam, false);
DevType devType = new DevType();
BeanUtil.copyProperties(addParam, devType);
@@ -83,6 +84,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
@Override
@Transactional
public boolean updateDevType(DevTypeParam.UpdateParam updateParam) {
updateParam.setName(updateParam.getName().trim());
this.checkRepeat(updateParam, true);
DevType devType = new DevType();
BeanUtil.copyProperties(updateParam, devType);

View File

@@ -0,0 +1,105 @@
package com.njcn.gather.advice;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.system.log.service.ISysLogAuditService;
import com.njcn.web.utils.HttpServletUtil;
import com.njcn.web.utils.ReflectCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
/**
* @author caozehui
* @data 2024-12-2
*/
@Slf4j
@ControllerAdvice
public class LogAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private ISysLogAuditService logService;
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
4, 8, 30, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
// 队列满时由主线程执行
new ThreadPoolExecutor.CallerRunsPolicy()
);
/**
* 无需审计记录的操作,比如根据客户端获取客户端信息
*/
private final static List<String> UN_LOG_INFO = Collections.singletonList("未知业务");
/**
* controller返回的响应体包含的状态码而非全局异常捕获器处抛出来的状态码
*/
private final static List<String> FILTER_CODE = Arrays.asList(CommonResponseEnum.SUCCESS.getCode(), CommonResponseEnum.FAIL.getCode(), CommonResponseEnum.NO_DATA.getCode());
/**
* 判断下结果,是不是成功
*
* @param returnType 返回类型包含大量信息controller、method、result等等
* @param converterType 消息转换器类型目前配置的是Jackson
*/
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
/**
* 拦截所有请求成功的操作进行日志入库处理
* 需要 用户标识、事件描述、事件结果、操作IP、事件类型、事件严重度、操作时间、操作类型
*
* @param body .
* @param returnType .
* @param selectedContentType .
* @param selectedConverterType .
* @param request .
* @param response .
* @return .
*/
@Override
public Object beforeBodyWrite(Object body, @Nonnull MethodParameter returnType, @Nonnull MediaType selectedContentType, @Nonnull Class selectedConverterType, @Nonnull ServerHttpRequest request, @Nonnull ServerHttpResponse response) {
if (body instanceof HttpResult) {
HttpResult<?> httpResult = (HttpResult<?>) body;
if (FILTER_CODE.contains(httpResult.getCode())) {
// 传递上下文
HttpServletRequest httpServletRequest = HttpServletUtil.getRequest();
String methodDescribe = ReflectCommonUtil.getMethodDescribeByMethod(returnType.getMethod());
if (!UN_LOG_INFO.contains(methodDescribe)) {
Future<?> future = executor.submit(() -> {
HttpServletUtil.setRequest(httpServletRequest);
logService.recodeAdviceLog(returnType, httpResult, methodDescribe);
});
try {
// 抛出 ExecutionException
future.get();
} catch (ExecutionException | InterruptedException e) {
log.error("保存审计日志异常,异常为:"+e.getMessage());
}
}
}
}
return body;
}
}

View File

@@ -6,11 +6,14 @@ 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.system.log.service.ISysLogAuditService;
import com.njcn.web.utils.HttpResultUtil;
import com.njcn.web.utils.HttpServletUtil;
import com.njcn.web.utils.ReflectCommonUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
@@ -18,6 +21,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
@@ -25,6 +29,7 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -40,7 +45,16 @@ import java.util.stream.Stream;
@RestControllerAdvice
public class GlobalBusinessExceptionHandler {
// private final ILogService logService;
@Resource
private final ISysLogAuditService sysLogAuditService;
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
4, 8, 30, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
// 队列满时由主线程执行
new ThreadPoolExecutor.CallerRunsPolicy()
);
/**
* 捕获业务功能异常,通常为业务数据抛出的异常
@@ -48,16 +62,9 @@ public class GlobalBusinessExceptionHandler {
* @param businessException 业务异常
*/
@ExceptionHandler(BusinessException.class)
public HttpResult<String> handleBusinessException(HttpServletRequest httpServletRequest, BusinessException businessException) {
public HttpResult<String> handleBusinessException(BusinessException businessException) {
String operate = ReflectCommonUtil.getMethodDescribeByException(businessException);
// logService.recodeBusinessExceptionLog(businessException, httpServletRequest, businessException.getMessage());
//判断方法上是否有自定义注解,做特殊处理
Method method = ReflectCommonUtil.getMethod(businessException);
// if (!Objects.isNull(method)){
// if(method.isAnnotationPresent(ReturnMsg.class)){
// return HttpResultUtil.assembleResult(businessException.getCode(), null, StrFormatter.format("{}",businessException.getMessage()));
// }
// }
recodeBusinessExceptionLog(businessException, businessException.getMessage());
return HttpResultUtil.assembleBusinessExceptionResult(businessException, null, operate);
}
@@ -68,9 +75,9 @@ public class GlobalBusinessExceptionHandler {
* @param nullPointerException 空指针异常
*/
@ExceptionHandler(NullPointerException.class)
public HttpResult<String> handleNullPointerException(HttpServletRequest httpServletRequest, NullPointerException nullPointerException) {
public HttpResult<String> handleNullPointerException(NullPointerException nullPointerException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage(), nullPointerException);
// logService.recodeBusinessExceptionLog(nullPointerException, httpServletRequest, CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage());
recodeBusinessExceptionLog(nullPointerException, CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NULL_POINTER_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(nullPointerException));
}
@@ -80,9 +87,9 @@ public class GlobalBusinessExceptionHandler {
* @param arithmeticException 算数运算异常由于除数为0引起的异常
*/
@ExceptionHandler(ArithmeticException.class)
public HttpResult<String> handleArithmeticException(HttpServletRequest httpServletRequest, ArithmeticException arithmeticException) {
public HttpResult<String> handleArithmeticException(ArithmeticException arithmeticException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage(), arithmeticException);
// logService.recodeBusinessExceptionLog(arithmeticException, httpServletRequest, CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage());
recodeBusinessExceptionLog(arithmeticException, CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ARITHMETIC_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(arithmeticException));
}
@@ -92,9 +99,9 @@ public class GlobalBusinessExceptionHandler {
* @param classCastException 类型转换异常
*/
@ExceptionHandler(ClassCastException.class)
public HttpResult<String> handleClassCastException(HttpServletRequest httpServletRequest, ClassCastException classCastException) {
public HttpResult<String> handleClassCastException(ClassCastException classCastException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage(), classCastException);
// logService.recodeBusinessExceptionLog(classCastException, httpServletRequest, CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage());
recodeBusinessExceptionLog(classCastException, CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.CLASS_CAST_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(classCastException));
}
@@ -105,9 +112,9 @@ public class GlobalBusinessExceptionHandler {
* @param indexOutOfBoundsException 索引下标越界异常
*/
@ExceptionHandler(IndexOutOfBoundsException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, IndexOutOfBoundsException indexOutOfBoundsException) {
public HttpResult<String> handleIndexOutOfBoundsException(IndexOutOfBoundsException indexOutOfBoundsException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage(), indexOutOfBoundsException);
// logService.recodeBusinessExceptionLog(indexOutOfBoundsException, httpServletRequest, CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage());
recodeBusinessExceptionLog(indexOutOfBoundsException, CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(indexOutOfBoundsException));
}
@@ -117,10 +124,10 @@ public class GlobalBusinessExceptionHandler {
* @param httpMediaTypeNotSupportedException 请求中参数的媒体方式不支持异常
*/
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public HttpResult<String> httpMediaTypeNotSupportedExceptionHandler(HttpServletRequest httpServletRequest, HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException) {
public HttpResult<String> httpMediaTypeNotSupportedExceptionHandler(HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage(), httpMediaTypeNotSupportedException);
// 然后提取错误提示信息进行返回
// logService.recodeBusinessExceptionLog(httpMediaTypeNotSupportedException, httpServletRequest, CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage());
recodeBusinessExceptionLog(httpMediaTypeNotSupportedException, CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(httpMediaTypeNotSupportedException));
}
@@ -131,13 +138,13 @@ public class GlobalBusinessExceptionHandler {
* @param methodArgumentNotValidException 参数校验异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public HttpResult<String> methodArgumentNotValidExceptionHandler(HttpServletRequest httpServletRequest, MethodArgumentNotValidException methodArgumentNotValidException) {
public HttpResult<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException) {
// 从异常对象中拿到allErrors数据
String messages = methodArgumentNotValidException.getBindingResult().getAllErrors()
.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(""));
// 然后提取错误提示信息进行返回
LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages);
// logService.recodeBusinessExceptionLog(methodArgumentNotValidException, httpServletRequest, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
recodeBusinessExceptionLog(methodArgumentNotValidException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages, ControllerUtil.getMethodArgumentNotValidException(methodArgumentNotValidException));
}
@@ -148,7 +155,7 @@ public class GlobalBusinessExceptionHandler {
* @param constraintViolationException 参数校验异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public HttpResult<String> constraintViolationExceptionExceptionHandler(HttpServletRequest httpServletRequest, ConstraintViolationException constraintViolationException) {
public HttpResult<String> constraintViolationExceptionExceptionHandler(ConstraintViolationException constraintViolationException) {
String exceptionMessage = constraintViolationException.getMessage();
StringBuilder messages = new StringBuilder();
if (exceptionMessage.indexOf(StrUtil.COMMA) > 0) {
@@ -161,7 +168,7 @@ public class GlobalBusinessExceptionHandler {
}
// 然后提取错误提示信息进行返回
LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages);
// logService.recodeBusinessExceptionLog(constraintViolationException, httpServletRequest, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
recodeBusinessExceptionLog(constraintViolationException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage());
List<ConstraintViolation<?>> constraintViolationList = new ArrayList<>(constraintViolationException.getConstraintViolations());
ConstraintViolation<?> constraintViolation = constraintViolationList.get(0);
Class<?> rootBeanClass = constraintViolation.getRootBeanClass();
@@ -182,24 +189,12 @@ public class GlobalBusinessExceptionHandler {
* @param illegalArgumentException 参数校验异常
*/
@ExceptionHandler(IllegalArgumentException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, IllegalArgumentException illegalArgumentException) {
public HttpResult<String> handleIndexOutOfBoundsException(IllegalArgumentException illegalArgumentException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), illegalArgumentException);
// logService.recodeBusinessExceptionLog(illegalArgumentException, httpServletRequest, CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage());
recodeBusinessExceptionLog(illegalArgumentException, CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, illegalArgumentException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(illegalArgumentException));
}
// /**
// * 表格校验异常
// *
// * @param excelAnalysisException 表格校验异常
// */
// @ExceptionHandler(ExcelAnalysisException.class)
// public HttpResult<String> handleExcelAnalysisException(HttpServletRequest httpServletRequest, ExcelAnalysisException excelAnalysisException) {
// LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), excelAnalysisException);
// // logService.recodeBusinessExceptionLog(excelAnalysisException, httpServletRequest,CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage());
// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, excelAnalysisException.getCause().getMessage(), ReflectCommonUtil.getMethodDescribeByException(excelAnalysisException));
// }
/**
* 未声明异常捕捉
@@ -207,7 +202,7 @@ public class GlobalBusinessExceptionHandler {
* @param exception 未声明异常
*/
@ExceptionHandler(Exception.class)
public HttpResult<String> handleException(HttpServletRequest httpServletRequest, Exception exception) {
public HttpResult<String> handleException(Exception exception) {
//针对fallbackFactory降级异常特殊处理
Exception tempException = exception;
String exceptionCause = CommonResponseEnum.UN_DECLARE.getMessage();
@@ -224,7 +219,7 @@ public class GlobalBusinessExceptionHandler {
}
}
LogUtil.logExceptionStackInfo(exceptionCause, tempException);
// logService.recodeBusinessExceptionLog(tempException, httpServletRequest, exceptionCause);
recodeBusinessExceptionLog(exception, exceptionCause);
//判断方法上是否有自定义注解,做特殊处理
// Method method = ReflectCommonUtil.getMethod(exception);
// if (!Objects.isNull(method)){
@@ -236,18 +231,30 @@ public class GlobalBusinessExceptionHandler {
}
/**
* json解析异常
*
* @param jsonException json参数
*/
@ExceptionHandler(JSONException.class)
public HttpResult<String> handleIndexOutOfBoundsException(HttpServletRequest httpServletRequest, JSONException jsonException) {
public HttpResult<String> handleIndexOutOfBoundsException(JSONException jsonException) {
LogUtil.logExceptionStackInfo(CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage(), jsonException);
// logService.recodeBusinessExceptionLog(jsonException, httpServletRequest, CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage());
recodeBusinessExceptionLog(jsonException, CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.JSON_CONVERT_EXCEPTION, jsonException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(jsonException));
}
private void recodeBusinessExceptionLog(Exception businessException, String methodDescribe) {
HttpServletRequest httpServletRequest = HttpServletUtil.getRequest();
Future<?> future = executor.submit(() -> {
HttpServletUtil.setRequest(httpServletRequest);
sysLogAuditService.recodeBusinessExceptionLog(businessException, methodDescribe);
});
try {
// 抛出 ExecutionException
future.get();
} catch (ExecutionException | InterruptedException e) {
log.error("保存审计日志异常,异常为:" + e.getMessage());
}
}
}

View File

@@ -6,7 +6,7 @@ spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.24:13306/pqs91001?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=CTT
url: jdbc:mysql://192.168.1.24:13306/pqs91003?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=CTT
username: root
password: njcnpqs
# url: jdbc:mysql://localhost:3306/pqs91001?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=CTT

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