Compare commits
62 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16ace94f8d | ||
|
|
ca9885c5dc | ||
|
|
78b52fa336 | ||
|
|
da08271f76 | ||
|
|
75bc44172b | ||
|
|
95544f1dc6 | ||
| 7a8071c9d7 | |||
| 75b19eb6ab | |||
|
|
efb379d6a4 | ||
|
|
cf2dcf8ff4 | ||
|
|
4d52e9c820 | ||
|
|
be318b2b54 | ||
| e3478e71d5 | |||
| 88d3e00559 | |||
|
|
1de66ce4dc | ||
|
|
597f70edd1 | ||
|
|
6f8acd3fb5 | ||
|
|
3c0d7a6268 | ||
|
|
7fd1563f3a | ||
|
|
4fd813f476 | ||
|
|
9dfb42f917 | ||
|
|
9990183c5d | ||
|
|
d746e68d63 | ||
|
|
1ff2d373f5 | ||
|
|
f298a7bb56 | ||
|
|
aafa38000d | ||
|
|
287ca2cddc | ||
|
|
82fdd7664b | ||
|
|
547d40ce99 | ||
|
|
49599582ba | ||
|
|
31a956a1fc | ||
|
|
55fe1fe05f | ||
| 366d1fadfa | |||
|
|
b35bbf11f7 | ||
| e2c7e745c8 | |||
|
|
29ddc8c2de | ||
|
|
212f1295eb | ||
|
|
7366e7815f | ||
|
|
a4858a818e | ||
|
|
de83f98845 | ||
|
|
061b65be1b | ||
|
|
694a99a96f | ||
| befe5abe0c | |||
| 46ec9923a7 | |||
|
|
d2388576a9 | ||
|
|
7f21049d0f | ||
|
|
49ca27d994 | ||
| 3cb4a46a16 | |||
|
|
13677f21d9 | ||
|
|
a1941a375b | ||
|
|
9dc8ecd873 | ||
|
|
7c6c103f17 | ||
|
|
b113788e54 | ||
|
|
599edde008 | ||
|
|
cc0b685c66 | ||
|
|
29b0a4f966 | ||
|
|
c651b18e72 | ||
|
|
6fd180b4d4 | ||
|
|
282f9cf4eb | ||
|
|
1cfea7fd6c | ||
|
|
251e302e59 | ||
|
|
873e920add |
9
.gitignore
vendored
9
.gitignore
vendored
@@ -48,3 +48,12 @@ rebel.xml
|
|||||||
/.fastRequest/collections/Root/Default Group/directory.json
|
/.fastRequest/collections/Root/Default Group/directory.json
|
||||||
/.fastRequest/collections/Root/directory.json
|
/.fastRequest/collections/Root/directory.json
|
||||||
/.fastRequest/config/fastRequestCurrentProjectConfig.json
|
/.fastRequest/config/fastRequestCurrentProjectConfig.json
|
||||||
|
|
||||||
|
# 个人工作文档,不与团队共享
|
||||||
|
CLAUDE.md
|
||||||
|
docs/
|
||||||
|
data/
|
||||||
|
.m2
|
||||||
|
|
||||||
|
# Windows 保留设备名误生成的真实文件(在 Git Bash 里把 2>nul 当成丢弃报错的写法,会真的建出名为 nul 的文件)
|
||||||
|
nul
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -145,7 +145,12 @@
|
|||||||
<artifactId>activate-tool</artifactId>
|
<artifactId>activate-tool</artifactId>
|
||||||
<version>1.0.0</version>
|
<version>1.0.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.njcn.gather.detection.controller;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLock;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
|
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
|
||||||
|
import com.njcn.web.controller.BaseController;
|
||||||
|
import com.njcn.web.utils.HttpResultUtil;
|
||||||
|
import com.njcn.web.utils.RequestUtil;
|
||||||
|
import io.swagger.annotations.Api;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测互斥锁管理接口。
|
||||||
|
* - GET /detection/lock/current 查询当前持锁状态;空闲返回 data=null
|
||||||
|
* - POST /detection/lock/forceRelease 管理员强制释放
|
||||||
|
*
|
||||||
|
* 鉴权:默认由 AuthGlobalFilter 做 JWT 校验,登录用户均可访问;
|
||||||
|
* 强释操作通过 @OperateInfo 落审计日志,谁操作谁担责。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Api(tags = "检测互斥锁")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/detection/lock")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class LockController extends BaseController {
|
||||||
|
|
||||||
|
@GetMapping("/current")
|
||||||
|
@ApiOperation("查询当前持锁状态;空闲返回 data=null")
|
||||||
|
public HttpResult<DetectionLockHolderVO> current() {
|
||||||
|
String methodDescribe = getMethodDescribe("current");
|
||||||
|
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||||
|
DetectionLockHolderVO data = cur == null ? null : DetectionLockManager.toHolderVO(cur);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, data, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/forceRelease")
|
||||||
|
@OperateInfo
|
||||||
|
@ApiOperation("管理员强制释放检测锁")
|
||||||
|
public HttpResult<?> forceRelease() {
|
||||||
|
String methodDescribe = getMethodDescribe("forceRelease");
|
||||||
|
String operator = RequestUtil.getUserId();
|
||||||
|
DetectionLockManager.getInstance().forceRelease(operator, "ADMIN_FORCE");
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,27 @@
|
|||||||
package com.njcn.gather.detection.controller;
|
package com.njcn.gather.detection.controller;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
import com.njcn.common.pojo.constant.OperateType;
|
import com.njcn.common.pojo.constant.OperateType;
|
||||||
import com.njcn.common.pojo.enums.common.LogEnum;
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.common.utils.LogUtil;
|
import com.njcn.common.utils.LogUtil;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLock;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager.AcquireResult;
|
||||||
|
import com.njcn.gather.detection.pojo.enums.DetectionResponseEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
|
import com.njcn.gather.detection.pojo.param.SimulateDetectionParam;
|
||||||
|
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
|
||||||
import com.njcn.gather.detection.service.PreDetectionService;
|
import com.njcn.gather.detection.service.PreDetectionService;
|
||||||
|
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||||
|
import com.njcn.gather.user.user.pojo.po.SysUser;
|
||||||
|
import com.njcn.gather.user.user.service.ISysUserService;
|
||||||
import com.njcn.web.controller.BaseController;
|
import com.njcn.web.controller.BaseController;
|
||||||
import com.njcn.web.utils.HttpResultUtil;
|
import com.njcn.web.utils.HttpResultUtil;
|
||||||
|
import com.njcn.web.utils.RequestUtil;
|
||||||
import io.swagger.annotations.Api;
|
import io.swagger.annotations.Api;
|
||||||
import io.swagger.annotations.ApiImplicitParam;
|
import io.swagger.annotations.ApiImplicitParam;
|
||||||
import io.swagger.annotations.ApiOperation;
|
import io.swagger.annotations.ApiOperation;
|
||||||
@@ -32,6 +42,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class PreDetectionController extends BaseController {
|
public class PreDetectionController extends BaseController {
|
||||||
|
|
||||||
private final PreDetectionService preDetectionService;
|
private final PreDetectionService preDetectionService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 开始检测通用入口
|
* 开始检测通用入口
|
||||||
@@ -42,10 +53,27 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("开始检测")
|
@ApiOperation("开始检测")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> startPreTest(@RequestBody @Validated PreDetectionParam param) {
|
public HttpResult<?> startPreTest(@RequestBody @Validated PreDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("startPreTest");
|
String methodDescribe = getMethodDescribe("startPreTest");
|
||||||
preDetectionService.sourceCommunicationCheck(param);
|
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getUserPageId());
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
// 同步阶段抛异常时回滚锁(PLAN_AND_SOURCE_NOT / SOURCE_INFO_NOT 等业务异常会被全局处理器吞掉,
|
||||||
|
// 锁会卡在用户手上直到 4 小时超时,故需 finally 兜底)
|
||||||
|
boolean keepLock = false;
|
||||||
|
try {
|
||||||
|
// 重置 FormalTestManager 暂停计数残留,避免上次暂停残留计数误触发 R4
|
||||||
|
FormalTestManager.stopTime = 0;
|
||||||
|
FormalTestManager.hasStopFlag = false;
|
||||||
|
preDetectionService.sourceCommunicationCheck(param);
|
||||||
|
keepLock = true;
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
} finally {
|
||||||
|
if (!keepLock) {
|
||||||
|
releaseLockSelf("START_PRE_SYNC_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -59,8 +87,12 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("源通讯校验")
|
@ApiOperation("源通讯校验")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> ytxCheckSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
public HttpResult<?> ytxCheckSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("ytxCheckSimulate");
|
String methodDescribe = getMethodDescribe("ytxCheckSimulate");
|
||||||
|
HttpResult<DetectionLockHolderVO> busy = requireFreeOrSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
preDetectionService.ytxCheckSimulate(param);
|
preDetectionService.ytxCheckSimulate(param);
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
@@ -72,10 +104,26 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("启动")
|
@ApiOperation("启动")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> startTestSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
public HttpResult<?> startTestSimulate(@RequestBody @Validated SimulateDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("startTestSimulate");
|
String methodDescribe = getMethodDescribe("startSimulateTest");
|
||||||
preDetectionService.sendScript(param);
|
// ContrastDetectionParam 无 userPageId 字段,用 loginName 作为会话标识(与 WS 会话 key 一致)
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getUserPageId());
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
// 同步阶段抛异常时回滚锁,理由同 startPreTest
|
||||||
|
boolean keepLock = false;
|
||||||
|
try {
|
||||||
|
FormalTestManager.stopTime = 0;
|
||||||
|
FormalTestManager.hasStopFlag = false;
|
||||||
|
preDetectionService.sendScript(param);
|
||||||
|
keepLock = true;
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
} finally {
|
||||||
|
if (!keepLock) {
|
||||||
|
releaseLockSelf("START_SIMULATE_TEST_SYNC_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,9 +133,18 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("停止")
|
@ApiOperation("停止")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> closeSimulateTest(@RequestBody @Validated SimulateDetectionParam param) {
|
public HttpResult<?> closeSimulateTest(@RequestBody @Validated SimulateDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("closeSimulateTest");
|
String methodDescribe = getMethodDescribe("closeSimulateTest");
|
||||||
preDetectionService.closeTestSimulate(param);
|
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
preDetectionService.closeTestSimulate(param);
|
||||||
|
} finally {
|
||||||
|
// 即使业务异常也要释放锁,避免锁残留导致他人无法接手
|
||||||
|
releaseLockSelf("USER_STOP");
|
||||||
|
}
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,8 +156,12 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("系数校验")
|
@ApiOperation("系数校验")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> coefficientCheck(@RequestBody PreDetectionParam param) {
|
public HttpResult<?> coefficientCheck(@RequestBody PreDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("coefficientCheck");
|
String methodDescribe = getMethodDescribe("coefficientCheck");
|
||||||
|
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
preDetectionService.coefficientCheck(param);
|
preDetectionService.coefficientCheck(param);
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
@@ -113,8 +174,13 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("暂停检测")
|
@ApiOperation("暂停检测")
|
||||||
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
||||||
public HttpResult<String> temStopTest() {
|
public HttpResult<?> temStopTest() {
|
||||||
String methodDescribe = getMethodDescribe("temStopTest");
|
String methodDescribe = getMethodDescribe("temStopTest");
|
||||||
|
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
// 暂停保持锁(spec §2.3),不释放
|
||||||
preDetectionService.temStopTest();
|
preDetectionService.temStopTest();
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
@@ -126,8 +192,12 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("重新开始检测")
|
@ApiOperation("重新开始检测")
|
||||||
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
@ApiImplicitParam(name = "param", value = "参数", required = true)
|
||||||
public HttpResult<String> restartTemTest(@RequestBody PreDetectionParam param) {
|
public HttpResult<?> restartTemTest(@RequestBody PreDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("restartTemTest");
|
String methodDescribe = getMethodDescribe("restartTemTest");
|
||||||
|
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
preDetectionService.restartTemTest(param);
|
preDetectionService.restartTemTest(param);
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
@@ -140,10 +210,26 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo
|
@OperateInfo
|
||||||
@ApiOperation("开始比对检测")
|
@ApiOperation("开始比对检测")
|
||||||
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
public HttpResult<String> startContrastTest(@RequestBody @Validated ContrastDetectionParam param) {
|
public HttpResult<?> startContrastTest(@RequestBody @Validated ContrastDetectionParam param) {
|
||||||
String methodDescribe = getMethodDescribe("startContrastTest");
|
String methodDescribe = getMethodDescribe("startContrastTest");
|
||||||
preDetectionService.startContrastTest(param);
|
// ContrastDetectionParam 无 userPageId 字段,用 loginName 作为会话标识(与 WS 会话 key 一致)
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
HttpResult<DetectionLockHolderVO> busy = tryAcquireLock(param.getLoginName());
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
// 同步阶段抛异常时回滚锁,理由同 startPreTest
|
||||||
|
boolean keepLock = false;
|
||||||
|
try {
|
||||||
|
FormalTestManager.stopTime = 0;
|
||||||
|
FormalTestManager.hasStopFlag = false;
|
||||||
|
preDetectionService.startContrastTest(param);
|
||||||
|
keepLock = true;
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
} finally {
|
||||||
|
if (!keepLock) {
|
||||||
|
releaseLockSelf("START_CONTRAST_SYNC_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -169,11 +255,91 @@ public class PreDetectionController extends BaseController {
|
|||||||
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||||
@GetMapping("/startCoefficient")
|
@GetMapping("/startCoefficient")
|
||||||
@ApiOperation("比对模式开启系数校验")
|
@ApiOperation("比对模式开启系数校验")
|
||||||
public HttpResult<String> startCoefficient() {
|
public HttpResult<?> startCoefficient() {
|
||||||
String methodDescribe = getMethodDescribe("startCoefficient");
|
String methodDescribe = getMethodDescribe("startCoefficient");
|
||||||
LogUtil.njcnDebug(log, "{}", methodDescribe);
|
LogUtil.njcnDebug(log, "{}", methodDescribe);
|
||||||
|
HttpResult<DetectionLockHolderVO> busy = requireHolderSelf();
|
||||||
|
if (busy != null) {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
preDetectionService.startCoefficient();
|
preDetectionService.startCoefficient();
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============ 检测互斥锁辅助方法 ============
|
||||||
|
|
||||||
|
/** 抢锁入口(startPreTest / startContrastTest 用)。
|
||||||
|
* 抢到→null;被他人持有或竞态失败→返回 busy 响应;
|
||||||
|
* 使用方:拿到非 null 返回值直接 return 给上层。 */
|
||||||
|
private HttpResult<DetectionLockHolderVO> tryAcquireLock(String userPageId) {
|
||||||
|
String userId = RequestUtil.getUserId();
|
||||||
|
AcquireResult r = DetectionLockManager.getInstance()
|
||||||
|
.tryAcquire(userId, resolveDisplayName(userId), userPageId);
|
||||||
|
if (r.isOk()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return HttpResultUtil.assembleResult(
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||||
|
r.getHolder(),
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 中间接口校验:要求当前 holder == 自己。
|
||||||
|
* 空闲 → 返回 busy data=null("请先开始检测"语义);
|
||||||
|
* 他人持有 → 返回 busy + holder;
|
||||||
|
* 自己持有 → 返回 null(放行)。 */
|
||||||
|
private HttpResult<DetectionLockHolderVO> requireHolderSelf() {
|
||||||
|
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||||
|
String me = RequestUtil.getUserId();
|
||||||
|
if (cur != null && me.equals(cur.getUserId())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
DetectionLockHolderVO holder = cur == null ? null : DetectionLockManager.toHolderVO(cur);
|
||||||
|
return HttpResultUtil.assembleResult(
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||||
|
holder,
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 辅助接口规则(ytxCheckSimulate):锁空闲 → 放行;他人持有 → busy;自己持有 → 放行。 */
|
||||||
|
private HttpResult<DetectionLockHolderVO> requireFreeOrSelf() {
|
||||||
|
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||||
|
if (cur == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String me = RequestUtil.getUserId();
|
||||||
|
if (me.equals(cur.getUserId())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return HttpResultUtil.assembleResult(
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getCode(),
|
||||||
|
DetectionLockManager.toHolderVO(cur),
|
||||||
|
DetectionResponseEnum.DETECTION_BUSY.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 释放锁(用户主动终止)。 */
|
||||||
|
private void releaseLockSelf(String reason) {
|
||||||
|
DetectionLockManager.getInstance().releaseIfHeldBy(RequestUtil.getUserId(), reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析展示给前端的用户名(昵称优先,loginName 兜底,避免 BUSY 弹窗显示 "unknown user")。 */
|
||||||
|
private String resolveDisplayName(String userId) {
|
||||||
|
if (StrUtil.isBlank(userId)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
SysUser user = sysUserService.getById(userId);
|
||||||
|
if (user != null && StrUtil.isNotBlank(user.getName())) {
|
||||||
|
return user.getName();
|
||||||
|
}
|
||||||
|
if (user != null && StrUtil.isNotBlank(user.getLoginName())) {
|
||||||
|
return user.getLoginName();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("解析检测锁持有者昵称失败,userId={}", userId, e);
|
||||||
|
}
|
||||||
|
// 最终兜底:用 token 里的 loginName,不要返回 "unknown user"
|
||||||
|
String loginName = RequestUtil.getLoginNameByToken();
|
||||||
|
return StrUtil.isNotBlank(loginName) ? loginName : userId;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.njcn.gather.detection.controller;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.gather.detection.sntp.SntpServerManager;
|
||||||
|
import com.njcn.web.controller.BaseController;
|
||||||
|
import com.njcn.web.utils.HttpResultUtil;
|
||||||
|
import io.swagger.annotations.Api;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Api(tags = "SNTP对时")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/sntp")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SntpController extends BaseController {
|
||||||
|
|
||||||
|
private final SntpServerManager sntpServerManager;
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||||
|
@PostMapping("/start")
|
||||||
|
@ApiOperation("启动SNTP对时服务")
|
||||||
|
public HttpResult<?> start() {
|
||||||
|
String methodDescribe = getMethodDescribe("start");
|
||||||
|
sntpServerManager.start();
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.SYSTEM_COMMON)
|
||||||
|
@PostMapping("/stop")
|
||||||
|
@ApiOperation("停止SNTP对时服务")
|
||||||
|
public HttpResult<?> stop() {
|
||||||
|
String methodDescribe = getMethodDescribe("stop");
|
||||||
|
sntpServerManager.stop();
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,6 +46,7 @@ import com.njcn.gather.storage.pojo.po.ContrastNonHarmonicResult;
|
|||||||
import com.njcn.gather.storage.service.DetectionDataDealService;
|
import com.njcn.gather.storage.service.DetectionDataDealService;
|
||||||
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
||||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
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.enums.DictDataEnum;
|
||||||
import com.njcn.gather.system.dictionary.pojo.po.DictData;
|
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.DictTree;
|
||||||
@@ -57,7 +58,6 @@ import com.njcn.gather.tools.comtrade.comparewave.service.ICompareWaveService;
|
|||||||
import com.njcn.gather.util.StorageUtil;
|
import com.njcn.gather.util.StorageUtil;
|
||||||
import com.njcn.web.utils.ExcelUtil;
|
import com.njcn.web.utils.ExcelUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
@@ -127,8 +127,9 @@ public class SocketContrastResponseService {
|
|||||||
// private SysRegRes contrastRegRes = null;
|
// private SysRegRes contrastRegRes = null;
|
||||||
|
|
||||||
|
|
||||||
@Value("${report.reportDir}")
|
// @Value("${report.reportDir}")
|
||||||
private String alignDataFilePath;
|
// private String alignDataFilePath;
|
||||||
|
private final PathConfig pathConfig;
|
||||||
|
|
||||||
public static final Map<String, List<String>> testItemCodeMap = new HashMap() {{
|
public static final Map<String, List<String>> testItemCodeMap = new HashMap() {{
|
||||||
put("FREQ", Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
|
put("FREQ", Arrays.asList(DetectionCodeEnum.FREQ.getCode()));
|
||||||
@@ -306,7 +307,7 @@ public class SocketContrastResponseService {
|
|||||||
FormalTestManager.numMap.clear();
|
FormalTestManager.numMap.clear();
|
||||||
FormalTestManager.numMap.putAll(numMap);
|
FormalTestManager.numMap.putAll(numMap);
|
||||||
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
|
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
|
||||||
if (param.getTestItemList().get(2)) {
|
if (param.isFormalTestSelected()) {
|
||||||
numMap.forEach((devMonitorId, num) -> {
|
numMap.forEach((devMonitorId, num) -> {
|
||||||
if (oneConfig.getMaxTime() < num) {
|
if (oneConfig.getMaxTime() < num) {
|
||||||
throw new BusinessException(DetectionResponseEnum.EXCEED_MAX_TIME);
|
throw new BusinessException(DetectionResponseEnum.EXCEED_MAX_TIME);
|
||||||
@@ -355,6 +356,7 @@ public class SocketContrastResponseService {
|
|||||||
|
|
||||||
|
|
||||||
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_SBTXJY;
|
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_SBTXJY;
|
||||||
|
FormalTestManager.checkStartTime = LocalDateTime.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deal(PreDetectionParam param, String msg) throws Exception {
|
public void deal(PreDetectionParam param, String msg) throws Exception {
|
||||||
@@ -553,7 +555,6 @@ public class SocketContrastResponseService {
|
|||||||
this.sendAlignData(s, requestOperateCode);
|
this.sendAlignData(s, requestOperateCode);
|
||||||
|
|
||||||
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_ALIGN;
|
FormalTestManager.currentStep = SourceOperateCodeEnum.YJC_ALIGN;
|
||||||
|
|
||||||
// if (FormalTestManager.isWaveCheck) {
|
// if (FormalTestManager.isWaveCheck) {
|
||||||
// System.out.println("(仅有闪变、录波)模型一致性校验成功!》》》》》》》》》》》》》》》》》》》》》》》》》》》》》开始相序校验》》》》》》》》》》》》》》》》");
|
// System.out.println("(仅有闪变、录波)模型一致性校验成功!》》》》》》》》》》》》》》》》》》》》》》》》》》》》》开始相序校验》》》》》》》》》》》》》》》》");
|
||||||
// this.sendXu(s);
|
// this.sendXu(s);
|
||||||
@@ -1153,7 +1154,7 @@ public class SocketContrastResponseService {
|
|||||||
|
|
||||||
private void sendFormalTest(String s, PreDetectionParam param, SourceOperateCodeEnum requestOperateCode, SourceOperateCodeEnum quitOperateCode) {
|
private void sendFormalTest(String s, PreDetectionParam param, SourceOperateCodeEnum requestOperateCode, SourceOperateCodeEnum quitOperateCode) {
|
||||||
// 后续做正式检测
|
// 后续做正式检测
|
||||||
if (param.getTestItemList().get(2)) {
|
if (param.isFormalTestSelected()) {
|
||||||
System.out.println("开始正式检测!");
|
System.out.println("开始正式检测!");
|
||||||
if (ObjectUtil.isNotNull(FormalTestManager.nonWaveDataSourceEnum)) {
|
if (ObjectUtil.isNotNull(FormalTestManager.nonWaveDataSourceEnum)) {
|
||||||
SocketMsg<String> socketMsg = new SocketMsg<>();
|
SocketMsg<String> socketMsg = new SocketMsg<>();
|
||||||
@@ -2314,7 +2315,7 @@ public class SocketContrastResponseService {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
ExcelUtil.saveExcel(alignDataFilePath, "对齐数据.xlsx", sheetsList);
|
ExcelUtil.saveExcel(pathConfig.getDataPath(), "对齐数据.xlsx", sheetsList);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import cn.hutool.core.util.ObjectUtil;
|
|||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.dto.DevXiNumData;
|
import com.njcn.gather.detection.pojo.dto.DevXiNumData;
|
||||||
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.DetectionCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
@@ -28,11 +29,14 @@ import com.njcn.gather.device.service.IPqDevSubService;
|
|||||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||||
import com.njcn.gather.plan.service.IAdPlanService;
|
import com.njcn.gather.plan.service.IAdPlanService;
|
||||||
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
|
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
|
||||||
|
import com.njcn.gather.result.service.IResultService;
|
||||||
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
|
import com.njcn.gather.script.pojo.param.PqScriptCheckDataParam;
|
||||||
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
|
import com.njcn.gather.script.pojo.param.PqScriptIssueParam;
|
||||||
import com.njcn.gather.script.pojo.po.SourceIssue;
|
import com.njcn.gather.script.pojo.po.SourceIssue;
|
||||||
import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
||||||
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
||||||
|
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.param.StorageParam;
|
||||||
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
|
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
|
||||||
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
|
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
|
||||||
@@ -43,6 +47,7 @@ import com.njcn.gather.system.dictionary.pojo.po.DictData;
|
|||||||
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
||||||
import com.njcn.gather.system.pojo.enums.DicDataEnum;
|
import com.njcn.gather.system.pojo.enums.DicDataEnum;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
@@ -76,6 +81,11 @@ public class SocketDevResponseService {
|
|||||||
private final SimAndDigHarmonicService adHarmonicService;
|
private final SimAndDigHarmonicService adHarmonicService;
|
||||||
private final IAdPlanService adPlanService;
|
private final IAdPlanService adPlanService;
|
||||||
private final IDictDataService dictDataService;
|
private final IDictDataService dictDataService;
|
||||||
|
private final IPqSourceService pqSourceService;
|
||||||
|
private final IResultService resultService;
|
||||||
|
|
||||||
|
@Value("${dataCheck.enable}")
|
||||||
|
private Boolean dataCheck;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 存储的装置相序数据
|
* 存储的装置相序数据
|
||||||
@@ -388,9 +398,10 @@ public class SocketDevResponseService {
|
|||||||
sendWebSocket(param.getUserPageId(), SourceOperateCodeEnum.Coefficient_Check.getValue(), SourceOperateCodeEnum.small_comp_end.getValue(), XiNumberManager.devParameterList.get(1));
|
sendWebSocket(param.getUserPageId(), SourceOperateCodeEnum.Coefficient_Check.getValue(), SourceOperateCodeEnum.small_comp_end.getValue(), XiNumberManager.devParameterList.get(1));
|
||||||
System.out.println("-------------------------已经全部结束----------------------");
|
System.out.println("-------------------------已经全部结束----------------------");
|
||||||
|
|
||||||
if (param.getTestItemList().get(2)) {
|
if (param.isFormalTestSelected()) {
|
||||||
//如果后续做正式检测
|
//如果后续做正式检测
|
||||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
|
issueParam.setSourceId(param.getSourceName());
|
||||||
issueParam.setPlanId(param.getPlanId());
|
issueParam.setPlanId(param.getPlanId());
|
||||||
issueParam.setSourceId(param.getSourceId());
|
issueParam.setSourceId(param.getSourceId());
|
||||||
issueParam.setDevIds(param.getDevIds());
|
issueParam.setDevIds(param.getDevIds());
|
||||||
@@ -688,7 +699,7 @@ public class SocketDevResponseService {
|
|||||||
*/
|
*/
|
||||||
private Double reduceList(List<Double> valList) {
|
private Double reduceList(List<Double> valList) {
|
||||||
// valList.subList(0, 5).clear();
|
// 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();
|
return valList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -894,20 +905,20 @@ public class SocketDevResponseService {
|
|||||||
//开始下源控制脚本
|
//开始下源控制脚本
|
||||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
issueParam.setPlanId(param.getPlanId());
|
issueParam.setPlanId(param.getPlanId());
|
||||||
issueParam.setSourceId(param.getSourceId());
|
issueParam.setSourceId(param.getSourceName());
|
||||||
issueParam.setDevIds(param.getDevIds());
|
issueParam.setDevIds(param.getDevIds());
|
||||||
issueParam.setScriptId(param.getScriptId());
|
issueParam.setScriptId(param.getScriptId());
|
||||||
|
|
||||||
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
|
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
|
||||||
List<SourceIssue> sourceIssues;
|
List<SourceIssue> sourceIssues;
|
||||||
// 做预检测、后续做系数校准
|
// 做预检测、后续做系数校准
|
||||||
if (param.getTestItemList().get(0) || param.getTestItemList().get(1)) {
|
if (param.isPreTestSelected() || param.isCoefficientSelected()) {
|
||||||
issueParam.setIsPhaseSequence(CommonEnum.PHASE_TEST.getValue());
|
issueParam.setIsPhaseSequence(CommonEnum.PHASE_TEST.getValue());
|
||||||
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
|
sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
|
||||||
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
|
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
|
||||||
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
|
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
|
||||||
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
|
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
|
||||||
} else if (param.getTestItemList().get(2)) {
|
} else if (param.isFormalTestSelected()) {
|
||||||
// 后续做正式检测
|
// 后续做正式检测
|
||||||
if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
|
if (param.getReCheckType().equals(SourceOperateCodeEnum.RE_ERROR_TEST.getValue())) {
|
||||||
//不合格项复检
|
//不合格项复检
|
||||||
@@ -948,9 +959,10 @@ public class SocketDevResponseService {
|
|||||||
//告诉前端当前项开始了
|
//告诉前端当前项开始了
|
||||||
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
||||||
String type = sourceIssues.get(0).getType();
|
String type = sourceIssues.get(0).getType();
|
||||||
if (ResultUnitEnum.P.getCode().equals(type)) {
|
if (StrUtil.isNotBlank(sourceIssues.get(0).getOtherType())) {
|
||||||
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
||||||
webSocketVO.setRequestId(ResultUnitEnum.P.getCode() + CnSocketUtil.START_TAG);
|
webSocketVO.setRequestId(sourceIssues.get(0).getOtherType() + CnSocketUtil.START_TAG);
|
||||||
|
type = sourceIssues.get(0).getOtherType();
|
||||||
} else {
|
} else {
|
||||||
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
|
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
|
||||||
}
|
}
|
||||||
@@ -1135,7 +1147,7 @@ public class SocketDevResponseService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 后续做系数校准
|
// 后续做系数校准
|
||||||
if (param.getTestItemList().get(1)) {
|
if (param.isCoefficientSelected()) {
|
||||||
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
||||||
webSocketVO.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
|
webSocketVO.setRequestId(SourceOperateCodeEnum.Coefficient_Check.getValue());
|
||||||
webSocketVO.setOperateCode(SourceOperateCodeEnum.big_start.getValue());
|
webSocketVO.setOperateCode(SourceOperateCodeEnum.big_start.getValue());
|
||||||
@@ -1159,11 +1171,11 @@ public class SocketDevResponseService {
|
|||||||
XiNumberManager.smallDevXiNumDataMap.clear();
|
XiNumberManager.smallDevXiNumDataMap.clear();
|
||||||
|
|
||||||
System.out.println("开始系数校准》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
|
System.out.println("开始系数校准》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");
|
||||||
} else if (param.getTestItemList().get(2)) {
|
} else if (param.isFormalTestSelected()) {
|
||||||
// 后续做正式检测
|
// 后续做正式检测
|
||||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
|
issueParam.setSourceId(param.getSourceName());
|
||||||
issueParam.setPlanId(param.getPlanId());
|
issueParam.setPlanId(param.getPlanId());
|
||||||
issueParam.setSourceId(param.getSourceId());
|
|
||||||
issueParam.setDevIds(param.getDevIds());
|
issueParam.setDevIds(param.getDevIds());
|
||||||
issueParam.setScriptId(param.getScriptId());
|
issueParam.setScriptId(param.getScriptId());
|
||||||
|
|
||||||
@@ -1205,13 +1217,16 @@ public class SocketDevResponseService {
|
|||||||
|
|
||||||
//告诉前端当前项开始了
|
//告诉前端当前项开始了
|
||||||
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
WebSocketVO<Object> webSocketVO = new WebSocketVO<>();
|
||||||
|
|
||||||
String type = sourceIssues.get(0).getType();
|
String type = sourceIssues.get(0).getType();
|
||||||
if (ResultUnitEnum.P.getCode().equals(type)) {
|
if (StrUtil.isNotBlank(sourceIssues.get(0).getOtherType())) {
|
||||||
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
sourceIssues.get(0).setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
||||||
webSocketVO.setRequestId(ResultUnitEnum.P.getCode() + CnSocketUtil.START_TAG);
|
webSocketVO.setRequestId(sourceIssues.get(0).getOtherType() + CnSocketUtil.START_TAG);
|
||||||
|
type = sourceIssues.get(0).getOtherType();
|
||||||
} else {
|
} else {
|
||||||
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
|
webSocketVO.setRequestId(sourceIssues.get(0).getType() + CnSocketUtil.START_TAG);
|
||||||
}
|
}
|
||||||
|
|
||||||
FormalTestManager.currentIssue = sourceIssues.get(0);
|
FormalTestManager.currentIssue = sourceIssues.get(0);
|
||||||
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
|
socketMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
|
||||||
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
|
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
|
||||||
@@ -1305,9 +1320,9 @@ public class SocketDevResponseService {
|
|||||||
|
|
||||||
//小项检测完后小项数减一,并更新map
|
//小项检测完后小项数减一,并更新map
|
||||||
long residueCount = 0;
|
long residueCount = 0;
|
||||||
if (sourceIssue.getIsP()) {
|
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
|
||||||
residueCount = SocketManager.getSourceTarget(ResultUnitEnum.P.getCode()) - 1;
|
residueCount = SocketManager.getSourceTarget(sourceIssue.getOtherType()) - 1;
|
||||||
SocketManager.addTargetMap(ResultUnitEnum.P.getCode(), residueCount);
|
SocketManager.addTargetMap(sourceIssue.getOtherType(), residueCount);
|
||||||
} else {
|
} else {
|
||||||
residueCount = SocketManager.getSourceTarget(sourceIssue.getType()) - 1;
|
residueCount = SocketManager.getSourceTarget(sourceIssue.getType()) - 1;
|
||||||
SocketManager.addTargetMap(sourceIssue.getType(), residueCount);
|
SocketManager.addTargetMap(sourceIssue.getType(), residueCount);
|
||||||
@@ -1351,14 +1366,15 @@ public class SocketDevResponseService {
|
|||||||
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
|
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
|
||||||
if (CollUtil.isNotEmpty(sourceIssueList)) {
|
if (CollUtil.isNotEmpty(sourceIssueList)) {
|
||||||
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
|
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
|
||||||
|
|
||||||
|
String type = sourceIssues.getType();
|
||||||
|
if (StrUtil.isNotBlank(sourceIssues.getOtherType())) {
|
||||||
|
sourceIssues.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
||||||
|
type = sourceIssues.getOtherType();
|
||||||
|
}
|
||||||
// 如果上一个大项检测完成,则检测下一个大项,并向前端推送消息
|
// 如果上一个大项检测完成,则检测下一个大项,并向前端推送消息
|
||||||
if (residueCount == 0) {
|
if (residueCount == 0) {
|
||||||
WebServiceManager.sendDetectionMessage(param.getUserPageId(), sourceIssues.getType() + CnSocketUtil.START_TAG, null, new ArrayList<>(), null);
|
WebServiceManager.sendDetectionMessage(param.getUserPageId(), type + CnSocketUtil.START_TAG, null, new ArrayList<>(), null);
|
||||||
}
|
|
||||||
String type = sourceIssues.getType();
|
|
||||||
if (sourceIssues.getIsP()) {
|
|
||||||
sourceIssues.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
|
||||||
type = ResultUnitEnum.P.getCode();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//控源下发下一个小项脚本
|
//控源下发下一个小项脚本
|
||||||
@@ -1374,8 +1390,14 @@ public class SocketDevResponseService {
|
|||||||
checkDataParam.setIsValueTypeName(false);
|
checkDataParam.setIsValueTypeName(false);
|
||||||
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
|
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);
|
||||||
|
if (Boolean.TRUE.equals(dataCheck)) {
|
||||||
|
resultService.tryNotifyThirdPartyAfterFormalTest(param);
|
||||||
|
}
|
||||||
CnSocketUtil.quitSend(param);
|
CnSocketUtil.quitSend(param);
|
||||||
|
// 数模式检测全部小项完成 → 释放锁,避免用户必须点"停止"才能让出
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_TEST_FINISHED");
|
||||||
}
|
}
|
||||||
successComm.clear();
|
successComm.clear();
|
||||||
FormalTestManager.realDataXiList.clear();
|
FormalTestManager.realDataXiList.clear();
|
||||||
@@ -1554,6 +1576,7 @@ public class SocketDevResponseService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param issue
|
* @param issue
|
||||||
* @return key为V或I,value为对应的源下发信息
|
* @return key为V或I,value为对应的源下发信息
|
||||||
@@ -1792,9 +1815,87 @@ public class SocketDevResponseService {
|
|||||||
//字典树
|
//字典树
|
||||||
SocketManager.valueTypeMap = iPqScriptCheckDataService.getValueTypeMap(param.getScriptId());
|
SocketManager.valueTypeMap = iPqScriptCheckDataService.getValueTypeMap(param.getScriptId());
|
||||||
|
|
||||||
if (param.getTestItemList().get(1)) {
|
if (param.isCoefficientSelected()) {
|
||||||
initXiManager(param);
|
initXiManager(param);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FormalTestManager.overload = getOverloadResult(param);
|
||||||
|
FormalTestManager.checkStartTime = LocalDateTime.now();
|
||||||
|
FormalTestManager.reCheckType = param.getReCheckType();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取过载测试结果
|
||||||
|
*
|
||||||
|
* @return 如果检测到电压过载,overload=1;如果检测到电流过载,overload=2;如果检测到电压&&电流过载,overload=3;反之,overload=4
|
||||||
|
*/
|
||||||
|
private int getOverloadResult(PreDetectionParam param) {
|
||||||
|
PqSource pqSource = pqSourceService.getPqSourceById(param.getSourceId());
|
||||||
|
BigDecimal maxVoltage = pqSource.getMaxVoltage();
|
||||||
|
BigDecimal maxCurrent = pqSource.getMaxCurrent();
|
||||||
|
|
||||||
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
|
issueParam.setSourceId(pqSource.getName());
|
||||||
|
issueParam.setPlanId(param.getPlanId());
|
||||||
|
issueParam.setDevIds(param.getDevIds());
|
||||||
|
issueParam.setScriptId(param.getScriptId());
|
||||||
|
issueParam.setIsPhaseSequence(CommonEnum.FORMAL_TEST.getValue());
|
||||||
|
List<SourceIssue> sourceIssues = pqScriptDtlsService.listSourceIssue(issueParam);
|
||||||
|
|
||||||
|
for (int i = 0; i < sourceIssues.size(); i++) {
|
||||||
|
SourceIssue sourceIssue = sourceIssues.get(i);
|
||||||
|
List<SourceIssue.ChannelListDTO> channelList = sourceIssue.getChannelList();
|
||||||
|
for (int j = 0; j < channelList.size(); j++) {
|
||||||
|
SourceIssue.ChannelListDTO channelListDTO = channelList.get(j);
|
||||||
|
Double fAmp = channelListDTO.getFAmp();
|
||||||
|
String channelType = channelListDTO.getChannelType();
|
||||||
|
|
||||||
|
if (ObjectUtil.isNotNull(fAmp)) {
|
||||||
|
if (channelType.contains("U")) {
|
||||||
|
// 电压判断
|
||||||
|
if (maxVoltage.compareTo(BigDecimal.valueOf(fAmp)) < 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 电流判断
|
||||||
|
if (maxCurrent.compareTo(BigDecimal.valueOf(fAmp)) < 0) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 暂态判断
|
||||||
|
if (channelListDTO.getDipFlag()) {
|
||||||
|
SourceIssue.ChannelListDTO.DipDataDTO dipData = channelListDTO.getDipData();
|
||||||
|
if (ObjectUtil.isNotNull(dipData)) {
|
||||||
|
Double fTransValue = dipData.getFTransValue();
|
||||||
|
if (ObjectUtil.isNotNull(fTransValue) && ObjectUtil.isNotNull(fAmp)) {
|
||||||
|
if (maxVoltage.compareTo(BigDecimal.valueOf(fTransValue / 100).max(BigDecimal.valueOf(fAmp))) < 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 谐波判断
|
||||||
|
if (channelListDTO.getHarmFlag()) {
|
||||||
|
List<SourceIssue.ChannelListDTO.HarmModel> harmList = channelListDTO.getHarmList();
|
||||||
|
double thd = harmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
|
||||||
|
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + thd) * fAmp)) < 0) {
|
||||||
|
return channelType.contains("U") ? 1 : 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 间谐波判断
|
||||||
|
if (channelListDTO.getInHarmFlag()) {
|
||||||
|
List<SourceIssue.ChannelListDTO.InharmModel> inharmList = channelListDTO.getInharmList();
|
||||||
|
double thd = inharmList.stream().map(harmModel -> harmModel.getFAmp() * harmModel.getFAmp() / 10000).mapToDouble(x -> x).sum();
|
||||||
|
if (maxVoltage.compareTo(BigDecimal.valueOf(Math.sqrt(1 + thd) * fAmp)) < 0) {
|
||||||
|
return channelType.contains("U") ? 1 : 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
//初始化系数校验参数
|
//初始化系数校验参数
|
||||||
@@ -1816,8 +1917,8 @@ public class SocketDevResponseService {
|
|||||||
XiNumberManager.devParameterList.add(devParameterSmall);
|
XiNumberManager.devParameterList.add(devParameterSmall);
|
||||||
|
|
||||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
|
issueParam.setSourceId(param.getSourceName());
|
||||||
issueParam.setPlanId(param.getPlanId());
|
issueParam.setPlanId(param.getPlanId());
|
||||||
issueParam.setSourceId(param.getSourceId());
|
|
||||||
issueParam.setDevIds(param.getDevIds());
|
issueParam.setDevIds(param.getDevIds());
|
||||||
issueParam.setScriptId(param.getScriptId());
|
issueParam.setScriptId(param.getScriptId());
|
||||||
issueParam.setIsPhaseSequence(CommonEnum.COEFFICIENT_TEST.getValue());
|
issueParam.setIsPhaseSequence(CommonEnum.COEFFICIENT_TEST.getValue());
|
||||||
@@ -1871,9 +1972,6 @@ public class SocketDevResponseService {
|
|||||||
|
|
||||||
if (nonHarmonicList.contains(sourceIssue.getType())) {
|
if (nonHarmonicList.contains(sourceIssue.getType())) {
|
||||||
for (DevData.SqlDataDTO sqlDataDTO : data.getSqlData()) {
|
for (DevData.SqlDataDTO sqlDataDTO : data.getSqlData()) {
|
||||||
if (sqlDataDTO.getDesc().equals("PF")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
DevData.SqlDataDTO.ListDTO listDTO = sqlDataDTO.getList();
|
DevData.SqlDataDTO.ListDTO listDTO = sqlDataDTO.getList();
|
||||||
SimAndDigNonHarmonicResult adNonHarmonicResult = new SimAndDigNonHarmonicResult();
|
SimAndDigNonHarmonicResult adNonHarmonicResult = new SimAndDigNonHarmonicResult();
|
||||||
adNonHarmonicResult.setTimeId(localDateTime);
|
adNonHarmonicResult.setTimeId(localDateTime);
|
||||||
|
|||||||
@@ -121,6 +121,15 @@ public class SocketSourceResponseService {
|
|||||||
sendErrorAndQuit(param, socketDataMsg, errorCode.getMessage());
|
sendErrorAndQuit(param, socketDataMsg, errorCode.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void sendSimulateInitFailure(PreDetectionParam param, String errorMessage) {
|
||||||
|
SocketDataMsg socketDataMsg = new SocketDataMsg();
|
||||||
|
socketDataMsg.setRequestId(SourceOperateCodeEnum.YJC_YTXJY.getValue());
|
||||||
|
socketDataMsg.setOperateCode(SourceOperateCodeEnum.INIT_GATHER.getValue());
|
||||||
|
socketDataMsg.setCode(SourceResponseCodeEnum.UNKNOWN_ERROR.getCode());
|
||||||
|
socketDataMsg.setData(errorMessage);
|
||||||
|
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当前检测会话中的设备列表
|
* 当前检测会话中的设备列表
|
||||||
@@ -214,12 +223,12 @@ public class SocketSourceResponseService {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
// TODO: 记录未知操作码到日志,并向前端发送友好提示
|
sendSimulateInitFailure(param, "未知操作码");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// TODO: 向前端发送错误提示
|
|
||||||
log.error("程控源响应消息操作码解析失败,原始消息: {}, 解析结果: {}", msg, enumByCode);
|
log.error("程控源响应消息操作码解析失败,原始消息: {}, 解析结果: {}", msg, enumByCode);
|
||||||
|
sendSimulateInitFailure(param, "未知操作码");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,10 +281,11 @@ public class SocketSourceResponseService {
|
|||||||
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
|
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
// 未识别的响应码:发送通用错误消息
|
sendSimulateInitFailure(param, "未知状态码");
|
||||||
WebServiceManager.sendUnknownErrorMessage(param.getUserPageId());
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
sendSimulateInitFailure(param, "未知状态码");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,18 +394,27 @@ public class SocketSourceResponseService {
|
|||||||
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
|
socketMsg.setRequestId(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + type);
|
||||||
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
|
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
|
||||||
} else {
|
} else {
|
||||||
//todo 前端推送收到的消息暂未处理好
|
// 推送过载测试结果
|
||||||
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
|
SocketDataMsg overloadSocketDataMsg = new SocketDataMsg();
|
||||||
//开始设备通讯检测(发送设备初始化)
|
overloadSocketDataMsg.setRequestId("overloadTest");
|
||||||
Map<String, List<PreDetection>> map = new HashMap<>(1);
|
overloadSocketDataMsg.setCode(FormalTestManager.overload);
|
||||||
map.put("deviceList", FormalTestManager.devList);
|
sendWebSocketMessage(param.getUserPageId(), overloadSocketDataMsg);
|
||||||
String jsonString = JSON.toJSONString(map);
|
if (FormalTestManager.overload != 4) {
|
||||||
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_SBTXJY.getValue());
|
CnSocketUtil.quitSendSource(param);
|
||||||
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_01.getValue());
|
} else {
|
||||||
socketMsg.setData(jsonString);
|
//todo 前端推送收到的消息暂未处理好
|
||||||
String json = JSON.toJSONString(socketMsg);
|
sendWebSocketMessage(param.getUserPageId(), socketDataMsg);
|
||||||
// 使用智能发送工具类,自动管理设备连接
|
//开始设备通讯检测(发送设备初始化)
|
||||||
socketManager.smartSendToDevice(param, json);
|
Map<String, List<PreDetection>> map = new HashMap<>(1);
|
||||||
|
map.put("deviceList", FormalTestManager.devList);
|
||||||
|
String jsonString = JSON.toJSONString(map);
|
||||||
|
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_SBTXJY.getValue());
|
||||||
|
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_01.getValue());
|
||||||
|
socketMsg.setData(jsonString);
|
||||||
|
String json = JSON.toJSONString(socketMsg);
|
||||||
|
// 使用智能发送工具类,自动管理设备连接
|
||||||
|
socketManager.smartSendToDevice(param, json);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case UNPROCESSED_BUSINESS:
|
case UNPROCESSED_BUSINESS:
|
||||||
@@ -556,9 +575,6 @@ public class SocketSourceResponseService {
|
|||||||
DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
|
DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
|
||||||
// 设置监测点ID列表
|
// 设置监测点ID列表
|
||||||
phaseSequenceParam.setMoniterIdList(monitorIdList);
|
phaseSequenceParam.setMoniterIdList(monitorIdList);
|
||||||
if (socketDataMsg.getRequestId().equals(SourceOperateCodeEnum.FORMAL_REAL.getValue() + CnSocketUtil.STEP_TAG + "P")) {
|
|
||||||
comm.add("real$PF");
|
|
||||||
}
|
|
||||||
// 设置数据类型列表
|
// 设置数据类型列表
|
||||||
phaseSequenceParam.setDataType(comm);
|
phaseSequenceParam.setDataType(comm);
|
||||||
// 设置读取次数
|
// 设置读取次数
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.njcn.gather.detection.lock;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测互斥锁对象(不可变)。
|
||||||
|
* 字段含义见 docs/superpowers/specs/2026-05-28-单用户检测互斥-design.md §2.1
|
||||||
|
*/
|
||||||
|
public final class DetectionLock {
|
||||||
|
|
||||||
|
private final String userId;
|
||||||
|
private final String userName;
|
||||||
|
private final String userPageId;
|
||||||
|
private final long acquireTime;
|
||||||
|
private final long expireAt;
|
||||||
|
|
||||||
|
public DetectionLock(String userId, String userName, String userPageId,
|
||||||
|
long acquireTime, long expireAt) {
|
||||||
|
this.userId = userId;
|
||||||
|
this.userName = userName;
|
||||||
|
this.userPageId = userPageId;
|
||||||
|
this.acquireTime = acquireTime;
|
||||||
|
this.expireAt = expireAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUserId() { return userId; }
|
||||||
|
public String getUserName() { return userName; }
|
||||||
|
public String getUserPageId() { return userPageId; }
|
||||||
|
public long getAcquireTime() { return acquireTime; }
|
||||||
|
public long getExpireAt() { return expireAt; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package com.njcn.gather.detection.lock;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
import com.njcn.gather.detection.pojo.vo.DetectionLockHolderVO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测互斥锁管理器(进程内单例)。
|
||||||
|
* 详细设计:docs/superpowers/specs/2026-05-28-单用户检测互斥-design.md
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public final class DetectionLockManager {
|
||||||
|
|
||||||
|
private static final long LOCK_MAX_HOLD_MS = TimeUnit.HOURS.toMillis(4);
|
||||||
|
|
||||||
|
private static final DetectionLockManager INSTANCE = new DetectionLockManager();
|
||||||
|
|
||||||
|
public static DetectionLockManager getInstance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final AtomicReference<DetectionLock> current = new AtomicReference<>(null);
|
||||||
|
|
||||||
|
private DetectionLockManager() {}
|
||||||
|
|
||||||
|
/** 抢锁。同账号视为重入(刷新 page/expireAt)。 */
|
||||||
|
public AcquireResult tryAcquire(String userId, String userName, String userPageId) {
|
||||||
|
for (int attempt = 0; attempt < 2; attempt++) {
|
||||||
|
DetectionLock cur = current.get();
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
// 空闲 或 绝对超时已过 → 直接抢
|
||||||
|
if (cur == null || now > cur.getExpireAt()) {
|
||||||
|
DetectionLock fresh = new DetectionLock(userId, userName, userPageId, now, now + LOCK_MAX_HOLD_MS);
|
||||||
|
if (current.compareAndSet(cur, fresh)) {
|
||||||
|
log.info("DetectionLock acquired by userId={}, userName={}, userPageId={}", userId, userName, userPageId);
|
||||||
|
return AcquireResult.ok();
|
||||||
|
}
|
||||||
|
continue; // CAS 失败重试
|
||||||
|
}
|
||||||
|
// 同账号重入 → 刷新
|
||||||
|
if (userId.equals(cur.getUserId())) {
|
||||||
|
DetectionLock refreshed = new DetectionLock(userId, userName, userPageId, now, now + LOCK_MAX_HOLD_MS);
|
||||||
|
if (current.compareAndSet(cur, refreshed)) {
|
||||||
|
log.debug("DetectionLock reentered by userId={}, new userPageId={}", userId, userPageId);
|
||||||
|
return AcquireResult.ok();
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 被他人持有
|
||||||
|
return AcquireResult.busy(toHolderVO(cur));
|
||||||
|
}
|
||||||
|
// 两次 CAS 都失败属于罕见高并发场景:绝不返回 ok()(那样会让调用方误以为持锁)。
|
||||||
|
// 返回 busy,data 可能为 null(锁刚被释放);调用方/前端按"请重试"处理。
|
||||||
|
DetectionLock cur = current.get();
|
||||||
|
return AcquireResult.busy(cur == null ? null : toHolderVO(cur));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅当 holder.userId == userId 才释放(幂等)。
|
||||||
|
* 循环终止性:每轮 CAS 失败意味着 current 被其他线程改写;
|
||||||
|
* 下一轮 get 后 cur 可能变成 null 或不再匹配 userId,命中前置 return 退出。
|
||||||
|
* 唯一可能继续的情况是另一线程把它换成了同 userId 的新 lock,下一轮 CAS 会再次尝试;
|
||||||
|
* 最坏情况下 CAS 成功,仍然终止。 */
|
||||||
|
public void releaseIfHeldBy(String userId, String reason) {
|
||||||
|
while (true) {
|
||||||
|
DetectionLock cur = current.get();
|
||||||
|
if (cur == null || !cur.getUserId().equals(userId)) return;
|
||||||
|
if (current.compareAndSet(cur, null)) {
|
||||||
|
log.info("DetectionLock released, reason={}, userId={}", reason, userId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅当 holder.userPageId == userPageId 才释放(幂等)。终止性同 releaseIfHeldBy。 */
|
||||||
|
public void releaseIfMatchPage(String userPageId, String reason) {
|
||||||
|
while (true) {
|
||||||
|
DetectionLock cur = current.get();
|
||||||
|
if (cur == null || !cur.getUserPageId().equals(userPageId)) return;
|
||||||
|
if (current.compareAndSet(cur, null)) {
|
||||||
|
log.info("DetectionLock released, reason={}, userPageId={}", reason, userPageId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 管理员强制释放,不校验 holder。 */
|
||||||
|
public void forceRelease(String operatorUserId, String reason) {
|
||||||
|
DetectionLock cur = current.getAndSet(null);
|
||||||
|
if (cur != null) {
|
||||||
|
log.warn("DetectionLock force-released by operator={}, victim userId={}, reason={}",
|
||||||
|
operatorUserId, cur.getUserId(), reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 返回当前 holder 快照;返回 null 表示空闲。 */
|
||||||
|
public DetectionLock getCurrent() {
|
||||||
|
DetectionLock cur = current.get();
|
||||||
|
// 顺手做惰性超时回收(spec R5)
|
||||||
|
if (cur != null && System.currentTimeMillis() > cur.getExpireAt()) {
|
||||||
|
current.compareAndSet(cur, null);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把 DetectionLock 转成给前端的 VO。 */
|
||||||
|
public static DetectionLockHolderVO toHolderVO(DetectionLock lock) {
|
||||||
|
DetectionLockHolderVO vo = new DetectionLockHolderVO();
|
||||||
|
vo.setHolderUserId(lock.getUserId());
|
||||||
|
vo.setHolderUserName(lock.getUserName());
|
||||||
|
vo.setAcquireTime(new Date(lock.getAcquireTime()));
|
||||||
|
vo.setExpireAt(new Date(lock.getExpireAt()));
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 抢锁结果。 */
|
||||||
|
public static final class AcquireResult {
|
||||||
|
private final boolean ok;
|
||||||
|
private final DetectionLockHolderVO holder;
|
||||||
|
|
||||||
|
private AcquireResult(boolean ok, DetectionLockHolderVO holder) {
|
||||||
|
this.ok = ok;
|
||||||
|
this.holder = holder;
|
||||||
|
}
|
||||||
|
public static AcquireResult ok() { return new AcquireResult(true, null); }
|
||||||
|
public static AcquireResult busy(DetectionLockHolderVO holder) { return new AcquireResult(false, holder); }
|
||||||
|
public boolean isOk() { return ok; }
|
||||||
|
public DetectionLockHolderVO getHolder() { return holder; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,13 +33,19 @@ public enum DetectionCodeEnum {
|
|||||||
IA("IA", "电流相角"),
|
IA("IA", "电流相角"),
|
||||||
I1A("I1A", "电流基波角度值"),
|
I1A("I1A", "电流基波角度值"),
|
||||||
V_UNBAN("V_UNBAN", "三相电压负序不平衡度"),
|
V_UNBAN("V_UNBAN", "三相电压负序不平衡度"),
|
||||||
|
SeqV("SeqV", "电压序分量"),
|
||||||
I_UNBAN("I_UNBAN", "三相电流负序不平衡度"),
|
I_UNBAN("I_UNBAN", "三相电流负序不平衡度"),
|
||||||
|
SeqA("SeqA", "电流序分量"),
|
||||||
PST("PST", "短时间闪变"),
|
PST("PST", "短时间闪变"),
|
||||||
W("W", "有功功率"),
|
W("W", "总有功功率"),
|
||||||
VARW("VARW", "无功功率"),
|
VARW("VARW", "总无功功率"),
|
||||||
VAW("VAW", "视在功率"),
|
VAW("VAW", "总视在功率"),
|
||||||
// PF("PF", "功率因数"),
|
PF("PF", "功率因数"),
|
||||||
// P_FUND("P_FUND", "基波有功功率"),
|
TOTW("TotW", "三相总有功功率"),
|
||||||
|
TOTVA("TotVA", "三相总视在功率"),
|
||||||
|
TOTVAR("TotVAr", "三相总无功功率"),
|
||||||
|
TOTPF("TotPF","三相功率因数"),
|
||||||
|
// P_FUND("P_FUND", "基波有功功率"),
|
||||||
// P_HVAR("P_HVAR", "基波无功功率"),
|
// P_HVAR("P_HVAR", "基波无功功率"),
|
||||||
// P_HVA("P_HVA", "基波视在功率"),
|
// P_HVA("P_HVA", "基波视在功率"),
|
||||||
I1("I1", "基波电流"),
|
I1("I1", "基波电流"),
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ public enum DetectionResponseEnum {
|
|||||||
|
|
||||||
|
|
||||||
SCRIPT_CHECK_DATA_NOT_EXIST("A020040","测试脚本项暂无配置" ),
|
SCRIPT_CHECK_DATA_NOT_EXIST("A020040","测试脚本项暂无配置" ),
|
||||||
EXCEED_MAX_TIME("A020041","检测次数超出最大限制!" );
|
EXCEED_MAX_TIME("A020041","检测次数超出最大限制!" ),
|
||||||
|
DETECTION_BUSY("A020042", "检测进行中");
|
||||||
|
|
||||||
private final String code;
|
private final String code;
|
||||||
private final String message;
|
private final String message;
|
||||||
|
|||||||
@@ -38,10 +38,31 @@ public class ContrastDetectionParam {
|
|||||||
@NotEmpty(message = DetectionValidMessage.PAIRS_NOT_EMPTY)
|
@NotEmpty(message = DetectionValidMessage.PAIRS_NOT_EMPTY)
|
||||||
private Map<String, String> pairs;
|
private Map<String, String> pairs;
|
||||||
/**
|
/**
|
||||||
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为正式检测
|
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为守时校验、第四个元素为正式检测。
|
||||||
|
* 比对场景暂不支持系数校准和守时校验,第二、第三个元素固定为 false。
|
||||||
*/
|
*/
|
||||||
private List<Boolean> testItemList;
|
private List<Boolean> testItemList;
|
||||||
|
|
||||||
|
public boolean isPreTestSelected() {
|
||||||
|
return isTestItemSelected(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCoefficientSelected() {
|
||||||
|
return isTestItemSelected(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTimeCheckSelected() {
|
||||||
|
return isTestItemSelected(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFormalTestSelected() {
|
||||||
|
return isTestItemSelected(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isTestItemSelected(int index) {
|
||||||
|
return testItemList != null && testItemList.size() > index && Boolean.TRUE.equals(testItemList.get(index));
|
||||||
|
}
|
||||||
|
|
||||||
private String userId;
|
private String userId;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import lombok.Data;
|
|||||||
import javax.validation.constraints.NotBlank;
|
import javax.validation.constraints.NotBlank;
|
||||||
import javax.validation.constraints.NotEmpty;
|
import javax.validation.constraints.NotEmpty;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author wr
|
* @author wr
|
||||||
@@ -46,6 +45,11 @@ public class PreDetectionParam {
|
|||||||
*/
|
*/
|
||||||
private String sourceId;
|
private String sourceId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 源名称
|
||||||
|
*/
|
||||||
|
private String sourceName;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 所属误差体系
|
* 所属误差体系
|
||||||
*/
|
*/
|
||||||
@@ -71,7 +75,27 @@ public class PreDetectionParam {
|
|||||||
private Float humidity;
|
private Float humidity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为正式检测
|
* 检测项列表。第一个元素为预检测、第二个元素为系数校准、第三个元素为守时校验、第四个元素为正式检测
|
||||||
*/
|
*/
|
||||||
private List<Boolean> testItemList;
|
private List<Boolean> testItemList;
|
||||||
|
|
||||||
|
public boolean isPreTestSelected() {
|
||||||
|
return isTestItemSelected(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCoefficientSelected() {
|
||||||
|
return isTestItemSelected(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTimeCheckSelected() {
|
||||||
|
return isTestItemSelected(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFormalTestSelected() {
|
||||||
|
return isTestItemSelected(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isTestItemSelected(int index) {
|
||||||
|
return testItemList != null && testItemList.size() > index && Boolean.TRUE.equals(testItemList.get(index));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.njcn.gather.detection.pojo.vo;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测锁持有者信息,用于在抢锁失败响应中返回给前端。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class DetectionLockHolderVO {
|
||||||
|
|
||||||
|
private String holderUserId;
|
||||||
|
private String holderUserName;
|
||||||
|
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||||
|
private Date acquireTime;
|
||||||
|
|
||||||
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||||
|
private Date expireAt;
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ import com.njcn.gather.monitor.service.IPqMonitorService;
|
|||||||
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
||||||
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
|
import com.njcn.gather.report.pojo.enums.PowerIndexEnum;
|
||||||
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
|
import com.njcn.gather.result.pojo.enums.ResultUnitEnum;
|
||||||
|
import com.njcn.gather.script.mapper.PqScriptMapper;
|
||||||
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
|
import com.njcn.gather.script.pojo.po.PqScriptCheckData;
|
||||||
import com.njcn.gather.script.pojo.po.SourceIssue;
|
import com.njcn.gather.script.pojo.po.SourceIssue;
|
||||||
import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
import com.njcn.gather.script.service.IPqScriptCheckDataService;
|
||||||
@@ -73,6 +74,7 @@ public class DetectionServiceImpl {
|
|||||||
private final IPqMonitorService pqMonitorService;
|
private final IPqMonitorService pqMonitorService;
|
||||||
private final IPqDevService pqDevService;
|
private final IPqDevService pqDevService;
|
||||||
private final IPqStandardDevGainRecordService pqStandardDevGainRecordService;
|
private final IPqStandardDevGainRecordService pqStandardDevGainRecordService;
|
||||||
|
private final PqScriptMapper pqScriptMapper;
|
||||||
|
|
||||||
public static final String TYPE_A = "A";
|
public static final String TYPE_A = "A";
|
||||||
public static final String TYPE_B = "B";
|
public static final String TYPE_B = "B";
|
||||||
@@ -162,9 +164,10 @@ public class DetectionServiceImpl {
|
|||||||
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
|
SysTestConfig oneConfig = sysTestConfigService.getOneConfig();
|
||||||
List<ErrDtlsCheckDataVO> errDtlsCheckData = pqErrSysDtlsService.listByPqErrSysIdAndTypes(param);
|
List<ErrDtlsCheckDataVO> errDtlsCheckData = pqErrSysDtlsService.listByPqErrSysIdAndTypes(param);
|
||||||
ResultUnitEnum resultUnitEnumByCode = ResultUnitEnum.getResultUnitEnumByCode(sourceIssue.getType());
|
ResultUnitEnum resultUnitEnumByCode = ResultUnitEnum.getResultUnitEnumByCode(sourceIssue.getType());
|
||||||
if (sourceIssue.getIsP()) {
|
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
|
||||||
resultUnitEnumByCode = ResultUnitEnum.P;
|
resultUnitEnumByCode = ResultUnitEnum.getResultUnitEnumByCode(sourceIssue.getOtherType());
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (resultUnitEnumByCode) {
|
switch (resultUnitEnumByCode) {
|
||||||
/**
|
/**
|
||||||
* 频率
|
* 频率
|
||||||
@@ -173,6 +176,8 @@ public class DetectionServiceImpl {
|
|||||||
return isQualified(dev, devIdMapComm, errDtlsCheckData, F, sourceIssue, dataRule, code, oneConfig.getScale());
|
return isQualified(dev, devIdMapComm, errDtlsCheckData, F, sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
case P:
|
case P:
|
||||||
return isQualified(dev, devIdMapComm, errDtlsCheckData, P, sourceIssue, dataRule, code, oneConfig.getScale());
|
return isQualified(dev, devIdMapComm, errDtlsCheckData, P, sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
|
case ANGLE:
|
||||||
|
return isQualified(dev, devIdMapComm, errDtlsCheckData, resultUnitEnumByCode.getCode(), sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
/**
|
/**
|
||||||
* 电压
|
* 电压
|
||||||
*/
|
*/
|
||||||
@@ -205,22 +210,12 @@ public class DetectionServiceImpl {
|
|||||||
* 三相电压不平衡度
|
* 三相电压不平衡度
|
||||||
*/
|
*/
|
||||||
case IMBV:
|
case IMBV:
|
||||||
SimAndDigNonHarmonicResult vUnban = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, "V_UNBAN", oneConfig.getScale());
|
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, U, sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
if (ObjectUtil.isNotNull(vUnban)) {
|
|
||||||
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(vUnban), code);
|
|
||||||
return vUnban.getResultFlag();
|
|
||||||
}
|
|
||||||
return 4;
|
|
||||||
/**
|
/**
|
||||||
* 三相电流不平衡度
|
* 三相电流不平衡度
|
||||||
*/
|
*/
|
||||||
case IMBA:
|
case IMBA:
|
||||||
SimAndDigNonHarmonicResult iUnban = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, "I_UNBAN", oneConfig.getScale());
|
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, I, sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
if (ObjectUtil.isNotNull(iUnban)) {
|
|
||||||
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(iUnban), code);
|
|
||||||
return iUnban.getResultFlag();
|
|
||||||
}
|
|
||||||
return 4;
|
|
||||||
/**
|
/**
|
||||||
* 谐波有功功率
|
* 谐波有功功率
|
||||||
*/
|
*/
|
||||||
@@ -235,12 +230,7 @@ public class DetectionServiceImpl {
|
|||||||
* 闪变
|
* 闪变
|
||||||
*/
|
*/
|
||||||
case F:
|
case F:
|
||||||
SimAndDigNonHarmonicResult pst = isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, null, sourceIssue, dataRule, "PST", oneConfig.getScale());
|
return isUnBalanceOrFlickerQualified(dev, devIdMapComm, errDtlsCheckData, DetectionCodeEnum.PST.getCode(), sourceIssue, dataRule, code, oneConfig.getScale());
|
||||||
if (ObjectUtil.isNotNull(pst)) {
|
|
||||||
detectionDataDealService.acceptNonHarmonicResult(Arrays.asList(pst), code);
|
|
||||||
return pst.getResultFlag();
|
|
||||||
}
|
|
||||||
return 4;
|
|
||||||
/**
|
/**
|
||||||
* 暂态
|
* 暂态
|
||||||
*/
|
*/
|
||||||
@@ -430,11 +420,13 @@ public class DetectionServiceImpl {
|
|||||||
List<SimAndDigNonHarmonicResult> info = new ArrayList<>();
|
List<SimAndDigNonHarmonicResult> info = new ArrayList<>();
|
||||||
List<String> devValueTypeList = sourceIssue.getDevValueTypeList();
|
List<String> devValueTypeList = sourceIssue.getDevValueTypeList();
|
||||||
for (String s : devValueTypeList) {
|
for (String s : devValueTypeList) {
|
||||||
if ((DetectionCodeEnum.REAL_PREFIX.getCode() + "PF").equals(s)) {
|
String[] splitArr = s.split("\\$");
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// 根据数据处理规则取值。key为相别,value为值列表
|
// 根据数据处理规则取值。key为相别,value为值列表
|
||||||
Map<String, List<Double>> map = devListMap(dev, dataRule, s.split("\\$")[1]);
|
Map<String, List<Double>> map = devListMap(dev, dataRule, splitArr[1]);
|
||||||
|
List<ErrDtlsCheckDataVO> dtlsCheckData = null;
|
||||||
|
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
|
||||||
|
dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(splitArr[1])).collect(Collectors.toList());
|
||||||
|
}
|
||||||
Double fData = 1.0;
|
Double fData = 1.0;
|
||||||
if (U.equals(type)) {
|
if (U.equals(type)) {
|
||||||
fData = sourceIssue.getFUn();
|
fData = sourceIssue.getFUn();
|
||||||
@@ -446,8 +438,18 @@ public class DetectionServiceImpl {
|
|||||||
fData = sourceIssue.getFFreq();
|
fData = sourceIssue.getFFreq();
|
||||||
}
|
}
|
||||||
if (P.equals(type)) {
|
if (P.equals(type)) {
|
||||||
fData = sourceIssue.getFUn() * sourceIssue.getFIn();
|
if (!DetectionCodeEnum.PF.getCode().equals(splitArr[1])) {
|
||||||
|
Boolean valueType = pqScriptMapper.selectScriptIsValueType(sourceIssue.getScriptId());
|
||||||
|
if (valueType) {
|
||||||
|
fData = sourceIssue.getFUn() * sourceIssue.getFIn() / 100;
|
||||||
|
}
|
||||||
|
Double finalFData = fData;
|
||||||
|
dtlsCheckData.stream().forEach(x -> x.setValue(x.getValue() * finalFData));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// if (ResultUnitEnum.ANGLE.getCode().equals(type)) {
|
||||||
|
// fData = null;
|
||||||
|
// }
|
||||||
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
|
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
|
||||||
String[] split = dev.get(0).getId().split("_");
|
String[] split = dev.get(0).getId().split("_");
|
||||||
String devID = devIdMapComm.get(split[0]);
|
String devID = devIdMapComm.get(split[0]);
|
||||||
@@ -457,52 +459,63 @@ public class DetectionServiceImpl {
|
|||||||
result.setDataType(sourceIssue.getDataType());
|
result.setDataType(sourceIssue.getDataType());
|
||||||
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
|
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
|
||||||
Integer isQualified = 4;
|
Integer isQualified = 4;
|
||||||
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
|
if (CollUtil.isNotEmpty(dtlsCheckData)) {
|
||||||
List<ErrDtlsCheckDataVO> dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(s.split("\\$")[1])).collect(Collectors.toList());
|
result.setAdType(dtlsCheckData.get(0).getValueType());
|
||||||
if (CollUtil.isNotEmpty(dtlsCheckData)) {
|
isQualified = dtlsCheckData.get(0).getIsQualified();
|
||||||
result.setAdType(dtlsCheckData.get(0).getValueType());
|
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
|
||||||
isQualified = dtlsCheckData.get(0).getIsQualified();
|
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
|
||||||
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
|
|
||||||
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (map.containsKey(TYPE_T)) {
|
}
|
||||||
List<ErrDtlsCheckDataVO> checkDataT = dtlsCheckData.stream().filter(x -> TYPE_T.equals(x.getPhase())).collect(Collectors.toList());
|
result.setResultFlag(isQualified);
|
||||||
if (CollUtil.isNotEmpty(checkDataT)) {
|
if (map.containsKey(TYPE_T)) {
|
||||||
DetectionData t = rangeComparisonList(map.get(TYPE_T), isQualified, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule, scale);
|
List<ErrDtlsCheckDataVO> checkDataT = dtlsCheckData.stream().filter(x -> TYPE_T.equals(x.getPhase())).collect(Collectors.toList());
|
||||||
result.setTValue(JSON.toJSONString(t));
|
if (CollUtil.isNotEmpty(checkDataT)) {
|
||||||
result.setResultFlag(t.getIsData());
|
DetectionData t = rangeComparisonList(map.get(TYPE_T), isQualified, pqErrSysDtls, fData, checkDataT.get(0).getValue(), dataRule, scale);
|
||||||
}
|
result.setTValue(JSON.toJSONString(t));
|
||||||
} else {
|
result.setResultFlag(t.getIsData());
|
||||||
List<DetectionData> resultFlag = new ArrayList<>();
|
}
|
||||||
Map<String, BiConsumer<SimAndDigNonHarmonicResult, DetectionData>> setters = new HashMap<>();
|
} else {
|
||||||
setters.put(TYPE_A, (r, d) -> r.setAValue(JSON.toJSONString(d)));
|
List<DetectionData> resultFlag = new ArrayList<>();
|
||||||
setters.put(TYPE_B, (r, d) -> r.setBValue(JSON.toJSONString(d)));
|
Map<String, BiConsumer<SimAndDigNonHarmonicResult, DetectionData>> setters = new HashMap<>();
|
||||||
setters.put(TYPE_C, (r, d) -> r.setCValue(JSON.toJSONString(d)));
|
setters.put(TYPE_A, (r, d) -> r.setAValue(JSON.toJSONString(d)));
|
||||||
|
setters.put(TYPE_B, (r, d) -> r.setBValue(JSON.toJSONString(d)));
|
||||||
|
setters.put(TYPE_C, (r, d) -> r.setCValue(JSON.toJSONString(d)));
|
||||||
|
|
||||||
List<String> phases = Arrays.asList(TYPE_A, TYPE_B, TYPE_C);
|
List<String> phases = Arrays.asList(TYPE_A, TYPE_B, TYPE_C);
|
||||||
for (String phase : phases) {
|
for (String phase : phases) {
|
||||||
List<ErrDtlsCheckDataVO> checkData = dtlsCheckData.stream()
|
List<ErrDtlsCheckDataVO> checkData = dtlsCheckData.stream()
|
||||||
.filter(x -> phase.equals(x.getPhase()))
|
.filter(x -> phase.equals(x.getPhase()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
if (CollUtil.isNotEmpty(checkData)) {
|
if (CollUtil.isNotEmpty(checkData)) {
|
||||||
List<Double> phaseValue = map.get(phase);
|
List<Double> phaseValue = map.get(phase);
|
||||||
// 注意:如果map中不存在该phase的键,phaseValue可能为null,需确保map包含该键
|
if (ResultUnitEnum.ANGLE.getCode().equals(type)) {
|
||||||
DetectionData detectionData = rangeComparisonList(phaseValue, isQualified, pqErrSysDtls, fData, checkData.get(0).getValue(), dataRule, scale);
|
phaseValue = phaseValue.stream().map(x -> {
|
||||||
resultFlag.add(detectionData);
|
// 原始误差值
|
||||||
BiConsumer<SimAndDigNonHarmonicResult, DetectionData> setter = setters.get(phase);
|
double originDiff = x - checkData.get(0).getValue();
|
||||||
if (setter != null) {
|
// 转换误差值
|
||||||
setter.accept(result, detectionData);
|
double translateDiff = Math.abs(originDiff) - 360;
|
||||||
} else {
|
if (Math.abs(translateDiff) <= 10) {
|
||||||
// 处理未定义的setter的情况
|
return Math.abs(x);
|
||||||
throw new IllegalArgumentException("Setter not defined for phase: " + phase);
|
} else {
|
||||||
}
|
return x;
|
||||||
|
}
|
||||||
|
}).collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
// 注意:如果map中不存在该phase的键,phaseValue可能为null,需确保map包含该键
|
||||||
|
DetectionData detectionData = rangeComparisonList(phaseValue, isQualified, pqErrSysDtls, fData, checkData.get(0).getValue(), dataRule, scale);
|
||||||
|
resultFlag.add(detectionData);
|
||||||
|
BiConsumer<SimAndDigNonHarmonicResult, DetectionData> setter = setters.get(phase);
|
||||||
|
if (setter != null) {
|
||||||
|
setter.accept(result, detectionData);
|
||||||
|
} else {
|
||||||
|
// 处理未定义的setter的情况
|
||||||
|
throw new IllegalArgumentException("Setter not defined for phase: " + phase);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result.setResultFlag(setResultFlag(resultFlag));
|
|
||||||
}
|
}
|
||||||
info.add(result);
|
result.setResultFlag(setResultFlag(resultFlag));
|
||||||
}
|
}
|
||||||
|
info.add(result);
|
||||||
}
|
}
|
||||||
if (CollUtil.isNotEmpty(info)) {
|
if (CollUtil.isNotEmpty(info)) {
|
||||||
detectionDataDealService.acceptNonHarmonicResult(info, code);
|
detectionDataDealService.acceptNonHarmonicResult(info, code);
|
||||||
@@ -605,74 +618,110 @@ public class DetectionServiceImpl {
|
|||||||
* @param dataRule 数据处理原则
|
* @param dataRule 数据处理原则
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public SimAndDigNonHarmonicResult isUnBalanceOrFlickerQualified(List<DevData> dev,
|
public Integer isUnBalanceOrFlickerQualified(List<DevData> dev,
|
||||||
Map<String, String> devIdMapComm,
|
Map<String, String> devIdMapComm,
|
||||||
List<ErrDtlsCheckDataVO> errDtlsCheckData,
|
List<ErrDtlsCheckDataVO> errDtlsCheckData,
|
||||||
String type,
|
String type,
|
||||||
SourceIssue sourceIssue,
|
SourceIssue sourceIssue,
|
||||||
DictDataEnum dataRule,
|
DictDataEnum dataRule,
|
||||||
String code, Integer scale) {
|
String code, Integer scale) {
|
||||||
|
List<SimAndDigNonHarmonicResult> info = new ArrayList<>();
|
||||||
List<PqScriptCheckData> checkData = pqScriptCheckDataService.list(new MPJLambdaWrapper<PqScriptCheckData>()
|
List<PqScriptCheckData> checkData = pqScriptCheckDataService.list(new MPJLambdaWrapper<PqScriptCheckData>()
|
||||||
.eq(PqScriptCheckData::getScriptIndex, sourceIssue.getIndex())
|
.eq(PqScriptCheckData::getScriptIndex, sourceIssue.getIndex())
|
||||||
.eq(PqScriptCheckData::getScriptId, sourceIssue.getScriptId())
|
.eq(PqScriptCheckData::getScriptId, sourceIssue.getScriptId())
|
||||||
);
|
);
|
||||||
Map<String, List<Double>> map = devListMap(dev, dataRule, code);
|
List<String> devValueTypeList = sourceIssue.getDevValueTypeList();
|
||||||
if (CollUtil.isNotEmpty(map)) {
|
for (String s : devValueTypeList) {
|
||||||
Double fData = 1.0;
|
String[] splitArr = s.split("\\$");
|
||||||
if (U.equals(type)) {
|
Map<String, List<Double>> map = devListMap(dev, dataRule, splitArr[1]);
|
||||||
fData = sourceIssue.getFUn();
|
if (CollUtil.isNotEmpty(map)) {
|
||||||
}
|
List<ErrDtlsCheckDataVO> dtlsCheckData = null;
|
||||||
if (I.equals(type)) {
|
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
|
||||||
fData = sourceIssue.getFIn();
|
dtlsCheckData = errDtlsCheckData.stream().filter(x -> x.getValueTypeCode().equals(s.split("\\$")[1])).collect(Collectors.toList());
|
||||||
}
|
|
||||||
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
|
|
||||||
String[] split = dev.get(0).getId().split("_");
|
|
||||||
String devID = devIdMapComm.get(split[0]);
|
|
||||||
result.setDevMonitorId(devID + "_" + split[1]);
|
|
||||||
result.setScriptId(sourceIssue.getScriptId());
|
|
||||||
result.setSort(sourceIssue.getIndex());
|
|
||||||
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
|
|
||||||
Integer isQualified = 4;
|
|
||||||
if (CollUtil.isNotEmpty(errDtlsCheckData)) {
|
|
||||||
result.setAdType(errDtlsCheckData.get(0).getValueType());
|
|
||||||
isQualified = errDtlsCheckData.get(0).getIsQualified();
|
|
||||||
if (CollUtil.isNotEmpty(errDtlsCheckData.get(0).getErrSysDtls())) {
|
|
||||||
pqErrSysDtls = errDtlsCheckData.get(0).getErrSysDtls();
|
|
||||||
}
|
}
|
||||||
|
Double fData = 1.0;
|
||||||
|
if (U.equals(type)) {
|
||||||
|
fData = sourceIssue.getFUn();
|
||||||
|
}
|
||||||
|
if (I.equals(type)) {
|
||||||
|
fData = sourceIssue.getFIn();
|
||||||
|
}
|
||||||
|
SimAndDigNonHarmonicResult result = new SimAndDigNonHarmonicResult();
|
||||||
|
String[] split = dev.get(0).getId().split("_");
|
||||||
|
String devID = devIdMapComm.get(split[0]);
|
||||||
|
result.setDevMonitorId(devID + "_" + split[1]);
|
||||||
|
result.setScriptId(sourceIssue.getScriptId());
|
||||||
|
result.setSort(sourceIssue.getIndex());
|
||||||
|
result.setDataType(sourceIssue.getDataType());
|
||||||
|
List<PqErrSysDtls> pqErrSysDtls = new ArrayList<>();
|
||||||
|
Integer isQualified = 4;
|
||||||
|
if (CollUtil.isNotEmpty(dtlsCheckData)) {
|
||||||
|
result.setAdType(dtlsCheckData.get(0).getValueType());
|
||||||
|
isQualified = dtlsCheckData.get(0).getIsQualified();
|
||||||
|
if (CollUtil.isNotEmpty(dtlsCheckData.get(0).getErrSysDtls())) {
|
||||||
|
pqErrSysDtls = dtlsCheckData.get(0).getErrSysDtls();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.setResultFlag(isQualified);
|
||||||
|
// 闪变
|
||||||
|
if (DetectionCodeEnum.PST.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
|
||||||
|
|
||||||
|
//取出源所对应的相别信息
|
||||||
|
List<PqScriptCheckData> channelTypeAList = checkData.stream()
|
||||||
|
.filter(x -> TYPE_A.equals(x.getPhase()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Double channelDataA = channelTypeAList.get(0).getValue();
|
||||||
|
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
|
||||||
|
channelDataA = BigDecimal.valueOf(channelDataA / 100 * fData)
|
||||||
|
.setScale(scale, RoundingMode.HALF_UP)
|
||||||
|
.doubleValue();
|
||||||
|
}
|
||||||
|
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, pqErrSysDtls, fData, channelDataA, dataRule, scale);
|
||||||
|
result.setAValue(JSON.toJSONString(a));
|
||||||
|
|
||||||
|
List<PqScriptCheckData> channelTypeBList = checkData.stream()
|
||||||
|
.filter(x -> TYPE_B.equals(x.getPhase()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Double channelDataB = channelTypeBList.get(0).getValue();
|
||||||
|
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
|
||||||
|
channelDataB = BigDecimal.valueOf(channelDataB / 100 * fData)
|
||||||
|
.setScale(scale, RoundingMode.HALF_UP)
|
||||||
|
.doubleValue();
|
||||||
|
}
|
||||||
|
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelDataB, dataRule, scale);
|
||||||
|
result.setBValue(JSON.toJSONString(b));
|
||||||
|
|
||||||
|
List<PqScriptCheckData> channelTypeCList = checkData.stream()
|
||||||
|
.filter(x -> TYPE_C.equals(x.getPhase()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Double channelDataC = channelTypeCList.get(0).getValue();
|
||||||
|
if (DetectionCodeEnum.SeqV.getCode().equals(splitArr[1]) || DetectionCodeEnum.SeqA.getCode().equals(splitArr[1])) {
|
||||||
|
channelDataC = BigDecimal.valueOf(channelDataC / 100 * fData)
|
||||||
|
.setScale(scale, RoundingMode.HALF_UP)
|
||||||
|
.doubleValue();
|
||||||
|
}
|
||||||
|
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, pqErrSysDtls, fData, channelDataC, dataRule, scale);
|
||||||
|
result.setCValue(JSON.toJSONString(c));
|
||||||
|
|
||||||
|
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
|
||||||
|
} else {
|
||||||
|
// 三项不平衡
|
||||||
|
List<PqScriptCheckData> channelTypeBList = checkData.stream()
|
||||||
|
.filter(x -> TYPE_T.equals(x.getPhase()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
|
||||||
|
result.setTValue(JSON.toJSONString(t));
|
||||||
|
result.setResultFlag(setResultFlag(Arrays.asList(t)));
|
||||||
|
}
|
||||||
|
info.add(result);
|
||||||
}
|
}
|
||||||
result.setDataType(sourceIssue.getDataType());
|
|
||||||
if (StrUtil.isBlank(type)) {
|
|
||||||
//取出源所对应的相别信息
|
|
||||||
List<PqScriptCheckData> channelTypeAList = checkData.stream()
|
|
||||||
.filter(x -> TYPE_A.equals(x.getPhase()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
DetectionData a = rangeComparisonList(map.get(TYPE_A), isQualified, pqErrSysDtls, fData, channelTypeAList.get(0).getValue(), dataRule, scale);
|
|
||||||
result.setAValue(JSON.toJSONString(a));
|
|
||||||
|
|
||||||
List<PqScriptCheckData> channelTypeBList = checkData.stream()
|
|
||||||
.filter(x -> TYPE_B.equals(x.getPhase()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
DetectionData b = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
|
|
||||||
result.setBValue(JSON.toJSONString(b));
|
|
||||||
|
|
||||||
List<PqScriptCheckData> channelTypeCList = checkData.stream()
|
|
||||||
.filter(x -> TYPE_C.equals(x.getPhase()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
DetectionData c = rangeComparisonList(map.get(TYPE_C), isQualified, pqErrSysDtls, fData, channelTypeCList.get(0).getValue(), dataRule, scale);
|
|
||||||
result.setCValue(JSON.toJSONString(c));
|
|
||||||
|
|
||||||
result.setResultFlag(setResultFlag(Arrays.asList(a, b, c)));
|
|
||||||
} else {
|
|
||||||
List<PqScriptCheckData> channelTypeBList = checkData.stream()
|
|
||||||
.filter(x -> TYPE_T.equals(x.getPhase()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
DetectionData t = rangeComparisonList(map.get(TYPE_B), isQualified, pqErrSysDtls, fData, channelTypeBList.get(0).getValue(), dataRule, scale);
|
|
||||||
result.setTValue(JSON.toJSONString(t));
|
|
||||||
result.setResultFlag(setResultFlag(Arrays.asList(t)));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
return null;
|
if (CollUtil.isNotEmpty(info)) {
|
||||||
|
detectionDataDealService.acceptNonHarmonicResult(info, code);
|
||||||
|
List<Integer> resultFlag = info.stream().map(SimAndDigNonHarmonicResult::getResultFlag).distinct().collect(Collectors.toList());
|
||||||
|
return StorageUtil.getInteger(resultFlag);
|
||||||
|
}
|
||||||
|
return 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.njcn.gather.detection.service.impl;
|
|||||||
|
|
||||||
import cn.hutool.core.collection.CollUtil;
|
import cn.hutool.core.collection.CollUtil;
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.njcn.common.pojo.exception.BusinessException;
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
@@ -41,6 +42,7 @@ import com.njcn.gather.script.service.IPqScriptDtlsService;
|
|||||||
import com.njcn.gather.source.pojo.po.SourceInitialize;
|
import com.njcn.gather.source.pojo.po.SourceInitialize;
|
||||||
import com.njcn.gather.source.service.IPqSourceService;
|
import com.njcn.gather.source.service.IPqSourceService;
|
||||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
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.enums.DictDataEnum;
|
||||||
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
||||||
import com.njcn.web.utils.HttpServletUtil;
|
import com.njcn.web.utils.HttpServletUtil;
|
||||||
@@ -53,6 +55,7 @@ import org.springframework.stereotype.Service;
|
|||||||
|
|
||||||
import javax.servlet.ServletOutputStream;
|
import javax.servlet.ServletOutputStream;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -81,8 +84,9 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
private final ISysTestConfigService sysTestConfigService;
|
private final ISysTestConfigService sysTestConfigService;
|
||||||
|
|
||||||
|
|
||||||
@Value("${report.reportDir}")
|
// @Value("${report.reportDir}")
|
||||||
private String alignDataFilePath;
|
// private String alignDataFilePath;
|
||||||
|
private final PathConfig pathConfig;
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -135,6 +139,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
);
|
);
|
||||||
if (ObjectUtil.isNotNull(planSource)) {
|
if (ObjectUtil.isNotNull(planSource)) {
|
||||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
||||||
|
param.setSourceName(sourceParam.getSourceId());
|
||||||
if (ObjectUtil.isNotNull(sourceParam)) {
|
if (ObjectUtil.isNotNull(sourceParam)) {
|
||||||
//开始组装socket报文请求头
|
//开始组装socket报文请求头
|
||||||
socketDevResponseService.initList(param);
|
socketDevResponseService.initList(param);
|
||||||
@@ -181,6 +186,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
if (ObjectUtil.isNotNull(planSource)) {
|
if (ObjectUtil.isNotNull(planSource)) {
|
||||||
//获取源初始化参数
|
//获取源初始化参数
|
||||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(planSource.getSourceId());
|
||||||
|
param.setSourceName(sourceParam.getSourceId());
|
||||||
if (ObjectUtil.isNotNull(sourceParam)) {
|
if (ObjectUtil.isNotNull(sourceParam)) {
|
||||||
//开始组装socket报文请求头
|
//开始组装socket报文请求头
|
||||||
socketDevResponseService.initList(param);
|
socketDevResponseService.initList(param);
|
||||||
@@ -218,6 +224,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
private void sendYtxSocketSimulate(PreDetectionParam param) {
|
private void sendYtxSocketSimulate(PreDetectionParam param) {
|
||||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||||
param.setSourceId(sourceParam.getSourceId());
|
param.setSourceId(sourceParam.getSourceId());
|
||||||
|
param.setSourceName(sourceParam.getSourceId());
|
||||||
String loginName = RequestUtil.getLoginNameByToken();
|
String loginName = RequestUtil.getLoginNameByToken();
|
||||||
WebServiceManager.addPreDetectionParam(loginName, param);
|
WebServiceManager.addPreDetectionParam(loginName, param);
|
||||||
if (ObjectUtil.isNotNull(sourceParam)) {
|
if (ObjectUtil.isNotNull(sourceParam)) {
|
||||||
@@ -243,6 +250,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
FormalTestManager.stopFlag = false;
|
FormalTestManager.stopFlag = false;
|
||||||
socketDevResponseService.initRestart();
|
socketDevResponseService.initRestart();
|
||||||
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
|
List<SourceIssue> sourceIssueList = SocketManager.getSourceList();
|
||||||
|
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||||
|
param.setSourceName(sourceInitialize.getSourceId());
|
||||||
if (CollUtil.isNotEmpty(sourceIssueList)) {
|
if (CollUtil.isNotEmpty(sourceIssueList)) {
|
||||||
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
|
SourceIssue sourceIssues = SocketManager.getSourceList().get(0);
|
||||||
SocketMsg<String> xuMsg = new SocketMsg<>();
|
SocketMsg<String> xuMsg = new SocketMsg<>();
|
||||||
@@ -258,7 +267,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
checkDataParam.setIsValueTypeName(false);
|
checkDataParam.setIsValueTypeName(false);
|
||||||
List<String> adType = iPqScriptCheckDataService.getValueType(checkDataParam);
|
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);
|
CnSocketUtil.quitSend(param);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +298,8 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
}
|
}
|
||||||
//组装源控制脚本
|
//组装源控制脚本
|
||||||
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
PqScriptIssueParam issueParam = new PqScriptIssueParam();
|
||||||
issueParam.setSourceId(param.getSourceId());
|
SourceInitialize sourceInitialize = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||||
|
issueParam.setSourceId(sourceInitialize.getSourceId());
|
||||||
issueParam.setScriptId(param.getScriptId());
|
issueParam.setScriptId(param.getScriptId());
|
||||||
issueParam.setType(1);
|
issueParam.setType(1);
|
||||||
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.SIMULATE_TEST.getValue());
|
issueParam.setIsPhaseSequence(SourceOperateCodeEnum.SIMULATE_TEST.getValue());
|
||||||
@@ -301,9 +311,9 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
|
|
||||||
SourceIssue sourceIssue = sourceIssues.get(0);
|
SourceIssue sourceIssue = sourceIssues.get(0);
|
||||||
String type = sourceIssue.getType();
|
String type = sourceIssue.getType();
|
||||||
if (sourceIssue.getIsP()) {
|
if (StrUtil.isNotBlank(sourceIssue.getOtherType())) {
|
||||||
sourceIssue.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
sourceIssue.setType(ResultUnitEnum.V_ABSOLUTELY.getCode());
|
||||||
type = ResultUnitEnum.P.getCode();
|
type = sourceIssue.getOtherType();
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> comm = sourceIssue.getDevValueTypeList();
|
List<String> comm = sourceIssue.getDevValueTypeList();
|
||||||
@@ -325,6 +335,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
SourceInitialize sourceParam = pqSourceService.getSourceInitializeParam(param.getSourceId());
|
||||||
PreDetectionParam preDetectionParam = new PreDetectionParam();
|
PreDetectionParam preDetectionParam = new PreDetectionParam();
|
||||||
preDetectionParam.setSourceId(sourceParam.getSourceId());
|
preDetectionParam.setSourceId(sourceParam.getSourceId());
|
||||||
|
preDetectionParam.setSourceName(sourceParam.getSourceId());
|
||||||
preDetectionParam.setUserPageId(param.getUserPageId());
|
preDetectionParam.setUserPageId(param.getUserPageId());
|
||||||
CnSocketUtil.quitSendSource(preDetectionParam);
|
CnSocketUtil.quitSendSource(preDetectionParam);
|
||||||
WebServiceManager.removePreDetectionParam();
|
WebServiceManager.removePreDetectionParam();
|
||||||
@@ -348,7 +359,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
|
|||||||
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
|
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
|
||||||
response.setContentType("application/octet-stream;charset=UTF-8");
|
response.setContentType("application/octet-stream;charset=UTF-8");
|
||||||
try {
|
try {
|
||||||
InputStream inputStream = new FileInputStream(alignDataFilePath + "\\" + fileName);
|
InputStream inputStream = new FileInputStream(pathConfig.getDataPath() + File.separator + fileName);
|
||||||
byte[] buffer = new byte[1024];
|
byte[] buffer = new byte[1024];
|
||||||
int len = 0;
|
int len = 0;
|
||||||
ServletOutputStream outputStream = response.getOutputStream();
|
ServletOutputStream outputStream = response.getOutputStream();
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.njcn.gather.detection.sntp;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SntpExchange {
|
||||||
|
|
||||||
|
private InetSocketAddress clientAddress;
|
||||||
|
|
||||||
|
private int version;
|
||||||
|
|
||||||
|
private Instant deviceInstant;
|
||||||
|
|
||||||
|
private byte[] clientTransmitTimestamp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package com.njcn.gather.detection.sntp;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class SntpPacketService {
|
||||||
|
|
||||||
|
private static final int MIN_PACKET_LENGTH = 48;
|
||||||
|
private static final int CLIENT_MODE = 3;
|
||||||
|
private static final int SERVER_MODE = 4;
|
||||||
|
// NTP纪元偏移量:2208988800秒(1900年到1970年的秒数差)
|
||||||
|
private static final long NTP_EPOCH_OFFSET = 2208988800L;
|
||||||
|
private static final ZoneId SHANGHAI_ZONE = ZoneId.of("Asia/Shanghai");
|
||||||
|
private static final byte[] REFERENCE_ID = "LOCL".getBytes(StandardCharsets.US_ASCII);
|
||||||
|
|
||||||
|
public SntpExchange parseRequest(byte[] request, InetSocketAddress clientAddress) {
|
||||||
|
if (request == null || request.length < MIN_PACKET_LENGTH) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int mode = request[0] & 0x07;
|
||||||
|
if (mode != CLIENT_MODE) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int version = (request[0] >> 3) & 0x07;
|
||||||
|
byte[] clientTransmitTimestamp = Arrays.copyOfRange(request, 40, 48);
|
||||||
|
Instant deviceInstant = fromNtpTimestamp(clientTransmitTimestamp);
|
||||||
|
return new SntpExchange(clientAddress, version == 0 ? 3 : version, deviceInstant, clientTransmitTimestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] buildResponse(SntpExchange exchange, Instant receiveInstant, Instant transmitInstant) {
|
||||||
|
byte[] response = new byte[MIN_PACKET_LENGTH];
|
||||||
|
int version = exchange.getVersion() == 0 ? 3 : exchange.getVersion();
|
||||||
|
response[0] = (byte) ((version << 3) | SERVER_MODE);
|
||||||
|
response[1] = 0x01;
|
||||||
|
response[2] = 0x04;
|
||||||
|
response[3] = (byte) 0xEC;
|
||||||
|
System.arraycopy(REFERENCE_ID, 0, response, 12, REFERENCE_ID.length);
|
||||||
|
|
||||||
|
byte[] receiveTimestamp = toNtpTimestamp(receiveInstant);
|
||||||
|
byte[] transmitTimestamp = toNtpTimestamp(transmitInstant);
|
||||||
|
|
||||||
|
System.arraycopy(receiveTimestamp, 0, response, 16, receiveTimestamp.length);
|
||||||
|
System.arraycopy(exchange.getClientTransmitTimestamp(), 0, response, 24, exchange.getClientTransmitTimestamp().length);
|
||||||
|
System.arraycopy(receiveTimestamp, 0, response, 32, receiveTimestamp.length);
|
||||||
|
System.arraycopy(transmitTimestamp, 0, response, 40, transmitTimestamp.length);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SntpPushMessage toPushMessage(String deviceIp, Instant computerInstant, Instant deviceInstant) {
|
||||||
|
long computerTimestampMs = computerInstant.toEpochMilli();
|
||||||
|
long deviceTimestampMs = deviceInstant.toEpochMilli();
|
||||||
|
return new SntpPushMessage(
|
||||||
|
"sntp_time_update",
|
||||||
|
deviceIp,
|
||||||
|
formatShanghaiTime(computerInstant),
|
||||||
|
formatShanghaiTime(deviceInstant),
|
||||||
|
computerTimestampMs,
|
||||||
|
deviceTimestampMs,
|
||||||
|
computerTimestampMs - deviceTimestampMs
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toNtpTimestamp(Instant instant) {
|
||||||
|
long ntpSeconds = instant.getEpochSecond() + NTP_EPOCH_OFFSET;
|
||||||
|
long fraction = ((long) instant.getNano() << 32) / 1_000_000_000L;
|
||||||
|
byte[] bytes = new byte[8];
|
||||||
|
writeUnsignedInt(bytes, 0, ntpSeconds);
|
||||||
|
writeUnsignedInt(bytes, 4, fraction);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Instant fromNtpTimestamp(byte[] bytes) {
|
||||||
|
long seconds = readUnsignedInt(bytes, 0);
|
||||||
|
long fraction = readUnsignedInt(bytes, 4);
|
||||||
|
long epochSeconds = seconds - NTP_EPOCH_OFFSET;
|
||||||
|
long nanos = ((fraction * 1_000_000_000L) + 0x80000000L) >>> 32;
|
||||||
|
if (nanos >= 1_000_000_000L) {
|
||||||
|
epochSeconds += 1;
|
||||||
|
nanos -= 1_000_000_000L;
|
||||||
|
}
|
||||||
|
return Instant.ofEpochSecond(epochSeconds, nanos);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String formatShanghaiTime(Instant instant) {
|
||||||
|
return LocalDateTime.ofInstant(instant, SHANGHAI_ZONE).toString().replace('T', ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long readUnsignedInt(byte[] bytes, int offset) {
|
||||||
|
return ((long) bytes[offset] & 0xFF) << 24
|
||||||
|
| ((long) bytes[offset + 1] & 0xFF) << 16
|
||||||
|
| ((long) bytes[offset + 2] & 0xFF) << 8
|
||||||
|
| ((long) bytes[offset + 3] & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void writeUnsignedInt(byte[] target, int offset, long value) {
|
||||||
|
target[offset] = (byte) ((value >>> 24) & 0xFF);
|
||||||
|
target[offset + 1] = (byte) ((value >>> 16) & 0xFF);
|
||||||
|
target[offset + 2] = (byte) ((value >>> 8) & 0xFF);
|
||||||
|
target[offset + 3] = (byte) (value & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.njcn.gather.detection.sntp;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SntpPushMessage {
|
||||||
|
|
||||||
|
private String type = "sntp_time_update";
|
||||||
|
|
||||||
|
private String deviceIp;
|
||||||
|
|
||||||
|
private String computerTime;
|
||||||
|
|
||||||
|
private String deviceTime;
|
||||||
|
|
||||||
|
private Long computerTimestampMs;
|
||||||
|
|
||||||
|
private Long deviceTimestampMs;
|
||||||
|
|
||||||
|
private Long errorMs;
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package com.njcn.gather.detection.sntp;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.detection.util.socket.websocket.WebServiceManager;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.PreDestroy;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.DatagramSocket;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SntpServerManager {
|
||||||
|
|
||||||
|
private final SntpServerProperties sntpServerProperties;
|
||||||
|
private final SntpPacketService sntpPacketService;
|
||||||
|
|
||||||
|
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||||
|
private final Object lifecycleMonitor = new Object();
|
||||||
|
|
||||||
|
private volatile DatagramSocket datagramSocket;
|
||||||
|
private volatile ExecutorService executorService;
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
// 使用同步锁和原子变量防止重复启动
|
||||||
|
synchronized (lifecycleMonitor) {
|
||||||
|
if (running.get()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int port = resolvePort();
|
||||||
|
DatagramSocket socket = createSocket(port);
|
||||||
|
ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> {
|
||||||
|
Thread thread = new Thread(runnable, "sntp-server");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
});
|
||||||
|
|
||||||
|
datagramSocket = socket;
|
||||||
|
executorService = executor;
|
||||||
|
running.set(true);
|
||||||
|
executor.submit(this::receiveLoop);
|
||||||
|
log.info("SNTP服务已启动,监听端口: {}", port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
synchronized (lifecycleMonitor) {
|
||||||
|
if (!running.get()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
running.set(false);
|
||||||
|
closeSocketQuietly(datagramSocket);
|
||||||
|
datagramSocket = null;
|
||||||
|
if (executorService != null) {
|
||||||
|
executorService.shutdownNow();
|
||||||
|
executorService = null;
|
||||||
|
}
|
||||||
|
log.info("SNTP服务已停止");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isRunning() {
|
||||||
|
return running.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void destroy() {
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void receiveLoop() {
|
||||||
|
byte[] buffer = new byte[512];
|
||||||
|
while (running.get()) {
|
||||||
|
DatagramSocket socket = datagramSocket;
|
||||||
|
if (socket == null || socket.isClosed()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
||||||
|
try {
|
||||||
|
socket.receive(packet);
|
||||||
|
handlePacket(socket, packet);
|
||||||
|
log.info("SNTP服务接收报文: {}", Arrays.toString(packet.getData()));
|
||||||
|
} catch (SocketException e) {
|
||||||
|
if (running.get()) {
|
||||||
|
log.error("SNTP服务接收报文失败", e);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("SNTP服务处理报文失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (lifecycleMonitor) {
|
||||||
|
if (running.get()) {
|
||||||
|
running.set(false);
|
||||||
|
closeSocketQuietly(datagramSocket);
|
||||||
|
datagramSocket = null;
|
||||||
|
if (executorService != null) {
|
||||||
|
executorService.shutdownNow();
|
||||||
|
executorService = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handlePacket(DatagramSocket socket, DatagramPacket packet) throws IOException {
|
||||||
|
Instant receiveInstant = Instant.now(); //T2:服务器接收请求时间
|
||||||
|
byte[] request = Arrays.copyOf(packet.getData(), packet.getLength());
|
||||||
|
InetSocketAddress clientAddress = new InetSocketAddress(packet.getAddress(), packet.getPort());
|
||||||
|
SntpExchange exchange = sntpPacketService.parseRequest(request, clientAddress);
|
||||||
|
if (exchange == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Instant transmitInstant = Instant.now(); //T3:服务器发送响应时间
|
||||||
|
byte[] response = sntpPacketService.buildResponse(exchange, receiveInstant, transmitInstant);
|
||||||
|
DatagramPacket responsePacket = new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
|
||||||
|
socket.send(responsePacket);
|
||||||
|
|
||||||
|
String deviceIp = clientAddress.getAddress().getHostAddress();
|
||||||
|
// SntpPushMessage pushMessage = sntpPacketService.toPushMessage(deviceIp, transmitInstant, exchange.getDeviceInstant());
|
||||||
|
SntpPushMessage pushMessage = sntpPacketService.toPushMessage(deviceIp, receiveInstant, exchange.getDeviceInstant());
|
||||||
|
WebServiceManager.broadcast(JSON.toJSONString(pushMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
private DatagramSocket createSocket(int port) {
|
||||||
|
try {
|
||||||
|
DatagramSocket socket = new DatagramSocket(port);
|
||||||
|
socket.setReuseAddress(true);
|
||||||
|
return socket;
|
||||||
|
} catch (SocketException e) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "SNTP服务启动失败,端口绑定异常");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int resolvePort() {
|
||||||
|
Integer port = sntpServerProperties.getPort();
|
||||||
|
if (port == null || port < 1 || port > 65535) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "SNTP服务启动失败,端口配置无效");
|
||||||
|
}
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭UDP Socket
|
||||||
|
*
|
||||||
|
* @param socket
|
||||||
|
*/
|
||||||
|
private void closeSocketQuietly(DatagramSocket socket) {
|
||||||
|
if (socket != null && !socket.isClosed()) {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.njcn.gather.detection.sntp;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "sntp")
|
||||||
|
public class SntpServerProperties {
|
||||||
|
|
||||||
|
private Integer port = 123;
|
||||||
|
}
|
||||||
@@ -47,9 +47,13 @@ public class CnSocketUtil {
|
|||||||
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE_SOURCE.getValue());
|
socketMsg.setRequestId(SourceOperateCodeEnum.QUITE_SOURCE.getValue());
|
||||||
socketMsg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue());
|
socketMsg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue());
|
||||||
JSONObject jsonObject = new JSONObject();
|
JSONObject jsonObject = new JSONObject();
|
||||||
jsonObject.put("sourceId", param.getSourceId());
|
jsonObject.put("sourceId", param.getSourceName());
|
||||||
socketMsg.setData(jsonObject.toJSONString());
|
socketMsg.setData(jsonObject.toJSONString());
|
||||||
SocketManager.sendMsg(param.getUserPageId() + SOURCE_TAG, JSON.toJSONString(socketMsg));
|
String sourceKey = param.getUserPageId() + SOURCE_TAG;
|
||||||
|
if (SocketManager.isChannelActive(sourceKey)) {
|
||||||
|
SocketManager.markActiveClose(sourceKey);
|
||||||
|
}
|
||||||
|
SocketManager.sendMsg(sourceKey, JSON.toJSONString(socketMsg));
|
||||||
WebServiceManager.removePreDetectionParam(param.getUserPageId());
|
WebServiceManager.removePreDetectionParam(param.getUserPageId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
|
|||||||
import com.njcn.gather.script.pojo.po.SourceIssue;
|
import com.njcn.gather.script.pojo.po.SourceIssue;
|
||||||
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
|
import com.njcn.gather.system.dictionary.pojo.enums.DictDataEnum;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -208,4 +209,20 @@ public class FormalTestManager {
|
|||||||
* 是否进行相序校验
|
* 是否进行相序校验
|
||||||
*/
|
*/
|
||||||
public static boolean isXu;
|
public static boolean isXu;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过载信息,如果检测到电压过载,overload=1;如果检测到电流过载,overload=2;如果检测到电压&&电流过载,overload=3;反之,overload=4
|
||||||
|
*/
|
||||||
|
public static int overload;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测开始时间
|
||||||
|
*/
|
||||||
|
public static LocalDateTime checkStartTime;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数模式 检测类型"1"-"全部检测" , "2"-"不合格项复检"
|
||||||
|
*/
|
||||||
|
public static String reCheckType;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ public class SocketManager {
|
|||||||
*/
|
*/
|
||||||
private static final Map<String, NioEventLoopGroup> socketGroup = new ConcurrentHashMap<>();
|
private static final Map<String, NioEventLoopGroup> socketGroup = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主动关闭中的连接。用于区分业务主动 close 和对端异常断线。
|
||||||
|
*/
|
||||||
|
private static final Map<String, Boolean> activeClosingUsers = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public static void addUser(String userId, Channel channel) {
|
public static void addUser(String userId, Channel channel) {
|
||||||
socketSessions.put(userId, channel);
|
socketSessions.put(userId, channel);
|
||||||
}
|
}
|
||||||
@@ -65,20 +70,31 @@ public class SocketManager {
|
|||||||
|
|
||||||
public static void removeUser(String userId) {
|
public static void removeUser(String userId) {
|
||||||
Channel channel = socketSessions.get(userId);
|
Channel channel = socketSessions.get(userId);
|
||||||
|
removeMapping(userId, false);
|
||||||
if (ObjectUtil.isNotNull(channel)) {
|
if (ObjectUtil.isNotNull(channel)) {
|
||||||
try {
|
try {
|
||||||
|
markActiveClose(userId);
|
||||||
channel.close().sync();
|
channel.close().sync();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
NioEventLoopGroup eventExecutors = socketGroup.get(userId);
|
System.out.println(userId + "__" + channel.id() + "关闭了客户端");
|
||||||
if (ObjectUtil.isNotNull(eventExecutors)) {
|
|
||||||
eventExecutors.shutdownGracefully();
|
|
||||||
System.out.println(userId + "__" + channel.id() + "关闭了客户端");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void removeMapping(String userId) {
|
||||||
|
removeMapping(userId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void removeMapping(String userId, boolean clearActiveClose) {
|
||||||
socketSessions.remove(userId);
|
socketSessions.remove(userId);
|
||||||
socketGroup.remove(userId);
|
NioEventLoopGroup eventExecutors = socketGroup.remove(userId);
|
||||||
|
if (clearActiveClose) {
|
||||||
|
consumeActiveClose(userId);
|
||||||
|
}
|
||||||
|
if (ObjectUtil.isNotNull(eventExecutors)) {
|
||||||
|
eventExecutors.shutdownGracefully();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Channel getChannelByUserId(String userId) {
|
public static Channel getChannelByUserId(String userId) {
|
||||||
@@ -89,6 +105,20 @@ public class SocketManager {
|
|||||||
return socketGroup.get(userId);
|
return socketGroup.get(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void markActiveClose(String userId) {
|
||||||
|
if (StrUtil.isNotBlank(userId)) {
|
||||||
|
activeClosingUsers.put(userId, Boolean.TRUE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean consumeActiveClose(String userId) {
|
||||||
|
return StrUtil.isNotBlank(userId) && activeClosingUsers.remove(userId) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isActiveClosing(String userId) {
|
||||||
|
return StrUtil.isNotBlank(userId) && activeClosingUsers.containsKey(userId);
|
||||||
|
}
|
||||||
|
|
||||||
public static void sendMsg(String userId, String msg) {
|
public static void sendMsg(String userId, String msg) {
|
||||||
Channel channel = socketSessions.get(userId);
|
Channel channel = socketSessions.get(userId);
|
||||||
if (ObjectUtil.isNotNull(channel)) {
|
if (ObjectUtil.isNotNull(channel)) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSON;
|
|||||||
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
||||||
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
||||||
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
import com.njcn.gather.detection.pojo.param.ContrastDetectionParam;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
@@ -349,7 +350,7 @@ public class NettyClient {
|
|||||||
NioEventLoopGroup group, String msg) {
|
NioEventLoopGroup group, String msg) {
|
||||||
channelFuture.addListener((ChannelFutureListener) ch -> {
|
channelFuture.addListener((ChannelFutureListener) ch -> {
|
||||||
if (!ch.isSuccess()) {
|
if (!ch.isSuccess()) {
|
||||||
onConnectionFailure(handler, group);
|
onConnectionFailure(param, handler, group);
|
||||||
} else {
|
} else {
|
||||||
onConnectionSuccess(channelFuture, param, handler, group, msg);
|
onConnectionSuccess(channelFuture, param, handler, group, msg);
|
||||||
}
|
}
|
||||||
@@ -358,15 +359,24 @@ public class NettyClient {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 连接失败处理
|
* 连接失败处理
|
||||||
* 输出失败信息并优雅关闭事件循环组
|
* 输出失败信息、优雅关闭事件循环组、通知前端、释放检测锁
|
||||||
*
|
*
|
||||||
|
* @param param 检测参数,用于定位锁与前端通知
|
||||||
* @param handler 业务处理器,用于区分设备类型
|
* @param handler 业务处理器,用于区分设备类型
|
||||||
* @param group 事件循环组
|
* @param group 事件循环组
|
||||||
*/
|
*/
|
||||||
private static void onConnectionFailure(SimpleChannelInboundHandler<String> handler, NioEventLoopGroup group) {
|
private static void onConnectionFailure(PreDetectionParam param,
|
||||||
|
SimpleChannelInboundHandler<String> handler, NioEventLoopGroup group) {
|
||||||
String deviceType = getDeviceType(handler);
|
String deviceType = getDeviceType(handler);
|
||||||
log.info("连接{}服务端失败...", deviceType);
|
log.info("连接{}服务端失败...", deviceType);
|
||||||
group.shutdownGracefully();
|
group.shutdownGracefully();
|
||||||
|
// 异步建连失败时前端原本静默,补一次通知避免用户黑屏等待
|
||||||
|
notifyFrontendError(param, handler);
|
||||||
|
// 释放检测锁:抢锁后由 controller 异步发起的建连若失败,无法走 controller 兜底
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "ASYNC_CONNECT_FAILED");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -455,6 +465,12 @@ public class NettyClient {
|
|||||||
|
|
||||||
// 通过WebSocket通知前端页面
|
// 通过WebSocket通知前端页面
|
||||||
notifyFrontendError(param, handler);
|
notifyFrontendError(param, handler);
|
||||||
|
|
||||||
|
// 释放检测锁,理由同 onConnectionFailure
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "ASYNC_CONNECT_EXCEPTION");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.njcn.gather.detection.util.socket.cilent;
|
|||||||
|
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
import com.njcn.gather.detection.handler.SocketContrastResponseService;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
@@ -68,6 +69,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
|||||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_01, false);
|
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_01, false);
|
||||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
||||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
||||||
|
// 业务消息处理异常 → 释放检测锁
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_READ_EXCEPTION");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +82,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
|||||||
System.out.println("与通信模块端断线");
|
System.out.println("与通信模块端断线");
|
||||||
ctx.close();
|
ctx.close();
|
||||||
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG);
|
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.CONTRAST_DEV_TAG);
|
||||||
|
// 比对通信模块主动断开 → 本次检测视为结束,释放检测锁
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_CHANNEL_INACTIVE");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -150,11 +161,18 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
|||||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_02, false);
|
||||||
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
CnSocketUtil.contrastSendquit(param.getUserPageId(), SourceOperateCodeEnum.QUIT_INIT_03, true);
|
||||||
ctx.close();
|
ctx.close();
|
||||||
|
// 比对通道异常 → 释放检测锁
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_EXCEPTION");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 接收数据超时处理
|
* 接收数据超时处理
|
||||||
|
* 比对模式读超时(10 分钟 Pst / 1 分钟实时 / 动态统计)都汇到这里,
|
||||||
|
* 推前端的同时一并释放检测锁(避免锁卡到 4 小时绝对超时)。
|
||||||
*/
|
*/
|
||||||
private void timeoutSend(SourceOperateCodeEnum sourceOperateCodeEnum) {
|
private void timeoutSend(SourceOperateCodeEnum sourceOperateCodeEnum) {
|
||||||
System.out.println("超时处理-----》" + "统计数据已超时----------------关闭");
|
System.out.println("超时处理-----》" + "统计数据已超时----------------关闭");
|
||||||
@@ -164,6 +182,11 @@ public class NettyContrastClientHandler extends SimpleChannelInboundHandler<Stri
|
|||||||
webSend.setData(sourceOperateCodeEnum.getMsg() + SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getMessage());
|
webSend.setData(sourceOperateCodeEnum.getMsg() + SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getMessage());
|
||||||
webSend.setCode(SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getCode());
|
webSend.setCode(SourceResponseCodeEnum.RECEIVE_DATA_TIME_OUT.getCode());
|
||||||
WebServiceManager.sendMsg(param.getUserPageId(), MsgUtil.msgToWebData(webSend, FormalTestManager.devNameMapComm, 0));
|
WebServiceManager.sendMsg(param.getUserPageId(), MsgUtil.msgToWebData(webSend, FormalTestManager.devNameMapComm, 0));
|
||||||
|
// 比对模式读超时终态 → 释放检测锁
|
||||||
|
if (param != null && param.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "CONTRAST_IDLE_TIMEOUT");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.njcn.gather.detection.util.socket.cilent;
|
|||||||
import cn.hutool.core.collection.CollUtil;
|
import cn.hutool.core.collection.CollUtil;
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
import com.njcn.gather.detection.handler.SocketDevResponseService;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLock;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.enums.ResultEnum;
|
import com.njcn.gather.detection.pojo.enums.ResultEnum;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
@@ -65,7 +67,7 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
/**
|
/**
|
||||||
* 实时数据检测超时时间:1分钟(60秒)
|
* 实时数据检测超时时间:1分钟(60秒)
|
||||||
*/
|
*/
|
||||||
private static final long REALTIME_TIMEOUT = 60L;
|
private static final long REALTIME_TIMEOUT = 60 * 3L;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 暂停操作超时时间:10分钟(600秒)
|
* 暂停操作超时时间:10分钟(600秒)
|
||||||
@@ -113,8 +115,15 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
||||||
log.warn("设备通讯客户端断线");
|
log.warn("设备通讯客户端断线");
|
||||||
ctx.close();
|
ctx.close();
|
||||||
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.DEV_TAG);
|
String key = param.getUserPageId() + CnSocketUtil.DEV_TAG;
|
||||||
|
if (SocketManager.consumeActiveClose(key)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SocketManager.removeUser(key);
|
||||||
CnSocketUtil.quitSendSource(param);
|
CnSocketUtil.quitSendSource(param);
|
||||||
|
// 设备主动断开 → 本次检测视为结束,释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_CHANNEL_INACTIVE");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -132,6 +141,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理服务端消息异常", e);
|
log.error("处理服务端消息异常", e);
|
||||||
CnSocketUtil.quitSend(param);
|
CnSocketUtil.quitSend(param);
|
||||||
|
// 业务消息处理异常 → 退出并释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_READ_EXCEPTION");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,6 +199,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
CnSocketUtil.quitSendSource(param);
|
CnSocketUtil.quitSendSource(param);
|
||||||
socketResponseService.backCheckState(param);
|
socketResponseService.backCheckState(param);
|
||||||
ctx.close();
|
ctx.close();
|
||||||
|
// 通道异常 → 释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_EXCEPTION");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -231,6 +246,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
CnSocketUtil.quitSend(param);
|
CnSocketUtil.quitSend(param);
|
||||||
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.SOCKET_TIMEOUT);
|
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.SOCKET_TIMEOUT);
|
||||||
socketResponseService.backCheckState(param);
|
socketResponseService.backCheckState(param);
|
||||||
|
// 常规步骤读超时兜底 → 释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_READ_TIMEOUT");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,6 +262,14 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
if (FormalTestManager.stopTime > STOP_TIMEOUT) {
|
if (FormalTestManager.stopTime > STOP_TIMEOUT) {
|
||||||
CnSocketUtil.quitSend(param);
|
CnSocketUtil.quitSend(param);
|
||||||
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.FORMAL_REAL.getValue(), SourceOperateCodeEnum.STOP_TIMEOUT);
|
WebServiceManager.sendDetectionErrorMessage(param.getUserPageId(), SourceOperateCodeEnum.FORMAL_REAL.getValue(), SourceOperateCodeEnum.STOP_TIMEOUT);
|
||||||
|
// R4 释放:暂停 10 分钟超时视同放弃本次检测
|
||||||
|
DetectionLock cur = DetectionLockManager.getInstance().getCurrent();
|
||||||
|
if (cur != null) {
|
||||||
|
DetectionLockManager.getInstance().releaseIfHeldBy(cur.getUserId(), "PAUSE_TIMEOUT");
|
||||||
|
}
|
||||||
|
// 重置 FormalTestManager 状态,避免下次进入误判
|
||||||
|
FormalTestManager.stopTime = 0;
|
||||||
|
FormalTestManager.hasStopFlag = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,6 +328,9 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
|
|||||||
CnSocketUtil.quitSend(param);
|
CnSocketUtil.quitSend(param);
|
||||||
timeoutSend(sourceIssue);
|
timeoutSend(sourceIssue);
|
||||||
socketResponseService.backCheckState(param);
|
socketResponseService.backCheckState(param);
|
||||||
|
// 单项检测超时本质等于整轮中止(已 quitSend),释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(param.getUserPageId(), "DEV_ITEM_TIMEOUT");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.njcn.gather.detection.util.socket.cilent;
|
package com.njcn.gather.detection.util.socket.cilent;
|
||||||
|
|
||||||
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
import com.njcn.gather.detection.handler.SocketSourceResponseService;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||||
@@ -69,7 +70,15 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
|||||||
ctx.close();
|
ctx.close();
|
||||||
// 从Socket管理器中移除用户通道映射
|
// 从Socket管理器中移除用户通道映射
|
||||||
if (webUser != null && StrUtil.isNotBlank(userId)) {
|
if (webUser != null && StrUtil.isNotBlank(userId)) {
|
||||||
SocketManager.removeUser(userId + CnSocketUtil.SOURCE_TAG);
|
String key = userId + CnSocketUtil.SOURCE_TAG;
|
||||||
|
if (SocketManager.isActiveClosing(key)) {
|
||||||
|
SocketManager.removeMapping(key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SocketManager.removeUser(key);
|
||||||
|
// 源端主动断开 → 本次检测视为结束,释放检测锁
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(userId, "SOURCE_CHANNEL_INACTIVE");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +95,7 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
|||||||
}
|
}
|
||||||
|
|
||||||
String userId = webUser.getUserPageId();
|
String userId = webUser.getUserPageId();
|
||||||
log.debug("源设备接收服务端数据, userId: {}, message: {}", userId, msg);
|
log.info("source接收server端数据, userId: {}, message: {}", userId, msg);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 委托给专门的响应处理服务处理业务逻辑
|
// 委托给专门的响应处理服务处理业务逻辑
|
||||||
@@ -95,6 +104,11 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
|||||||
log.error("源设备消息处理异常, userId: {}, message: {}", userId, msg, e);
|
log.error("源设备消息处理异常, userId: {}, message: {}", userId, msg, e);
|
||||||
// 发生异常时退出发送,避免后续问题
|
// 发生异常时退出发送,避免后续问题
|
||||||
CnSocketUtil.quitSend(webUser);
|
CnSocketUtil.quitSend(webUser);
|
||||||
|
// 业务消息处理异常 → 释放检测锁
|
||||||
|
if (StrUtil.isNotBlank(userId)) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(userId, "SOURCE_READ_EXCEPTION");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,6 +125,11 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
|||||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||||
String userId = webUser != null ? webUser.getUserPageId() : "unknown";
|
String userId = webUser != null ? webUser.getUserPageId() : "unknown";
|
||||||
String channelId = ctx.channel().id().toString();
|
String channelId = ctx.channel().id().toString();
|
||||||
|
if (StrUtil.isNotBlank(userId) && SocketManager.isActiveClosing(userId + CnSocketUtil.SOURCE_TAG)) {
|
||||||
|
log.debug("ignore source exception during active close, channelId: {}, userId: {}", channelId, userId);
|
||||||
|
ctx.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 根据异常类型进行分类处理和日志记录
|
// 根据异常类型进行分类处理和日志记录
|
||||||
if (cause instanceof ConnectException) {
|
if (cause instanceof ConnectException) {
|
||||||
@@ -136,6 +155,13 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<String
|
|||||||
|
|
||||||
// 发生异常时关闭通道
|
// 发生异常时关闭通道
|
||||||
ctx.close();
|
ctx.close();
|
||||||
|
|
||||||
|
// 源通道异常 → 释放检测锁
|
||||||
|
String userIdForRelease = webUser != null ? webUser.getUserPageId() : null;
|
||||||
|
if (StrUtil.isNotBlank(userIdForRelease)) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(userIdForRelease, "SOURCE_EXCEPTION");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.njcn.gather.detection.util.socket.websocket;
|
package com.njcn.gather.detection.util.socket.websocket;
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
import com.njcn.gather.detection.pojo.vo.WebSocketVO;
|
import com.njcn.gather.detection.pojo.vo.WebSocketVO;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
@@ -86,6 +87,16 @@ public class WebServiceManager {
|
|||||||
return userSessions.remove(userId);
|
return userSessions.remove(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅当当前会话仍绑定到指定通道时才移除,避免旧连接误删新连接映射。
|
||||||
|
*/
|
||||||
|
public static boolean removeByUserId(String userId, Channel channel) {
|
||||||
|
if (userId == null || channel == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return userSessions.remove(userId, channel);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据channelId移除会话(兼容老版本)
|
* 根据channelId移除会话(兼容老版本)
|
||||||
* 时间复杂度:O(n),建议使用removeByUserId替代
|
* 时间复杂度:O(n),建议使用removeByUserId替代
|
||||||
@@ -142,6 +153,19 @@ public class WebServiceManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void broadcast(String msg) {
|
||||||
|
for (Map.Entry<String, Channel> entry : userSessions.entrySet()) {
|
||||||
|
String userId = entry.getKey();
|
||||||
|
Channel channel = entry.getValue();
|
||||||
|
if (Objects.nonNull(channel) && channel.isActive()) {
|
||||||
|
channel.writeAndFlush(new TextWebSocketFrame(msg));
|
||||||
|
} else {
|
||||||
|
log.error("WebSocket broadcast failed, disconnected user, time: {}, userId: {}", LocalDateTime.now(), userId);
|
||||||
|
WebSocketHandler.cleanupSocketResources(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 存储检测参数(基于用户ID)
|
* 存储检测参数(基于用户ID)
|
||||||
* 支持多用户并发检测,每个用户的检测参数独立存储
|
* 支持多用户并发检测,每个用户的检测参数独立存储
|
||||||
@@ -296,6 +320,8 @@ public class WebServiceManager {
|
|||||||
webSocketVO.setData(errorType.getMsg());
|
webSocketVO.setData(errorType.getMsg());
|
||||||
webSocketVO.setOperateCode(errorType.getValue());
|
webSocketVO.setOperateCode(errorType.getValue());
|
||||||
sendMessage(userId, webSocketVO);
|
sendMessage(userId, webSocketVO);
|
||||||
|
// 守门员:错误推送即视为本次检测终态,释放检测锁(幂等,与显式释放点叠加双保险)
|
||||||
|
releaseLockOnTerminal(userId, errorType);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -313,6 +339,25 @@ public class WebServiceManager {
|
|||||||
webSocketVO.setData(errorType.getMsg());
|
webSocketVO.setData(errorType.getMsg());
|
||||||
webSocketVO.setOperateCode(errorType.getValue());
|
webSocketVO.setOperateCode(errorType.getValue());
|
||||||
sendMessage(userId, webSocketVO);
|
sendMessage(userId, webSocketVO);
|
||||||
|
// 守门员:理由同上
|
||||||
|
releaseLockOnTerminal(userId, errorType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 守门员释放锁
|
||||||
|
* <p>覆盖业务回调里所有走 {@code sendDetectionErrorMessage} 的失败路径,
|
||||||
|
* 等价于在 detection/handler 全目录的错误终态点显式释放。与各 Netty handler
|
||||||
|
* 内的显式释放幂等叠加,形成双保险。</p>
|
||||||
|
*
|
||||||
|
* <p>注:业务"正常完成"路径不走此方法(数模式 formalDeal 已在 Phase 1 显式释放;
|
||||||
|
* 比对模式正常完成走 sendMsg 推 ERROR_FLOW_END,依赖 WS 断开后心跳超时兜底)。</p>
|
||||||
|
*/
|
||||||
|
private static void releaseLockOnTerminal(String userId, SourceOperateCodeEnum errorType) {
|
||||||
|
if (userId == null || userId.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(userId, "WS_ERROR_PUSH:" + errorType.name());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.njcn.gather.detection.util.socket.websocket;
|
package com.njcn.gather.detection.util.socket.websocket;
|
||||||
|
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
|
import com.njcn.gather.detection.lock.DetectionLockManager;
|
||||||
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
|
||||||
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
import com.njcn.gather.detection.util.socket.CnSocketUtil;
|
||||||
@@ -110,7 +111,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
|||||||
public void handlerRemoved(ChannelHandlerContext ctx) {
|
public void handlerRemoved(ChannelHandlerContext ctx) {
|
||||||
log.info("webSocket客户端退出,channelId: {}, userId: {}", ctx.channel().id(), this.userId);
|
log.info("webSocket客户端退出,channelId: {}, userId: {}", ctx.channel().id(), this.userId);
|
||||||
if (this.userId != null) {
|
if (this.userId != null) {
|
||||||
WebServiceManager.removeByUserId(this.userId);
|
WebServiceManager.removeByUserId(this.userId, ctx.channel());
|
||||||
} else {
|
} else {
|
||||||
// 备用方案:如果userId为空,使用传统方法
|
// 备用方案:如果userId为空,使用传统方法
|
||||||
WebServiceManager.removeChannel(ctx.channel().id().toString());
|
WebServiceManager.removeChannel(ctx.channel().id().toString());
|
||||||
@@ -167,7 +168,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
|||||||
log.error("客户端心跳检测空闲次数超过{}次,关闭连接,channelId: {}, userId: {}", MAX_HEARTBEAT_MISS_COUNT, ctx.channel().id(), this.userId);
|
log.error("客户端心跳检测空闲次数超过{}次,关闭连接,channelId: {}, userId: {}", MAX_HEARTBEAT_MISS_COUNT, ctx.channel().id(), this.userId);
|
||||||
ctx.channel().close();
|
ctx.channel().close();
|
||||||
if (this.userId != null) {
|
if (this.userId != null) {
|
||||||
WebServiceManager.removeByUserId(this.userId);
|
WebServiceManager.removeByUserId(this.userId, ctx.channel());
|
||||||
} else {
|
} else {
|
||||||
WebServiceManager.removeChannel(ctx.channel().id().toString());
|
WebServiceManager.removeChannel(ctx.channel().id().toString());
|
||||||
}
|
}
|
||||||
@@ -325,7 +326,7 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
|||||||
|
|
||||||
// 清理会话
|
// 清理会话
|
||||||
if (this.userId != null) {
|
if (this.userId != null) {
|
||||||
WebServiceManager.removeByUserId(this.userId);
|
WebServiceManager.removeByUserId(this.userId, ctx.channel());
|
||||||
log.debug("已清理WebSocket会话,userId: {}, channelId: {}", this.userId, channelId);
|
log.debug("已清理WebSocket会话,userId: {}, channelId: {}", this.userId, channelId);
|
||||||
} else {
|
} else {
|
||||||
WebServiceManager.removeChannel(channelId);
|
WebServiceManager.removeChannel(channelId);
|
||||||
@@ -414,6 +415,11 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
|||||||
}
|
}
|
||||||
// 清理完成后移除该用户的检测参数
|
// 清理完成后移除该用户的检测参数
|
||||||
WebServiceManager.removePreDetectionParam(userId);
|
WebServiceManager.removePreDetectionParam(userId);
|
||||||
|
// R3 释放:WS 断开 / 客户端关页面 / 心跳超时后顺手释放检测锁
|
||||||
|
if (preDetectionParam.getUserPageId() != null) {
|
||||||
|
DetectionLockManager.getInstance()
|
||||||
|
.releaseIfMatchPage(preDetectionParam.getUserPageId(), "WS_DISCONNECTED");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("清理Socket连接时发生异常,userId: {}", userId, e);
|
log.error("清理Socket连接时发生异常,userId: {}", userId, e);
|
||||||
@@ -421,4 +427,4 @@ public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketF
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ================================ URL解析工具已移至WebSocketPreprocessor ================================
|
// ================================ URL解析工具已移至WebSocketPreprocessor ================================
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
|||||||
import com.njcn.common.pojo.exception.BusinessException;
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.common.utils.LogUtil;
|
import com.njcn.common.utils.LogUtil;
|
||||||
|
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
|
||||||
import com.njcn.gather.device.pojo.param.PqDevParam;
|
import com.njcn.gather.device.pojo.param.PqDevParam;
|
||||||
import com.njcn.gather.device.pojo.vo.PqDevVO;
|
import com.njcn.gather.device.pojo.vo.PqDevVO;
|
||||||
import com.njcn.gather.device.service.IPqDevService;
|
import com.njcn.gather.device.service.IPqDevService;
|
||||||
@@ -22,6 +23,7 @@ import io.swagger.annotations.ApiImplicitParams;
|
|||||||
import io.swagger.annotations.ApiOperation;
|
import io.swagger.annotations.ApiOperation;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
@@ -68,10 +70,10 @@ public class PqDevController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@OperateInfo(operateType = OperateType.ADD)
|
@OperateInfo(operateType = OperateType.ADD)
|
||||||
@PostMapping("/add")
|
@PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
@ApiOperation("新增被检设备")
|
@ApiOperation("新增被检设备")
|
||||||
@ApiImplicitParam(name = "pqDevParam", value = "被检设备", required = true)
|
@ApiImplicitParam(name = "pqDevParam", value = "被检设备", required = true)
|
||||||
public HttpResult<Boolean> add(@RequestBody @Validated PqDevParam pqDevParam) {
|
public HttpResult<Boolean> add(@ModelAttribute @Validated PqDevParam pqDevParam) {
|
||||||
String methodDescribe = getMethodDescribe("add");
|
String methodDescribe = getMethodDescribe("add");
|
||||||
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, pqDevParam);
|
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, pqDevParam);
|
||||||
boolean result = pqDevService.addPqDev(pqDevParam);
|
boolean result = pqDevService.addPqDev(pqDevParam);
|
||||||
@@ -83,10 +85,10 @@ public class PqDevController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@OperateInfo(operateType = OperateType.UPDATE)
|
@OperateInfo(operateType = OperateType.UPDATE)
|
||||||
@PostMapping("/update")
|
@PostMapping(value = "/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
@ApiOperation("修改被检设备")
|
@ApiOperation("修改被检设备")
|
||||||
@ApiImplicitParam(name = "updateParam", value = "被检设备", required = true)
|
@ApiImplicitParam(name = "updateParam", value = "被检设备", required = true)
|
||||||
public HttpResult<Boolean> update(@RequestBody @Validated PqDevParam.UpdateParam updateParam) {
|
public HttpResult<Boolean> update(@ModelAttribute @Validated PqDevParam.UpdateParam updateParam) {
|
||||||
String methodDescribe = getMethodDescribe("update");
|
String methodDescribe = getMethodDescribe("update");
|
||||||
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, updateParam);
|
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, updateParam);
|
||||||
boolean result = pqDevService.updatePqDev(updateParam);
|
boolean result = pqDevService.updatePqDev(updateParam);
|
||||||
@@ -97,6 +99,14 @@ public class PqDevController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
|
||||||
|
@GetMapping("/image/download")
|
||||||
|
@ApiOperation("下载设备图片")
|
||||||
|
@ApiImplicitParam(name = "id", value = "被检设备id", required = true)
|
||||||
|
public void downloadImage(@RequestParam("id") String id, HttpServletResponse response) {
|
||||||
|
pqDevService.downloadImage(id, response);
|
||||||
|
}
|
||||||
|
|
||||||
@OperateInfo(operateType = OperateType.DELETE)
|
@OperateInfo(operateType = OperateType.DELETE)
|
||||||
@PostMapping("/delete")
|
@PostMapping("/delete")
|
||||||
@ApiOperation("删除被检设备")
|
@ApiOperation("删除被检设备")
|
||||||
@@ -170,23 +180,14 @@ public class PqDevController extends BaseController {
|
|||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPLOAD)
|
@OperateInfo
|
||||||
@PostMapping(value = "/ttt")
|
@GetMapping("/getDataCheckRes")
|
||||||
@ApiOperation("批量导入被检设备")
|
@ApiOperation("获取接入测试-数据校验结果")
|
||||||
@ApiImplicitParams({
|
@ApiImplicitParam(name = "monitorId", value = "监测点id", required = true)
|
||||||
@ApiImplicitParam(name = "file", value = "被检设备数据文件", required = true),
|
public HttpResult<DataCheckResDTO> getDataCheckRes(@RequestParam("monitorId") String monitorId) {
|
||||||
@ApiImplicitParam(name = "patternId", value = "模式id", required = true)
|
String methodDescribe = getMethodDescribe("getDataCheckRes");
|
||||||
})
|
DataCheckResDTO dataCheckRes = pqDevService.getDataCheckRes(monitorId);
|
||||||
public HttpResult ttt(@RequestParam("file") MultipartFile file, @RequestParam("patternId") String patternId, @RequestParam("planId") String planId, @RequestParam(value = "cover", defaultValue = "0") Integer cover, HttpServletResponse response) {
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dataCheckRes, methodDescribe);
|
||||||
String methodDescribe = getMethodDescribe("ttt");
|
|
||||||
LogUtil.njcnDebug(log, "{},上传文件为:{}", methodDescribe, file.getOriginalFilename());
|
|
||||||
boolean fileType = FileUtil.judgeFileIsExcel(file.getOriginalFilename());
|
|
||||||
if (!fileType) {
|
|
||||||
throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR);
|
|
||||||
}
|
|
||||||
if ("null".equals(planId)) {
|
|
||||||
planId = null;
|
|
||||||
}
|
|
||||||
return pqDevService.importDev(file, patternId, planId, response, cover);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,8 +86,45 @@
|
|||||||
WHERE id = #{planId}
|
WHERE id = #{planId}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<sql id="DevColumnsNoImage">
|
||||||
|
dev.Id,
|
||||||
|
dev.Name,
|
||||||
|
dev.Pattern,
|
||||||
|
dev.Dev_Type,
|
||||||
|
dev.Manufacturer,
|
||||||
|
dev.Create_Date,
|
||||||
|
dev.Create_Id,
|
||||||
|
dev.Hardware_Version,
|
||||||
|
dev.Software_Version,
|
||||||
|
dev.Protocol,
|
||||||
|
dev.IP,
|
||||||
|
dev.Port,
|
||||||
|
dev.Encryption_Flag,
|
||||||
|
dev.Series,
|
||||||
|
dev.Dev_Key,
|
||||||
|
dev.Sample_Id,
|
||||||
|
dev.Arrived_Date,
|
||||||
|
dev.City_Name,
|
||||||
|
dev.Gd_Name,
|
||||||
|
dev.Sub_Name,
|
||||||
|
dev.Report_Path,
|
||||||
|
dev.Plan_Id,
|
||||||
|
dev.Factor_Flag,
|
||||||
|
dev.Preinvestment_Plan,
|
||||||
|
dev.Delegate,
|
||||||
|
dev.Inspect_Channel,
|
||||||
|
dev.Inspect_Date,
|
||||||
|
dev.Harm_Sys_Id,
|
||||||
|
dev.Import_Flag,
|
||||||
|
dev.State,
|
||||||
|
dev.Create_By,
|
||||||
|
dev.Create_Time,
|
||||||
|
dev.Update_By,
|
||||||
|
dev.Update_Time
|
||||||
|
</sql>
|
||||||
|
|
||||||
<select id="selectByQueryParam" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
|
<select id="selectByQueryParam" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
|
||||||
SELECT dev.*,dev_sub.* FROM pq_dev dev
|
SELECT <include refid="DevColumnsNoImage"/>, dev_sub.* FROM pq_dev dev
|
||||||
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
|
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
|
||||||
<where>
|
<where>
|
||||||
dev.state = 1
|
dev.state = 1
|
||||||
@@ -124,7 +161,7 @@
|
|||||||
</select>
|
</select>
|
||||||
|
|
||||||
<select id="listByDevIds" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
|
<select id="listByDevIds" resultType="com.njcn.gather.device.pojo.vo.PqDevVO">
|
||||||
SELECT dev.*, dev_sub.*
|
SELECT <include refid="DevColumnsNoImage"/>, dev_sub.*
|
||||||
FROM pq_dev dev
|
FROM pq_dev dev
|
||||||
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
|
left JOIN pq_dev_sub dev_sub ON dev.Id = dev_sub.Dev_Id
|
||||||
WHERE dev.state = 1
|
WHERE dev.state = 1
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.njcn.gather.device.pojo.dto;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author caozehui
|
||||||
|
* @data 2026-06-15
|
||||||
|
*/
|
||||||
|
public class DataCheckResDTO {
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
import org.hibernate.validator.constraints.Range;
|
import org.hibernate.validator.constraints.Range;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import javax.validation.constraints.*;
|
import javax.validation.constraints.*;
|
||||||
@@ -136,6 +137,9 @@ public class PqDevParam {
|
|||||||
@ApiModelProperty("是否为导入设备")
|
@ApiModelProperty("是否为导入设备")
|
||||||
private Integer importFlag;
|
private Integer importFlag;
|
||||||
|
|
||||||
|
@ApiModelProperty("设备图片")
|
||||||
|
private MultipartFile image;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新操作实体
|
* 更新操作实体
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.njcn.gather.device.pojo.po;
|
|||||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
import com.baomidou.mybatisplus.annotation.TableField;
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
import com.baomidou.mybatisplus.annotation.TableName;
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||||
@@ -184,6 +185,9 @@ public class PqDev extends BaseEntity implements Serializable {
|
|||||||
*/
|
*/
|
||||||
private Integer importFlag;
|
private Integer importFlag;
|
||||||
|
|
||||||
|
@JsonIgnore
|
||||||
|
private byte[] image;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 状态:0-删除 1-正常
|
* 状态:0-删除 1-正常
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -56,10 +56,16 @@ public class PqDevSub {
|
|||||||
private String checkBy;
|
private String checkBy;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检测时间
|
* 检测开始时间
|
||||||
*/
|
*/
|
||||||
@TableField("Check_Time")
|
@TableField("Check_Start_Time")
|
||||||
private LocalDateTime checkTime;
|
private LocalDateTime checkStartTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测结束时间
|
||||||
|
*/
|
||||||
|
@TableField("Check_End_Time")
|
||||||
|
private LocalDateTime checkEndTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 预检测耗时
|
* 预检测耗时
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.njcn.gather.device.pojo.vo;
|
package com.njcn.gather.device.pojo.vo;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
import com.njcn.gather.device.pojo.po.PqDev;
|
import com.njcn.gather.device.pojo.po.PqDev;
|
||||||
import com.njcn.gather.monitor.pojo.po.PqMonitor;
|
import com.njcn.gather.monitor.pojo.po.PqMonitor;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
@@ -73,9 +74,14 @@ public class PqDevVO extends PqDev {
|
|||||||
private String checkBy;
|
private String checkBy;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检测时间
|
* 检测开始时间
|
||||||
*/
|
*/
|
||||||
private LocalDateTime checkTime;
|
private LocalDateTime checkStartTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测结束时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime checkEndTime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 预检测耗时
|
* 预检测耗时
|
||||||
@@ -116,4 +122,10 @@ public class PqDevVO extends PqDev {
|
|||||||
* 检测点结果
|
* 检测点结果
|
||||||
*/
|
*/
|
||||||
private List<Integer> monitorResults;
|
private List<Integer> monitorResults;
|
||||||
|
|
||||||
|
private Boolean hasImage;
|
||||||
|
|
||||||
|
private String imageBase64;
|
||||||
|
|
||||||
|
private String imageContentType;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.njcn.common.pojo.poi.PullDown;
|
import com.njcn.common.pojo.poi.PullDown;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
|
||||||
import com.njcn.gather.device.pojo.enums.TimeCheckResultEnum;
|
import com.njcn.gather.device.pojo.enums.TimeCheckResultEnum;
|
||||||
import com.njcn.gather.device.pojo.param.PqDevParam;
|
import com.njcn.gather.device.pojo.param.PqDevParam;
|
||||||
import com.njcn.gather.device.pojo.po.PqDev;
|
import com.njcn.gather.device.pojo.po.PqDev;
|
||||||
@@ -95,6 +96,14 @@ public interface IPqDevService extends IService<PqDev> {
|
|||||||
*/
|
*/
|
||||||
PqDevVO getPqDevById(String id);
|
PqDevVO getPqDevById(String id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下载设备图片
|
||||||
|
*
|
||||||
|
* @param id 设备id
|
||||||
|
* @param response 响应
|
||||||
|
*/
|
||||||
|
void downloadImage(String id, HttpServletResponse response);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取装置信息和装置下监测点信息
|
* 获取装置信息和装置下监测点信息
|
||||||
*
|
*
|
||||||
@@ -115,9 +124,10 @@ public interface IPqDevService extends IService<PqDev> {
|
|||||||
* @param userId
|
* @param userId
|
||||||
* @param temperature
|
* @param temperature
|
||||||
* @param humidity
|
* @param humidity
|
||||||
|
* @param updateCheckNum 是否更新检测次数
|
||||||
* @return
|
* @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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 比对式-修改设备状态
|
* 比对式-修改设备状态
|
||||||
@@ -288,4 +298,11 @@ public interface IPqDevService extends IService<PqDev> {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
List<ContrastDevExcel> getExportContrastDevData(List<PqDevVO> pqDevVOList);
|
List<ContrastDevExcel> getExportContrastDevData(List<PqDevVO> pqDevVOList);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取接入测试-数据校验结果
|
||||||
|
* @param monitorId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
DataCheckResDTO getDataCheckRes(String monitorId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ package com.njcn.gather.device.service;
|
|||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.njcn.gather.device.pojo.po.PqDevSub;
|
import com.njcn.gather.device.pojo.po.PqDevSub;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
* @date 2025-07-04
|
* @date 2025-07-04
|
||||||
*/
|
*/
|
||||||
public interface IPqDevSubService extends IService<PqDevSub> {
|
public interface IPqDevSubService extends IService<PqDevSub> {
|
||||||
|
|
||||||
|
LocalDateTime resolveBatchMaxCheckEndTime(List<String> devIds);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
|
|||||||
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
||||||
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
|
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
|
||||||
import cn.hutool.core.bean.BeanUtil;
|
import cn.hutool.core.bean.BeanUtil;
|
||||||
|
import cn.hutool.core.bean.copier.CopyOptions;
|
||||||
import cn.hutool.core.collection.CollUtil;
|
import cn.hutool.core.collection.CollUtil;
|
||||||
import cn.hutool.core.collection.CollectionUtil;
|
import cn.hutool.core.collection.CollectionUtil;
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
@@ -26,7 +27,10 @@ import com.njcn.common.pojo.poi.PullDown;
|
|||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.common.utils.EncryptionUtil;
|
import com.njcn.common.utils.EncryptionUtil;
|
||||||
import com.njcn.db.mybatisplus.constant.DbConstant;
|
import com.njcn.db.mybatisplus.constant.DbConstant;
|
||||||
|
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
|
||||||
|
import com.njcn.gather.detection.util.socket.FormalTestManager;
|
||||||
import com.njcn.gather.device.mapper.PqDevMapper;
|
import com.njcn.gather.device.mapper.PqDevMapper;
|
||||||
|
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
|
||||||
import com.njcn.gather.device.pojo.enums.*;
|
import com.njcn.gather.device.pojo.enums.*;
|
||||||
import com.njcn.gather.device.pojo.param.PqDevParam;
|
import com.njcn.gather.device.pojo.param.PqDevParam;
|
||||||
import com.njcn.gather.device.pojo.po.PqDev;
|
import com.njcn.gather.device.pojo.po.PqDev;
|
||||||
@@ -34,10 +38,14 @@ import com.njcn.gather.device.pojo.po.PqDevSub;
|
|||||||
import com.njcn.gather.device.pojo.vo.*;
|
import com.njcn.gather.device.pojo.vo.*;
|
||||||
import com.njcn.gather.device.service.IPqDevService;
|
import com.njcn.gather.device.service.IPqDevService;
|
||||||
import com.njcn.gather.device.service.IPqDevSubService;
|
import com.njcn.gather.device.service.IPqDevSubService;
|
||||||
|
import com.njcn.gather.device.util.PqDevImageSupport;
|
||||||
import com.njcn.gather.monitor.pojo.po.PqMonitor;
|
import com.njcn.gather.monitor.pojo.po.PqMonitor;
|
||||||
import com.njcn.gather.monitor.pojo.vo.PqMonitorExcel;
|
import com.njcn.gather.monitor.pojo.vo.PqMonitorExcel;
|
||||||
import com.njcn.gather.monitor.service.IPqMonitorService;
|
import com.njcn.gather.monitor.service.IPqMonitorService;
|
||||||
|
import com.njcn.gather.plan.mapper.AdPlanMapper;
|
||||||
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
import com.njcn.gather.plan.pojo.enums.DataSourceEnum;
|
||||||
|
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||||
|
import com.njcn.gather.plan.service.IPqDevCheckHistoryService;
|
||||||
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
||||||
import com.njcn.gather.storage.service.DetectionDataDealService;
|
import com.njcn.gather.storage.service.DetectionDataDealService;
|
||||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||||
@@ -51,6 +59,7 @@ import com.njcn.gather.type.pojo.po.DevType;
|
|||||||
import com.njcn.gather.type.service.IDevTypeService;
|
import com.njcn.gather.type.service.IDevTypeService;
|
||||||
import com.njcn.gather.user.user.pojo.po.SysUser;
|
import com.njcn.gather.user.user.pojo.po.SysUser;
|
||||||
import com.njcn.gather.user.user.service.ISysUserService;
|
import com.njcn.gather.user.user.service.ISysUserService;
|
||||||
|
import com.njcn.http.util.RestTemplateUtil;
|
||||||
import com.njcn.web.factory.PageFactory;
|
import com.njcn.web.factory.PageFactory;
|
||||||
import com.njcn.web.utils.ExcelUtil;
|
import com.njcn.web.utils.ExcelUtil;
|
||||||
import com.njcn.web.utils.HttpResultUtil;
|
import com.njcn.web.utils.HttpResultUtil;
|
||||||
@@ -64,6 +73,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@@ -87,6 +97,9 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
private final IDictTypeService dictTypeService;
|
private final IDictTypeService dictTypeService;
|
||||||
private final ISysUserService userService;
|
private final ISysUserService userService;
|
||||||
private final IPqDevSubService pqDevSubService;
|
private final IPqDevSubService pqDevSubService;
|
||||||
|
private final AdPlanMapper adPlanMapper;
|
||||||
|
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
|
||||||
|
private final RestTemplateUtil restTemplateUtil;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
|
public Page<PqDevVO> listPqDevs(PqDevParam.QueryParam queryParam) {
|
||||||
@@ -128,7 +141,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
this.checkRepeat(pqDevParam, false);
|
this.checkRepeat(pqDevParam, false);
|
||||||
|
|
||||||
PqDev pqDev = new PqDev();
|
PqDev pqDev = new PqDev();
|
||||||
BeanUtil.copyProperties(pqDevParam, pqDev);
|
BeanUtil.copyProperties(pqDevParam, pqDev, CopyOptions.create().setIgnoreProperties("image"));
|
||||||
|
fillImage(pqDev, pqDevParam);
|
||||||
String currrentScene = sysTestConfigService.getCurrrentScene();
|
String currrentScene = sysTestConfigService.getCurrrentScene();
|
||||||
this.checkParams(pqDev, currrentScene);
|
this.checkParams(pqDev, currrentScene);
|
||||||
|
|
||||||
@@ -159,6 +173,19 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
return this.save(pqDev);
|
return this.save(pqDev);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void fillImage(PqDev pqDev, PqDevParam pqDevParam) {
|
||||||
|
try {
|
||||||
|
byte[] image = PqDevImageSupport.processUpload(pqDevParam.getImage());
|
||||||
|
if (image != null) {
|
||||||
|
pqDev.setImage(image);
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, e.getMessage());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "图片处理失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验参数
|
* 校验参数
|
||||||
*
|
*
|
||||||
@@ -201,7 +228,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
this.checkRepeat(updateParam, true);
|
this.checkRepeat(updateParam, true);
|
||||||
|
|
||||||
PqDev pqDev = new PqDev();
|
PqDev pqDev = new PqDev();
|
||||||
BeanUtil.copyProperties(updateParam, pqDev);
|
BeanUtil.copyProperties(updateParam, pqDev, CopyOptions.create().setIgnoreProperties("image"));
|
||||||
|
fillImage(pqDev, updateParam);
|
||||||
String currrentScene = sysTestConfigService.getCurrrentScene();
|
String currrentScene = sysTestConfigService.getCurrrentScene();
|
||||||
this.checkParams(pqDev, currrentScene);
|
this.checkParams(pqDev, currrentScene);
|
||||||
|
|
||||||
@@ -268,6 +296,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> listUnbound(String pattern) {
|
public List<Map<String, Object>> listUnbound(String pattern) {
|
||||||
List<PqDev> pqDevList = this.lambdaQuery()
|
List<PqDev> pqDevList = this.lambdaQuery()
|
||||||
|
.select(PqDev::getId, PqDev::getName, PqDev::getDevType, PqDev::getManufacturer,
|
||||||
|
PqDev::getCityName, PqDev::getGdName, PqDev::getSubName)
|
||||||
.eq(PqDev::getPattern, pattern)
|
.eq(PqDev::getPattern, pattern)
|
||||||
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
|
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
|
||||||
.isNull(PqDev::getPlanId)
|
.isNull(PqDev::getPlanId)
|
||||||
@@ -382,6 +412,10 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
@Override
|
@Override
|
||||||
public PqDevVO getPqDevById(String id) {
|
public PqDevVO getPqDevById(String id) {
|
||||||
PqDevVO pqDevVO = this.baseMapper.selectByDevId(id);
|
PqDevVO pqDevVO = this.baseMapper.selectByDevId(id);
|
||||||
|
if (ObjectUtil.isNull(pqDevVO)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
setImageEchoFields(pqDevVO);
|
||||||
if (StrUtil.isNotBlank(pqDevVO.getSeries())) {
|
if (StrUtil.isNotBlank(pqDevVO.getSeries())) {
|
||||||
pqDevVO.setSeries(EncryptionUtil.decoderString(1, pqDevVO.getSeries()));
|
pqDevVO.setSeries(EncryptionUtil.decoderString(1, pqDevVO.getSeries()));
|
||||||
}
|
}
|
||||||
@@ -410,6 +444,37 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
return pqDevVO;
|
return pqDevVO;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void downloadImage(String id, HttpServletResponse response) {
|
||||||
|
PqDev pqDev = this.getById(id);
|
||||||
|
if (ObjectUtil.isNull(pqDev) || pqDev.getImage() == null || pqDev.getImage().length == 0) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "设备图片不存在");
|
||||||
|
}
|
||||||
|
String contentType = PqDevImageSupport.detectContentType(pqDev.getImage());
|
||||||
|
String filename = "device-image-" + id + "." + PqDevImageSupport.getExtension(contentType);
|
||||||
|
response.setContentType(contentType);
|
||||||
|
response.setContentLength(pqDev.getImage().length);
|
||||||
|
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
|
||||||
|
try {
|
||||||
|
response.getOutputStream().write(pqDev.getImage());
|
||||||
|
response.flushBuffer();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "设备图片下载失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setImageEchoFields(PqDevVO pqDevVO) {
|
||||||
|
try {
|
||||||
|
PqDevImageSupport.ImageEchoPayload payload = PqDevImageSupport.buildEchoPayload(pqDevVO.getImage());
|
||||||
|
pqDevVO.setHasImage(payload.isHasImage());
|
||||||
|
pqDevVO.setImageBase64(payload.getImageBase64());
|
||||||
|
pqDevVO.setImageContentType(payload.getImageContentType());
|
||||||
|
pqDevVO.setImage(null);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取查询条件wrapper
|
* 获取查询条件wrapper
|
||||||
@@ -419,6 +484,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
*/
|
*/
|
||||||
private Wrapper getQueryWrapper(PqDevParam.QueryParam queryParam) {
|
private Wrapper getQueryWrapper(PqDevParam.QueryParam queryParam) {
|
||||||
QueryWrapper<PqDev> queryWrapper = new QueryWrapper<>();
|
QueryWrapper<PqDev> queryWrapper = new QueryWrapper<>();
|
||||||
|
queryWrapper.select("pq_dev.Id");
|
||||||
if (ObjectUtil.isNotNull(queryParam)) {
|
if (ObjectUtil.isNotNull(queryParam)) {
|
||||||
queryWrapper
|
queryWrapper
|
||||||
.like(StrUtil.isNotBlank(queryParam.getName()), "pq_dev.name", queryParam.getName())
|
.like(StrUtil.isNotBlank(queryParam.getName()), "pq_dev.name", queryParam.getName())
|
||||||
@@ -483,7 +549,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@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)) {
|
if (CollUtil.isNotEmpty(ids)) {
|
||||||
|
|
||||||
SysTestConfig config = sysTestConfigService.getOneConfig();
|
SysTestConfig config = sysTestConfigService.getOneConfig();
|
||||||
@@ -500,7 +566,8 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
LambdaUpdateWrapper<PqDevSub> wrapper = new LambdaUpdateWrapper<PqDevSub>()
|
LambdaUpdateWrapper<PqDevSub> wrapper = new LambdaUpdateWrapper<PqDevSub>()
|
||||||
.set(PqDevSub::getCheckResult, result.get(pqDevVo.getId()))
|
.set(PqDevSub::getCheckResult, result.get(pqDevVo.getId()))
|
||||||
.set(StrUtil.isNotBlank(userId), PqDevSub::getCheckBy, userId)
|
.set(StrUtil.isNotBlank(userId), PqDevSub::getCheckBy, userId)
|
||||||
.set(PqDevSub::getCheckTime, LocalDateTime.now())
|
.set(updateCheckNum && SourceOperateCodeEnum.ALL_TEST.getValue().equals(FormalTestManager.reCheckType), PqDevSub::getCheckEndTime, LocalDateTime.now())
|
||||||
|
.set(updateCheckNum && SourceOperateCodeEnum.ALL_TEST.getValue().equals(FormalTestManager.reCheckType) && ObjectUtil.isNotNull(FormalTestManager.checkStartTime), PqDevSub::getCheckStartTime, FormalTestManager.checkStartTime)
|
||||||
.eq(PqDevSub::getDevId, pqDevVo.getId());
|
.eq(PqDevSub::getDevId, pqDevVo.getId());
|
||||||
String currrentScene = sysTestConfigService.getCurrrentScene();
|
String currrentScene = sysTestConfigService.getCurrrentScene();
|
||||||
if (SceneEnum.PROVINCE_PLATFORM.getValue().equals(currrentScene)) {
|
if (SceneEnum.PROVINCE_PLATFORM.getValue().equals(currrentScene)) {
|
||||||
@@ -515,13 +582,18 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
checkState = CheckStateEnum.DOCUMENTED.getValue();
|
checkState = CheckStateEnum.DOCUMENTED.getValue();
|
||||||
i = pqDevVo.getRecheckNum();
|
i = pqDevVo.getRecheckNum();
|
||||||
} else {
|
} else {
|
||||||
checkState = CheckStateEnum.CHECKED.getValue();
|
checkState = pqDevVo.getCheckState() == CheckStateEnum.DOCUMENTED.getValue() ? CheckStateEnum.DOCUMENTED.getValue() : CheckStateEnum.CHECKED.getValue();
|
||||||
i = pqDevVo.getRecheckNum() + 1;
|
if (updateCheckNum) {
|
||||||
|
i = pqDevVo.getRecheckNum() + 1;
|
||||||
|
} else {
|
||||||
|
i = pqDevVo.getRecheckNum();
|
||||||
|
}
|
||||||
wrapper.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
wrapper.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
||||||
}
|
}
|
||||||
wrapper.set(PqDevSub::getRecheckNum, i)
|
wrapper.set(PqDevSub::getRecheckNum, i)
|
||||||
.set(PqDevSub::getCheckState, checkState);
|
.set(PqDevSub::getCheckState, checkState);
|
||||||
pqDevSubService.update(wrapper);
|
pqDevSubService.update(wrapper);
|
||||||
|
saveCheckHistory(pqDevVo, i, checkState, userId);
|
||||||
|
|
||||||
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
||||||
param.setPlanIdList(Arrays.asList(pqDevVo.getPlanId()));
|
param.setPlanIdList(Arrays.asList(pqDevVo.getPlanId()));
|
||||||
@@ -573,13 +645,23 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
|
|
||||||
SysUser user = userService.getById(userId);
|
SysUser user = userService.getById(userId);
|
||||||
|
|
||||||
|
// 查询当前设备的检测时间
|
||||||
|
PqDevSub currentDevSub = pqDevSubService.lambdaQuery()
|
||||||
|
.eq(PqDevSub::getDevId, devId)
|
||||||
|
.one();
|
||||||
|
|
||||||
LambdaUpdateChainWrapper<PqDevSub> w = pqDevSubService.lambdaUpdate()
|
LambdaUpdateChainWrapper<PqDevSub> w = pqDevSubService.lambdaUpdate()
|
||||||
.set(PqDevSub::getCheckState, checkState)
|
.set(PqDevSub::getCheckState, checkState)
|
||||||
.set(PqDevSub::getCheckResult, checkResult)
|
.set(PqDevSub::getCheckResult, checkResult)
|
||||||
.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue())
|
.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue())
|
||||||
.set(PqDevSub::getCheckTime, LocalDateTime.now())
|
|
||||||
.eq(PqDevSub::getDevId, devId);
|
.eq(PqDevSub::getDevId, devId);
|
||||||
|
|
||||||
|
// 只有当checkTime为空时,才设置为当前时间
|
||||||
|
if (currentDevSub != null && currentDevSub.getCheckEndTime() == null) {
|
||||||
|
w.set(PqDevSub::getCheckEndTime, LocalDateTime.now());
|
||||||
|
w.set(ObjectUtil.isNotNull(FormalTestManager.checkStartTime), PqDevSub::getCheckStartTime, currentDevSub.getCheckStartTime());
|
||||||
|
}
|
||||||
|
|
||||||
if (ObjectUtil.isNotNull(user)) {
|
if (ObjectUtil.isNotNull(user)) {
|
||||||
w.set(PqDevSub::getCheckBy, user.getName());
|
w.set(PqDevSub::getCheckBy, user.getName());
|
||||||
}
|
}
|
||||||
@@ -587,6 +669,7 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
w.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
w.set(PqDevSub::getReportState, DevReportStateEnum.NOT_GENERATED.getValue());
|
||||||
}
|
}
|
||||||
w.update();
|
w.update();
|
||||||
|
saveCheckHistory(devId, userId);
|
||||||
|
|
||||||
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
PqDevParam.QueryParam param = new PqDevParam.QueryParam();
|
||||||
String planId = dev.getPlanId();
|
String planId = dev.getPlanId();
|
||||||
@@ -622,6 +705,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.setCheckEndTime(LocalDateTime.now());
|
||||||
|
pqDevCheckHistoryService.saveOrUpdateDeviceHistory(plan, pqDevVo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveCheckHistory(String devId, String userId) {
|
||||||
|
PqDevVO pqDevVo = this.baseMapper.selectByDevId(devId);
|
||||||
|
if (ObjectUtil.isNull(pqDevVo)
|
||||||
|
|| (!CheckStateEnum.CHECKED.getValue().equals(pqDevVo.getCheckState()) && !CheckStateEnum.DOCUMENTED.getValue().equals(pqDevVo.getCheckState()))) {
|
||||||
|
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
|
@Override
|
||||||
public void updatePqDevReportState(String devId, int reportState) {
|
public void updatePqDevReportState(String devId, int reportState) {
|
||||||
LambdaUpdateWrapper<PqDevSub> updateWrapper = new LambdaUpdateWrapper<>();
|
LambdaUpdateWrapper<PqDevSub> updateWrapper = new LambdaUpdateWrapper<>();
|
||||||
@@ -1601,7 +1715,10 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, List<String>> listSelectOptions(String pattern) {
|
public Map<String, List<String>> listSelectOptions(String pattern) {
|
||||||
List<PqDev> pqDevList = this.lambdaQuery().eq(PqDev::getPattern, pattern)
|
List<PqDev> pqDevList = this.lambdaQuery()
|
||||||
|
.select(PqDev::getCityName, PqDev::getGdName, PqDev::getSubName,
|
||||||
|
PqDev::getHardwareVersion, PqDev::getSoftwareVersion)
|
||||||
|
.eq(PqDev::getPattern, pattern)
|
||||||
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
|
.eq(PqDev::getState, DataStateEnum.ENABLE.getCode())
|
||||||
.list();
|
.list();
|
||||||
String[] devKeyArray = new String[]{"cityName", "gdName", "subName", "hardwareVersion", "softwareVersion"};
|
String[] devKeyArray = new String[]{"cityName", "gdName", "subName", "hardwareVersion", "softwareVersion"};
|
||||||
@@ -1625,4 +1742,11 @@ public class PqDevServiceImpl extends ServiceImpl<PqDevMapper, PqDev> implements
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DataCheckResDTO getDataCheckRes(String monitorId) {
|
||||||
|
// restTemplateUtil.postJson();
|
||||||
|
DataCheckResDTO dataCheckResDTO = restTemplateUtil.postJson("http://localhost:8080/api/v1/dataCheck/getDataCheckRes", monitorId, DataCheckResDTO.class);
|
||||||
|
return dataCheckResDTO;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
package com.njcn.gather.device.service.impl;
|
package com.njcn.gather.device.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.collection.CollUtil;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.njcn.gather.device.pojo.po.PqDevSub;
|
|
||||||
import com.njcn.gather.device.mapper.PqDevSubMapper;
|
import com.njcn.gather.device.mapper.PqDevSubMapper;
|
||||||
|
import com.njcn.gather.device.pojo.po.PqDevSub;
|
||||||
import com.njcn.gather.device.service.IPqDevSubService;
|
import com.njcn.gather.device.service.IPqDevSubService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
* @date 2025-07-04
|
* @date 2025-07-04
|
||||||
@@ -16,5 +23,19 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class PqDevSubServiceImpl extends ServiceImpl<PqDevSubMapper, PqDevSub> implements IPqDevSubService {
|
public class PqDevSubServiceImpl extends ServiceImpl<PqDevSubMapper, PqDevSub> implements IPqDevSubService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public LocalDateTime resolveBatchMaxCheckEndTime(List<String> devIds) {
|
||||||
|
if (CollUtil.isEmpty(devIds)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.list(new LambdaQueryWrapper<PqDevSub>()
|
||||||
|
.in(PqDevSub::getDevId, devIds)
|
||||||
|
.isNotNull(PqDevSub::getCheckEndTime))
|
||||||
|
.stream()
|
||||||
|
.map(PqDevSub::getCheckEndTime)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.max(Comparator.naturalOrder())
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
package com.njcn.gather.device.util;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import javax.imageio.IIOImage;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.ImageWriteParam;
|
||||||
|
import javax.imageio.ImageWriter;
|
||||||
|
import javax.imageio.stream.ImageOutputStream;
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.RenderingHints;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public final class PqDevImageSupport {
|
||||||
|
|
||||||
|
private static final long MAX_FILE_SIZE = 10L * 1024L * 1024L;
|
||||||
|
private static final int MAX_EDGE = 1600;
|
||||||
|
private static final float JPEG_QUALITY = 0.82f;
|
||||||
|
|
||||||
|
private PqDevImageSupport() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ImageEchoPayload buildEchoPayload(byte[] imageBytes) {
|
||||||
|
if (imageBytes == null || imageBytes.length == 0) {
|
||||||
|
return new ImageEchoPayload(false, null, null);
|
||||||
|
}
|
||||||
|
return new ImageEchoPayload(true, Base64.getEncoder().encodeToString(imageBytes), detectContentType(imageBytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String detectContentType(byte[] imageBytes) {
|
||||||
|
if (imageBytes == null || imageBytes.length < 4) {
|
||||||
|
throw new IllegalArgumentException("图片内容无效");
|
||||||
|
}
|
||||||
|
if (isPng(imageBytes)) {
|
||||||
|
return "image/png";
|
||||||
|
}
|
||||||
|
if (isJpeg(imageBytes)) {
|
||||||
|
return "image/jpeg";
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("仅支持 JPG、PNG 图片");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] processUpload(MultipartFile image) throws IOException {
|
||||||
|
if (image == null || image.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (image.getSize() > MAX_FILE_SIZE) {
|
||||||
|
throw new IllegalArgumentException("图片大小不能超过 10MB");
|
||||||
|
}
|
||||||
|
|
||||||
|
String normalizedName = normalize(image.getOriginalFilename());
|
||||||
|
String normalizedContentType = normalize(image.getContentType());
|
||||||
|
boolean allowedType = normalizedContentType.equals("image/jpeg")
|
||||||
|
|| normalizedContentType.equals("image/png")
|
||||||
|
|| normalizedName.endsWith(".jpg")
|
||||||
|
|| normalizedName.endsWith(".jpeg")
|
||||||
|
|| normalizedName.endsWith(".png");
|
||||||
|
if (!allowedType) {
|
||||||
|
throw new IllegalArgumentException("仅支持 JPG、PNG 图片");
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] originalBytes = image.getBytes();
|
||||||
|
String contentType = detectContentType(originalBytes);
|
||||||
|
BufferedImage source;
|
||||||
|
try (InputStream inputStream = image.getInputStream()) {
|
||||||
|
source = ImageIO.read(inputStream);
|
||||||
|
}
|
||||||
|
if (source == null) {
|
||||||
|
throw new IllegalArgumentException("图片内容无效");
|
||||||
|
}
|
||||||
|
|
||||||
|
BufferedImage target = scaleIfNeeded(source);
|
||||||
|
if ("image/png".equals(contentType)) {
|
||||||
|
return writePng(target);
|
||||||
|
}
|
||||||
|
return writeJpeg(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getExtension(String contentType) {
|
||||||
|
return "image/png".equals(contentType) ? "png" : "jpg";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BufferedImage scaleIfNeeded(BufferedImage source) {
|
||||||
|
int width = source.getWidth();
|
||||||
|
int height = source.getHeight();
|
||||||
|
int max = Math.max(width, height);
|
||||||
|
if (max <= MAX_EDGE) {
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
double scale = (double) MAX_EDGE / max;
|
||||||
|
int targetWidth = Math.max(1, (int) Math.round(width * scale));
|
||||||
|
int targetHeight = Math.max(1, (int) Math.round(height * scale));
|
||||||
|
int type = source.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_ARGB : source.getType();
|
||||||
|
BufferedImage target = new BufferedImage(targetWidth, targetHeight, type);
|
||||||
|
Graphics2D graphics = target.createGraphics();
|
||||||
|
try {
|
||||||
|
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||||
|
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
|
||||||
|
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||||
|
graphics.drawImage(source, 0, 0, targetWidth, targetHeight, null);
|
||||||
|
} finally {
|
||||||
|
graphics.dispose();
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] writePng(BufferedImage image) throws IOException {
|
||||||
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
ImageIO.write(image, "png", outputStream);
|
||||||
|
return outputStream.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] writeJpeg(BufferedImage image) throws IOException {
|
||||||
|
BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
|
||||||
|
Graphics2D graphics = rgbImage.createGraphics();
|
||||||
|
try {
|
||||||
|
graphics.drawImage(image, 0, 0, null);
|
||||||
|
} finally {
|
||||||
|
graphics.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
|
||||||
|
if (!writers.hasNext()) {
|
||||||
|
throw new IOException("未找到 JPG 图片编码器");
|
||||||
|
}
|
||||||
|
ImageWriter writer = writers.next();
|
||||||
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream)) {
|
||||||
|
writer.setOutput(imageOutputStream);
|
||||||
|
ImageWriteParam writeParam = writer.getDefaultWriteParam();
|
||||||
|
if (writeParam.canWriteCompressed()) {
|
||||||
|
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||||
|
writeParam.setCompressionQuality(JPEG_QUALITY);
|
||||||
|
}
|
||||||
|
writer.write(null, new IIOImage(rgbImage, null, null), writeParam);
|
||||||
|
} finally {
|
||||||
|
writer.dispose();
|
||||||
|
}
|
||||||
|
return outputStream.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isPng(byte[] imageBytes) {
|
||||||
|
return imageBytes.length >= 8
|
||||||
|
&& (imageBytes[0] & 0xFF) == 0x89
|
||||||
|
&& imageBytes[1] == 0x50
|
||||||
|
&& imageBytes[2] == 0x4E
|
||||||
|
&& imageBytes[3] == 0x47
|
||||||
|
&& imageBytes[4] == 0x0D
|
||||||
|
&& imageBytes[5] == 0x0A
|
||||||
|
&& imageBytes[6] == 0x1A
|
||||||
|
&& imageBytes[7] == 0x0A;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isJpeg(byte[] imageBytes) {
|
||||||
|
return imageBytes.length >= 3
|
||||||
|
&& (imageBytes[0] & 0xFF) == 0xFF
|
||||||
|
&& (imageBytes[1] & 0xFF) == 0xD8
|
||||||
|
&& (imageBytes[2] & 0xFF) == 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalize(String value) {
|
||||||
|
return value == null ? "" : value.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ImageEchoPayload {
|
||||||
|
private boolean hasImage;
|
||||||
|
private String imageBase64;
|
||||||
|
private String imageContentType;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
package com.njcn.gather.icd.controller;
|
package com.njcn.gather.icd.controller;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
import com.njcn.common.pojo.annotation.OperateInfo;
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
import com.njcn.common.pojo.constant.OperateType;
|
import com.njcn.common.pojo.constant.OperateType;
|
||||||
import com.njcn.common.pojo.enums.common.LogEnum;
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.common.utils.LogUtil;
|
import com.njcn.common.utils.LogUtil;
|
||||||
|
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
||||||
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
|
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
|
||||||
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
||||||
import com.njcn.gather.icd.service.IPqIcdPathService;
|
import com.njcn.gather.icd.service.IPqIcdPathService;
|
||||||
@@ -18,12 +21,20 @@ import io.swagger.annotations.ApiImplicitParam;
|
|||||||
import io.swagger.annotations.ApiOperation;
|
import io.swagger.annotations.ApiOperation;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import org.springframework.web.util.UriUtils;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
* @date 2025-02-10
|
* @date 2025-02-10
|
||||||
@@ -38,7 +49,7 @@ public class PqIcdPathController extends BaseController {
|
|||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
@GetMapping("/listAll")
|
@GetMapping("/listAll")
|
||||||
@ApiOperation("获取所有icd")
|
@ApiOperation("获取全部icd")
|
||||||
public HttpResult<List<PqIcdPath>> listAll() {
|
public HttpResult<List<PqIcdPath>> listAll() {
|
||||||
String methodDescribe = getMethodDescribe("listAll");
|
String methodDescribe = getMethodDescribe("listAll");
|
||||||
List<PqIcdPath> result = pqIcdPathService.listAll();
|
List<PqIcdPath> result = pqIcdPathService.listAll();
|
||||||
@@ -60,7 +71,7 @@ public class PqIcdPathController extends BaseController {
|
|||||||
@PostMapping("/add")
|
@PostMapping("/add")
|
||||||
@ApiOperation("新增icd")
|
@ApiOperation("新增icd")
|
||||||
@ApiImplicitParam(name = "param", value = "icd新增参数", required = true)
|
@ApiImplicitParam(name = "param", value = "icd新增参数", required = true)
|
||||||
public HttpResult<Boolean> add(PqIcdPathParam param) {
|
public HttpResult<Boolean> add(@Validated PqIcdPathParam.CreateParam param) {
|
||||||
String methodDescribe = getMethodDescribe("add");
|
String methodDescribe = getMethodDescribe("add");
|
||||||
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, param);
|
LogUtil.njcnDebug(log, "{},新增数据为:{}", methodDescribe, param);
|
||||||
|
|
||||||
@@ -72,11 +83,27 @@ public class PqIcdPathController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
|
||||||
|
@PostMapping("/external/add")
|
||||||
|
@ApiOperation("外部系统新增icd")
|
||||||
|
@ApiImplicitParam(name = "param", value = "外部系统icd新增参数", required = true)
|
||||||
|
public HttpResult<Boolean> externalAdd(@RequestBody List<PqIcdPathParam.ExternalCreateParam> param) {
|
||||||
|
String methodDescribe = getMethodDescribe("externalAdd");
|
||||||
|
LogUtil.njcnDebug(log, "{},外部新增数据为:{}", methodDescribe, param);
|
||||||
|
|
||||||
|
boolean result = pqIcdPathService.addUpstreamIcd(param);
|
||||||
|
if (result) {
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||||
|
} else {
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
|
||||||
@PostMapping("/update")
|
@PostMapping("/update")
|
||||||
@ApiOperation("修改icd")
|
@ApiOperation("修改icd")
|
||||||
@ApiImplicitParam(name = "param", value = "icd修改参数", required = true)
|
@ApiImplicitParam(name = "param", value = "icd修改参数", required = true)
|
||||||
public HttpResult<Boolean> update(PqIcdPathParam.UpdateParam param) {
|
public HttpResult<Boolean> update(@Validated PqIcdPathParam.UpdateParam param) {
|
||||||
String methodDescribe = getMethodDescribe("update");
|
String methodDescribe = getMethodDescribe("update");
|
||||||
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, param);
|
LogUtil.njcnDebug(log, "{},修改数据为:{}", methodDescribe, param);
|
||||||
|
|
||||||
@@ -88,6 +115,24 @@ public class PqIcdPathController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@GetMapping("/standard-list")
|
||||||
|
@ApiOperation("获取标准ICD列表")
|
||||||
|
public HttpResult<List<PqIcdPath>> standardList() {
|
||||||
|
String methodDescribe = getMethodDescribe("standardList");
|
||||||
|
List<PqIcdPath> result = pqIcdPathService.listStandardIcd();
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@GetMapping("/getById")
|
||||||
|
@ApiOperation("根据id获取ICD详情")
|
||||||
|
public HttpResult<PqIcdPath> getById(@RequestParam String id) {
|
||||||
|
String methodDescribe = getMethodDescribe("getById");
|
||||||
|
PqIcdPath result = pqIcdPathService.getIcdById(id);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
|
||||||
@PostMapping("/delete")
|
@PostMapping("/delete")
|
||||||
@ApiOperation("删除icd")
|
@ApiOperation("删除icd")
|
||||||
@@ -103,5 +148,70 @@ public class PqIcdPathController extends BaseController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@GetMapping("/export/{id}")
|
||||||
|
@ApiOperation("导出icd")
|
||||||
|
public ResponseEntity<ByteArrayResource> export(@PathVariable String id) {
|
||||||
|
PqIcdPath detail = pqIcdPathService.getIcdById(id);
|
||||||
|
byte[] body = pqIcdPathService.exportIcd(id);
|
||||||
|
String fileName = UriUtils.encode(detail.getName() + ".zip", StandardCharsets.UTF_8);
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.contentLength(body.length)
|
||||||
|
.body(new ByteArrayResource(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@PostMapping("/export/json")
|
||||||
|
@ApiOperation("导出icd json")
|
||||||
|
@ApiImplicitParam(name = "ids", value = "id集合", required = true)
|
||||||
|
public ResponseEntity<ByteArrayResource> exportJson(@RequestBody List<String> ids) {
|
||||||
|
byte[] body = pqIcdPathService.exportIcdJson(ids);
|
||||||
|
String fileName = UriUtils.encode(LocalDate.now() + ".json", StandardCharsets.UTF_8);
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.contentLength(body.length)
|
||||||
|
.body(new ByteArrayResource(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
|
||||||
|
@PostMapping("/import/json")
|
||||||
|
@ApiOperation("导入icd json")
|
||||||
|
@ApiImplicitParam(name = "file", value = "json文件", required = true)
|
||||||
|
public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
|
||||||
|
String methodDescribe = getMethodDescribe("importJson");
|
||||||
|
LogUtil.njcnDebug(log, "{},导入文件为:{}", methodDescribe, file == null ? null : file.getOriginalFilename());
|
||||||
|
|
||||||
|
List<PqIcdPathParam.ExternalCreateParam> param = parseExternalCreateParams(file);
|
||||||
|
boolean result = pqIcdPathService.addUpstreamIcd(param);
|
||||||
|
if (result) {
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||||
|
} else {
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PqIcdPathParam.ExternalCreateParam> parseExternalCreateParams(MultipartFile file) {
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
|
||||||
|
}
|
||||||
|
String fileName = file.getOriginalFilename();
|
||||||
|
if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
String content = new String(file.getBytes(), StandardCharsets.UTF_8);
|
||||||
|
List<PqIcdPathParam.ExternalCreateParam> params = JSON.parseArray(content, PqIcdPathParam.ExternalCreateParam.class);
|
||||||
|
if (params == null) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
} catch (BusinessException ex) {
|
||||||
|
throw ex;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package com.njcn.gather.icd.mapper;
|
package com.njcn.gather.icd.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.github.yulichang.base.MPJBaseMapper;
|
import com.github.yulichang.base.MPJBaseMapper;
|
||||||
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
||||||
|
import com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
* @date 2025-02-10
|
* @date 2025-02-10
|
||||||
@@ -17,5 +21,21 @@ public interface PqIcdPathMapper extends MPJBaseMapper<PqIcdPath> {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
PqIcdPath selectIcdByDevType(@Param("devTypeId") String devTypeId);
|
PqIcdPath selectIcdByDevType(@Param("devTypeId") String devTypeId);
|
||||||
|
|
||||||
|
List<PqIcdPath> selectPageList(Page<PqIcdPath> page, @Param("name") String name);
|
||||||
|
|
||||||
|
List<PqIcdPath> selectStandardList();
|
||||||
|
|
||||||
|
PqIcdPath selectStandardByName(@Param("name") String name);
|
||||||
|
|
||||||
|
List<PqIcdPath> selectByIdsWithoutBlob(@Param("ids") List<String> ids);
|
||||||
|
|
||||||
|
Long countActiveReferencesToStandards(@Param("standardIds") List<String> standardIds);
|
||||||
|
|
||||||
|
PqIcdPath selectDetailById(@Param("id") String id);
|
||||||
|
|
||||||
|
PqIcdPath selectExportById(@Param("id") String id);
|
||||||
|
|
||||||
|
List<PqIcdExportJsonVO> selectExportJsonByIds(@Param("ids") List<String> ids);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,135 @@
|
|||||||
|
|
||||||
|
|
||||||
<select id="selectIcdByDevType" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
<select id="selectIcdByDevType" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
select *
|
select path.*
|
||||||
from pq_icd_path path
|
from pq_icd_path path
|
||||||
inner join pq_dev_type type on path.id = type.icd
|
inner join pq_dev_type type on path.id = type.icd
|
||||||
where type.id = #{devTypeId}
|
where type.id = #{devTypeId}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="selectPageList" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select p.id,
|
||||||
|
p.name,
|
||||||
|
p.state,
|
||||||
|
p.angle,
|
||||||
|
p.use_phase_index as usePhaseIndex,
|
||||||
|
p.Json_Str as jsonStr,
|
||||||
|
p.Xml_Str as xmlStr,
|
||||||
|
p.Result as result,
|
||||||
|
p.Msg as msg,
|
||||||
|
p.Type as type,
|
||||||
|
p.Reference_Icd_Id as referenceIcdId,
|
||||||
|
ref.name as referenceIcdName,
|
||||||
|
case when p.Icd is null then false else true end as hasIcdFile,
|
||||||
|
p.create_by as createBy,
|
||||||
|
p.create_time as createTime,
|
||||||
|
p.update_by as updateBy,
|
||||||
|
p.update_time as updateTime
|
||||||
|
from pq_icd_path p
|
||||||
|
left join pq_icd_path ref on p.Reference_Icd_Id = ref.id
|
||||||
|
and ref.state = 1
|
||||||
|
and ref.Type in (1, 3)
|
||||||
|
where p.state = 1
|
||||||
|
<if test="name != null and name != ''">
|
||||||
|
and p.name like concat('%', #{name}, '%')
|
||||||
|
</if>
|
||||||
|
order by p.create_time desc
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectStandardList" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select id, name, Type as type
|
||||||
|
from pq_icd_path
|
||||||
|
where state = 1
|
||||||
|
and Type in (1, 3)
|
||||||
|
order by create_time desc
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectStandardByName" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select id, name, Type as type, state
|
||||||
|
from pq_icd_path
|
||||||
|
where state = 1
|
||||||
|
and Type in (1, 3)
|
||||||
|
and name = #{name}
|
||||||
|
limit 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectByIdsWithoutBlob" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select id, name, Type as type, state
|
||||||
|
from pq_icd_path
|
||||||
|
where id in
|
||||||
|
<foreach collection="ids" item="id" open="(" separator="," close=")">
|
||||||
|
#{id}
|
||||||
|
</foreach>
|
||||||
|
and state = 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="countActiveReferencesToStandards" resultType="java.lang.Long">
|
||||||
|
select count(1)
|
||||||
|
from pq_icd_path
|
||||||
|
where state = 1
|
||||||
|
and Type in (2, 4)
|
||||||
|
and Reference_Icd_Id in
|
||||||
|
<foreach collection="standardIds" item="id" open="(" separator="," close=")">
|
||||||
|
#{id}
|
||||||
|
</foreach>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectDetailById" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select p.id,
|
||||||
|
p.name,
|
||||||
|
p.state,
|
||||||
|
p.angle,
|
||||||
|
p.use_phase_index as usePhaseIndex,
|
||||||
|
p.Json_Str as jsonStr,
|
||||||
|
p.Xml_Str as xmlStr,
|
||||||
|
p.Result as result,
|
||||||
|
p.Msg as msg,
|
||||||
|
p.Type as type,
|
||||||
|
p.Reference_Icd_Id as referenceIcdId,
|
||||||
|
ref.name as referenceIcdName,
|
||||||
|
case when p.Icd is null then false else true end as hasIcdFile,
|
||||||
|
p.create_by as createBy,
|
||||||
|
p.create_time as createTime,
|
||||||
|
p.update_by as updateBy,
|
||||||
|
p.update_time as updateTime
|
||||||
|
from pq_icd_path p
|
||||||
|
left join pq_icd_path ref on p.Reference_Icd_Id = ref.id
|
||||||
|
and ref.state = 1
|
||||||
|
and ref.Type in (1, 3)
|
||||||
|
where p.id = #{id}
|
||||||
|
and p.state = 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectExportById" resultType="com.njcn.gather.icd.pojo.po.PqIcdPath">
|
||||||
|
select id,
|
||||||
|
name,
|
||||||
|
state,
|
||||||
|
Json_Str as jsonStr,
|
||||||
|
Xml_Str as xmlStr,
|
||||||
|
Icd as icd
|
||||||
|
from pq_icd_path
|
||||||
|
where id = #{id}
|
||||||
|
and state = 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectExportJsonByIds" resultType="com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO">
|
||||||
|
select id,
|
||||||
|
name,
|
||||||
|
Icd as rawIcd,
|
||||||
|
angle,
|
||||||
|
use_phase_index as usePhaseIndex,
|
||||||
|
Json_Str as jsonStr,
|
||||||
|
Xml_Str as xmlStr,
|
||||||
|
Result as result,
|
||||||
|
Msg as msg,
|
||||||
|
Type as type,
|
||||||
|
Reference_Icd_Id as referenceIcdId
|
||||||
|
from pq_icd_path
|
||||||
|
where state = 1
|
||||||
|
and id in
|
||||||
|
<foreach collection="ids" item="id" open="(" separator="," close=")">
|
||||||
|
#{id}
|
||||||
|
</foreach>
|
||||||
|
</select>
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,45 @@
|
|||||||
package com.njcn.gather.icd.pojo.enums;
|
package com.njcn.gather.icd.pojo.enums;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
* @data 2025-11-11
|
* @data 2025-11-11
|
||||||
*/
|
*/
|
||||||
|
@Getter
|
||||||
public enum IcdResponseEnum {
|
public enum IcdResponseEnum {
|
||||||
FILE_NOT_NULL("A018001", "映射文件不能为空"),
|
FILE_NOT_NULL("A018001", "映射文件不能为空"),
|
||||||
FILE_TYPE_ERROR("A018002", "映射文件类型错误"),
|
FILE_TYPE_ERROR("A018002", "映射文件类型错误"),
|
||||||
FILE_SIZE_ERROR("A018003", "映射文件大小超出限制");
|
FILE_SIZE_ERROR("A018003", "映射文件大小超出限制"),
|
||||||
|
ICD_FILE_NOT_NULL("A018004", "ICD原始文件不能为空"),
|
||||||
|
ICD_FILE_TYPE_ERROR("A018005", "ICD原始文件类型错误"),
|
||||||
|
ICD_FILE_READ_ERROR("A018006", "ICD原始文件读取失败"),
|
||||||
|
JSON_FORMAT_ERROR("A018007", "JSON格式错误"),
|
||||||
|
XML_FORMAT_ERROR("A018008", "XML格式错误"),
|
||||||
|
STANDARD_ICD_IN_USE("A018009", "该标准ICD已被非标准ICD引用,禁止删除"),
|
||||||
|
ICD_FILE_NOT_FOUND("A018010", "ICD原始文件不存在"),
|
||||||
|
ICD_EXPORT_FAILED("A018011", "ICD导出失败"),
|
||||||
|
ICD_NOT_FOUND("A018012", "ICD不存在"),
|
||||||
|
RESULT_NOT_NULL("A018013", "结论不能为空"),
|
||||||
|
MSG_NOT_BLANK("A018014", "当结论为否时,描述不能为空"),
|
||||||
|
TYPE_NOT_NULL("A018015", "ICD类型不能为空"),
|
||||||
|
TYPE_VALUE_ERROR("A018016", "ICD类型取值错误"),
|
||||||
|
REFERENCE_ICD_NOT_BLANK("A018017", "非标准ICD必须选择参照标准ICD"),
|
||||||
|
REFERENCE_ICD_INVALID("A018018", "参照标准ICD无效"),
|
||||||
|
GENERATE_FILE("A018019", "文件生成失败"),
|
||||||
|
ICD_TXT_SYNC_FAILED("A018020", "ICD txt文件同步失败"),
|
||||||
|
REFERENCE_STANDARD_ICD_NAME_NOT_FOUND("A018021", "参照标准ICD名称不存在"),
|
||||||
|
EXTERNAL_ICD_ITEM_NOT_NULL("A018022", "导入数据项不能为空"),
|
||||||
|
EXTERNAL_ICD_ID_REPEAT("A018023", "导入数据中存在重复id"),
|
||||||
|
EXTERNAL_ICD_DELETED_NOT_ALLOW_OVERWRITE("A018024", "该ICD已删除,不允许通过导入覆盖"),
|
||||||
|
EXTERNAL_ICD_IMPORT_FAILED("A018025", "ICD导入失败"),
|
||||||
|
ANGLE_NOT_NULL("A018026", "是否支持相角不能为空"),
|
||||||
|
ANGLE_VALUE_ERROR("A018027", "是否支持相角取值错误"),
|
||||||
|
USE_PHASE_INDEX_NOT_NULL("A018028", "是否使用相别指标不能为空"),
|
||||||
|
USE_PHASE_INDEX_VALUE_ERROR("A018029", "是否使用相别指标取值错误");
|
||||||
|
|
||||||
private String code;
|
private final String code;
|
||||||
private String message;
|
private final String message;
|
||||||
|
|
||||||
IcdResponseEnum(String code, String message) {
|
IcdResponseEnum(String code, String message) {
|
||||||
this.code = code;
|
this.code = code;
|
||||||
|
|||||||
@@ -17,39 +17,63 @@ import javax.validation.constraints.Pattern;
|
|||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class PqIcdPathParam {
|
public class PqIcdPathParam {
|
||||||
@ApiModelProperty(value = "名称", required = true)
|
@ApiModelProperty(value = "angle", required = true)
|
||||||
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
|
|
||||||
@Pattern(regexp = PatternRegex.ICD_NAME_REGEX, message = DetectionValidMessage.ICD_NAME_FORMAT_ERROR)
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
@ApiModelProperty(value = "存储路径", required = true)
|
|
||||||
@NotBlank(message = DetectionValidMessage.ICD_PATH_NOT_BLANK)
|
|
||||||
@Pattern(regexp = PatternRegex.ICD_PATH_REGEX, message = DetectionValidMessage.ICD_PATH_FORMAT_ERROR)
|
|
||||||
private String path;
|
|
||||||
|
|
||||||
@ApiModelProperty(value = "是否支持电压相角、电流相角指标,0表示否,1表示是", required = true)
|
|
||||||
private Integer angle;
|
private Integer angle;
|
||||||
|
|
||||||
@ApiModelProperty(value = "角型接线时是否使用相别的指标来进行检测,0表示否,1表示是", required = true)
|
@ApiModelProperty(value = "usePhaseIndex", required = true)
|
||||||
private Integer usePhaseIndex;
|
private Integer usePhaseIndex;
|
||||||
|
|
||||||
@ApiModelProperty(value = "映射文件", required = true)
|
@ApiModelProperty(value = "jsonStr")
|
||||||
private MultipartFile mappingFile;
|
private String jsonStr;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "xmlStr")
|
||||||
|
private String xmlStr;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "result")
|
||||||
|
private Integer result;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "msg")
|
||||||
|
private String msg;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "type")
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "referenceIcdId")
|
||||||
|
private String referenceIcdId;
|
||||||
|
|
||||||
/**
|
|
||||||
* 分页查询实体
|
|
||||||
*/
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
public static class QueryParam extends BaseParam {
|
public static class QueryParam extends BaseParam {
|
||||||
@ApiModelProperty(value = "名称", required = true)
|
@ApiModelProperty(value = "name", required = true)
|
||||||
private String name;
|
private String name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public static class CreateParam extends PqIcdPathParam {
|
||||||
|
@ApiModelProperty(value = "icdFile", required = true)
|
||||||
|
private MultipartFile icdFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public static class ExternalCreateParam extends PqIcdPathParam {
|
||||||
|
@ApiModelProperty(value = "id", required = true)
|
||||||
|
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
|
||||||
|
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "name", required = true)
|
||||||
|
@NotBlank(message = DetectionValidMessage.NAME_NOT_BLANK)
|
||||||
|
@Pattern(regexp = PatternRegex.SCRIPT_NAME_REGEX, message = DetectionValidMessage.ICD_NAME_FORMAT_ERROR)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "icd", required = true)
|
||||||
|
@NotBlank(message = IcdExternalValidMessage.ICD_FILE_NOT_BLANK)
|
||||||
|
private String icd;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新参数
|
|
||||||
*/
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
public static class UpdateParam extends PqIcdPathParam {
|
public static class UpdateParam extends PqIcdPathParam {
|
||||||
@@ -57,5 +81,12 @@ public class PqIcdPathParam {
|
|||||||
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
|
@NotBlank(message = DetectionValidMessage.ID_NOT_BLANK)
|
||||||
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
|
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "icdFile")
|
||||||
|
private MultipartFile icdFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
private interface IcdExternalValidMessage {
|
||||||
|
String ICD_FILE_NOT_BLANK = "ICD原始文件不能为空";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,6 @@ public class PqIcdPath extends BaseEntity implements Serializable {
|
|||||||
*/
|
*/
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
/**
|
|
||||||
* icd存储地址
|
|
||||||
*/
|
|
||||||
private String path;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 状态:0-删除 1-正常
|
* 状态:0-删除 1-正常
|
||||||
*/
|
*/
|
||||||
@@ -46,19 +41,55 @@ public class PqIcdPath extends BaseEntity implements Serializable {
|
|||||||
/**
|
/**
|
||||||
* 角型接线时是否使用相别的指标来进行检测,0表示否,1表示是
|
* 角型接线时是否使用相别的指标来进行检测,0表示否,1表示是
|
||||||
*/
|
*/
|
||||||
|
@TableField("use_phase_index")
|
||||||
private Integer usePhaseIndex;
|
private Integer usePhaseIndex;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 映射文件路径
|
* 解析后的json字符串
|
||||||
*/
|
*/
|
||||||
|
@TableField("Json_Str")
|
||||||
|
private String jsonStr;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析后的xml字符串
|
||||||
|
*/
|
||||||
|
@TableField("Xml_Str")
|
||||||
|
private String xmlStr;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ICD原始文件二进制
|
||||||
|
*/
|
||||||
|
@TableField("Icd")
|
||||||
|
private byte[] icd;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结论
|
||||||
|
*/
|
||||||
|
@TableField("Result")
|
||||||
|
private Integer result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结论描述
|
||||||
|
*/
|
||||||
|
@TableField("Msg")
|
||||||
|
private String msg;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ICD类型
|
||||||
|
*/
|
||||||
|
@TableField("Type")
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 参照标准ICD
|
||||||
|
*/
|
||||||
|
@TableField("Reference_Icd_Id")
|
||||||
|
private String referenceIcdId;
|
||||||
|
|
||||||
@TableField(exist = false)
|
@TableField(exist = false)
|
||||||
private FileVO mappingFile;
|
private String referenceIcdName;
|
||||||
|
|
||||||
@Data
|
@TableField(exist = false)
|
||||||
public static class FileVO{
|
private Boolean hasIcdFile;
|
||||||
private String name;
|
|
||||||
|
|
||||||
private String url;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.njcn.gather.icd.pojo.vo;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.annotation.JSONField;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ICD JSON export item.
|
||||||
|
*
|
||||||
|
* @author caozehui
|
||||||
|
* @date 2026-06-17
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class PqIcdExportJsonVO {
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@JSONField(serialize = false)
|
||||||
|
private byte[] rawIcd;
|
||||||
|
|
||||||
|
private String icd;
|
||||||
|
|
||||||
|
private Integer angle;
|
||||||
|
|
||||||
|
private Integer usePhaseIndex;
|
||||||
|
|
||||||
|
private String jsonStr;
|
||||||
|
|
||||||
|
private String xmlStr;
|
||||||
|
|
||||||
|
private Integer result;
|
||||||
|
|
||||||
|
private String msg;
|
||||||
|
|
||||||
|
private Integer type;
|
||||||
|
|
||||||
|
private String referenceIcdId;
|
||||||
|
}
|
||||||
@@ -28,13 +28,22 @@ public interface IPqIcdPathService extends IService<PqIcdPath> {
|
|||||||
*/
|
*/
|
||||||
Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param);
|
Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有标准ICD
|
||||||
|
*
|
||||||
|
* @return 标准ICD列表
|
||||||
|
*/
|
||||||
|
List<PqIcdPath> listStandardIcd();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 新增Icd
|
* 新增Icd
|
||||||
*
|
*
|
||||||
* @param param 新增Icd参数
|
* @param param 新增Icd参数
|
||||||
* @return 成功返回true,失败返回false
|
* @return 成功返回true,失败返回false
|
||||||
*/
|
*/
|
||||||
boolean addIcd(PqIcdPathParam param);
|
boolean addIcd(PqIcdPathParam.CreateParam param);
|
||||||
|
|
||||||
|
boolean addUpstreamIcd(List<PqIcdPathParam.ExternalCreateParam> param);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修改Icd
|
* 修改Icd
|
||||||
@@ -52,6 +61,24 @@ public interface IPqIcdPathService extends IService<PqIcdPath> {
|
|||||||
*/
|
*/
|
||||||
boolean deleteIcd(List<String> ids);
|
boolean deleteIcd(List<String> ids);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据id获取ICD详情
|
||||||
|
*
|
||||||
|
* @param id ICD id
|
||||||
|
* @return ICD详情
|
||||||
|
*/
|
||||||
|
PqIcdPath getIcdById(String id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出ICD压缩包
|
||||||
|
*
|
||||||
|
* @param id ICD id
|
||||||
|
* @return zip字节数组
|
||||||
|
*/
|
||||||
|
byte[] exportIcd(String id);
|
||||||
|
|
||||||
|
byte[] exportIcdJson(List<String> ids);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据设备类型id获取Icd
|
* 根据设备类型id获取Icd
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,34 +1,42 @@
|
|||||||
package com.njcn.gather.icd.service.impl;
|
package com.njcn.gather.icd.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.collection.CollUtil;
|
||||||
import cn.hutool.core.util.ObjectUtil;
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
|
import cn.hutool.core.util.ReUtil;
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
||||||
import com.njcn.common.pojo.exception.BusinessException;
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.common.pojo.constant.PatternRegex;
|
||||||
import com.njcn.gather.icd.mapper.PqIcdPathMapper;
|
import com.njcn.gather.icd.mapper.PqIcdPathMapper;
|
||||||
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
||||||
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
|
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
|
||||||
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
||||||
|
import com.njcn.gather.icd.pojo.vo.PqIcdExportJsonVO;
|
||||||
|
import com.njcn.gather.pojo.constant.DetectionValidMessage;
|
||||||
import com.njcn.gather.icd.service.IPqIcdPathService;
|
import com.njcn.gather.icd.service.IPqIcdPathService;
|
||||||
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
import com.njcn.gather.icd.service.support.IcdArchiveBuilder;
|
||||||
import com.njcn.gather.report.pojo.enums.ReportResponseEnum;
|
import com.njcn.gather.icd.service.support.IcdPayloadAssembler;
|
||||||
import com.njcn.web.factory.PageFactory;
|
import com.njcn.web.factory.PageFactory;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
import java.io.BufferedOutputStream;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author caozehui
|
* @author caozehui
|
||||||
@@ -38,174 +46,165 @@ import java.util.List;
|
|||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath> implements IPqIcdPathService {
|
public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath> implements IPqIcdPathService {
|
||||||
|
// 手动录入标准ICD
|
||||||
|
private static final int TYPE_STANDARD = 1;
|
||||||
|
// 手动录入非标准ICD
|
||||||
|
private static final int TYPE_NON_STANDARD = 2;
|
||||||
|
// 上游录入的标准ICD
|
||||||
|
private static final int TYPE_UPSTREAM_STANDARD = 3;
|
||||||
|
|
||||||
|
// 上游录入的非标准ICD
|
||||||
|
private static final int TYPE_UPSTREAM_NON_STANDARD = 4;
|
||||||
|
private static final int RESULT_NO = 0;
|
||||||
|
private static final int RESULT_YES = 1;
|
||||||
|
|
||||||
|
@Value("${icd.txt-dir}")
|
||||||
|
private String icdTxtDir;
|
||||||
|
|
||||||
|
private final IcdPayloadAssembler icdPayloadAssembler;
|
||||||
|
private final IcdArchiveBuilder icdArchiveBuilder;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<PqIcdPath> listAll() {
|
public List<PqIcdPath> listAll() {
|
||||||
return this.lambdaQuery().eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode()).list();
|
return this.lambdaQuery()
|
||||||
|
.select(PqIcdPath::getId, PqIcdPath::getName, PqIcdPath::getType, PqIcdPath::getReferenceIcdId)
|
||||||
|
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
|
||||||
|
.orderByDesc(PqIcdPath::getCreateTime)
|
||||||
|
.list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<PqIcdPath> listStandardIcd() {
|
||||||
|
return this.baseMapper.selectStandardList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param) {
|
public Page<PqIcdPath> listIcd(PqIcdPathParam.QueryParam param) {
|
||||||
LambdaQueryWrapper<PqIcdPath> wrapper = new LambdaQueryWrapper<>();
|
Page<PqIcdPath> page = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param));
|
||||||
wrapper.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
|
page.setRecords(this.baseMapper.selectPageList(page, StrUtil.trim(param.getName())));
|
||||||
.like(StrUtil.isNotBlank(param.getName()), PqIcdPath::getName, param.getName())
|
|
||||||
.orderByDesc(PqIcdPath::getCreateTime);
|
|
||||||
Page<PqIcdPath> page = this.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), wrapper);
|
|
||||||
String commInstallPath = this.getCommInstallPath();
|
|
||||||
page.getRecords().forEach(pqIcdPath -> {
|
|
||||||
PqIcdPath.FileVO fileVO = new PqIcdPath.FileVO();
|
|
||||||
fileVO.setUrl(commInstallPath + "\\DeviceControl\\Config\\" + pqIcdPath.getName() + ".txt");
|
|
||||||
fileVO.setName(pqIcdPath.getName() + ".txt");
|
|
||||||
pqIcdPath.setMappingFile(fileVO);
|
|
||||||
});
|
|
||||||
return page;
|
return page;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public boolean addIcd(PqIcdPathParam param) {
|
public boolean addIcd(PqIcdPathParam.CreateParam param) {
|
||||||
param.setName(param.getName().trim());
|
validateBusinessFields(param, null);
|
||||||
this.checkRepeat(param, false);
|
PqIcdPath pqIcdPath = icdPayloadAssembler.fromCreate(param);
|
||||||
PqIcdPath pqIcdPath = new PqIcdPath();
|
validateReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), null);
|
||||||
BeanUtils.copyProperties(param, pqIcdPath);
|
boolean saved = this.save(pqIcdPath);
|
||||||
pqIcdPath.setState(DataStateEnum.ENABLE.getCode());
|
if (saved) {
|
||||||
|
writeIcdTextFile(resolveIcdTxtDir(), pqIcdPath.getName(), pqIcdPath.getJsonStr());
|
||||||
String commInstallPath = this.getCommInstallPath();
|
|
||||||
System.out.println("commInstallPath = " + commInstallPath);
|
|
||||||
long FILE_SIZE_LIMIT = 1 * 1024 * 1024;
|
|
||||||
MultipartFile mappingFile = param.getMappingFile();
|
|
||||||
|
|
||||||
System.out.println("mappingFile = " + ObjectUtil.isNotNull(mappingFile) + " " + !mappingFile.isEmpty());
|
|
||||||
if (ObjectUtil.isNotNull(mappingFile) && !mappingFile.isEmpty()) {
|
|
||||||
String mappingFilename = mappingFile.getOriginalFilename();
|
|
||||||
|
|
||||||
if (!mappingFilename.endsWith(".txt")) {
|
|
||||||
throw new BusinessException(IcdResponseEnum.FILE_TYPE_ERROR);
|
|
||||||
}
|
|
||||||
if (mappingFile.getSize() > FILE_SIZE_LIMIT) {
|
|
||||||
throw new BusinessException(IcdResponseEnum.FILE_SIZE_ERROR);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 如果文件存在,则先删除
|
|
||||||
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + mappingFilename;
|
|
||||||
System.out.println("mappingFilePath = " + mappingFilePath);
|
|
||||||
Path path = Paths.get(mappingFilePath);
|
|
||||||
File file = path.toFile();
|
|
||||||
if (file.exists()) {
|
|
||||||
file.delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 保存文件
|
|
||||||
byte[] bytes = mappingFile.getBytes();
|
|
||||||
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(mappingFilePath));
|
|
||||||
bufferedOutputStream.write(bytes);
|
|
||||||
bufferedOutputStream.flush();
|
|
||||||
|
|
||||||
bufferedOutputStream.close();
|
|
||||||
System.out.println("File saved successfully");
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new BusinessException(ReportResponseEnum.FILE_UPLOAD_FAILED);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.out.println("mappingFile is null or empty");
|
|
||||||
throw new BusinessException(IcdResponseEnum.FILE_NOT_NULL);
|
|
||||||
}
|
}
|
||||||
|
return saved;
|
||||||
this.executeRestartCmd(commInstallPath);
|
|
||||||
|
|
||||||
return this.save(pqIcdPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
@Override
|
||||||
* 执行重启通讯服务脚本
|
@Transactional
|
||||||
*
|
public boolean addUpstreamIcd(List<PqIcdPathParam.ExternalCreateParam> param) {
|
||||||
* @param commInstallPath
|
if (CollUtil.isEmpty(param)) {
|
||||||
*/
|
return true;
|
||||||
private void executeRestartCmd(String commInstallPath) {
|
|
||||||
// 以管理员身份运行bat脚本
|
|
||||||
String batFilePath = commInstallPath + "\\重启所有服务.bat";
|
|
||||||
try {
|
|
||||||
Runtime.getRuntime().exec(batFilePath);
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("重启通讯服务失败", e);
|
|
||||||
}
|
}
|
||||||
}
|
validateExternalItems(param);
|
||||||
|
Set<String> requestStandardIds = collectRequestStandardIds(param);
|
||||||
private String getCommInstallPath() {
|
Path directory = resolveIcdTxtDir();
|
||||||
String workDir = System.getProperty("user.dir");
|
for (PqIcdPathParam.ExternalCreateParam item : param) {
|
||||||
// String workDir = "D:\\program\\CN_Gather";
|
validateBusinessFields(item, null);
|
||||||
// 获取映射文件存放文件夹
|
PqIcdPath current = this.baseMapper.selectById(item.getId());
|
||||||
String dirPath = workDir + "\\9100";
|
if (current != null && !ObjectUtil.equals(current.getState(), DataStateEnum.ENABLE.getCode())) {
|
||||||
int index = workDir.indexOf("\\resources\\extraResources\\java");
|
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_DELETED_NOT_ALLOW_OVERWRITE);
|
||||||
if (index != -1) {
|
}
|
||||||
dirPath = workDir.substring(0, workDir.indexOf("\\resources\\extraResources\\java")) + "\\9100";
|
PqIcdPath pqIcdPath = icdPayloadAssembler.fromExternalCreate(item, item.getType(), item.getAngle(), item.getUsePhaseIndex());
|
||||||
|
String currentId = current == null ? null : current.getId();
|
||||||
|
String oldName = current == null ? null : current.getName();
|
||||||
|
validateExternalReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), currentId, requestStandardIds);
|
||||||
|
boolean saved = current == null ? this.save(pqIcdPath) : this.updateById(pqIcdPath);
|
||||||
|
if (!saved) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_IMPORT_FAILED);
|
||||||
|
}
|
||||||
|
if (current == null) {
|
||||||
|
writeIcdTextFile(directory, pqIcdPath.getName(), pqIcdPath.getJsonStr());
|
||||||
|
} else {
|
||||||
|
syncUpdatedIcdTextFile(directory, oldName, pqIcdPath.getName(), pqIcdPath.getJsonStr());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return dirPath;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public boolean updateIcd(PqIcdPathParam.UpdateParam param) {
|
public boolean updateIcd(PqIcdPathParam.UpdateParam param) {
|
||||||
param.setName(param.getName().trim());
|
PqIcdPath current = getActiveEntity(param.getId());
|
||||||
this.checkRepeat(param, true);
|
String oldName = current.getName();
|
||||||
PqIcdPath pqIcdPath = new PqIcdPath();
|
validateBusinessFields(param, current.getId());
|
||||||
BeanUtils.copyProperties(param, pqIcdPath);
|
PqIcdPath pqIcdPath = icdPayloadAssembler.merge(current, param);
|
||||||
|
validateReferenceIcd(pqIcdPath.getType(), pqIcdPath.getReferenceIcdId(), current.getId());
|
||||||
String commInstallPath = this.getCommInstallPath();
|
boolean updated = this.updateById(pqIcdPath);
|
||||||
long FILE_SIZE_LIMIT = 1 * 1024 * 1024;
|
if (updated) {
|
||||||
MultipartFile mappingFile = param.getMappingFile();
|
syncUpdatedIcdTextFile(resolveIcdTxtDir(), oldName, pqIcdPath.getName(), pqIcdPath.getJsonStr());
|
||||||
if (ObjectUtil.isNotNull(mappingFile) && !mappingFile.isEmpty()) {
|
|
||||||
String mappingFilename = mappingFile.getOriginalFilename();
|
|
||||||
|
|
||||||
if (!mappingFilename.endsWith(".txt")) {
|
|
||||||
throw new BusinessException(IcdResponseEnum.FILE_TYPE_ERROR);
|
|
||||||
}
|
|
||||||
if (mappingFile.getSize() > FILE_SIZE_LIMIT) {
|
|
||||||
throw new BusinessException(IcdResponseEnum.FILE_SIZE_ERROR);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 如果文件存在,则先删除
|
|
||||||
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + mappingFilename;
|
|
||||||
Path path = Paths.get(mappingFilePath);
|
|
||||||
File file = path.toFile();
|
|
||||||
if (file.exists()) {
|
|
||||||
file.delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 保存文件
|
|
||||||
byte[] bytes = mappingFile.getBytes();
|
|
||||||
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(mappingFilePath));
|
|
||||||
bufferedOutputStream.write(bytes);
|
|
||||||
bufferedOutputStream.flush();
|
|
||||||
|
|
||||||
bufferedOutputStream.close();
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new BusinessException(ReportResponseEnum.FILE_UPLOAD_FAILED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return updated;
|
||||||
this.executeRestartCmd(commInstallPath);
|
|
||||||
|
|
||||||
return this.updateById(pqIcdPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public boolean deleteIcd(List<String> ids) {
|
public boolean deleteIcd(List<String> ids) {
|
||||||
List<PqIcdPath> pqIcdPaths = this.listByIds(ids);
|
if (CollUtil.isEmpty(ids)) {
|
||||||
String commInstallPath = this.getCommInstallPath();
|
return true;
|
||||||
pqIcdPaths.forEach(pqIcdPath -> {
|
}
|
||||||
String mappingFilePath = commInstallPath + "\\DeviceControl\\Config\\" + pqIcdPath.getName() + ".txt";
|
List<PqIcdPath> pqIcdPaths = this.baseMapper.selectByIdsWithoutBlob(ids);
|
||||||
Path path = Paths.get(mappingFilePath);
|
List<String> standardIds = pqIcdPaths.stream()
|
||||||
File file = path.toFile();
|
.filter(pqIcdPath -> ObjectUtil.equals(pqIcdPath.getType(), TYPE_STANDARD))
|
||||||
if (file.exists()) {
|
.map(PqIcdPath::getId)
|
||||||
file.delete();
|
.collect(Collectors.toList());
|
||||||
|
if (!standardIds.isEmpty()) {
|
||||||
|
Long count = this.baseMapper.countActiveReferencesToStandards(standardIds);
|
||||||
|
if (ObjectUtil.isNotNull(count) && count > 0) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.STANDARD_ICD_IN_USE);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
return this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
|
boolean deleted = this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
|
||||||
|
if (deleted) {
|
||||||
|
Path directory = resolveIcdTxtDir();
|
||||||
|
for (PqIcdPath pqIcdPath : pqIcdPaths) {
|
||||||
|
deleteIcdTextFile(directory, pqIcdPath.getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PqIcdPath getIcdById(String id) {
|
||||||
|
PqIcdPath detail = this.baseMapper.selectDetailById(id);
|
||||||
|
if (ObjectUtil.isNull(detail)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
|
||||||
|
}
|
||||||
|
return detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] exportIcd(String id) {
|
||||||
|
PqIcdPath detail = this.baseMapper.selectExportById(id);
|
||||||
|
if (ObjectUtil.isNull(detail)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
|
||||||
|
}
|
||||||
|
return icdArchiveBuilder.build(detail);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] exportIcdJson(List<String> ids) {
|
||||||
|
if (CollUtil.isEmpty(ids)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
|
||||||
|
}
|
||||||
|
List<PqIcdExportJsonVO> details = this.baseMapper.selectExportJsonByIds(ids);
|
||||||
|
if (CollUtil.isEmpty(details)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
|
||||||
|
}
|
||||||
|
for (PqIcdExportJsonVO detail : details) {
|
||||||
|
detail.setIcd(encodeIcdFile(detail.getRawIcd()));
|
||||||
|
normalizeExportDetail(detail);
|
||||||
|
}
|
||||||
|
return JSON.toJSONString(details).getBytes(StandardCharsets.UTF_8);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -213,18 +212,188 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
|
|||||||
return this.baseMapper.selectIcdByDevType(devTypeId);
|
return this.baseMapper.selectIcdByDevType(devTypeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkRepeat(PqIcdPathParam param, boolean isExcludeSelf) {
|
private void validateBusinessFields(PqIcdPathParam param, String currentId) {
|
||||||
LambdaQueryWrapper<PqIcdPath> wrapper = new LambdaQueryWrapper<>();
|
if (ObjectUtil.isNull(param.getResult())) {
|
||||||
wrapper.eq(PqIcdPath::getName, param.getName())
|
throw new BusinessException(IcdResponseEnum.RESULT_NOT_NULL);
|
||||||
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode());
|
|
||||||
if (isExcludeSelf) {
|
|
||||||
if (param instanceof PqIcdPathParam.UpdateParam) {
|
|
||||||
wrapper.ne(PqIcdPath::getId, ((PqIcdPathParam.UpdateParam) param).getId());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
int count = this.count(wrapper);
|
if (ObjectUtil.equals(param.getResult(), RESULT_NO) && StrUtil.isBlank(param.getMsg())) {
|
||||||
if (count > 0) {
|
throw new BusinessException(IcdResponseEnum.MSG_NOT_BLANK);
|
||||||
throw new BusinessException(DetectionResponseEnum.ICD_PATH_NAME_REPEAT);
|
}
|
||||||
|
if (ObjectUtil.isNull(param.getType())) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.TYPE_NOT_NULL);
|
||||||
|
}
|
||||||
|
if (!ObjectUtil.equals(param.getType(), TYPE_STANDARD)
|
||||||
|
&& !ObjectUtil.equals(param.getType(), TYPE_NON_STANDARD)
|
||||||
|
&& !ObjectUtil.equals(param.getType(), TYPE_UPSTREAM_STANDARD)
|
||||||
|
&& !ObjectUtil.equals(param.getType(), TYPE_UPSTREAM_NON_STANDARD)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.TYPE_VALUE_ERROR);
|
||||||
|
}
|
||||||
|
if (requiresReferenceIcd(param.getType()) && StrUtil.isBlank(param.getReferenceIcdId())) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_NOT_BLANK);
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, StrUtil.trim(param.getReferenceIcdId()))) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void validateReferenceIcd(Integer type, String referenceIcdId, String currentId) {
|
||||||
|
if (!requiresReferenceIcd(type)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, referenceIcdId)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
|
||||||
|
}
|
||||||
|
long count = this.lambdaQuery()
|
||||||
|
.eq(PqIcdPath::getId, referenceIcdId)
|
||||||
|
.in(PqIcdPath::getType, TYPE_STANDARD, TYPE_UPSTREAM_STANDARD)
|
||||||
|
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
|
||||||
|
.count();
|
||||||
|
if (count <= 0L) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateExternalReferenceIcd(Integer type, String referenceIcdId, String currentId, Set<String> requestStandardIds) {
|
||||||
|
if (!requiresReferenceIcd(type)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String trimmedReferenceId = StrUtil.trim(referenceIcdId);
|
||||||
|
if (StrUtil.isNotBlank(currentId) && StrUtil.equals(currentId, trimmedReferenceId)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.REFERENCE_ICD_INVALID);
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(trimmedReferenceId) && requestStandardIds.contains(trimmedReferenceId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
validateReferenceIcd(type, trimmedReferenceId, currentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> collectRequestStandardIds(List<PqIcdPathParam.ExternalCreateParam> params) {
|
||||||
|
Set<String> ids = new HashSet<>();
|
||||||
|
for (PqIcdPathParam.ExternalCreateParam param : params) {
|
||||||
|
if (isStandardType(param.getType()) && StrUtil.isNotBlank(param.getId())) {
|
||||||
|
ids.add(StrUtil.trim(param.getId()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateExternalItems(List<PqIcdPathParam.ExternalCreateParam> params) {
|
||||||
|
Set<String> ids = new HashSet<>();
|
||||||
|
for (PqIcdPathParam.ExternalCreateParam param : params) {
|
||||||
|
if (param == null) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_ITEM_NOT_NULL);
|
||||||
|
}
|
||||||
|
validateExternalItem(param);
|
||||||
|
String trimmedId = StrUtil.trim(param.getId());
|
||||||
|
if (!ids.add(trimmedId)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.EXTERNAL_ICD_ID_REPEAT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateExternalItem(PqIcdPathParam.ExternalCreateParam param) {
|
||||||
|
if (StrUtil.isBlank(param.getId())) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.ID_NOT_BLANK);
|
||||||
|
}
|
||||||
|
if (!ReUtil.isMatch(PatternRegex.SYSTEM_ID, StrUtil.trim(param.getId()))) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.ID_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
if (StrUtil.isBlank(param.getName())) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.NAME_NOT_BLANK);
|
||||||
|
}
|
||||||
|
if (!ReUtil.isMatch(PatternRegex.SCRIPT_NAME_REGEX, StrUtil.trim(param.getName()))) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.ICD_NAME_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
if (StrUtil.isBlank(param.getIcd())) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
|
||||||
|
}
|
||||||
|
if (ObjectUtil.isNull(param.getAngle())) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ANGLE_NOT_NULL);
|
||||||
|
}
|
||||||
|
if (!ObjectUtil.equals(param.getAngle(), 0) && !ObjectUtil.equals(param.getAngle(), 1)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ANGLE_VALUE_ERROR);
|
||||||
|
}
|
||||||
|
if (ObjectUtil.isNull(param.getUsePhaseIndex())) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.USE_PHASE_INDEX_NOT_NULL);
|
||||||
|
}
|
||||||
|
if (!ObjectUtil.equals(param.getUsePhaseIndex(), 0) && !ObjectUtil.equals(param.getUsePhaseIndex(), 1)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.USE_PHASE_INDEX_VALUE_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean requiresReferenceIcd(Integer type) {
|
||||||
|
return ObjectUtil.equals(type, TYPE_NON_STANDARD) || ObjectUtil.equals(type, TYPE_UPSTREAM_NON_STANDARD);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isStandardType(Integer type) {
|
||||||
|
return ObjectUtil.equals(type, TYPE_STANDARD) || ObjectUtil.equals(type, TYPE_UPSTREAM_STANDARD);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PqIcdPath getActiveEntity(String id) {
|
||||||
|
PqIcdPath current = this.lambdaQuery()
|
||||||
|
.eq(PqIcdPath::getId, id)
|
||||||
|
.eq(PqIcdPath::getState, DataStateEnum.ENABLE.getCode())
|
||||||
|
.one();
|
||||||
|
if (ObjectUtil.isNull(current)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_NOT_FOUND);
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
Path resolveIcdTxtDir() {
|
||||||
|
if (StrUtil.isBlank(icdTxtDir)) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
|
||||||
|
}
|
||||||
|
return Paths.get(icdTxtDir.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeIcdTextFile(Path directory, String name, String jsonStr) {
|
||||||
|
try {
|
||||||
|
Files.createDirectories(directory);
|
||||||
|
Files.write(resolveTxtFile(directory, name), StrUtil.nullToDefault(jsonStr, "").getBytes(StandardCharsets.UTF_8),
|
||||||
|
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
|
||||||
|
} catch (IOException ex) {
|
||||||
|
log.error("sync icd txt file failed, name={}", name, ex);
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void syncUpdatedIcdTextFile(Path directory, String oldName, String newName, String jsonStr) {
|
||||||
|
if (StrUtil.isNotBlank(oldName) && !StrUtil.equals(oldName, newName)) {
|
||||||
|
deleteIcdTextFile(directory, oldName);
|
||||||
|
}
|
||||||
|
writeIcdTextFile(directory, newName, jsonStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void deleteIcdTextFile(Path directory, String name) {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(resolveTxtFile(directory, name));
|
||||||
|
} catch (IOException ex) {
|
||||||
|
log.error("delete icd txt file failed, name={}", name, ex);
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_TXT_SYNC_FAILED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path resolveTxtFile(Path directory, String name) {
|
||||||
|
return directory.resolve(name + ".txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String encodeIcdFile(byte[] rawValue) {
|
||||||
|
if (rawValue == null || rawValue.length == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Base64.getEncoder().encodeToString(rawValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void normalizeExportDetail(PqIcdExportJsonVO detail) {
|
||||||
|
detail.setRawIcd(null);
|
||||||
|
detail.setAngle(detail.getAngle() == null ? 0 : detail.getAngle());
|
||||||
|
detail.setUsePhaseIndex(detail.getUsePhaseIndex() == null ? 1 : detail.getUsePhaseIndex());
|
||||||
|
if (isStandardType(detail.getType())) {
|
||||||
|
detail.setType(TYPE_UPSTREAM_STANDARD);
|
||||||
|
detail.setReferenceIcdId(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
detail.setType(TYPE_UPSTREAM_NON_STANDARD);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.njcn.gather.icd.service.support;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
||||||
|
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class IcdArchiveBuilder {
|
||||||
|
|
||||||
|
public byte[] build(PqIcdPath item) {
|
||||||
|
if (item == null || item.getIcd() == null || item.getIcd().length == 0) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_FOUND);
|
||||||
|
}
|
||||||
|
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||||
|
ZipOutputStream zos = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
|
||||||
|
writeTextEntry(zos, item.getName() + ".json", item.getJsonStr());
|
||||||
|
writeTextEntry(zos, item.getName() + ".xml", item.getXmlStr());
|
||||||
|
writeBinaryEntry(zos, item.getName() + ".icd", item.getIcd());
|
||||||
|
zos.finish();
|
||||||
|
return bos.toByteArray();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_EXPORT_FAILED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向ZIP流中写入文本条目
|
||||||
|
*
|
||||||
|
* @param zos ZIP输出流
|
||||||
|
* @param name 条目名称(文件路径)
|
||||||
|
* @param value 文本内容,如果为null则写入空字节数组
|
||||||
|
* @throws IOException 写入异常
|
||||||
|
*/
|
||||||
|
private void writeTextEntry(ZipOutputStream zos, String name, String value) throws IOException {
|
||||||
|
// 将文本转换为UTF-8编码的字节数组,null值转换为空数组
|
||||||
|
writeBinaryEntry(zos, name, value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向ZIP流中写入二进制条目
|
||||||
|
*
|
||||||
|
* @param zos ZIP输出流
|
||||||
|
* @param name 条目名称(文件路径)
|
||||||
|
* @param data 二进制数据
|
||||||
|
* @throws IOException 写入异常
|
||||||
|
*/
|
||||||
|
private void writeBinaryEntry(ZipOutputStream zos, String name, byte[] data) throws IOException {
|
||||||
|
// 创建新的ZIP条目并设置文件名
|
||||||
|
zos.putNextEntry(new ZipEntry(name));
|
||||||
|
// 写入二进制数据
|
||||||
|
zos.write(data);
|
||||||
|
// 关闭当前条目,准备写入下一个条目
|
||||||
|
zos.closeEntry();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.njcn.gather.icd.service.support;
|
||||||
|
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
||||||
|
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
|
||||||
|
import com.njcn.gather.icd.pojo.po.PqIcdPath;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class IcdPayloadAssembler {
|
||||||
|
|
||||||
|
private final IcdPayloadValidator validator;
|
||||||
|
|
||||||
|
public PqIcdPath fromCreate(PqIcdPathParam.CreateParam param) {
|
||||||
|
MultipartFile file = validator.validateIcdFile(param.getIcdFile(), true);
|
||||||
|
validator.validateJson(param.getJsonStr());
|
||||||
|
validator.validateXml(param.getXmlStr());
|
||||||
|
|
||||||
|
PqIcdPath entity = new PqIcdPath();
|
||||||
|
applyCommonFields(entity, param);
|
||||||
|
entity.setName(validator.extractName(file.getOriginalFilename()));
|
||||||
|
entity.setIcd(getBytes(file));
|
||||||
|
entity.setState(DataStateEnum.ENABLE.getCode());
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PqIcdPath fromExternalCreate(PqIcdPathParam.ExternalCreateParam param, int type, int angle, int usePhaseIndex) {
|
||||||
|
byte[] fileBytes = validator.decodeExternalIcdFile(param.getIcd());
|
||||||
|
validator.validateJson(param.getJsonStr());
|
||||||
|
validator.validateXml(param.getXmlStr());
|
||||||
|
|
||||||
|
PqIcdPath entity = new PqIcdPath();
|
||||||
|
entity.setId(normalizeNullableText(param.getId()));
|
||||||
|
param.setType(type);
|
||||||
|
param.setAngle(angle);
|
||||||
|
param.setUsePhaseIndex(usePhaseIndex);
|
||||||
|
applyCommonFields(entity, param);
|
||||||
|
entity.setName(normalizeNullableText(param.getName()));
|
||||||
|
entity.setIcd(fileBytes);
|
||||||
|
entity.setState(DataStateEnum.ENABLE.getCode());
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PqIcdPath merge(PqIcdPath current, PqIcdPathParam.UpdateParam param) {
|
||||||
|
MultipartFile file = validator.validateIcdFile(param.getIcdFile(), false);
|
||||||
|
validator.validateJson(param.getJsonStr());
|
||||||
|
validator.validateXml(param.getXmlStr());
|
||||||
|
|
||||||
|
applyCommonFields(current, param);
|
||||||
|
if (file != null && !file.isEmpty()) {
|
||||||
|
current.setName(validator.extractName(file.getOriginalFilename()));
|
||||||
|
current.setIcd(getBytes(file));
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyCommonFields(PqIcdPath entity, PqIcdPathParam param) {
|
||||||
|
entity.setAngle(param.getAngle());
|
||||||
|
entity.setUsePhaseIndex(param.getUsePhaseIndex());
|
||||||
|
entity.setJsonStr(param.getJsonStr());
|
||||||
|
entity.setXmlStr(param.getXmlStr());
|
||||||
|
entity.setResult(param.getResult());
|
||||||
|
entity.setMsg(param.getResult() != null && param.getResult() == 1 ? null : normalizeNullableText(param.getMsg()));
|
||||||
|
entity.setType(param.getType());
|
||||||
|
entity.setReferenceIcdId(requiresReferenceIcd(param.getType()) ? normalizeNullableText(param.getReferenceIcdId()) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String normalizeNullableText(String value) {
|
||||||
|
return StrUtil.emptyToNull(StrUtil.trim(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean requiresReferenceIcd(Integer type) {
|
||||||
|
return type != null && (type == 2 || type == 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] getBytes(MultipartFile file) {
|
||||||
|
try {
|
||||||
|
return file.getBytes();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_READ_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.njcn.gather.icd.service.support;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import org.xml.sax.InputSource;
|
||||||
|
|
||||||
|
import javax.xml.parsers.DocumentBuilderFactory;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class IcdPayloadValidator {
|
||||||
|
|
||||||
|
public MultipartFile validateIcdFile(MultipartFile file, boolean required) {
|
||||||
|
if ((file == null || file.isEmpty()) && required) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
|
||||||
|
}
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String originalName = file.getOriginalFilename();
|
||||||
|
if (originalName == null || !originalName.toLowerCase(Locale.ROOT).endsWith(".icd")) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_TYPE_ERROR);
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String extractName(String originalName) {
|
||||||
|
int suffixIndex = originalName.toLowerCase(Locale.ROOT).lastIndexOf(".icd");
|
||||||
|
return suffixIndex >= 0 ? originalName.substring(0, suffixIndex) : originalName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeExternalIcdFile(String base64Content) {
|
||||||
|
if (base64Content == null || base64Content.trim().isEmpty()) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Base64.getDecoder().decode(base64Content.trim());
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.ICD_FILE_READ_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateJson(String jsonStr) {
|
||||||
|
try {
|
||||||
|
JSON.parse(jsonStr);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateXml(String xmlStr) {
|
||||||
|
try {
|
||||||
|
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||||
|
// 禁用 DOCTYPE 声明
|
||||||
|
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||||
|
factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(IcdResponseEnum.XML_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.param.AdPlanParam;
|
||||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||||
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
|
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.AsyncPlanHandler;
|
||||||
import com.njcn.gather.plan.service.IAdPlanService;
|
import com.njcn.gather.plan.service.IAdPlanService;
|
||||||
import com.njcn.gather.type.pojo.po.DevType;
|
import com.njcn.gather.type.pojo.po.DevType;
|
||||||
@@ -198,6 +199,17 @@ public class AdPlanController extends BaseController {
|
|||||||
adPlanService.analyse(ids);
|
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)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
@PostMapping("/listByPlanId")
|
@PostMapping("/listByPlanId")
|
||||||
@ApiOperation("查询出所有已绑定的设备")
|
@ApiOperation("查询出所有已绑定的设备")
|
||||||
|
|||||||
@@ -29,13 +29,4 @@ public interface AdPlanMapper extends MPJBaseMapper<AdPlan> {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
PqReport getPqReportById(String id);
|
PqReport getPqReportById(String id);
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取所有报告模板名称
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
List<String> listAllReportTemplateName();
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
<mapper namespace="com.njcn.gather.plan.mapper.AdPlanMapper">
|
<mapper namespace="com.njcn.gather.plan.mapper.AdPlanMapper">
|
||||||
|
|
||||||
|
|
||||||
<select id="getReportIdByNameAndVersion" resultType="java.lang.String">
|
<select id="getReportIdByNameAndVersion" resultType="java.lang.String">
|
||||||
SELECT id
|
SELECT id
|
||||||
FROM pq_report
|
FROM pq_report
|
||||||
@@ -17,10 +16,4 @@
|
|||||||
WHERE id = #{id}
|
WHERE id = #{id}
|
||||||
and state = 1
|
and state = 1
|
||||||
</select>
|
</select>
|
||||||
<select id="listAllReportTemplateName" resultType="java.lang.String">
|
|
||||||
SELECT concat(name, '_', version) as name
|
|
||||||
FROM pq_report
|
|
||||||
WHERE state = 1
|
|
||||||
</select>
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -130,4 +130,17 @@ public class AdPlanParam {
|
|||||||
private String patternId;
|
private String patternId;
|
||||||
private String scriptType;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.njcn.gather.plan.pojo.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PlanStatisticsOptionVO {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备厂家筛选项。
|
||||||
|
*/
|
||||||
|
private List<PlanStatisticsOptionVO> manufacturerOptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备类型筛选项。
|
||||||
|
*/
|
||||||
|
private List<PlanStatisticsOptionVO> devTypeOptions;
|
||||||
|
}
|
||||||
@@ -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.po.AdPlan;
|
||||||
import com.njcn.gather.plan.pojo.vo.AdPlanCheckDataVO;
|
import com.njcn.gather.plan.pojo.vo.AdPlanCheckDataVO;
|
||||||
import com.njcn.gather.plan.service.util.BatchFileReader;
|
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.system.config.handler.NonWebAutoFillValueHandler;
|
||||||
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
||||||
import com.njcn.gather.type.pojo.po.DevType;
|
import com.njcn.gather.type.pojo.po.DevType;
|
||||||
@@ -64,11 +65,11 @@ public class AsyncPlanHandler {
|
|||||||
|
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
private final PathConfig pathConfig;
|
||||||
@Value("${report.reportDir}")
|
// @Value("${report.reportDir}")
|
||||||
private String reportPath;
|
// private String reportPath;
|
||||||
@Value("${data.homeDir}")
|
// @Value("${data.homeDir}")
|
||||||
private String dataPath;
|
// private String dataPath;
|
||||||
|
|
||||||
private static final int BATCH_SIZE = 10000;
|
private static final int BATCH_SIZE = 10000;
|
||||||
private static final int FINAL_STEP = 85;
|
private static final int FINAL_STEP = 85;
|
||||||
@@ -199,13 +200,13 @@ public class AsyncPlanHandler {
|
|||||||
|
|
||||||
// 创建 ZIP 文件
|
// 创建 ZIP 文件
|
||||||
String zipFileName = plan.getName() + "_检测数据包.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)) {
|
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
|
||||||
for (PqDev dev : devList) {
|
for (PqDev dev : devList) {
|
||||||
DevType devType = devTypeService.getById(dev.getDevType());
|
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));
|
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||||
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
||||||
if (FileUtil.exist(reportFile)) {
|
if (FileUtil.exist(reportFile)) {
|
||||||
@@ -344,7 +345,7 @@ public class AsyncPlanHandler {
|
|||||||
for (File docx : docxFiles) {
|
for (File docx : docxFiles) {
|
||||||
for (PqDev dev : devList) {
|
for (PqDev dev : devList) {
|
||||||
DevType devType = devTypeService.getById(dev.getDevType());
|
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));
|
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||||
// 文件名匹配,复制到对应目录下
|
// 文件名匹配,复制到对应目录下
|
||||||
if (docx.getName().equals(reportFile.getName())) {
|
if (docx.getName().equals(reportFile.getName())) {
|
||||||
|
|||||||
@@ -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.param.AdPlanParam;
|
||||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||||
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
|
import com.njcn.gather.plan.pojo.vo.AdPlanVO;
|
||||||
|
import com.njcn.gather.plan.pojo.vo.PlanStatisticsVO;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
@@ -105,6 +106,14 @@ public interface IAdPlanService extends IService<AdPlan> {
|
|||||||
*/
|
*/
|
||||||
void analyse(List<String> ids);
|
void analyse(List<String> ids);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计检测计划结果。
|
||||||
|
*
|
||||||
|
* @param planId 检测计划ID
|
||||||
|
* @return 检测计划统计结果
|
||||||
|
*/
|
||||||
|
PlanStatisticsVO statistics(AdPlanParam.StatisticsParam param);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 导出检测计划数据
|
* 导出检测计划数据
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -59,6 +59,7 @@ import com.njcn.gather.plan.service.IAdPlanService;
|
|||||||
import com.njcn.gather.plan.service.IAdPlanSourceService;
|
import com.njcn.gather.plan.service.IAdPlanSourceService;
|
||||||
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
|
import com.njcn.gather.plan.service.IAdPlanStandardDevService;
|
||||||
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
|
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.pojo.enums.DetectionResponseEnum;
|
||||||
import com.njcn.gather.report.pojo.po.PqReport;
|
import com.njcn.gather.report.pojo.po.PqReport;
|
||||||
import com.njcn.gather.report.service.IPqReportService;
|
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.pojo.po.PqSource;
|
||||||
import com.njcn.gather.source.service.IPqSourceService;
|
import com.njcn.gather.source.service.IPqSourceService;
|
||||||
import com.njcn.gather.storage.pojo.param.StorageParam;
|
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.SimAndDigHarmonicService;
|
||||||
|
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
||||||
import com.njcn.gather.storage.service.TableGenService;
|
import com.njcn.gather.storage.service.TableGenService;
|
||||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||||
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
import com.njcn.gather.system.cfg.pojo.po.SysTestConfig;
|
||||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
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.DictData;
|
||||||
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
import com.njcn.gather.system.dictionary.pojo.po.DictTree;
|
||||||
import com.njcn.gather.system.dictionary.pojo.po.DictType;
|
import com.njcn.gather.system.dictionary.pojo.po.DictType;
|
||||||
@@ -107,6 +111,8 @@ import javax.servlet.ServletOutputStream;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -133,6 +139,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
|||||||
private final IDevTypeService devTypeService;
|
private final IDevTypeService devTypeService;
|
||||||
private final IDictTypeService dictTypeService;
|
private final IDictTypeService dictTypeService;
|
||||||
private final SimAndDigHarmonicService adHarmonicService;
|
private final SimAndDigHarmonicService adHarmonicService;
|
||||||
|
private final SimAndDigNonHarmonicService adNonHarmonicService;
|
||||||
private final PqDevMapper pqDevMapper;
|
private final PqDevMapper pqDevMapper;
|
||||||
private final IPqDevSubService pqDevSubService;
|
private final IPqDevSubService pqDevSubService;
|
||||||
private final IAdPlanStandardDevService adPlanStandardDevService;
|
private final IAdPlanStandardDevService adPlanStandardDevService;
|
||||||
@@ -145,10 +152,12 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
|||||||
private final IAdPariService adPairService;
|
private final IAdPariService adPairService;
|
||||||
private final IAdPlanTestConfigService adPlanTestConfigService;
|
private final IAdPlanTestConfigService adPlanTestConfigService;
|
||||||
private final ISysUserService sysUserService;
|
private final ISysUserService sysUserService;
|
||||||
|
private final IPqDevCheckHistoryService pqDevCheckHistoryService;
|
||||||
|
|
||||||
private final JdbcTemplate jdbcTemplate;
|
private final JdbcTemplate jdbcTemplate;
|
||||||
@Value("${report.reportDir}")
|
// @Value("${report.reportDir}")
|
||||||
private String reportPath;
|
// private String reportPath;
|
||||||
|
private final PathConfig pathConfig;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<AdPlanVO> listAdPlan(AdPlanParam.QueryParam queryParam) {
|
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("name", adPlan.getName());
|
||||||
child.put("timeCheck", adPlan.getTimeCheck());
|
child.put("timeCheck", adPlan.getTimeCheck());
|
||||||
child.put("dataRule", adPlan.getDataRule());
|
child.put("dataRule", adPlan.getDataRule());
|
||||||
|
child.put("testState", adPlan.getTestState());
|
||||||
|
|
||||||
List<PqStandardDev> pqStandardDevs = adPlanStandardDevMapper.listByPlanId(Collections.singletonList(adPlan.getId()));
|
List<PqStandardDev> pqStandardDevs = adPlanStandardDevMapper.listByPlanId(Collections.singletonList(adPlan.getId()));
|
||||||
List<String> devTypeIdList = pqStandardDevs.stream().map(PqStandardDev::getDevType).collect(Collectors.toList());
|
List<String> devTypeIdList = pqStandardDevs.stream().map(PqStandardDev::getDevType).collect(Collectors.toList());
|
||||||
@@ -809,6 +819,290 @@ 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> allPlanDevices = listPlanDevices(plan.getId(), null, null);
|
||||||
|
List<PqDevVO> planDevices = filterPlanDevices(allPlanDevices, 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.setManufacturerOptions(buildManufacturerOptions(allPlanDevices, param.getDevType()));
|
||||||
|
statistics.setDevTypeOptions(buildDevTypeOptions(allPlanDevices, param.getManufacturer()));
|
||||||
|
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 filterPlanDevices(pqDevVOList, manufacturer, devType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PqDevVO> filterPlanDevices(List<PqDevVO> devices, String manufacturer, String devType) {
|
||||||
|
if (CollUtil.isEmpty(devices)) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
return devices.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 List<PlanStatisticsOptionVO> buildManufacturerOptions(List<PqDevVO> devices, String devType) {
|
||||||
|
if (CollUtil.isEmpty(devices)) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
List<String> ids = devices.stream()
|
||||||
|
.filter(dev -> StrUtil.isBlank(devType) || Objects.equals(dev.getDevType(), devType))
|
||||||
|
.map(PqDevVO::getManufacturer)
|
||||||
|
.filter(StrUtil::isNotBlank)
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Map<String, String> nameMap = ids.isEmpty()
|
||||||
|
? Collections.emptyMap()
|
||||||
|
: dictDataService.listByIds(ids).stream()
|
||||||
|
.collect(Collectors.toMap(DictData::getId, DictData::getName, (left, right) -> left));
|
||||||
|
return ids.stream()
|
||||||
|
.map(id -> new PlanStatisticsOptionVO(id, nameMap.getOrDefault(id, id)))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PlanStatisticsOptionVO> buildDevTypeOptions(List<PqDevVO> devices, String manufacturer) {
|
||||||
|
if (CollUtil.isEmpty(devices)) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
List<String> ids = devices.stream()
|
||||||
|
.filter(dev -> StrUtil.isBlank(manufacturer) || Objects.equals(dev.getManufacturer(), manufacturer))
|
||||||
|
.map(PqDevVO::getDevType)
|
||||||
|
.filter(StrUtil::isNotBlank)
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
Map<String, String> nameMap = ids.isEmpty()
|
||||||
|
? Collections.emptyMap()
|
||||||
|
: devTypeService.listByIds(ids).stream()
|
||||||
|
.collect(Collectors.toMap(DevType::getId, DevType::getName, (left, right) -> left));
|
||||||
|
return ids.stream()
|
||||||
|
.map(id -> new PlanStatisticsOptionVO(id, nameMap.getOrDefault(id, id)))
|
||||||
|
.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
|
@Override
|
||||||
public void exportPlan(AdPlanParam.QueryParam queryParam) {
|
public void exportPlan(AdPlanParam.QueryParam queryParam) {
|
||||||
DictData dictData = dictDataService.getDictDataById(queryParam.getPatternId());
|
DictData dictData = dictDataService.getDictDataById(queryParam.getPatternId());
|
||||||
@@ -1265,7 +1559,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
|||||||
for (int i = 1; i <= maxTime; i++) {
|
for (int i = 1; i <= maxTime; i++) {
|
||||||
row2[i] = i + "次检测";
|
row2[i] = i + "次检测";
|
||||||
int tempI = 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();
|
long passCount = tempDevList.stream().filter(dev -> dev.getCheckResult() == CheckResultEnum.ACCORD.getValue()).count();
|
||||||
row3[i] = passCount + "";
|
row3[i] = passCount + "";
|
||||||
row4[i] = total + "";
|
row4[i] = total + "";
|
||||||
@@ -1612,7 +1906,9 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
|||||||
pullDowns.add(pullDown);
|
pullDowns.add(pullDown);
|
||||||
|
|
||||||
// 报告模板
|
// 报告模板
|
||||||
List<String> strings = this.baseMapper.listAllReportTemplateName();
|
List<String> strings = SpringUtil.getBean(IPqReportService.class).listOptions(patternId).stream()
|
||||||
|
.map(option -> option.getDisplayName())
|
||||||
|
.collect(Collectors.toList());
|
||||||
pullDown = new PullDown();
|
pullDown = new PullDown();
|
||||||
pullDown.setFirstCol(8);
|
pullDown.setFirstCol(8);
|
||||||
pullDown.setLastCol(8);
|
pullDown.setLastCol(8);
|
||||||
@@ -2089,7 +2385,7 @@ public class AdPlanServiceImpl extends ServiceImpl<AdPlanMapper, AdPlan> impleme
|
|||||||
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
|
if (ObjectUtil.isNotNull(report) && report.equals(1)) {
|
||||||
for (PqDev dev : devList) {
|
for (PqDev dev : devList) {
|
||||||
DevType devType = devTypeService.getById(dev.getDevType());
|
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));
|
File reportFile = new File(dirPath.concat(File.separator).concat(dev.getCreateId()).concat(ReportConstant.DOCX));
|
||||||
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
// 如果reportFile存在,则将reportFile中的文件添加到已有的zip文件中
|
||||||
if (FileUtil.exist(reportFile)) {
|
if (FileUtil.exist(reportFile)) {
|
||||||
|
|||||||
@@ -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.getCheckEndTime()) ? device.getCheckEndTime() : 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,7 +75,8 @@ public enum DetectionResponseEnum {
|
|||||||
PLAN_REPEATED_IN_SAME_LEVEL("A02096", "该父计划下存在同名的子计划"),
|
PLAN_REPEATED_IN_SAME_LEVEL("A02096", "该父计划下存在同名的子计划"),
|
||||||
PLEASE_UNASSIGN_STANDARD_DEV("A02097", "存在已分配给子计划的标准设备,请先解除分配"),
|
PLEASE_UNASSIGN_STANDARD_DEV("A02097", "存在已分配给子计划的标准设备,请先解除分配"),
|
||||||
PLEASE_UNASSIGN_DEVICE("A02098", "存在已分配给计划的被检设备,请先解除分配"),
|
PLEASE_UNASSIGN_DEVICE("A02098", "存在已分配给计划的被检设备,请先解除分配"),
|
||||||
DEV_IP_PORT_EXIST("A02099", "存在重复被检设备");
|
DEV_IP_PORT_EXIST("A02099", "存在重复被检设备"),
|
||||||
|
PQDIF_NOT_EXIST("A02100", "PQDIF不存在");
|
||||||
|
|
||||||
private final String code;
|
private final String code;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.njcn.gather.pqdif.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
|
import com.njcn.common.pojo.constant.OperateType;
|
||||||
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.common.utils.LogUtil;
|
||||||
|
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
|
||||||
|
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
|
||||||
|
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
|
||||||
|
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
|
||||||
|
import com.njcn.gather.pqdif.service.support.PqdifImportParser;
|
||||||
|
import com.njcn.web.controller.BaseController;
|
||||||
|
import com.njcn.web.utils.HttpResultUtil;
|
||||||
|
import io.swagger.annotations.Api;
|
||||||
|
import io.swagger.annotations.ApiImplicitParam;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Api(tags = "PQDIF管理")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/pqdif")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PqPqdifPathController extends BaseController {
|
||||||
|
private final IPqPqdifPathService pqPqdifPathService;
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@GetMapping("/listAll")
|
||||||
|
@ApiOperation("获取全部PQDIF")
|
||||||
|
public HttpResult<List<PqPqdifPath>> listAll() {
|
||||||
|
String methodDescribe = getMethodDescribe("listAll");
|
||||||
|
List<PqPqdifPath> result = pqPqdifPathService.listAll();
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo
|
||||||
|
@PostMapping("/list")
|
||||||
|
@ApiOperation("分页查询PQDIF")
|
||||||
|
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
|
||||||
|
public HttpResult<Page<PqPqdifPath>> list(@RequestBody @Validated PqPqdifPathParam.QueryParam param) {
|
||||||
|
String methodDescribe = getMethodDescribe("list");
|
||||||
|
LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, param);
|
||||||
|
Page<PqPqdifPath> result = pqPqdifPathService.listPqdif(param);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
|
||||||
|
@PostMapping("/import/json")
|
||||||
|
@ApiOperation("导入PQDIF json")
|
||||||
|
@ApiImplicitParam(name = "file", value = "json文件", required = true)
|
||||||
|
public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
|
||||||
|
String methodDescribe = getMethodDescribe("importJson");
|
||||||
|
LogUtil.njcnDebug(log, "{},导入文件为:{}", methodDescribe, file == null ? null : file.getOriginalFilename());
|
||||||
|
List<PqPqdifPathParam.ImportItem> items = parseImportItems(file);
|
||||||
|
boolean result = pqPqdifPathService.importPqdif(items);
|
||||||
|
if (result) {
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
|
||||||
|
}
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PqPqdifPathParam.ImportItem> parseImportItems(MultipartFile file) {
|
||||||
|
if (file == null || file.isEmpty()) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FILE_NOT_NULL);
|
||||||
|
}
|
||||||
|
String fileName = file.getOriginalFilename();
|
||||||
|
if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return PqdifImportParser.parse(new String(file.getBytes(), StandardCharsets.UTF_8));
|
||||||
|
} catch (BusinessException ex) {
|
||||||
|
throw ex;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.njcn.gather.pqdif.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.github.yulichang.base.MPJBaseMapper;
|
||||||
|
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface PqPqdifPathMapper extends MPJBaseMapper<PqPqdifPath> {
|
||||||
|
List<PqPqdifPath> selectPageList(Page<PqPqdifPath> page, @Param("name") String name, @Param("result") Integer result);
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.njcn.gather.pqdif.mapper.PqPqdifPathMapper">
|
||||||
|
<select id="selectPageList" resultType="com.njcn.gather.pqdif.pojo.po.PqPqdifPath">
|
||||||
|
select id,
|
||||||
|
Name as name,
|
||||||
|
File_Path as filePath,
|
||||||
|
Record_Count as recordCount,
|
||||||
|
Observation_Count as observationCount,
|
||||||
|
Sample_Value_Count as sampleValueCount,
|
||||||
|
Result as result,
|
||||||
|
Msg as msg,
|
||||||
|
State as state,
|
||||||
|
Create_By as createBy,
|
||||||
|
Create_Time as createTime,
|
||||||
|
Update_By as updateBy,
|
||||||
|
Update_Time as updateTime
|
||||||
|
from pq_pqdif_path
|
||||||
|
where State = 1
|
||||||
|
<if test="name != null and name != ''">
|
||||||
|
and Name like concat('%', #{name}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="result != null">
|
||||||
|
and Result = #{result}
|
||||||
|
</if>
|
||||||
|
order by Update_Time desc, Create_Time desc
|
||||||
|
</select>
|
||||||
|
</mapper>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.njcn.gather.pqdif.pojo.enums;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public enum PqdifResponseEnum {
|
||||||
|
JSON_FILE_NOT_NULL("A019001", "JSON文件不能为空"),
|
||||||
|
JSON_FORMAT_ERROR("A019002", "JSON格式错误"),
|
||||||
|
IMPORT_ITEM_NOT_NULL("A019003", "导入数据项不能为空"),
|
||||||
|
IMPORT_ID_REPEAT("A019004", "导入数据中存在重复id"),
|
||||||
|
IMPORT_FAILED("A019005", "PQDIF导入失败");
|
||||||
|
|
||||||
|
private final String code;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
PqdifResponseEnum(String code, String message) {
|
||||||
|
this.code = code;
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.njcn.gather.pqdif.pojo.param;
|
||||||
|
|
||||||
|
import com.njcn.web.pojo.param.BaseParam;
|
||||||
|
import io.swagger.annotations.ApiModelProperty;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class PqPqdifPathParam {
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public static class QueryParam extends BaseParam {
|
||||||
|
@ApiModelProperty(value = "name")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "result")
|
||||||
|
private Integer result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class ImportItem {
|
||||||
|
private String id;
|
||||||
|
private String name;
|
||||||
|
private String filePath;
|
||||||
|
private Long recordCount;
|
||||||
|
private Long observationCount;
|
||||||
|
private Integer sampleValueCount;
|
||||||
|
private Integer result;
|
||||||
|
private String msg;
|
||||||
|
private Integer state;
|
||||||
|
private Object parseResult;
|
||||||
|
private String createBy;
|
||||||
|
private String createTime;
|
||||||
|
private String updateBy;
|
||||||
|
private String updateTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.njcn.gather.pqdif.pojo.po;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.njcn.db.mybatisplus.bo.BaseEntity;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@TableName("pq_pqdif_path")
|
||||||
|
public class PqPqdifPath extends BaseEntity implements Serializable {
|
||||||
|
private static final long serialVersionUID = 2536904714178389110L;
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@TableField("File_Path")
|
||||||
|
private String filePath;
|
||||||
|
|
||||||
|
@TableField("Record_Count")
|
||||||
|
private Long recordCount;
|
||||||
|
|
||||||
|
@TableField("Observation_Count")
|
||||||
|
private Long observationCount;
|
||||||
|
|
||||||
|
@TableField("Sample_Value_Count")
|
||||||
|
private Integer sampleValueCount;
|
||||||
|
|
||||||
|
@TableField("Result")
|
||||||
|
private Integer result;
|
||||||
|
|
||||||
|
@TableField("Msg")
|
||||||
|
private String msg;
|
||||||
|
|
||||||
|
@TableField("State")
|
||||||
|
private Integer state;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.njcn.gather.pqdif.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
|
||||||
|
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface IPqPqdifPathService extends IService<PqPqdifPath> {
|
||||||
|
List<PqPqdifPath> listAll();
|
||||||
|
|
||||||
|
Page<PqPqdifPath> listPqdif(PqPqdifPathParam.QueryParam param);
|
||||||
|
|
||||||
|
boolean importPqdif(List<PqPqdifPathParam.ImportItem> items);
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package com.njcn.gather.pqdif.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.collection.CollUtil;
|
||||||
|
import cn.hutool.core.util.ReUtil;
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.njcn.common.pojo.constant.PatternRegex;
|
||||||
|
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.pojo.constant.DetectionValidMessage;
|
||||||
|
import com.njcn.gather.pqdif.mapper.PqPqdifPathMapper;
|
||||||
|
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
|
||||||
|
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
|
||||||
|
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
|
||||||
|
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
|
||||||
|
import com.njcn.web.factory.PageFactory;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class PqPqdifPathServiceImpl extends ServiceImpl<PqPqdifPathMapper, PqPqdifPath> implements IPqPqdifPathService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<PqPqdifPath> listAll() {
|
||||||
|
return this.lambdaQuery()
|
||||||
|
.select(PqPqdifPath::getId, PqPqdifPath::getName)
|
||||||
|
.eq(PqPqdifPath::getState, DataStateEnum.ENABLE.getCode())
|
||||||
|
.orderByDesc(PqPqdifPath::getCreateTime)
|
||||||
|
.list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<PqPqdifPath> listPqdif(PqPqdifPathParam.QueryParam param) {
|
||||||
|
Page<PqPqdifPath> page = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param));
|
||||||
|
page.setRecords(this.baseMapper.selectPageList(page, StrUtil.trim(param.getName()), param.getResult()));
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public boolean importPqdif(List<PqPqdifPathParam.ImportItem> items) {
|
||||||
|
if (CollUtil.isEmpty(items)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
validateItems(items);
|
||||||
|
for (PqPqdifPathParam.ImportItem item : items) {
|
||||||
|
PqPqdifPath entity = toEntity(item);
|
||||||
|
boolean saved = this.saveOrUpdate(entity);
|
||||||
|
if (!saved) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.IMPORT_FAILED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateItems(List<PqPqdifPathParam.ImportItem> items) {
|
||||||
|
Set<String> ids = new HashSet<>();
|
||||||
|
for (PqPqdifPathParam.ImportItem item : items) {
|
||||||
|
if (item == null) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.IMPORT_ITEM_NOT_NULL);
|
||||||
|
}
|
||||||
|
String id = StrUtil.trim(item.getId());
|
||||||
|
if (StrUtil.isBlank(id)) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.ID_NOT_BLANK);
|
||||||
|
}
|
||||||
|
if (!ReUtil.isMatch(PatternRegex.SYSTEM_ID, id)) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.ID_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
if (!ids.add(id)) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.IMPORT_ID_REPEAT);
|
||||||
|
}
|
||||||
|
if (StrUtil.isBlank(item.getName())) {
|
||||||
|
throw new BusinessException(DetectionValidMessage.NAME_NOT_BLANK);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private PqPqdifPath toEntity(PqPqdifPathParam.ImportItem item) {
|
||||||
|
PqPqdifPath entity = new PqPqdifPath();
|
||||||
|
entity.setId(StrUtil.trim(item.getId()));
|
||||||
|
entity.setName(StrUtil.trim(item.getName()));
|
||||||
|
entity.setFilePath(StrUtil.trim(item.getFilePath()));
|
||||||
|
entity.setRecordCount(item.getRecordCount());
|
||||||
|
entity.setObservationCount(item.getObservationCount());
|
||||||
|
entity.setSampleValueCount(item.getSampleValueCount());
|
||||||
|
entity.setResult(item.getResult());
|
||||||
|
entity.setMsg(item.getMsg());
|
||||||
|
entity.setState(item.getState() == null ? DataStateEnum.ENABLE.getCode() : item.getState());
|
||||||
|
entity.setCreateBy(StrUtil.trim(item.getCreateBy()));
|
||||||
|
entity.setUpdateBy(StrUtil.trim(item.getUpdateBy()));
|
||||||
|
entity.setCreateTime(parseDateTime(item.getCreateTime()));
|
||||||
|
entity.setUpdateTime(parseDateTime(item.getUpdateTime()));
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalDateTime parseDateTime(String value) {
|
||||||
|
if (StrUtil.isBlank(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return LocalDateTime.parse(StrUtil.trim(value));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.njcn.gather.pqdif.service.support;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONArray;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
|
||||||
|
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class PqdifImportParser {
|
||||||
|
|
||||||
|
private PqdifImportParser() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<PqPqdifPathParam.ImportItem> parse(String content) {
|
||||||
|
try {
|
||||||
|
JSONArray jsonArray = JSON.parseArray(content);
|
||||||
|
if (jsonArray == null) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
List<PqPqdifPathParam.ImportItem> items = new ArrayList<>();
|
||||||
|
for (int i = 0; i < jsonArray.size(); i++) {
|
||||||
|
JSONObject jsonObject = jsonArray.getJSONObject(i);
|
||||||
|
if (jsonObject == null) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.IMPORT_ITEM_NOT_NULL);
|
||||||
|
}
|
||||||
|
PqPqdifPathParam.ImportItem item = jsonObject.toJavaObject(PqPqdifPathParam.ImportItem.class);
|
||||||
|
Object msg = jsonObject.get("msg");
|
||||||
|
item.setMsg(normalizeMsg(msg));
|
||||||
|
items.add(item);
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
} catch (BusinessException ex) {
|
||||||
|
throw ex;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeMsg(Object msg) {
|
||||||
|
if (msg == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (msg instanceof String) {
|
||||||
|
return (String) msg;
|
||||||
|
}
|
||||||
|
return JSON.toJSONString(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -134,11 +134,12 @@ public class ReportController extends BaseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@OperateInfo
|
@OperateInfo
|
||||||
@GetMapping("/listAllName")
|
@GetMapping("/listOptions")
|
||||||
@ApiOperation("查询所有报告模板名称")
|
@ApiOperation("查询所有报告模板名称")
|
||||||
public HttpResult<List<String>> listAllName() {
|
public HttpResult<List<PqReportVO.OptionVO>> listOptions(@RequestParam("pattern") String pattern) {
|
||||||
String methodDescribe = getMethodDescribe("listAllName");
|
String methodDescribe = getMethodDescribe("listOptions");
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqReportService.listAllName(), methodDescribe);
|
LogUtil.njcnDebug(log, "{}锛屾煡璇㈠弬鏁颁负锛歿}", methodDescribe, pattern);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqReportService.listOptions(pattern), methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
|
||||||
|
|||||||
@@ -2,18 +2,17 @@ package com.njcn.gather.report.mapper;
|
|||||||
|
|
||||||
import com.github.yulichang.base.MPJBaseMapper;
|
import com.github.yulichang.base.MPJBaseMapper;
|
||||||
import com.njcn.gather.report.pojo.po.PqReport;
|
import com.njcn.gather.report.pojo.po.PqReport;
|
||||||
|
import com.njcn.gather.report.pojo.vo.PqReportVO;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
|
||||||
* @author makejava
|
|
||||||
* @date 2025-03-19
|
|
||||||
*/
|
|
||||||
public interface PqReportMapper extends MPJBaseMapper<PqReport> {
|
public interface PqReportMapper extends MPJBaseMapper<PqReport> {
|
||||||
/**
|
/**
|
||||||
* 获取所有已被计划绑定的报告模板id
|
* 获取所有已被计划绑定的报告模板id
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
List<String> getBoundReportIds();
|
List<String> getBoundReportIds();
|
||||||
}
|
|
||||||
|
|
||||||
|
List<PqReportVO.OptionVO> listOptionsByPattern(@Param("pattern") String pattern);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,9 +2,19 @@
|
|||||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
<mapper namespace="com.njcn.gather.report.mapper.PqReportMapper">
|
<mapper namespace="com.njcn.gather.report.mapper.PqReportMapper">
|
||||||
|
|
||||||
|
|
||||||
<select id="getBoundReportIds" resultType="java.lang.String">
|
<select id="getBoundReportIds" resultType="java.lang.String">
|
||||||
select distinct Report_Template_Id from ad_plan where state = 1
|
select distinct Report_Template_Id from ad_plan where state = 1
|
||||||
</select>
|
</select>
|
||||||
</mapper>
|
|
||||||
|
|
||||||
|
<select id="listOptionsByPattern" resultType="com.njcn.gather.report.pojo.vo.PqReportVO$OptionVO">
|
||||||
|
select
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
concat(name, '_', version) as displayName
|
||||||
|
from pq_report
|
||||||
|
where state = 1
|
||||||
|
and pattern = #{pattern}
|
||||||
|
order by update_time desc
|
||||||
|
</select>
|
||||||
|
</mapper>
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.njcn.gather.report.pojo.constant;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "指标锚点"新型模板的书签命名空间常量。
|
||||||
|
* 设计文档:docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §3.1
|
||||||
|
*
|
||||||
|
* @author hongawen
|
||||||
|
*/
|
||||||
|
public interface ItemAnchorConstant {
|
||||||
|
|
||||||
|
/** 数据锚点书签前缀:item_{scriptCode},锚点处按回路插入检测数据表 */
|
||||||
|
String ITEM_PREFIX = "item_";
|
||||||
|
|
||||||
|
/** 区段书签前缀:sect_{scriptCode} / sect_{GRP_XXX},指标无数据时整段删除 */
|
||||||
|
String SECT_PREFIX = "sect_";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 父节 → 子节 scriptCode 映射;一个父节的全部子节都隐藏时,父节(组标题+组内公共文字)一并隐藏。
|
||||||
|
* key 与模板中 sect_GRP_* 书签名的 GRP_* 部分一致。
|
||||||
|
*/
|
||||||
|
Map<String, List<String>> GRP_CHILDREN = buildGrpChildren();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已知指标 scriptCode 白名单(规范大写,即云南模板 11 个锚点)。
|
||||||
|
* 分流与锚点解析以此为准:白名单外的 item_* 书签一律视为无效,防止老模板中
|
||||||
|
* 作者手工遗留的同前缀书签(如 item_1)把整份报告误路由进新路径。
|
||||||
|
*/
|
||||||
|
Set<String> KNOWN_SCRIPT_CODES = buildKnownScriptCodes();
|
||||||
|
|
||||||
|
static Map<String, List<String>> buildGrpChildren() {
|
||||||
|
Map<String, List<String>> map = new LinkedHashMap<>();
|
||||||
|
map.put("GRP_FUND", Arrays.asList("V", "I", "P", "ANGLE"));
|
||||||
|
map.put("GRP_UNB", Arrays.asList("IMBV", "IMBA"));
|
||||||
|
map.put("GRP_HARM", Arrays.asList("HV", "HI", "HP"));
|
||||||
|
return Collections.unmodifiableMap(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Set<String> buildKnownScriptCodes() {
|
||||||
|
return Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(
|
||||||
|
"V", "I", "P", "ANGLE", "FREQ", "F", "IMBV", "IMBA", "HV", "HI", "HP")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从书签名解析指标锚点的 scriptCode。
|
||||||
|
*
|
||||||
|
* @param bookmarkName 书签名
|
||||||
|
* @return 规范大写 scriptCode(scriptMap / 模板 H5 分组 key 均为大写);
|
||||||
|
* 非 item_ 前缀、空 code 或不在 {@link #KNOWN_SCRIPT_CODES} 白名单内返回 null
|
||||||
|
*/
|
||||||
|
static String resolveItemScriptCode(String bookmarkName) {
|
||||||
|
if (bookmarkName == null || bookmarkName.length() <= ITEM_PREFIX.length()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!bookmarkName.substring(0, ITEM_PREFIX.length()).equalsIgnoreCase(ITEM_PREFIX)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String code = bookmarkName.substring(ITEM_PREFIX.length()).toUpperCase();
|
||||||
|
return KNOWN_SCRIPT_CODES.contains(code) ? code : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,18 +12,32 @@ import lombok.Getter;
|
|||||||
public enum AffectEnum {
|
public enum AffectEnum {
|
||||||
|
|
||||||
|
|
||||||
BASE("base", "额定工作条件下的检测"),
|
// 第三个参数 sort 为报告小节排序档位:额定=1、单影响量=2、多影响量=3(同档内再按 Script_Index 升序)
|
||||||
VOL("vol", "电压对XX测量的影响"),
|
BASE("Base", "额定条件XX准确度测试", 1),
|
||||||
FREQ("freq", "频率对XX测量的影响"),
|
VOL("VOL", "电压幅值对XX测量的影响", 2),
|
||||||
HARM("harm", "谐波对XX测量的影响");
|
FREQ("Freq", "频率变化对XX测量的影响", 2),
|
||||||
|
HARM("Harm", "谐波对XX测量的影响", 2),
|
||||||
|
// Single / Many 是检测树的分组标题,不会作为叶子 Script_SubType 落到设备数据上
|
||||||
|
SINGLE("Single", "单影响量下XX准确度测试", 2),
|
||||||
|
MANY("Many", "多影响量下XX准确度测试", 3),
|
||||||
|
// 以下为真实的多影响量组合 Script_SubType(报告与检测树共用同一份文案)
|
||||||
|
MANY_VOL_HARM_INHARM("Many-Vol-Harm-InHarm", "电压和谐波和间谐波对XX的影响", 3),
|
||||||
|
MANY_IMBV_HARM_INHARM("Many-IMBV-Harm-InHarm", "三项电压不平衡和谐波和间谐波对XX的影响", 3),
|
||||||
|
MANY_FREQ_HARM_INHARM("Many-Freq-Harm-InHarm", "频率和谐波和间谐波对XX的影响", 3);
|
||||||
|
|
||||||
private String key;
|
private String key;
|
||||||
|
|
||||||
private String desc;
|
private String desc;
|
||||||
|
|
||||||
AffectEnum(String key, String desc) {
|
/**
|
||||||
|
* 报告小节排序档位:额定=1、单影响量=2、多影响量=3;同档内再按 Script_Index 升序
|
||||||
|
*/
|
||||||
|
private int sort;
|
||||||
|
|
||||||
|
AffectEnum(String key, String desc, int sort) {
|
||||||
this.key = key;
|
this.key = key;
|
||||||
this.desc = desc;
|
this.desc = desc;
|
||||||
|
this.sort = sort;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -17,19 +17,24 @@ public enum BaseReportKeyEnum {
|
|||||||
|
|
||||||
DEV_TYPE("devType","设备型号、规格"),
|
DEV_TYPE("devType","设备型号、规格"),
|
||||||
DEV_CODE("createId","装置编号"),
|
DEV_CODE("createId","装置编号"),
|
||||||
|
DEV_NAME("devName","装置名称"),
|
||||||
POWER("power","工作电源"),
|
POWER("power","工作电源"),
|
||||||
DEV_CURR("devCurr","额定电流"),
|
DEV_CURR("devCurr","额定电流"),
|
||||||
DEV_VOLT("devVolt","额定电压"),
|
DEV_VOLT("devVolt","额定电压"),
|
||||||
|
SOURCE_NAME("sourceName","检测源名称"),
|
||||||
COUNT("count","通道数"),
|
COUNT("count","通道数"),
|
||||||
MANUFACTURER("manufacturer","设备厂家、制造厂商"),
|
MANUFACTURER("manufacturer","设备厂家、制造厂商"),
|
||||||
SAMPLE_ID("sampleId","样品编号"),
|
SAMPLE_ID("sampleId","样品编号"),
|
||||||
ARRIVED_DATE("arrivedDate","收样日期"),
|
ARRIVED_DATE("arrivedDate","收样日期"),
|
||||||
|
ARRIVED_DATE_C("arrivedDateC","收样日期"),
|
||||||
TEST_DATE("testDate","检测日期"),
|
TEST_DATE("testDate","检测日期"),
|
||||||
|
TEST_DATE_C("testDateC","检测日期"),
|
||||||
INSPECTOR("inspector","检测员"),
|
INSPECTOR("inspector","检测员"),
|
||||||
YEAR("year","年份"),
|
YEAR("year","年份"),
|
||||||
MONTH("month","月份"),
|
MONTH("month","月份"),
|
||||||
DAY("day","日"),
|
DAY("day","日"),
|
||||||
YEAR_MONTH_DAY("year-month-day","年-月-日"),
|
YEAR_MONTH_DAY("year-month-day","年-月-日"),
|
||||||
|
YEAR_MONTH_DAY_UP("year-month-day-up","中文数字 年-月-日"),
|
||||||
REPORT_DATE("reportDate","年-月-日"),
|
REPORT_DATE("reportDate","年-月-日"),
|
||||||
GD_NAME("gdName","供电部门"),
|
GD_NAME("gdName","供电部门"),
|
||||||
SUB_NAME("subName","变电站"),
|
SUB_NAME("subName","变电站"),
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ public enum BookmarkEnum {
|
|||||||
|
|
||||||
private String desc;
|
private String desc;
|
||||||
|
|
||||||
|
/** 书签处理顺序:1=数据项,2=结果信息,3=目录信息;由 dealDataModelScatteredByBookmark 排序时使用 */
|
||||||
private Integer sort;
|
private Integer sort;
|
||||||
|
|
||||||
BookmarkEnum(String key, String desc, Integer sort) {
|
BookmarkEnum(String key, String desc, Integer sort) {
|
||||||
|
|||||||
@@ -45,7 +45,34 @@ public enum ItemReportKeyEnum {
|
|||||||
RESULT_B("resultB", "结论 比如:合格/不合格"),
|
RESULT_B("resultB", "结论 比如:合格/不合格"),
|
||||||
RESULT_C("resultC", "结论 比如:合格/不合格"),
|
RESULT_C("resultC", "结论 比如:合格/不合格"),
|
||||||
RESULT_MAG("resultMag", "特征幅值结论 比如:合格/不合格"),
|
RESULT_MAG("resultMag", "特征幅值结论 比如:合格/不合格"),
|
||||||
RESULT_DUR("resultDur", "持续时间结论 比如:合格/不合格");
|
RESULT_DUR("resultDur", "持续时间结论 比如:合格/不合格"),
|
||||||
|
|
||||||
|
// ===== 以下为"指标锚点"新型模板(云南检定报告)新增 key,见 docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §5 =====
|
||||||
|
STANDARD_V("standardV", "P表:基波电压设置值"),
|
||||||
|
STANDARD_I("standardI", "P表:基波电流设置值"),
|
||||||
|
STANDARD_U_ANGLE("standardUAngle", "P表:电压相角设置值"),
|
||||||
|
STANDARD_I_ANGLE("standardIAngle", "P表:电流相角设置值"),
|
||||||
|
ACTIVE_POWER("activePower", "P表:有功功率实测值(三相之和)"),
|
||||||
|
REACTIVE_POWER("reactivePower", "P表:无功功率实测值(数据侧暂无,留空)"),
|
||||||
|
APPARENT_POWER("apparentPower", "P表:视在功率实测值(数据侧暂无,留空)"),
|
||||||
|
POWER_FACTOR("powerFactor", "P表:功率因数实测值(数据侧暂无,留空)"),
|
||||||
|
POS_SEQ("posSeq", "不平衡表:基波正序(数据侧暂无,留空)"),
|
||||||
|
NEG_SEQ("negSeq", "不平衡表:基波负序(数据侧暂无,留空)"),
|
||||||
|
ZERO_SEQ("zeroSeq", "不平衡表:基波零序(数据侧暂无,留空)"),
|
||||||
|
BASE_CURRENT_A("baseCurrentA", "HI表:A相基波电流幅值,用于计算谐波电流含有率"),
|
||||||
|
BASE_CURRENT_B("baseCurrentB", "HI表:B相基波电流幅值,用于计算谐波电流含有率"),
|
||||||
|
BASE_CURRENT_C("baseCurrentC", "HI表:C相基波电流幅值,用于计算谐波电流含有率"),
|
||||||
|
STANDARD_RATE("standardRate", "HI表:标准源输出含有率"),
|
||||||
|
TEST_RATE_A("testRateA", "HI表:A相谐波电流含有率"),
|
||||||
|
TEST_RATE_B("testRateB", "HI表:B相谐波电流含有率"),
|
||||||
|
TEST_RATE_C("testRateC", "HI表:C相谐波电流含有率"),
|
||||||
|
ERROR_RATE_A("errorRateA", "HI表:A相谐波电流含有率误差"),
|
||||||
|
ERROR_RATE_B("errorRateB", "HI表:B相谐波电流含有率误差"),
|
||||||
|
ERROR_RATE_C("errorRateC", "HI表:C相谐波电流含有率误差"),
|
||||||
|
STANDARD_THD("standardThd", "HV/HI表:标准源总谐波畸变率"),
|
||||||
|
THD_A("thdA", "HV/HI表:A相总谐波畸变率"),
|
||||||
|
THD_B("thdB", "HV/HI表:B相总谐波畸变率"),
|
||||||
|
THD_C("thdC", "HV/HI表:C相总谐波畸变率");
|
||||||
|
|
||||||
private String key;
|
private String key;
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ public enum PowerIndexEnum {
|
|||||||
V("V", "电压"),
|
V("V", "电压"),
|
||||||
I("I", "电流"),
|
I("I", "电流"),
|
||||||
P("P", "功率"),
|
P("P", "功率"),
|
||||||
|
ANGLE("Angle", "基波相位"),
|
||||||
IMBV("IMBV", "负序电压不平衡度"),
|
IMBV("IMBV", "负序电压不平衡度"),
|
||||||
IMBA("IMBA", "负序电流不平衡度"),
|
IMBA("IMBA", "负序电流不平衡度"),
|
||||||
F("F", "短时电压闪变"),
|
F("F", "短时电压闪变"),
|
||||||
|
|||||||
@@ -6,10 +6,6 @@ import lombok.Data;
|
|||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
/**
|
|
||||||
* @author caozehui
|
|
||||||
* @data 2025-03-19
|
|
||||||
*/
|
|
||||||
@Data
|
@Data
|
||||||
public class ReportParam {
|
public class ReportParam {
|
||||||
|
|
||||||
@@ -19,23 +15,29 @@ public class ReportParam {
|
|||||||
@ApiModelProperty(value = "版本号", required = true)
|
@ApiModelProperty(value = "版本号", required = true)
|
||||||
private String version;
|
private String version;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "模式id", required = true)
|
||||||
|
private String pattern;
|
||||||
|
|
||||||
@ApiModelProperty(value = "描述信息", required = true)
|
@ApiModelProperty(value = "描述信息", required = true)
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
@ApiModelProperty(value = "基础模板文件", required = true)
|
@ApiModelProperty(value = "基础模板文件", required = true)
|
||||||
private MultipartFile baseFile;
|
private MultipartFile baseFile;
|
||||||
|
|
||||||
@ApiModelProperty(value = "检测项模版文件", required = true)
|
@ApiModelProperty(value = "检测项模板文件", required = true)
|
||||||
private MultipartFile detailFile;
|
private MultipartFile detailFile;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
public static class QueryParam extends BaseParam {
|
public static class QueryParam extends BaseParam {
|
||||||
@ApiModelProperty(value = "报告模板名称", required = true)
|
@ApiModelProperty(value = "报告模板名称")
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
@ApiModelProperty(value = "版本号", required = true)
|
@ApiModelProperty(value = "版本号")
|
||||||
private String version;
|
private String version;
|
||||||
|
|
||||||
|
@ApiModelProperty(value = "模式id", required = true)
|
||||||
|
private String pattern;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
|
|||||||
@@ -6,17 +6,13 @@ import lombok.Data;
|
|||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author makejava
|
|
||||||
* @date 2025-03-19
|
|
||||||
*/
|
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
@TableName("pq_report")
|
@TableName("pq_report")
|
||||||
public class PqReport extends BaseEntity implements Serializable {
|
public class PqReport extends BaseEntity implements Serializable {
|
||||||
private static final long serialVersionUID = 582972970946593407L;
|
private static final long serialVersionUID = 582972970946593407L;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 报告模板id
|
* 报告模板id
|
||||||
*/
|
*/
|
||||||
@@ -32,13 +28,18 @@ public class PqReport extends BaseEntity implements Serializable {
|
|||||||
*/
|
*/
|
||||||
private String version;
|
private String version;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模式id
|
||||||
|
*/
|
||||||
|
private String pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 基础模板文件路径
|
* 基础模板文件路径
|
||||||
*/
|
*/
|
||||||
private String basePath;
|
private String basePath;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检测项模版文件路径
|
* 检测项模板文件路径
|
||||||
*/
|
*/
|
||||||
private String detailPath;
|
private String detailPath;
|
||||||
|
|
||||||
@@ -52,4 +53,3 @@ public class PqReport extends BaseEntity implements Serializable {
|
|||||||
*/
|
*/
|
||||||
private Integer state;
|
private Integer state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,60 +9,42 @@ import lombok.Data;
|
|||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
/**
|
|
||||||
* @author caozehui
|
|
||||||
* @data 2025-03-19
|
|
||||||
*/
|
|
||||||
@Data
|
@Data
|
||||||
public class PqReportVO {
|
public class PqReportVO {
|
||||||
/**
|
|
||||||
* 报告模板id
|
|
||||||
*/
|
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
/**
|
|
||||||
* 报告模板名称
|
|
||||||
*/
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
/**
|
|
||||||
* 版本号
|
|
||||||
*/
|
|
||||||
private String version;
|
private String version;
|
||||||
|
|
||||||
|
private String pattern;
|
||||||
|
|
||||||
/**
|
|
||||||
* 基础模板文件路径
|
|
||||||
*/
|
|
||||||
private FileVO baseFileVO;
|
private FileVO baseFileVO;
|
||||||
|
|
||||||
/**
|
|
||||||
* 检测项模版文件路径
|
|
||||||
*/
|
|
||||||
private FileVO detailFileVO;
|
private FileVO detailFileVO;
|
||||||
|
|
||||||
/**
|
|
||||||
* 描述信息
|
|
||||||
*/
|
|
||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
/**
|
|
||||||
* 创建时间
|
|
||||||
*/
|
|
||||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||||
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
|
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
|
||||||
@JsonSerialize(using = LocalDateTimeSerializer.class)
|
@JsonSerialize(using = LocalDateTimeSerializer.class)
|
||||||
private LocalDateTime createTime;
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
/**
|
|
||||||
* 状态:0-删除 1-正常
|
|
||||||
*/
|
|
||||||
//private Integer state;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class FileVO{
|
public static class FileVO {
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
private String url;
|
private String url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class OptionVO {
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private String version;
|
||||||
|
|
||||||
|
private String displayName;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,19 +55,12 @@ public interface IPqReportService extends IService<PqReport> {
|
|||||||
*/
|
*/
|
||||||
boolean delete(List<String> ids);
|
boolean delete(List<String> ids);
|
||||||
|
|
||||||
/**
|
List<PqReportVO.OptionVO> listOptions(String pattern);
|
||||||
* 查询所有报告名称
|
|
||||||
*
|
|
||||||
* @return key为报告id,value为报告名称
|
|
||||||
*/
|
|
||||||
List<String> listAllName();
|
|
||||||
|
|
||||||
void generateReport(DevReportParam devReportParam);
|
void generateReport(DevReportParam devReportParam);
|
||||||
|
|
||||||
|
|
||||||
void downloadReport(DevReportParam devReportParam, HttpServletResponse response);
|
void downloadReport(DevReportParam devReportParam, HttpServletResponse response);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备归档操作
|
* 设备归档操作
|
||||||
*
|
*
|
||||||
@@ -82,5 +75,4 @@ public interface IPqReportService extends IService<PqReport> {
|
|||||||
* @param deviceIds 被检设备ID列表,为空时上传所有已生成报告的设备
|
* @param deviceIds 被检设备ID列表,为空时上传所有已生成报告的设备
|
||||||
*/
|
*/
|
||||||
void uploadReportToCloud(List<String> deviceIds);
|
void uploadReportToCloud(List<String> deviceIds);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.njcn.common.pojo.constant.PatternRegex;
|
import com.njcn.common.pojo.constant.PatternRegex;
|
||||||
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
import com.njcn.common.pojo.enums.common.DataStateEnum;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.exception.BusinessException;
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
import com.njcn.common.utils.images.ImageConverter;
|
import com.njcn.common.utils.images.ImageConverter;
|
||||||
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
|
import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
|
||||||
@@ -46,10 +47,12 @@ import com.njcn.gather.plan.pojo.enums.PlanReportStateEnum;
|
|||||||
import com.njcn.gather.plan.pojo.po.AdPlan;
|
import com.njcn.gather.plan.pojo.po.AdPlan;
|
||||||
import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
|
import com.njcn.gather.plan.pojo.po.AdPlanTestConfig;
|
||||||
import com.njcn.gather.plan.service.IAdPlanService;
|
import com.njcn.gather.plan.service.IAdPlanService;
|
||||||
|
import com.njcn.gather.plan.service.IAdPlanSourceService;
|
||||||
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
|
import com.njcn.gather.plan.service.IAdPlanTestConfigService;
|
||||||
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
|
||||||
import com.njcn.gather.report.mapper.PqReportMapper;
|
import com.njcn.gather.report.mapper.PqReportMapper;
|
||||||
import com.njcn.gather.report.pojo.DevReportParam;
|
import com.njcn.gather.report.pojo.DevReportParam;
|
||||||
|
import com.njcn.gather.report.pojo.constant.ItemAnchorConstant;
|
||||||
import com.njcn.gather.report.pojo.constant.PowerConstant;
|
import com.njcn.gather.report.pojo.constant.PowerConstant;
|
||||||
import com.njcn.gather.report.pojo.enums.*;
|
import com.njcn.gather.report.pojo.enums.*;
|
||||||
import com.njcn.gather.report.pojo.param.ReportParam;
|
import com.njcn.gather.report.pojo.param.ReportParam;
|
||||||
@@ -58,9 +61,12 @@ import com.njcn.gather.report.pojo.result.ContrastTestResult;
|
|||||||
import com.njcn.gather.report.pojo.result.SingleTestResult;
|
import com.njcn.gather.report.pojo.result.SingleTestResult;
|
||||||
import com.njcn.gather.report.pojo.vo.PqReportVO;
|
import com.njcn.gather.report.pojo.vo.PqReportVO;
|
||||||
import com.njcn.gather.report.service.IPqReportService;
|
import com.njcn.gather.report.service.IPqReportService;
|
||||||
|
import com.njcn.gather.report.util.ItemAnchorAssembler;
|
||||||
|
import com.njcn.gather.report.util.ItemAnchorSectionUtil;
|
||||||
import com.njcn.gather.result.service.IResultService;
|
import com.njcn.gather.result.service.IResultService;
|
||||||
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
|
import com.njcn.gather.script.pojo.vo.PqScriptDtlDataVO;
|
||||||
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
import com.njcn.gather.script.service.IPqScriptDtlsService;
|
||||||
|
import com.njcn.gather.source.pojo.po.PqSource;
|
||||||
import com.njcn.gather.storage.pojo.param.SingleNonHarmParam;
|
import com.njcn.gather.storage.pojo.param.SingleNonHarmParam;
|
||||||
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
|
import com.njcn.gather.storage.pojo.po.SimAndDigHarmonicResult;
|
||||||
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
|
import com.njcn.gather.storage.pojo.po.SimAndDigNonHarmonicResult;
|
||||||
@@ -68,15 +74,13 @@ import com.njcn.gather.storage.service.SimAndDigHarmonicService;
|
|||||||
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
import com.njcn.gather.storage.service.SimAndDigNonHarmonicService;
|
||||||
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
import com.njcn.gather.system.cfg.pojo.enums.SceneEnum;
|
||||||
import com.njcn.gather.system.cfg.service.ISysTestConfigService;
|
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.DictData;
|
||||||
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
import com.njcn.gather.system.dictionary.service.IDictDataService;
|
||||||
import com.njcn.gather.system.pojo.enums.SystemResponseEnum;
|
import com.njcn.gather.system.pojo.enums.SystemResponseEnum;
|
||||||
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
import com.njcn.gather.tools.report.model.constant.ReportConstant;
|
||||||
import com.njcn.gather.tools.report.service.IWordReportService;
|
import com.njcn.gather.tools.report.service.IWordReportService;
|
||||||
import com.njcn.gather.tools.report.util.BookmarkUtil;
|
import com.njcn.gather.tools.report.util.*;
|
||||||
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.type.pojo.po.DevType;
|
import com.njcn.gather.type.pojo.po.DevType;
|
||||||
import com.njcn.gather.type.service.IDevTypeService;
|
import com.njcn.gather.type.service.IDevTypeService;
|
||||||
import com.njcn.gather.user.user.pojo.po.SysUser;
|
import com.njcn.gather.user.user.pojo.po.SysUser;
|
||||||
@@ -116,6 +120,7 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.NoSuchFileException;
|
import java.nio.file.NoSuchFileException;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -133,13 +138,25 @@ import java.util.stream.Collectors;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> implements IPqReportService {
|
public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> implements IPqReportService {
|
||||||
|
|
||||||
@Value("${report.template:D:\\template}")
|
/**
|
||||||
private String templatePath;
|
* resultMap 内部协议:当 dealDataLine 跑完一轮但未采集到任何有效合格性数据时,
|
||||||
|
* 在 resultMap 中塞入这个 key 作为"已尝试且无数据"的哨兵,避免后续 TEST_RESULT_*
|
||||||
@Value("${report.reportDir:D:\\report}")
|
* 分支的 fallback 重复调用 dealDataLine 浪费资源;同时 dealTestResultLine 检测到
|
||||||
private String reportPath;
|
* 此 key 存在时跳过结论表生成。
|
||||||
|
* <p>
|
||||||
|
* 故意使用明显非业务字符串,避免与任何 PqScriptDtls.scriptCode / PowerIndexEnum
|
||||||
|
* 的真实业务取值撞车。
|
||||||
|
*/
|
||||||
|
private static final String RESULT_MAP_NO_DATA_FLAG = "__internal_no_data__";
|
||||||
|
private static final String[] CHINESE_DIGITS = {"O", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
|
||||||
|
|
||||||
|
// @Value("${report.template:D:\\template}")
|
||||||
|
// private String templatePath;
|
||||||
|
//
|
||||||
|
// @Value("${report.reportDir:D:\\report}")
|
||||||
|
// private String reportPath;
|
||||||
|
private final PathConfig pathConfig;
|
||||||
|
|
||||||
@Value("${qr.cloud}")
|
@Value("${qr.cloud}")
|
||||||
private String cloudUrl;
|
private String cloudUrl;
|
||||||
|
|
||||||
@@ -175,6 +192,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
private final IPqDevSubService iPqDevSubService;
|
private final IPqDevSubService iPqDevSubService;
|
||||||
private final IDictDataService dictDataService;
|
private final IDictDataService dictDataService;
|
||||||
private final IAdPlanService adPlanService;
|
private final IAdPlanService adPlanService;
|
||||||
|
private final IAdPlanSourceService adPlanSourceService;
|
||||||
private final IPqScriptDtlsService pqScriptDtlsService;
|
private final IPqScriptDtlsService pqScriptDtlsService;
|
||||||
private final SimAndDigNonHarmonicService adNonHarmonicService;
|
private final SimAndDigNonHarmonicService adNonHarmonicService;
|
||||||
private final SimAndDigHarmonicService adHarmonicService;
|
private final SimAndDigHarmonicService adHarmonicService;
|
||||||
@@ -197,6 +215,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
QueryWrapper<PqReport> wrapper = new QueryWrapper<>();
|
QueryWrapper<PqReport> wrapper = new QueryWrapper<>();
|
||||||
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "name", queryParam.getName())
|
wrapper.like(StrUtil.isNotBlank(queryParam.getName()), "name", queryParam.getName())
|
||||||
.eq(StrUtil.isNotBlank(queryParam.getVersion()), "version", queryParam.getVersion())
|
.eq(StrUtil.isNotBlank(queryParam.getVersion()), "version", queryParam.getVersion())
|
||||||
|
.eq("pattern", queryParam.getPattern())
|
||||||
.eq("state", DataStateEnum.ENABLE.getCode());
|
.eq("state", DataStateEnum.ENABLE.getCode());
|
||||||
wrapper.orderByDesc("Update_Time");
|
wrapper.orderByDesc("Update_Time");
|
||||||
Page<PqReport> page1 = this.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), wrapper);
|
Page<PqReport> page1 = this.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), wrapper);
|
||||||
@@ -298,11 +317,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<String> listAllName() {
|
public List<PqReportVO.OptionVO> listOptions(String pattern) {
|
||||||
List<PqReport> reportList = this.lambdaQuery()
|
return this.baseMapper.listOptionsByPattern(pattern);
|
||||||
.eq(PqReport::getState, DataStateEnum.ENABLE.getCode()).list();
|
|
||||||
List<String> collect = reportList.stream().map(pqReport -> pqReport.getName() + "_" + pqReport.getVersion()).collect(Collectors.toList());
|
|
||||||
return collect;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -315,8 +331,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
private void uploadFile(ReportParam reportParam, PqReport pqReport, boolean isAdd) {
|
private void uploadFile(ReportParam reportParam, PqReport pqReport, boolean isAdd) {
|
||||||
MultipartFile baseFile = reportParam.getBaseFile();
|
MultipartFile baseFile = reportParam.getBaseFile();
|
||||||
MultipartFile detailFile = reportParam.getDetailFile();
|
MultipartFile detailFile = reportParam.getDetailFile();
|
||||||
String relativePath = reportParam.getName() + File.separator + reportParam.getVersion() + File.separator;
|
String relativePath = this.buildReportTemplateRelativeDir(reportParam.getPattern(), reportParam.getName(), reportParam.getVersion());
|
||||||
String newDir = templatePath + File.separator + relativePath;
|
String newDir = pathConfig.getReportTemplatePath() + File.separator + relativePath;
|
||||||
|
|
||||||
long FILE_SIZE_LIMIT = 5 * 1024 * 1024;
|
long FILE_SIZE_LIMIT = 5 * 1024 * 1024;
|
||||||
if (isAdd) {
|
if (isAdd) {
|
||||||
@@ -393,13 +409,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
// 文件夹重命名
|
// 文件夹重命名
|
||||||
String oldBasePathStr = oldPqReport.getBasePath();
|
String oldBasePathStr = oldPqReport.getBasePath();
|
||||||
String baseName = oldBasePathStr.substring(oldBasePathStr.lastIndexOf(File.separator) + 1);
|
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);
|
Path newBasePath = Paths.get(newDir + baseName);
|
||||||
pqReport.setBasePath(relativePath + baseName);
|
pqReport.setBasePath(relativePath + baseName);
|
||||||
|
|
||||||
String oldDetailPathStr = oldPqReport.getDetailPath();
|
String oldDetailPathStr = oldPqReport.getDetailPath();
|
||||||
String detailName = oldDetailPathStr.substring(oldDetailPathStr.lastIndexOf(File.separator) + 1);
|
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);
|
Path newDetailPath = Paths.get(newDir + detailName);
|
||||||
pqReport.setDetailPath(relativePath + detailName);
|
pqReport.setDetailPath(relativePath + detailName);
|
||||||
|
|
||||||
@@ -410,13 +426,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
Files.move(oldBasePath, newBasePath);
|
Files.move(oldBasePath, newBasePath);
|
||||||
Files.move(oldDetailPath, newDetailPath);
|
Files.move(oldDetailPath, newDetailPath);
|
||||||
if (!oldPqReport.getName().equals(reportParam.getName()) && !this.existSameName(pqReport.getId(), oldPqReport.getName())) {
|
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 {
|
} else {
|
||||||
Paths.get(templatePath + oldDir).toFile().delete();
|
Paths.get(pathConfig.getReportTemplatePath() + oldDir).toFile().delete();
|
||||||
}
|
}
|
||||||
} else {
|
} 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) {
|
} catch (IOException e) {
|
||||||
throw new BusinessException(ReportResponseEnum.FILE_RENAME_FAILED);
|
throw new BusinessException(ReportResponseEnum.FILE_RENAME_FAILED);
|
||||||
@@ -425,13 +441,13 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
|
|
||||||
if (!baseFileOriginalFilename.isEmpty()) {
|
if (!baseFileOriginalFilename.isEmpty()) {
|
||||||
pqReport.setBasePath(relativePath + baseFileOriginalFilename);
|
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();
|
Paths.get(newDir + oldPqReport.getBasePath().substring(oldPqReport.getBasePath().lastIndexOf(File.separator) + 1)).toFile().delete();
|
||||||
this.uploadFile(baseFile, newDir + baseFileOriginalFilename);
|
this.uploadFile(baseFile, newDir + baseFileOriginalFilename);
|
||||||
}
|
}
|
||||||
if (!detailFileOriginalFilename.isEmpty()) {
|
if (!detailFileOriginalFilename.isEmpty()) {
|
||||||
pqReport.setDetailPath(relativePath + detailFileOriginalFilename);
|
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();
|
Paths.get(newDir + oldPqReport.getDetailPath().substring(oldPqReport.getDetailPath().lastIndexOf(File.separator) + 1)).toFile().delete();
|
||||||
this.uploadFile(detailFile, newDir + detailFileOriginalFilename);
|
this.uploadFile(detailFile, newDir + detailFileOriginalFilename);
|
||||||
}
|
}
|
||||||
@@ -516,7 +532,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
private void deleteFile(List<String> ids) {
|
private void deleteFile(List<String> ids) {
|
||||||
List<PqReport> pqReports = this.listByIds(ids);
|
List<PqReport> pqReports = this.listByIds(ids);
|
||||||
for (PqReport pqReport : pqReports) {
|
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);
|
Path uploadPath = Paths.get(uploadDir);
|
||||||
if (Files.exists(uploadPath)) {
|
if (Files.exists(uploadPath)) {
|
||||||
//清空目录下的文件
|
//清空目录下的文件
|
||||||
@@ -528,7 +544,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
file1.delete();
|
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);
|
Path dirPath = Paths.get(dir);
|
||||||
File dirFile = dirPath.toFile();
|
File dirFile = dirPath.toFile();
|
||||||
File[] fileArr2 = dirFile.listFiles();
|
File[] fileArr2 = dirFile.listFiles();
|
||||||
@@ -583,6 +599,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
/**
|
/**
|
||||||
* 根据设备类型生成报告
|
* 根据设备类型生成报告
|
||||||
* 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整
|
* 注:该方法目前仅支持楼下出厂检测场景,属于模板占位符替换方式,后期可能会有调整
|
||||||
|
* <p>
|
||||||
|
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||||
|
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||||
|
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||||
|
* 而非待修复缺陷。
|
||||||
*
|
*
|
||||||
* @param devReportParam 被检设备信息
|
* @param devReportParam 被检设备信息
|
||||||
*/
|
*/
|
||||||
@@ -617,8 +638,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
InputStream finalWordStream = DocxMergeUtil.mergeDocuments(wordFileInputStreams);
|
InputStream finalWordStream = DocxMergeUtil.mergeDocuments(wordFileInputStreams);
|
||||||
// 处理需要输出的目录地址 基础路径+设备类型+装置编号.docx
|
// 处理需要输出的目录地址 基础路径+设备类型+装置编号.docx
|
||||||
// 最终文件输出的路径
|
// 最终文件输出的路径
|
||||||
// String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
// String dirPath = pathConfig.getReportPath().concat(File.separator).concat(devType.getName());
|
||||||
String dirPath = reportPath;
|
String dirPath = pathConfig.getReportPath();
|
||||||
// 确保目录存在
|
// 确保目录存在
|
||||||
ensureDirectoryExists(dirPath);
|
ensureDirectoryExists(dirPath);
|
||||||
String reportFullPath = dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
String reportFullPath = dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX);
|
||||||
@@ -783,6 +804,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
/**
|
/**
|
||||||
* 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果
|
* 需要支持批量生成,如果用户选择批量生成,则默认都采用测试数据的第一个合格,如果
|
||||||
* 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告
|
* 比对模式下生成检测报告,实际后期需要根据用户选择的检测数据或者某次波形数据生成报告
|
||||||
|
* <p>
|
||||||
|
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||||
|
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||||
|
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||||
|
* 而非待修复缺陷。
|
||||||
*
|
*
|
||||||
* @param plan 计划信息
|
* @param plan 计划信息
|
||||||
* @param devReportParam 设备信息
|
* @param devReportParam 设备信息
|
||||||
@@ -806,8 +832,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
if (Objects.isNull(report)) {
|
if (Objects.isNull(report)) {
|
||||||
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
||||||
}
|
}
|
||||||
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
|
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
|
||||||
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
|
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
|
||||||
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
||||||
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
||||||
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
||||||
@@ -821,7 +847,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
|
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
|
||||||
dealDataModelScatteredByBookmarkByPlanContrast(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
|
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);
|
ensureDirectoryExists(dirPath);
|
||||||
// 构建文件名:cityName_gdName_subName_name.docx
|
// 构建文件名:cityName_gdName_subName_name.docx
|
||||||
@@ -839,6 +865,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
Docx4jUtil.addWatermarkToDocument(baseModelDocument, "非正式");
|
Docx4jUtil.addWatermarkToDocument(baseModelDocument, "非正式");
|
||||||
}
|
}
|
||||||
Docx4jUtil.cleanBlankPagesAndRedundantPageBreaks(baseModelDocument);
|
Docx4jUtil.cleanBlankPagesAndRedundantPageBreaks(baseModelDocument);
|
||||||
|
Docx4jUtil.enableUpdateFieldsOnOpen(baseModelDocument);
|
||||||
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(fileName)));
|
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(fileName)));
|
||||||
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
|
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
|
||||||
} catch (NoSuchFileException e) {
|
} catch (NoSuchFileException e) {
|
||||||
@@ -861,6 +888,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
/**
|
/**
|
||||||
* 根据计划绑定的报告模板生成报告
|
* 根据计划绑定的报告模板生成报告
|
||||||
* 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式
|
* 注:该方法目前属于同用信息占位符替换,数据页为面向对象动态填充拼凑方式
|
||||||
|
* <p>
|
||||||
|
* 批量语义:采用"任一设备失败则整批中断"——forEach 循环内任一设备抛 BusinessException
|
||||||
|
* 会终止整个循环,已生成的报告文件保留,中断之后的设备不再处理;失败原因通过异常抛给
|
||||||
|
* 调用方,调用方应提示用户修复问题后重新发起批量。此为有意保留的批量原子语义,
|
||||||
|
* 而非待修复缺陷。
|
||||||
*
|
*
|
||||||
* @param plan 计划信息
|
* @param plan 计划信息
|
||||||
* @param devReportParam 设备信息
|
* @param devReportParam 设备信息
|
||||||
@@ -883,25 +915,38 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
if (Objects.isNull(report)) {
|
if (Objects.isNull(report)) {
|
||||||
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
throw new BusinessException(ReportResponseEnum.REPORT_TEMPLATE_NOT_EXIST);
|
||||||
}
|
}
|
||||||
Path basePath = Paths.get(templatePath + File.separator + report.getBasePath());
|
Path basePath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getBasePath());
|
||||||
Path detailPath = Paths.get(templatePath + File.separator + report.getDetailPath());
|
Path detailPath = Paths.get(pathConfig.getReportTemplatePath() + File.separator + report.getDetailPath());
|
||||||
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
try (InputStream baseInputStream = Files.newInputStream(basePath);
|
||||||
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
InputStream detailInputStream = Files.newInputStream(detailPath)) {
|
||||||
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
WordprocessingMLPackage detailModelDocument = WordprocessingMLPackage.load(detailInputStream);
|
||||||
// 获取文档基础部分,并替换占位符
|
// 获取文档基础部分,并替换占位符
|
||||||
Map<String, String> baseModelDataMap = dealBaseModelData(pqDevVO, devType);
|
Map<String, String> baseModelDataMap = dealBaseModelData(pqDevVO, devType);
|
||||||
|
// 补充检测源名称:计划↔源走 ad_plan_source 中间表(业务上单源),datasourceId 是数据源类型枚举、不指向 pq_source
|
||||||
|
List<PqSource> planSources = adPlanSourceService.listPqSourceByPlanId(plan.getId());
|
||||||
|
baseModelDataMap.put(BaseReportKeyEnum.SOURCE_NAME.getKey(),
|
||||||
|
CollUtil.isNotEmpty(planSources) ? planSources.get(0).getName() : StrUtil.EMPTY);
|
||||||
InputStream wordFinishInputStream = wordReportService.replacePlaceholders(baseInputStream, baseModelDataMap);
|
InputStream wordFinishInputStream = wordReportService.replacePlaceholders(baseInputStream, baseModelDataMap);
|
||||||
WordprocessingMLPackage baseModelDocument = WordprocessingMLPackage.load(wordFinishInputStream);
|
WordprocessingMLPackage baseModelDocument = WordprocessingMLPackage.load(wordFinishInputStream);
|
||||||
MainDocumentPart baseDocumentPart = baseModelDocument.getMainDocumentPart();
|
MainDocumentPart baseDocumentPart = baseModelDocument.getMainDocumentPart();
|
||||||
|
|
||||||
// 获取数据模版页内容,根据脚本动态组装数据页内容
|
// 获取数据模版页内容,根据脚本动态组装数据页内容
|
||||||
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
|
MainDocumentPart detailDocumentPart = detailModelDocument.getMainDocumentPart();
|
||||||
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
|
// 新旧模板分流:base 含白名单内 item_ 前缀书签 → 指标锚点新型模板(云南检定报告类),走独立旁路;
|
||||||
|
// 否则走原路径,行为与改动前完全一致。设计文档 specs/2026-07-02-item-anchor-report-template-design.md §4.1
|
||||||
|
// 书签全文档扫描只做一次,分流判断与新路径共用;老路径方法签名不动,内部自扫
|
||||||
|
List<BookmarkUtil.BookmarkInfo> baseBookmarks = BookmarkUtil.findAllBookmarks(baseDocumentPart);
|
||||||
|
if (hasItemAnchor(baseBookmarks)) {
|
||||||
|
dealDataModelByItemAnchor(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO, baseBookmarks);
|
||||||
|
} else {
|
||||||
|
dealDataModelScatteredByBookmark(baseDocumentPart, detailDocumentPart, devReportParam, pqDevVO);
|
||||||
|
}
|
||||||
|
|
||||||
// 保存新的文档
|
// 保存新的文档
|
||||||
String dirPath = reportPath.concat(File.separator).concat(devType.getName());
|
String dirPath = pathConfig.getReportPath().concat(File.separator).concat(FilePathSanitizer.toSafeFileName(devType.getName()));
|
||||||
// 确保目录存在
|
// 确保目录存在
|
||||||
ensureDirectoryExists(dirPath);
|
ensureDirectoryExists(dirPath);
|
||||||
|
Docx4jUtil.enableUpdateFieldsOnOpen(baseModelDocument);
|
||||||
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX)));
|
baseModelDocument.save(new File(dirPath.concat(File.separator).concat(pqDevVO.getCreateId()).concat(ReportConstant.DOCX)));
|
||||||
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
|
this.updateDevAndPlanState(devId, devReportParam.getPlanId());
|
||||||
} catch (NoSuchFileException e) {
|
} catch (NoSuchFileException e) {
|
||||||
@@ -950,9 +995,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
* 1、数据项
|
* 1、数据项
|
||||||
* 2、结果信息
|
* 2、结果信息
|
||||||
* 3、目录信息
|
* 3、目录信息
|
||||||
* 所以要先先获取的书签进行操作排序
|
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序
|
||||||
* */
|
* */
|
||||||
Collections.sort(bookmarkEnums);
|
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
|
||||||
List<Object> todoInsertList;
|
List<Object> todoInsertList;
|
||||||
BookmarkUtil.BookmarkInfo bookmarkInfo;
|
BookmarkUtil.BookmarkInfo bookmarkInfo;
|
||||||
Map<Integer/*回路号*/, List<ContrastTestResult>> resultMap = null;
|
Map<Integer/*回路号*/, List<ContrastTestResult>> resultMap = null;
|
||||||
@@ -1199,6 +1244,131 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断 base 文档是否为"指标锚点"新型模板(含任一白名单内 item_ 前缀书签)。
|
||||||
|
* 白名单校验在 resolveItemScriptCode 内:老模板中手工遗留的同前缀书签(如 item_1)
|
||||||
|
* 不会触发新路径,避免整份报告错路由导致 DATA_LINE / TEST_RESULT_* 全不填。
|
||||||
|
*
|
||||||
|
* @param bookmarks base 文档书签集合(调用方已扫,避免全文档重复扫描)
|
||||||
|
*/
|
||||||
|
private boolean hasItemAnchor(List<BookmarkUtil.BookmarkInfo> bookmarks) {
|
||||||
|
for (BookmarkUtil.BookmarkInfo info : bookmarks) {
|
||||||
|
if (ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName()) != null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "指标锚点"新型模板装配(云南检定报告类)。
|
||||||
|
* 流程:逐 item_* 锚点 → detail 池取 H5 模板表 → 按回路构造成品表插入锚点;
|
||||||
|
* 无数据/无模板的指标记入隐藏集合 → 区段删除 → 第 7 节编号重排 → 残留书签清理。
|
||||||
|
* 设计文档:docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2
|
||||||
|
*/
|
||||||
|
private void dealDataModelByItemAnchor(MainDocumentPart baseDocumentPart, MainDocumentPart detailDocumentPart,
|
||||||
|
DevReportParam devReportParam, PqDevVO pqDevVO,
|
||||||
|
List<BookmarkUtil.BookmarkInfo> bookmarks) {
|
||||||
|
ObjectFactory factory = new ObjectFactory();
|
||||||
|
// 检测脚本明细按 scriptCode 分组
|
||||||
|
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
|
||||||
|
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream()
|
||||||
|
.collect(Collectors.groupingBy(item -> itemAnchorGroupKey(item.getScriptCode()), LinkedHashMap::new, Collectors.toList()));
|
||||||
|
// detail 模板池按 H5 分组
|
||||||
|
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(detailDocumentPart.getContent(), detailDocumentPart);
|
||||||
|
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream()
|
||||||
|
.collect(Collectors.groupingBy(item -> itemAnchorGroupKey(item.getHeadingText()), LinkedHashMap::new, Collectors.toList()));
|
||||||
|
int devChns = pqDevVO.getDevChns() == null ? 1 : pqDevVO.getDevChns();
|
||||||
|
Set<String> hiddenCodes = new LinkedHashSet<>();
|
||||||
|
for (BookmarkUtil.BookmarkInfo info : bookmarks) {
|
||||||
|
String scriptCode = ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName());
|
||||||
|
if (scriptCode == null) {
|
||||||
|
// 新路径按设计忽略老锚点(互斥分流,spec §4.1);发现 BookmarkEnum 残留提示模板可能混用
|
||||||
|
if (Objects.nonNull(BookmarkEnum.getByKey(info.bookmark.getName()))) {
|
||||||
|
log.warn("指标锚点模板中发现老模板锚点书签 {},新路径不处理该书签", info.bookmark.getName());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<PqScriptDtlDataVO> itemDtls = scriptMap.get(scriptCode);
|
||||||
|
List<Docx4jUtil.HeadingContent> tpl = contentMap.get(scriptCode);
|
||||||
|
if (CollUtil.isEmpty(itemDtls) || CollUtil.isEmpty(tpl)) {
|
||||||
|
log.warn("指标锚点 {} 无脚本数据或无模板分组,整节隐藏", info.bookmark.getName());
|
||||||
|
hiddenCodes.add(scriptCode);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> tableKeys = ItemAnchorAssembler.extractTableKeys(tpl);
|
||||||
|
// 有脚本明细且模板分组在,keys 仍取不到属模板错误 → 显性中断,不得静默走"未测→整节隐藏"
|
||||||
|
ItemAnchorAssembler.requireTableKeys(scriptCode, tableKeys);
|
||||||
|
List<Object> todoInsertList = new ArrayList<>();
|
||||||
|
for (int line = 0; line < devChns; line++) {
|
||||||
|
List<SingleTestResult> results = new ArrayList<>();
|
||||||
|
if (PowerConstant.TIME.contains(scriptCode)) {
|
||||||
|
// 谐波类:一个 scriptIndex 一张表(与老路径语义一致)
|
||||||
|
Map<Integer, List<PqScriptDtlDataVO>> scriptIndexMap = itemDtls.stream()
|
||||||
|
.collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptIndex, TreeMap::new, Collectors.toList()));
|
||||||
|
for (List<PqScriptDtlDataVO> indexItem : scriptIndexMap.values()) {
|
||||||
|
SingleTestResult single = resultService.getFinalContent(indexItem, devReportParam.getPlanCode(), pqDevVO.getId(), line + 1, tableKeys);
|
||||||
|
if (Objects.nonNull(single)) {
|
||||||
|
results.add(single);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
SingleTestResult single = resultService.getFinalContent(itemDtls, devReportParam.getPlanCode(), pqDevVO.getId(), line + 1, tableKeys);
|
||||||
|
if (Objects.nonNull(single)) {
|
||||||
|
results.add(single);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<Object> lineTables = ItemAnchorAssembler.buildTables(scriptCode, results, tpl.get(0), tableKeys, factory);
|
||||||
|
if (lineTables.isEmpty()) {
|
||||||
|
// 该回路无数据,跳过;是否整节隐藏由所有回路汇总后判断
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 回路标题:单回路省略;多回路"测量回路{n}"从 1 起(spec §4.2)
|
||||||
|
if (devChns > 1) {
|
||||||
|
todoInsertList.add(buildItemLineTitle(contentMap, line, factory));
|
||||||
|
}
|
||||||
|
todoInsertList.addAll(lineTables);
|
||||||
|
}
|
||||||
|
if (todoInsertList.isEmpty()) {
|
||||||
|
log.warn("指标 {} 所有回路均无检测数据,整节隐藏", scriptCode);
|
||||||
|
hiddenCodes.add(scriptCode);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
BookmarkUtil.insertElement(info, todoInsertList);
|
||||||
|
// 已填充节不再需要 item/sect 标记:空锚点段直接删除,避免表格前残留空行;
|
||||||
|
// 若未来模板把锚点放进非空段,则只清书签保留段落正文。
|
||||||
|
if (!ItemAnchorSectionUtil.removeEmptyItemAnchorParagraph(info)) {
|
||||||
|
BookmarkUtil.removeBookmark(info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ItemAnchorSectionUtil.removeSectRanges(baseDocumentPart, hiddenCodes);
|
||||||
|
ItemAnchorSectionUtil.renumberChapter7(baseDocumentPart);
|
||||||
|
ItemAnchorSectionUtil.stripItemAnchorBookmarks(baseDocumentPart);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String itemAnchorGroupKey(String value) {
|
||||||
|
return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新型模板的回路标题(仅多回路时被调用):"测量回路{n}",n 从 1 起。
|
||||||
|
* 与老路径 getLineTitle 的差异(有意):不带 "n." 前缀、单回路由调用方直接省略。
|
||||||
|
*/
|
||||||
|
private P buildItemLineTitle(Map<String, List<Docx4jUtil.HeadingContent>> contentMap, int lineIndex, ObjectFactory factory) {
|
||||||
|
int lineNo = lineIndex + 1;
|
||||||
|
P titleParagraph = factory.createP();
|
||||||
|
PPr pPr = factory.createPPr();
|
||||||
|
PPrBase.Spacing spacing = factory.createPPrBaseSpacing();
|
||||||
|
spacing.setBefore(BigInteger.valueOf(60));
|
||||||
|
spacing.setAfter(BigInteger.valueOf(20));
|
||||||
|
spacing.setLine(BigInteger.valueOf(240));
|
||||||
|
spacing.setLineRule(STLineSpacingRule.AUTO);
|
||||||
|
pPr.setSpacing(spacing);
|
||||||
|
titleParagraph.setPPr(pPr);
|
||||||
|
Docx4jUtil.createTitle(factory, titleParagraph, "测量回路" + lineNo, 24, true);
|
||||||
|
return titleParagraph;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 通过提前在模板文档里埋下书签
|
* 通过提前在模板文档里埋下书签
|
||||||
* 1、目录信息
|
* 1、目录信息
|
||||||
@@ -1230,9 +1400,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
* 1、数据项
|
* 1、数据项
|
||||||
* 2、结果信息
|
* 2、结果信息
|
||||||
* 3、目录信息
|
* 3、目录信息
|
||||||
* 所以要先先获取的书签进行操作排序
|
* 按 BookmarkEnum.sort 字段排序,避免依赖枚举常量声明顺序
|
||||||
* */
|
* */
|
||||||
Collections.sort(bookmarkEnums);
|
bookmarkEnums.sort(Comparator.comparingInt(BookmarkEnum::getSort).thenComparingInt(Enum::ordinal));
|
||||||
// 定义个结果,以便存在结果信息的书签
|
// 定义个结果,以便存在结果信息的书签
|
||||||
Map<String/*指标名称*/, List<Boolean/*以回路的顺序填充结果*/>> resultMap = new HashMap<>();
|
Map<String/*指标名称*/, List<Boolean/*以回路的顺序填充结果*/>> resultMap = new HashMap<>();
|
||||||
List<Object> todoInsertList;
|
List<Object> todoInsertList;
|
||||||
@@ -1246,6 +1416,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.DATA_LINE.getKey(), bookmarks);
|
bookmarkInfo = BookmarkUtil.getBookmarkInfo(BookmarkEnum.DATA_LINE.getKey(), bookmarks);
|
||||||
todoInsertList = dealDataLine(detailDocumentPart, devReportParam, pqDevVO, resultMap);
|
todoInsertList = dealDataLine(detailDocumentPart, devReportParam, pqDevVO, resultMap);
|
||||||
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
|
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
|
||||||
|
// 锚点位于 base 模板中间(其后仍有有效内容)时,在数据块末尾补一个分页符,
|
||||||
|
// 让 base 剩余部分另起新页;锚点在文档末尾时不加,存量模板行为不变
|
||||||
|
if (hasContentAfterBookmark(bookmarkInfo)) {
|
||||||
|
todoInsertList.add(Docx4jUtil.getPageBreak());
|
||||||
|
}
|
||||||
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
|
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
|
||||||
BookmarkUtil.removeBookmark(bookmarkInfo);
|
BookmarkUtil.removeBookmark(bookmarkInfo);
|
||||||
}
|
}
|
||||||
@@ -1281,7 +1456,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
if (CollUtil.isEmpty(resultMap)) {
|
if (CollUtil.isEmpty(resultMap)) {
|
||||||
dealDataLine(baseDocumentPart, devReportParam, pqDevVO, 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);
|
todoInsertList = dealTestResultLine(devReportParam, resultMap, DocAnchorEnum.TEST_RESULT_DETAIL);
|
||||||
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
|
if (Objects.nonNull(bookmarkInfo) && CollectionUtil.isNotEmpty(todoInsertList)) {
|
||||||
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
|
BookmarkUtil.insertElement(bookmarkInfo, todoInsertList);
|
||||||
@@ -1298,6 +1473,40 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断书签段落之后是否还有有意义的内容(非空文本段落,或表格等非段落元素)。
|
||||||
|
* <p>
|
||||||
|
* 用于数模式 DATA_LINE 锚点位于 base 模板中间时,决定是否在插入的数据块末尾追加分页符,
|
||||||
|
* 使 base 剩余部分另起新页;书签在文档末尾(其后仅剩空段落)时返回 false,不追加分页符,
|
||||||
|
* 避免末尾凭空多出一页空白,存量模板(锚点在末尾)行为保持不变。
|
||||||
|
* <p>
|
||||||
|
* 注:仅以文本判断段落是否有意义,纯图片段落不会被识别为有效内容。
|
||||||
|
*
|
||||||
|
* @param bookmarkInfo 书签信息
|
||||||
|
* @return 书签之后存在有意义内容时返回 true
|
||||||
|
*/
|
||||||
|
private boolean hasContentAfterBookmark(BookmarkUtil.BookmarkInfo bookmarkInfo) {
|
||||||
|
List<Object> parentContent = bookmarkInfo.parentContainer.getContent();
|
||||||
|
int idx = parentContent.indexOf(bookmarkInfo.parentParagraph);
|
||||||
|
if (idx < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (int i = idx + 1; i < parentContent.size(); i++) {
|
||||||
|
Object obj = parentContent.get(i);
|
||||||
|
Object realObj = (obj instanceof JAXBElement) ? ((JAXBElement<?>) obj).getValue() : obj;
|
||||||
|
if (realObj instanceof P) {
|
||||||
|
// 非空文本段落才算有意义,纯空段落不触发分页
|
||||||
|
if (StrUtil.isNotBlank(Docx4jUtil.getTextFromP((P) realObj))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 表格等非段落元素一律视为有意义内容
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 如何处理结果性数据进文档,各省级平台的结果表格不一致,如何做到一致
|
* 如何处理结果性数据进文档,各省级平台的结果表格不一致,如何做到一致
|
||||||
@@ -1306,8 +1515,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
*/
|
*/
|
||||||
private List<Object> dealTestResultLine(DevReportParam devReportParam, Map<String, List<Boolean>> resultMap, DocAnchorEnum docAnchorEnum) {
|
private List<Object> dealTestResultLine(DevReportParam devReportParam, Map<String, List<Boolean>> resultMap, DocAnchorEnum docAnchorEnum) {
|
||||||
List<Object> todoInsertList = new ArrayList<>();
|
List<Object> todoInsertList = new ArrayList<>();
|
||||||
// 先判断数据有没有,如果没有,则不处理
|
// 先判断数据有没有,如果没有,则不处理(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)
|
||||||
if (CollUtil.isEmpty(resultMap.get(PowerIndexEnum.UNKNOWN.getKey()))) {
|
if (!resultMap.containsKey(RESULT_MAP_NO_DATA_FLAG)) {
|
||||||
ObjectFactory factory = Context.getWmlObjectFactory();
|
ObjectFactory factory = Context.getWmlObjectFactory();
|
||||||
// 源文档的内容
|
// 源文档的内容
|
||||||
// 创建表格(示例为3列,列数可任意调整)
|
// 创建表格(示例为3列,列数可任意调整)
|
||||||
@@ -1396,13 +1605,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 modelPart 文档模板部分;常规传 detail 文档,fallback 仅需算 resultMap 时可传 base 文档
|
||||||
* @param devReportParam 测试报告参数
|
* @param devReportParam 测试报告参数
|
||||||
* @param pqDevVO 被检设备
|
* @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<>();
|
List<Object> todoInsertList = new ArrayList<>();
|
||||||
// 以回路维度处理数据项
|
// 以回路维度处理数据项
|
||||||
Integer devChns = pqDevVO.getDevChns();
|
Integer devChns = pqDevVO.getDevChns();
|
||||||
@@ -1410,8 +1633,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
// 读取该计划的检测大项组装数据内容
|
// 读取该计划的检测大项组装数据内容
|
||||||
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
|
List<PqScriptDtlDataVO> pqScriptDtlsList = pqScriptDtlsService.getScriptDtlsDataList(devReportParam.getScriptId());
|
||||||
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList()));
|
Map<String, List<PqScriptDtlDataVO>> scriptMap = pqScriptDtlsList.stream().collect(Collectors.groupingBy(PqScriptDtlDataVO::getScriptCode, LinkedHashMap::new, Collectors.toList()));
|
||||||
List<Object> allContent = detailModelDocument.getContent();
|
List<Object> allContent = modelPart.getContent();
|
||||||
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, detailModelDocument);
|
List<Docx4jUtil.HeadingContent> headingContents = Docx4jUtil.extractHeading5Contents(allContent, modelPart);
|
||||||
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream().collect(Collectors.groupingBy(Docx4jUtil.HeadingContent::getHeadingText, Collectors.toList()));
|
Map<String, List<Docx4jUtil.HeadingContent>> contentMap = headingContents.stream().collect(Collectors.groupingBy(Docx4jUtil.HeadingContent::getHeadingText, Collectors.toList()));
|
||||||
for (int i = 0; i < devChns; i++) {
|
for (int i = 0; i < devChns; i++) {
|
||||||
// 回路标题
|
// 回路标题
|
||||||
@@ -1479,9 +1702,11 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 如果经过一顿处理后,结果性数据集合还是空,塞个特殊数据进去,避免嵌套循环
|
// 经过一轮处理仍未采集到任何合格性数据时,塞入哨兵:
|
||||||
|
// 一是让后续 TEST_RESULT_* 分支的 fallback 看到 resultMap 非空而跳过重复调用本方法,
|
||||||
|
// 二是供 dealTestResultLine 据此跳过结论表生成(哨兵协议详见 RESULT_MAP_NO_DATA_FLAG 注释)。
|
||||||
if (CollUtil.isEmpty(resultMap)) {
|
if (CollUtil.isEmpty(resultMap)) {
|
||||||
resultMap.put(PowerIndexEnum.UNKNOWN.getKey(), Collections.singletonList(false));
|
resultMap.put(RESULT_MAP_NO_DATA_FLAG, Collections.singletonList(false));
|
||||||
}
|
}
|
||||||
return todoInsertList;
|
return todoInsertList;
|
||||||
}
|
}
|
||||||
@@ -1894,7 +2119,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
|
|
||||||
if (SceneEnum.LEAVE_FACTORY_TEST.getValue().equals(currrentScene)) {
|
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;
|
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||||
} else if (plan != null) {
|
} else if (plan != null) {
|
||||||
// 根据计划模式确定路径结构
|
// 根据计划模式确定路径结构
|
||||||
@@ -1906,16 +2131,16 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
pqDevVO.getGdName() != null ? pqDevVO.getGdName() : "未知供电公司",
|
pqDevVO.getGdName() != null ? pqDevVO.getGdName() : "未知供电公司",
|
||||||
pqDevVO.getSubName() != null ? pqDevVO.getSubName() : "未知电站",
|
pqDevVO.getSubName() != null ? pqDevVO.getSubName() : "未知电站",
|
||||||
pqDevVO.getName() != null ? pqDevVO.getName() : "未知设备");
|
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;
|
downloadFileName = fileName;
|
||||||
} else {
|
} 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;
|
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||||
}
|
}
|
||||||
} else {
|
} 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;
|
downloadFileName = pqDevVO.getCreateId() + ReportConstant.DOCX;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2038,13 +2263,14 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
// 软件版本
|
// 软件版本
|
||||||
baseModelMap.put(BaseReportKeyEnum.SW_VERSION.getKey(), StrUtil.isNotBlank(pqDevVO.getSoftwareVersion()) ? pqDevVO.getSoftwareVersion() : StrUtil.EMPTY);
|
baseModelMap.put(BaseReportKeyEnum.SW_VERSION.getKey(), StrUtil.isNotBlank(pqDevVO.getSoftwareVersion()) ? pqDevVO.getSoftwareVersion() : StrUtil.EMPTY);
|
||||||
// 调试日期
|
// 调试日期
|
||||||
if (pqDevVO.getCheckTime() != null) {
|
if (pqDevVO.getCheckEndTime() != null) {
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(pqDevVO.getCheckTime(), DatePattern.CHINESE_DATE_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(pqDevVO.getCheckEndTime(), DatePattern.CHINESE_DATE_PATTERN));
|
||||||
} else {
|
} else {
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
|
||||||
}
|
}
|
||||||
// 装置编码
|
// 装置编码
|
||||||
baseModelMap.put(BaseReportKeyEnum.DEV_CODE.getKey(), pqDevVO.getCreateId());
|
baseModelMap.put(BaseReportKeyEnum.DEV_CODE.getKey(), pqDevVO.getCreateId());
|
||||||
|
baseModelMap.put(BaseReportKeyEnum.DEV_NAME.getKey(), StrUtil.isBlank(pqDevVO.getName()) ? StrPool.TAB : pqDevVO.getName());
|
||||||
// 工作电源
|
// 工作电源
|
||||||
baseModelMap.put(BaseReportKeyEnum.POWER.getKey(), devType.getPower());
|
baseModelMap.put(BaseReportKeyEnum.POWER.getKey(), devType.getPower());
|
||||||
// 额定电流
|
// 额定电流
|
||||||
@@ -2082,14 +2308,17 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
baseModelMap.put(BaseReportKeyEnum.SAMPLE_ID.getKey(), StrUtil.isEmpty(pqDevVO.getSampleId()) ? StrPool.TAB : pqDevVO.getSampleId());
|
baseModelMap.put(BaseReportKeyEnum.SAMPLE_ID.getKey(), StrUtil.isEmpty(pqDevVO.getSampleId()) ? StrPool.TAB : pqDevVO.getSampleId());
|
||||||
// 收样日期
|
// 收样日期
|
||||||
baseModelMap.put(BaseReportKeyEnum.ARRIVED_DATE.getKey(), Objects.isNull(pqDevVO.getArrivedDate()) ? StrPool.TAB : String.valueOf(pqDevVO.getArrivedDate()));
|
baseModelMap.put(BaseReportKeyEnum.ARRIVED_DATE.getKey(), Objects.isNull(pqDevVO.getArrivedDate()) ? StrPool.TAB : String.valueOf(pqDevVO.getArrivedDate()));
|
||||||
|
baseModelMap.put(BaseReportKeyEnum.ARRIVED_DATE_C.getKey(), Objects.isNull(pqDevVO.getArrivedDate()) ? StrPool.TAB : formatNumberChineseDate(pqDevVO.getArrivedDate()));
|
||||||
// 检测日期
|
// 检测日期
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), Objects.isNull(pqDevVO.getCheckTime()) ? StrPool.TAB : String.valueOf(pqDevVO.getCheckTime()).substring(0, 10));
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), Objects.isNull(pqDevVO.getCheckEndTime()) ? StrPool.TAB : String.valueOf(pqDevVO.getCheckEndTime()).substring(0, 10));
|
||||||
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE_C.getKey(), Objects.isNull(pqDevVO.getCheckEndTime()) ? StrPool.TAB : formatNumberChineseDate(pqDevVO.getCheckEndTime().toLocalDate()));
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEMPERATURE.getKey(), Objects.isNull(pqDevVO.getTemperature()) ? StrPool.TAB : pqDevVO.getTemperature().toString());
|
baseModelMap.put(BaseReportKeyEnum.TEMPERATURE.getKey(), Objects.isNull(pqDevVO.getTemperature()) ? StrPool.TAB : pqDevVO.getTemperature().toString());
|
||||||
baseModelMap.put(BaseReportKeyEnum.HUMIDITY.getKey(), Objects.isNull(pqDevVO.getHumidity()) ? StrPool.TAB : pqDevVO.getHumidity().toString());
|
baseModelMap.put(BaseReportKeyEnum.HUMIDITY.getKey(), Objects.isNull(pqDevVO.getHumidity()) ? StrPool.TAB : pqDevVO.getHumidity().toString());
|
||||||
baseModelMap.put(BaseReportKeyEnum.YEAR.getKey(), DateUtil.format(new Date(), DatePattern.NORM_YEAR_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.YEAR.getKey(), DateUtil.format(new Date(), DatePattern.NORM_YEAR_PATTERN));
|
||||||
baseModelMap.put(BaseReportKeyEnum.MONTH.getKey(), DateUtil.format(new Date(), DatePattern.SIMPLE_MONTH_PATTERN).substring(4));
|
baseModelMap.put(BaseReportKeyEnum.MONTH.getKey(), DateUtil.format(new Date(), DatePattern.SIMPLE_MONTH_PATTERN).substring(4));
|
||||||
baseModelMap.put(BaseReportKeyEnum.DAY.getKey(), DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN).substring(6));
|
baseModelMap.put(BaseReportKeyEnum.DAY.getKey(), DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN).substring(6));
|
||||||
baseModelMap.put(BaseReportKeyEnum.YEAR_MONTH_DAY.getKey(), DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.YEAR_MONTH_DAY.getKey(), DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
|
||||||
|
baseModelMap.put(BaseReportKeyEnum.YEAR_MONTH_DAY_UP.getKey(), formatChineseReportDate(LocalDate.now()));
|
||||||
baseModelMap.put(BaseReportKeyEnum.REPORT_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.REPORT_DATE.getKey(), DateUtil.format(new Date(), DatePattern.CHINESE_DATE_PATTERN));
|
||||||
return baseModelMap;
|
return baseModelMap;
|
||||||
}
|
}
|
||||||
@@ -2156,9 +2385,9 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
// 检测日期
|
// 检测日期
|
||||||
PqDevSub devSub = iPqDevSubService.lambdaQuery().eq(PqDevSub::getDevId, pqDevVO.getId()).one();
|
PqDevSub devSub = iPqDevSubService.lambdaQuery().eq(PqDevSub::getDevId, pqDevVO.getId()).one();
|
||||||
if (Objects.nonNull(devSub)) {
|
if (Objects.nonNull(devSub)) {
|
||||||
LocalDateTime checkTime = devSub.getCheckTime();
|
LocalDateTime checkEndTime = devSub.getCheckEndTime();
|
||||||
if (Objects.nonNull(checkTime)) {
|
if (Objects.nonNull(checkEndTime)) {
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(checkTime, DatePattern.NORM_DATE_PATTERN));
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), DateUtil.format(checkEndTime, DatePattern.NORM_DATE_PATTERN));
|
||||||
} else {
|
} else {
|
||||||
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), StrPool.TAB);
|
baseModelMap.put(BaseReportKeyEnum.TEST_DATE.getKey(), StrPool.TAB);
|
||||||
}
|
}
|
||||||
@@ -2394,6 +2623,40 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
return String.format("%.4f", bp.setScale(i, RoundingMode.HALF_UP).doubleValue());
|
return String.format("%.4f", bp.setScale(i, RoundingMode.HALF_UP).doubleValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static String formatChineseReportDate(LocalDate date) {
|
||||||
|
Objects.requireNonNull(date, "date");
|
||||||
|
return formatChineseYear(date.getYear()) + "年"
|
||||||
|
+ formatChineseMonthDayNumber(date.getMonthValue()) + "月"
|
||||||
|
+ formatChineseMonthDayNumber(date.getDayOfMonth()) + "日";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String formatNumberChineseDate(LocalDate date) {
|
||||||
|
Objects.requireNonNull(date, "date");
|
||||||
|
return date.getYear() + "年" + date.getMonthValue() + "月" + date.getDayOfMonth() + "日";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatChineseYear(int year) {
|
||||||
|
String yearValue = String.valueOf(year);
|
||||||
|
StringBuilder builder = new StringBuilder(yearValue.length());
|
||||||
|
for (int i = 0; i < yearValue.length(); i++) {
|
||||||
|
builder.append(CHINESE_DIGITS[yearValue.charAt(i) - '0']);
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formatChineseMonthDayNumber(int value) {
|
||||||
|
if (value < 10) {
|
||||||
|
return CHINESE_DIGITS[value];
|
||||||
|
}
|
||||||
|
if (value == 10) {
|
||||||
|
return "十";
|
||||||
|
}
|
||||||
|
if (value < 20) {
|
||||||
|
return "十" + CHINESE_DIGITS[value % 10];
|
||||||
|
}
|
||||||
|
return CHINESE_DIGITS[value / 10] + "十" + (value % 10 == 0 ? "" : CHINESE_DIGITS[value % 10]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private void ensureDirectoryExists(String directoryPath) {
|
private void ensureDirectoryExists(String directoryPath) {
|
||||||
File directory = new File(directoryPath);
|
File directory = new File(directoryPath);
|
||||||
@@ -2415,7 +2678,8 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
*/
|
*/
|
||||||
private void checkRepeat(ReportParam reportParam, boolean isExcludeSelf) {
|
private void checkRepeat(ReportParam reportParam, boolean isExcludeSelf) {
|
||||||
QueryWrapper<PqReport> wrapper = new QueryWrapper();
|
QueryWrapper<PqReport> wrapper = new QueryWrapper();
|
||||||
wrapper.eq("name", reportParam.getName())
|
wrapper.eq("pattern", reportParam.getPattern())
|
||||||
|
.eq("name", reportParam.getName())
|
||||||
.eq("version", reportParam.getVersion())
|
.eq("version", reportParam.getVersion())
|
||||||
.eq("state", DataStateEnum.ENABLE.getCode());
|
.eq("state", DataStateEnum.ENABLE.getCode());
|
||||||
if (isExcludeSelf) {
|
if (isExcludeSelf) {
|
||||||
@@ -2429,6 +2693,21 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String sanitizePathSegment(String value) {
|
||||||
|
return StrUtil.blankToDefault(value, StrUtil.EMPTY).replaceAll("[\\\\/:*?\"<>|]", "_").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildReportTemplateRelativeDir(String patternId, String name, String version) {
|
||||||
|
DictData dictData = dictDataService.getDictDataById(patternId);
|
||||||
|
if (ObjectUtil.isNull(dictData) || StrUtil.isBlank(dictData.getName())) {
|
||||||
|
throw new BusinessException(CommonResponseEnum.FAIL, "模式不存在或字典名称缺失");
|
||||||
|
}
|
||||||
|
String patternName = this.sanitizePathSegment(dictData.getName());
|
||||||
|
String reportName = this.sanitizePathSegment(name);
|
||||||
|
String reportVersion = this.sanitizePathSegment(version);
|
||||||
|
return patternName + File.separator + reportName + File.separator + reportVersion + File.separator;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void uploadReportToCloud(List<String> deviceIds) {
|
public void uploadReportToCloud(List<String> deviceIds) {
|
||||||
log.info("开始批量上传检测报告到云端,设备ID列表:{}", deviceIds);
|
log.info("开始批量上传检测报告到云端,设备ID列表:{}", deviceIds);
|
||||||
@@ -2443,7 +2722,7 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
log.info("找到{}台设备需要上传报告", devices.size());
|
log.info("找到{}台设备需要上传报告", devices.size());
|
||||||
String dirPath = reportPath;
|
String dirPath = pathConfig.getReportPath();
|
||||||
// 确保目录存在
|
// 确保目录存在
|
||||||
ensureDirectoryExists(dirPath);
|
ensureDirectoryExists(dirPath);
|
||||||
// 异步批量上传每台设备的报告
|
// 异步批量上传每台设备的报告
|
||||||
@@ -2487,13 +2766,14 @@ public class PqReportServiceImpl extends ServiceImpl<PqReportMapper, PqReport> i
|
|||||||
List<Docx4jUtil.HeadingContent> headingContents = contentMap.get(PowerIndexEnum.LINE_TITLE.getKey());
|
List<Docx4jUtil.HeadingContent> headingContents = contentMap.get(PowerIndexEnum.LINE_TITLE.getKey());
|
||||||
int lineNo = currentLine + 1;
|
int lineNo = currentLine + 1;
|
||||||
// 如果contentMap中有指定内容,创建大纲级别为2的标题
|
// 如果contentMap中有指定内容,创建大纲级别为2的标题
|
||||||
|
// 回路标题恒带回路号(单回路也显示"测量回路1"),与结论表头"测量回路N"保持一致
|
||||||
if (CollUtil.isNotEmpty(headingContents)) {
|
if (CollUtil.isNotEmpty(headingContents)) {
|
||||||
return Docx4jUtil.createTitle(factory, 2, totalLine > 1 ? lineNo + ".测量回路" + lineNo : lineNo + ".测量回路",
|
return Docx4jUtil.createTitle(factory, 2, lineNo + ".测量回路" + lineNo,
|
||||||
"SimSun", 30, true);
|
"SimSun", 30, true);
|
||||||
}
|
}
|
||||||
// 没有模板配置时,创建默认样式段落
|
// 没有模板配置时,创建默认样式段落
|
||||||
P titleParagraph = factory.createP();
|
P titleParagraph = factory.createP();
|
||||||
Docx4jUtil.createTitle(factory, titleParagraph, totalLine > 1 ? "测量回路" + lineNo : "测量回路",
|
Docx4jUtil.createTitle(factory, titleParagraph, "测量回路" + lineNo,
|
||||||
28, true);
|
28, true);
|
||||||
return titleParagraph;
|
return titleParagraph;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,532 @@
|
|||||||
|
package com.njcn.gather.report.util;
|
||||||
|
|
||||||
|
import cn.hutool.core.collection.CollUtil;
|
||||||
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.gather.report.pojo.enums.ItemReportKeyEnum;
|
||||||
|
import com.njcn.gather.report.pojo.result.SingleTestResult;
|
||||||
|
import com.njcn.gather.tools.report.util.Docx4jUtil;
|
||||||
|
import org.docx4j.wml.ObjectFactory;
|
||||||
|
import org.docx4j.wml.P;
|
||||||
|
import org.docx4j.wml.R;
|
||||||
|
import org.docx4j.wml.RPr;
|
||||||
|
import org.docx4j.wml.Tbl;
|
||||||
|
import org.docx4j.wml.Tc;
|
||||||
|
import org.docx4j.wml.TcPr;
|
||||||
|
import org.docx4j.wml.Text;
|
||||||
|
import org.docx4j.wml.Tr;
|
||||||
|
import org.docx4j.wml.TrPr;
|
||||||
|
|
||||||
|
import javax.xml.bind.JAXBElement;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "指标锚点"模板的表格装配器:模板表(末行为 key 行)+ SingleTestResult → 成品表列表。
|
||||||
|
* 只服务新路径,不被老路径引用;对 Docx4jUtil 只调用不修改。
|
||||||
|
* 设计文档:docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2 / §6
|
||||||
|
*
|
||||||
|
* @author hongawen
|
||||||
|
*/
|
||||||
|
public final class ItemAnchorAssembler {
|
||||||
|
|
||||||
|
private ItemAnchorAssembler() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造成品表。results 每个有效元素产出一张表(谐波类调用方按 scriptIndex 拆分后传入)。
|
||||||
|
*
|
||||||
|
* @param scriptCode 指标编码(P 走有功功率特例映射)
|
||||||
|
* @param results 检测结果列表,null/空 detail 的元素跳过
|
||||||
|
* @param template detail 模板池中该指标的 H5 分组(取其中第一张表为模板)
|
||||||
|
* @param tableKeys key 行的占位符列表(调用方经 Docx4jUtil.getTableFillKeys 读出)
|
||||||
|
* @param factory docx4j 工厂
|
||||||
|
* @return 待插入锚点的表格元素列表(JAXBElement<Tbl>)
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static List<Object> buildTables(String scriptCode, List<SingleTestResult> results,
|
||||||
|
Docx4jUtil.HeadingContent template, List<String> tableKeys,
|
||||||
|
ObjectFactory factory) {
|
||||||
|
List<Object> out = new ArrayList<>();
|
||||||
|
JAXBElement<Tbl> templateTbl = findFirstTable(template);
|
||||||
|
if (templateTbl == null || CollUtil.isEmpty(results) || CollUtil.isEmpty(tableKeys)) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
int tableNo = 0;
|
||||||
|
for (SingleTestResult result : results) {
|
||||||
|
List<Map<String, String>> rows = flattenRows(result, scriptCode);
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
tableNo++;
|
||||||
|
applyHarmonicDerivedValues(rows, scriptCode);
|
||||||
|
Map<String, String> fixedPlaceholders = buildHarmonicFixedPlaceholders(rows, scriptCode);
|
||||||
|
JAXBElement<Tbl> copied;
|
||||||
|
try {
|
||||||
|
copied = Docx4jUtil.deepCopyTbl(templateTbl);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("指标锚点模板表深拷贝失败: " + scriptCode, e);
|
||||||
|
}
|
||||||
|
Tbl tbl = copied.getValue();
|
||||||
|
replaceFixedPlaceholders(tbl, fixedPlaceholders);
|
||||||
|
applyHarmonicPowerHeader(tbl, scriptCode, tableNo, rows);
|
||||||
|
List<Object> trs = tbl.getContent();
|
||||||
|
// 模板规范约定:最后一行是 key 行(不走 judgeTableCross,新路径自带定位依据);
|
||||||
|
// 从尾部找最后一个真正的 Tr——Word 重存可能把 bookmarkStart/End 漏成 w:tbl 直接子节点(本仓 _GoBack 先例)
|
||||||
|
Tr keyRow = findLastRow(trs);
|
||||||
|
if (keyRow == null) {
|
||||||
|
throw new BusinessException("指标 " + scriptCode + " 的模板表无有效行,请检查 detail 模板该分组表格");
|
||||||
|
}
|
||||||
|
TrPr trPr = keyRow.getTrPr();
|
||||||
|
List<TcPr> tcPrList = new ArrayList<>();
|
||||||
|
RPr templateRPr = null;
|
||||||
|
for (Object cellObj : keyRow.getContent()) {
|
||||||
|
if (cellObj instanceof JAXBElement) {
|
||||||
|
Tc cell = ((JAXBElement<Tc>) cellObj).getValue();
|
||||||
|
TcPr tcPr = cell.getTcPr() != null ? cell.getTcPr() : factory.createTcPr();
|
||||||
|
// 注意:不覆写 tcW(老 fill 的 5000/n 均分会破坏客户模板列宽),沿用模板原宽
|
||||||
|
tcPrList.add(tcPr);
|
||||||
|
if (templateRPr == null && !cell.getContent().isEmpty() && cell.getContent().get(0) instanceof P) {
|
||||||
|
templateRPr = Docx4jUtil.getTcPrFromParagraph((P) cell.getContent().get(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trs.remove(keyRow);
|
||||||
|
for (Map<String, String> row : rows) {
|
||||||
|
// 缺失 key 一律补空串:"拿不到的先空着"(spec §6 #2)
|
||||||
|
for (String key : tableKeys) {
|
||||||
|
row.putIfAbsent(key, "");
|
||||||
|
}
|
||||||
|
Tr newRow = Docx4jUtil.createCustomRow(factory, row, tableKeys, trPr, tcPrList, templateRPr, true);
|
||||||
|
// Docx4jUtil.createCustomRow 产出的单元格是裸 Tc(未包 JAXBElement),
|
||||||
|
// 与模板行(真实 docx4j 解析结果 / deepCopy 而来)里统一的 JAXBElement<Tc> 不一致;
|
||||||
|
// 这里做一次归一化包装,避免下游按 JAXBElement 读取该行时 ClassCastException(不改 createCustomRow 本身)
|
||||||
|
List<Object> normalized = new ArrayList<>();
|
||||||
|
for (Object cellObj : newRow.getContent()) {
|
||||||
|
if (cellObj instanceof Tc) {
|
||||||
|
normalized.add(factory.createTrTc((Tc) cellObj));
|
||||||
|
} else {
|
||||||
|
normalized.add(cellObj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newRow.getContent().clear();
|
||||||
|
newRow.getContent().addAll(normalized);
|
||||||
|
trs.add(newRow);
|
||||||
|
}
|
||||||
|
out.add(copied);
|
||||||
|
}
|
||||||
|
// 多表(谐波类多 scriptIndex)背靠背插入时,OOXML 相邻 w:tbl 会被 Word 合并渲染成一张大表;
|
||||||
|
// 只插入空段落做结构分隔。测点号属于 HP 表内标题单元格,不能作为表外可见段落。
|
||||||
|
if (out.size() > 1) {
|
||||||
|
List<Object> withSeparators = new ArrayList<>(out.size() * 2 - 1);
|
||||||
|
for (int i = 0; i < out.size(); i++) {
|
||||||
|
withSeparators.add(out.get(i));
|
||||||
|
if (i < out.size() - 1) {
|
||||||
|
withSeparators.add(factory.createP());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return withSeparators;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验模板 key 行占位符已成功取出。调用方仅在"该指标有脚本明细且模板分组存在"时调用:
|
||||||
|
* 此时 keys 为空属模板错误(key 行缺失或表结构不符合 getTableFillKeys 的识别规则),
|
||||||
|
* 必须显性中断报告生成,不得静默走"未测→整节隐藏"(否则有数据的节凭空消失,违反红线 2)。
|
||||||
|
*/
|
||||||
|
public static void requireTableKeys(String scriptCode, List<String> tableKeys) {
|
||||||
|
if (CollUtil.isEmpty(tableKeys)) {
|
||||||
|
throw new BusinessException("指标 " + scriptCode + " 的模板表 key 行占位符解析为空,请检查 detail 模板该分组的表格(表末行应为占位符 key 行),已中断报告生成");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 指标锚点模板专用 key 读取:按 spec 直接取 H5 分组第一张表的最后一个真实 Tr。
|
||||||
|
* 不复用旧 getTableFillKeys 的横/纵表启发式,避免 HV/HI/HP 标题区末格为数值时被误判。
|
||||||
|
*/
|
||||||
|
public static List<String> extractTableKeys(List<Docx4jUtil.HeadingContent> tempContent) {
|
||||||
|
List<String> keys = new ArrayList<>();
|
||||||
|
if (CollUtil.isEmpty(tempContent)) {
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
JAXBElement<Tbl> table = findFirstTable(tempContent.get(0));
|
||||||
|
if (table == null) {
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
Tr keyRow = findLastRow(table.getValue().getContent());
|
||||||
|
if (keyRow == null) {
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
for (Object cellObj : keyRow.getContent()) {
|
||||||
|
Object value = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
|
||||||
|
if (value instanceof Tc) {
|
||||||
|
keys.add(Docx4jUtil.getTextFromCell((Tc) value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从尾部向前找最后一个真正的 Tr(含 JAXBElement 解包);无 Tr 返回 null */
|
||||||
|
private static Tr findLastRow(List<Object> content) {
|
||||||
|
for (int i = content.size() - 1; i >= 0; i--) {
|
||||||
|
Object v = content.get(i) instanceof JAXBElement
|
||||||
|
? ((JAXBElement<?>) content.get(i)).getValue() : content.get(i);
|
||||||
|
if (v instanceof Tr) {
|
||||||
|
return (Tr) v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 SingleTestResult 的三层嵌套 detail 摊平成行列表,并做新模板专属的行级补充:
|
||||||
|
* errorScope 注入(HV/HI/HP 的标准限值列)、time 缺失时"测点{n}"兜底(F/IMBV/IMBA)、P 有功特例。
|
||||||
|
*/
|
||||||
|
static List<Map<String, String>> flattenRows(SingleTestResult result, String scriptCode) {
|
||||||
|
List<Map<String, String>> out = new ArrayList<>();
|
||||||
|
if (result == null || CollUtil.isEmpty(result.getDetail())) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
int seq = 0;
|
||||||
|
for (Map.Entry<String, List<Map<String, List<Map<String, String>>>>> influenceEntry : result.getDetail().entrySet()) {
|
||||||
|
if (influenceEntry.getValue() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Map<String, List<Map<String, String>>> byError : influenceEntry.getValue()) {
|
||||||
|
if (byError == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Map.Entry<String, List<Map<String, String>>> errorEntry : byError.entrySet()) {
|
||||||
|
String errorScope = errorEntry.getKey();
|
||||||
|
if (errorEntry.getValue() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Map<String, String> raw : errorEntry.getValue()) {
|
||||||
|
seq++;
|
||||||
|
Map<String, String> row = new LinkedHashMap<>(raw);
|
||||||
|
applyErrorScope(row, scriptCode, errorScope);
|
||||||
|
if (StrUtil.isBlank(row.get(ItemReportKeyEnum.TIME.getKey()))) {
|
||||||
|
row.put(ItemReportKeyEnum.TIME.getKey(), "测点" + seq);
|
||||||
|
}
|
||||||
|
if ("P".equalsIgnoreCase(scriptCode)) {
|
||||||
|
applyPowerMapping(row);
|
||||||
|
}
|
||||||
|
out.add(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void applyErrorScope(Map<String, String> row, String scriptCode, String errorScope) {
|
||||||
|
String key = ItemReportKeyEnum.ERROR_SCOPE.getKey();
|
||||||
|
if ("HV".equalsIgnoreCase(scriptCode) || "HP".equalsIgnoreCase(scriptCode)) {
|
||||||
|
String value = StrUtil.isBlank(row.get(key)) ? errorScope : row.get(key);
|
||||||
|
row.put(key, stripTrailingUnit(value));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
row.putIfAbsent(key, errorScope);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String stripTrailingUnit(String value) {
|
||||||
|
if (StrUtil.isBlank(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return value.trim().replaceFirst("\\s*(?:(?:[%%‰°℃]|[a-zA-Z]+|[\\u4e00-\\u9fa5]+)\\s*)+$", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P(有功功率)特例:activePower = 三相实测之和;设置类与无功/视在/功率因数数据侧暂无,留空。
|
||||||
|
* spec §6 #2 处置。
|
||||||
|
*/
|
||||||
|
static void applyPowerMapping(Map<String, String> row) {
|
||||||
|
BigDecimal sum = BigDecimal.ZERO;
|
||||||
|
boolean hasValue = false;
|
||||||
|
for (String key : Arrays.asList(ItemReportKeyEnum.TEST_A.getKey(),
|
||||||
|
ItemReportKeyEnum.TEST_B.getKey(), ItemReportKeyEnum.TEST_C.getKey())) {
|
||||||
|
String value = row.get(key);
|
||||||
|
if (StrUtil.isNotBlank(value)) {
|
||||||
|
try {
|
||||||
|
sum = sum.add(new BigDecimal(value.trim()));
|
||||||
|
hasValue = true;
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
// 非数值(如"--")不参与求和
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String activePower = row.get(ItemReportKeyEnum.ACTIVE_POWER.getKey());
|
||||||
|
if (hasValue && (StrUtil.isBlank(activePower) || "/".equals(activePower))) {
|
||||||
|
row.put(ItemReportKeyEnum.ACTIVE_POWER.getKey(), sum.toPlainString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void applyHarmonicDerivedValues(List<Map<String, String>> rows, String scriptCode) {
|
||||||
|
if (!"HI".equalsIgnoreCase(scriptCode)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Map<String, String> row : rows) {
|
||||||
|
String scriptStandardRate = row.get(ItemReportKeyEnum.STANDARD_RATE.getKey());
|
||||||
|
String standardRate = parseNumber(scriptStandardRate) == null ? "" : scriptStandardRate;
|
||||||
|
String testRateA = rate(row.get(ItemReportKeyEnum.TEST_A.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_A.getKey()));
|
||||||
|
String testRateB = rate(row.get(ItemReportKeyEnum.TEST_B.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_B.getKey()));
|
||||||
|
String testRateC = rate(row.get(ItemReportKeyEnum.TEST_C.getKey()), row.get(ItemReportKeyEnum.BASE_CURRENT_C.getKey()));
|
||||||
|
String errorRateA = difference(testRateA, standardRate);
|
||||||
|
String errorRateB = difference(testRateB, standardRate);
|
||||||
|
String errorRateC = difference(testRateC, standardRate);
|
||||||
|
row.put(ItemReportKeyEnum.STANDARD_RATE.getKey(), standardRate);
|
||||||
|
row.put(ItemReportKeyEnum.TEST_RATE_A.getKey(), testRateA);
|
||||||
|
row.put(ItemReportKeyEnum.TEST_RATE_B.getKey(), testRateB);
|
||||||
|
row.put(ItemReportKeyEnum.TEST_RATE_C.getKey(), testRateC);
|
||||||
|
row.put(ItemReportKeyEnum.ERROR_RATE_A.getKey(), errorRateA);
|
||||||
|
row.put(ItemReportKeyEnum.ERROR_RATE_B.getKey(), errorRateB);
|
||||||
|
row.put(ItemReportKeyEnum.ERROR_RATE_C.getKey(), errorRateC);
|
||||||
|
row.put(ItemReportKeyEnum.ERROR_SCOPE.getKey(), harmonicCurrentErrorScope(standardRate));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String harmonicCurrentErrorScope(String standardRateText) {
|
||||||
|
Double standardRate = parseNumber(standardRateText);
|
||||||
|
if (standardRate == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
double limit = standardRate >= 3D ? standardRate * 0.05D : 0.15D;
|
||||||
|
return "±" + format4(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> buildHarmonicFixedPlaceholders(List<Map<String, String>> rows, String scriptCode) {
|
||||||
|
Map<String, String> placeholders = new LinkedHashMap<>();
|
||||||
|
if ("HV".equalsIgnoreCase(scriptCode)) {
|
||||||
|
placeholders.put(ItemReportKeyEnum.STANDARD_THD.getKey(), thd(rows, ItemReportKeyEnum.STANDARD.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_A.getKey(), thd(rows, ItemReportKeyEnum.TEST_A.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_B.getKey(), thd(rows, ItemReportKeyEnum.TEST_B.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_C.getKey(), thd(rows, ItemReportKeyEnum.TEST_C.getKey()));
|
||||||
|
} else if ("HI".equalsIgnoreCase(scriptCode)) {
|
||||||
|
placeholders.put(ItemReportKeyEnum.STANDARD_THD.getKey(), thd(rows, ItemReportKeyEnum.STANDARD_RATE.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_A.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_A.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_B.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_B.getKey()));
|
||||||
|
placeholders.put(ItemReportKeyEnum.THD_C.getKey(), thd(rows, ItemReportKeyEnum.TEST_RATE_C.getKey()));
|
||||||
|
}
|
||||||
|
return placeholders;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void applyHarmonicPowerHeader(Tbl tbl, String scriptCode, int pointNo, List<Map<String, String>> rows) {
|
||||||
|
if (!"HP".equalsIgnoreCase(scriptCode)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Tr firstRow = findFirstRow(tbl.getContent());
|
||||||
|
if (firstRow == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Tc titleCell = cellAt(firstRow, 0);
|
||||||
|
if (titleCell == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String title = Docx4jUtil.getTextFromCell(titleCell);
|
||||||
|
String baseTitle = StrUtil.blankToDefault(title, StrUtil.EMPTY)
|
||||||
|
.replaceFirst("(测点\\s*\\d+)$", "");
|
||||||
|
setCellText(titleCell, baseTitle + "(测点" + pointNo + ")");
|
||||||
|
fillNextCellByLabel(tbl, "基波电压", firstDataValue(rows, ItemReportKeyEnum.STANDARD_V.getKey()));
|
||||||
|
fillNextCellByLabel(tbl, "基波电流", firstDataValue(rows, ItemReportKeyEnum.STANDARD_I.getKey()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstDataValue(List<Map<String, String>> rows, String key) {
|
||||||
|
if (CollUtil.isEmpty(rows)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
for (Map<String, String> row : rows) {
|
||||||
|
String value = row.get(key);
|
||||||
|
if (StrUtil.isNotBlank(value) && !"/".equals(value.trim())) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void fillNextCellByLabel(Tbl tbl, String label, String value) {
|
||||||
|
if (StrUtil.isBlank(value) || tbl == null || tbl.getContent() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object o : tbl.getContent()) {
|
||||||
|
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
|
||||||
|
if (v instanceof Tr && fillNextCellByLabel((Tr) v, label, value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean fillNextCellByLabel(Tr row, String label, String value) {
|
||||||
|
if (StrUtil.isBlank(value) || row == null || row.getContent() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
List<Object> cells = row.getContent();
|
||||||
|
for (int i = 0; i < cells.size() - 1; i++) {
|
||||||
|
Tc labelCell = cellAt(row, i);
|
||||||
|
if (labelCell != null && Docx4jUtil.getTextFromCell(labelCell).contains(label)) {
|
||||||
|
Tc valueCell = cellAt(row, i + 1);
|
||||||
|
if (valueCell != null) {
|
||||||
|
setCellText(valueCell, value);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Tr findFirstRow(List<Object> content) {
|
||||||
|
for (Object o : content) {
|
||||||
|
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
|
||||||
|
if (v instanceof Tr) {
|
||||||
|
return (Tr) v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Tc cellAt(Tr row, int index) {
|
||||||
|
if (row == null || row.getContent() == null || row.getContent().size() <= index) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Object cellObj = row.getContent().get(index);
|
||||||
|
Object value = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
|
||||||
|
return value instanceof Tc ? (Tc) value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String rate(String numeratorText, String denominatorText) {
|
||||||
|
Double numerator = parseNumber(numeratorText);
|
||||||
|
Double denominator = parseNumber(denominatorText);
|
||||||
|
if (numerator == null || denominator == null || denominator == 0D) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return format4(numerator / denominator * 100D);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String difference(String minuendText, String subtrahendText) {
|
||||||
|
Double minuend = parseNumber(minuendText);
|
||||||
|
Double subtrahend = parseNumber(subtrahendText);
|
||||||
|
if (minuend == null || subtrahend == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return format4(minuend - subtrahend);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String thd(List<Map<String, String>> rows, String key) {
|
||||||
|
double sum = 0D;
|
||||||
|
boolean hasValue = false;
|
||||||
|
for (Map<String, String> row : rows) {
|
||||||
|
Double value = parseNumber(row.get(key));
|
||||||
|
if (value != null) {
|
||||||
|
sum += value * value;
|
||||||
|
hasValue = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasValue ? format4(Math.sqrt(sum)) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Double parseNumber(String text) {
|
||||||
|
if (StrUtil.isBlank(text) || "/".equals(text.trim()) || "--".equals(text.trim())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Double.parseDouble(text.trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String format4(double value) {
|
||||||
|
return String.format(Locale.ROOT, "%.4f", value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void replaceFixedPlaceholders(Tbl tbl, Map<String, String> values) {
|
||||||
|
if (values.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object rowObj : tbl.getContent()) {
|
||||||
|
Object rowValue = rowObj instanceof JAXBElement ? ((JAXBElement<?>) rowObj).getValue() : rowObj;
|
||||||
|
if (!(rowValue instanceof Tr)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Object cellObj : ((Tr) rowValue).getContent()) {
|
||||||
|
Object cellValue = cellObj instanceof JAXBElement ? ((JAXBElement<?>) cellObj).getValue() : cellObj;
|
||||||
|
if (cellValue instanceof Tc) {
|
||||||
|
Tc cell = (Tc) cellValue;
|
||||||
|
String replacement = values.get(Docx4jUtil.getTextFromCell(cell));
|
||||||
|
if (replacement != null) {
|
||||||
|
setCellText(cell, replacement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void setCellText(Tc cell, String value) {
|
||||||
|
P firstParagraph = null;
|
||||||
|
for (Object content : cell.getContent()) {
|
||||||
|
if (content instanceof P) {
|
||||||
|
firstParagraph = (P) content;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (firstParagraph == null) {
|
||||||
|
firstParagraph = new P();
|
||||||
|
cell.getContent().add(firstParagraph);
|
||||||
|
}
|
||||||
|
boolean written = false;
|
||||||
|
for (Object paragraphObj : cell.getContent()) {
|
||||||
|
if (!(paragraphObj instanceof P)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
P paragraph = (P) paragraphObj;
|
||||||
|
for (Object runObj : paragraph.getContent()) {
|
||||||
|
if (!(runObj instanceof R)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
R run = (R) runObj;
|
||||||
|
for (Object textObj : run.getContent()) {
|
||||||
|
Text text = unwrapText(textObj);
|
||||||
|
if (text != null) {
|
||||||
|
text.setValue(written ? "" : value);
|
||||||
|
written = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!written) {
|
||||||
|
R run = new R();
|
||||||
|
Text text = new Text();
|
||||||
|
text.setValue(value);
|
||||||
|
run.getContent().add(text);
|
||||||
|
firstParagraph.getContent().add(run);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Text unwrapText(Object textObj) {
|
||||||
|
if (textObj instanceof Text) {
|
||||||
|
return (Text) textObj;
|
||||||
|
}
|
||||||
|
if (textObj instanceof JAXBElement && ((JAXBElement<?>) textObj).getValue() instanceof Text) {
|
||||||
|
return (Text) ((JAXBElement<?>) textObj).getValue();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static JAXBElement<Tbl> findFirstTable(Docx4jUtil.HeadingContent template) {
|
||||||
|
if (template == null || CollUtil.isEmpty(template.getSubContent())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (Object o : template.getSubContent()) {
|
||||||
|
if (o instanceof JAXBElement && ((JAXBElement<?>) o).getValue() instanceof Tbl) {
|
||||||
|
return (JAXBElement<Tbl>) o;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
package com.njcn.gather.report.util;
|
||||||
|
|
||||||
|
import com.njcn.gather.report.pojo.constant.ItemAnchorConstant;
|
||||||
|
import com.njcn.gather.tools.report.util.BookmarkUtil;
|
||||||
|
import com.njcn.gather.tools.report.util.Docx4jUtil;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
|
||||||
|
import org.docx4j.wml.CTBookmark;
|
||||||
|
import org.docx4j.wml.CTMarkupRange;
|
||||||
|
import org.docx4j.wml.P;
|
||||||
|
import org.docx4j.wml.R;
|
||||||
|
import org.docx4j.wml.Text;
|
||||||
|
|
||||||
|
import javax.xml.bind.JAXBElement;
|
||||||
|
import java.math.BigInteger;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "指标锚点"模板的区段隐藏 / 编号重排 / 书签清理工具。
|
||||||
|
* 只服务新路径 dealDataModelByItemAnchor,不被老路径引用。
|
||||||
|
* 设计文档:docs/superpowers/specs/2026-07-02-item-anchor-report-template-design.md §4.2
|
||||||
|
*
|
||||||
|
* @author hongawen
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public final class ItemAnchorSectionUtil {
|
||||||
|
|
||||||
|
private ItemAnchorSectionUtil() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 三级编号:7.x.y(半角点) */
|
||||||
|
private static final Pattern LEVEL3 = Pattern.compile("^7\\.(\\d+)\\.(\\d+)");
|
||||||
|
/** 二级编号:7.x(半角点,排除 7.x.y) */
|
||||||
|
private static final Pattern LEVEL2 = Pattern.compile("^7\\.(\\d+)(?![\\.\\d])");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除已填充 item_* 的空锚点段,避免插入表格前残留一行空段落。
|
||||||
|
* 只处理指标锚点新路径的白名单 item_*;段落内存在正文时保留,防止模板内容被误删。
|
||||||
|
*/
|
||||||
|
public static boolean removeEmptyItemAnchorParagraph(BookmarkUtil.BookmarkInfo info) {
|
||||||
|
if (info == null || info.bookmark == null || info.parentParagraph == null || info.parentContainer == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (ItemAnchorConstant.resolveItemScriptCode(info.bookmark.getName()) == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String text = Docx4jUtil.getTextFromP(info.parentParagraph);
|
||||||
|
if (text != null && !text.trim().isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return info.parentContainer.getContent().remove(info.parentParagraph);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除隐藏指标对应的 sect_{code} 区段(body 块级整段删除)。
|
||||||
|
* GRP 折叠规则:GRP_CHILDREN 中某组的子节全部在 hiddenCodes 中时,删父节区段(含组标题与组内公共文字),
|
||||||
|
* 不再单删子节;父区段定位失败时回退按子节各自删除,避免组和子节一个都删不掉(静默违反红线 2)。
|
||||||
|
*/
|
||||||
|
public static void removeSectRanges(MainDocumentPart part, Set<String> hiddenCodes) {
|
||||||
|
if (part == null || hiddenCodes == null || hiddenCodes.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<Object> body = part.getContent();
|
||||||
|
// 单遍扫描收集全部书签区段,后续按名 O(1) 取用
|
||||||
|
Map<String, int[]> allRanges = locateRanges(body);
|
||||||
|
List<int[]> ranges = new ArrayList<>();
|
||||||
|
Set<String> coveredByGrp = new HashSet<>();
|
||||||
|
for (Map.Entry<String, List<String>> entry : ItemAnchorConstant.GRP_CHILDREN.entrySet()) {
|
||||||
|
if (!hiddenCodes.containsAll(entry.getValue())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int[] grpRange = allRanges.get((ItemAnchorConstant.SECT_PREFIX + entry.getKey()).toLowerCase());
|
||||||
|
if (grpRange != null) {
|
||||||
|
ranges.add(grpRange);
|
||||||
|
coveredByGrp.addAll(entry.getValue());
|
||||||
|
} else {
|
||||||
|
log.warn("父区段书签 {}{} 定位失败,回退按子节区段各自删除,请检查模板书签是否完整",
|
||||||
|
ItemAnchorConstant.SECT_PREFIX, entry.getKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (String code : hiddenCodes) {
|
||||||
|
if (coveredByGrp.contains(code)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int[] range = allRanges.get((ItemAnchorConstant.SECT_PREFIX + code).toLowerCase());
|
||||||
|
if (range != null) {
|
||||||
|
ranges.add(range);
|
||||||
|
} else {
|
||||||
|
log.warn("区段书签 {}{} 定位失败,该节无法隐藏,请检查模板书签是否完整",
|
||||||
|
ItemAnchorConstant.SECT_PREFIX, code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 起点降序删除,避免前面的删除让后面的索引失效
|
||||||
|
ranges.sort((a, b) -> Integer.compare(b[0], a[0]));
|
||||||
|
for (int[] range : ranges) {
|
||||||
|
for (int i = range[1]; i >= range[0]; i--) {
|
||||||
|
if (i < body.size()) {
|
||||||
|
body.remove(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理全文残留的 item_ / sect_ 书签(start 与配对的 end),其他书签不动。
|
||||||
|
* 已填充节的 sect end 会被 BookmarkUtil.removeBookmark 顺带清掉,留下无 end 的 start,本方法兜底清理。
|
||||||
|
*/
|
||||||
|
public static void stripItemAnchorBookmarks(MainDocumentPart part) {
|
||||||
|
if (part == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Set<BigInteger> ourIds = new HashSet<>();
|
||||||
|
// 第一遍:删 start 并记 id
|
||||||
|
for (Object block : part.getContent()) {
|
||||||
|
P p = asP(block);
|
||||||
|
if (p == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Iterator<Object> it = p.getContent().iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
Object v = unwrap(it.next());
|
||||||
|
if (v instanceof CTBookmark) {
|
||||||
|
String name = ((CTBookmark) v).getName();
|
||||||
|
if (isOurNamespace(name)) {
|
||||||
|
ourIds.add(((CTBookmark) v).getId());
|
||||||
|
it.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 第二遍:删配对 end
|
||||||
|
for (Object block : part.getContent()) {
|
||||||
|
P p = asP(block);
|
||||||
|
if (p == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Iterator<Object> it = p.getContent().iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
Object v = unwrap(it.next());
|
||||||
|
if (v instanceof CTMarkupRange && !(v instanceof CTBookmark)
|
||||||
|
&& ourIds.contains(((CTMarkupRange) v).getId())) {
|
||||||
|
it.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 第 7 节编号重排:区段删除后,把剩余的 7.x / 7.x.y 标题按出现顺序重写为连续编号。
|
||||||
|
* 顶级"7.准确度检查:"用全角点,正则天然不匹配,保持不动。
|
||||||
|
*/
|
||||||
|
public static void renumberChapter7(MainDocumentPart part) {
|
||||||
|
if (part == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int l2 = 0;
|
||||||
|
int l3 = 0;
|
||||||
|
for (Object block : part.getContent()) {
|
||||||
|
P p = asP(block);
|
||||||
|
if (p == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String text = Docx4jUtil.getTextFromP(p);
|
||||||
|
if (text == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Matcher m3 = LEVEL3.matcher(text);
|
||||||
|
if (m3.find()) {
|
||||||
|
l3++;
|
||||||
|
String newPrefix = "7." + l2 + "." + l3;
|
||||||
|
if (!m3.group().equals(newPrefix)) {
|
||||||
|
replacePrefix(p, m3.group().length(), newPrefix);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Matcher m2 = LEVEL2.matcher(text);
|
||||||
|
if (m2.find()) {
|
||||||
|
l2++;
|
||||||
|
l3 = 0;
|
||||||
|
String newPrefix = "7." + l2;
|
||||||
|
if (!m2.group().equals(newPrefix)) {
|
||||||
|
replacePrefix(p, m2.group().length(), newPrefix);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单遍扫描 body,收集全部段落内书签区段:书签名(小写)→ [start块下标, end块下标]。
|
||||||
|
* 同名书签只记首个(与逐名定位"取第一处命中"语义一致);无配对 end 的 start 不产出条目。
|
||||||
|
*/
|
||||||
|
private static Map<String, int[]> locateRanges(List<Object> body) {
|
||||||
|
Map<String, int[]> out = new HashMap<>();
|
||||||
|
Map<BigInteger, String> openNames = new HashMap<>();
|
||||||
|
Map<BigInteger, Integer> openStarts = new HashMap<>();
|
||||||
|
for (int i = 0; i < body.size(); i++) {
|
||||||
|
P p = asP(body.get(i));
|
||||||
|
if (p == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Object o : p.getContent()) {
|
||||||
|
Object v = unwrap(o);
|
||||||
|
// CTBookmark 继承 CTMarkupRange:先判 start,else 分支天然排除 CTBookmark,即 bookmarkEnd
|
||||||
|
if (v instanceof CTBookmark) {
|
||||||
|
CTBookmark start = (CTBookmark) v;
|
||||||
|
if (start.getName() != null && start.getId() != null) {
|
||||||
|
openNames.put(start.getId(), start.getName().toLowerCase());
|
||||||
|
openStarts.put(start.getId(), i);
|
||||||
|
}
|
||||||
|
} else if (v instanceof CTMarkupRange) {
|
||||||
|
BigInteger id = ((CTMarkupRange) v).getId();
|
||||||
|
String name = openNames.remove(id);
|
||||||
|
if (name != null) {
|
||||||
|
out.putIfAbsent(name, new int[]{openStarts.remove(id), i});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isOurNamespace(String name) {
|
||||||
|
if (name == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String lower = name.toLowerCase();
|
||||||
|
return lower.startsWith(ItemAnchorConstant.ITEM_PREFIX) || lower.startsWith(ItemAnchorConstant.SECT_PREFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object unwrap(Object o) {
|
||||||
|
return (o instanceof JAXBElement) ? ((JAXBElement<?>) o).getValue() : o;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static P asP(Object block) {
|
||||||
|
Object v = unwrap(block);
|
||||||
|
return (v instanceof P) ? (P) v : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 跨 run 替换段首前 oldLen 个字符为 newPrefix(编号可能被 Word 拆进多个 text 节点) */
|
||||||
|
private static void replacePrefix(P p, int oldLen, String newPrefix) {
|
||||||
|
List<Text> texts = new ArrayList<>();
|
||||||
|
collectTexts(p.getContent(), texts);
|
||||||
|
int remaining = oldLen;
|
||||||
|
boolean inserted = false;
|
||||||
|
for (Text t : texts) {
|
||||||
|
if (remaining <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
String value = t.getValue() == null ? "" : t.getValue();
|
||||||
|
int cut = Math.min(remaining, value.length());
|
||||||
|
remaining -= cut;
|
||||||
|
String rest = value.substring(cut);
|
||||||
|
t.setValue(inserted ? rest : newPrefix + rest);
|
||||||
|
inserted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectTexts(List<Object> content, List<Text> out) {
|
||||||
|
for (Object o : content) {
|
||||||
|
Object v = unwrap(o);
|
||||||
|
if (v instanceof R) {
|
||||||
|
collectTexts(((R) v).getContent(), out);
|
||||||
|
} else if (v instanceof Text) {
|
||||||
|
out.add((Text) v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -163,6 +163,18 @@ public class ResultController extends BaseController {
|
|||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@GetMapping("/createChecksquareTask")
|
||||||
|
@ApiOperation("调用第三方数模数据检测接口")
|
||||||
|
@ApiImplicitParam(name = "devId", value = "设备id", required = true)
|
||||||
|
public HttpResult<DataCheckResultVO> createChecksquareTask(@RequestParam("devId") String devId) {
|
||||||
|
String methodDescribe = getMethodDescribe("createChecksquareTask");
|
||||||
|
LogUtil.njcnDebug(log, "{},调用第三方数模数据检测接口,设备id为:{}", methodDescribe, devId);
|
||||||
|
|
||||||
|
DataCheckResultVO result = resultService.createChecksquareTaskByDevId(devId);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
@GetMapping("/getMonitorDataSourceResult")
|
@GetMapping("/getMonitorDataSourceResult")
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ public enum ResultUnitEnum {
|
|||||||
IMBA("%", "电流不平衡度","IMBA"),
|
IMBA("%", "电流不平衡度","IMBA"),
|
||||||
F("","闪变","F"),
|
F("","闪变","F"),
|
||||||
P("W", "功率","P"),
|
P("W", "功率","P"),
|
||||||
|
ANGLE("°", "相角","Angle"),
|
||||||
|
|
||||||
UNKNOWN("","未知","UNKNOWN"),
|
UNKNOWN("","未知","UNKNOWN"),
|
||||||
;
|
;
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.njcn.gather.result.pojo.param;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class DataCheckRequest {
|
||||||
|
private List<String> lineIds;
|
||||||
|
private List<String> indicatorCodes;
|
||||||
|
private String timeStart;
|
||||||
|
private String timeEnd;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user