33 Commits

Author SHA1 Message Date
caozehui
d2388576a9 资源管理微调 2026-05-28 16:27:04 +08:00
caozehui
7f21049d0f 检测计划统计功能 2026-05-28 13:27:15 +08:00
caozehui
49ca27d994 微调 2026-05-27 11:20:44 +08:00
3cb4a46a16 refactor(report): 优化报告生成服务的安全性和文档处理
- 添加 FilePathSanitizer 工具类,防止路径穿越和非法字符问题
- 在报告目录路径构建中使用安全的文件名处理
- 为 BookmarkEnum 添加排序字段和注释说明
- 改进书签处理排序逻辑,使用 sort 字段而非依赖枚举声明顺序
- 添加批量处理的语义说明文档
- 优化数据处理流程中的哨兵标记机制
- 为 WordReportService 接口添加详细的资源管理契约文档
- 改进 dealDataLine 方法的职责分离和参数命名
- 修复测试结果详情书签键值引用错误
2026-05-26 19:20:03 +08:00
caozehui
13677f21d9 微调 2026-05-26 15:41:28 +08:00
caozehui
a1941a375b 检测计划统计功能 2026-05-26 09:23:04 +08:00
caozehui
9dc8ecd873 Reapply "统一sourceId"
This reverts commit 7c6c103f17.
2026-05-25 18:41:39 +08:00
caozehui
7c6c103f17 Revert "统一sourceId"
This reverts commit 1cfea7fd6c.
2026-05-25 18:41:19 +08:00
caozehui
b113788e54 Revert "报告生成、检测结果查询调整"
This reverts commit 282f9cf4eb.
2026-05-25 18:41:15 +08:00
caozehui
599edde008 Revert "微调"
This reverts commit 6fd180b4d4.
2026-05-25 18:41:11 +08:00
caozehui
cc0b685c66 Reapply "统一sourceId"
This reverts commit c651b18e72.
2026-05-25 18:41:07 +08:00
caozehui
29b0a4f966 Merge remote-tracking branch 'origin/master' 2026-05-25 18:39:25 +08:00
caozehui
c651b18e72 Revert "统一sourceId"
This reverts commit 1cfea7fd6c.
2026-05-25 18:39:19 +08:00
caozehui
6fd180b4d4 微调 2026-05-25 16:20:06 +08:00
caozehui
282f9cf4eb 报告生成、检测结果查询调整 2026-05-25 14:27:15 +08:00
caozehui
1cfea7fd6c 统一sourceId 2026-05-12 14:34:57 +08:00
caozehui
251e302e59 统一sourceId 2026-05-12 10:36:44 +08:00
caozehui
873e920add 微调 2026-04-22 09:36:35 +08:00
caozehui
fd7c6ada6b 回滚 2026-04-13 15:41:37 +08:00
caozehui
c148bddfc9 Revert "微调"
This reverts commit 4110a835c8.
2026-04-13 15:39:15 +08:00
caozehui
f0857b7c46 Revert "微调"
This reverts commit ef757c52ea.
2026-04-13 15:38:55 +08:00
9b1c6f61e6 revert e78ce544e3
revert 微调
2026-04-13 15:31:24 +08:00
caozehui
3f72c52cdc Revert "微调"
This reverts commit e78ce544e3.
2026-04-13 15:27:55 +08:00
caozehui
ef757c52ea 微调 2026-04-10 15:13:22 +08:00
caozehui
4110a835c8 微调 2026-04-10 14:13:27 +08:00
caozehui
e78ce544e3 微调 2026-03-26 13:23:02 +08:00
caozehui
c10d54e79a 微调 2026-01-30 16:11:14 +08:00
caozehui
2796558040 重采方案 2026-01-26 10:16:48 +08:00
caozehui
920a808729 微调 2026-01-22 15:25:48 +08:00
caozehui
8e24ac4b71 脚本单独配置BC暂态时左侧树形列表展示不全问题 2026-01-22 15:09:02 +08:00
caozehui
3eb2736edb 微调 2026-01-22 11:26:25 +08:00
caozehui
8c3eba9224 平均值时移除误差较大的几组数据 2026-01-21 14:01:07 +08:00
caozehui
6288aa565e 系数下发 2026-01-19 14:23:23 +08:00
68 changed files with 3077 additions and 321 deletions

5
.gitignore vendored
View File

@@ -48,3 +48,8 @@ rebel.xml
/.fastRequest/collections/Root/Default Group/directory.json
/.fastRequest/collections/Root/directory.json
/.fastRequest/config/fastRequestCurrentProjectConfig.json
# 个人工作文档,不与团队共享
CLAUDE.md
docs/
data/

View File

