修复2次关源指令bug

完善数据校验结果接口调用
pqdif功补充
This commit is contained in:
caozehui
2026-06-23 10:04:16 +08:00
parent d746e68d63
commit 9990183c5d
36 changed files with 703 additions and 911 deletions

View File

@@ -150,6 +150,10 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>

View File

@@ -16,6 +16,7 @@ import com.njcn.gather.detection.pojo.po.DevData;
import com.njcn.gather.detection.pojo.po.IcdCheckData;
import com.njcn.gather.detection.pojo.po.SourceCompareDev;
import com.njcn.gather.detection.pojo.vo.*;
import com.njcn.gather.detection.service.FormalTestEventPublisher;
import com.njcn.gather.detection.service.impl.DetectionServiceImpl;
import com.njcn.gather.detection.util.DetectionUtil;
import com.njcn.gather.detection.util.socket.*;
@@ -83,6 +84,7 @@ public class SocketDevResponseService {
private final IDictDataService dictDataService;
private final IPqSourceService pqSourceService;
private final IResultService resultService;
private final FormalTestEventPublisher formalTestEventPublisher;
@Value("${dataCheck.enable}")
private Boolean dataCheck;
@@ -1229,6 +1231,7 @@ public class SocketDevResponseService {
socketMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
SocketManager.sendMsg(param.getUserPageId() + CnSocketUtil.SOURCE_TAG, JSON.toJSONString(socketMsg));
this.publishFormalStartIfNeeded();
webSocketVO.setDesc(null);
WebServiceManager.sendMsg(param.getUserPageId(), JSON.toJSONString(webSocketVO));
} else {
@@ -1386,7 +1389,7 @@ public class SocketDevResponseService {
List<String> valueType = iPqScriptCheckDataService.getValueType(checkDataParam);
iPqDevService.updateResult(param.getDevIds(), valueType, param.getCode(), param.getUserId(), param.getTemperature(), param.getHumidity(), true);
if (dataCheck) {
if (Boolean.TRUE.equals(dataCheck)) {
resultService.tryNotifyThirdPartyAfterFormalTest(param);
}
CnSocketUtil.quitSend(param);
@@ -1527,6 +1530,7 @@ public class SocketDevResponseService {
switch (Objects.requireNonNull(operateCodeEnum)) {
case QUIT_INIT_01:
//关闭所有
publishFormalEndIfNeeded();
SocketManager.removeUser(s);
CnSocketUtil.quitSendSource(param);
break;
@@ -1549,6 +1553,7 @@ public class SocketDevResponseService {
case NO_INIT_DEV:
switch (operateCodeEnum) {
case QUIT_INIT_01:
publishFormalEndIfNeeded();
SocketManager.removeUser(s);
// CnSocketUtil.quitSendSource(param);
break;
@@ -1571,6 +1576,22 @@ public class SocketDevResponseService {
}
private void publishFormalEndIfNeeded() {
if (FormalTestManager.endEventPublished && !Boolean.TRUE.equals(dataCheck)) {
return;
}
formalTestEventPublisher.publishEnd(FormalTestManager.sessionId, FormalTestManager.devList);
FormalTestManager.endEventPublished = true;
}
private void publishFormalStartIfNeeded() {
if (FormalTestManager.startEventPublished || ObjectUtil.isNull(FormalTestManager.sessionId) && !Boolean.TRUE.equals(dataCheck)) {
return;
}
formalTestEventPublisher.publishStart(FormalTestManager.sessionId, FormalTestManager.devList);
FormalTestManager.startEventPublished = true;
}
/**
* @param issue
* @return key为V或Ivalue为对应的源下发信息
@@ -1816,6 +1837,9 @@ public class SocketDevResponseService {
FormalTestManager.overload = getOverloadResult(param);
FormalTestManager.checkStartTime = LocalDateTime.now();
FormalTestManager.reCheckType = param.getReCheckType();
FormalTestManager.sessionId = UUID.randomUUID().toString().replace("-", "");
FormalTestManager.startEventPublished = false;
FormalTestManager.endEventPublished = false;
}

View File

@@ -0,0 +1,17 @@
package com.njcn.gather.detection.pojo.vo;
import lombok.Data;
@Data
public class FormalTestDevicePayload {
private String deviceId;
private String monitorId;
private String deviceIp;
private String deviceType;
private String icdMappingName;
}

View File

@@ -0,0 +1,18 @@
package com.njcn.gather.detection.pojo.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class FormalTestEventPayload {
private String eventType;
private LocalDateTime eventTime;
private String sessionId;
private List<FormalTestDevicePayload> devices;
}

View File

@@ -0,0 +1,12 @@
package com.njcn.gather.detection.service;
import com.njcn.gather.device.pojo.vo.PreDetection;
import java.util.List;
public interface FormalTestEventPublisher {
void publishStart(String sessionId, List<PreDetection> devices);
void publishEnd(String sessionId, List<PreDetection> devices);
}

View File

@@ -0,0 +1,95 @@
package com.njcn.gather.detection.service.impl;
import com.alibaba.fastjson.JSON;
import com.njcn.gather.detection.pojo.vo.FormalTestDevicePayload;
import com.njcn.gather.detection.pojo.vo.FormalTestEventPayload;
import com.njcn.gather.detection.service.FormalTestEventPublisher;
import com.njcn.gather.device.pojo.vo.PreDetection;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Service
@RequiredArgsConstructor
public class FormalTestEventPublisherImpl implements FormalTestEventPublisher {
private final StringRedisTemplate stringRedisTemplate;
private static String msgChannel = "formal-test-msg-channel";
private final Set<String> publishedStartSessions =
Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final Set<String> publishedEndSessions =
Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
@Override
public void publishStart(String sessionId, List<PreDetection> devices) {
publish("start", sessionId, devices);
}
@Override
public void publishEnd(String sessionId, List<PreDetection> devices) {
publish("end", sessionId, devices);
}
public FormalTestEventPayload buildPayload(String eventType, String sessionId, List<PreDetection> devices) {
FormalTestEventPayload payload = new FormalTestEventPayload();
payload.setEventType(eventType);
payload.setEventTime(LocalDateTime.now());
payload.setSessionId(sessionId);
payload.setDevices(buildDevices(devices));
return payload;
}
private void publish(String eventType, String sessionId, List<PreDetection> devices) {
if (sessionId == null) {
return;
}
Set<String> dedupSet = "start".equals(eventType) ? publishedStartSessions : publishedEndSessions;
if (!dedupSet.add(sessionId)) {
return;
}
try {
FormalTestEventPayload payload = buildPayload(eventType, sessionId, devices);
stringRedisTemplate.convertAndSend(msgChannel, JSON.toJSONString(payload));
} catch (Exception ex) {
log.error("publish formal test event failed, eventType={}, sessionId={}, deviceCount={}",
eventType, sessionId, devices == null ? 0 : devices.size(), ex);
}
}
private List<FormalTestDevicePayload> buildDevices(List<PreDetection> devices) {
List<FormalTestDevicePayload> results = new ArrayList<>();
if (devices == null) {
return results;
}
for (PreDetection device : devices) {
if (device == null || device.getMonitorList() == null) {
continue;
}
for (PreDetection.MonitorListDTO monitor : device.getMonitorList()) {
if (monitor == null || monitor.getLine() == null) {
continue;
}
FormalTestDevicePayload payload = new FormalTestDevicePayload();
payload.setDeviceId(device.getDevId());
payload.setMonitorId(device.getDevId() + "_" + monitor.getLine());
payload.setDeviceIp(device.getDevIP());
payload.setDeviceType(device.getDevType());
payload.setIcdMappingName(device.getIcdType());
results.add(payload);
}
}
return results;
}
}

View File

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

View File

@@ -220,6 +220,12 @@ public class FormalTestManager {
*/
public static LocalDateTime checkStartTime;
public static String sessionId;
public static boolean startEventPublished;
public static boolean endEventPublished;
/**
* 数模式 检测类型"1"-"全部检测" , "2"-"不合格项复检"
*/

View File

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

View File

@@ -115,7 +115,11 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.warn("设备通讯客户端断线");
ctx.close();
SocketManager.removeUser(param.getUserPageId() + CnSocketUtil.DEV_TAG);
String key = param.getUserPageId() + CnSocketUtil.DEV_TAG;
if (SocketManager.consumeActiveClose(key)) {
return;
}
SocketManager.removeUser(key);
CnSocketUtil.quitSendSource(param);
// 设备主动断开 → 本次检测视为结束,释放检测锁
DetectionLockManager.getInstance()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -164,7 +164,7 @@ public class ResultController extends BaseController {
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/createChecksquareTask")
@GetMapping("/createChecksquareTask")
@ApiOperation("调用第三方数模数据检测接口")
@ApiImplicitParam(name = "devId", value = "设备id", required = true)
public HttpResult<String> createChecksquareTask(@RequestParam("devId") String devId) {

View File

@@ -206,19 +206,23 @@ public class ResultServiceImpl implements IResultService {
throw new BusinessException(CommonResponseEnum.FAIL, "该设备监测点不存在");
}
PqDevSub devSub = pqDevSubService.getOne(new LambdaQueryWrapper<PqDevSub>()
.eq(PqDevSub::getDevId, devId), false);
if (ObjectUtil.isNull(devSub)
|| ObjectUtil.isNull(devSub.getCheckStartTime())
|| ObjectUtil.isNull(devSub.getCheckEndTime())) {
throw new BusinessException(CommonResponseEnum.FAIL, "该设备检测开始时间或结束时间为空");
}
// PqDevSub devSub = pqDevSubService.getOne(new LambdaQueryWrapper<PqDevSub>()
// .eq(PqDevSub::getDevId, devId), false);
// if (ObjectUtil.isNull(devSub)
// || ObjectUtil.isNull(devSub.getCheckStartTime())
// || ObjectUtil.isNull(devSub.getCheckEndTime())) {
// throw new BusinessException(CommonResponseEnum.FAIL, "该设备检测开始时间或结束时间为空");
// }
DataCheckRequest request = new DataCheckRequest();
request.setLineIds(monitorList.stream().map(PqMonitor::getId).collect(Collectors.toList()));
// request.setLineIds(monitorList.stream().map(PqMonitor::getId).collect(Collectors.toList()));
// request.setIndicatorCodes(Collections.emptyList());
// request.setTimeStart(CHECKSQUARE_TIME_FORMATTER.format(devSub.getCheckStartTime()));
// request.setTimeEnd(CHECKSQUARE_TIME_FORMATTER.format(devSub.getCheckEndTime()));
request.setLineIds(Arrays.asList("ee9a33337bfd4d5588c00a2dbef6bc7e"));
request.setIndicatorCodes(Collections.emptyList());
request.setTimeStart(CHECKSQUARE_TIME_FORMATTER.format(devSub.getCheckStartTime()));
request.setTimeEnd(CHECKSQUARE_TIME_FORMATTER.format(devSub.getCheckEndTime()));
request.setTimeStart("2026-05-22 09:00:00");
request.setTimeEnd("2026-05-22 12:00:00");
return restTemplateUtil.postJson(CHECKSQUARE_CREATE_URL, request, String.class);
}

View File

@@ -27,6 +27,11 @@ public class DevTypeParam {
@NotBlank(message = DetectionValidMessage.ICD_NOT_BLANK)
private String icd;
@ApiModelProperty(value = "设备关联的PQDIF", required = true)
@NotBlank(message = "PQDIF不能为空")
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = DetectionValidMessage.ID_FORMAT_ERROR)
private String pqdif;
@ApiModelProperty(value = "工作电源", required = true)
@NotBlank(message = DetectionValidMessage.POWER_NOT_BLANK)
private String power;

View File

@@ -37,6 +37,8 @@ public class DevType extends BaseEntity {
/**
* 工作电源
*/
private String pqdif;
private String power;
/**

View File

@@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.pqdif.pojo.po.PqPqdifPath;
import com.njcn.gather.pqdif.service.IPqPqdifPathService;
import com.njcn.gather.pojo.enums.DetectionResponseEnum;
import com.njcn.gather.system.dictionary.pojo.po.DictData;
import com.njcn.gather.system.dictionary.service.IDictDataService;
@@ -36,6 +38,9 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
@Resource
private IDictDataService dictDataService;
@Resource
private IPqPqdifPathService pqPqdifPathService;
@Override
public List<DevType> listAll() {
@@ -76,6 +81,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
public boolean addDevType(DevTypeParam addParam) {
addParam.setName(addParam.getName().trim());
this.checkRepeat(addParam, false);
this.checkPqdif(addParam.getPqdif());
DevType devType = new DevType();
BeanUtil.copyProperties(addParam, devType);
devType.setState(DataStateEnum.ENABLE.getCode());
@@ -87,6 +93,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
public boolean updateDevType(DevTypeParam.UpdateParam updateParam) {
updateParam.setName(updateParam.getName().trim());
this.checkRepeat(updateParam, true);
this.checkPqdif(updateParam.getPqdif());
DevType devType = new DevType();
BeanUtil.copyProperties(updateParam, devType);
return this.updateById(devType);
@@ -121,4 +128,14 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
throw new BusinessException(DetectionResponseEnum.DEV_TYPE_NAME_REPEAT);
}
}
private void checkPqdif(String pqdifId) {
PqPqdifPath pqdif = pqPqdifPathService.lambdaQuery()
.eq(PqPqdifPath::getId, pqdifId)
.eq(PqPqdifPath::getState, DataStateEnum.ENABLE.getCode())
.one();
if (Objects.isNull(pqdif)) {
throw new BusinessException(DetectionResponseEnum.PQDIF_NOT_EXIST);
}
}
}

View File

@@ -1,59 +0,0 @@
package com.njcn.gather.source.pojo;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.njcn.gather.source.pojo.param.PqSourceParam;
import com.njcn.gather.source.pojo.po.PqSource;
import org.junit.Assert;
import org.junit.Test;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.DecimalMin;
import java.lang.reflect.Field;
import java.math.BigDecimal;
public class PqSourceCapacityFieldsTest {
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
@Test
public void shouldExposeExplicitCapacityColumnMappings() throws Exception {
Field maxVoltage = PqSource.class.getDeclaredField("maxVoltage");
Field maxCurrent = PqSource.class.getDeclaredField("maxCurrent");
Assert.assertEquals("Max_Voltage", maxVoltage.getAnnotation(TableField.class).value());
Assert.assertEquals("Max_Current", maxCurrent.getAnnotation(TableField.class).value());
}
@Test
public void shouldExposeNonNegativeCapacityValidation() throws Exception {
Field maxVoltage = PqSourceParam.class.getDeclaredField("maxVoltage");
Field maxCurrent = PqSourceParam.class.getDeclaredField("maxCurrent");
Assert.assertEquals("0", maxVoltage.getAnnotation(DecimalMin.class).value());
Assert.assertEquals("0", maxCurrent.getAnnotation(DecimalMin.class).value());
PqSourceParam.UpdateParam param = new PqSourceParam.UpdateParam();
param.setId("12345678901234567890123456789012");
param.setPattern("12345678901234567890123456789012");
param.setType("12345678901234567890123456789012");
param.setDevType("12345678901234567890123456789012");
param.setMaxVoltage(new BigDecimal("-1"));
Assert.assertFalse(validator.validate(param).isEmpty());
}
@Test
public void shouldCopyCapacityFieldsFromRequestToEntity() {
PqSourceParam.UpdateParam param = new PqSourceParam.UpdateParam();
param.setMaxVoltage(new BigDecimal("220.00"));
param.setMaxCurrent(new BigDecimal("5.00"));
PqSource source = new PqSource();
BeanUtil.copyProperties(param, source);
Assert.assertEquals(new BigDecimal("220.00"), source.getMaxVoltage());
Assert.assertEquals(new BigDecimal("5.00"), source.getMaxCurrent());
}
}