@@ -155,4 +155,25 @@ public class PreDetectionController extends BaseController {
LogUtil.njcnDebug(log, "{}", methodDescribe);
preDetectionService.exportAlignData();
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@GetMapping("/canCoefficient")
@ApiOperation("比对模式是否能够进行系数校验")
public HttpResult<Boolean> canCoefficient() {
String methodDescribe = getMethodDescribe("canCoefficient");
LogUtil.njcnDebug(log, "{}", methodDescribe);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, preDetectionService.getCanCoefficient(), methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@GetMapping("/startCoefficient")
@ApiOperation("比对模式开启系数校验")
public HttpResult<String> startCoefficient() {
String methodDescribe = getMethodDescribe("startCoefficient");
LogUtil.njcnDebug(log, "{}", methodDescribe);
preDetectionService.startCoefficient();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
}

View File

@@ -11,7 +11,9 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.HashBiMap;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.pojo.dto.DevXiNumData;
import com.njcn.gather.detection.pojo.dto.WaveCommandDTO;
import com.njcn.gather.detection.pojo.dto.WaveResultDTO;
import com.njcn.gather.detection.pojo.enums.*;
@@ -24,15 +26,17 @@ import com.njcn.gather.detection.pojo.vo.*;
import com.njcn.gather.detection.service.IAdPariService;
import com.njcn.gather.detection.service.impl.DetectionServiceImpl;
import com.njcn.gather.detection.util.DetectionUtil;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.detection.util.socket.MsgUtil;
import com.njcn.gather.detection.util.socket.SocketManager;
import com.njcn.gather.detection.util.socket.*;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import com.njcn.gather.device.pojo.enums.PatternEnum;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
import com.njcn.gather.device.pojo.po.PqStandardDevGainRecord;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.device.service.IPqStandardDevGainRecordService;
import com.njcn.gather.device.service.IPqStandardDevGainService;
import com.njcn.gather.device.service.IPqStandardDevService;
import com.njcn.gather.monitor.pojo.po.PqMonitor;
import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.service.IAdPlanService;
@@ -42,6 +46,7 @@ import com.njcn.gather.storage.pojo.po.ContrastNonHarmonicResult;
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.config.PathConfig;
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;
@@ -53,7 +58,6 @@ import com.njcn.gather.tools.comtrade.comparewave.service.ICompareWaveService;
import com.njcn.gather.util.StorageUtil;
import com.njcn.web.utils.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
@@ -62,6 +66,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@@ -92,6 +97,8 @@ public class SocketContrastResponseService {
private final IAdPariService adPairService;
private final ICompareWaveService compareWaveService;
private final IAdPlanTestConfigService adPlanTestConfigService;
private final IPqStandardDevGainService pqStandardDevGainService;
private final IPqStandardDevGainRecordService pqStandardDevGainRecordService;
/**
@@ -120,8 +127,9 @@ public class SocketContrastResponseService {
// private SysRegRes contrastRegRes = null;
@Value("${report.reportDir}")
private String alignDataFilePath;
// @Value("${report.reportDir}")
// private String alignDataFilePath;
private final PathConfig pathConfig;
public static final Map<String, List<String>> testItemCodeMap = new HashMap() {{
put("FREQ", Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
@@ -185,6 +193,7 @@ public class SocketContrastResponseService {
FormalTestManager.isXu = param.getPhaseCheck() == 1 ? true : false;
// FormalTestManager.isXu = true;
FormalTestManager.nonWaveDataSourceEnum = null;
DetectionServiceImpl.vAndIResultMap = new HashMap<>();
String[] datasourceIds = FormalTestManager.currentTestPlan.getDatasourceId().split(",");
for (String datasourceId : datasourceIds) {
@@ -377,6 +386,10 @@ public class SocketContrastResponseService {
case RECORD_WAVE_STEP1:
this.recordWave(param, socketDataMsg);
break;
//系数校验
case Coefficient_Check:
this.coefficient(param, socketDataMsg);
break;
//退出关闭
case QUITE:
quitDeal(socketDataMsg, param);
@@ -1405,6 +1418,28 @@ public class SocketContrastResponseService {
pqDevService.updateResult(id1.split(CnSocketUtil.SPLIT_TAG)[0], param.getUserId());
});
FormalTestManager.isTesting = false;
if (CollUtil.isNotEmpty(DetectionServiceImpl.vAndIResultMap)) {
// 是否进行系数校准
//万一录波了这里就进不来了但是在误差处理的时候DetectionServiceImpl.vAndIResultMap该集合会保留不符合的结果
XiNumberManager.xiDevList.clear();
XiNumberManager.devXiNumDataMap.clear();
List<String> stdIpList = DetectionServiceImpl.vAndIResultMap.values().stream().map(DetectionServiceImpl.VAndIResult::getIp).collect(Collectors.toList());
XiNumberManager.xiDevList = FormalTestManager.standardDevList.stream().filter(d -> stdIpList.contains(d.getDevIP())).collect(Collectors.toList());
// 逐一设备向通讯模块要原始系数
SocketMsg<String> socketMsg = new SocketMsg<>();
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() + CnSocketUtil.CONTRAST_DEV_TAG, JSON.toJSONString(socketMsg));
FormalTestManager.currentStep = SourceOperateCodeEnum.Coefficient_Check;
}
}
} else {
// 配对关系入库
@@ -1682,6 +1717,160 @@ public class SocketContrastResponseService {
}
}
private void coefficient(PreDetectionParam param, SocketDataMsg socketDataMsg) {
SourceOperateCodeEnum sourceOperateCodeEnum = SourceOperateCodeEnum.getDictDataEnumByCode(socketDataMsg.getOperateCode());
SourceResponseCodeEnum dictDataEnumByCode = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
SocketMsg<String> xiSocket = new SocketMsg<>();
xiSocket.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
switch (Objects.requireNonNull(sourceOperateCodeEnum)) {
case DATA_CHNFACTOR$01:
//获取系数
switch (Objects.requireNonNull(dictDataEnumByCode)) {
case SUCCESS:
if (CollUtil.isNotEmpty(XiNumberManager.xiDevList)) {
List<DevXiNumData.GF> gfList = JSON.parseArray(socketDataMsg.getData(), DevXiNumData.GF.class);
DevXiNumData devXiNumData = new DevXiNumData();
String ip = XiNumberManager.xiDevList.get(0).getDevIP();
devXiNumData.setDevIP(ip);
//String stdMonitorId = DetectionServiceImpl.vAndIResultMap.keySet().stream().filter(key -> key.contains(ip)).findFirst().get();
List<PqStandardDevGain> pqStandardDevGainList = new ArrayList<>();
List<PqStandardDevGainRecord> recordList = new ArrayList<>();
for (int i = 0; i < gfList.size(); i++) {
DevXiNumData.GF gf = gfList.get(i);
String stdDevMonitorId = FormalTestManager.devIdMapComm.get(ip) + CnSocketUtil.SPLIT_TAG + (gf.getUMonitorPoint() + 1);
String devMonitorId = FormalTestManager.pairsIdMap.inverse().get(stdDevMonitorId);
PqStandardDevGain pqStandardDevGain = new PqStandardDevGain();
pqStandardDevGain.setStdDevMonitorId(stdDevMonitorId);
DevXiNumData.F f = gf.getF();
pqStandardDevGain.setUaGain(f.getUa_gain());
pqStandardDevGain.setUbGain(f.getUb_gain());
pqStandardDevGain.setUcGain(f.getUc_gain());
pqStandardDevGain.setU0Gain(f.getU0_gain());
pqStandardDevGain.setIaGain(f.getIa_gain());
pqStandardDevGain.setIbGain(f.getIb_gain());
pqStandardDevGain.setIcGain(f.getIc_gain());
pqStandardDevGain.setI0Gain(f.getI0_gain());
pqStandardDevGain.setUabGain(f.getUab_gain());
pqStandardDevGain.setUbcGain(f.getUbc_gain());
pqStandardDevGain.setUcaGain(f.getUca_gain());
pqStandardDevGain.setState(DataStateEnum.ENABLE.getCode());
pqStandardDevGainList.add(pqStandardDevGain);
DetectionServiceImpl.VAndIResult vAndIResult = DetectionServiceImpl.vAndIResultMap.get(ip + CnSocketUtil.SPLIT_TAG + (gf.getUMonitorPoint() + 1));
if (ObjectUtil.isNotNull(vAndIResult)) {
int maxNum = pqStandardDevGainRecordService.getMaxNum(stdDevMonitorId, devMonitorId);
PqStandardDevGainRecord record = new PqStandardDevGainRecord();
record.setStdDevMonitorId(stdDevMonitorId);
record.setDevMonitorId(devMonitorId);
record.setNum(maxNum + 1);
recordList.add(record);
updateGfList(f, vAndIResult, stdDevMonitorId, maxNum);
}
}
xiSocket.setOperateCode(SourceOperateCodeEnum.DATA_CHNFACTOR$02.getValue());
devXiNumData.setGf(gfList);
xiSocket.setData(JSON.toJSONString(devXiNumData));
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG, JSON.toJSONString(xiSocket));
// 原始系数入库
pqStandardDevGainService.add(pqStandardDevGainList);
pqStandardDevGainRecordService.addOrUpdate(recordList);
}
break;
case UNPROCESSED_BUSINESS:
break;
case NORMAL_RESPONSE:
break;
case DATA_RESOLVE:
break;
case COMMUNICATION_ERR:
break;
default:
break;
}
break;
case DATA_CHNFACTOR$02:
//系数下发后的响应
switch (Objects.requireNonNull(dictDataEnumByCode)) {
case SUCCESS:
//单台装置系数下发后,需要删除集合中存在的当前装置
XiNumberManager.xiDevList.remove(0);
//继续下发每台装置系数,只到集合为空
if (CollUtil.isNotEmpty(XiNumberManager.xiDevList)) {
xiSocket.setOperateCode(SourceOperateCodeEnum.DATA_CHNFACTOR$01.getValue());
xiSocket.setData(JSON.toJSONString(XiNumberManager.devXiNumDataMap.get(XiNumberManager.xiDevList.get(0))));
PreDetection preDetection = XiNumberManager.xiDevList.get(0);
Map<String, Object> map = new HashMap<>();
map.put("devIP", preDetection.getDevIP());
map.put("chnNum", preDetection.getDevChns());
xiSocket.setData(JSON.toJSONString(map));
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG, JSON.toJSONString(xiSocket));
} else {
//{"requestId":"Coefficient_Check","operateCode":"DATA_CHNFACTOR$02","data":"end","code":10200}
// 通知前端全部下发系数完成
}
break;
case UNPROCESSED_BUSINESS:
break;
case NORMAL_RESPONSE:
break;
case DATA_RESOLVE:
//quitSend(param);
break;
case COMMUNICATION_ERR:
break;
default:
break;
}
break;
// case DEV_DATA_REQUEST_02:
// //实时采集申请
// String data = socketDataMsg.getData();
// DevData devData = JSON.parseObject(data, DevData.class);
// if (ObjectUtil.isNotNull(dictDataEnumByCode)) {
// switch (dictDataEnumByCode) {
// case SUCCESS:
// if (devData.getResult()) {
// FormalTestManager.realDataXiList.add(devData);
// successComm.add(devData.getId());
// System.out.println(successComm.size() + " ==" + FormalTestManager.monitorIdListComm.size() + "FormalTestManager.realDataXiList:" + FormalTestManager.realDataXiList.size() + "当前步骤" + XiNumberManager.stepNumber);
// if (successComm.size() == FormalTestManager.monitorIdListComm.size()) {
// processData(param, xiSocket);
// }
// } else {
// System.out.println("系数校准抛除数据" + devData);
// }
// break;
// case UNPROCESSED_BUSINESS:
// WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(socketDataMsg));
// break;
// case NORMAL_RESPONSE:
// if (devData.getResult()) {
// FormalTestManager.realDataXiList.add(devData);
// } else {
// System.out.println("系数校准抛除数据" + devData);
// }
// break;
// default:
// xiSocket.setRequestId(socketDataMsg.getRequestId());
// xiSocket.setOperateCode(socketDataMsg.getOperateCode());
// xiSocket.setData(dictDataEnumByCode.getMessage());
// WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(xiSocket));
// break;
// }
// }
// break;
default:
WebServiceManager.sendUnknownErrorMessage(param.getUserPageId());
break;
}
}
/**
* 退出检测返回
@@ -1856,13 +2045,13 @@ public class SocketContrastResponseService {
*/
private Integer getTargetCount() {
if (FormalTestManager.isPstData) {
return FormalTestManager.curretntTestPlanConfig.getFlicker();
return FormalTestManager.curretntTestPlanConfig.getFlicker() * 2;
}
if (ObjectUtil.isNotNull(FormalTestManager.nonWaveDataSourceEnum)) {
if (FormalTestManager.nonWaveDataSourceEnum == DataSourceEnum.REAL_DATA) {
return FormalTestManager.curretntTestPlanConfig.getRealTime();
return FormalTestManager.curretntTestPlanConfig.getRealTime() * 2;
} else {
return FormalTestManager.curretntTestPlanConfig.getStatistics();
return FormalTestManager.curretntTestPlanConfig.getStatistics() * 2;
}
}
return -1;
@@ -1948,8 +2137,13 @@ public class SocketContrastResponseService {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
if (DetectionCodeEnum.STAR.getCode().equals(monitorListDTO.getConnection())) {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
}
}
}
@@ -2052,8 +2246,13 @@ public class SocketContrastResponseService {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
if (DetectionCodeEnum.STAR.getCode().equals(monitorListDTO.getConnection())) {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
}
}
}
@@ -2116,7 +2315,7 @@ public class SocketContrastResponseService {
});
});
ExcelUtil.saveExcel(alignDataFilePath, "对齐数据.xlsx", sheetsList);
ExcelUtil.saveExcel(pathConfig.getDataPath(), "对齐数据.xlsx", sheetsList);
}
/**
@@ -2273,8 +2472,13 @@ public class SocketContrastResponseService {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
if (DetectionCodeEnum.STAR.getCode().equals(monitorListDTO.getConnection())) {
isStar = true;
isDelta = false;
} else {
isStar = false;
isDelta = true;
}
}
}
@@ -2592,18 +2796,30 @@ public class SocketContrastResponseService {
devInfo = pqDevService.getDevInfo(Collections.singletonList(devId));
}
Integer usePhaseIndex = devInfo.get(0).getUsePhaseIndex();
List<String> allDesc = data.getSqlData().stream().map(x -> x.getDesc()).collect(Collectors.toList());
allDesc.addAll(data.getSqlDataHarm().stream().map(x -> x.getDesc()).collect(Collectors.toList()));
String bzDevId = devId;
if (isStdDev) {
String s = FormalTestManager.pairsIdMap.inverse().get(devId + CnSocketUtil.SPLIT_TAG + splitArr[1]);
bzDevId = s.split(CnSocketUtil.SPLIT_TAG)[0];
}
PqMonitor monitor = pqMonitorService.getByDevIdAndNum(bzDevId, Integer.parseInt(splitArr[1]));
DictData dictData = dictDataService.getById(monitor.getConnection());
for (DevData.SqlDataDTO sqlDataDTO : data.getSqlData()) {
if (usePhaseIndex.equals(1)) {
if (DetectionCodeEnum.PVRMS.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.PU1.getCode().equals(sqlDataDTO.getDesc())) {
continue;
}
} else {
if (DetectionCodeEnum.VRMS.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.U1.getCode().equals(sqlDataDTO.getDesc())) {
continue;
if (DetectionCodeEnum.STAR.getCode().equals(dictData.getCode())) {
if (DetectionCodeEnum.PVRMS.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.PU1.getCode().equals(sqlDataDTO.getDesc())) {
continue;
}
} else {
if ((DetectionCodeEnum.VRMS.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.U1.getCode().equals(sqlDataDTO.getDesc()))) {
continue;
}
}
}
@@ -2651,8 +2867,14 @@ public class SocketContrastResponseService {
continue;
}
} else {
if (DetectionCodeEnum.V2_50.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.SV_1_49.getCode().equals(sqlDataDTO.getDesc())) {
continue;
if (DetectionCodeEnum.STAR.getCode().equals(dictData.getCode())) {
if (DetectionCodeEnum.PV2_50.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.PSV_1_49.getCode().equals(sqlDataDTO.getDesc())) {
continue;
}
} else {
if (DetectionCodeEnum.V2_50.getCode().equals(sqlDataDTO.getDesc()) || DetectionCodeEnum.SV_1_49.getCode().equals(sqlDataDTO.getDesc())) {
continue;
}
}
}
@@ -3289,4 +3511,46 @@ public class SocketContrastResponseService {
devData.setSqlDataHarm(sqlDataHarmDTOS);
return devData;
}
/**
* 修改通道系数
*
* @param f
*/
private void updateGfList(DevXiNumData.F f, DetectionServiceImpl.VAndIResult vAndIResult, String stdDevMonitorId, int maxNum) {
DevXiNumData.F originF = BeanUtil.copyProperties(f, DevXiNumData.F.class);
if (maxNum != 0) {
PqStandardDevGain pqStandardDevGain = pqStandardDevGainService.get(stdDevMonitorId);
originF.setUa_gain(pqStandardDevGain.getUaGain());
originF.setUb_gain(pqStandardDevGain.getUbGain());
originF.setUc_gain(pqStandardDevGain.getUcGain());
originF.setU0_gain(pqStandardDevGain.getU0Gain());
originF.setIa_gain(pqStandardDevGain.getIaGain());
originF.setIb_gain(pqStandardDevGain.getIbGain());
originF.setIc_gain(pqStandardDevGain.getIcGain());
originF.setI0_gain(pqStandardDevGain.getI0Gain());
originF.setUab_gain(pqStandardDevGain.getUabGain());
originF.setUbc_gain(pqStandardDevGain.getUbcGain());
originF.setUca_gain(pqStandardDevGain.getUcaGain());
}
if (vAndIResult.getVa() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getVaXi() * 10000), BigDecimal.valueOf(originF.getUa_gain() * 0.95), BigDecimal.valueOf(originF.getUa_gain() * 1.05))) {
f.setUa_gain(BigDecimal.valueOf(f.getUa_gain()).multiply(BigDecimal.valueOf(vAndIResult.getVaXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
if (vAndIResult.getVb() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getVbXi() * 10000), BigDecimal.valueOf(originF.getUb_gain() * 0.95), BigDecimal.valueOf(originF.getUb_gain() * 1.05))) {
f.setUb_gain(BigDecimal.valueOf(f.getUb_gain()).multiply(BigDecimal.valueOf(vAndIResult.getVbXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
if (vAndIResult.getVc() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getVcXi() * 10000), BigDecimal.valueOf(originF.getUc_gain() * 0.95), BigDecimal.valueOf(originF.getUc_gain() * 1.05))) {
f.setUc_gain(BigDecimal.valueOf(f.getUc_gain()).multiply(BigDecimal.valueOf(vAndIResult.getVcXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
if (vAndIResult.getIa() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getIaXi() * 10000), BigDecimal.valueOf(originF.getIa_gain() * 0.95), BigDecimal.valueOf(originF.getIa_gain() * 1.05))) {
f.setIa_gain(BigDecimal.valueOf(f.getIa_gain()).multiply(BigDecimal.valueOf(vAndIResult.getIaXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
if (vAndIResult.getIb() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getIbXi() * 10000), BigDecimal.valueOf(originF.getIb_gain() * 0.95), BigDecimal.valueOf(originF.getIb_gain() * 1.05))) {
f.setIb_gain(BigDecimal.valueOf(f.getIb_gain()).multiply(BigDecimal.valueOf(vAndIResult.getIbXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
if (vAndIResult.getIc() && NumberUtil.isIn(BigDecimal.valueOf(vAndIResult.getIcXi() * 10000), BigDecimal.valueOf(originF.getIc_gain() * 0.95), BigDecimal.valueOf(originF.getIc_gain() * 1.05))) {
f.setIc_gain(BigDecimal.valueOf(f.getIc_gain()).multiply(BigDecimal.valueOf(vAndIResult.getIcXi())).setScale(0, RoundingMode.HALF_UP).intValue());
}
}
}

View File

@@ -33,6 +33,7 @@ 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.source.service.IPqSourceService;
import com.njcn.gather.storage.pojo.param.StorageParam;
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
@@ -76,6 +77,7 @@ public class SocketDevResponseService {
private final SimAndDigHarmonicService adHarmonicService;
private final IAdPlanService adPlanService;
private final IDictDataService dictDataService;
private final IPqSourceService pqSourceService;
/**
* 存储的装置相序数据
@@ -391,6 +393,7 @@ public class SocketDevResponseService {
if (param.getTestItemList().get(2)) {
//如果后续做正式检测
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
@@ -688,7 +691,7 @@ public class SocketDevResponseService {
*/
private Double reduceList(List<Double> valList) {
// valList.subList(0, 5).clear();
valList.subList(valList.size() - 2, valList.size()).clear();
valList.subList(valList.size() - 2, valList.size()).clear();
return valList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
}
@@ -894,7 +897,7 @@ public class SocketDevResponseService {
//开始下源控制脚本
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setSourceId(param.getSourceName());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
@@ -1162,8 +1165,8 @@ public class SocketDevResponseService {
} else if (param.getTestItemList().get(2)) {
// 后续做正式检测
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
@@ -1374,7 +1377,7 @@ public class SocketDevResponseService {
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
CnSocketUtil.quitSend(param);
}
successComm.clear();
@@ -1816,8 +1819,8 @@ public class SocketDevResponseService {
XiNumberManager.devParameterList.add(devParameterSmall);
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceName());
issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
issueParam.setIsPhaseSequence(CommonEnum.COEFFICIENT_TEST.getValue());

View File

@@ -46,6 +46,11 @@ public class PreDetectionParam {
*/
private String sourceId;
/**
* 源名称
*/
private String sourceName;
/**
* 所属误差体系
*/

View File

@@ -4,6 +4,7 @@ import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
import java.util.List;
import java.util.Map;
@@ -63,4 +64,8 @@ public interface PreDetectionService {
* 导出实时数据对齐过程中的数据
*/
void exportAlignData();
boolean getCanCoefficient();
void startCoefficient();
}

View File

@@ -16,8 +16,10 @@ import com.njcn.gather.detection.pojo.vo.DetectionData;
import com.njcn.gather.detection.pojo.vo.DevLineTestResult;
import com.njcn.gather.detection.util.DetectionUtil;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.device.service.IPqStandardDevGainRecordService;
import com.njcn.gather.err.pojo.param.PqErrSysParam;
import com.njcn.gather.err.pojo.po.PqErrSysDtls;
import com.njcn.gather.err.pojo.vo.ErrDtlsCheckDataVO;
@@ -36,7 +38,10 @@ 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.util.StorageUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
@@ -56,6 +61,7 @@ import java.util.stream.Stream;
* @description
* @date 2024/12/20 13:52
*/
@Log4j
@Service
@RequiredArgsConstructor
public class DetectionServiceImpl {
@@ -66,6 +72,7 @@ public class DetectionServiceImpl {
private final ISysTestConfigService sysTestConfigService;
private final IPqMonitorService pqMonitorService;
private final IPqDevService pqDevService;
private final IPqStandardDevGainRecordService pqStandardDevGainRecordService;
public static final String TYPE_A = "A";
public static final String TYPE_B = "B";
@@ -82,6 +89,44 @@ public class DetectionServiceImpl {
private static final Integer INHARMONIC_FLAG = 1;
private static final Integer HARMONIC_FLAG = 2;
// @Value("${error.removeCount:14}")
// private Integer removeErrorValueCount;
@Data
@AllArgsConstructor
public static class VAndIResult {
private String ip;
private Integer chnNum;
private Boolean va;
private Boolean vb;
private Boolean vc;
private Boolean ia;
private Boolean ib;
private Boolean ic;
private Double vaXi;
private Double vbXi;
private Double vcXi;
private Double iaXi;
private Double ibXi;
private Double icXi;
// 皮尔逊相关系数
private BigDecimal pearsonCorrelationCoefficientVa;
private BigDecimal pearsonCorrelationCoefficientVb;
private BigDecimal pearsonCorrelationCoefficientVc;
private BigDecimal pearsonCorrelationCoefficientIa;
private BigDecimal pearsonCorrelationCoefficientIb;
private BigDecimal pearsonCorrelationCoefficientIc;
// 比值一致性 CV 系数
private BigDecimal cVCoefficientVa;
private BigDecimal cVCoefficientVb;
private BigDecimal cVCoefficientVc;
private BigDecimal cVCoefficientIa;
private BigDecimal cVCoefficientIb;
private BigDecimal cVCoefficientIc;
}
public static Map<String, VAndIResult> vAndIResultMap = null;
/**
* 开始处理指标类型
@@ -401,7 +446,9 @@ public class DetectionServiceImpl {
fData = sourceIssue.getFFreq();
}
if (P.equals(type)) {
fData = sourceIssue.getFUn() * sourceIssue.getFIn();
fData = sourceIssue.getFUn() * sourceIssue.getFIn() * 0.01;
Double finalFData = fData;
errDtlsCheckData.stream().forEach(x -> x.setValue(x.getValue() * finalFData));
}
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
String[] split = dev.get(0).getId().split("_");
@@ -1572,6 +1619,23 @@ public class DetectionServiceImpl {
if (CollUtil.isNotEmpty(devDataList) && CollUtil.isNotEmpty(standardDevDataList) && CollUtil.isNotEmpty(testItemCodeList)) {
devDataList = devDataList.stream().sorted(Comparator.comparing(DevData::getTime)).collect(Collectors.toList());
standardDevDataList = standardDevDataList.stream().sorted(Comparator.comparing(DevData::getTime)).collect(Collectors.toList());
boolean isRemoveMaxElement = ObjectUtil.isNotNull(waveNum) ? false : true;
// List<Double> freqStdDevData = standardDevDataList.stream().flatMap(standardDevData -> standardDevData.getSqlData().stream())
// .filter(sqlDataDTO -> DetectionCodeEnum.FREQ.getCode().equals(sqlDataDTO.getDesc()))
// .map(sqlDataDTO -> sqlDataDTO.getList().getT()).collect(Collectors.toList());
// Double maxFreq = CollUtil.isNotEmpty(freqStdDevData) ? CollUtil.max(freqStdDevData) : null;
// Double minFreq = CollUtil.isNotEmpty(freqStdDevData) ? CollUtil.min(freqStdDevData) : null;
// if (maxFreq != null && minFreq != null) {
// isRemoveMaxElement = DictDataEnum.AVG_VALUE.equals(dataRule);
// double freqErrorValue = maxFreq - minFreq;
// if (NumberUtil.isGreaterOrEqual(BigDecimal.valueOf(freqErrorValue), BigDecimal.valueOf(0.02))) {
// isRemoveMaxElement = isRemoveMaxElement && true;
// }
// }
// 处理谐波数据
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
String[] split1 = devDataList.get(0).getId().split("_");
@@ -1618,12 +1682,12 @@ public class DetectionServiceImpl {
// sqlData.setList(listDTO);
// }));
// }
resultMap.put(PowerIndexEnum.FREQ.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fHz, DetectionCodeEnum.FREQ.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.FREQ.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fHz, DetectionCodeEnum.FREQ.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case VRMS:
case PVRMS:
// 如果是角型接法且存在角型接法的一些指标,则不进行使用角型接线的指标。反之,则使用相别的指标。
resultMap.put(PowerIndexEnum.V.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fUn, (isDelta && isExitDelta ? DetectionCodeEnum.PVRMS.getCode() : DetectionCodeEnum.VRMS.getCode()), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.V.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fUn, (isDelta && isExitDelta ? DetectionCodeEnum.PVRMS.getCode() : DetectionCodeEnum.VRMS.getCode()), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case IRMS:
// if (ObjectUtil.isNotNull(waveNum) && (waveNum.equals(2) || waveNum.equals(5))) {
@@ -1634,33 +1698,33 @@ public class DetectionServiceImpl {
// sqlData.setList(listDTO);
// }));
// }
resultMap.put(PowerIndexEnum.I.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fIn, DetectionCodeEnum.IRMS.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.I.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fIn, DetectionCodeEnum.IRMS.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case V_UNBAN:
resultMap.put(PowerIndexEnum.IMBV.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, false, fUn, DetectionCodeEnum.V_UNBAN.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.IMBV.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, false, fUn, DetectionCodeEnum.V_UNBAN.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case I_UNBAN:
resultMap.put(PowerIndexEnum.IMBA.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, false, fIn, DetectionCodeEnum.I_UNBAN.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.IMBA.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, false, fIn, DetectionCodeEnum.I_UNBAN.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case V2_50:
case PV2_50:
resultMap.put(PowerIndexEnum.HV.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, U, fUn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.HV.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, U, fUn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case I2_50:
resultMap.put(PowerIndexEnum.HI.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, I, fIn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.HI.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, I, fIn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case P2_50:
resultMap.put(PowerIndexEnum.HP.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, HP, fUn * fIn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.HP.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, HP, fUn * fIn, HARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case SV_1_49:
case PSV_1_49:
resultMap.put(PowerIndexEnum.HSV.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, U, fUn, INHARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.HSV.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, U, fUn, INHARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case SI_1_49:
resultMap.put(PowerIndexEnum.HSI.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, I, fIn, INHARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum));
resultMap.put(PowerIndexEnum.HSI.getKey(), isHarmQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, I, fIn, INHARMONIC_FLAG, isDelta && isExitDelta, dataRule, num, code, oneConfig.getScale(), waveNum, dataSourceEnum, isRemoveMaxElement));
break;
case PST:
resultMap.put(PowerIndexEnum.F.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fUn, DetectionCodeEnum.PST.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, DataSourceEnum.MINUTE_STATISTICS_AVG));
resultMap.put(PowerIndexEnum.F.getKey(), isQualified(devDataList, standardDevDataList, devIdMapComm, pqErrSysDtls, true, fUn, DetectionCodeEnum.PST.getCode(), dataRule, num, code, oneConfig.getScale(), waveNum, DataSourceEnum.MINUTE_STATISTICS_AVG, isRemoveMaxElement));
break;
case UNKNOWN_ERROR:
break;
@@ -1734,22 +1798,29 @@ public class DetectionServiceImpl {
String code,
Integer scale,
Integer waveNum,
DataSourceEnum dataSourceEnum) {
DataSourceEnum dataSourceEnum,
boolean isRemoveMaxElement) {
List<ContrastNonHarmonicResult> info = new ArrayList<>();
if (CollUtil.isNotEmpty(devDataList) && CollUtil.isNotEmpty(standardDevDataList) && CollUtil.isNotEmpty(errSysDtls)) {
Map<String, List<List<Double>>> map = devListMap(devDataList, standardDevDataList, desc, dataRule);
Map<String, List<List<Double>>> phaseValueList = this.getPhaseValueList(devDataList, standardDevDataList, desc);
Map<String, List<List<Double>>> map = devListMap(phaseValueList, dataRule, isRemoveMaxElement);
if (ObjectUtil.isNull(map)) {
return 4;
}
ContrastNonHarmonicResult result = new ContrastNonHarmonicResult();
result.setWaveNum(waveNum);
String[] split1 = devDataList.get(0).getId().split(CnSocketUtil.SPLIT_TAG);
String[] split2 = standardDevDataList.get(0).getId().split(CnSocketUtil.SPLIT_TAG);
String devId = devDataList.get(0).getId();
String stdId = standardDevDataList.get(0).getId();
String[] split1 = devId.split(CnSocketUtil.SPLIT_TAG);
String[] split2 = stdId.split(CnSocketUtil.SPLIT_TAG);
result.setNum(num);
result.setDevMonitorId(devIdMapComm.get(split1[0]) + "_" + split1[1]);
result.setStdDevMonitorId(devIdMapComm.get(split2[0]) + "_" + split2[1]);
String devMonitorId = devIdMapComm.get(split1[0]) + "_" + split1[1];
result.setDevMonitorId(devMonitorId);
String stdDevMonitorId = devIdMapComm.get(split2[0]) + "_" + split2[1];
result.setStdDevMonitorId(stdDevMonitorId);
result.setAdType(errSysDtls.get(0).getScriptType());
result.setDataType(dataSourceEnum.getValue());
if (ObjectUtil.isNotNull(waveNum)) {
@@ -1790,6 +1861,78 @@ public class DetectionServiceImpl {
List<DetectionData> phaseList = rangeComparisonList(map.get(phase).get(0), map.get(phase).get(1), errSysDtls, fData, scale, dataRule);
this.setValidGroupNum(phaseList, validGroupNum);
resultFlag.addAll(phaseList);
if (FormalTestManager.isTesting && ObjectUtil.isNull(waveNum)) { //只有“正式检测并且不是录波数据”的时候才能进入这段代码,重新计算、切换误差体系额操作不会进入这段代码,提升效率。
// if (true) { //只有“正式检测并且不是录波数据”的时候才能进入这段代码,重新计算、切换误差体系额操作不会进入这段代码,提升效率。
if (DetectionCodeEnum.PVRMS.getCode().equals(desc) || DetectionCodeEnum.VRMS.getCode().equals(desc) || DetectionCodeEnum.IRMS.getCode().equals(desc)) {
Integer phaseResultFlag = setResultFlag(phaseList);
boolean b = phaseResultFlag == 2 ? true : false;
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
if (b && oneConfig.getCoefficient() == 1) {
BigDecimal pearsonCorrelationCoefficient = DetectionUtil.getPearsonCorrelationCoefficient(phaseValueList.get(phase).get(0), phaseValueList.get(phase).get(1));
if (NumberUtil.isGreaterOrEqual(pearsonCorrelationCoefficient, BigDecimal.valueOf(0.8))) {
BigDecimal cvCoefficient = DetectionUtil.getCvCoefficient(phaseValueList.get(phase).get(0), phaseValueList.get(phase).get(1));
if (NumberUtil.isLess(cvCoefficient, BigDecimal.valueOf(0.05))) {
int maxNum = pqStandardDevGainRecordService.getMaxNum(stdDevMonitorId, devMonitorId);
// 如果没有超出次数限制
if (maxNum + 1 <= 5) {
VAndIResult vAndIResult = vAndIResultMap.getOrDefault(stdId, new VAndIResult(split2[0], Integer.valueOf(split2[1]), false, false, false, false, false, false,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.2), BigDecimal.valueOf(0.2)));
Double newXi = DetectionUtil.getNewXi(map.get(phase).get(0), map.get(phase).get(1));
switch (phase) {
case TYPE_A:
if (DetectionCodeEnum.IRMS.getCode().equals(desc)) {
vAndIResult.setIa(b);
vAndIResult.setIaXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientIa(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientIa(cvCoefficient);
} else {
vAndIResult.setVa(b);
vAndIResult.setVaXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientVa(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientVa(cvCoefficient);
}
break;
case TYPE_B:
if (DetectionCodeEnum.IRMS.getCode().equals(desc)) {
vAndIResult.setIb(b);
vAndIResult.setIbXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientIb(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientIb(cvCoefficient);
} else {
vAndIResult.setVb(b);
vAndIResult.setVbXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientVb(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientVb(cvCoefficient);
}
break;
case TYPE_C:
if (DetectionCodeEnum.IRMS.getCode().equals(desc)) {
vAndIResult.setIc(b);
vAndIResult.setIcXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientIc(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientIc(cvCoefficient);
} else {
vAndIResult.setVc(b);
vAndIResult.setVcXi(newXi);
vAndIResult.setPearsonCorrelationCoefficientVc(pearsonCorrelationCoefficient);
vAndIResult.setCVCoefficientVc(cvCoefficient);
}
break;
default:
break;
}
vAndIResultMap.put(stdId, vAndIResult);
}
}
}
}
}
}
BiConsumer<ContrastNonHarmonicResult, List<DetectionData>> setter = setters.get(phase);
setter.accept(result, phaseList);
}
@@ -1999,7 +2142,8 @@ public class DetectionServiceImpl {
String code,
Integer scale,
Integer waveNum,
DataSourceEnum dataSourceEnum) {
DataSourceEnum dataSourceEnum,
boolean isRemoveMaxElement) {
List<ContrastHarmonicResult> info = new ArrayList<>();
if (CollUtil.isNotEmpty(devDataList) && CollUtil.isNotEmpty(standardDevDataList) && CollUtil.isNotEmpty(errSysDtls)) {
String fundCode = "";
@@ -2034,7 +2178,7 @@ public class DetectionServiceImpl {
harmCode = DetectionCodeEnum.P2_50.getCode();
}
Map<String, List<Map<Double, List<Double>>>> devMap = devHarmListMap(devDataList, standardDevDataList, fundCode, harmCode, harmonicFlag, dataRule);
Map<String, List<Map<Double, List<Double>>>> devMap = devHarmListMap(devDataList, standardDevDataList, fundCode, harmCode, harmonicFlag, dataRule, isRemoveMaxElement);
if (ObjectUtil.isNull(devMap)) {
return 4;
}
@@ -2141,14 +2285,285 @@ public class DetectionServiceImpl {
/**
* 处理非谐波类取值
*
* @param dev 被检设备原始数据
* @param standardDev 与之对齐的标准设备原始数据
* @param desc 检测项
* @param dataRule 数据处理原则
* @param dataRule 数据处理原则
*/
public Map<String, List<List<Double>>> devListMap(List<DevData> dev, List<DevData> standardDev, String desc, DictDataEnum dataRule) {
public Map<String, List<List<Double>>> devListMap(Map<String, List<List<Double>>> phaseValueList, DictDataEnum dataRule, boolean isRemoveMaxElement) {
Map<String, List<List<Double>>> resultMap = new HashMap<>(3);
List<Double> aDev = new ArrayList<>();
List<Double> aStandardDev = new ArrayList<>();
if (phaseValueList.containsKey(TYPE_A)) {
if (phaseValueList.get(TYPE_A).size() >= 1) {
aDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_A).get(0), Double.class));
aStandardDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_A).get(1), Double.class));
} else {
log.error("数据异常phaseValueList.get(TYPE_A).size()=" + phaseValueList.get(TYPE_A).size());
}
} else {
log.equals("数据异常phaseValueList.containsKey(TYPE_A)=" + phaseValueList.containsKey(TYPE_A));
}
List<Double> bDev = new ArrayList<>();
List<Double> bStandardDev = new ArrayList<>();
if (phaseValueList.containsKey(TYPE_B)) {
if (phaseValueList.get(TYPE_B).size() >= 1) {
bDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_B).get(0), Double.class));
bStandardDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_B).get(1), Double.class));
} else {
log.error("数据异常phaseValueList.get(TYPE_B).size()=" + phaseValueList.get(TYPE_B).size());
}
} else {
log.equals("数据异常phaseValueList.containsKey(TYPE_B)=" + phaseValueList.containsKey(TYPE_B));
}
List<Double> cDev = new ArrayList<>();
List<Double> cStandardDev = new ArrayList<>();
if (phaseValueList.containsKey(TYPE_C)) {
if (phaseValueList.get(TYPE_C).size() >= 1) {
cDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_C).get(0), Double.class));
cStandardDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_C).get(1), Double.class));
} else {
log.error("数据异常phaseValueList.get(TYPE_C).size()=" + phaseValueList.get(TYPE_C).size());
}
} else {
log.equals("数据异常phaseValueList.containsKey(TYPE_C)=" + phaseValueList.containsKey(TYPE_C));
}
List<Double> tDev = new ArrayList<>();
List<Double> tStandardDev = new ArrayList<>();
if (phaseValueList.containsKey(TYPE_T)) {
if (phaseValueList.get(TYPE_T).size() >= 1) {
tDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_T).get(0), Double.class));
tStandardDev.addAll(BeanUtil.copyToList(phaseValueList.get(TYPE_T).get(1), Double.class));
} else {
log.error("数据异常phaseValueList.get(TYPE_T).size()=" + phaseValueList.get(TYPE_T).size());
}
} else {
log.equals("数据异常phaseValueList.containsKey(TYPE_T)=" + phaseValueList.containsKey(TYPE_T));
}
if (isRemoveMaxElement) {
List<Double> aErrorValueList = new ArrayList<>();
List<Double> bErrorValueList = new ArrayList<>();
List<Double> cErrorValueList = new ArrayList<>();
List<Double> tErrorValueList = new ArrayList<>();
for (int i = 0; i < aStandardDev.size(); i++) {
aErrorValueList.add(Math.abs(aStandardDev.get(i) - aDev.get(i)));
}
for (int i = 0; i < bStandardDev.size(); i++) {
bErrorValueList.add(Math.abs(bStandardDev.get(i) - bDev.get(i)));
}
for (int i = 0; i < cStandardDev.size(); i++) {
cErrorValueList.add(Math.abs(cStandardDev.get(i) - cDev.get(i)));
}
for (int i = 0; i < tStandardDev.size(); i++) {
tErrorValueList.add(Math.abs(tStandardDev.get(i) - tDev.get(i)));
}
List<Integer> aErrorValueIdxs = DetectionUtil.sort(aErrorValueList, false);
List<Integer> bErrorValueIdxs = DetectionUtil.sort(bErrorValueList, false);
List<Integer> cErrorValueIdxs = DetectionUtil.sort(cErrorValueList, false);
List<Integer> tErrorValueIdxs = DetectionUtil.sort(tErrorValueList, false);
int removeCount = aErrorValueIdxs.size() / 2;
List<Double> newArray = DetectionUtil.getNewArray(aStandardDev, aErrorValueIdxs.subList(removeCount, aErrorValueIdxs.size()));
aStandardDev.clear();
aStandardDev.addAll(newArray);
newArray = DetectionUtil.getNewArray(aDev, aErrorValueIdxs.subList(removeCount, aErrorValueIdxs.size()));
aDev.clear();
aDev.addAll(newArray);
removeCount = bErrorValueIdxs.size() / 2;
newArray = DetectionUtil.getNewArray(bStandardDev, bErrorValueIdxs.subList(removeCount, bErrorValueIdxs.size()));
bStandardDev.clear();
bStandardDev.addAll(newArray);
newArray = DetectionUtil.getNewArray(bDev, bErrorValueIdxs.subList(removeCount, bErrorValueIdxs.size()));
bDev.clear();
bDev.addAll(newArray);
removeCount = cErrorValueIdxs.size() / 2;
newArray = DetectionUtil.getNewArray(cStandardDev, cErrorValueIdxs.subList(removeCount, cErrorValueIdxs.size()));
cStandardDev.clear();
cStandardDev.addAll(newArray);
newArray = DetectionUtil.getNewArray(cDev, cErrorValueIdxs.subList(removeCount, cErrorValueIdxs.size()));
cDev.clear();
cDev.addAll(newArray);
removeCount = tErrorValueIdxs.size() / 2;
newArray = DetectionUtil.getNewArray(tStandardDev, tErrorValueIdxs.subList(removeCount, tErrorValueIdxs.size()));
tStandardDev.clear();
tStandardDev.addAll(newArray);
newArray = DetectionUtil.getNewArray(tDev, tErrorValueIdxs.subList(removeCount, tErrorValueIdxs.size()));
tDev.clear();
tDev.addAll(newArray);
}
switch (dataRule) {
case SECTION_VALUE: {
List<Integer> aIdxs = DetectionUtil.sort(aStandardDev, false);
List<Integer> bIdxs = DetectionUtil.sort(bStandardDev, false);
List<Integer> cIdxs = DetectionUtil.sort(cStandardDev, false);
List<Integer> tIdxs = DetectionUtil.sort(tStandardDev, false);
if (aStandardDev.size() > 2) {
aStandardDev.remove(0);
aStandardDev.remove(aStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(aDev, aIdxs.subList(1, aIdxs.size() - 1));
aDev.clear();
aDev.addAll(newArray);
}
if (bStandardDev.size() > 2) {
bStandardDev.remove(0);
bStandardDev.remove(bStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(bDev, bIdxs.subList(1, bIdxs.size() - 1));
bDev.clear();
bDev.addAll(newArray);
}
if (cStandardDev.size() > 2) {
cStandardDev.remove(0);
cStandardDev.remove(cStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(cDev, cIdxs.subList(1, cIdxs.size() - 1));
cDev.clear();
cDev.addAll(newArray);
}
if (tStandardDev.size() > 2) {
tStandardDev.remove(0);
tStandardDev.remove(tStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(tDev, tIdxs.subList(1, tIdxs.size() - 1));
tDev.clear();
tDev.addAll(newArray);
}
}
break;
case CP95_VALUE: {
List<Integer> aIdxs = DetectionUtil.sort(aStandardDev, false);
List<Integer> bIdxs = DetectionUtil.sort(bStandardDev, false);
List<Integer> cIdxs = DetectionUtil.sort(cStandardDev, false);
List<Integer> tIdxs = DetectionUtil.sort(tStandardDev, false);
if (CollUtil.isNotEmpty(aStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(aStandardDev);
aStandardDev = Collections.singletonList(aStandardDev.get(cp95Idx));
aDev = Collections.singletonList(aDev.get(aIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(bStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(bStandardDev);
bStandardDev = Collections.singletonList(bStandardDev.get(cp95Idx));
bDev = Collections.singletonList(bDev.get(bIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(cStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(cStandardDev);
cStandardDev = Collections.singletonList(cStandardDev.get(cp95Idx));
cDev = Collections.singletonList(cDev.get(cIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(tStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(tStandardDev);
tStandardDev = Collections.singletonList(tStandardDev.get(cp95Idx));
tDev = Collections.singletonList(tDev.get(tIdxs.get(cp95Idx)));
}
}
break;
case AVG_VALUE:
aDev = DetectionUtil.getAvgDoubles(aDev);
bDev = DetectionUtil.getAvgDoubles(bDev);
cDev = DetectionUtil.getAvgDoubles(cDev);
tDev = DetectionUtil.getAvgDoubles(tDev);
aStandardDev = DetectionUtil.getAvgDoubles(aStandardDev);
bStandardDev = DetectionUtil.getAvgDoubles(bStandardDev);
cStandardDev = DetectionUtil.getAvgDoubles(cStandardDev);
tStandardDev = DetectionUtil.getAvgDoubles(tStandardDev);
break;
case Own_value:
break;
case AT_WILL_VALUE:
if (isRemoveMaxElement) {
if (CollUtil.isNotEmpty(aStandardDev) && CollUtil.isNotEmpty(aDev)) {
aStandardDev = aStandardDev.subList(aStandardDev.size() - 1, aStandardDev.size());
aDev = aDev.subList(aDev.size() - 1, aDev.size());
}
if (CollUtil.isNotEmpty(bStandardDev) && CollUtil.isNotEmpty(bDev)) {
bStandardDev = bStandardDev.subList(bStandardDev.size() - 1, bStandardDev.size());
bDev = bDev.subList(bDev.size() - 1, bDev.size());
}
if (CollUtil.isNotEmpty(cStandardDev) && CollUtil.isNotEmpty(cDev)) {
cStandardDev = cStandardDev.subList(cStandardDev.size() - 1, cStandardDev.size());
cDev = cDev.subList(cDev.size() - 1, cDev.size());
}
if (CollUtil.isNotEmpty(tStandardDev) && CollUtil.isNotEmpty(tDev)) {
tStandardDev = tStandardDev.subList(tStandardDev.size() - 1, tStandardDev.size());
tDev = tDev.subList(tDev.size() - 1, tDev.size());
}
} else {
List<Double> aErrorValueList = new ArrayList<>();
List<Double> bErrorValueList = new ArrayList<>();
List<Double> cErrorValueList = new ArrayList<>();
List<Double> tErrorValueList = new ArrayList<>();
for (int i = 0; i < aStandardDev.size(); i++) {
aErrorValueList.add(Math.abs(aStandardDev.get(i) - aDev.get(i)));
}
for (int i = 0; i < bStandardDev.size(); i++) {
bErrorValueList.add(Math.abs(bStandardDev.get(i) - bDev.get(i)));
}
for (int i = 0; i < cStandardDev.size(); i++) {
cErrorValueList.add(Math.abs(cStandardDev.get(i) - cDev.get(i)));
}
for (int i = 0; i < tStandardDev.size(); i++) {
tErrorValueList.add(Math.abs(tStandardDev.get(i) - tDev.get(i)));
}
List<Integer> aErrorValueIdxs = DetectionUtil.sort(aErrorValueList, true);
List<Integer> bErrorValueIdxs = DetectionUtil.sort(bErrorValueList, true);
List<Integer> cErrorValueIdxs = DetectionUtil.sort(cErrorValueList, true);
List<Integer> tErrorValueIdxs = DetectionUtil.sort(tErrorValueList, true);
if (CollUtil.isNotEmpty(aStandardDev) && CollUtil.isNotEmpty(aDev)) {
Double v = aStandardDev.get(aErrorValueIdxs.get(0));
aStandardDev.clear();
aStandardDev.add(v);
v = aDev.get(aErrorValueIdxs.get(0));
aDev.clear();
aDev.add(v);
}
if (CollUtil.isNotEmpty(bStandardDev) && CollUtil.isNotEmpty(bDev)) {
Double v = bStandardDev.get(bErrorValueIdxs.get(0));
bStandardDev.clear();
bStandardDev.add(v);
v = bDev.get(bErrorValueIdxs.get(0));
bDev.clear();
bDev.add(v);
}
if (CollUtil.isNotEmpty(cStandardDev) && CollUtil.isNotEmpty(cDev)) {
Double v = cStandardDev.get(cErrorValueIdxs.get(0));
cStandardDev.clear();
cStandardDev.add(v);
v = cDev.get(cErrorValueIdxs.get(0));
cDev.clear();
cDev.add(v);
}
if (CollUtil.isNotEmpty(tStandardDev) && CollUtil.isNotEmpty(tDev)) {
Double v = tStandardDev.get(tErrorValueIdxs.get(0));
tStandardDev.clear();
tStandardDev.add(v);
v = tDev.get(tErrorValueIdxs.get(0));
tDev.clear();
tDev.add(v);
}
}
break;
}
resultMap.put(TYPE_A, Arrays.asList(aDev, aStandardDev));
resultMap.put(TYPE_B, Arrays.asList(bDev, bStandardDev));
resultMap.put(TYPE_C, Arrays.asList(cDev, cStandardDev));
if (CollUtil.isNotEmpty(tDev)) {
resultMap.put(TYPE_T, Arrays.asList(tDev, tStandardDev));
}
return resultMap;
}
private Map<String, List<List<Double>>> getPhaseValueList(List<DevData> dev, List<DevData> standardDev, String desc) {
Map<String, List<List<Double>>> resultMap = new HashMap<>(3);
List<Double> aDev = new ArrayList<>();
List<Double> aStandardDev = new ArrayList<>();
List<Double> bDev = new ArrayList<>();
@@ -2202,87 +2617,12 @@ public class DetectionServiceImpl {
.map(x -> x.getT().doubleValue())
.collect(Collectors.toList()));
}
List<Integer> aIdxs = DetectionUtil.sort(aStandardDev, false);
List<Integer> bIdxs = DetectionUtil.sort(bStandardDev, false);
List<Integer> cIdxs = DetectionUtil.sort(cStandardDev, false);
List<Integer> tIdxs = DetectionUtil.sort(tStandardDev, false);
switch (dataRule) {
case SECTION_VALUE:
if (aStandardDev.size() > 2) {
aStandardDev.remove(0);
aStandardDev.remove(aStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(aDev, aIdxs.subList(1, aIdxs.size() - 1));
aDev.clear();
aDev.addAll(newArray);
}
if (bStandardDev.size() > 2) {
bStandardDev.remove(0);
bStandardDev.remove(bStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(bDev, bIdxs.subList(1, bIdxs.size() - 1));
bDev.clear();
bDev.addAll(newArray);
}
if (cStandardDev.size() > 2) {
cStandardDev.remove(0);
cStandardDev.remove(cStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(cDev, cIdxs.subList(1, cIdxs.size() - 1));
cDev.clear();
cDev.addAll(newArray);
}
if (tStandardDev.size() > 2) {
tStandardDev.remove(0);
tStandardDev.remove(tStandardDev.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(tDev, tIdxs.subList(1, tIdxs.size() - 1));
tDev.clear();
tDev.addAll(newArray);
}
break;
case CP95_VALUE:
if (CollUtil.isNotEmpty(aStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(aStandardDev);
aStandardDev = Collections.singletonList(aStandardDev.get(cp95Idx));
aDev = Collections.singletonList(aDev.get(aIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(bStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(bStandardDev);
bStandardDev = Collections.singletonList(bStandardDev.get(cp95Idx));
bDev = Collections.singletonList(bDev.get(bIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(cStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(cStandardDev);
cStandardDev = Collections.singletonList(cStandardDev.get(cp95Idx));
cDev = Collections.singletonList(cDev.get(cIdxs.get(cp95Idx)));
}
if (CollUtil.isNotEmpty(tStandardDev)) {
int cp95Idx = DetectionUtil.getCP95Idx(tStandardDev);
tStandardDev = Collections.singletonList(tStandardDev.get(cp95Idx));
tDev = Collections.singletonList(tDev.get(tIdxs.get(cp95Idx)));
}
break;
case AVG_VALUE:
aDev = DetectionUtil.getAvgDoubles(aDev);
bDev = DetectionUtil.getAvgDoubles(bDev);
cDev = DetectionUtil.getAvgDoubles(cDev);
tDev = DetectionUtil.getAvgDoubles(tDev);
aStandardDev = DetectionUtil.getAvgDoubles(aStandardDev);
bStandardDev = DetectionUtil.getAvgDoubles(bStandardDev);
cStandardDev = DetectionUtil.getAvgDoubles(cStandardDev);
tStandardDev = DetectionUtil.getAvgDoubles(tStandardDev);
break;
}
resultMap.put(TYPE_A, Arrays.asList(aDev, aStandardDev));
resultMap.put(TYPE_B, Arrays.asList(bDev, bStandardDev));
resultMap.put(TYPE_C, Arrays.asList(cDev, cStandardDev));
if (CollUtil.isNotEmpty(tDev)) {
resultMap.put(TYPE_T, Arrays.asList(tDev, tStandardDev));
}
resultMap.put(TYPE_T, Arrays.asList(tDev, tStandardDev));
return resultMap;
}
@@ -2302,8 +2642,7 @@ public class DetectionServiceImpl {
String fundCode,
String harmCode,
Integer harmonicFlag,
DictDataEnum dataRule) {
System.out.println("aaa" + dev.size() + " " + standardDev.size());
DictDataEnum dataRule, boolean isRemoveMaxElement) {
Map<String, List<Map<Double, List<Double>>>> resultMap = new HashMap<>(3);
// key为相别、value{key为谐波次数value为按数据处理原则处理后的数据}
@@ -2328,27 +2667,6 @@ public class DetectionServiceImpl {
first1 = devSqlData.stream().filter(j -> fundCode.equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
first2 = standardDevSqlData.stream().filter(j -> fundCode.equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
}
// // 如果角型接法中,不存在线电压谐波电压基波有效值,则取相电压谐波电压基波有效值进行计算
// if (!first1.isPresent()) {
// if (DetectionCodeEnum.PU1.getCode().equals(fundCode)) {
// first1 = devSqlData.stream().filter(j -> DetectionCodeEnum.U1.getCode().equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
// }
// } else {
// // 防止出现有PU1而没有PV2_50、SV_1_49的情况
// if ((DetectionCodeEnum.PV2_50.getCode().equals(harmCode) || DetectionCodeEnum.PSV_1_49.getCode().equals(harmCode)) && DetectionCodeEnum.PU1.getCode().equals(fundCode)) {
// first1 = devSqlData.stream().filter(j -> DetectionCodeEnum.U1.getCode().equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
// }
// }
// if (!first2.isPresent()) {
// if (DetectionCodeEnum.PU1.getCode().equals(fundCode)) {
// first2 = devSqlData.stream().filter(j -> DetectionCodeEnum.U1.getCode().equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
// }
// } else {
// // 防止出现有PU1而没有PV2_50、SV_1_49的情况
// if ((DetectionCodeEnum.PV2_50.getCode().equals(harmCode) || DetectionCodeEnum.PSV_1_49.getCode().equals(harmCode)) && DetectionCodeEnum.PU1.getCode().equals(fundCode)) {
// first2 = devSqlData.stream().filter(j -> DetectionCodeEnum.U1.getCode().equals(j.getDesc())).collect(Collectors.toList()).stream().findFirst();
// }
// }
DevData.SqlDataDTO fund1 = null;
DevData.SqlDataDTO fund2 = null;
@@ -2365,23 +2683,6 @@ public class DetectionServiceImpl {
if (CollUtil.isEmpty(devHarmList) || CollUtil.isEmpty(stdDevHarmList)) {
return null;
}
// // 如果角型接法中,不存在线电压谐波电压含有率,则取相电压谐波电压含有率进行计算
// if (CollUtil.isEmpty(devHarmList)) {
// if (DetectionCodeEnum.PV2_50.getCode().equals(harmCode)) {
// devHarmList = dev.get(i).getSqlDataHarm().stream().filter(x -> DetectionCodeEnum.V2_50.getCode().equals(x.getDesc())).collect(Collectors.toList());
// }
// if (DetectionCodeEnum.PSV_1_49.getCode().equals(harmCode)) {
// devHarmList = dev.get(i).getSqlDataHarm().stream().filter(x -> DetectionCodeEnum.SV_1_49.getCode().equals(x.getDesc())).collect(Collectors.toList());
// }
// }
// if (CollUtil.isEmpty(stdDevHarmList)) {
// if (DetectionCodeEnum.PV2_50.getCode().equals(harmCode)) {
// stdDevHarmList = standardDev.get(i).getSqlDataHarm().stream().filter(x -> DetectionCodeEnum.V2_50.getCode().equals(x.getDesc())).collect(Collectors.toList());
// }
// if (DetectionCodeEnum.PSV_1_49.getCode().equals(harmCode)) {
// stdDevHarmList = standardDev.get(i).getSqlDataHarm().stream().filter(x -> DetectionCodeEnum.SV_1_49.getCode().equals(x.getDesc())).collect(Collectors.toList());
// }
// }
if (CollUtil.isNotEmpty(devHarmList) && CollUtil.isNotEmpty(stdDevHarmList)) {
DevData.SqlDataHarmDTO devHarm = devHarmList.get(0);
@@ -2403,38 +2704,87 @@ public class DetectionServiceImpl {
}
}
}
standardDevMap.forEach((typeKey, typeValue) -> {
typeValue.forEach((key, value) -> {
standardDevMap.forEach((phase, harmonicMap) -> {
harmonicMap.forEach((harmonicNum, value) -> {
List<Double> devPhaseHarmData = devMap.get(phase).get(harmonicNum);
if (isRemoveMaxElement) {
List<Double> errorValueList = new ArrayList<>();
for (int i = 0; i < value.size(); i++) {
errorValueList.add(Math.abs(value.get(i) - devPhaseHarmData.get(i)));
}
List<Integer> idxErrorValueList = DetectionUtil.sort(errorValueList, false);
int removeCount = idxErrorValueList.size() / 2;
List<Double> newArray = DetectionUtil.getNewArray(value, idxErrorValueList.subList(removeCount, idxErrorValueList.size()));
value.clear();
value.addAll(newArray);
newArray = DetectionUtil.getNewArray(devPhaseHarmData, idxErrorValueList.subList(removeCount, idxErrorValueList.size()));
devPhaseHarmData.clear();
devPhaseHarmData.addAll(newArray);
}
if (CollUtil.isNotEmpty(value)) {
List<Integer> idx = DetectionUtil.sort(value, false);
switch (dataRule) {
case SECTION_VALUE:
case SECTION_VALUE: {
List<Integer> idx = DetectionUtil.sort(value, false);
if (value.size() > 2) {
value.remove(0);
value.remove(value.size() - 1);
List<Double> newArray = DetectionUtil.getNewArray(devMap.get(typeKey).get(key), idx.subList(1, idx.size() - 1));
devMap.get(typeKey).get(key).clear();
devMap.get(typeKey).get(key).addAll(newArray);
List<Double> newArray = DetectionUtil.getNewArray(devPhaseHarmData, idx.subList(1, idx.size() - 1));
devPhaseHarmData.clear();
devPhaseHarmData.addAll(newArray);
}
break;
}
break;
case CP95_VALUE:
if (CollUtil.isNotEmpty(value)) {
List<Integer> idx = DetectionUtil.sort(value, false);
int cp95Idx = DetectionUtil.getCP95Idx(value);
List<Double> newValue = Collections.singletonList(value.get(cp95Idx));
value.clear();
value.addAll(newValue);
Double devCP95Data = devMap.get(typeKey).get(key).get(idx.get(cp95Idx));
devMap.get(typeKey).get(key).clear();
devMap.get(typeKey).get(key).add(devCP95Data);
Double devCP95Data = devPhaseHarmData.get(idx.get(cp95Idx));
devPhaseHarmData.clear();
devPhaseHarmData.add(devCP95Data);
}
break;
case AVG_VALUE:
List<Double> avgDoubles = DetectionUtil.getAvgDoubles(value);
value.clear();
value.addAll(avgDoubles);
List<Double> devAvgData = DetectionUtil.getAvgDoubles(devMap.get(typeKey).get(key));
devMap.get(typeKey).get(key).clear();
devMap.get(typeKey).get(key).addAll(devAvgData);
List<Double> devAvgData = DetectionUtil.getAvgDoubles(devMap.get(phase).get(harmonicNum));
devPhaseHarmData.clear();
devPhaseHarmData.addAll(devAvgData);
break;
case Own_value:
break;
case AT_WILL_VALUE:
if (isRemoveMaxElement) {
if (CollUtil.isNotEmpty(value)) {
Double v = value.get(value.size() - 1);
value.clear();
value.add(v);
}
if (CollUtil.isNotEmpty(devPhaseHarmData)) {
Double v = devPhaseHarmData.get(devPhaseHarmData.size() - 1);
devPhaseHarmData.clear();
devPhaseHarmData.add(v);
}
} else {
List<Double> errorValueList = new ArrayList<>();
for (int i = 0; i < value.size(); i++) {
errorValueList.add(Math.abs(value.get(i) - devPhaseHarmData.get(i)));
}
List<Integer> idxErrorValueList = DetectionUtil.sort(errorValueList, true);
Double v = value.get(idxErrorValueList.get(0));
value.clear();
value.add(v);
v = devPhaseHarmData.get(idxErrorValueList.get(0));
devPhaseHarmData.clear();
devPhaseHarmData.add(v);
}
break;
}
}

View File

@@ -21,6 +21,8 @@ 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;
import com.njcn.gather.detection.util.socket.XiNumberManager;
import com.njcn.gather.detection.util.socket.cilent.NettyContrastClientHandler;
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
import com.njcn.gather.device.pojo.po.PqDev;
import com.njcn.gather.device.pojo.vo.PreDetection;
@@ -38,6 +40,8 @@ import com.njcn.gather.script.service.IPqScriptCheckDataService;
import com.njcn.gather.script.service.IPqScriptDtlsService;
import com.njcn.gather.source.pojo.po.SourceInitialize;
import com.njcn.gather.source.service.IPqSourceService;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
import com.njcn.gather.system.dictionary.service.IDictDataService;
import com.njcn.web.utils.HttpServletUtil;
@@ -50,6 +54,7 @@ import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -75,9 +80,12 @@ public class PreDetectionServiceImpl implements PreDetectionService {
private final SocketContrastResponseService socketContrastResponseService;
private final IPqScriptCheckDataService iPqScriptCheckDataService;
private final SocketManager socketManager;
private final ISysTestConfigService sysTestConfigService;
@Value("${report.reportDir}")
private String alignDataFilePath;
// @Value("${report.reportDir}")
// private String alignDataFilePath;
private final PathConfig pathConfig;
@Override
@@ -130,6 +138,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
);
if (ObjectUtil.isNotNull(planSource)) {
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
param.setSourceName(sourceParam.getSourceId());
if (ObjectUtil.isNotNull(sourceParam)) {
//开始组装socket报文请求头
socketDevResponseService.initList(param);
@@ -176,6 +185,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
if (ObjectUtil.isNotNull(planSource)) {
//获取源初始化参数
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
param.setSourceName(sourceParam.getSourceId());
if (ObjectUtil.isNotNull(sourceParam)) {
//开始组装socket报文请求头
socketDevResponseService.initList(param);
@@ -238,6 +248,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
FormalTestManager.stopFlag = false;
socketDevResponseService.initRestart();
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
param.setSourceName(sourceInitialize.getSourceId());
if (CollUtil.isNotEmpty(sourceIssueList)) {
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
SocketMsg<String> xuMsg = new SocketMsg<>();
@@ -253,7 +265,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
checkDataParam.setIsValueTypeName(false);
List<String> adType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), adType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
iPqDevService.updateResult(param.getDevIds(), adType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
CnSocketUtil.quitSend(param);
}
@@ -284,7 +296,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
}
//组装源控制脚本
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceId());
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
issueParam.setSourceId(sourceInitialize.getSourceId());
issueParam.setScriptId(param.getScriptId());
issueParam.setType(1);
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.SIMULATE_TEST.getValue());
@@ -343,7 +356,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/octet-stream;charset=UTF-8");
try {
InputStream inputStream = new FileInputStream(alignDataFilePath + "\\" + fileName);
InputStream inputStream = new FileInputStream(pathConfig.getDataPath() + File.separator + fileName);
byte[] buffer = new byte[1024];
int len = 0;
ServletOutputStream outputStream = response.getOutputStream();
@@ -358,6 +371,36 @@ public class PreDetectionServiceImpl implements PreDetectionService {
}
}
@Override
public boolean getCanCoefficient() {
return CollUtil.isNotEmpty(DetectionServiceImpl.vAndIResultMap);
}
@Override
public void startCoefficient() {
if (CollUtil.isNotEmpty(DetectionServiceImpl.vAndIResultMap)) {
// 是否进行系数校准
//万一录波了这里就进不来了但是在误差处理的时候DetectionServiceImpl.vAndIResultMap该集合会保留不符合的结果
XiNumberManager.xiDevList.clear();
XiNumberManager.devXiNumDataMap.clear();
List<String> stdIpList = DetectionServiceImpl.vAndIResultMap.values().stream().map(DetectionServiceImpl.VAndIResult::getIp).collect(Collectors.toList());
XiNumberManager.xiDevList = FormalTestManager.standardDevList.stream().filter(d -> stdIpList.contains(d.getDevIP())).collect(Collectors.toList());
// 逐一设备向通讯模块要原始系数
SocketMsg<String> socketMsg = new SocketMsg<>();
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(NettyContrastClientHandler.param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG, JSON.toJSONString(socketMsg));
FormalTestManager.currentStep = SourceOperateCodeEnum.Coefficient_Check;
}
}
/**
* 比对式-与通信模块进行连接
*

View File

@@ -1,6 +1,7 @@
package com.njcn.gather.detection.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.njcn.gather.detection.pojo.po.DevData;
import lombok.extern.slf4j.Slf4j;
@@ -421,7 +422,7 @@ public class DetectionUtil {
}
return newList;
}
return null;
return Collections.emptyList();
}
/**
@@ -437,4 +438,94 @@ public class DetectionUtil {
System.out.println(" 文件大小: " + file.length() + " bytes");
}
}
/**
* 获取皮尔逊系数
*
* <p>相关系数绝对值|r|所代表的相关强度</p>
* <ul>
* <li>0.8 - 1.0:极强相关</li>
* <li>0.6 - 0.8:强相关</li>
* <li>0.4 - 0.6:中等程度相关</li>
* <li>0.2 - 0.4:弱相关</li>
* <li>0.0 - 0.2:极弱相关或无相关</li>
* </ul>
*
* @return
*/
public static BigDecimal getPearsonCorrelationCoefficient(List<Double> x, List<Double> y) {
Double xAvg = x.parallelStream().mapToDouble(Double::doubleValue).average().orElse(0.0);
Double yAvg = y.parallelStream().mapToDouble(Double::doubleValue).average().orElse(0.0);
// 协方差求和
BigDecimal covarianceSum = BigDecimal.ZERO;
// x的方差
BigDecimal varianceX = BigDecimal.ZERO;
// y的方差
BigDecimal varianceY = BigDecimal.ZERO;
for (int i = 0; i < x.size(); i++) {
covarianceSum = covarianceSum.add(BigDecimal.valueOf((x.get(i) - xAvg) * (y.get(i) - yAvg)));
varianceX = varianceX.add(BigDecimal.valueOf(Math.pow(x.get(i) - xAvg, 2)));
varianceY = varianceY.add(BigDecimal.valueOf(Math.pow(y.get(i) - yAvg, 2)));
}
BigDecimal fm = BigDecimal.valueOf(Math.sqrt(varianceX.doubleValue()) * Math.sqrt(varianceY.doubleValue()));
if (NumberUtil.equals(fm.doubleValue(), BigDecimal.ZERO.doubleValue())) {
if (NumberUtil.equals(covarianceSum, BigDecimal.ZERO)) {
return BigDecimal.valueOf(1.0);
} else {
return BigDecimal.ZERO;
}
} else {
return BigDecimal.valueOf(Math.abs(covarianceSum.divide(fm, 8, BigDecimal.ROUND_HALF_UP).doubleValue())); //相关系数
}
}
/**
* 比值一致性获取CV系数
*
* <p>一致性等级</p>
* <ul>
* <li>CV<1%:非常优秀</li>
* <li>1%≤CV5%:优良</li>
* <li>5%≤CV10%:良好</li>
* <li>10%≤CV20%:中等</li>
* <li>20%≤CV较差</li>
* </ul>
*
* @param x
* @param y
* @return
*/
public static BigDecimal getCvCoefficient(List<Double> x, List<Double> y) {
List<BigDecimal> ratioList = new ArrayList<>();
for (int i = 0; i < x.size(); i++) {
ratioList.add(BigDecimal.valueOf(x.get(i) / y.get(i)));
}
BigDecimal avg = BigDecimal.valueOf(ratioList.parallelStream().mapToDouble(BigDecimal::doubleValue).average().orElse(0.0));
BigDecimal variance = BigDecimal.valueOf(
ratioList.parallelStream().mapToDouble(BigDecimal::doubleValue)
.map(v -> Math.pow(v - avg.doubleValue(), 2)).average().orElse(0.0));
return BigDecimal.valueOf(Math.sqrt(variance.doubleValue()) / avg.doubleValue());
}
/**
* 计算新的系数
*
* @param devList
* @param stdDevList
* @return
*/
public static Double getNewXi(List<Double> devList, List<Double> stdDevList) {
ArrayList<Double> xiList = new ArrayList<>();
for (int i = 0; i < stdDevList.size(); i++) {
if (!stdDevList.get(i).equals(0)) {
BigDecimal bigDecimalDev = BigDecimal.valueOf(devList.get(i));
BigDecimal bigDecimalStdDev = BigDecimal.valueOf(stdDevList.get(i));
xiList.add((bigDecimalDev.subtract(bigDecimalStdDev)).divide(BigDecimal.valueOf(2.0).multiply(bigDecimalDev), 8, BigDecimal.ROUND_HALF_UP).doubleValue() + 1.0);
}
}
return xiList.stream().mapToDouble(Double::doubleValue).average().orElse(1.0);
}
}

View File

@@ -47,7 +47,7 @@ public class CnSocketUtil {
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE_SOURCE.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue());
JSONObject jsonObject = new JSONObject();
jsonObject.put("sourceId", param.getSourceId());
jsonObject.put("sourceId", param.getSourceName());
socketMsg.setData(jsonObject.toJSONString());
SocketManager.sendMsg(param.getUserPageId() + SOURCE_TAG, JSON.toJSONString(socketMsg));
WebServiceManager.removePreDetectionParam(param.getUserPageId());

View File

@@ -12,6 +12,7 @@ import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.device.pojo.param.PqStandardDevParam;
import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.device.pojo.vo.PqStandardDevVO;
import com.njcn.gather.device.service.IPqStandardDevService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.FileUtil;
@@ -55,10 +56,10 @@ public class PqStandardDevController extends BaseController {
@GetMapping("/getById")
@ApiOperation("根据id查询标准设备")
@ApiImplicitParam(name = "id", value = "标准设备id", required = true)
public HttpResult<PqStandardDev> getById(@RequestParam("id") String id) {
public HttpResult<PqStandardDevVO> getById(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("getById");
LogUtil.njcnDebug(log, "{}查询ID为{}", methodDescribe, id);
PqStandardDev result = pqStandardDevService.getPqStandardDevById(id);
PqStandardDevVO result = pqStandardDevService.getPqStandardDevById(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}

View File

@@ -0,0 +1,13 @@
package com.njcn.gather.device.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
/**
* @author caozehui
* @date 2026-01-12
*/
public interface PqStandardDevGainMapper extends MPJBaseMapper<PqStandardDevGain> {
}

View File

@@ -0,0 +1,13 @@
package com.njcn.gather.device.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.device.pojo.po.PqStandardDevGainRecord;
/**
* @author caozehui
* @date 2026-01-15
*/
public interface PqStandardDevGainRecordMapper extends MPJBaseMapper<PqStandardDevGainRecord> {
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.device.mapper.PqStandardDevGainMapper">
</mapper>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.device.mapper.PqStandardDevGainRecordMapper">
</mapper>

View File

@@ -0,0 +1,61 @@
package com.njcn.gather.device.pojo.po;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.mybatisplus.bo.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
/**
* @author caozehui
* @date 2026-01-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("pq_standard_dev_gain")
public class PqStandardDevGain extends BaseEntity implements Serializable {
private static final long serialVersionUID = -46280767885558804L;
/**
* 标准设备Id_通道号
*/
@TableId
private String stdDevMonitorId;
private Integer uaGain;
private Integer ubGain;
private Integer ucGain;
private Integer u0Gain;
private Integer iaGain;
private Integer ibGain;
private Integer icGain;
private Integer i0Gain;
private Integer uabGain;
private Integer ubcGain;
private Integer ucaGain;
private Integer state;
}

View File

@@ -0,0 +1,35 @@
package com.njcn.gather.device.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.mybatisplus.bo.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
/**
* @author caozehui
* @date 2026-01-15
*/
@Data
@TableName("pq_standard_dev_gain_record")
public class PqStandardDevGainRecord implements Serializable {
private static final long serialVersionUID = 477276215572686991L;
/**
* 标准设备监测点id,由设备id_通道号组成
*/
private String stdDevMonitorId;
/**
* 被检设备监测点id,由设备id_通道号组成
*/
private String devMonitorId;
/**
* 系数下发次数
*/
private Integer num;
}

View File

@@ -0,0 +1,20 @@
package com.njcn.gather.device.pojo.vo;
import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
import lombok.Data;
import java.util.List;
/**
* @author caozehui
* @data 2026-01-19
*/
@Data
public class PqStandardDevVO extends PqStandardDev {
/**
* 通道系数
*/
List<PqStandardDevGain> gainList;
}

View File

@@ -115,9 +115,10 @@ public interface IPqDevService extends IService<PqDev> {
* @param userId
* @param temperature
* @param humidity
* @param updateCheckNum 是否更新检测次数
* @return
*/
boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity);
boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum);
/**
* 比对式-修改设备状态

View File

@@ -0,0 +1,29 @@
package com.njcn.gather.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.device.pojo.po.PqStandardDevGainRecord;
import java.util.List;
/**
* @author caozehui
* @date 2026-01-15
*/
public interface IPqStandardDevGainRecordService extends IService<PqStandardDevGainRecord> {
/**
* 获取最大下发系数的次数
*
* @param stdDevMonitorId
* @param devMonitorId
* @return
*/
int getMaxNum(String stdDevMonitorId, String devMonitorId);
/**
* 批量新增或更新记录
* @param recordList
* @return
*/
boolean addOrUpdate(List<PqStandardDevGainRecord> recordList);
}

View File

@@ -0,0 +1,19 @@
package com.njcn.gather.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
import java.util.List;
/**
* @author caozehui
* @date 2026-01-12
*/
public interface IPqStandardDevGainService extends IService<PqStandardDevGain> {
boolean add(List<PqStandardDevGain> pqStandardDevGainList);
PqStandardDevGain get(String stdDevMonitorId);
List<PqStandardDevGain> list(String stdDevId);
}

View File

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.device.pojo.param.PqStandardDevParam;
import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.device.pojo.vo.PqStandardDevVO;
import com.njcn.gather.device.pojo.vo.PreDetection;
import org.springframework.web.multipart.MultipartFile;
@@ -30,7 +31,7 @@ public interface IPqStandardDevService extends IService<PqStandardDev> {
* @param id 设备id
* @return 设备对象
*/
PqStandardDev getPqStandardDevById(String id);
PqStandardDevVO getPqStandardDevById(String id);
/**
* 新增标准设备

View File

@@ -38,6 +38,9 @@ import com.njcn.gather.monitor.pojo.po.PqMonitor;
import com.njcn.gather.monitor.pojo.vo.PqMonitorExcel;
import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
import com.njcn.gather.plan.mapper.AdPlanMapper;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.storage.service.DetectionDataDealService;
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
@@ -87,6 +90,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
private final IDictTypeService dictTypeService;
private final ISysUserService userService;
private final IPqDevSubService pqDevSubService;
private final AdPlanMapper adPlanMapper;
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
@Override
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
@@ -483,7 +488,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
@Override
public boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity) {
public boolean updateResult(List<String> ids, List<String> adType, String code, String userId, Float temperature, Float humidity, boolean updateCheckNum) {
if (CollUtil.isNotEmpty(ids)) {
SysTestConfig config = sysTestConfigService.getOneConfig();
@@ -515,13 +520,18 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
checkState = CheckStateEnum.DOCUMENTED.getValue();
i = pqDevVo.getRecheckNum();
} else {
checkState = CheckStateEnum.CHECKED.getValue();
i = pqDevVo.getRecheckNum() + 1;
checkState = pqDevVo.getCheckState() == CheckStateEnum.DOCUMENTED.getValue() ? CheckStateEnum.DOCUMENTED.getValue() : CheckStateEnum.CHECKED.getValue();
if (updateCheckNum) {
i = pqDevVo.getRecheckNum() + 1;
} else {
i = pqDevVo.getRecheckNum();
}
wrapper.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
}
wrapper.set(PqDevSub::getRecheckNum, i)
.set(PqDevSub::getCheckState, checkState);
pqDevSubService.update(wrapper);
saveCheckHistory(pqDevVo, i, checkState, userId);
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
param.setPlanIdList(Arrays.asList(pqDevVo.getPlanId()));
@@ -587,6 +597,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
w.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
}
w.update();
saveCheckHistory(devId, userId);
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
String planId = dev.getPlanId();
@@ -622,6 +633,37 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
}
}
private void saveCheckHistory(PqDevVO pqDevVo, Integer recheckNum, Integer checkState, String userId) {
if (ObjectUtil.isNull(pqDevVo)
|| (!CheckStateEnum.CHECKED.getValue().equals(checkState) && !CheckStateEnum.DOCUMENTED.getValue().equals(checkState))) {
return;
}
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
if (ObjectUtil.isNull(plan)) {
return;
}
pqDevVo.setRecheckNum(recheckNum);
pqDevVo.setCheckBy(userId);
pqDevVo.setCheckTime(LocalDateTime.now());
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
}
private void saveCheckHistory(String devId, String userId) {
PqDevVO pqDevVo = this.baseMapper.selectByDevId(devId);
if (ObjectUtil.isNull(pqDevVo)
|| (!CheckStateEnum.CHECKED.getValue().equals(pqDevVo.getCheckState()) && !CheckStateEnum.DOCUMENTED.getValue().equals(pqDevVo.getCheckState()))) {
return;
}
AdPlan plan = adPlanMapper.selectById(pqDevVo.getPlanId());
if (ObjectUtil.isNull(plan)) {
return;
}
if (StrUtil.isBlank(pqDevVo.getCheckBy())) {
pqDevVo.setCheckBy(userId);
}
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
}
@Override
public void updatePqDevReportState(String devId, int reportState) {
LambdaUpdateWrapper<PqDevSub> updateWrapper = new LambdaUpdateWrapper<>();

View File

@@ -0,0 +1,45 @@
package com.njcn.gather.device.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.device.mapper.PqStandardDevGainRecordMapper;
import com.njcn.gather.device.pojo.po.PqStandardDevGainRecord;
import com.njcn.gather.device.service.IPqStandardDevGainRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author caozehui
* @date 2026-01-15
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PqStandardDevGainRecordServiceImpl extends ServiceImpl<PqStandardDevGainRecordMapper, PqStandardDevGainRecord> implements IPqStandardDevGainRecordService {
@Override
public int getMaxNum(String stdDevMonitorId, String devMonitorId) {
return this.lambdaQuery().eq(PqStandardDevGainRecord::getStdDevMonitorId, stdDevMonitorId)
.eq(PqStandardDevGainRecord::getDevMonitorId, devMonitorId)
.list().stream().mapToInt(PqStandardDevGainRecord::getNum).max().orElse(0);
}
@Override
public boolean addOrUpdate(List<PqStandardDevGainRecord> recordList) {
recordList.forEach(record -> {
List<PqStandardDevGainRecord> list = this.lambdaQuery().eq(PqStandardDevGainRecord::getStdDevMonitorId, record.getStdDevMonitorId())
.eq(PqStandardDevGainRecord::getDevMonitorId, record.getDevMonitorId()).list();
if (CollectionUtil.isNotEmpty(list)) {
this.lambdaUpdate().eq(PqStandardDevGainRecord::getStdDevMonitorId, record.getStdDevMonitorId())
.eq(PqStandardDevGainRecord::getDevMonitorId, record.getDevMonitorId())
.set(PqStandardDevGainRecord::getNum, record.getNum()).update();
} else {
this.save(record);
}
});
return true;
}
}

View File

@@ -0,0 +1,42 @@
package com.njcn.gather.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.device.mapper.PqStandardDevGainMapper;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
import com.njcn.gather.device.service.IPqStandardDevGainService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author caozehui
* @date 2026-01-12
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PqStandardDevGainServiceImpl extends ServiceImpl<PqStandardDevGainMapper, PqStandardDevGain> implements IPqStandardDevGainService {
@Override
public boolean add(List<PqStandardDevGain> pqStandardDevGainList) {
log.info("add PqStandardDevGainList: {}", pqStandardDevGainList.size());
List<String> stdMonitorIdList = pqStandardDevGainList.stream().map(PqStandardDevGain::getStdDevMonitorId).distinct().collect(Collectors.toList());
List<String> existingStdMonitorIdList = this.listByIds(stdMonitorIdList).stream().map(PqStandardDevGain::getStdDevMonitorId).collect(Collectors.toList());
pqStandardDevGainList = pqStandardDevGainList.stream().filter(pqStandardDevGain -> !existingStdMonitorIdList.contains(pqStandardDevGain.getStdDevMonitorId())).collect(Collectors.toList());
return this.saveBatch(pqStandardDevGainList);
}
@Override
public PqStandardDevGain get(String stdDevMonitorId) {
return this.lambdaQuery().eq(PqStandardDevGain::getStdDevMonitorId, stdDevMonitorId).one();
}
@Override
public List<PqStandardDevGain> list(String stdDevId) {
return this.lambdaQuery().likeRight(PqStandardDevGain::getStdDevMonitorId, stdDevId).orderByAsc(PqStandardDevGain::getStdDevMonitorId).list();
}
}

View File

@@ -19,8 +19,11 @@ import com.njcn.common.utils.EncryptionUtil;
import com.njcn.gather.device.mapper.PqStandardDevMapper;
import com.njcn.gather.device.pojo.param.PqStandardDevParam;
import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.device.pojo.po.PqStandardDevGain;
import com.njcn.gather.device.pojo.vo.PqStandardDevExcel;
import com.njcn.gather.device.pojo.vo.PqStandardDevVO;
import com.njcn.gather.device.pojo.vo.PreDetection;
import com.njcn.gather.device.service.IPqStandardDevGainService;
import com.njcn.gather.device.service.IPqStandardDevService;
import com.njcn.gather.plan.mapper.AdPlanStandardDevMapper;
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
@@ -58,8 +61,7 @@ public class PqStandardDevServiceImpl extends ServiceImpl<PqStandardDevMapper, P
private final IDevTypeService devTypeService;
private final IDictDataService dictDataService;
private final IDictTypeService dictTypeService;
private final AdPlanStandardDevMapper adPlanStandardDevMapper;
private final IAdPlanStandardDevService adPlanStandardDevService;
private final IPqStandardDevGainService pqStandardDevGainService;
@Override
public Page<PqStandardDev> listPqStandardDevs(PqStandardDevParam.QueryParam queryParam) {
@@ -73,13 +75,17 @@ public class PqStandardDevServiceImpl extends ServiceImpl<PqStandardDevMapper, P
}
@Override
public PqStandardDev getPqStandardDevById(String id) {
public PqStandardDevVO getPqStandardDevById(String id) {
PqStandardDev standardDev = this.getById(id);
PqStandardDevVO pqStandardDevVO = BeanUtil.copyProperties(standardDev, PqStandardDevVO.class);
if (standardDev.getEncryptionFlag() == 1) {
standardDev.setSeries(EncryptionUtil.decoderString(1, standardDev.getSeries()));
standardDev.setDevKey(EncryptionUtil.decoderString(1, standardDev.getDevKey()));
pqStandardDevVO.setSeries(EncryptionUtil.decoderString(1, standardDev.getSeries()));
pqStandardDevVO.setDevKey(EncryptionUtil.decoderString(1, standardDev.getDevKey()));
}
return standardDev;
List<PqStandardDevGain> gainList = pqStandardDevGainService.list(id);
pqStandardDevVO.setGainList(gainList);
return pqStandardDevVO;
}
@Override

View File

@@ -121,8 +121,8 @@ public interface IPqMonitorService extends IService<PqMonitor> {
/**
* 根据被检设备id和监测点编号获取监测点信息
* @param id 被检设备id
* @param devId 设备id
* @param monitorNum 监测点编号
*/
PqMonitor getByDevAndNum(String id, int monitorNum);
PqMonitor getByDevIdAndNum(String devId, int monitorNum);
}

View File

@@ -84,6 +84,7 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
if (ObjectUtil.isNotNull(pqMonitor)) {
BeanUtil.copyProperties(monitorList.get(0), pqMonitor, "id", "realtimeResult", "statisticsResult", "recordedResult", "realtimeNum", "statisticsNum", "recordedNum", "resultType", "qualifiedNum");
newMonitorList.add(pqMonitor);
existedMonitorList.remove(pqMonitor);
} else {
newMonitorList.addAll(monitorList);
}
@@ -168,6 +169,7 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
this.baseMapper.updatePlanReportRState(plan.getId(), PlanReportStateEnum.REPORT_STATE_NOT_GENERATED.getValue());
}
}
this.removeByIds(existedMonitorList.stream().map(PqMonitor::getId).collect(Collectors.toList()));
return this.saveOrUpdateBatch(newMonitorList);
}
@@ -438,7 +440,7 @@ public class PqMonitorServiceImpl extends ServiceImpl<PqMonitorMapper, PqMonitor
}
@Override
public PqMonitor getByDevAndNum(String devId, int monitorNum) {
public PqMonitor getByDevIdAndNum(String devId, int monitorNum) {
QueryWrapper<PqMonitor> wrapper = new QueryWrapper<>();
wrapper.eq("pq_monitor.Dev_Id", devId)
.eq("pq_monitor.Num", monitorNum);

View File

@@ -22,6 +22,7 @@ import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.plan.pojo.param.AdPlanParam;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
import com.njcn.gather.plan.pojo.vo.PlanStatisticsVO;
import com.njcn.gather.plan.service.AsyncPlanHandler;
import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.type.pojo.po.DevType;
@@ -198,6 +199,17 @@ public class AdPlanController extends BaseController {
adPlanService.analyse(ids);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/statistics")
@ApiOperation("检测计划统计")
@ApiImplicitParam(name = "param", value = "检测计划统计参数", required = true)
public HttpResult<PlanStatisticsVO> statistics(@RequestBody @Validated AdPlanParam.StatisticsParam param) {
String methodDescribe = getMethodDescribe("statistics");
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, param);
PlanStatisticsVO result = adPlanService.statistics(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/listByPlanId")
@ApiOperation("查询出所有已绑定的设备")

View File

@@ -0,0 +1,15 @@
package com.njcn.gather.plan.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface PqDevCheckHistoryMapper extends MPJBaseMapper<PqDevCheckHistory> {
List<PlanStatisticsItemVO> listItemDistributions(@Param("planId") String planId,
@Param("manufacturer") String manufacturer,
@Param("devType") String devType);
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.plan.mapper.PqDevCheckHistoryMapper">
<select id="listItemDistributions" resultType="com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO">
SELECT
Item_Id AS itemId,
Item_Name AS itemName,
SUM(CASE WHEN Result = 0 THEN 1 ELSE 0 END) AS unqualifiedCount
FROM pq_dev_check_history
<where>
State = 1
AND Plan_Id = #{planId}
<if test="manufacturer != null and manufacturer != ''">
AND Manufacturer = #{manufacturer}
</if>
<if test="devType != null and devType != ''">
AND Dev_Type = #{devType}
</if>
</where>
GROUP BY Item_Id, Item_Name
ORDER BY unqualifiedCount DESC, Item_Name ASC
</select>
</mapper>

View File

@@ -130,4 +130,17 @@ public class AdPlanParam {
private String patternId;
private String scriptType;
}
@Data
public static class StatisticsParam {
@ApiModelProperty(value = "检测计划ID", required = true)
@NotBlank(message = DetectionValidMessage.PLAN_ID_NOT_BLANK)
private String planId;
@ApiModelProperty("设备厂家")
private String manufacturer;
@ApiModelProperty("设备类型")
private String devType;
}
}

View File

@@ -0,0 +1,60 @@
package com.njcn.gather.plan.pojo.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("pq_dev_check_history")
public class PqDevCheckHistory {
@TableId(value = "Id", type = IdType.ASSIGN_UUID)
private String id;
@TableField("Plan_Id")
private String planId;
@TableField("Dev_Id")
private String devId;
@TableField("Dev_Type")
private String devType;
@TableField("Manufacturer")
private String manufacturer;
@TableField("ReCheck_Num")
private Integer recheckNum;
@TableField("Item_Id")
private String itemId;
@TableField("Item_Name")
private String itemName;
@TableField("Result")
private Integer result;
@TableField("Check_Time")
private LocalDateTime checkTime;
@TableField("State")
private Integer state;
@TableField("Create_By")
private String createBy;
@TableField(value = "Create_Time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField("Update_By")
private String updateBy;
@TableField(value = "Update_Time", fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,25 @@
package com.njcn.gather.plan.pojo.vo;
import lombok.Data;
/**
* 检测计划单个检测大项柱状图统计结果。
*/
@Data
public class PlanStatisticsItemVO {
/**
* 检测大项ID。
*/
private String itemId;
/**
* 检测大项名称。
*/
private String itemName;
/**
* 不合格次数。
*/
private Integer unqualifiedCount;
}

View File

@@ -0,0 +1,93 @@
package com.njcn.gather.plan.pojo.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 检测计划统计结果。
*/
@Data
public class PlanStatisticsVO {
/**
* 检测计划ID。
*/
private String planId;
/**
* 检测计划名称。
*/
private String planName;
/**
* 所有设备检测次数之和。
*/
private Integer totalCheckCount;
/**
* 已检设备总数。
*/
private Integer checkedDeviceCount;
/**
* 未检设备总数。
*/
private Integer uncheckedDeviceCount;
/**
* 第一次检测合格的设备数量。
*/
private Integer firstQualifiedDeviceCount;
/**
* 第二次检测后合格的设备数量。
*/
private Integer secondQualifiedDeviceCount;
/**
* 第三次及以上检测后合格的设备数量。
*/
private Integer thirdOrMoreQualifiedDeviceCount;
/**
* 最终合格的设备数量。
*/
private Integer qualifiedDeviceCount;
/**
* 最终不合格的设备数量。
*/
private Integer unqualifiedDeviceCount;
/**
* 存在不合格结果的检测项数量。
*/
private Integer unqualifiedItemCount;
/**
* 一次合格率,百分制。
*/
private BigDecimal firstPassRate;
/**
* 二次合格率,百分制。
*/
private BigDecimal secondPassRate;
/**
* 三次及以上合格率,百分制。
*/
private BigDecimal thirdOrMorePassRate;
/**
* 不合格率,百分制。
*/
private BigDecimal unqualifiedRate;
/**
* 检测项分布。
*/
private List<PlanStatisticsItemVO> itemDistributions;
}

View File

@@ -23,6 +23,7 @@ import com.njcn.gather.monitor.service.IPqMonitorService;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.vo.AdPlanCheckDataVO;
import com.njcn.gather.plan.service.util.BatchFileReader;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.config.handler.NonWebAutoFillValueHandler;
import com.njcn.gather.tools.report.model.constant.ReportConstant;
import com.njcn.gather.type.pojo.po.DevType;
@@ -64,11 +65,11 @@ public class AsyncPlanHandler {
private final JdbcTemplate jdbcTemplate;
@Value("${report.reportDir}")
private String reportPath;
@Value("${data.homeDir}")
private String dataPath;
private final PathConfig pathConfig;
// @Value("${report.reportDir}")
// private String reportPath;
// @Value("${data.homeDir}")
// private String dataPath;
private static final int BATCH_SIZE = 10000;
private static final int FINAL_STEP = 85;
@@ -199,13 +200,13 @@ public class AsyncPlanHandler {
// 创建 ZIP 文件
String zipFileName = plan.getName() + "_检测数据包.zip";
File zipFile = FileUtil.file(dataPath + File.separator + TEST_DATA_DIR + File.separator, zipFileName);
File zipFile = FileUtil.file(pathConfig.getDataPath() + File.separator + TEST_DATA_DIR + File.separator, zipFileName);
// 添加检测报告文件
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
for (PqDev dev : devList) {
DevType devType = devTypeService.getById(dev.getDevType());
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
// 如果reportFile存在则将reportFile中的文件添加到已有的zip文件中
if (FileUtil.exist(reportFile)) {
@@ -344,7 +345,7 @@ public class AsyncPlanHandler {
for (File docx : docxFiles) {
for (PqDev dev : devList) {
DevType devType = devTypeService.getById(dev.getDevType());
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
// 文件名匹配,复制到对应目录下
if (docx.getName().equals(reportFile.getName())) {

View File

@@ -6,6 +6,7 @@ import com.njcn.gather.device.pojo.po.PqStandardDev;
import com.njcn.gather.plan.pojo.param.AdPlanParam;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
import com.njcn.gather.plan.pojo.vo.PlanStatisticsVO;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@@ -105,6 +106,14 @@ public interface IAdPlanService extends IService<AdPlan> {
*/
void analyse(List<String> ids);
/**
* 统计检测计划结果。
*
* @param planId 检测计划ID
* @return 检测计划统计结果
*/
PlanStatisticsVO statistics(AdPlanParam.StatisticsParam param);
/**
* 导出检测计划数据
*

View File

@@ -0,0 +1,18 @@
package com.njcn.gather.plan.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.device.pojo.vo.PqDevVO;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
import java.util.List;
public interface IPqDevCheckHistoryService extends IService<PqDevCheckHistory> {
void saveOrUpdateDeviceHistory(AdPlan plan, PqDevVO device);
void backfillPlanHistoryIfEmpty(AdPlan plan, List<PqDevVO> checkedDevices);
List<PlanStatisticsItemVO> listItemDistributions(String planId, String manufacturer, String devType);
}

View File

@@ -59,6 +59,7 @@ import com.njcn.gather.plan.service.IAdPlanService;
import com.njcn.gather.plan.service.IAdPlanSourceService;
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.report.pojo.po.PqReport;
import com.njcn.gather.report.service.IPqReportService;
@@ -69,11 +70,14 @@ import com.njcn.gather.script.service.IPqScriptService;
import com.njcn.gather.source.pojo.po.PqSource;
import com.njcn.gather.source.service.IPqSourceService;
import com.njcn.gather.storage.pojo.param.StorageParam;
import com.njcn.gather.storage.pojo.po.SimAndDigBaseResult;
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
import com.njcn.gather.storage.service.TableGenService;
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.dictionary.pojo.po.DictData;
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
import com.njcn.gather.system.dictionary.pojo.po.DictType;
@@ -107,6 +111,8 @@ import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
@@ -133,6 +139,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
private final IDevTypeService devTypeService;
private final IDictTypeService dictTypeService;
private final SimAndDigHarmonicService adHarmonicService;
private final SimAndDigNonHarmonicService adNonHarmonicService;
private final PqDevMapper pqDevMapper;
private final IPqDevSubService pqDevSubService;
private final IAdPlanStandardDevService adPlanStandardDevService;
@@ -145,10 +152,12 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
private final IAdPariService adPairService;
private final IAdPlanTestConfigService adPlanTestConfigService;
private final ISysUserService sysUserService;
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
private final JdbcTemplate jdbcTemplate;
@Value("${report.reportDir}")
private String reportPath;
// @Value("${report.reportDir}")
// private String reportPath;
private final PathConfig pathConfig;
@Override
public List<AdPlanVO> listAdPlan(AdPlanParam.QueryParam queryParam) {
@@ -555,6 +564,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
child.put("name", adPlan.getName());
child.put("timeCheck", adPlan.getTimeCheck());
child.put("dataRule", adPlan.getDataRule());
child.put("testState", adPlan.getTestState());
List<PqStandardDev> pqStandardDevs = adPlanStandardDevMapper.listByPlanId(Collections.singletonList(adPlan.getId()));
List<String> devTypeIdList = pqStandardDevs.stream().map(PqStandardDev::getDevType).collect(Collectors.toList());
@@ -809,6 +819,242 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
}
}
@Override
public PlanStatisticsVO statistics(AdPlanParam.StatisticsParam param) {
String planId = param.getPlanId();
AdPlan plan = this.getById(planId);
if (ObjectUtil.isNull(plan)) {
throw new BusinessException(DetectionResponseEnum.PLAN_NOT_EXIST);
}
List<PqDevVO> planDevices = listPlanDevices(plan.getId(), param.getManufacturer(), param.getDevType());
List<PqDevVO> checkedDevices = planDevices.stream()
.filter(this::isCheckedDevice)
.collect(Collectors.toList());
PlanStatisticsVO statistics = new PlanStatisticsVO();
statistics.setPlanId(plan.getId());
statistics.setPlanName(plan.getName());
statistics.setUncheckedDeviceCount(planDevices.size() - checkedDevices.size());
statistics.setCheckedDeviceCount(checkedDevices.size());
statistics.setTotalCheckCount(checkedDevices.stream().mapToInt(dev -> defaultZero(dev.getRecheckNum())).sum());
int firstQualifiedCount = (int) checkedDevices.stream()
.filter(dev -> Objects.equals(dev.getRecheckNum(), 1))
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
.count();
int secondQualifiedCount = (int) checkedDevices.stream()
.filter(dev -> Objects.equals(dev.getRecheckNum(), 2))
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
.count();
int thirdOrMoreQualifiedCount = (int) checkedDevices.stream()
.filter(dev -> defaultZero(dev.getRecheckNum()) >= 3)
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.ACCORD.getValue()))
.count();
int unqualifiedDeviceCount = (int) checkedDevices.stream()
.filter(dev -> Objects.equals(dev.getCheckResult(), CheckResultEnum.NOT_ACCORD.getValue()))
.count();
statistics.setFirstQualifiedDeviceCount(firstQualifiedCount);
statistics.setSecondQualifiedDeviceCount(secondQualifiedCount);
statistics.setThirdOrMoreQualifiedDeviceCount(thirdOrMoreQualifiedCount);
statistics.setQualifiedDeviceCount(firstQualifiedCount + secondQualifiedCount + thirdOrMoreQualifiedCount);
statistics.setUnqualifiedDeviceCount(unqualifiedDeviceCount);
statistics.setFirstPassRate(rate(firstQualifiedCount, checkedDevices.size()));
statistics.setSecondPassRate(rate(secondQualifiedCount, checkedDevices.size()));
statistics.setThirdOrMorePassRate(rate(thirdOrMoreQualifiedCount, checkedDevices.size()));
statistics.setUnqualifiedRate(rate(unqualifiedDeviceCount, checkedDevices.size()));
pqDevCheckHistoryService.backfillPlanHistoryIfEmpty(plan, checkedDevices);
List<PlanStatisticsItemVO> itemDistributions = pqDevCheckHistoryService.listItemDistributions(plan.getId(), param.getManufacturer(), param.getDevType());
statistics.setItemDistributions(itemDistributions);
statistics.setUnqualifiedItemCount(itemDistributions.stream()
.mapToInt(item -> defaultZero(item.getUnqualifiedCount()))
.sum());
return statistics;
}
private List<PqDevVO> listPlanDevices(String planId, String manufacturer, String devType) {
PqDevParam.QueryParam queryParam = new PqDevParam.QueryParam();
queryParam.setPlanIdList(Collections.singletonList(planId));
List<PqDevVO> pqDevVOList = pqDevMapper.selectByQueryParam(queryParam);
if (CollUtil.isEmpty(pqDevVOList)) {
return Collections.emptyList();
}
return pqDevVOList.stream()
.filter(dev -> StrUtil.isBlank(manufacturer) || Objects.equals(dev.getManufacturer(), manufacturer))
.filter(dev -> StrUtil.isBlank(devType) || Objects.equals(dev.getDevType(), devType))
.collect(Collectors.toList());
}
private boolean isCheckedDevice(PqDevVO dev) {
return (Objects.equals(dev.getCheckState(), CheckStateEnum.CHECKED.getValue())
|| Objects.equals(dev.getCheckState(), CheckStateEnum.DOCUMENTED.getValue()))
&& !Objects.equals(dev.getCheckResult(), CheckResultEnum.UNCHECKED.getValue());
}
private List<PlanStatisticsItemVO> buildItemDistributions(AdPlan plan, List<PqDevVO> checkedDevices) {
if (CollUtil.isEmpty(checkedDevices) || StrUtil.isBlank(plan.getScriptId()) || ObjectUtil.isNull(plan.getCode())) {
return Collections.emptyList();
}
Map<Integer, ScriptItemInfo> scriptItemInfoMap = getScriptItemInfoMap(plan.getScriptId());
if (CollUtil.isEmpty(scriptItemInfoMap)) {
return Collections.emptyList();
}
Map<String, PlanStatisticsItemAccumulator> itemAccumulatorMap = new TreeMap<>();
for (PqDevVO device : checkedDevices) {
List<SimAndDigBaseResult> deviceResultList = new ArrayList<>();
deviceResultList.addAll(adNonHarmonicService.listSimAndDigBaseResult(plan.getScriptId(), plan.getCode() + "", device.getId()));
deviceResultList.addAll(adHarmonicService.listAllResultData(plan.getScriptId(), plan.getCode() + "", device.getId()));
if (CollUtil.isEmpty(deviceResultList)) {
continue;
}
Map<String, List<SimAndDigBaseResult>> deviceItemResultMap = deviceResultList.stream()
.filter(result -> ObjectUtil.isNotNull(result.getSort()))
.map(result -> new AbstractMap.SimpleEntry<>(scriptItemInfoMap.get(result.getSort()), result))
.filter(entry -> ObjectUtil.isNotNull(entry.getKey()))
.collect(Collectors.groupingBy(
entry -> entry.getKey().getItemId(),
TreeMap::new,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));
deviceItemResultMap.forEach((itemId, results) -> {
boolean hasUnqualified = results.stream().anyMatch(result -> isUnqualifiedResultFlag(result.getResultFlag()));
boolean hasQualified = results.stream().anyMatch(result -> Objects.equals(result.getResultFlag(), 1));
if (!hasUnqualified && !hasQualified) {
return;
}
ScriptItemInfo itemInfo = scriptItemInfoMap.get(results.get(0).getSort());
PlanStatisticsItemAccumulator accumulator = itemAccumulatorMap.computeIfAbsent(
itemId,
key -> new PlanStatisticsItemAccumulator(itemId, itemInfo.getItemName())
);
accumulator.totalCount++;
if (hasUnqualified) {
accumulator.unqualifiedCount++;
} else {
accumulator.qualifiedCount++;
}
});
}
return itemAccumulatorMap.values().stream()
.map(PlanStatisticsItemAccumulator::toVO)
.collect(Collectors.toList());
}
private Map<Integer, ScriptItemInfo> getScriptItemInfoMap(String scriptId) {
List<PqScriptDtls> scriptDtlsList = pqScriptDtlsService.list(new LambdaQueryWrapper<PqScriptDtls>()
.eq(PqScriptDtls::getScriptId, scriptId)
.ne(PqScriptDtls::getScriptIndex, -1)
.eq(PqScriptDtls::getEnable, DataStateEnum.ENABLE.getCode())
);
if (CollUtil.isEmpty(scriptDtlsList)) {
return Collections.emptyMap();
}
List<String> scriptTypeIds = scriptDtlsList.stream()
.map(PqScriptDtls::getScriptType)
.filter(StrUtil::isNotBlank)
.distinct()
.collect(Collectors.toList());
Map<String, DictTree> dictTreeMap = Collections.emptyMap();
if (CollUtil.isNotEmpty(scriptTypeIds)) {
dictTreeMap = dictTreeService.getDictTreeById(scriptTypeIds).stream()
.collect(Collectors.toMap(DictTree::getId, dictTree -> dictTree, (left, right) -> left));
}
Map<String, DictTree> finalDictTreeMap = dictTreeMap;
return scriptDtlsList.stream()
.collect(Collectors.groupingBy(PqScriptDtls::getScriptIndex, TreeMap::new, Collectors.toList()))
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> resolveScriptItemInfo(entry.getKey(), entry.getValue(), finalDictTreeMap),
(left, right) -> left,
TreeMap::new
));
}
private ScriptItemInfo resolveScriptItemInfo(Integer sort, List<PqScriptDtls> dtlsList, Map<String, DictTree> dictTreeMap) {
if (CollUtil.isEmpty(dtlsList)) {
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
}
PqScriptDtls first = dtlsList.get(0);
DictTree dictTree = dictTreeMap.get(first.getScriptType());
if (ObjectUtil.isNotNull(dictTree) && StrUtil.isNotBlank(dictTree.getName())) {
return new ScriptItemInfo(dictTree.getId(), dictTree.getName());
}
if (StrUtil.isNotBlank(first.getScriptType())) {
return new ScriptItemInfo(first.getScriptType(), "检测项" + sort);
}
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
}
private boolean isUnqualifiedResultFlag(Integer resultFlag) {
return ObjectUtil.isNotNull(resultFlag)
&& !Objects.equals(resultFlag, 1)
&& !Objects.equals(resultFlag, 4)
&& !Objects.equals(resultFlag, 5);
}
private Integer defaultZero(Integer value) {
return ObjectUtil.isNull(value) ? 0 : value;
}
private BigDecimal rate(Integer numerator, Integer denominator) {
if (ObjectUtil.isNull(denominator) || denominator == 0) {
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
}
return BigDecimal.valueOf(defaultZero(numerator))
.multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(denominator), 2, RoundingMode.HALF_UP);
}
private class PlanStatisticsItemAccumulator {
private final String itemId;
private final String itemName;
private int totalCount;
private int qualifiedCount;
private int unqualifiedCount;
private PlanStatisticsItemAccumulator(String itemId, String itemName) {
this.itemId = itemId;
this.itemName = itemName;
}
private PlanStatisticsItemVO toVO() {
PlanStatisticsItemVO itemVO = new PlanStatisticsItemVO();
itemVO.setItemId(itemId);
itemVO.setItemName(itemName);
itemVO.setUnqualifiedCount(unqualifiedCount);
return itemVO;
}
}
private static class ScriptItemInfo {
private final String itemId;
private final String itemName;
private ScriptItemInfo(String itemId, String itemName) {
this.itemId = itemId;
this.itemName = itemName;
}
private String getItemId() {
return itemId;
}
private String getItemName() {
return itemName;
}
}
@Override
public void exportPlan(AdPlanParam.QueryParam queryParam) {
DictData dictData = dictDataService.getDictDataById(queryParam.getPatternId());
@@ -1265,7 +1511,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
for (int i = 1; i <= maxTime; i++) {
row2[i] = i + "次检测";
int tempI = i;
List<PqDevVO> tempDevList = devList.stream().filter(dev -> dev.getRecheckNum() <= tempI).collect(Collectors.toList());
List<PqDevVO> tempDevList = devList.stream().filter(dev -> dev.getRecheckNum() == tempI).collect(Collectors.toList());
long passCount = tempDevList.stream().filter(dev -> dev.getCheckResult() == CheckResultEnum.ACCORD.getValue()).count();
row3[i] = passCount + "";
row4[i] = total + "";
@@ -2089,7 +2335,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
for (PqDev dev : devList) {
DevType devType = devTypeService.getById(dev.getDevType());
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
// 如果reportFile存在则将reportFile中的文件添加到已有的zip文件中
if (FileUtil.exist(reportFile)) {

View File

@@ -0,0 +1,220 @@
package com.njcn.gather.plan.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.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.gather.device.pojo.vo.PqDevVO;
import com.njcn.gather.plan.mapper.PqDevCheckHistoryMapper;
import com.njcn.gather.plan.pojo.po.AdPlan;
import com.njcn.gather.plan.pojo.po.PqDevCheckHistory;
import com.njcn.gather.plan.pojo.vo.PlanStatisticsItemVO;
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
import com.njcn.gather.script.mapper.PqScriptDtlsMapper;
import com.njcn.gather.script.pojo.po.PqScriptDtls;
import com.njcn.gather.storage.pojo.po.SimAndDigBaseResult;
import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
import com.njcn.gather.system.dictionary.service.IDictTreeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PqDevCheckHistoryServiceImpl extends ServiceImpl<PqDevCheckHistoryMapper, PqDevCheckHistory> implements IPqDevCheckHistoryService {
private final SimAndDigNonHarmonicService adNonHarmonicService;
private final SimAndDigHarmonicService adHarmonicService;
private final PqScriptDtlsMapper pqScriptDtlsMapper;
private final IDictTreeService dictTreeService;
@Override
@Transactional
public void saveOrUpdateDeviceHistory(AdPlan plan, PqDevVO device) {
if (ObjectUtil.isNull(plan)
|| ObjectUtil.isNull(device)
|| StrUtil.isBlank(plan.getScriptId())
|| ObjectUtil.isNull(plan.getCode())
|| StrUtil.isBlank(device.getId())
|| ObjectUtil.isNull(device.getRecheckNum())) {
return;
}
Map<Integer, ScriptItemInfo> scriptItemInfoMap = getScriptItemInfoMap(plan.getScriptId());
if (CollUtil.isEmpty(scriptItemInfoMap)) {
return;
}
List<SimAndDigBaseResult> resultList = new ArrayList<>();
resultList.addAll(adNonHarmonicService.listSimAndDigBaseResult(plan.getScriptId(), plan.getCode() + "", device.getId()));
resultList.addAll(adHarmonicService.listAllResultData(plan.getScriptId(), plan.getCode() + "", device.getId()));
if (CollUtil.isEmpty(resultList)) {
return;
}
Map<String, List<SimAndDigBaseResult>> itemResultMap = resultList.stream()
.filter(result -> ObjectUtil.isNotNull(result.getSort()))
.map(result -> new AbstractMap.SimpleEntry<>(scriptItemInfoMap.get(result.getSort()), result))
.filter(entry -> ObjectUtil.isNotNull(entry.getKey()))
.collect(Collectors.groupingBy(
entry -> entry.getKey().getItemId(),
TreeMap::new,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));
LocalDateTime now = LocalDateTime.now();
itemResultMap.forEach((itemId, results) -> {
boolean hasUnqualified = results.stream().anyMatch(result -> isUnqualifiedResultFlag(result.getResultFlag()));
boolean hasQualified = results.stream().anyMatch(result -> Objects.equals(result.getResultFlag(), 1));
if (!hasUnqualified && !hasQualified) {
return;
}
ScriptItemInfo itemInfo = scriptItemInfoMap.get(results.get(0).getSort());
PqDevCheckHistory history = this.getOne(new LambdaQueryWrapper<PqDevCheckHistory>()
.eq(PqDevCheckHistory::getPlanId, plan.getId())
.eq(PqDevCheckHistory::getDevId, device.getId())
.eq(PqDevCheckHistory::getRecheckNum, device.getRecheckNum())
.eq(PqDevCheckHistory::getItemId, itemId)
.last("LIMIT 1"));
if (ObjectUtil.isNull(history)) {
history = new PqDevCheckHistory();
history.setId(UUID.randomUUID().toString().replaceAll("-", ""));
history.setPlanId(plan.getId());
history.setDevId(device.getId());
history.setRecheckNum(device.getRecheckNum());
history.setItemId(itemId);
history.setCreateBy(device.getCheckBy());
history.setCreateTime(now);
}
history.setDevType(device.getDevType());
history.setManufacturer(device.getManufacturer());
history.setItemName(itemInfo.getItemName());
history.setResult(hasUnqualified ? 0 : 1);
history.setCheckTime(ObjectUtil.isNotNull(device.getCheckTime()) ? device.getCheckTime() : now);
history.setState(DataStateEnum.ENABLE.getCode());
history.setUpdateBy(device.getCheckBy());
history.setUpdateTime(now);
this.saveOrUpdate(history);
});
}
@Override
public void backfillPlanHistoryIfEmpty(AdPlan plan, List<PqDevVO> checkedDevices) {
if (ObjectUtil.isNull(plan) || CollUtil.isEmpty(checkedDevices)) {
return;
}
long historyCount = this.count(new LambdaQueryWrapper<PqDevCheckHistory>()
.eq(PqDevCheckHistory::getPlanId, plan.getId())
.eq(PqDevCheckHistory::getState, DataStateEnum.ENABLE.getCode()));
if (historyCount > 0) {
return;
}
checkedDevices.forEach(device -> saveOrUpdateDeviceHistory(plan, device));
}
@Override
public List<PlanStatisticsItemVO> listItemDistributions(String planId, String manufacturer, String devType) {
List<PlanStatisticsItemVO> itemDistributions = this.baseMapper.listItemDistributions(planId, manufacturer, devType);
if (CollUtil.isEmpty(itemDistributions)) {
return Collections.emptyList();
}
itemDistributions.forEach(item -> item.setUnqualifiedCount(defaultZero(item.getUnqualifiedCount())));
return itemDistributions;
}
private Map<Integer, ScriptItemInfo> getScriptItemInfoMap(String scriptId) {
List<PqScriptDtls> scriptDtlsList = pqScriptDtlsMapper.selectList(new LambdaQueryWrapper<PqScriptDtls>()
.eq(PqScriptDtls::getScriptId, scriptId)
.ne(PqScriptDtls::getScriptIndex, -1)
.eq(PqScriptDtls::getEnable, DataStateEnum.ENABLE.getCode())
);
if (CollUtil.isEmpty(scriptDtlsList)) {
return Collections.emptyMap();
}
List<String> scriptTypeIds = scriptDtlsList.stream()
.map(PqScriptDtls::getScriptType)
.filter(StrUtil::isNotBlank)
.distinct()
.collect(Collectors.toList());
Map<String, DictTree> dictTreeMap = Collections.emptyMap();
if (CollUtil.isNotEmpty(scriptTypeIds)) {
dictTreeMap = dictTreeService.getDictTreeById(scriptTypeIds).stream()
.collect(Collectors.toMap(DictTree::getId, dictTree -> dictTree, (left, right) -> left));
}
Map<String, DictTree> finalDictTreeMap = dictTreeMap;
return scriptDtlsList.stream()
.collect(Collectors.groupingBy(PqScriptDtls::getScriptIndex, TreeMap::new, Collectors.toList()))
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> resolveScriptItemInfo(entry.getKey(), entry.getValue(), finalDictTreeMap),
(left, right) -> left,
TreeMap::new
));
}
private ScriptItemInfo resolveScriptItemInfo(Integer sort, List<PqScriptDtls> dtlsList, Map<String, DictTree> dictTreeMap) {
if (CollUtil.isEmpty(dtlsList)) {
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
}
PqScriptDtls first = dtlsList.get(0);
DictTree dictTree = dictTreeMap.get(first.getScriptType());
if (ObjectUtil.isNotNull(dictTree) && StrUtil.isNotBlank(dictTree.getName())) {
return new ScriptItemInfo(dictTree.getId(), dictTree.getName());
}
if (StrUtil.isNotBlank(first.getScriptType())) {
return new ScriptItemInfo(first.getScriptType(), "检测项" + sort);
}
return new ScriptItemInfo(String.valueOf(sort), "检测项" + sort);
}
private boolean isUnqualifiedResultFlag(Integer resultFlag) {
return ObjectUtil.isNotNull(resultFlag)
&& !Objects.equals(resultFlag, 1)
&& !Objects.equals(resultFlag, 4)
&& !Objects.equals(resultFlag, 5);
}
private Integer defaultZero(Integer value) {
return ObjectUtil.isNull(value) ? 0 : value;
}
private static class ScriptItemInfo {
private final String itemId;
private final String itemName;
private ScriptItemInfo(String itemId, String itemName) {
this.itemId = itemId;
this.itemName = itemName;
}
private String getItemId() {
return itemId;
}
private String getItemName() {
return itemName;
}
}
}

View File

@@ -30,6 +30,7 @@ public enum BookmarkEnum {
private String desc;
/** 书签处理顺序1=数据项2=结果信息3=目录信息;由 dealDataModelScatteredByBookmark 排序时使用 */
private Integer sort;
BookmarkEnum(String key, String desc, Integer sort) {

View File

@@ -68,15 +68,13 @@ import com.njcn.gather.storage.service.SimAndDigHarmonicService;
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.dictionary.pojo.po.DictData;
import com.njcn.gather.system.dictionary.service.IDictDataService;
import com.njcn.gather.system.pojo.enums.SystemResponseEnum;
import com.njcn.gather.tools.report.model.constant.ReportConstant;
import com.njcn.gather.tools.report.service.IWordReportService;
import com.njcn.gather.tools.report.util.BookmarkUtil;
import com.njcn.gather.tools.report.util.Docx4jUtil;
import com.njcn.gather.tools.report.util.DocxMergeUtil;
import com.njcn.gather.tools.report.util.WordDocumentUtil;
import com.njcn.gather.tools.report.util.*;
import com.njcn.gather.type.pojo.po.DevType;
import com.njcn.gather.type.service.IDevTypeService;
import com.njcn.gather.user.user.pojo.po.SysUser;
@@ -133,13 +131,24 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> implements IPqReportService {
@Value("${report.template:D:\\template}")
private String templatePath;
@Value("${report.reportDir:D:\\report}")
private String reportPath;
/**
* resultMap 内部协议:当 dealDataLine 跑完一轮但未采集到任何有效合格性数据时,
* 在 resultMap 中塞入这个 key 作为"已尝试且无数据"的哨兵,避免后续 TEST_RESULT_*
* 分支的 fallback 重复调用 dealDataLine 浪费资源;同时 dealTestResultLine 检测到
* 此 key 存在时跳过结论表生成。
* <p>
* 故意使用明显非业务字符串,避免与任何 PqScriptDtls.scriptCode / PowerIndexEnum
* 的真实业务取值撞车。
*/
private static final String RESULT_MAP_NO_DATA_FLAG = "__internal_no_data__";
// @Value("${report.template:D:\\template}")
// private String templatePath;
//
// @Value("${report.reportDir:D:\\report}")
// private String reportPath;
private final PathConfig pathConfig;
@Value("${qr.cloud}")
private String cloudUrl;
@@ -316,7 +325,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
MultipartFile baseFile = reportParam.getBaseFile();
MultipartFile detailFile = reportParam.getDetailFile();
String relativePath = reportParam.getName() + File.separator + reportParam.getVersion() + File.separator;
String newDir = templatePath + File.separator + relativePath;
String newDir = pathConfig.getReportTemplatePath() + File.separator + relativePath;
long FILE_SIZE_LIMIT = 5 * 1024 * 1024;
if (isAdd) {
@@ -393,13 +402,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
// 文件夹重命名
String oldBasePathStr = oldPqReport.getBasePath();
String baseName = oldBasePathStr.substring(oldBasePathStr.lastIndexOf(File.separator) + 1);
Path oldBasePath = Paths.get(templatePath + File.separator + oldBasePathStr);
Path oldBasePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldBasePathStr);
Path newBasePath = Paths.get(newDir + baseName);
pqReport.setBasePath(relativePath + baseName);
String oldDetailPathStr = oldPqReport.getDetailPath();
String detailName = oldDetailPathStr.substring(oldDetailPathStr.lastIndexOf(File.separator) + 1);
Path oldDetailPath = Paths.get(templatePath + File.separator + oldDetailPathStr);
Path oldDetailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldDetailPathStr);
Path newDetailPath = Paths.get(newDir + detailName);
pqReport.setDetailPath(relativePath + detailName);
@@ -410,13 +419,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
Files.move(oldBasePath, newBasePath);
Files.move(oldDetailPath, newDetailPath);
if (!oldPqReport.getName().equals(reportParam.getName()) && !this.existSameName(pqReport.getId(), oldPqReport.getName())) {
this.recursionDeleteDirectory(templatePath + File.separator + oldPqReport.getName());
this.recursionDeleteDirectory(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getName());
} else {
Paths.get(templatePath + oldDir).toFile().delete();
Paths.get(pathConfig.getReportTemplatePath() + oldDir).toFile().delete();
}
} else {
// 文件夹重命名
Paths.get(templatePath + oldDir).toFile().renameTo(Paths.get(newDir).toFile());
Paths.get(pathConfig.getReportTemplatePath() + oldDir).toFile().renameTo(Paths.get(newDir).toFile());
}
} catch (IOException e) {
throw new BusinessException(ReportResponseEnum.FILE_RENAME_FAILED);
@@ -425,13 +434,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
if (!baseFileOriginalFilename.isEmpty()) {
pqReport.setBasePath(relativePath + baseFileOriginalFilename);
Paths.get(templatePath + File.separator + oldPqReport.getBasePath()).toFile().delete();
Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getBasePath()).toFile().delete();
Paths.get(newDir + oldPqReport.getBasePath().substring(oldPqReport.getBasePath().lastIndexOf(File.separator) + 1)).toFile().delete();
this.uploadFile(baseFile, newDir + baseFileOriginalFilename);
}
if (!detailFileOriginalFilename.isEmpty()) {
pqReport.setDetailPath(relativePath + detailFileOriginalFilename);
Paths.get(templatePath + File.separator + oldPqReport.getDetailPath()).toFile().delete();
Paths.get(pathConfig.getReportTemplatePath() + File.separator + oldPqReport.getDetailPath()).toFile().delete();
Paths.get(newDir + oldPqReport.getDetailPath().substring(oldPqReport.getDetailPath().lastIndexOf(File.separator) + 1)).toFile().delete();
this.uploadFile(detailFile, newDir + detailFileOriginalFilename);
}
@@ -516,7 +525,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
private void deleteFile(List<String> ids) {
List<PqReport> pqReports = this.listByIds(ids);
for (PqReport pqReport : pqReports) {
String uploadDir = templatePath + File.separator + pqReport.getName() + File.separator + pqReport.getVersion() + File.separator;
String uploadDir = pathConfig.getReportTemplatePath() + File.separator + pqReport.getName() + File.separator + pqReport.getVersion() + File.separator;
Path uploadPath = Paths.get(uploadDir);
if (Files.exists(uploadPath)) {
//清空目录下的文件
@@ -528,7 +537,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
}
file1.delete();
String dir = templatePath + File.separator + pqReport.getName() + File.separator;
String dir = pathConfig.getReportTemplatePath() + File.separator + pqReport.getName() + File.separator;
Path dirPath = Paths.get(dir);
File dirFile = dirPath.toFile();
File[] fileArr2 = dirFile.listFiles();
@@ -583,6 +592,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
/**
* 根据设备类型生成报告
* 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param devReportParam 被检设备信息
*/
@@ -617,8 +631,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
InputStream finalWordStream = DocxMergeUtil.mergeDocuments(wordFileInputStreams);
// 处理需要输出的目录地址 基础路径+设备类型+装置编号.docx
// 最终文件输出的路径
// String dirPath = reportPath.concat(File.separator).concat(devType.getName());
String dirPath = reportPath;
// String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
String dirPath = pathConfig.getReportPath();
// 确保目录存在
ensureDirectoryExists(dirPath);
String reportFullPath = dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
@@ -783,6 +797,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
/**
* 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果
* 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param plan 计划信息
* @param devReportParam 设备信息
@@ -806,8 +825,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
if (Objects.isNull(report)) {
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
}
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
try (InputStream baseInputStream = Files.newInputStream(basePath);
InputStream detailInputStream = Files.newInputStream(detailPath)) {
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
@@ -821,7 +840,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
dealDataModelScatteredByBookmarkByPlanContrast(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
// 保存新的文档
String dirPath = reportPath.concat(File.separator).concat(plan.getName());
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName()));
// 确保目录存在
ensureDirectoryExists(dirPath);
// 构建文件名cityName_gdName_subName_name.docx
@@ -861,6 +880,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
/**
* 根据计划绑定的报告模板生成报告
* 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式
* <p>
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
* 而非待修复缺陷。
*
* @param plan 计划信息
* @param devReportParam 设备信息
@@ -883,8 +907,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
if (Objects.isNull(report)) {
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
}
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
try (InputStream baseInputStream = Files.newInputStream(basePath);
InputStream detailInputStream = Files.newInputStream(detailPath)) {
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
@@ -899,7 +923,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
// 保存新的文档
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName()));
// 确保目录存在
ensureDirectoryExists(dirPath);
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX)));
@@ -950,9 +974,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
* 1、数据项
* 2、结果信息
* 3、目录信息
* 所以要先先获取的书签进行操作排
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺
* */
Collections.sort(bookmarkEnums);
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
List<Object> todoInsertList;
BookmarkUtil.BookmarkInfo bookmarkInfo;
Map<Integer/*回路号*/, List<ContrastTestResult>> resultMap = null;
@@ -1173,7 +1197,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
Integer monitorNum = next.getKey();
// 线路下的指标数据
List<ContrastTestResult> contrastTestResults = next.getValue();
PqMonitor pqMonitor = pqMonitorService.getByDevAndNum(pqDevVO.getId(), monitorNum);
PqMonitor pqMonitor = pqMonitorService.getByDevIdAndNum(pqDevVO.getId(), monitorNum);
// 插入回路号前,先换个页
todoInsertList.add(Docx4jUtil.createPageBreakParagraph());
// 回路标题
@@ -1230,9 +1254,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
* 1、数据项
* 2、结果信息
* 3、目录信息
* 所以要先先获取的书签进行操作排
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺
* */
Collections.sort(bookmarkEnums);
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
// 定义个结果,以便存在结果信息的书签
Map<String/*指标名称*/, List<Boolean/*以回路的顺序填充结果*/>> resultMap = new HashMap<>();
List<Object> todoInsertList;
@@ -1281,7 +1305,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
if (CollUtil.isEmpty(resultMap)) {
dealDataLine(baseDocumentPart, devReportParam, pqDevVO, resultMap);
}
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_LINE.getKey(), bookmarks);
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.TEST_RESULT_DETAIL.getKey(), bookmarks);
todoInsertList = dealTestResultLine(devReportParam, resultMap, DocAnchorEnum.TEST_RESULT_DETAIL);
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
@@ -1306,8 +1330,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
*/
private List<Object> dealTestResultLine(DevReportParam devReportParam, Map<String, List<Boolean>> resultMap, DocAnchorEnum docAnchorEnum) {
List<Object> todoInsertList = new ArrayList<>();
// 先判断数据有没有,如果没有,则不处理
if (CollUtil.isEmpty(resultMap.get(PowerIndexEnum.UNKNOWN.getKey()))) {
// 先判断数据有没有,如果没有,则不处理(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)
if (!resultMap.containsKey(RESULT_MAP_NO_DATA_FLAG)) {
ObjectFactory factory = Context.getWmlObjectFactory();
// 源文档的内容
// 创建表格示例为3列列数可任意调整
@@ -1396,13 +1420,27 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
/**
* 处理以回路维度数据项,书签占位符的方式
* 以回路维度处理数据项,并填充 resultMap指标合格性结论
* <p>
* 本方法承担双重职责:
* <ol>
* <li><b>返回值</b>:根据 modelPart 中的 H5 分组表格模板,灌入实测数据后生成可插入文档的元素列表;</li>
* <li><b>副作用</b>:把每个指标在各回路上的合格性写入 resultMap供后续 dealTestResultLine 构造结论表使用。</li>
* </ol>
* 调用约定(务必区分以下两条路径,避免误解形参用途):
* <ul>
* <li><b>常规路径</b>DATA_LINE 分支modelPart 传 detail 文档(数据页模板池),返回值会被插入 DATA_LINE 书签锚点。</li>
* <li><b>fallback 路径</b>TEST_RESULT_* 分支且 resultMap 为空时modelPart 允许传 base 文档(封面页);此时模板池为空,返回值无业务意义,调用方应丢弃,仅借此触发 resultMap 计算。</li>
* </ul>
* 因此 modelPart 命名保持中性,不要改回 detailXxx 等带语义偏向的名字。
*
* @param detailModelDocument 数据项模板
* @param devReportParam 测试报告参数
* @param pqDevVO 被检设备
* @param modelPart 文档模板部分;常规传 detail 文档fallback 仅需算 resultMap 时可传 base 文档
* @param devReportParam 测试报告参数
* @param pqDevVO 被检设备
* @param resultMap 结果性数据集合被本方法写入fallback 路径正是借此计算)
* @return 待插入文档的元素列表fallback 路径下应被调用方丢弃
*/
private List<Object> dealDataLine(MainDocumentPart detailModelDocument, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
private List<Object> dealDataLine(MainDocumentPart modelPart, DevReportParam devReportParam, PqDevVO pqDevVO, Map<String, List<Boolean>> resultMap) {
List<Object> todoInsertList = new ArrayList<>();
// 以回路维度处理数据项
Integer devChns = pqDevVO.getDevChns();
@@ -1410,8 +1448,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
// 读取该计划的检测大项组装数据内容
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList()));
List<Object> allContent = detailModelDocument.getContent();
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, detailModelDocument);
List<Object> allContent = modelPart.getContent();
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, modelPart);
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream().collect(Collectors.groupingBy(Docx4jUtil.HeadingContent::getHeadingText, Collectors.toList()));
for (int i = 0; i < devChns; i++) {
// 回路标题
@@ -1479,9 +1517,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
}
}
}
// 如果经过一处理后,结果性数据集合还是空,塞个特殊数据进去,避免嵌套循环
// 经过一处理仍未采集到任何合格性数据时,塞入哨兵:
// 一是让后续 TEST_RESULT_* 分支的 fallback 看到 resultMap 非空而跳过重复调用本方法,
// 二是供 dealTestResultLine 据此跳过结论表生成(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)。
if (CollUtil.isEmpty(resultMap)) {
resultMap.put(PowerIndexEnum.UNKNOWN.getKey(), Collections.singletonList(false));
resultMap.put(RESULT_MAP_NO_DATA_FLAG, Collections.singletonList(false));
}
return todoInsertList;
}
@@ -1894,7 +1934,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
if (SceneEnum.LEAVE_FACTORY_TEST.getValue().equals(currrentScene)) {
// 出厂测试场景
filePath = reportPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
filePath = pathConfig.getReportPath().concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
} else if (plan != null) {
// 根据计划模式确定路径结构
@@ -1906,16 +1946,16 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
pqDevVO.getGdName() != null ? pqDevVO.getGdName() : "未知供电公司",
pqDevVO.getSubName() != null ? pqDevVO.getSubName() : "未知电站",
pqDevVO.getName() != null ? pqDevVO.getName() : "未知设备");
filePath = reportPath.concat(File.separator).concat(plan.getName()).concat(File.separator).concat(fileName);
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(plan.getName())).concat(File.separator).concat(fileName);
downloadFileName = fileName;
} else {
// 数字/模拟模式:使用原来的路径结构
filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
}
} else {
// 兜底:使用旧的路径结构
filePath = reportPath.concat(File.separator).concat(devType.getName()).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
filePath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName())).concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
}
@@ -2443,7 +2483,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
return;
}
log.info("找到{}台设备需要上传报告", devices.size());
String dirPath = reportPath;
String dirPath = pathConfig.getReportPath();
// 确保目录存在
ensureDirectoryExists(dirPath);
// 异步批量上传每台设备的报告
@@ -2503,7 +2543,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
* 创建回路标题到报告中
*/
private P getContrastLineTitle(Map<String, List<Docx4jUtil.HeadingContent>> contentMap, int monitorNum, int index, ObjectFactory factory, PqDevVO pqDevVO) {
PqMonitor pqMonitor = pqMonitorService.getByDevAndNum(pqDevVO.getId(), monitorNum);
PqMonitor pqMonitor = pqMonitorService.getByDevIdAndNum(pqDevVO.getId(), monitorNum);
String monitorInfoName = "";
if (StrUtil.isNotBlank(pqDevVO.getSubName()) && Objects.nonNull(pqMonitor)) {
monitorInfoName = "(" + pqDevVO.getSubName() + "-" + pqMonitor.getName() + ")";

View File

@@ -198,7 +198,7 @@ public class ResultController extends BaseController {
String methodDescribe = getMethodDescribe("getCheckItem");
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, monitorQueryParam);
List<ContrastTestItemVO> result = resultService.getCheckItem(monitorQueryParam.getPlanId(), monitorQueryParam.getDevId(), monitorQueryParam.getChnNum(), monitorQueryParam.getNum());
List<ContrastTestItemVO> result = resultService.getCheckItem(monitorQueryParam.getPlanId(), monitorQueryParam.getDevId(), monitorQueryParam.getChnNum(), monitorQueryParam.getNum(), monitorQueryParam.getCode());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
}

View File

@@ -17,4 +17,6 @@ public class MonitorQueryParam {
private Integer waveNum;
private String planId;
private String code;
}

View File

@@ -123,9 +123,10 @@ public interface IResultService {
* @param devId
* @param chnNum
* @param num
* @param code
* @return
*/
List<ContrastTestItemVO> getCheckItem(String planId, String devId, String chnNum, Integer num);
List<ContrastTestItemVO> getCheckItem(String planId, String devId, String chnNum, Integer num,String code);
/**
* 获取设备比对式结果,用于出比对检测的报告

View File

@@ -341,10 +341,19 @@ public class ResultServiceImpl implements IResultService {
private void dipScriptTypeName(List<PqScriptDtls> subValue, List<TreeDataVO> subTypeList, Map<Integer, Set<Integer>> finalResultMap, Boolean isValueType, String name, Integer start, Integer end) {
List<TreeDataVO> info = new ArrayList<>();
List<PqScriptDtls> dip = subValue.stream()
.filter(x -> "Dip".equals(x.getValueType()) && "A".equals(x.getPhase()))
// .filter(x -> "Dip".equals(x.getValueType()) && "A".equals(x.getPhase()))
.filter(x -> "Dip".equals(x.getValueType()))
.filter(x -> x.getTransValue() >= start && x.getTransValue() <= end)
.sorted(Comparator.comparing(PqScriptDtls::getScriptIndex))
.collect(Collectors.toList());
LinkedHashMap<Integer, List<PqScriptDtls>> idxDipMap = dip.stream().collect(Collectors.groupingBy(d -> d.getScriptIndex(), LinkedHashMap::new, Collectors.toList()));
dip.clear();
idxDipMap.forEach((idx, scriptDtlList) -> {
scriptDtlList.sort(Comparator.comparing(PqScriptDtls::getPhase));
dip.add(scriptDtlList.get(0));
});
TreeDataVO vo = new TreeDataVO();
vo.setScriptTypeName(name);
vo.setScriptTypeCode("Base_" + start + "_" + end);
@@ -1883,10 +1892,10 @@ public class ResultServiceImpl implements IResultService {
}
@Override
public List<ContrastTestItemVO> getCheckItem(String planId, String devId, String chnNum, Integer num) {
public List<ContrastTestItemVO> getCheckItem(String planId, String devId, String chnNum, Integer num, String code) {
// PqDev dev = pqDevService.getById(devId);
AdPlan plan = adPlanService.getById(planId);
String code = String.valueOf(plan.getCode());
// String code = String.valueOf(plan.getCode());
String monitorId = devId + CnSocketUtil.SPLIT_TAG + chnNum;
@@ -3131,7 +3140,7 @@ public class ResultServiceImpl implements IResultService {
checkDataParam.setIsValueTypeName(false);
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity());
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), false);
}
/**

View File

@@ -34,6 +34,7 @@ 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.source.service.IPqSourceService;
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;
@@ -68,20 +69,17 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
private final static String INHARM_I = "InHarm_I";
private final static String DIP = "Dip";
private final static String FLICKER = "Flicker";
// @Value("${Dip.fPreTime}")
// @Value("${Dip.fPreTime}")
// private Double fPreTime;
@Value("${Dip.fRampIn}")
private Double fRampIn;
@Value("${Dip.fRampOut}")
private Double fRampOut;
// @Value("${Dip.fAfterTime}")
// @Value("${Dip.fAfterTime}")
// private Double fAfterTime;
@Value("${Flicker.waveFluType}")
private String waveFluType;
@Value("${Flicker.waveType}")
private String waveType;
@Value("${Flicker.fDutyCycle}")
private Double fDutyCycle;
private static final String waveFluType = "SQU";
private static final String waveType = "CPM";
private static final Double fDutyCycle = 50.0;
private final IPqDevService pqDevService;
@@ -91,6 +89,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
private final IDevTypeService devTypeService;
private final IDictTreeService dictTreeService;
private final AdPlanMapper adPlanMapper;
private final IPqSourceService pqSourceService;
@Override
@Transactional
@@ -422,7 +421,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
@Override
public List<PqScriptDtlsParam.CheckData> scriptDtlsCheckDataList(PqScriptDtlsParam sourceIssue) {
Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
// Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
List<PqScriptDtlsParam.CheckData> info = new ArrayList<>();
//获取所有下拉值情况
@@ -630,9 +629,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
//电压*电流*cos电压角度-电流角度)
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000 * Math.cos((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100 * Math.cos((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
// if (valueType) {
checkData.setValue(checkData.getValue() * 57.74 * 5);
// checkData.setValue(checkData.getValue() * 57.74 * 5);
// }
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
}
@@ -653,9 +652,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
//电压*电流*cos电压角度-电流角度)
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000 * Math.sin((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100 * Math.sin((listDTO.getFPhase() - channelI.get(0).getFPhase()) * Math.PI / 180));
// if (valueType) {
checkData.setValue(checkData.getValue() * 57.74 * 5);
// checkData.setValue(checkData.getValue() * 57.74 * 5);
// }
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
}
@@ -676,9 +675,9 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
checkData.setErrorFlag(channelListDTO.getErrorFlag());
checkData.setEnable(channelListDTO.getEnable());
//电压*电流*cos电压角度-电流角度)
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 10000);
checkData.setValue(channelI.get(0).getFAmp() * listDTO.getFAmp() / 100);
// if (valueType) {
checkData.setValue(checkData.getValue() * 57.74 * 5);
// checkData.setValue(checkData.getValue() * 57.74 * 5);
// }
setCheck(info, checkData, channelListDTO, checkArchive, listDTO);
}
@@ -781,7 +780,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
@Override
public Set<String> getScriptToIcdCheckInfo(PreDetectionParam param) {
PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setSourceId(param.getSourceId());
issueParam.setSourceId(param.getSourceName());
issueParam.setDevIds(param.getDevIds());
issueParam.setScriptId(param.getScriptId());
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
@@ -974,7 +973,7 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
for (int i = 0; i < pqScriptDtls.size(); i++) {
PqScriptDtls scriptDtls = pqScriptDtls.get(i);
// 注意此处scriptDtls.getValue() < 1.0,考虑到有些已经投入运行的地方,可能没有改库,避免不必要的异常
if(scriptDtls.getValueType().equalsIgnoreCase("CUR") && scriptDtls.getValue() < 1.0){
if (scriptDtls.getValueType().equalsIgnoreCase("CUR") && scriptDtls.getValue() < 1.0) {
scriptDtls.setValue(devCurr * scriptDtls.getValue());
}
}
@@ -1065,9 +1064,16 @@ public class PqScriptDtlsServiceImpl extends ServiceImpl<PqScriptDtlsMapper, PqS
channelListDTO.setDipData(dipDataDTO);
//闪变数据
SourceIssue.ChannelListDTO.FlickerDataDTO flickerDataDTO = new SourceIssue.ChannelListDTO.FlickerDataDTO();
flickerDataDTO.setWaveFluType(waveFluType);
flickerDataDTO.setWaveType(waveType);
flickerDataDTO.setFDutyCycle(fDutyCycle);
SourceIssue.ChannelListDTO.FlickerDataDTO flickerData = channelListDTO.getFlickerData();
if (ObjectUtil.isNotNull(flickerData)) {
flickerDataDTO.setWaveFluType(flickerData.getWaveFluType());
flickerDataDTO.setWaveType(flickerData.getWaveType());
flickerDataDTO.setFDutyCycle(flickerData.getFDutyCycle());
} else {
flickerDataDTO.setWaveFluType(waveFluType);
flickerDataDTO.setWaveType(waveType);
flickerDataDTO.setFDutyCycle(fDutyCycle);
}
flickerDataDTO.setFChagFre(0.0);
flickerDataDTO.setFChagValue(0.0);

View File

@@ -0,0 +1,16 @@
package com.njcn.gather.plan.pojo.vo;
import org.junit.Assert;
import org.junit.Test;
public class PlanStatisticsVOTest {
@Test
public void shouldExposeQualifiedDeviceCount() {
PlanStatisticsVO statistics = new PlanStatisticsVO();
statistics.setQualifiedDeviceCount(6);
Assert.assertEquals(Integer.valueOf(6), statistics.getQualifiedDeviceCount());
}
}

View File

@@ -1,15 +1,15 @@
server:
port: 18092
port: 18093
spring:
application:
name: entrance
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://192.168.1.24:13306/pqs91002?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
url: jdbc:mysql://192.168.1.24:13306/pqs9100?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
# username: root
# password: njcnpqs
url: jdbc:mysql://192.168.1.24:13306/pqs9100_nx?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
# url: jdbc:mysql://127.0.0.1:3306/pqs9100?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
username: root
password: njcnpqs
#初始化建立物理连接的个数、最小、最大连接数
@@ -36,9 +36,9 @@ mybatis-plus:
#驼峰命名
map-underscore-to-camel-case: true
#配置sql日志输出
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#关闭日志输出
# log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
global-config:
db-config:
#指定主键生成策略
@@ -60,34 +60,36 @@ socket:
# port: 61000
webSocket:
port: 7777
port: 7778
#源参数下发,暂态数据默认值
Dip:
#暂态前时间s
fPreTime: 2f
# 暂态前时间s
# fPreTime: 2f
#写入时间s
fRampIn: 0.001f
#写出时间s
fRampOut: 0.001f
#暂态后时间s
fAfterTime: 3f
# 暂态后时间s
# fAfterTime: 3f
Flicker:
waveFluType: CPM
waveType: SQU
fDutyCycle: 50f
#Flicker:
# waveFluType: CPM
# waveType: SQU
# fDutyCycle: 50f
log:
homeDir: D:\logs
commonLevel: info
#log:
# homeDir: D:\logs
# commonLevel: info
report:
template: D:\template
reportDir: D:\report
# template: D:\template
# reportDir: D:\report
dateFormat: yyyy年MM月dd日
data:
homeDir: D:\data
#data:
# homeDir: D:\data
#resource:
# videoDir: ${data.homeDir}\resources\videos
qr:
cloud: http://pqmcc.com:18082/api/file
dev:
@@ -122,4 +124,4 @@ power-quality:
# 激活配置
activate:
private-key: "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCcUyYhVqczGxblL+o/xZzF/8nf+LjrfUE/dS1aRHM7uMDD0cgCArhjtfneFePrMxt+Z7W8yNBzSarub8qsfhaVNikV7Es7oaeTygfjQXTi2n4AFkir3fM07J08RpWhl5M8f8uWTCuvFUYAw00gq55typqmnbkmJa2VIUy/iQf+cMCP7abz4/jNhUzUR3qA7TV4oMRgTdIEDUp63YF8dOC+JH8XxYrCVeHXV6fLCwmesdMzl0lB2VTEKMfLbXhOmF5g7P9y/16VCcN8UBuZlbyYfn+GAxJOSbeHi5HshOKfoSuD7Jz+3WQZpNavOWjIFExKIU38/CvnJCOP7XBCqpSTAgMBAAECggEAYeWokWRE3TpvwiOZnUpR/aVMdVi75a3ROL5XIpqPV61B+t/bU3cEpl0GF9C5pUeiRi0IoStZb3mI9D1KPW/REKyUWkhabQO1gFYbTnRlkNOn6MILzKX4cwJjDaZeeo4EBPU7N+qHyOOXrU6hdH5FfxhMdV983ajm5eeuupxER1C2kAcIklTeVpTX6EKOgZb5LBp5ssOVm2P42pOauvcRozRcvZmqnErXmukv0H4l3EVNt4rHpTn9riHUC63e8JfiYzVaF6zuNUxv6nHEft0/SRMw11XSTnNfDzcKqgjz6ksFBS/6eQQYKESk+ONC53HUuYHFAknkwsPupDCT2W8FIQKBgQDLHT/xCU3nxGr4vFKBDNaO2D5oK20ECbBO4oDvLWWmQG7f+6TsMy8PgVdMnoL4RfqGlwFAKEpS6KVFHnBVqnNEhcdy9uCI7x7Xx8UnyUtxj1EDTm76uta9Ki9OrlqB6tImDM9+Ya3vGktW37ht4WOx2OsJRhG1dbf6RLwFlH7DWwKBgQDFBxvi5I1BR6hg6Tj7xd2SqOT2Y+BED3xuSYENhWbmMhLJDResaB7mjztbxlYaY2mOE0holWm2uDmVFFhMh4jYXik4hYH8nmDzq9mDpZCZ9pyjYqnAP8THoAa8EbgrUWB8A6BPH4iL3KbMnBfBKY0pIr2xrvnjQjNBAgta7KDRKQKBgCe6oe4wxrdF2TKsC2tIqpMoQxS3Icy/ZGgZr+SYuaBKTCWtoDW/UT40K3JGMxIDBhzbXphBCUCsVt9tM8Xd4EwP6tJW7dZ7B0pnve2pVwNwaAVAiz6p2yUHIle+jN+Koe5lZRSwYIg7WW81tWpwwsJfzqFyvjYDP6hJV4mz4ROvAoGAaRcdnKvjXApomShMqJ4lTPChD3q+SA8qg3jZSOj6tZXHx00gb2kp8jg7pPvpOTIFPy6x1Ha9aCRjMk0ju84fA6lVuzwa1S907wOehUVuF3Eeo1cgy9Y3k3KbpPyeixxgpkUY4JslLdSHc2NemD0dee951qhJyRmqVOZOQDUuoeECgYEAqBw2cAFk3vM97WY06TSldGA8ajVHx3BYRjj+zl62NTQthy8fw3tqxb3c5e8toOmZWKjZvDhg2TRLhsDDQWEYg3LZG87REqVIjgEPcpjNLidjygGX8n3JF2o0O5I/EMvl0s/+LVQONfduOBvhwDqr8QNisbLsyneiAq7umewMolo="
public-key: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnFMmIVanMxsW5S/qP8Wcxf/J3/i4631BP3UtWkRzO7jAw9HIAgK4Y7X53hXj6zMbfme1vMjQc0mq7m/KrH4WlTYpFexLO6Gnk8oH40F04tp+ABZIq93zNOydPEaVoZeTPH/LlkwrrxVGAMNNIKuebcqapp25JiWtlSFMv4kH/nDAj+2m8+P4zYVM1Ed6gO01eKDEYE3SBA1Ket2BfHTgviR/F8WKwlXh11enywsJnrHTM5dJQdlUxCjHy214TpheYOz/cv9elQnDfFAbmZW8mH5/hgMSTkm3h4uR7ITin6Erg+yc/t1kGaTWrzloyBRMSiFN/Pwr5yQjj+1wQqqUkwIDAQAB"
public-key: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnFMmIVanMxsW5S/qP8Wcxf/J3/i4631BP3UtWkRzO7jAw9HIAgK4Y7X53hXj6zMbfme1vMjQc0mq7m/KrH4WlTYpFexLO6Gnk8oH40F04tp+ABZIq93zNOydPEaVoZeTPH/LlkwrrxVGAMNNIKuebcqapp25JiWtlSFMv4kH/nDAj+2m8+P4zYVM1Ed6gO01eKDEYE3SBA1Ket2BfHTgviR/F8WKwlXh11enywsJnrHTM5dJQdlUxCjHy214TpheYOz/cv9elQnDfFAbmZW8mH5/hgMSTkm3h4uR7ITin6Erg+yc/t1kGaTWrzloyBRMSiFN/Pwr5yQjj+1wQqqUkwIDAQAB"

View File

@@ -325,7 +325,7 @@ public class DetectionDataServiceImpl extends ReplenishMybatisServiceImpl<Detect
resultFlags = resultFlags.stream().filter(x -> 4 != x && 5 != x).distinct().collect(Collectors.toList());
if (CollUtil.isNotEmpty(resultFlags)) {
if (resultFlags.contains(2)) {
return 2;
return 0;
} else {
switch (resultFlags.get(0)) {
case 1:

View File

@@ -28,6 +28,9 @@ public class SysTestConfigParam {
@ApiModelProperty(value = "场景")
private String scene;
@ApiModelProperty(value = "比对监测后,当电压、电流不符合时,是否对标准设备进行系数校准")
private Integer coefficient;
@Data
public static class UpdateParam extends SysTestConfigParam {
@ApiModelProperty("id")

View File

@@ -51,6 +51,11 @@ public class SysTestConfig extends BaseEntity implements Serializable {
*/
private Integer scale;
/**
* 比对监测后,当电压、电流不符合时,是否对标准设备进行系数校准
*/
private Integer coefficient;
/**
* 状态0-删除 1-正常

View File

@@ -49,6 +49,7 @@ public class SysTestConfigServiceImpl extends ServiceImpl<SysTestConfigMapper, S
oneConfig.setScale(ObjectUtil.isNotNull(param.getScale()) ? param.getScale() : oneConfig.getScale());
oneConfig.setMaxTime(ObjectUtil.isNotNull(param.getMaxTime()) ? param.getMaxTime() : oneConfig.getMaxTime());
oneConfig.setScene(StringUtils.isNotBlank(param.getScene()) ? param.getScene() : oneConfig.getScene());
oneConfig.setCoefficient(param.getCoefficient());
return this.updateById(oneConfig);
}

View File

@@ -0,0 +1,50 @@
package com.njcn.gather.system.config;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.File;
/**
* @author caozehui
* @data 2026-05-28
*/
@Component
public class PathConfig {
private String appPath;
@PostConstruct
public void init() {
// 获取程序运行目录
appPath = System.getProperty("user.dir");
// 或者获取jar包所在目录
// appPath = new File(getClass().getProtectionDomain()
// .getCodeSource().getLocation().getPath()).getParent();
}
public String getAppPath() {
return appPath;
}
public String getLogPath() {
return appPath + File.separator + "logs";
}
public String getDataPath() {
return appPath + File.separator + "data";
}
public String getReportTemplatePath() {
return this.getDataPath() + File.separator + "template";
}
public String getReportPath() {
return this.getDataPath() + File.separator + "report";
}
public String getResourcePath() {
return this.getDataPath() + File.separator + "resource";
}
}

View File

@@ -0,0 +1,100 @@
package com.njcn.gather.system.resource.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;
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
import com.njcn.gather.system.resource.service.IResourceManageService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
/**
* 资源管理
*/
@Slf4j
@Api(tags = "资源管理")
@RestController
@RequestMapping("/resourceManage")
@RequiredArgsConstructor
public class ResourceManageController extends BaseController {
private final IResourceManageService resourceManageService;
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@PostMapping("/list")
@ApiOperation("分页查询资源列表")
@ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
public HttpResult<Page<ResourceManageVO>> list(@RequestBody @Validated ResourceManageParam.QueryParam queryParam) {
String methodDescribe = getMethodDescribe("list");
LogUtil.njcnDebug(log, "{},查询参数为:{}", methodDescribe, queryParam);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, resourceManageService.list(queryParam), methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD)
@PostMapping("/add")
@ApiOperation("新增视频资源")
@ApiImplicitParam(name = "resourceManageParam", value = "资源参数", required = true)
public HttpResult<Boolean> add(ResourceManageParam resourceManageParam) {
String methodDescribe = getMethodDescribe("add");
LogUtil.njcnDebug(log, "{},新增资源参数为:{}", methodDescribe, resourceManageParam);
boolean result = resourceManageService.add(resourceManageParam);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE)
@PostMapping("/update")
@ApiOperation("编辑资源信息")
@ApiImplicitParam(name = "updateParam", value = "资源参数", required = true)
public HttpResult<Boolean> update(@RequestBody @Validated ResourceManageParam.UpdateParam updateParam) {
String methodDescribe = getMethodDescribe("update");
LogUtil.njcnDebug(log, "{},编辑资源参数为:{}", methodDescribe, updateParam);
boolean result = resourceManageService.update(updateParam);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
}
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
@GetMapping("/play")
@ApiOperation("获取视频播放地址")
@ApiImplicitParam(name = "id", value = "资源id", required = true)
public HttpResult<PlayVO> play(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("play");
LogUtil.njcnDebug(log, "{}资源id为{}", methodDescribe, id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, resourceManageService.play(id), methodDescribe);
}
@GetMapping("/stream")
@ApiOperation("播放视频流")
public void stream(@RequestParam("id") String id,
@RequestParam("token") String token,
@RequestHeader(value = "Range", required = false) String rangeHeader,
HttpServletResponse response) {
resourceManageService.stream(id, token, rangeHeader, response);
}
}

View File

@@ -0,0 +1,10 @@
package com.njcn.gather.system.resource.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
/**
* 资源管理 mapper
*/
public interface ResourceManageMapper extends MPJBaseMapper<ResourceManage> {
}

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njcn.gather.system.resource.mapper.ResourceManageMapper">
</mapper>

View File

@@ -0,0 +1,32 @@
package com.njcn.gather.system.resource.pojo.enums;
import lombok.Getter;
/**
* 资源管理业务响应
*/
@Getter
public enum ResourceManageResponseEnum {
NAME_NOT_BLANK("A013001", "资源名称不能为空"),
REMARK_NOT_BLANK("A013002", "备注不能为空"),
FILE_NOT_NULL("A013003", "上传的视频文件不能为空"),
FILE_SUFFIX_ERROR("A013004", "仅支持上传 MP4 文件"),
FILE_SIZE_ERROR("A013005", "文件大小不能超过 250MB"),
FILE_UPLOAD_FAILED("A013006", "文件上传失败"),
RESOURCE_NOT_EXIST("A013007", "资源不存在"),
RESOURCE_FILE_NOT_EXIST("A013008", "资源文件不存在"),
PLAY_TOKEN_INVALID("A013009", "播放授权无效"),
PLAY_TOKEN_EXPIRED("A013010", "播放授权已过期"),
RANGE_INVALID("A013011", "视频请求范围非法"),
DISK_SPACE_NOT_ENOUGH("A013012", "磁盘空间不足"),
ID_NOT_BLANK("A013013", "资源id不能为空");
private final String code;
private final String message;
ResourceManageResponseEnum(String code, String message) {
this.code = code;
this.message = message;
}
}

View File

@@ -0,0 +1,45 @@
package com.njcn.gather.system.resource.pojo.param;
import com.njcn.web.pojo.param.BaseParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.web.multipart.MultipartFile;
/**
* 资源管理参数
*/
@Data
public class ResourceManageParam {
@ApiModelProperty(value = "资源名称", required = true)
private String name;
@ApiModelProperty(value = "备注", required = true)
private String remark;
@ApiModelProperty(value = "视频文件", required = true)
private MultipartFile file;
@Data
public static class UpdateParam {
@ApiModelProperty(value = "资源id", required = true)
private String id;
@ApiModelProperty(value = "资源名称", required = true)
private String name;
@ApiModelProperty(value = "备注", required = true)
private String remark;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty("资源名称")
private String name;
@ApiModelProperty("原始文件名")
private String fileName;
}
}

View File

@@ -0,0 +1,32 @@
package com.njcn.gather.system.resource.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.mybatisplus.bo.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
/**
* 资源管理
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("sys_resource_manage")
public class ResourceManage extends BaseEntity implements Serializable {
private static final long serialVersionUID = 684206384930125506L;
private String id;
private String name;
private String fileName;
private Long fileSize;
private String relativePath;
private String remark;
private Integer state;
}

View File

@@ -0,0 +1,15 @@
package com.njcn.gather.system.resource.pojo.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 播放授权信息
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PlayVO {
private String url;
}

View File

@@ -0,0 +1,33 @@
package com.njcn.gather.system.resource.pojo.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 资源管理列表数据
*/
@Data
public class ResourceManageVO {
private String id;
private String name;
private String fileName;
private Long fileSize;
private String relativePath;
private String remark;
private Integer state;
private String createBy;
private LocalDateTime createTime;
private String updateBy;
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,26 @@
package com.njcn.gather.system.resource.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
import javax.servlet.http.HttpServletResponse;
/**
* 资源管理服务
*/
public interface IResourceManageService extends IService<ResourceManage> {
Page<ResourceManageVO> list(ResourceManageParam.QueryParam queryParam);
boolean add(ResourceManageParam resourceManageParam);
boolean update(ResourceManageParam.UpdateParam updateParam);
PlayVO play(String id);
void stream(String id, String token, String rangeHeader, HttpServletResponse response);
}

View File

@@ -0,0 +1,385 @@
package com.njcn.gather.system.resource.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.system.config.PathConfig;
import com.njcn.gather.system.resource.mapper.ResourceManageMapper;
import com.njcn.gather.system.resource.pojo.enums.ResourceManageResponseEnum;
import com.njcn.gather.system.resource.pojo.param.ResourceManageParam;
import com.njcn.gather.system.resource.pojo.po.ResourceManage;
import com.njcn.gather.system.resource.pojo.vo.PlayVO;
import com.njcn.gather.system.resource.pojo.vo.ResourceManageVO;
import com.njcn.gather.system.resource.service.IResourceManageService;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ResourceManageServiceImpl extends ServiceImpl<ResourceManageMapper, ResourceManage> implements IResourceManageService {
private static final long MAX_FILE_SIZE = 250L * 1024L * 1024L;
private static final long PLAY_TOKEN_TTL_MILLIS = 30L * 60L * 1000L;
private static final String MP4_SUFFIX = ".mp4";
private static final String RELATIVE_VIDEO_ROOT = "resources/videos";
private static final int BUFFER_SIZE = 8192;
private static final ConcurrentHashMap<String, PlayToken> PLAY_TOKEN_CACHE = new ConcurrentHashMap<>();
// @Value("${resource.videoDir:D:/data/resources/videos}")
// private String videoDir;
private final PathConfig pathConfig;
@Override
public Page<ResourceManageVO> list(ResourceManageParam.QueryParam queryParam) {
QueryWrapper<ResourceManage> wrapper = new QueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "Name", queryParam.getName())
.like(StrUtil.isNotBlank(queryParam.getFileName()), "File_Name", queryParam.getFileName())
.eq("State", DataStateEnum.ENABLE.getCode())
.orderByDesc("Create_Time");
Page<ResourceManage> page = this.page(
new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)),
wrapper
);
List<ResourceManageVO> records = page.getRecords().stream().map(resource -> {
ResourceManageVO vo = new ResourceManageVO();
BeanUtil.copyProperties(resource, vo);
return vo;
}).collect(Collectors.toList());
Page<ResourceManageVO> result = new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam));
result.setTotal(page.getTotal());
result.setPages(page.getPages());
result.setCurrent(page.getCurrent());
result.setSize(page.getSize());
result.setRecords(records);
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean add(ResourceManageParam resourceManageParam) {
validateAddParam(resourceManageParam);
MultipartFile file = resourceManageParam.getFile();
String originalFilename = file.getOriginalFilename();
String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String savedFileName = UUID.randomUUID().toString().replace("-", "") + MP4_SUFFIX;
Path rootPath = Paths.get(pathConfig.getResourcePath()).toAbsolutePath().normalize();
Path targetDir = rootPath.resolve(dateDir).normalize();
Path targetFile = targetDir.resolve(savedFileName).normalize();
ensurePathInRoot(rootPath, targetFile);
String relativePath = RELATIVE_VIDEO_ROOT + "/" + dateDir + "/" + savedFileName;
try {
Files.createDirectories(targetDir);
long usableSpace = targetDir.toFile().getUsableSpace();
if (usableSpace > 0 && usableSpace < file.getSize()) {
throw new BusinessException(ResourceManageResponseEnum.DISK_SPACE_NOT_ENOUGH);
}
file.transferTo(targetFile.toFile());
} catch (BusinessException e) {
throw e;
} catch (IOException e) {
throw new BusinessException(ResourceManageResponseEnum.FILE_UPLOAD_FAILED);
}
ResourceManage resourceManage = new ResourceManage();
resourceManage.setId(UUID.randomUUID().toString().replace("-", ""));
resourceManage.setName(resourceManageParam.getName().trim());
resourceManage.setRemark(resourceManageParam.getRemark().trim());
resourceManage.setFileName(originalFilename);
resourceManage.setFileSize(file.getSize());
resourceManage.setRelativePath(relativePath);
resourceManage.setState(DataStateEnum.ENABLE.getCode());
try {
boolean saved = this.save(resourceManage);
if (!saved) {
deleteQuietly(targetFile);
}
return saved;
} catch (RuntimeException e) {
deleteQuietly(targetFile);
throw e;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean update(ResourceManageParam.UpdateParam updateParam) {
validateUpdateParam(updateParam);
getEnabledResource(updateParam.getId());
return this.lambdaUpdate()
.set(ResourceManage::getName, updateParam.getName().trim())
.set(ResourceManage::getRemark, updateParam.getRemark().trim())
.eq(ResourceManage::getId, updateParam.getId())
.eq(ResourceManage::getState, DataStateEnum.ENABLE.getCode())
.update();
}
@Override
public PlayVO play(String id) {
ResourceManage resourceManage = getEnabledResource(id);
Path filePath = resolveResourcePath(resourceManage);
if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
}
String token = UUID.randomUUID().toString().replace("-", "");
PlayToken playToken = new PlayToken();
playToken.setResourceId(id);
playToken.setUserId(RequestUtil.getUserId());
playToken.setExpireTime(System.currentTimeMillis() + PLAY_TOKEN_TTL_MILLIS);
PLAY_TOKEN_CACHE.put(token, playToken);
clearExpiredTokens();
return new PlayVO("/resourceManage/stream?id=" + id + "&token=" + token);
}
@Override
public void stream(String id, String token, String rangeHeader, HttpServletResponse response) {
if (!validatePlayToken(id, token)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
ResourceManage resourceManage = getEnabledResource(id);
Path filePath = resolveResourcePath(resourceManage);
if (!Files.exists(filePath) || !Files.isRegularFile(filePath)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
try {
long fileLength = Files.size(filePath);
Range range = parseRange(rangeHeader, fileLength);
String encodedFileName = URLEncoder.encode(resourceManage.getFileName(), "UTF-8")
.replaceAll("\\+", "%20");
response.setContentType("video/mp4");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + encodedFileName);
response.setHeader("Content-Length", String.valueOf(range.getLength()));
if (range.isPartial()) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader("Content-Range", "bytes " + range.getStart() + "-" + range.getEnd() + "/" + fileLength);
} else {
response.setStatus(HttpServletResponse.SC_OK);
}
writeRange(filePath, range, response);
} catch (IllegalArgumentException e) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
private void validateAddParam(ResourceManageParam param) {
if (param == null || StrUtil.isBlank(param.getName())) {
throw new BusinessException(ResourceManageResponseEnum.NAME_NOT_BLANK);
}
if (StrUtil.isBlank(param.getRemark())) {
throw new BusinessException(ResourceManageResponseEnum.REMARK_NOT_BLANK);
}
MultipartFile file = param.getFile();
if (file == null || file.isEmpty()) {
throw new BusinessException(ResourceManageResponseEnum.FILE_NOT_NULL);
}
String originalFilename = file.getOriginalFilename();
if (StrUtil.isBlank(originalFilename) || !originalFilename.toLowerCase().endsWith(MP4_SUFFIX)) {
throw new BusinessException(ResourceManageResponseEnum.FILE_SUFFIX_ERROR);
}
String contentType = file.getContentType();
if (StrUtil.isNotBlank(contentType) && !"video/mp4".equalsIgnoreCase(contentType)
&& !"application/octet-stream".equalsIgnoreCase(contentType)) {
throw new BusinessException(ResourceManageResponseEnum.FILE_SUFFIX_ERROR);
}
if (file.getSize() > MAX_FILE_SIZE) {
throw new BusinessException(ResourceManageResponseEnum.FILE_SIZE_ERROR);
}
}
private void validateUpdateParam(ResourceManageParam.UpdateParam param) {
if (param == null || StrUtil.isBlank(param.getId())) {
throw new BusinessException(ResourceManageResponseEnum.ID_NOT_BLANK);
}
if (StrUtil.isBlank(param.getName())) {
throw new BusinessException(ResourceManageResponseEnum.NAME_NOT_BLANK);
}
if (StrUtil.isBlank(param.getRemark())) {
throw new BusinessException(ResourceManageResponseEnum.REMARK_NOT_BLANK);
}
}
private ResourceManage getEnabledResource(String id) {
ResourceManage resourceManage = this.lambdaQuery()
.eq(ResourceManage::getId, id)
.eq(ResourceManage::getState, DataStateEnum.ENABLE.getCode())
.one();
if (resourceManage == null) {
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_NOT_EXIST);
}
return resourceManage;
}
private Path resolveResourcePath(ResourceManage resourceManage) {
Path rootPath = Paths.get(pathConfig.getResourcePath()).toAbsolutePath().normalize();
String relativePath = resourceManage.getRelativePath().replace("\\", "/");
String prefix = RELATIVE_VIDEO_ROOT + "/";
if (!relativePath.startsWith(prefix)) {
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
}
String relativeToVideoRoot = relativePath.substring(prefix.length());
Path filePath = rootPath.resolve(relativeToVideoRoot).normalize();
ensurePathInRoot(rootPath, filePath);
return filePath;
}
private void ensurePathInRoot(Path rootPath, Path targetPath) {
if (!targetPath.startsWith(rootPath)) {
throw new BusinessException(ResourceManageResponseEnum.RESOURCE_FILE_NOT_EXIST);
}
}
private boolean validatePlayToken(String id, String token) {
if (StrUtil.isBlank(id) || StrUtil.isBlank(token)) {
return false;
}
PlayToken playToken = PLAY_TOKEN_CACHE.get(token);
if (playToken == null || !id.equals(playToken.getResourceId())) {
return false;
}
if (playToken.getExpireTime() < System.currentTimeMillis()) {
PLAY_TOKEN_CACHE.remove(token);
return false;
}
return true;
}
private void clearExpiredTokens() {
long now = System.currentTimeMillis();
PLAY_TOKEN_CACHE.entrySet().removeIf(entry -> entry.getValue().getExpireTime() < now);
}
private Range parseRange(String rangeHeader, long fileLength) {
if (StrUtil.isBlank(rangeHeader)) {
return new Range(0, fileLength - 1, false);
}
if (!rangeHeader.startsWith("bytes=")) {
throw new IllegalArgumentException("Invalid range");
}
String rangeValue = rangeHeader.substring("bytes=".length());
String[] parts = rangeValue.split("-", -1);
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid range");
}
long start;
long end;
if (StrUtil.isBlank(parts[0])) {
long suffixLength = Long.parseLong(parts[1]);
if (suffixLength <= 0) {
throw new IllegalArgumentException("Invalid range");
}
start = Math.max(fileLength - suffixLength, 0);
end = fileLength - 1;
} else {
start = Long.parseLong(parts[0]);
end = StrUtil.isBlank(parts[1]) ? fileLength - 1 : Long.parseLong(parts[1]);
}
if (start < 0 || end < start || start >= fileLength) {
throw new IllegalArgumentException("Invalid range");
}
end = Math.min(end, fileLength - 1);
return new Range(start, end, true);
}
private void writeRange(Path filePath, Range range, HttpServletResponse response) throws IOException {
try (InputStream inputStream = Files.newInputStream(filePath);
ServletOutputStream outputStream = response.getOutputStream()) {
long skipped = inputStream.skip(range.getStart());
while (skipped < range.getStart()) {
long current = inputStream.skip(range.getStart() - skipped);
if (current <= 0) {
break;
}
skipped += current;
}
byte[] buffer = new byte[BUFFER_SIZE];
long bytesRemaining = range.getLength();
while (bytesRemaining > 0) {
int readLength = (int) Math.min(buffer.length, bytesRemaining);
int read = inputStream.read(buffer, 0, readLength);
if (read == -1) {
break;
}
outputStream.write(buffer, 0, read);
bytesRemaining -= read;
}
outputStream.flush();
}
}
private void deleteQuietly(Path path) {
try {
Files.deleteIfExists(path);
} catch (IOException e) {
log.warn("删除资源文件失败: {}", path, e);
}
}
@Data
private static class PlayToken {
private String resourceId;
private String userId;
private long expireTime;
}
@Data
private static class Range {
private final long start;
private final long end;
private final boolean partial;
private long getLength() {
return end - start + 1;
}
}
}

View File

@@ -14,10 +14,17 @@ public interface IWordReportService {
/**
* 替换Word文档中的占位符
*
*
* @param templateInputStream 模板文档输入流
* @param placeholderMap 占位符替换映射表key为占位符标识value为替换值
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作
* @return 处理后的文档输入流,调用方可根据需要进行下载、上传等操作
* <p>
* <b>资源管理契约:</b>当前实现返回 {@link java.io.ByteArrayInputStream}
* 其 {@code close()} 为空操作、内部仅持有 byte 数组、不占用文件句柄等 native 资源,
* 调用方<strong>不强制</strong>用 try-with-resources 包裹该返回流;
* 若未来该方法的实现改为返回底层依赖文件 / 网络 / 临时文件的真实流,
* 必须先改造所有调用方按 try-with-resources 关流后再合并实现,
* 以避免句柄泄漏。
* @throws Exception 处理异常
*/
InputStream replacePlaceholders(InputStream templateInputStream, Map<String, String> placeholderMap) throws Exception;

View File

@@ -40,6 +40,10 @@ public class WordReportServiceImpl implements IWordReportService {
PlaceholderUtil.replaceAllPlaceholders(mainDocumentPart, placeholderMap);
// 将处理后的文档转换为字节数组输入流
// 注:返回类型必须是 ByteArrayInputStream 或 close() 为空操作的等价流,
// 以满足 IWordReportService.replacePlaceholders 接口契约
// (多个调用方未对返回流做 try-with-resources 兜底)。
// 若需改为依赖文件 / 网络 / 临时文件的真实流,必须先改造所有调用方再合并。
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
wordPackage.save(outputStream);
byte[] documentBytes = outputStream.toByteArray();

View File

@@ -0,0 +1,60 @@
package com.njcn.gather.tools.report.util;
import cn.hutool.core.util.StrUtil;
/**
* 文件路径片段净化工具。
* <p>
* 用于把外部输入(数据库中的设备型号名、计划名等)作为目录或文件名片段拼入磁盘路径前的兜底清洗,
* 防止 {@code /} {@code \} {@code ..} {@code :} 等路径敏感字符导致:
* <ul>
* <li>报告文件被写到预期目录之外(路径穿越)</li>
* <li>名字含 {@code /} 时被操作系统解释成多级子目录(即使无恶意,自然命名如"高/中压"也会触发)</li>
* <li>Windows 上 {@code :} 触发 NTFS 备用数据流</li>
* <li>文件创建失败抛 IO 异常</li>
* </ul>
*
* @author hongawen
*/
public final class FilePathSanitizer {
/**
* Windows + Linux 共同非法字符 + 控制字符:替换为下划线
*/
private static final String UNSAFE_CHAR_PATTERN = "[\\\\/:*?\"<>|\\x00-\\x1F]";
private FilePathSanitizer() {
}
/**
* 把一段字符串净化成可安全拼入磁盘路径的片段。
* <p>
* 规则:
* <ol>
* <li>{@code null} 或全空白 → 返回 {@code "_"}(保证拼出来的路径仍合法)</li>
* <li>{@code /} {@code \} {@code :} {@code *} {@code ?} {@code "} {@code <} {@code >} {@code |}
* 及 ASCII 控制字符替换为 {@code _}</li>
* <li>把 {@code ..} 折叠为 {@code _},防止路径穿越</li>
* <li>连续 {@code _} 合并为单个 {@code _}</li>
* <li>首尾空白与 {@code .} 去掉Windows 不允许文件名以 {@code .} 结尾)</li>
* </ol>
*
* @param raw 原始字符串
* @return 净化后的片段;当输入合法且无危险字符时与原值一致
*/
public static String toSafeFileName(String raw) {
if (StrUtil.isBlank(raw)) {
return "_";
}
String result = raw.replaceAll(UNSAFE_CHAR_PATTERN, "_");
// 折叠路径穿越序列
while (result.contains("..")) {
result = result.replace("..", "_");
}
// 合并连续下划线
result = result.replaceAll("_+", "_");
// 去掉首尾空白和点
result = result.replaceAll("^[\\s.]+|[\\s.]+$", "");
return result.isEmpty() ? "_" : result;
}
}

View File

@@ -25,7 +25,7 @@ import java.util.List;
@Slf4j
@Component
public class AuthGlobalFilter implements Filter, Ordered {
private final static List<String> IGNORE_URI = Arrays.asList("/doc.html","/v3/api-docs","/admin/login","/admin/getPublicKey", "/report/generateReport");
private final static List<String> IGNORE_URI = Arrays.asList("/doc.html","/v3/api-docs","/admin/login","/admin/getPublicKey", "/report/generateReport", "/resourceManage/stream");
@Override
public int getOrder() {