13 Commits

Author SHA1 Message Date
xy
6bb9d932b8 feat(notification): 添加异步通知服务并重构事件处理逻辑
- 新增 AppNotificationService 处理应用内事件通知
- 新增 SmsNotificationService 处理短信通知功能
- 配置 AsyncConfig 异步执行器支持事件通知处理
- 重构 CsEventPOServiceImpl 事件处理逻辑,分离通知功能
- 添加 @EnableAsync 注解启用异步处理
- 优化 CsDeviceUserPOServiceImpl 用户查询返回空对象
- 修复 WlUserServiceImpl 中的空指针检查逻辑
2026-04-22 16:03:59 +08:00
xy
8841000989 refactor(service): 优化设备交付服务中的日志处理逻辑
- 移除未使用的 ICsTerminalLogsService 依赖注入
- 删除前置推送日志的清理代码,简化设备删除流程
- 在创建操作日志时添加UUID标识符
- 在终端日志服务中增加Redis缓存清理逻辑
- 为设备列表处理添加空值检查,避免空指针异常
- 重构设备分组和消息发送逻辑,提高代码可读性
2026-04-21 20:33:55 +08:00
xy
8559d7548a refactor(device): 优化设备交付服务和终端回复服务
- 移除未使用的 EngineeringFeignClient 和 IMqttUserService 依赖
- 添加 CsTerminalLogsService 用于管理前置推送日志
- 在删除设备时同步清理相关的前置推送日志记录
- 简化终端回复查询逻辑,移除不必要的分组判断
- 注释掉废弃的 queryReplyData 方法以提高代码整洁性
- 统一设备操作结果的消息返回格式
2026-04-21 19:47:29 +08:00
xy
d8b292d447 mqtt依赖包引入 2026-04-21 19:21:35 +08:00
xy
fed766bca4 短信服务集成 2026-04-21 16:10:01 +08:00
xy
353a4cc83b refactor(event): 重构事件统计功能并迁移消息推送服务
- 移除暂态事件统计相关接口和实现方法
- 删除EventStatisticsVo相关代码
- 将设备消息推送功能从CsEventPOServiceImpl迁移到新创建的DeviceMessageService
- 新增DeviceMessageFeignClient用于服务间调用
- 实现DeviceMessageController提供统一的消息推送接口
2026-04-17 16:19:10 +08:00
xy
9caaf9bea2 feat(alarm): 添加告警统计功能并优化设备管理
- 在AlarmVO中新增interruptCounts和warnCounts字段用于统计通信中断和终端告警次数
- 在CsAlarmServiceImpl中实现告警次数统计逻辑,解析告警事件数据并计算各类告警数量
- 重构CsEventUserPOServiceImpl中的查询逻辑,优化暂态事件详细信息查询接口
- 在CsEquipmentDeliveryServiceImpl中集成事件查询功能,实时获取设备告警状态
- 优化数据库查询语句,改进事件查询的排序和过滤逻辑
2026-04-16 16:14:10 +08:00
xy
e77108ebf5 feat(service): 实现分页功能并优化设备权限管理
- 在控制器层添加分页支持,将返回类型从 List 修改为 Page
- 实现服务层分页逻辑,集成 MyBatis Plus 分页插件
- 重构设备权限管理逻辑,区分超级管理员、普通用户和游客权限
- 添加营销用户和工程用户的特殊权限处理机制
- 迁移事件查询逻辑到统一的事件用户服务中
- 移除过时的设备用户映射器接口和 XML 查询方法
- 为暂降事件报告添加动态文件名生成功能
- 修复时间范围计算中的日期边界问题
- 优化台账树结构以支持多层级权限过滤
- 统计未读事件数量的查询逻辑优化
2026-04-14 19:09:23 +08:00
xy
460a10f3b5 微调 2026-04-08 15:14:41 +08:00
xy
f242e45c2f App事件一键已读功能调整 2026-04-08 14:31:39 +08:00
xy
45fd613e47 代码优化 2026-04-08 10:19:06 +08:00
xy
445f27143b 微调 2026-04-07 15:42:30 +08:00
xy
622d977d62 微调 2026-04-07 14:19:30 +08:00
116 changed files with 4201 additions and 1042 deletions

View File

@@ -6,6 +6,7 @@ import com.njcn.csdevice.api.fallback.AppProjectClientFallbackFactory;
import com.njcn.csdevice.pojo.param.AppProjectAddParm;
import com.njcn.csdevice.pojo.po.AppProjectPO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@@ -25,7 +26,7 @@ public interface AppProjectFeignClient {
@PostMapping("/getProjectByName")
HttpResult<AppProjectPO> getProjectByName(@RequestParam("name") String name);
@PostMapping("/addAppProject")
HttpResult<AppProjectPO> addAppProject(@RequestBody AppProjectAddParm appProjectAddParm);
@PostMapping("/addPortableProject")
HttpResult<AppProjectPO> addPortableProject(@Validated @RequestBody AppProjectAddParm appProjectAddParm);
}

View File

@@ -6,7 +6,6 @@ import com.njcn.csdevice.api.fallback.CsDeviceUserClientFallbackFactory;
import com.njcn.csdevice.pojo.param.UserDevParam;
import com.njcn.csdevice.pojo.po.CsDeviceUserPO;
import com.njcn.csdevice.pojo.vo.DevUserVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -36,6 +35,8 @@ public interface CsDeviceUserFeignClient {
HttpResult<DevUserVO> queryUserById(@RequestParam("devId") String devId);
@PostMapping("/getList")
@ApiOperation("根据设备集合获取数据")
HttpResult<List<CsDeviceUserPO>> getList(@RequestBody UserDevParam param);
@PostMapping("/getIdList")
HttpResult<List<String>> getIdList(@RequestParam("param") String param);
}

View File

@@ -0,0 +1,34 @@
package com.njcn.csdevice.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.fallback.DeviceMessageClientFallbackFactory;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.user.pojo.po.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_DEVICE_BOOT, path = "/deviceMessage", fallbackFactory = DeviceMessageClientFallbackFactory.class,contextId = "deviceMessage")
public interface DeviceMessageFeignClient {
@PostMapping("/getEventUserByDeviceId")
@ApiOperation("根据设备获取需要推送的用户id")
HttpResult<List<String>> getEventUserByDeviceId(@RequestParam("devId") String devId, @RequestParam("isAdmin") Boolean isAdmin);
@PostMapping("/getSendUserByType")
@ApiOperation("根据事件类型和用户id查询打开推送的用户信息")
HttpResult<List<User>> getSendUserByType(@RequestBody DeviceMessageParam param);
@PostMapping("/getLineInfo")
@ApiOperation("获取监测点信息")
HttpResult<String> getLineInfo(@RequestParam("id") String id);
}

View File

@@ -51,9 +51,6 @@ public interface EquipmentFeignClient {
@PostMapping("/updateModuleNumber")
HttpResult<String> updateModuleNumber(@RequestParam("nDid") String nDid,@RequestParam("number") Integer number);
@PostMapping("/updateLedger")
HttpResult<String> updateLedger(@RequestParam("nDid") String nDid,@RequestParam("engineeringId") String engineeringId,@RequestParam("projectId") String projectId);
@PostMapping("/getAll")
HttpResult<List<CsEquipmentDeliveryPO>> getAll();

View File

@@ -0,0 +1,23 @@
package com.njcn.csdevice.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.fallback.SmsSendClientFallbackFactory;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_DEVICE_BOOT, path = "/sms", fallbackFactory = SmsSendClientFallbackFactory.class,contextId = "sms")
public interface SmsSendFeignClient {
@PostMapping("/send/simple")
@ApiOperation("发送短信(简化参数)")
HttpResult<String> sendSmsSimple(@RequestParam("receiver") String receiver
, @RequestParam("content") String content
, @RequestParam("messageType") String messageType);
}

View File

@@ -41,8 +41,8 @@ public class AppProjectClientFallbackFactory implements FallbackFactory<AppProje
}
@Override
public HttpResult<AppProjectPO> addAppProject(AppProjectAddParm appProjectAddParm) {
log.error("{}异常,降级处理,异常为:{}","新增项目异常",cause.toString());
public HttpResult<AppProjectPO> addPortableProject(AppProjectAddParm appProjectAddParm) {
log.error("{}异常,降级处理,异常为:{}","新增便携式项目",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};

View File

@@ -64,6 +64,12 @@ public class CsDeviceUserClientFallbackFactory implements FallbackFactory<CsDevi
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<String>> getIdList(String param) {
log.error("{}异常,降级处理,异常为:{}","获取事件id集合数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -0,0 +1,50 @@
package com.njcn.csdevice.api.fallback;
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.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.user.pojo.po.User;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author xy
*/
@Slf4j
@Component
public class DeviceMessageClientFallbackFactory implements FallbackFactory<DeviceMessageFeignClient> {
@Override
public DeviceMessageFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new DeviceMessageFeignClient() {
@Override
public HttpResult<List<String>> getEventUserByDeviceId(String devId, Boolean isAdmin) {
log.error("{}异常,降级处理,异常为:{}","根据设备获取需要推送的用户id数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<User>> getSendUserByType(DeviceMessageParam param) {
log.error("{}异常,降级处理,异常为:{}","根据事件类型和用户id查询打开推送的用户信息数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> getLineInfo(String id) {
log.error("{}异常,降级处理,异常为:{}","获取监测点信息数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -72,12 +72,6 @@ public class EquipmentFeignClientFallbackFactory implements FallbackFactory<Equi
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<String> updateLedger(String nDid, String engineeringId, String projectId) {
log.error("{}异常,降级处理,异常为:{}","更新设备预设工程和项目id数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<CsEquipmentDeliveryPO>> getAll() {
log.error("{}异常,降级处理,异常为:{}","获取所有装置",cause.toString());

View File

@@ -0,0 +1,34 @@
package com.njcn.csdevice.api.fallback;
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.csdevice.api.SmsSendFeignClient;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author xy
*/
@Slf4j
@Component
public class SmsSendClientFallbackFactory implements FallbackFactory<SmsSendFeignClient> {
@Override
public SmsSendFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new SmsSendFeignClient() {
@Override
public HttpResult<String> sendSmsSimple(String receiver, String content, String messageType) {
log.error("{}异常,降级处理,异常为:{}","发送短信(简化参数)数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -0,0 +1,20 @@
package com.njcn.csdevice.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author xy
*/
@Data
public class DeviceMessageParam {
@ApiModelProperty("用户id集合")
private List<String> userList;
@ApiModelProperty("事件类型 0:暂态 1:稳态 2:运行 3:告警")
private Integer eventType;
}

View File

@@ -0,0 +1,35 @@
package com.njcn.csdevice.pojo.dto;
/**
* @author caozehui
* @data 2026-03-31
*/
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
/**
* 系统凭证请求 DTO
*
* @author msgpush
*/
@Data
public class CredentialReqDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 上游系统名称
*/
@NotEmpty(message = "上游系统名称不能为空")
private String systemName;
/**
* 密钥(用于生成凭证)
*/
@NotEmpty(message = "密钥不能为空")
private String secretKey;
}

View File

@@ -3,6 +3,8 @@ package com.njcn.csdevice.pojo.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* Description:
* Date: 2023/9/6 13:59【需求编号】
@@ -37,4 +39,7 @@ public class DevDetailDTO {
@ApiModelProperty(value = "设备MAC地址")
private String devMac;
@ApiModelProperty(value = "监测点id集合")
private List<String> lineList;
}

View File

@@ -1,8 +1,10 @@
package com.njcn.csdevice.pojo.dto;
import com.njcn.web.pojo.param.BaseParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
@@ -13,7 +15,7 @@ import java.util.List;
* @version V1.0.0
*/
@Data
public class LineParamDTO {
public class LineParamDTO extends BaseParam implements Serializable {
@ApiModelProperty(value = "工程id")
private String engineerId;

View File

@@ -0,0 +1,21 @@
package com.njcn.csdevice.pojo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
/**
* @author xy
*/
@Data
@AllArgsConstructor
public class SendResult implements Serializable {
private final boolean success;
private final String messageId;
private final String failReason;
private final boolean isTimeOut;
private final boolean unauthorized;
}

View File

@@ -67,7 +67,7 @@ public class CsEdDataAuditParm {
private String versionType;
@ApiModelProperty(value = "crc信息")
private String crcInfo;
private String crc;
@ApiModelProperty(value="0删除 1正常")
private String status;
@ApiModelProperty(value = ".bin文件")

View File

@@ -88,6 +88,12 @@ public class CsEdDataPO extends BaseEntity {
@TableField(value = "file_path")
private String filePath;
/**
* crc文件校验码
*/
@TableField(value = "crc")
private String crc;
}

View File

@@ -0,0 +1,45 @@
package com.njcn.csdevice.pojo.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @author xy
*/
@Data
@TableName("cs_sms_send_record")
public class CsSmsSendRecord implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
private String id;
private String receiver;
private String content;
private String messageType;
private String credentialToken;
private Integer sendStatus;
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String failReason;
private Integer retryCount;
private Integer maxRetry;
private Long responseTime;
private LocalDateTime sendTime;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,40 @@
package com.njcn.csdevice.pojo.vo;
import cn.hutool.core.lang.RegexPool;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* @author caozehui
* @data 2026-02-27
*/
@Data
@Schema(description = "管理后台 - 消息记录发送 Request VO")
public class MessageRecordReqVO {
private String channel;
@Schema(description = "消息类型", example = "verify_code/order_notify/marketing/system_notify")
@NotBlank(message = "消息类型不能为空")
private String messageType;
@Schema(description = "接收者")
@NotBlank(message = "接收者不能为空")
@Pattern(regexp = RegexPool.EMAIL + "|" + RegexPool.MOBILE, message = "必须是有效的邮箱或手机号格式")
private String receiver;
@Schema(description = "标题")
private String title;
@Schema(description = "消息内容")
private String content;
@Schema(description = "模板编码")
private String templateCode;
@Schema(description = "模板参数")
private String templateParams;
}

View File

@@ -66,6 +66,9 @@ public class ProjectEquipmentVO {
@ApiModelProperty(value = "设备类型(监测设备:DEV_CLD 治理设备:Direct_Connected_Device)")
private String devType;
@ApiModelProperty(value = "是否存在告警(告警通过查询当日的未读的暂态事件判断)")
private Boolean isAlarm;
@ApiModelProperty(value = "监测点集合")
private List<CsLinePO> lineList;

View File

@@ -1,74 +1,74 @@
package com.njcn.csdevice.utils;
import org.eclipse.paho.client.mqttv3.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Description:
* Date: 2023/8/2 13:41【需求编号】
*
* @author clam
* @version V1.0.0
*/
public class MqttTest {
private static final String MQTT_BROKER = "tcp://192.168.1.13:1883";
private static final String MQTT_TOPIC = "file/upload";
private static final String FILE_PATH = "C:\\Users\\无名\\Desktop\\111.json"; // Replace with the path to your file
public static void main(String[] args) {
MqttClient mqttClient = null;
try {
// Connect to the MQTT broker
mqttClient = new MqttClient(MQTT_BROKER, MqttClient.generateClientId());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName("t_user");
connOpts.setPassword("njcnpqs".toCharArray());
mqttClient.connect(connOpts);
// Read the file
File file = new File(FILE_PATH);
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = new byte[(int) file.length()];
fis.read(fileContent);
fis.close();
// Create a new MQTT message
MqttMessage message = new MqttMessage(fileContent);
// Set QoS level and retain flag as per your requirement
message.setQos(1);
// message.setRetained(false);
// Record the start time
long startTime = System.currentTimeMillis();
// Publish the message to the MQTT topic
mqttClient.publish(MQTT_TOPIC, message);
// Record the end time
long endTime = System.currentTimeMillis();
System.out.println("File published successfully!");
System.out.println("Time taken: " + (endTime - startTime) + " ms");
} catch (MqttException | IOException e) {
e.printStackTrace();
} finally {
// Disconnect from the MQTT broker
if (mqttClient != null && mqttClient.isConnected()) {
try {
mqttClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
}
//package com.njcn.csdevice.utils;
//
//import org.eclipse.paho.client.mqttv3.*;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Paths;
//
///**
// * Description:
// * Date: 2023/8/2 13:41【需求编号】
// *
// * @author clam
// * @version V1.0.0
// */
//public class MqttTest {
// private static final String MQTT_BROKER = "tcp://192.168.1.13:1883";
// private static final String MQTT_TOPIC = "file/upload";
// private static final String FILE_PATH = "C:\\Users\\无名\\Desktop\\111.json"; // Replace with the path to your file
//
// public static void main(String[] args) {
// MqttClient mqttClient = null;
// try {
// // Connect to the MQTT broker
// mqttClient = new MqttClient(MQTT_BROKER, MqttClient.generateClientId());
// MqttConnectOptions connOpts = new MqttConnectOptions();
// connOpts.setUserName("t_user");
// connOpts.setPassword("njcnpqs".toCharArray());
//
// mqttClient.connect(connOpts);
//
// // Read the file
// File file = new File(FILE_PATH);
// FileInputStream fis = new FileInputStream(file);
// byte[] fileContent = new byte[(int) file.length()];
// fis.read(fileContent);
// fis.close();
//
// // Create a new MQTT message
// MqttMessage message = new MqttMessage(fileContent);
//
// // Set QoS level and retain flag as per your requirement
// message.setQos(1);
//// message.setRetained(false);
//
// // Record the start time
// long startTime = System.currentTimeMillis();
//
// // Publish the message to the MQTT topic
// mqttClient.publish(MQTT_TOPIC, message);
//
// // Record the end time
// long endTime = System.currentTimeMillis();
//
// System.out.println("File published successfully!");
// System.out.println("Time taken: " + (endTime - startTime) + " ms");
// } catch (MqttException | IOException e) {
// e.printStackTrace();
// } finally {
// // Disconnect from the MQTT broker
// if (mqttClient != null && mqttClient.isConnected()) {
// try {
// mqttClient.disconnect();
// } catch (MqttException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
//}

View File

@@ -21,6 +21,10 @@
</properties>
<dependencies>
<dependency>
<groupId>com.github.tocrhz</groupId>
<artifactId>mqtt-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>common-web</artifactId>

View File

@@ -11,8 +11,11 @@ import com.njcn.csdevice.pojo.po.CsDeviceUserPO;
import com.njcn.csdevice.pojo.vo.DevCountVO;
import com.njcn.csdevice.pojo.vo.DevUserVO;
import com.njcn.csdevice.service.CsDeviceUserPOService;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.web.advice.DeviceLog;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
@@ -21,7 +24,9 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
@@ -37,6 +42,8 @@ import java.util.List;
public class DeviceUserController extends BaseController {
private final CsDeviceUserPOService csDeviceUserPOService;
private final EventUserFeignClient eventUserFeignClient;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/add")
@ApiOperation("新增设备扫码设备用户绑定")
@@ -174,4 +181,25 @@ public class DeviceUserController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getIdList")
@ApiOperation("获取事件id集合")
@ApiImplicitParam(name = "param", value = "参数", required = true)
public HttpResult<List<String>> getIdList(@RequestParam("param") String param){
String methodDescribe = getMethodDescribe("getIdList");
List<String> list = new ArrayList<>();
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(null);
param1.setEndTime(null);
param1.setEventIds(null);
if (Objects.equals(param, "1")) {
list = eventUserFeignClient.queryTempHarmonic(param1).getData();
} else if (Objects.equals(param, "3")) {
list = eventUserFeignClient.queryAlarmEvent(param1).getData();
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
}

View File

@@ -303,20 +303,6 @@ public class EquipmentDeliveryController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/updateLedger")
@ApiOperation("更新设备预设工程和项目id")
@ApiImplicitParams({
@ApiImplicitParam(name = "nDid", value = "网络设备码", required = true),
@ApiImplicitParam(name = "engineeringId", value = "工程id", required = true),
@ApiImplicitParam(name = "projectId", value = "项目id", required = true)
})
public HttpResult<String> updateLedger(@RequestParam("nDid") String nDid,@RequestParam("engineeringId") String engineeringId,@RequestParam("projectId") String projectId){
String methodDescribe = getMethodDescribe("updateLedger");
csEquipmentDeliveryService.updateLedger(nDid,engineeringId,projectId);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/rebootDevice")
@ApiOperation("重启设备")

View File

@@ -0,0 +1,80 @@
package com.njcn.csdevice.controller.message;
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.common.utils.HttpResultUtil;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.param.DataArrayParam;
import com.njcn.csdevice.pojo.po.CsDataArray;
import com.njcn.csdevice.pojo.vo.DataArrayTreeVO;
import com.njcn.csdevice.pojo.vo.DeviceManagerDetailVO;
import com.njcn.csdevice.service.DeviceMessageService;
import com.njcn.csdevice.service.ICsDataArrayService;
import com.njcn.user.pojo.po.User;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
/**
* <p>
* 详细数据表 前端控制器
* </p>
*
* @author xuyang
* @since 2023-05-31
*/
@Slf4j
@RestController
@RequestMapping("/deviceMessage")
@Api(tags = "App消息推送管理")
@AllArgsConstructor
public class DeviceMessageController extends BaseController {
private final DeviceMessageService deviceMessageService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getEventUserByDeviceId")
@ApiOperation("根据设备获取需要推送的用户id")
@ApiImplicitParams({
@ApiImplicitParam(name = "devId", value = "设备id", required = true, paramType = "query"),
@ApiImplicitParam(name = "isAdmin", value = "是否需要推送给管理员", required = true, paramType = "query")
})
public HttpResult<List<String>> getEventUserByDeviceId(@RequestParam("devId") String devId, @RequestParam("isAdmin") Boolean isAdmin){
String methodDescribe = getMethodDescribe("getEventUserByDeviceId");
List<String> list = deviceMessageService.getEventUserByDeviceId(devId,isAdmin);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getSendUserByType")
@ApiOperation("根据事件类型和用户id查询打开推送的用户信息")
@ApiImplicitParam(name = "param", value = "参数", required = true, paramType = "query")
public HttpResult<List<User>> getSendUserByType(@RequestBody DeviceMessageParam param){
String methodDescribe = getMethodDescribe("getSendUserByType");
List<User> list = deviceMessageService.getSendUserByType(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getLineInfo")
@ApiOperation("获取监测点信息")
@ApiImplicitParam(name = "id", value = "参数", required = true, paramType = "query")
public HttpResult<String> getLineInfo(@RequestParam("id") String id){
String methodDescribe = getMethodDescribe("getLineInfo");
deviceMessageService.getLineInfo(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "success", methodDescribe);
}
}

View File

@@ -0,0 +1,77 @@
package com.njcn.csdevice.controller.message;
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.common.utils.HttpResultUtil;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
import com.njcn.csdevice.service.ISmsSendService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* @author xy
*/
@Slf4j
@RestController
@RequestMapping("/sms")
@Api(tags = "短信发送管理")
@AllArgsConstructor
public class SmsSendController extends BaseController {
private final ISmsSendService smsSendService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/send")
@ApiOperation("发送短信(同步,包含重试)")
public HttpResult<String> sendSms(@RequestBody MessageRecordReqVO vo) {
String methodDescribe = getMethodDescribe("sendSms");
try {
smsSendService.sendSmsWithRetry(vo);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.SUCCESS,
"短信发送成功",
methodDescribe
);
} catch (Exception e) {
log.error("短信发送失败", e);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.FAIL,
e.getMessage(),
methodDescribe
);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/send/simple")
@ApiOperation("发送短信(简化参数)")
public HttpResult<String> sendSmsSimple(
@RequestParam String receiver,
@RequestParam String content,
@RequestParam(defaultValue = "verify_code") String messageType) {
String methodDescribe = getMethodDescribe("sendSmsSimple");
try {
smsSendService.sendSmsWithRetry(receiver, content, messageType);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.SUCCESS,
"短信发送成功",
methodDescribe
);
} catch (Exception e) {
log.error("短信发送失败", e);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.FAIL,
e.getMessage(),
methodDescribe
);
}
}
}

View File

@@ -65,12 +65,21 @@ public class AppProjectController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/addAppProject")
@ApiOperation("新增项目")
public HttpResult<AppProjectPO> addAppProject(@Validated @RequestBody AppProjectAddParm appProjectAddParm){
public HttpResult<AppProjectPO> addAppProject(@Validated AppProjectAddParm appProjectAddParm){
String methodDescribe = getMethodDescribe("addAppProject");
AppProjectPO po = appProjectService.addAppProject(appProjectAddParm);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, po, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/addPortableProject")
@ApiOperation("新增便携式项目")
public HttpResult<AppProjectPO> addPortableProject(@Validated @RequestBody AppProjectAddParm appProjectAddParm){
String methodDescribe = getMethodDescribe("addPortableProject");
AppProjectPO po = appProjectService.addAppProject(appProjectAddParm);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, po, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/auditAppProject")
@ApiOperation("修改/删除项目")

View File

@@ -61,7 +61,7 @@ public class CsTouristDataPOController extends BaseController {
@PostMapping("/queryAll")
@ApiOperation("查询游客数据")
public HttpResult<List<CsTouristDataParmVO>> queryAll(){
String methodDescribe = getMethodDescribe("query");
String methodDescribe = getMethodDescribe("queryAll");
List<CsTouristDataParmVO> list = csTouristDataPOService.queryAll();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);

View File

@@ -2,9 +2,6 @@ package com.njcn.csdevice.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csdevice.pojo.po.CsDeviceUserPO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
*
@@ -15,17 +12,4 @@ import java.util.List;
* @version V1.0.0
*/
public interface CsDeviceUserPOMapper extends BaseMapper<CsDeviceUserPO> {
//查询暂态事件(未读)
int queryTempEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询稳态事件(未读)
int queryTempHarmonic(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询告警事件(未读)
int queryAlarmEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询运行事件(未读)
int queryRunEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
}

View File

@@ -0,0 +1,7 @@
package com.njcn.csdevice.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
public interface CsSmsSendRecordMapper extends BaseMapper<CsSmsSendRecord> {
}

View File

@@ -16,72 +16,4 @@
<!--@mbg.generated-->
primary_user_id, sub_user_id, device_id, create_by, create_time, update_by, update_time
</sql>
<select id="queryTempEvent" resultType="java.lang.Integer">
SELECT
COUNT(1)
FROM
cs_event_user t1 right join cs_event t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
and t2.type = 0
<if test="ids != null and ids.size > 0">
and t2.line_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
<select id="queryAlarmEvent" resultType="java.lang.Integer">
SELECT
COUNT(1)
FROM
cs_event_user t1 right join cs_alarm t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
<if test="ids != null and ids.size > 0">
and (
<foreach collection="ids" item="tag" separator=" OR ">
FIND_IN_SET(#{tag}, t2.dev_list) > 0
</foreach>
)
</if>
</select>
<select id="queryRunEvent" resultType="java.lang.Integer">
SELECT
COUNT(1)
FROM
cs_event_user t1 right join cs_event t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
and t2.type = 2
<if test="ids != null and ids.size > 0">
and t2.device_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
<select id="queryTempHarmonic" resultType="java.lang.Integer">
SELECT
COUNT(1)
FROM
cs_event_user t1 right join cs_harmonic t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
<if test="ids != null and ids.size > 0">
and t2.line_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
</mapper>

View File

@@ -11,7 +11,6 @@ import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO;
import com.njcn.csdevice.pojo.vo.DeviceManagerVO;
import com.njcn.csdevice.pojo.vo.ProjectEquipmentVO;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@@ -122,8 +121,6 @@ public interface CsEquipmentDeliveryService extends IService<CsEquipmentDelivery
*/
void updateModuleNumber(String nDid, Integer number);
void updateLedger(String nDid,String engineeringId,String projectId);
boolean rebootDevice(String nDid);
/**

View File

@@ -0,0 +1,19 @@
package com.njcn.csdevice.service;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.user.pojo.po.User;
import java.util.List;
/**
* @author xy
*/
public interface DeviceMessageService {
List<String> getEventUserByDeviceId(String devId, Boolean isAdmin);
List<User> getSendUserByType(DeviceMessageParam param);
void getLineInfo(String id);
}

View File

@@ -0,0 +1,12 @@
package com.njcn.csdevice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
public interface ISmsSendService extends IService<CsSmsSendRecord> {
void sendSmsWithRetry(String receiver, String content, String messageType);
void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO);
}

View File

@@ -93,27 +93,33 @@ public class CsCommTerminalServiceImpl implements CsCommTerminalService {
@Override
public List<String> commGetDevIds(String userId) {
UserVO userVO = userFeignClient.getUserById(userId).getData();
List<String> devIds;
List<String> devIds = new ArrayList<>();
if (userVO.getType().equals(UserType.SUPER_ADMINISTRATOR) || userVO.getType().equals(UserType.ADMINISTRATOR)) {
devIds = csEquipmentDeliveryService.getAll().stream().map(CsEquipmentDeliveryPO::getId).collect(Collectors.toList());
} else {
List<CsDeviceUserPO> devList = csDeviceUserPOService.lambdaQuery().select(CsDeviceUserPO::getDeviceId)
.and(w -> w.eq(CsDeviceUserPO::getPrimaryUserId, userId).or().eq(CsDeviceUserPO::getSubUserId, userId))
.eq(CsDeviceUserPO::getStatus, DataStateEnum.ENABLE.getCode()).list();
devIds = devList.stream().map(CsDeviceUserPO::getDeviceId).distinct().collect(Collectors.toList());
//note 黄是在cs_market_data写入数据是用户和工程的关系
// 但是权限根据用户和设备来判断会有问题,还需要用户和工程的关系(针对营销 工程用户),所以这边还要添加用户和工程的关系
List<CsMarketDataVO> list = csMarketDataService.queryByUseId(userId);
if (CollUtil.isNotEmpty(list)) {
List<String> engineerIds = list.stream().map(CsMarketDataVO::getEngineerId).distinct().collect(Collectors.toList());
List<DevDetailDTO> devs = csLedgerService.getDevInfoByEngineerIds(engineerIds);
devIds.addAll(devs.stream().map(DevDetailDTO::getEquipmentId).distinct().collect(Collectors.toList()));
// 但是权限根据用户和设备来判断会有问题,还需要用户和工程的关系(针对营销 工程用户),所以这边还要添加用户和工程的关系
// 如果是营销 工程用户 没有配置相关工程,直接返回空的设备列表;如果有数据,也要判断下当前关注的工程里面是否包含主用户的设备,可能出现没有关注该工程,但是因为是设备的主用户导致数据统计错误
String roleString = RequestUtil.getUserRole();
if (roleString.contains(AppRoleEnum.MARKET_USER.getCode()) || roleString.contains(AppRoleEnum.ENGINEERING_USER.getCode())) {
List<CsMarketDataVO> list = csMarketDataService.queryByUseId(userId);
if (CollUtil.isNotEmpty(list)) {
List<String> engineerIds = list.stream().map(CsMarketDataVO::getEngineerId).distinct().collect(Collectors.toList());
List<DevDetailDTO> devs = csLedgerService.getDevInfoByEngineerIds(engineerIds);
devIds = devs.stream().map(DevDetailDTO::getEquipmentId).distinct().collect(Collectors.toList());
}
}
//note 如果是游客,则还需要加入系统配置的设备
String roleString = RequestUtil.getUserRole();
if (roleString.contains(AppRoleEnum.TOURIST.getCode())) {
else if (roleString.contains(AppRoleEnum.TOURIST.getCode())) {
devIds.addAll(csTouristDataPOService.queryAll().stream().map(CsTouristDataParmVO::getDeviceId).distinct().collect(Collectors.toList()));
}
//note 如果是普通用户,则需要根据用户权限来获取设备列表
else {
List<CsDeviceUserPO> devList = csDeviceUserPOService.lambdaQuery().select(CsDeviceUserPO::getDeviceId)
.and(w -> w.eq(CsDeviceUserPO::getPrimaryUserId, userId).or().eq(CsDeviceUserPO::getSubUserId, userId))
.eq(CsDeviceUserPO::getStatus, DataStateEnum.ENABLE.getCode()).list();
devIds = devList.stream().map(CsDeviceUserPO::getDeviceId).distinct().collect(Collectors.toList());
}
}
if (!CollUtil.isEmpty(devIds)) {
devIds = devIds.stream().distinct().collect(Collectors.toList());

View File

@@ -10,14 +10,16 @@ import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.mapper.CsDeviceUserPOMapper;
import com.njcn.csdevice.mapper.CsEquipmentDeliveryMapper;
import com.njcn.csdevice.mapper.CsMarketDataMapper;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.param.UserDevParam;
import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csdevice.pojo.vo.CsTouristDataParmVO;
import com.njcn.csdevice.pojo.vo.DevCountVO;
import com.njcn.csdevice.pojo.vo.DevUserVO;
import com.njcn.csdevice.service.*;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.cssystem.api.FeedBackFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.harmonic.utils.PublicDataUtils;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.enums.AppRoleEnum;
@@ -30,6 +32,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -51,14 +54,12 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
private final CsDevModelRelationService csDevModelRelationService;
private final ICsLedgerService iCsLedgerService;
private final CsEquipmentDeliveryMapper csEquipmentDeliveryMapper;
private final RoleEngineerDevService roleEngineerDevService;
private final AppLineTopologyDiagramService appLineTopologyDiagramService;
private final CsTouristDataPOService csTouristDataPOService;
private final CsLinePOService csLinePOService;
private final CsMarketDataMapper csMarketDataMapper;
private final EventUserFeignClient eventUserFeignClient;
private final UserFeignClient userFeignClient;
private final FeedBackFeignClient feedBackFeignClient;
private final IMqttUserService mqttUserService;
@Override
@@ -122,17 +123,61 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
DevCountVO vo = new DevCountVO();
//获取app用户的台账树包含四个层级 工程、项目、设备、监测点
List<CsLedgerVO> appLedger = iCsLedgerService.appLineTree();
//判断当前用户,如果是游客,则需要筛选数据,只保留游客的数据
String roleString = RequestUtil.getUserRole();
if (roleString.contains(AppRoleEnum.TOURIST.getCode())) {
List<CsTouristDataParmVO> csTouristDataParmVOList = csTouristDataPOService.queryAll();
if (CollectionUtil.isNotEmpty(csTouristDataParmVOList)) {
List<String> devList = csTouristDataParmVOList.stream().map(CsTouristDataParmVO::getDeviceId).collect(Collectors.toList());
// 保留游客有权限的工程、项目、设备、监测点数据
appLedger = appLedger.stream()
.filter(engineering -> {
boolean hasValidProject = false;
if (CollectionUtil.isNotEmpty(engineering.getChildren())) {
List<CsLedgerVO> validProjects = engineering.getChildren().stream()
.filter(project -> {
boolean hasValidDevice = false;
if (CollectionUtil.isNotEmpty(project.getChildren())) {
List<CsLedgerVO> validDevices = project.getChildren().stream()
.filter(device -> devList.contains(device.getId()))
.collect(Collectors.toList());
project.setChildren(validDevices);
hasValidDevice = CollectionUtil.isNotEmpty(validDevices);
}
return hasValidDevice;
})
.collect(Collectors.toList());
engineering.setChildren(validProjects);
hasValidProject = CollectionUtil.isNotEmpty(validProjects);
}
return hasValidProject;
})
.collect(Collectors.toList());
} else {
// 如果游客没有配置任何数据权限,返回空列表
appLedger = new ArrayList<>();
}
}
if (CollectionUtil.isNotEmpty(appLedger)) {
//获取第一层项目层级
List<CsLedgerVO> firstLevelList = new ArrayList<>();
//获取第三层设备层级
List<CsLedgerVO> thirdLevelList = new ArrayList<>();
//获取第四层设备层级
List<CsLedgerVO> forthLevelList = new ArrayList<>();
for (CsLedgerVO firstLevel : appLedger) {
firstLevelList.add(firstLevel);
if (CollectionUtil.isNotEmpty(firstLevel.getChildren())) {
for (CsLedgerVO secondLevel : firstLevel.getChildren()) {
if (CollectionUtil.isNotEmpty(secondLevel.getChildren())) {
thirdLevelList.addAll(secondLevel.getChildren());
for (CsLedgerVO threeLevel : secondLevel.getChildren()) {
if (CollectionUtil.isNotEmpty(threeLevel.getChildren())) {
forthLevelList.addAll(threeLevel.getChildren());
}
}
}
}
}
@@ -159,19 +204,34 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
vo.setOffLineDevCount(offlineDevs.size());
vo.setOffLineDevs(offlineDevs);
}
} else {
return vo;
}
//获取未读事件数量
int eventCount = this.baseMapper.queryTempEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),null);
vo.setEventCount(eventCount);
if (CollectionUtil.isNotEmpty(forthLevelList)) {
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
param1.setEventIds(forthLevelList.stream().map(CsLedgerVO::getId).collect(Collectors.toList()));
int harmonicCount = this.baseMapper.queryTempHarmonic(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),null);
vo.setHarmonicCount(harmonicCount);
List<String> eventCount = eventUserFeignClient.queryTempEvent(param1).getData();
vo.setEventCount(CollectionUtil.isNotEmpty(eventCount)?eventCount.size():0);
List<String> harmonicCount = eventUserFeignClient.queryTempHarmonic(param1).getData();
vo.setHarmonicCount(CollectionUtil.isNotEmpty(harmonicCount)?harmonicCount.size():0);
}
if (CollectionUtil.isNotEmpty(thirdLevelList)) {
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
param1.setEventIds(thirdLevelList.stream().map(CsLedgerVO::getId).collect(Collectors.toList()));
int alarmCount = this.baseMapper.queryAlarmEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),null);
vo.setAlarmCount(alarmCount);
int runCount = this.baseMapper.queryRunEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),null);
vo.setRunCount(runCount);
List<String> alarmCount = eventUserFeignClient.queryAlarmEvent(param1).getData();
vo.setAlarmCount(CollectionUtil.isNotEmpty(alarmCount)?alarmCount.size():0);
List<String> runCount = eventUserFeignClient.queryRunEvent(param1).getData();
vo.setRunCount(CollectionUtil.isNotEmpty(runCount)?runCount.size():0);
}
//note 当前工程数据
//当前工程id
@@ -226,143 +286,35 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
}
//获取未读事件数量
if (CollectionUtil.isNotEmpty(currentLineIds)) {
int eventCount2 = this.baseMapper.queryTempEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),currentLineIds);
vo.setCurrentEventCount(eventCount2);
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
param1.setEventIds(currentLineIds);
int harmonicCount2 = this.baseMapper.queryTempHarmonic(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),currentLineIds);
vo.setCurrentHarmonicCount(harmonicCount2);
List<String> eventCount2 = eventUserFeignClient.queryTempEvent(param1).getData();
vo.setCurrentEventCount(CollectionUtil.isNotEmpty(eventCount2)?eventCount2.size():0);
List<String> harmonicCount2 = eventUserFeignClient.queryTempHarmonic(param1).getData();
vo.setCurrentHarmonicCount(CollectionUtil.isNotEmpty(harmonicCount2)?harmonicCount2.size():0);
}
if (CollectionUtil.isNotEmpty(currentDevIds)) {
int alarmCount2 = this.baseMapper.queryAlarmEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),currentDevIds);
vo.setCurrentAlarmCount(alarmCount2);
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
param1.setEventIds(currentDevIds);
int runCount2 = this.baseMapper.queryRunEvent(RequestUtil.getUserIndex(),PublicDataUtils.calculateMonthStart(time),PublicDataUtils.calculateMonthEnd(time),currentDevIds);
vo.setCurrentRunCount(runCount2);
List<String> alarmCount2 = eventUserFeignClient.queryAlarmEvent(param1).getData();
vo.setCurrentAlarmCount(CollectionUtil.isNotEmpty(alarmCount2)?alarmCount2.size():0);
List<String> runCount2 = eventUserFeignClient.queryRunEvent(param1).getData();
vo.setCurrentRunCount(CollectionUtil.isNotEmpty(runCount2)?runCount2.size():0);
}
}
return vo;
}
// @Override
// public DevCountVO devCount(String id,String time) {
// QueryWrapper<CsEquipmentDeliveryPO> queryWrapper = new QueryWrapper<>();
//
// DevCountVO devCountVO = new DevCountVO();
//
// String userRole = RequestUtil.getUserRole();
// List<String> strings = JSONArray.parseArray(userRole, String.class);
// if(CollectionUtils.isEmpty(strings)){
// throw new BusinessException(AlgorithmResponseEnum.UNKNOW_ROLE);
//
// }
// userRole=strings.get(0);
//
// List<String> device = roleEngineerDevService.getDevice();
// if(CollectionUtils.isEmpty(device)){
// devCountVO.setOnLineDevCount(0);
// devCountVO.setOnLineDevs(new ArrayList<>());
// devCountVO.setOffLineDevCount(0);
// devCountVO.setOffLineDevs(new ArrayList<>());
// }else {
// queryWrapper.clear();
// queryWrapper.in("id",device);
//
// List<CsEquipmentDeliveryPO> csEquipmentDeliveryPOS = csEquipmentDeliveryMapper.selectList(queryWrapper);
// List<CsEquipmentDeliveryPO> collect = csEquipmentDeliveryPOS.stream().filter(temp -> temp.getRunStatus() == 1).collect(Collectors.toList());
// List<CsEquipmentDeliveryPO> collect2= csEquipmentDeliveryPOS.stream().filter(temp -> temp.getRunStatus() == 2).collect(Collectors.toList());
// devCountVO.setOnLineDevCount(collect2.size());
// devCountVO.setOnLineDevs(collect2);
// devCountVO.setOffLineDevCount(collect.size());
// devCountVO.setOffLineDevs(collect);
// List<String> roleengineer = roleEngineerDevService.getRoleengineer();
// devCountVO.setEningerCount(roleengineer.size());
// }
//
// List<CsLedgerVO> deviceTree = iCsLedgerService.getDeviceTree(null);
// //由于多加了一程便携式设备
// List<String> collect1 = deviceTree.stream()
// .map(CsLedgerVO::getChildren).flatMap(Collection::stream)
// .filter(temp -> temp.getId().equals(id))
// .map(CsLedgerVO::getChildren).flatMap(Collection::stream)
// .map(CsLedgerVO::getChildren).flatMap(Collection::stream)
// .map(CsLedgerVO::getId).collect(Collectors.toList());
// //求交集
// device.retainAll(collect1);
// if(CollectionUtils.isEmpty(device)){
// devCountVO.setCurrentOnLineDevCount(0);
// devCountVO.setCurrentOnLineDevs(new ArrayList<>());
// devCountVO.setCurrentOffLineDevCount(0);
// devCountVO.setCurrentOffLineDevs(new ArrayList<>());
// devCountVO.setCurrentProjectCount(0);
//
// }else {
// queryWrapper.clear();
// queryWrapper.in("id",device);
//
// List<CsEquipmentDeliveryPO> csEquipmentDeliveryPOS = csEquipmentDeliveryMapper.selectList(queryWrapper);
// List<CsEquipmentDeliveryPO> collect = csEquipmentDeliveryPOS.stream().filter(temp -> temp.getRunStatus() == 1).collect(Collectors.toList());
// List<CsEquipmentDeliveryPO> collect2= csEquipmentDeliveryPOS.stream().filter(temp -> temp.getRunStatus() == 2).collect(Collectors.toList());
// devCountVO.setCurrentOnLineDevCount(collect2.size());
// devCountVO.setCurrentOnLineDevs(collect2);
// devCountVO.setCurrentOffLineDevCount(collect.size());
// devCountVO.setCurrentOffLineDevs(collect);
// List<CsLedger> list = iCsLedgerService.lambdaQuery().eq(CsLedger::getPid, id).eq(CsLedger::getState, 1).list();
// devCountVO.setCurrentProjectCount(list.size());
// }
// CsEventUserQueryParam csEventUserQueryParam = new CsEventUserQueryParam();
// csEventUserQueryParam.setStatus("0");
//
// //查询暂态事件、运行事件还是使用之前的方法
// List<EventDetailVO> data = eventUserFeignClient.queryEventList(csEventUserQueryParam).getData();
// //查询稳态事件 先获取监测点id
// csLinePOService.getLinesByDevList(device);
//
//
// //查询运行告警事件
//
//
//
//
// List<EventDetailVO> event = data.stream().filter(temp -> temp.getType() == 0).collect(Collectors.toList());
// List<EventDetailVO> harmonic = data.stream().filter(temp -> temp.getType() == 1).collect(Collectors.toList());
// List<EventDetailVO> alarm = data.stream().filter(temp -> temp.getType() == 3).collect(Collectors.toList());
//
// if(Objects.equals(userRole, AppRoleEnum.APP_VIP_USER.getCode())){
// alarm = alarm.stream().filter(temp -> Objects.equals("3", temp.getLevel())).collect(Collectors.toList());
// }
// List<EventDetailVO> run = data.stream().filter(temp -> temp.getType() == 2).collect(Collectors.toList());
// if(Objects.equals(userRole,AppRoleEnum.APP_VIP_USER.getCode())||Objects.equals(userRole,AppRoleEnum.TOURIST.getCode())
// ||Objects.equals(userRole,AppRoleEnum.MARKET_USER.getCode())){
// devCountVO.setFeedBackCount(0);
//
// }else {
// CsFeedbackQueryParm csFeedbackQueryParm = new CsFeedbackQueryParm();
// csFeedbackQueryParm.setPageNum(1);
// csFeedbackQueryParm.setPageSize(100000);
// csFeedbackQueryParm.setStatus("1");
// Page<CsFeedbackVO> data1 = feedBackFeignClient.queryFeedBackPage(csFeedbackQueryParm).getData();
// List<CsFeedbackVO> collect = data1.getRecords().stream().filter(temp -> !Objects.equals(temp.getUserId(), RequestUtil.getUserIndex())).collect(Collectors.toList());
// devCountVO.setFeedBackCount(collect.size());
// }
//
// //todo 后续添加警告数,事件数
// devCountVO.setEventCount(event.size());
// devCountVO.setAlarmCount(alarm.size());
// devCountVO.setRunCount(run.size());
// devCountVO.setHarmonicCount(harmonic.size());
// List<EventDetailVO> curEvent = event.stream().filter(temp -> Objects.equals(temp.getEngineeringid(), id)).collect(Collectors.toList());
// List<EventDetailVO> curHarmonic = harmonic.stream().filter(temp -> Objects.equals(temp.getEngineeringid(), id)).collect(Collectors.toList());
// List<EventDetailVO> curAlarm = alarm.stream().filter(temp -> Objects.equals(temp.getEngineeringid(), id)).collect(Collectors.toList());
// List<EventDetailVO> curRun = run.stream().filter(temp -> Objects.equals(temp.getEngineeringid(), id)).collect(Collectors.toList());
//
// devCountVO.setCurrentEventCount(curEvent.size());
// devCountVO.setCurrentAlarmCount(curAlarm.size());
// devCountVO.setCurrentRunCount(curRun.size());
// devCountVO.setCurrentHarmonicCount(curHarmonic.size());
//
//
// return devCountVO;
// }
/**
* @Description: 判断当前用户是否是主用户 0-否1-是
* @Param:
@@ -510,16 +462,16 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
@Override
public DevUserVO queryUserById(String devId) {
DevUserVO devUser = new DevUserVO();
List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, devId).eq(CsDeviceUserPO::getStatus, "1").list();
if (CollectionUtils.isEmpty(list)) {
throw new BusinessException(AlgorithmResponseEnum.DATA_ARRAY_MISSING);
return devUser;
}
List<String> collect = list.stream().map(CsDeviceUserPO::getSubUserId).distinct().collect(Collectors.toList());
List<User> data = userFeignClient.appuserByIdList(collect).getData();
String primaryUserId = list.get(0).getPrimaryUserId();
List<User> subUser = data.stream().filter(temp -> !Objects.equals(temp.getId(), primaryUserId)).collect(Collectors.toList());
List<User> primaryUser = data.stream().filter(temp -> Objects.equals(temp.getId(), primaryUserId)).collect(Collectors.toList());
DevUserVO devUser = new DevUserVO();
devUser.setDevId(devId);
devUser.setSubUsers(subUser);
devUser.setMasterUser(primaryUser.get(0));
@@ -533,6 +485,21 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
if (CollectionUtil.isNotEmpty(list)){
result = list.stream().map(CsDeviceUserPO::getSubUserId).collect(Collectors.toList());
}
//获取关注设备的用户(工程用户、营销用户)
List<DevDetailDTO> ledger = iCsLedgerService.getInfoByIds(Collections.singletonList(devId));
if (CollectionUtil.isNotEmpty(ledger)) {
DevDetailDTO item = ledger.get(0);
LambdaQueryWrapper<CsMarketData> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(CsMarketData::getEngineerId, item.getEngineeringid());
List<CsMarketData> csMarketData = csMarketDataMapper.selectList(queryWrapper);
if (CollectionUtil.isNotEmpty(csMarketData)) {
List<String> collect = csMarketData.stream().map(CsMarketData::getUserId).collect(Collectors.toList());
result.addAll(collect);
}
}
if (CollectionUtil.isNotEmpty(result)) {
result = result.stream().distinct().collect(Collectors.toList());
}
return result;
}

View File

@@ -255,7 +255,9 @@ public class CsEngineeringServiceImpl extends ServiceImpl<CsEngineeringMapper, C
CsEngineeringPO po = new CsEngineeringPO();
po.setId(item.getEngineeringid());
po.setName(map.get(item.getEngineeringid()).getName());
result.add(po);
if (!Objects.equals(po.getName(), "便携式工程")) {
result.add(po);
}
});
}
}

View File

@@ -9,6 +9,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -24,7 +25,6 @@ import com.njcn.access.utils.MqttUtil;
import com.njcn.common.pojo.dto.DeviceLogDTO;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLogsFeignClient;
import com.njcn.csdevice.api.EngineeringFeignClient;
import com.njcn.csdevice.constant.DataParam;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.mapper.CsEquipmentDeliveryMapper;
@@ -41,6 +41,9 @@ import com.njcn.csdevice.service.*;
import com.njcn.csdevice.util.QRCodeUtil;
import com.njcn.csdevice.utils.ExcelStyleUtil;
import com.njcn.csdevice.utils.StringUtil;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.redis.pojo.enums.AppRedisKey;
@@ -68,6 +71,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@@ -99,7 +103,6 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
private final AskDeviceDataFeignClient askDeviceDataFeignClient;
private final RedisUtil redisUtil;
private final CsSoftInfoMapper csSoftInfoMapper;
private final IMqttUserService mqttUserService;
private final MqttUtil mqttUtil;
private final CsLogsFeignClient csLogsFeignClient;
private final INodeService nodeService;
@@ -108,7 +111,7 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
private final CsTerminalLogsMapper csTerminalLogsMapper;
private final ICsCommunicateService csCommunicateService;
private final ICsUserPinsService csUserPinsService;
private final EngineeringFeignClient engineeringFeignClient;
private final EventUserFeignClient eventUserFeignClient;
@Override
public void refreshDeviceDataCache() {
@@ -157,29 +160,40 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
csEquipmentProcess.setDevId(csEquipmentDeliveryAddParm.getNdid());
csEquipmentProcess.setOperator(RequestUtil.getUserIndex());
csEquipmentProcess.setStartTime(LocalDateTime.now());
// csEquipmentProcess.setProcess(1);
csEquipmentProcess.setProcess(4);
csEquipmentProcess.setStatus (1);
csEquipmentProcessPOService.save(csEquipmentProcess);
result = this.save (csEquipmentDeliveryPo);
//谁新建的设备,则认为是该设备的主用户,新建用户设备关系表数据
boolean addUser = csDeviceUserPOService.add(csEquipmentDeliveryPo.getId());
if (result && addUser) {
refreshDeviceDataCache();
String code = dictTreeFeignClient.queryById(csEquipmentDeliveryAddParm.getDevType()).getData().getCode();
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),code) && Objects.equals(csEquipmentDeliveryAddParm.getDevAccessMethod(),"CLD")) {
//谁新建的设备,则认为是该设备的主用户,新建用户设备关系表数据
boolean addUser = csDeviceUserPOService.add(csEquipmentDeliveryPo.getId());
if (result && addUser) {
refreshDeviceDataCache();
}
} else {
if (result) {
refreshDeviceDataCache();
}
}
return csEquipmentDeliveryPo;
}
@Override
@Transactional(rollbackFor = {Exception.class})
public Boolean AuditEquipmentDelivery(String id) {
CsEquipmentDeliveryPO one = this.lambdaQuery().eq(CsEquipmentDeliveryPO::getId, id).one();
//物理删除
QueryWrapper<CsEquipmentDeliveryPO> wrapper = new QueryWrapper();
wrapper.eq ("id", id);
boolean update = this.remove (wrapper);
//删除deviceuser表里的设备游客数据设备,删除监测点相关数据
boolean update = false;
LambdaQueryWrapper<CsEquipmentDeliveryPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsEquipmentDeliveryPO::getId,id);
CsEquipmentDeliveryPO po = this.getOne(wrapper);
if (po != null) {
update = this.remove(wrapper);
redisUtil.deleteKeysByString(AppRedisKey.LINE_POSITION+po.getNdid());
}
//删除监测点表、监测点拓扑图关系
List<CsLedger> list = csLedgerService.lambdaQuery().eq(CsLedger::getPid, id).list();
if(!CollectionUtils.isEmpty(list)){
List<String> collect = list.stream().map(CsLedger::getId).collect(Collectors.toList());
@@ -190,8 +204,8 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
appLineTopologyDiagramPOQueryWrapper.clear();
appLineTopologyDiagramPOQueryWrapper.in("line_id",collect);
appLineTopologyDiagramService.remove(appLineTopologyDiagramPOQueryWrapper);
// appLineTopologyDiagramService.lambdaUpdate().in(AppLineTopologyDiagramPO::getLineId,collect).set(AppLineTopologyDiagramPO::getStatus,0).update();
}
//清空关系表
LambdaQueryWrapper<CsLedger> csLedgerLambdaQueryWrapper = new LambdaQueryWrapper<>();
csLedgerLambdaQueryWrapper.clear();
csLedgerLambdaQueryWrapper.eq(CsLedger::getId,id);
@@ -199,14 +213,20 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
csLedgerLambdaQueryWrapper.clear();
csLedgerLambdaQueryWrapper.eq(CsLedger::getPid,id);
csLedgerService.remove(csLedgerLambdaQueryWrapper);
csDeviceUserPOService.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId,id).set(CsDeviceUserPO::getStatus,0).update();
//删除设备和模板的关系
LambdaQueryWrapper<CsDevModelRelationPO> csDevModelRelationPOQueryWrapper = new LambdaQueryWrapper<>();
csDevModelRelationPOQueryWrapper.clear();
csDevModelRelationPOQueryWrapper.eq(CsDevModelRelationPO::getDevId,id);
csDevModelRelationService.remove(csDevModelRelationPOQueryWrapper);
//删除设备/用户关系
QueryWrapper<CsDeviceUserPO> csDeviceUserPOQueryWrapper = new QueryWrapper<>();
csDeviceUserPOQueryWrapper.clear();
csDeviceUserPOQueryWrapper.eq("device_id",id);
csDeviceUserPOService.remove(csDeviceUserPOQueryWrapper);
//删除游客
QueryWrapper<CsTouristDataPO> queryWrap = new QueryWrapper<>();
queryWrap.eq("device_id",id);
csTouristDataPOService.getBaseMapper().delete(queryWrap);
/*后续徐那边做处理*/
// CsEquipmentDeliveryPO csEquipmentDeliveryPO = this.getBaseMapper().selectById(id);
// mqttUserService.deleteUser(csEquipmentDeliveryPO.getNdid());
csDevModelRelationService.lambdaUpdate().eq(CsDevModelRelationPO::getDevId,id).set(CsDevModelRelationPO::getStatus,0).update();
if (update) {
refreshDeviceDataCache();
}
@@ -221,8 +241,12 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
return result;
}
BeanUtils.copyProperties (csEquipmentDeliveryPO,result);
result.setAssociatedEngineeringName(csLedgerService.findDataById(csEquipmentDeliveryPO.getAssociatedEngineering()).getName());
result.setAssociatedProjectName(csLedgerService.findDataById(csEquipmentDeliveryPO.getAssociatedProject()).getName());
if(!Objects.isNull (csEquipmentDeliveryPO.getAssociatedEngineering()) && !Objects.equals(csEquipmentDeliveryPO.getAssociatedEngineering(),"")) {
result.setAssociatedEngineeringName(csLedgerService.findDataById(csEquipmentDeliveryPO.getAssociatedEngineering()).getName());
}
if(!Objects.isNull (csEquipmentDeliveryPO.getAssociatedProject()) && !Objects.equals(csEquipmentDeliveryPO.getAssociatedProject(),"")) {
result.setAssociatedProjectName(csLedgerService.findDataById(csEquipmentDeliveryPO.getAssociatedProject()).getName());
}
return result;
}
@@ -244,7 +268,17 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
Page<ProjectEquipmentVO> list = this.baseMapper.queryProjectEquipmentVO(returnpage,projectEquipmentQueryParm,device);
//根据设备id获取监测点id集合
List<CsLinePO> lineIds = csLinePOService.getLineByDev(device);
//根据设备获取当日是否存在未读取的暂态事件
CsEventUserQueryParam param = new CsEventUserQueryParam();
param.setUserId(RequestUtil.getUserIndex());
param.setStartTime(LocalDate.now().atStartOfDay().format(DatePattern.NORM_DATETIME_FORMATTER));
param.setEndTime(LocalDateTime.now().format(DatePattern.NORM_DATETIME_FORMATTER));
param.setEventIds(lineIds.stream().map(CsLinePO::getLineId).collect(Collectors.toList()));
List<CsEventPO> eventList = eventUserFeignClient.queryTempEventDetail(param).getData();
Map<String, List<CsEventPO>> eventMap = Optional.ofNullable(eventList)
.orElse(Collections.emptyList())
.stream()
.collect(Collectors.groupingBy(CsEventPO::getDeviceId));
List<ProjectEquipmentVO> recordList = new ArrayList<>();
list.getRecords().forEach(temp->{
@@ -256,6 +290,8 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
if (!Objects.equals(DicDataEnum.PORTABLE.getCode(),temp.getDevType())) {
recordList.add(temp);
}
//判断设备是否存在告警
temp.setIsAlarm(CollectionUtil.isNotEmpty(eventMap.get(temp.getEquipmentId())));
});
//获取用户置顶的设备
@@ -358,11 +394,14 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
int total = this.baseMapper.getCounts(queryParam);
if (total > 0) {
List<CsEquipmentDeliveryVO> recordList = this.baseMapper.getList(queryParam);
//新增逻辑(针对便携式设备):修改设备中的未注册状态(status = 1)改为5(前端定义的字典也即未接入)
//新增逻辑(针对便携式设备、监测设备):修改设备中的未注册状态(status = 1)改为5(前端定义的字典也即未接入)
for(CsEquipmentDeliveryVO csEquipmentDeliveryVO : recordList){
if(DataParam.portableDevType.equals(csEquipmentDeliveryVO.getDevType()) && csEquipmentDeliveryVO.getStatus() == 1){
String code = dictTreeFeignClient.queryById(csEquipmentDeliveryVO.getDevType()).getData().getCode();
if((Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && csEquipmentDeliveryVO.getStatus() == 1)
|| (Objects.equals(code, DicDataEnum.DEV_CLD.getCode()) && csEquipmentDeliveryVO.getStatus() == 1)){
csEquipmentDeliveryVO.setStatus(5);
} else if (DataParam.portableDevType.equals(csEquipmentDeliveryVO.getDevType()) && csEquipmentDeliveryVO.getStatus() == 2) {
} else if((Objects.equals(code, DicDataEnum.PORTABLE.getCode()) && csEquipmentDeliveryVO.getStatus() == 2)
|| (Objects.equals(code, DicDataEnum.DEV_CLD.getCode()) && csEquipmentDeliveryVO.getStatus() == 2)){
csEquipmentDeliveryVO.setStatus(6);
}
//判断装置是否已经连接上mqtt服务器
@@ -755,20 +794,6 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
}
}
@Override
public void updateLedger(String nDid,String engineeringId,String projectId) {
boolean result;
LambdaUpdateWrapper<CsEquipmentDeliveryPO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.eq(CsEquipmentDeliveryPO::getNdid,nDid)
.ne(CsEquipmentDeliveryPO::getRunStatus,0)
.set(CsEquipmentDeliveryPO::getAssociatedEngineering,engineeringId)
.set(CsEquipmentDeliveryPO::getAssociatedProject,projectId);
result = this.update(lambdaUpdateWrapper);
if (result) {
refreshDeviceDataCache();
}
}
@Override
public boolean rebootDevice(String nDid) {
boolean result = false;
@@ -826,11 +851,6 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
@Transactional(rollbackFor = Exception.class)
public CsEquipmentDeliveryPO saveCld(CsEquipmentDeliveryAddParm param) {
boolean result;
//设备名称可以重复
//CsEquipmentDeliveryPO one = this.lambdaQuery().eq(CsEquipmentDeliveryPO::getName, param.getName()).ne(CsEquipmentDeliveryPO::getRunStatus, 0).one();
//if(Objects.nonNull (one)){
// throw new BusinessException ("设备名称不能重复");
//}
StringUtil.containsSpecialCharacters(param.getNdid());
CsEquipmentDeliveryPO po = this.queryEquipmentPOByndid (param.getNdid());
if(!Objects.isNull (po)){
@@ -912,6 +932,7 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
}
//新增操作日志
CsTerminalLogs csTerminalLogs = new CsTerminalLogs();
csTerminalLogs.setId(IdUtil.simpleUUID());
csTerminalLogs.setDeviceId(id);
csTerminalLogs.setOperateType(2);
csTerminalLogs.setIsPush(0);
@@ -1006,7 +1027,8 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
}
LambdaQueryWrapper<CsEquipmentDeliveryPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(CsEquipmentDeliveryPO::getNodeId,id)
.in(ObjectUtil.isNotEmpty(state),CsEquipmentDeliveryPO::getUsageStatus,state);
.in(ObjectUtil.isNotEmpty(state),CsEquipmentDeliveryPO::getUsageStatus,state)
.eq(CsEquipmentDeliveryPO::getDevAccessMethod,"CLD");
return this.list(lambdaQueryWrapper);
}

View File

@@ -21,7 +21,6 @@ import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csdevice.pojo.param.CsLedgerParam;
import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csdevice.pojo.vo.CsMarketDataVO;
import com.njcn.csdevice.service.*;
import com.njcn.csharmonic.api.PqSensitiveUserFeignClient;
import com.njcn.device.biz.pojo.po.PqSensitiveUser;
@@ -1296,9 +1295,19 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
if (CollectionUtil.isNotEmpty(enginingeringIds)) {
List<CsLedger> engineer = this.listByIds(enginingeringIds);
engineer.forEach(item -> {
List<String> devNames = new ArrayList<>();
List<String> devIds = new ArrayList<>();
DevDetailDTO detail = new DevDetailDTO();
detail.setEngineeringid(item.getId());
detail.setEngineeringName(item.getName());
ledgers.forEach(item2->{
if (item2.getPids().contains(item.getId())) {
devIds.add(item2.getId());
devNames.add(item2.getName());
}
});
detail.setEquipmentId(String.join(",", devIds));
detail.setEquipmentName(String.join(",", devNames));
details.add(detail);
});
}
@@ -1341,11 +1350,25 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
if (CollUtil.isNotEmpty(dev)) {
List<String> devIds = dev.stream().map(CsLedger::getId).collect(Collectors.toList());
//监测点
LambdaQueryWrapper<CsLedger> queryWrapper3 = new LambdaQueryWrapper<>();
queryWrapper3.in(CsLedger::getPid, devIds);
List<CsLedger> line = this.list(queryWrapper3);
Map<String,List<CsLedger>> lineMap = line.stream().collect(Collectors.groupingBy(CsLedger::getPid));
List<CsEquipmentDeliveryPO> devs = csEquipmentDeliveryMapper.selectBatchIds(devIds);
Map<String, CsEquipmentDeliveryPO> devsMap = devs.stream().collect(Collectors.toMap(CsEquipmentDeliveryPO::getId, item -> item));
dev.forEach(item -> {
DevDetailDTO detail = new DevDetailDTO();
//监测点
List<CsLedger> lines = lineMap.get(item.getId());
if (CollUtil.isNotEmpty(lines)) {
detail.setLineList(lines.stream().map(CsLedger::getId).collect(Collectors.toList()));
}
detail.setEquipmentName(item.getName());
detail.setEquipmentId(item.getId());
@@ -1381,15 +1404,17 @@ public class CsLedgerServiceImpl extends ServiceImpl<CsLedgerMapper, CsLedger> i
LambdaQueryWrapper<CsLedger> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(CsLedger::getPid, item);
List<CsLedger> project = this.list(queryWrapper);
//工程id
List<String> projectIds = project.stream().map(CsLedger::getId).collect(Collectors.toList());
LambdaQueryWrapper<CsLedger> queryWrapper2 = new LambdaQueryWrapper<>();
queryWrapper2.in(CsLedger::getPid, projectIds);
List<CsLedger> dev = this.list(queryWrapper2);
if (CollectionUtil.isNotEmpty(dev)) {
DevDetailDTO dto = new DevDetailDTO();
dto.setEngineeringid(item);
result.add(dto);
if (CollectionUtil.isNotEmpty(project)) {
//项目id
List<String> projectIds = project.stream().map(CsLedger::getId).collect(Collectors.toList());
LambdaQueryWrapper<CsLedger> queryWrapper2 = new LambdaQueryWrapper<>();
queryWrapper2.in(CsLedger::getPid, projectIds);
List<CsLedger> dev = this.list(queryWrapper2);
if (CollectionUtil.isNotEmpty(dev)) {
DevDetailDTO dto = new DevDetailDTO();
dto.setEngineeringid(item);
result.add(dto);
}
}
});
return result;

View File

@@ -66,6 +66,8 @@ public class CsTerminalLogsServiceImpl extends ServiceImpl<CsTerminalLogsMapper,
wrapper.eq(CsTerminalLogs::getIsPush, 0);
List<CsTerminalLogs> list = this.list(wrapper);
if (CollectionUtil.isNotEmpty(list)) {
//先清空缓存
redisUtil.delete(RequestUtil.getUserIndex()+"reply");
//新增台账集合
List<String> addList = new ArrayList<>();
//修改台账集合
@@ -97,42 +99,44 @@ public class CsTerminalLogsServiceImpl extends ServiceImpl<CsTerminalLogsMapper,
});
//整合后 所有设备的id
List<String> devList = Stream.of(addList, updateList, deleteList).flatMap(List::stream).collect(Collectors.toList());
//获取设备集合
List<CsEquipmentDeliveryPO> deviceList = csEquipmentDeliveryService.listByIds(devList);
//按照前置机id分组
Map<String,List<CsEquipmentDeliveryPO>> nodeMap = deviceList.stream().collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeId));
nodeMap.forEach((k,v)->{
int maxProcessNum = nodeService.getNodeById(k).getMaxProcessNum();
//按照进程号分组
Map<Integer,List<CsEquipmentDeliveryPO>> nodeProcessMap = v.stream().collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeProcess));
nodeProcessMap.forEach((k1,v1)->{
if (v1.size() > 10) {
//一个进程下修改的设备数量超过10台重启该进程号下的前置
CldControlMessage cldControlMessage = new CldControlMessage();
cldControlMessage.setGuid(IdUtil.simpleUUID());
cldControlMessage.setCode("set_process");
cldControlMessage.setProcessNo(k1);
cldControlMessage.setFun("delete");
cldControlMessage.setProcessNum(maxProcessNum);
controlMessageTemplate.sendMember(cldControlMessage,k);
}
if (CollectionUtil.isNotEmpty(devList)) {
//获取设备集合
List<CsEquipmentDeliveryPO> deviceList = csEquipmentDeliveryService.listByIds(devList);
//按照前置机id分组
Map<String,List<CsEquipmentDeliveryPO>> nodeMap = deviceList.stream().collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeId));
nodeMap.forEach((k,v)->{
int maxProcessNum = nodeService.getNodeById(k).getMaxProcessNum();
//按照进程号分组
Map<Integer,List<CsEquipmentDeliveryPO>> nodeProcessMap = v.stream().collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeProcess));
nodeProcessMap.forEach((k1,v1)->{
if (v1.size() > 10) {
//一个进程下修改的设备数量超过10台重启该进程号下的前置
CldControlMessage cldControlMessage = new CldControlMessage();
cldControlMessage.setGuid(IdUtil.simpleUUID());
cldControlMessage.setCode("set_process");
cldControlMessage.setProcessNo(k1);
cldControlMessage.setFun("delete");
cldControlMessage.setProcessNum(maxProcessNum);
controlMessageTemplate.sendMember(cldControlMessage,k);
}
});
});
});
if (CollectionUtil.isNotEmpty(addList)) {
sendMessage(addList, deviceList, "add_terminal");
}
if (CollectionUtil.isNotEmpty(updateList)) {
sendMessage(updateList, deviceList, "ledger_modify");
}
if (CollectionUtil.isNotEmpty(deleteList)) {
sendDeleteMessage(deleteList, list, "delete_terminal");
}
if (CollectionUtil.isNotEmpty(addList)) {
sendMessage(addList, deviceList, "add_terminal");
}
if (CollectionUtil.isNotEmpty(updateList)) {
sendMessage(updateList, deviceList, "ledger_modify");
}
if (CollectionUtil.isNotEmpty(deleteList)) {
sendDeleteMessage(deleteList, list, "delete_terminal");
}
//推送完将数据改成推送
LambdaUpdateWrapper<CsTerminalLogs> wrapper2 = new LambdaUpdateWrapper<>();
wrapper2.set(CsTerminalLogs::getIsPush, 1);
this.update(wrapper2);
//推送完将数据改成推送
LambdaUpdateWrapper<CsTerminalLogs> wrapper2 = new LambdaUpdateWrapper<>();
wrapper2.set(CsTerminalLogs::getIsPush, 1);
this.update(wrapper2);
}
} else {
return "暂无需要推送的数据";
}

View File

@@ -57,53 +57,98 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
List<String> redisList = Stream.of(object.toString().split(",")).collect(Collectors.toList());
List<CsTerminalReply> list = this.lambdaQuery().in(CsTerminalReply::getReplyId,redisList).orderByAsc(CsTerminalReply::getCreateTime).list();
if (CollectionUtil.isNotEmpty(list)) {
Map<Integer,List<CsTerminalReply>> map = list.stream().collect(Collectors.groupingBy(CsTerminalReply::getIsReceived));
List<CsTerminalReply> list1 = map.get(1);
if (CollectionUtil.isEmpty(list1)) {
String key = "更新失败,未收到前置应答,请查看应答报文是否发送";
result.add(key);
//将cs_terminal_logs数据置为未发送
list.forEach(item->{
list.forEach(item->{
String key;
String code = "";
if (Objects.equals(item.getCode(), "add_terminal")) {
code = "新增";
} else if (Objects.equals(item.getCode(), "ledger_modify")) {
code = "修改";
} else if (Objects.equals(item.getCode(), "delete_terminal")){
code = "删除";
}
String nodeName = nodeService.getNodeById(item.getNodeId()).getName();
List<CsEquipmentDeliveryPO> devList1 = csEquipmentDeliveryService.getAll();
List<CsEquipmentDeliveryPO> devList2 = devList1.stream().filter(item1 -> Objects.equals(item1.getId(), item.getDeviceId())).collect(Collectors.toList());
List<String> devNameList = devList2.stream().map(CsEquipmentDeliveryPO::getName).collect(Collectors.toList());
String devNameListString;
if (CollectionUtil.isNotEmpty(devNameList)) {
devNameListString = devNameList.toString();
} else {
devNameListString = "[" + item.getDeviceName() + "]";
}
if (item.getIsReceived() == 0) {
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备未收到应答";
//将cs_terminal_logs数据置为未发送
csTerminalLogsService.updateLaterData(item.getDeviceId(),item.getCode());
});
} else {
list.forEach(item->{
String key;
String code = "";
if (Objects.equals(item.getCode(), "add_terminal")) {
code = "新增";
} else if (Objects.equals(item.getCode(), "ledger_modify")) {
code = "修改";
} else if (Objects.equals(item.getCode(), "delete_terminal")){
code = "删除";
}
String nodeName = nodeService.getNodeById(item.getNodeId()).getName();
List<CsEquipmentDeliveryPO> devList1 = csEquipmentDeliveryService.getAll();
List<CsEquipmentDeliveryPO> devList2 = devList1.stream().filter(item1 -> Objects.equals(item1.getId(), item.getDeviceId())).collect(Collectors.toList());
List<String> devNameList = devList2.stream().map(CsEquipmentDeliveryPO::getName).collect(Collectors.toList());
String devNameListString;
if (CollectionUtil.isNotEmpty(devNameList)) {
devNameListString = devNameList.toString();
} else {
devNameListString = "[" + item.getDeviceName() + "]";
}
if (item.getIsReceived() == 0) {
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备未收到应答";
//将cs_terminal_logs数据置为未发送
csTerminalLogsService.updateLaterData(item.getDeviceId(),item.getCode());
} else if (item.getIsReceived() == 1){
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据成功";
} else {
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据失败";
}
result.add(key);
});
}
} else if (item.getIsReceived() == 1){
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据成功";
} else {
key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据失败";
}
result.add(key);
});
}
}
return result;
}
// @Override
// public List<String> queryReplyData() {
// List<String> result = new ArrayList<>();
// Object object = redisUtil.getObjectByKey(RequestUtil.getUserIndex()+"reply");
// if (object != null) {
// List<String> redisList = Stream.of(object.toString().split(",")).collect(Collectors.toList());
// List<CsTerminalReply> list = this.lambdaQuery().in(CsTerminalReply::getReplyId,redisList).orderByAsc(CsTerminalReply::getCreateTime).list();
// if (CollectionUtil.isNotEmpty(list)) {
// Map<Integer,List<CsTerminalReply>> map = list.stream().collect(Collectors.groupingBy(CsTerminalReply::getIsReceived));
// List<CsTerminalReply> list1 = map.get(1);
// if (CollectionUtil.isEmpty(list1)) {
// String key = "更新失败,未收到前置应答,请查看应答报文是否发送";
// result.add(key);
// //将cs_terminal_logs数据置为未发送
// list.forEach(item->{
// csTerminalLogsService.updateLaterData(item.getDeviceId(),item.getCode());
// });
// } else {
// list.forEach(item->{
// String key;
// String code = "";
// if (Objects.equals(item.getCode(), "add_terminal")) {
// code = "新增";
// } else if (Objects.equals(item.getCode(), "ledger_modify")) {
// code = "修改";
// } else if (Objects.equals(item.getCode(), "delete_terminal")){
// code = "删除";
// }
// String nodeName = nodeService.getNodeById(item.getNodeId()).getName();
// List<CsEquipmentDeliveryPO> devList1 = csEquipmentDeliveryService.getAll();
// List<CsEquipmentDeliveryPO> devList2 = devList1.stream().filter(item1 -> Objects.equals(item1.getId(), item.getDeviceId())).collect(Collectors.toList());
// List<String> devNameList = devList2.stream().map(CsEquipmentDeliveryPO::getName).collect(Collectors.toList());
// String devNameListString;
// if (CollectionUtil.isNotEmpty(devNameList)) {
// devNameListString = devNameList.toString();
// } else {
// devNameListString = "[" + item.getDeviceName() + "]";
// }
// if (item.getIsReceived() == 0) {
// key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备未收到应答";
// //将cs_terminal_logs数据置为未发送
// csTerminalLogsService.updateLaterData(item.getDeviceId(),item.getCode());
// } else if (item.getIsReceived() == 1){
// key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据成功";
// } else {
// key = nodeName + item.getProcessNo() + "号进程下," + devNameListString + "设备" + code + "数据失败";
// }
// result.add(key);
// });
// }
// }
// }
// return result;
// }
@Override
public void updateReplyData(IcdBzReplyParam param) {
LambdaUpdateWrapper<CsTerminalReply> wrapper = new LambdaUpdateWrapper<>();

View File

@@ -99,6 +99,10 @@ public class DeviceFtpServiceImpl implements DeviceFtpService {
if (!mqttClient) {
throw new BusinessException(AccessResponseEnum.MISSING_CLIENT);
}
//判断文件如果过大,不给下载
if (size > 15728640) {
throw new BusinessException("文件过大(超过15M),暂不支持下载!");
}
Object task = redisUtil.getObjectByKey("fileDowning:"+nDid);
if (Objects.nonNull(task)) {
throw new BusinessException(AlgorithmResponseEnum.FILE_DOWNLOADING);

View File

@@ -0,0 +1,112 @@
package com.njcn.csdevice.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.csdevice.service.DeviceMessageService;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.AppInfoSetFeignClient;
import com.njcn.user.api.AppUserFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.po.app.AppInfoSet;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
class DeviceMessageServiceImpl implements DeviceMessageService {
private final AppUserFeignClient appUserFeignClient;
private final CsDeviceUserFeignClient csDeviceUserFeignClient;
private final AppInfoSetFeignClient appInfoSetFeignClient;
private final UserFeignClient userFeignClient;
private final CsLinePOService csLinePOService;
private final DicDataFeignClient dicDataFeignClient;
private final RedisUtil redisUtil;
@Override
public List<String> getEventUserByDeviceId(String devId, Boolean isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
List<String> result = new ArrayList<>(list);
if (isAdmin) {
List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
result.addAll(adminList);
}
if (CollectionUtil.isNotEmpty(result)) {
result = result.stream().distinct().collect(Collectors.toList());
}
return result;
}
@Override
public List<User> getSendUserByType(DeviceMessageParam param) {
List<User> users = new ArrayList<>();
List<String> result = new ArrayList<>();
List<AppInfoSet> appInfoSet = appInfoSetFeignClient.getListById(param.getUserList()).getData();
switch (param.getEventType()) {
case 0:
result = appInfoSet.stream()
.filter(person -> person.getEventInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 1:
result = appInfoSet.stream()
.filter(person -> person.getHarmonicInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 2:
result = appInfoSet.stream()
.filter(person -> person.getRunInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 3:
result = appInfoSet.stream()
.filter(person -> person.getAlarmInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
default:
break;
}
if (CollectionUtil.isNotEmpty(result)){
users = userFeignClient.appuserByIdList(result).getData();
}
return users;
}
@Override
public void getLineInfo(String id) {
Map<Integer,String> map = new HashMap<>();
List<CsLinePO> lineList = csLinePOService.findByNdid(id);
if (CollectionUtil.isEmpty(lineList)){
throw new BusinessException("监测点为空");
}
for (CsLinePO item : lineList) {
if (Objects.isNull(item.getPosition())){
map.put(item.getClDid(),item.getLineId());
} else {
DictData dictData = dicDataFeignClient.getDicDataById(item.getPosition()).getData();
if (Objects.equals(dictData.getCode(), DicDataEnum.OUTPUT_SIDE.getCode())){
map.put(0,item.getLineId());
} else if (Objects.equals(dictData.getCode(), DicDataEnum.GRID_SIDE.getCode())){
map.put(1,item.getLineId());
} else if (Objects.equals(dictData.getCode(), DicDataEnum.LOAD_SIDE.getCode())){
map.put(2,item.getLineId());
}
}
}
redisUtil.saveByKey(AppRedisKey.LINE_POSITION+id,map);
}
}

View File

@@ -183,7 +183,7 @@ public class EngineeringProjectServiceImpl implements IEngineeringProjectService
//查询所有拓扑图
LambdaQueryWrapper<AppTopologyDiagramPO> queryWrapper3 = new LambdaQueryWrapper<>();
queryWrapper3.eq(AppTopologyDiagramPO::getStatus,"1");
queryWrapper3.eq(AppTopologyDiagramPO::getStatus,1);
List<AppTopologyDiagramPO> list3 = appTopologyDiagramService.list(queryWrapper3);
Map<String,AppTopologyDiagramPO> map3 = list3.stream().collect(Collectors.toMap(AppTopologyDiagramPO::getProjectId, item->item));

View File

@@ -132,18 +132,19 @@ public class RoleEngineerDevServiceImpl implements RoleEngineerDevService {
}
//fix 新需求 工程用户可以看到关注工程的设备和对应的主用户和子用户的设备
//note 这边工程用户不查询主设备,只看关注的工程,做下调整,不然会出现工程用户未关注任何工程,但是有一台主设备,导致界面有数据
else if (Objects.equals(role, AppRoleEnum.ENGINEERING_USER.getCode())) {
List<String> sumDevId = new ArrayList<>();
csDeviceUserPOQueryWrapper.clear();
csDeviceUserPOQueryWrapper.eq("status","1").and(wq -> {
wq.eq("primary_user_id", userIndex)
.or()
.eq("sub_user_id",userIndex);
});
List<CsDeviceUserPO> csDeviceUserPOS = csDeviceUserPOMapper.selectList(csDeviceUserPOQueryWrapper);
if(!CollectionUtils.isEmpty(csDeviceUserPOS)){
sumDevId = csDeviceUserPOS.stream().map(CsDeviceUserPO::getDeviceId).distinct().collect(Collectors.toList());
}
// csDeviceUserPOQueryWrapper.eq("status","1").and(wq -> {
// wq.eq("primary_user_id", userIndex)
// .or()
// .eq("sub_user_id",userIndex);
// });
// List<CsDeviceUserPO> csDeviceUserPOS = csDeviceUserPOMapper.selectList(csDeviceUserPOQueryWrapper);
// if(!CollectionUtils.isEmpty(csDeviceUserPOS)){
// sumDevId = csDeviceUserPOS.stream().map(CsDeviceUserPO::getDeviceId).distinct().collect(Collectors.toList());
// }
QueryWrapper<CsMarketData> csMarketDataQueryWrapper = new QueryWrapper<>();
csMarketDataQueryWrapper.eq("user_id", userIndex);

View File

@@ -0,0 +1,417 @@
package com.njcn.csdevice.service.impl;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.mapper.CsSmsSendRecordMapper;
import com.njcn.csdevice.pojo.dto.CredentialReqDTO;
import com.njcn.csdevice.pojo.dto.SendResult;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
import com.njcn.csdevice.service.ISmsSendService;
import com.njcn.redis.utils.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* @author xy
*/
@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class SmsSendServiceImpl extends ServiceImpl<CsSmsSendRecordMapper, CsSmsSendRecord> implements ISmsSendService {
@Value("${msg.credential_url:http://192.168.2.126:48083/admin-api/push/credential/generate}")
private String CREDENTIAL_URL;
@Value("${msg.sms_send_url:http://192.168.2.126:48083/admin-api/push/message/send/sms}")
private String SMS_SEND_URL;
@Value("${msg.connect_timeout:5000}")
private Integer CONNECT_TIMEOUT;
@Value("${msg.read_timeout:30000}")
private Integer READ_TIMEOUT;
@Value("${msg.system_name:NPQS-9500}")
private String SYSTEM_NAME;
@Value("${msg.secret_key:123456}")
private String SECRET_KEY;
private static final int[] RETRY_DELAYS = {1, 2, 3};
private static final int MAX_RETRY = 3;
private static final String CREDENTIAL_CACHE_KEY = "SMS_CREDENTIAL_TOKEN";
private static final Gson GSON = new Gson();
@Resource
private RedisUtil redisUtil;
@Override
public void sendSmsWithRetry(String receiver, String content, String messageType) {
MessageRecordReqVO vo = new MessageRecordReqVO();
vo.setReceiver(receiver);
vo.setContent(content);
vo.setMessageType(messageType);
sendSmsWithRetry(vo);
}
@Override
public void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO) {
CsSmsSendRecord record = initRecord(messageRecordReqVO);
this.save(record);
try {
String credentialToken = getOrRefreshCredentialWithRetry(record);
if (credentialToken == null) {
record.setSendStatus(0);
record.setFailReason("获取凭证失败已重试3次");
log.error("获取凭证失败,短信未发送,接收者: {}", messageRecordReqVO.getReceiver());
this.updateById(record);
throw new BusinessException("获取凭证失败已重试3次");
}
record.setCredentialToken(credentialToken);
record.setSendTime(LocalDateTime.now());
this.updateById(record);
boolean success = attemptSendWithRetry(messageRecordReqVO, credentialToken, record);
if (success) {
record.setSendStatus(1);
record.setFailReason(null);
log.info("短信发送成功,接收者: {}", messageRecordReqVO.getReceiver());
} else {
record.setSendStatus(0);
if (record.getFailReason() == null) {
record.setFailReason("超过最大重试次数,发送失败");
}
log.error("短信发送失败,接收者: {},已重试{}次,原因: {}",
messageRecordReqVO.getReceiver(), record.getRetryCount(), record.getFailReason());
throw new BusinessException("短信发送失败: " + record.getFailReason());
}
} catch (BusinessException e) {
record.setSendStatus(0);
record.setFailReason(e.getMessage());
log.error("短信发送业务异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
this.updateById(record);
throw e;
} catch (Exception e) {
record.setSendStatus(0);
record.setFailReason("发送异常: " + e.getMessage());
log.error("短信发送异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
this.updateById(record);
throw new BusinessException("短信发送异常: " + e.getMessage());
} finally {
this.updateById(record);
}
}
private CsSmsSendRecord initRecord(MessageRecordReqVO vo) {
CsSmsSendRecord record = new CsSmsSendRecord();
record.setReceiver(vo.getReceiver());
record.setContent(vo.getContent());
record.setMessageType(vo.getMessageType());
record.setSendStatus(-1);
record.setRetryCount(0);
record.setMaxRetry(MAX_RETRY);
record.setCreateTime(LocalDateTime.now());
return record;
}
private String getOrRefreshCredentialWithRetry(CsSmsSendRecord record) {
Object cachedToken = redisUtil.getObjectByKey(CREDENTIAL_CACHE_KEY);
if (cachedToken != null) {
log.info("使用缓存的凭证令牌");
return cachedToken.toString();
}
log.info("缓存中无凭证开始获取新凭证最多重试3次");
for (int i = 1; i <= 3; i++) {
try {
String token = fetchNewCredential();
log.info("第{}次尝试获取凭证成功", i);
return token;
} catch (Exception e) {
log.warn("第{}次获取凭证失败: {}", i, e.getMessage());
record.setFailReason("获取凭证第" + i + "次失败: " + e.getMessage());
this.updateById(record);
try {
int waitSeconds = i * 10;
log.info("等待{}秒后重试...", waitSeconds);
TimeUnit.SECONDS.sleep(waitSeconds);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
log.error("凭证获取重试被中断");
record.setFailReason("获取凭证实例被中断");
this.updateById(record);
return null;
}
}
}
log.error("获取凭证失败已重试3次");
return null;
}
private String fetchNewCredential() {
CredentialReqDTO reqDTO = new CredentialReqDTO();
reqDTO.setSystemName(SYSTEM_NAME);
reqDTO.setSecretKey(SECRET_KEY);
HttpURLConnection connection = null;
try {
URL url = new URL(CREDENTIAL_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(GSON.toJson(reqDTO).getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new BusinessException("获取凭证失败HTTP响应码: " + responseCode);
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
int code = jsonResponse.get("code").getAsInt();
if (code != 0) {
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
throw new BusinessException("获取凭证失败,错误码: " + code + ",错误信息: " + msg);
}
JsonObject data = jsonResponse.getAsJsonObject("data");
String token = data.get("credentialToken").getAsString();
long expiresTimestamp = data.get("expiresTime").getAsLong();
LocalDateTime expiresTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(expiresTimestamp),
ZoneId.systemDefault()
);
long expireSeconds = calculateExpireSeconds(expiresTime);
redisUtil.saveByKeyWithExpire(CREDENTIAL_CACHE_KEY, token, expireSeconds);
log.info("获取新凭证成功,过期时间: {},缓存有效期: {}秒", expiresTime, expireSeconds);
return token;
} catch (SocketTimeoutException e) {
throw new BusinessException("获取凭证超时(30秒),请检查网络连接");
} catch (ConnectException e) {
throw new BusinessException("无法连接到凭证服务,请检查服务是否启动和网络是否正常");
} catch (IOException e) {
throw new BusinessException("获取凭证IO异常: " + e.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private long calculateExpireSeconds(LocalDateTime expiresTime) {
long expireSeconds = java.time.Duration.between(
LocalDateTime.now(),
expiresTime
).getSeconds();
expireSeconds = expireSeconds - 60;
return Math.max(expireSeconds, 60);
}
private boolean attemptSendWithRetry(MessageRecordReqVO vo, String token, CsSmsSendRecord record) {
for (int attempt = 0; attempt <= MAX_RETRY; attempt++) {
if (attempt > 0) {
int delayMinutes = RETRY_DELAYS[attempt - 1];
log.info("第{}次重试,等待{}分钟后发送...", attempt, delayMinutes);
try {
TimeUnit.MINUTES.sleep(delayMinutes);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("重试等待被中断", e);
record.setFailReason("重试等待被中断");
return false;
}
record.setRetryCount(attempt);
}
SendResult result = executeSendSms(vo, token, record);
if (result.isSuccess()) {
record.setFailReason(null);
log.info("第{}次尝试发送成功消息ID: {}", attempt, result.getMessageId());
return true;
}
record.setFailReason(result.getFailReason());
if (result.isUnauthorized()) {
log.warn("凭证失效(401),重新获取凭证后重试...");
String newToken = getOrRefreshCredentialWithRetry(record);
if (newToken == null) {
record.setFailReason("凭证刷新失败,无法重新获取凭证");
return false;
}
token = newToken;
record.setCredentialToken(newToken);
this.updateById(record);
continue;
}
if (!result.isTimeOut()) {
log.warn("发送失败且非超时,不再重试,原因: {},响应时间: {}ms",
result.getFailReason(), record.getResponseTime());
return false;
}
log.warn("第{}次发送超时,将重试,响应时间: {}ms",
attempt, record.getResponseTime());
}
record.setFailReason("超过最大重试次数,发送超时");
return false;
}
private SendResult executeSendSms(MessageRecordReqVO vo, String token, CsSmsSendRecord record) {
HttpURLConnection connection = null;
long startTime = System.currentTimeMillis();
try {
URL url = new URL(SMS_SEND_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Credential-Token", token);
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(GSON.toJson(Collections.singletonList(vo)).getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
responseCode == 200 ? connection.getInputStream() : connection.getErrorStream(),
StandardCharsets.UTF_8
)
);
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
if (responseCode != 200) {
String failReason = "HTTP响应码异常: " + responseCode;
if (response.length() > 0) {
failReason += ",响应: " + response.toString();
}
record.setFailReason(failReason);
return new SendResult(false, null, failReason, false, false);
}
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
int code = jsonResponse.get("code").getAsInt();
if (code == 401) {
String failReason = "凭证失效(HTTP 401)";
record.setFailReason(failReason);
redisUtil.delete(CREDENTIAL_CACHE_KEY);
return new SendResult(false, null, failReason, false, true);
} else {
if (code != 0) {
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
String failReason = "业务错误码: " + code + ",错误信息: " + msg;
record.setFailReason(failReason);
return new SendResult(false, null, failReason, false, false);
}
}
JsonObject firstResult = jsonResponse.getAsJsonArray("data").get(0).getAsJsonObject();
boolean result = firstResult.get("result").getAsBoolean();
String messageId = firstResult.has("messageId") ? firstResult.get("messageId").getAsString() : null;
String detail = firstResult.has("detail") ? firstResult.get("detail").getAsString() : null;
if (result) {
log.info("短信发送成功,接收者: {}消息ID: {},详情: {},耗时: {}ms",
vo.getReceiver(), messageId, detail, responseTime);
return new SendResult(true, messageId, null, false, false);
} else {
String failReason = "发送失败: " + detail;
record.setFailReason(failReason);
return new SendResult(false, messageId, failReason, false, false);
}
} catch (SocketTimeoutException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "请求超时(30秒)";
record.setFailReason(failReason);
log.warn("短信发送超时,接收者: {},耗时: {}ms", vo.getReceiver(), responseTime);
return new SendResult(false, null, failReason, true, false);
} catch (ConnectException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "无法连接到短信服务";
record.setFailReason(failReason);
log.error("短信服务连接失败,接收者: {}", vo.getReceiver(), e);
return new SendResult(false, null, failReason, false, false);
} catch (IOException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "IO异常: " + e.getMessage();
record.setFailReason(failReason);
log.error("短信发送IO异常接收者: {},耗时: {}ms", vo.getReceiver(), responseTime, e);
return new SendResult(false, null, failReason, false, false);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}

View File

@@ -0,0 +1,22 @@
package com.njcn.csharmonic.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csharmonic.api.fallback.CsHarmonicPlanFeignClientFallbackFactory;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_HARMONIC_BOOT, path = "/csHarmonicPlan", fallbackFactory = CsHarmonicPlanFeignClientFallbackFactory.class,contextId = "csHarmonicPlan")
public interface CsHarmonicPlanFeignClient {
@GetMapping("/getById")
@ApiOperation("根据ID查询稳态指标方案")
HttpResult<CsHarmonicPlan> getById(@RequestParam("id") String id);
}

View File

@@ -0,0 +1,21 @@
package com.njcn.csharmonic.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csharmonic.api.fallback.CsHarmonicPlanLineFeignClientFallbackFactory;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_HARMONIC_BOOT, path = "/csHarmonicPlanLine", fallbackFactory = CsHarmonicPlanLineFeignClientFallbackFactory.class,contextId = "csHarmonicPlanLine")
public interface CsHarmonicPlanLineFeignClient {
@GetMapping("/getPlanIdByLineId")
@ApiOperation("根据监测点ID查询方案ID")
HttpResult<String> getPlanIdByLineId(@RequestParam("lineId") String lineId);
}

View File

@@ -1,11 +1,18 @@
package com.njcn.csharmonic.api;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csharmonic.api.fallback.EventUserFeignClientFallbackFactory;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -27,4 +34,24 @@ public interface EventUserFeignClient {
@PostMapping("/deleteByIds")
HttpResult<Boolean> deleteByIds(@RequestBody List<String> eventList);
@PostMapping("/queryTempEvent")
@ApiOperation("查询暂态事件(未读)")
HttpResult<List<String>> queryTempEvent(@RequestBody CsEventUserQueryParam param);
@PostMapping("/queryTempEventDetail")
@ApiOperation("查询暂态事件详细信息(未读)")
HttpResult<List<CsEventPO>> queryTempEventDetail(@RequestBody CsEventUserQueryParam param);
@PostMapping("/queryTempHarmonic")
@ApiOperation("查询稳态事件(未读)")
HttpResult<List<String>> queryTempHarmonic(@RequestBody CsEventUserQueryParam param);
@PostMapping("/queryAlarmEvent")
@ApiOperation("查询告警事件(未读)")
HttpResult<List<String>> queryAlarmEvent(@RequestBody CsEventUserQueryParam param);
@PostMapping("/queryRunEvent")
@ApiOperation("查询运行事件(未读)")
HttpResult<List<String>> queryRunEvent(@RequestBody CsEventUserQueryParam param);
}

View File

@@ -0,0 +1,39 @@
package com.njcn.csharmonic.api.fallback;
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.csharmonic.api.CsHarmonicFeignClient;
import com.njcn.csharmonic.api.CsHarmonicPlanFeignClient;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author xy
*/
@Slf4j
@Component
public class CsHarmonicPlanFeignClientFallbackFactory implements FallbackFactory<CsHarmonicPlanFeignClient> {
@Override
public CsHarmonicPlanFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new CsHarmonicPlanFeignClient() {
@Override
public HttpResult<CsHarmonicPlan> getById(String id) {
log.error("{}异常,降级处理,异常为:{}","根据ID查询稳态指标方案异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -0,0 +1,33 @@
package com.njcn.csharmonic.api.fallback;
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.csharmonic.api.CsHarmonicPlanLineFeignClient;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author xy
*/
@Slf4j
@Component
public class CsHarmonicPlanLineFeignClientFallbackFactory implements FallbackFactory<CsHarmonicPlanLineFeignClient> {
@Override
public CsHarmonicPlanLineFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new CsHarmonicPlanLineFeignClient() {
@Override
public HttpResult<String> getPlanIdByLineId(String lineId) {
log.error("{}异常,降级处理,异常为:{}","根据监测点ID查询方案ID异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -5,6 +5,7 @@ import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import feign.hystrix.FallbackFactory;
@@ -45,6 +46,36 @@ public class EventUserFeignClientFallbackFactory implements FallbackFactory<Even
log.error("{}异常,降级处理,异常为:{}","根据id删除数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<String>> queryTempEvent(CsEventUserQueryParam param) {
log.error("{}异常,降级处理,异常为:{}","查询暂态事件(未读)异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<CsEventPO>> queryTempEventDetail(CsEventUserQueryParam param) {
log.error("{}异常,降级处理,异常为:{}","查询暂态事件详细信息(未读)异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<String>> queryTempHarmonic(CsEventUserQueryParam param) {
log.error("{}异常,降级处理,异常为:{}","查询稳态事件(未读)异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<String>> queryAlarmEvent(CsEventUserQueryParam param) {
log.error("{}异常,降级处理,异常为:{}","查询告警事件(未读)异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
@Override
public HttpResult<List<String>> queryRunEvent(CsEventUserQueryParam param) {
log.error("{}异常,降级处理,异常为:{}","查询运行事件(未读)异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -1,7 +1,5 @@
package com.njcn.csharmonic.param;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@@ -37,6 +35,9 @@ public class CsEventUserQueryParam {
*/
private List<String> target;
/**
* '暂态事件'0 '稳态事件'1 '运行告警'3 '运行事件'2
*/
private String type;
/**
* 状态(0:未读取 1:已读取)

View File

@@ -0,0 +1,32 @@
package com.njcn.csharmonic.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
/**
* 稳态指标方案与测点关系参数类
*
* @author xy
* @since 2026-04-15
*/
@Data
public class CsHarmonicPlanLineParam {
/**
* 方案ID
*/
@ApiModelProperty(value = "方案ID")
@NotBlank(message = "方案ID不能为空")
private String id;
/**
* 监测点ID集合
*/
@ApiModelProperty(value = "监测点ID集合")
@NotEmpty(message = "监测点ID集合不能为空")
private List<String> lineIds;
}

View File

@@ -0,0 +1,65 @@
package com.njcn.csharmonic.param;
import com.njcn.web.pojo.param.BaseParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* 稳态指标方案参数类
*
* @author xy
* @since 2026-04-15
*/
@Data
public class CsHarmonicPlanParam {
/**
* 稳态方案名称
*/
@ApiModelProperty(value = "稳态方案名称")
@NotBlank(message = "稳态方案名称不能为空")
private String name;
/**
* 稳态指标集合
*/
@ApiModelProperty(value = "稳态指标集合")
private String harmonicTarget;
/**
* 排序
*/
@ApiModelProperty(value = "排序")
private Integer sort;
/**
* 监测点id集合
*/
@ApiModelProperty(value = "监测点id集合")
private List<String> lineList;
/**
* 修改参数类
*/
@Data
@EqualsAndHashCode(callSuper = true)
public static class UpdateCsHarmonicPlanParam extends CsHarmonicPlanParam {
@ApiModelProperty("ID")
@NotBlank(message = "ID不能为空")
private String id;
}
/**
* 分页查询参数类
*/
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty(value = "稳态方案名称")
private String name;
}
}

View File

@@ -0,0 +1,52 @@
package com.njcn.csharmonic.pojo.po;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Getter
@Setter
@TableName("cs_harmonic_plan")
public class CsHarmonicPlan extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 稳态方案名称
*/
private String name;
/**
* 稳态指标集合
*/
private String harmonicTarget;
/**
* 排序
*/
private Integer sort;
/**
* 监测点ID集合(非数据库字段)
*/
@TableField(exist = false)
private List<String> lineList;
}

View File

@@ -0,0 +1,35 @@
package com.njcn.csharmonic.pojo.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.njcn.db.bo.BaseEntity;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Getter
@Setter
@TableName("cs_harmonic_plan_line")
public class CsHarmonicPlanLine implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 监测点id
*/
private String lineId;
}

View File

@@ -24,6 +24,12 @@ public class AlarmVO implements Serializable {
@ApiModelProperty(value = "告警设备台数")
private Integer warnNums;
@ApiModelProperty(value = "通讯中断告警次数")
private Integer interruptCounts;
@ApiModelProperty(value = "终端告警次数")
private Integer warnCounts;
@ApiModelProperty(value = "告警设备id集合")
private List<String> devIds;
@@ -42,6 +48,9 @@ public class AlarmVO implements Serializable {
@ApiModelProperty(value = "设备名称")
private String devName;
@ApiModelProperty(value = "设备类型")
private String devType;
@ApiModelProperty(value = "告警次数")
private Integer warnCounts = 0;

View File

@@ -8,7 +8,6 @@ import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
/**
@@ -47,6 +46,8 @@ public class EventDetailVO {
*/
private String deviceId;
@ApiModelProperty(value = "设备类型")
private String devType;
@ApiModelProperty(value = "设备名称")
private String equipmentName;

View File

@@ -24,7 +24,10 @@ public class HarmonicVO implements Serializable {
@ApiModelProperty(value = "越限监测点数")
private Integer overLineNums = 0;
@ApiModelProperty(value = "越限监测点数")
@ApiModelProperty(value = "越限日期")
private List<String> overDaysList;
@ApiModelProperty(value = "越限监测点详情")
private List<LineHarmonicDetail> list = new ArrayList<>();
@Data
@@ -59,5 +62,31 @@ public class HarmonicVO implements Serializable {
}
@Data
public static class LineHarmonicOverDays implements Serializable {
@ApiModelProperty(value = "工程名称")
private String engineeringName;
@ApiModelProperty(value = "项目名称")
private String projectName;
@ApiModelProperty(value = "设备名称")
private String devName;
@ApiModelProperty(value = "监测点id")
private String lineId;
@ApiModelProperty(value = "监测点名称")
private String lineName;
@ApiModelProperty(value = "越限日期字符串")
private String timeString;
@ApiModelProperty(value = "越限日期集合")
private List<String> timeList;
}
}

View File

@@ -20,6 +20,10 @@
</properties>
<dependencies>
<dependency>
<groupId>com.github.tocrhz</groupId>
<artifactId>mqtt-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>common-web</artifactId>

View File

@@ -6,6 +6,7 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.EnableAsync;
/**
@@ -18,6 +19,7 @@ import org.springframework.context.annotation.DependsOn;
@EnableFeignClients(basePackages = "com.njcn")
@SpringBootApplication(scanBasePackages = "com.njcn")
@DependsOn("proxyMapperRegister")
@EnableAsync
public class CsHarmonicBootApplication {
public static void main(String[] args) {

View File

@@ -0,0 +1,42 @@
package com.njcn.csharmonic.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author xy
*/
@Configuration
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
@Bean("eventNotificationExecutor")
public Executor eventNotificationExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setThreadNamePrefix("event-notify-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Bean("smsNotificationExecutor")
public Executor smsNotificationExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("sms-notify-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}

View File

@@ -2,6 +2,7 @@ package com.njcn.csharmonic.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
@@ -42,9 +43,9 @@ public class CsAlarmController extends BaseController {
@PostMapping("/queryAlarmList")
@ApiOperation("运行告警事件列表(app)")
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<List<AlarmVO>> queryAlarmList(@RequestBody LineParamDTO param) {
public HttpResult<Page<AlarmVO>> queryAlarmList(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("queryAlarmList");
List<AlarmVO> result = csAlarmService.queryAlarmList(param);
Page<AlarmVO> result = csAlarmService.queryAlarmList(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}

View File

@@ -81,7 +81,7 @@ public class CsEventController extends BaseController {
@ApiImplicitParam(name = "eventId", value = "暂态事件索引", required = true)
public HttpResult<WaveDataDTO> analyseWave(String eventId) {
String methodDescribe = getMethodDescribe("analyseWave");
WaveDataDTO wave = csEventPOService.analyseWave(eventId,1);
WaveDataDTO wave = csEventPOService.analyseWave(eventId,2);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, wave, methodDescribe);
}
@@ -176,16 +176,6 @@ public class CsEventController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/eventStatistics")
@ApiOperation("暂态事件统计")
@ApiImplicitParam(name = "param", value = "事件信息", required = true)
public HttpResult<List<EventStatisticsVo>> getEventStatistics(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("getEventByTime");
List<EventStatisticsVo> list = csEventPOService.getEventStatistics(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getDevAlarmList")
@ApiOperation("获取设备运行告警事件")

View File

@@ -2,6 +2,7 @@ package com.njcn.csharmonic.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
@@ -42,17 +43,17 @@ public class CsHarmonicController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryHarmonicList")
@ApiOperation("稳态事件列表(app)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<HarmonicVO> queryHarmonicList(@RequestBody LineParamDTO param) {
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<Page<HarmonicVO.LineHarmonicDetail>> queryHarmonicList(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("queryHarmonicList");
HarmonicVO vo = csHarmonicService.queryAppList(param);
Page<HarmonicVO.LineHarmonicDetail> vo = csHarmonicService.queryAppList(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryHarmonicDetail")
@ApiOperation("稳态事件详情(app)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<List<HarmonicDetailVO>> queryHarmonicDetail(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("queryHarmonicDetail");
List<HarmonicDetailVO> vo = csHarmonicService.queryHarmonicDetail(param);
@@ -62,7 +63,7 @@ public class CsHarmonicController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/addList")
@ApiOperation("批量写入数据")
@ApiImplicitParam(name = "list", value = "暂降事件查询参数", required = true)
@ApiImplicitParam(name = "list", value = "事件查询参数", required = true)
public HttpResult<Boolean> addList(@RequestBody List<CsHarmonic> list) {
String methodDescribe = getMethodDescribe("addList");
boolean result = csHarmonicService.saveOrUpdateBatch(list);
@@ -93,5 +94,25 @@ public class CsHarmonicController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryAppHarmonicCounts")
@ApiOperation("查询App稳态事件总数")
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<HarmonicVO> queryAppHarmonicCounts(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("queryAppHarmonicCounts");
HarmonicVO vo = csHarmonicService.queryAppHarmonicCounts(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryAppHarmonicLine")
@ApiOperation("查询App稳态越限监测点")
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<Page<HarmonicVO.LineHarmonicOverDays>> queryAppHarmonicLine(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("queryAppHarmonicLine");
Page<HarmonicVO.LineHarmonicOverDays> result = csHarmonicService.queryAppHarmonicLine(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
}

View File

@@ -0,0 +1,115 @@
package com.njcn.csharmonic.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csharmonic.param.CsHarmonicPlanParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import com.njcn.csharmonic.service.ICsHarmonicPlanService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 稳态指标方案 前端控制器
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Slf4j
@RestController
@RequestMapping("/csHarmonicPlan")
@Api(tags = "稳态指标方案")
@AllArgsConstructor
public class CsHarmonicPlanController extends BaseController {
private final ICsHarmonicPlanService csHarmonicPlanService;
/**
* 新增稳态指标方案(包含监测点关联)
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@PostMapping("/save")
@ApiOperation("新增稳态指标方案")
public HttpResult<Boolean> save(@RequestBody @Validated CsHarmonicPlanParam param) {
String methodDescribe = getMethodDescribe("save");
csHarmonicPlanService.save(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
/**
* 修改稳态指标方案(包含监测点关联)
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
@PostMapping("/update")
@ApiOperation("修改稳态指标方案")
public HttpResult<Boolean> update(@RequestBody @Validated CsHarmonicPlanParam.UpdateCsHarmonicPlanParam param) {
String methodDescribe = getMethodDescribe("update");
csHarmonicPlanService.update(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
/**
* 删除稳态指标方案(同时删除监测点关联)
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
@PostMapping("/delete")
@ApiOperation("删除稳态指标方案")
@ApiImplicitParam(name = "ids", value = "ID集合")
public HttpResult<Boolean> delete(@RequestBody List<String> ids) {
String methodDescribe = getMethodDescribe("delete");
csHarmonicPlanService.deleteWithLines(ids);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
/**
* 根据ID查询稳态指标方案(包含监测点列表)
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getById")
@ApiOperation("根据ID查询稳态指标方案")
@ApiImplicitParam(name = "id", value = "ID", required = true)
public HttpResult<CsHarmonicPlan> getById(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("getById");
CsHarmonicPlan plan = csHarmonicPlanService.getByIdWithLines(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, plan, methodDescribe);
}
/**
* 分页查询稳态指标方案
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getPage")
@ApiOperation("分页查询稳态指标方案")
@ApiImplicitParam(name = "param", value = "查询参数", required = true)
public HttpResult<Page<CsHarmonicPlan>> getPage(@RequestBody CsHarmonicPlanParam.QueryParam param) {
String methodDescribe = getMethodDescribe("getPage");
Page<CsHarmonicPlan> page = csHarmonicPlanService.getPage(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe);
}
/**
* 查询所有稳态指标方案
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/list")
@ApiOperation("查询所有稳态指标方案")
public HttpResult<List<CsHarmonicPlan>> list() {
String methodDescribe = getMethodDescribe("list");
List<CsHarmonicPlan> list = csHarmonicPlanService.listAllOrderBySort();
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
}

View File

@@ -0,0 +1,91 @@
package com.njcn.csharmonic.controller;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
import com.njcn.csharmonic.service.ICsHarmonicPlanLineService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Slf4j
@RestController
@RequestMapping("/csHarmonicPlanLine")
@Api(tags = "稳态指标方案与测点关系")
@AllArgsConstructor
public class CsHarmonicPlanLineController extends BaseController {
private final ICsHarmonicPlanLineService csHarmonicPlanLineService;
/**
* 根据方案ID查询关联的监测点
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getByPlanId")
@ApiOperation("根据方案ID查询关联的监测点")
@ApiImplicitParam(name = "id", value = "方案ID", required = true)
public HttpResult<List<CsHarmonicPlanLine>> getByPlanId(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("getByPlanId");
List<CsHarmonicPlanLine> list = csHarmonicPlanLineService.getByPlanId(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
/**
* 新增方案与监测点关联
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
@PostMapping("/savePlanLines")
@ApiOperation("新增方案与监测点关联")
public HttpResult<Boolean> savePlanLines(@RequestBody @Validated CsHarmonicPlanLineParam param) {
String methodDescribe = getMethodDescribe("savePlanLines");
csHarmonicPlanLineService.savePlanLines(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
/**
* 根据监测点ID集合删除关联
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
@PostMapping("/deleteByLineIds")
@ApiOperation("根据监测点ID集合删除关联")
@ApiImplicitParam(name = "lineIds", value = "监测点ID集合")
public HttpResult<Boolean> deleteByLineIds(@RequestBody List<String> lineIds) {
String methodDescribe = getMethodDescribe("deleteByLineIds");
csHarmonicPlanLineService.deleteByLineIds(lineIds);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
}
/**
* 根据监测点ID查询方案ID
*/
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/getPlanIdByLineId")
@ApiOperation("根据监测点ID查询方案ID")
@ApiImplicitParam(name = "lineId", value = "监测点ID", required = true)
public HttpResult<String> getPlanIdByLineId(@RequestParam("lineId") String lineId) {
String methodDescribe = getMethodDescribe("getPlanIdByLineId");
String planId = csHarmonicPlanLineService.getPlanIdByLineId(lineId);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, planId, methodDescribe);
}
}

View File

@@ -7,12 +7,14 @@ import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csharmonic.mapper.CsEventUserPOMapper;
import com.njcn.csharmonic.param.CldWarnParam;
import com.njcn.csharmonic.param.CsEventUserQueryPage;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.event.EventStatisticVO;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
@@ -40,7 +42,10 @@ import java.util.List;
@Api(tags = "事件")
@AllArgsConstructor
public class EventUserController extends BaseController {
private final CsEventUserPOService csEventUserPOService;
private final CsEventUserPOMapper csEventUserPOMapper;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryEvent")
@ApiOperation("暂降事件未读消息")
@@ -120,4 +125,64 @@ public class EventUserController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryTempEvent")
@ApiOperation("查询暂态事件(未读)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<List<String>> queryTempEvent(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("queryTempEvent");
List<String> result = csEventUserPOMapper.queryTempEvent(param.getUserId(), param.getStartTime(), param.getEndTime(), param.getEventIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryTempEventDetail")
@ApiOperation("查询暂态事件详细信息(未读)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<List<CsEventPO>> queryTempEventDetail(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("queryTempEventDetail");
List<CsEventPO> result = csEventUserPOMapper.queryTempEventDetail(param.getUserId(), param.getStartTime(), param.getEndTime(), param.getEventIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryTempHarmonic")
@ApiOperation("查询稳态事件(未读)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<List<String>> queryTempHarmonic(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("queryTempEvent");
List<String> result = csEventUserPOMapper.queryTempHarmonic(param.getUserId(), param.getStartTime(), param.getEndTime(), param.getEventIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryAlarmEvent")
@ApiOperation("查询告警事件(未读)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<List<String>> queryAlarmEvent(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("queryAlarmEvent");
List<String> result = csEventUserPOMapper.queryAlarmEvent(param.getUserId(), param.getStartTime(), param.getEndTime(), param.getEventIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryRunEvent")
@ApiOperation("查询运行事件(未读)")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<List<String>> queryRunEvent(@RequestBody CsEventUserQueryParam param) {
String methodDescribe = getMethodDescribe("queryRunEvent");
List<String> result = csEventUserPOMapper.queryRunEvent(param.getUserId(), param.getStartTime(), param.getEndTime(), param.getEventIds());
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/queryAppEventCounts")
@ApiOperation("查询App暂态事件总数")
@ApiImplicitParam(name = "param", value = "暂降事件查询参数", required = true)
public HttpResult<EventStatisticVO> queryAppEventCounts(@RequestBody CsEventUserQueryPage param) {
String methodDescribe = getMethodDescribe("queryAppEventCounts");
EventStatisticVO result = csEventUserPOService.queryAppEventCounts(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}
}

View File

@@ -41,8 +41,8 @@ public class RealDataController extends BaseController {
@PostMapping("/getBaseRealData")
@ApiOperation("获取基础实时数据")
@ApiImplicitParam(name = "lineId", value = "监测点id")
public HttpResult<Boolean> getRealData(@RequestParam("lineId") String lineId) {
String methodDescribe = getMethodDescribe("getRealData");
public HttpResult<Boolean> getBaseRealData(@RequestParam("lineId") String lineId) {
String methodDescribe = getMethodDescribe("getBaseRealData");
boolean result = realDataService.getBaseRealData(lineId);
if (result) {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);

View File

@@ -3,18 +3,11 @@ package com.njcn.csharmonic.handler;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tocrhz.mqtt.annotation.MqttSubscribe;
import com.github.tocrhz.mqtt.annotation.NamedValue;
import com.github.tocrhz.mqtt.annotation.Payload;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.utils.ChannelObjectUtil;
import com.njcn.access.utils.FileCommonUtils;
import com.njcn.csdevice.api.DevCapacityFeignClient;
import com.njcn.csdevice.api.DeviceFtpFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.pojo.vo.CsEquipmentDeliveryVO;
import com.njcn.csharmonic.param.CommonStatisticalQueryParam;
import com.njcn.csharmonic.param.FrequencyStatisticalQueryParam;
import com.njcn.csharmonic.pojo.dto.RealTimeDataDTO;
@@ -26,8 +19,6 @@ import com.njcn.csharmonic.service.ILineTargetService;
import com.njcn.csharmonic.service.StableDataService;
import com.njcn.csharmonic.service.TemperatureService;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.oss.constant.OssPath;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.CsStatisticalSetFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
@@ -56,25 +47,15 @@ import java.util.stream.Stream;
public class MqttMessageHandler {
private final MqttPublisher publisher;
private final FileCommonUtils fileCommonUtils;
private final ILineTargetService lineTargetService;
private final CsStatisticalSetFeignClient csStatisticalSetFeignClient;
private final StableDataService stableDataService;
private final RedisUtil redisUtil;
private final TemperatureService temperatureService;
private final DevCapacityFeignClient devCapacityFeignClient;
private final DecimalFormat df = new DecimalFormat("#0.000");
private final ChannelObjectUtil channelObjectUtil;
private final EquipmentFeignClient equipmentFeignClient;
private final CsTopicFeignClient csTopicFeignClient;
private final DeviceFtpFeignClient deviceFtpFeignClient;
private static Integer mid = 1;
private final FileFeignClient fileFeignClient;
CsEventPOService csEventPOService;
private final CsEventPOService csEventPOService;
/**
* 实时数据应答

View File

@@ -5,8 +5,10 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.csharmonic.param.CsEventUserQueryPage;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.event.EventStatisticVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@@ -35,4 +37,21 @@ public interface CsEventUserPOMapper extends BaseMapper<CsEventUserPO> {
Page<EventDetailVO> queryEventPageWeb(Page<EventDetailVO> returnpage,@Param("csEventUserQueryPage") CsEventUserQueryPage csEventUserQueryPage,@Param("devIds") List<String> collect);
//查询暂态事件(未读)
List<String> queryTempEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询暂态事件详细信息(未读)
List<CsEventPO> queryTempEventDetail(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询稳态事件(未读)
List<String> queryTempHarmonic(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询告警事件(未读)
List<String> queryAlarmEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
//查询运行事件(未读)
List<String> queryRunEvent(@Param("userId") String userId, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
EventStatisticVO getEventCounts(@Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
}

View File

@@ -1,7 +1,12 @@
package com.njcn.csharmonic.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
import com.njcn.csharmonic.pojo.vo.HarmonicVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
@@ -13,4 +18,10 @@ import com.njcn.csharmonic.pojo.po.CsHarmonic;
*/
public interface CsHarmonicMapper extends BaseMapper<CsHarmonic> {
HarmonicVO getHarmonicCounts(@Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
List<String> getOverDays(@Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
Page<HarmonicVO.LineHarmonicOverDays> getLineHarmonicOverDays(Page<HarmonicVO.LineHarmonicOverDays> page, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("ids") List<String> ids);
}

View File

@@ -0,0 +1,16 @@
package com.njcn.csharmonic.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xy
* @since 2026-04-15
*/
public interface CsHarmonicPlanLineMapper extends BaseMapper<CsHarmonicPlanLine> {
}

View File

@@ -0,0 +1,16 @@
package com.njcn.csharmonic.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xy
* @since 2026-04-15
*/
public interface CsHarmonicPlanMapper extends BaseMapper<CsHarmonicPlan> {
}

View File

@@ -150,10 +150,35 @@
<!-- </select>-->
<select id="queryEventpage" resultType="com.njcn.csharmonic.pojo.vo.EventDetailVO">
select DISTINCT b.id,b.device_id deviceId,b.line_id lineId,b.code code,b.start_time startTime,b.amplitude,b.persist_time,
round(b.amplitude,2) evtParamVVaDepth,round(b.persist_time,2) evtParamTm,b.phase evtParamPhase,b.location evtParamPosition,
b.tag tag ,b.wave_path wavePath,b.instant_pics,b.rms_pics , b.type type,b.level level,b.location location,d.name lineName
from cs_event b inner join cs_equipment_delivery c on b.device_id=c.id inner join cs_line d on d.device_id=b.device_id and d.clDid=b.cl_did where 1=1
SELECT DISTINCT b.id,
b.device_id deviceId,
b.line_id lineId,
b.CODE CODE,
b.start_time startTime,
b.amplitude,
b.persist_time,
round(b.amplitude, 2) evtParamVVaDepth,
round(b.persist_time, 2) evtParamTm,
b.phase evtParamPhase,
b.location evtParamPosition,
b.tag tag,
b.wave_path wavePath,
b.instant_pics,
b.rms_pics,
b.type type,
b.LEVEL LEVEL,
b.location location,
c.dev_type devType
<if test="csEventUserQueryPage != null and csEventUserQueryPage.type != null and csEventUserQueryPage.type != '' and csEventUserQueryPage.type ==0">
,d.NAME lineName
</if>
from
cs_event b
inner join cs_equipment_delivery c on b.device_id=c.id
<if test="csEventUserQueryPage != null and csEventUserQueryPage.type != null and csEventUserQueryPage.type != '' and csEventUserQueryPage.type ==0">
inner join cs_line d on d.device_id=b.device_id
</if>
where 1=1
and b.process=c.process
<if test="csEventUserQueryPage!=null and csEventUserQueryPage.endTime != null and csEventUserQueryPage.endTime !=''">
AND DATE(b.start_time) &lt;= DATE(#{csEventUserQueryPage.endTime})
@@ -174,8 +199,11 @@
<if test="csEventUserQueryPage!=null and csEventUserQueryPage.lineId != null and csEventUserQueryPage.lineId !=''">
AND b.line_id = #{csEventUserQueryPage.lineId}
</if>
<if test="csEventUserQueryPage!=null and csEventUserQueryPage.type != null and csEventUserQueryPage.type !=''">
AND b.type =#{ csEventUserQueryPage.type}
<if test="csEventUserQueryPage != null and csEventUserQueryPage.type != null and csEventUserQueryPage.type != ''">
AND b.type = #{csEventUserQueryPage.type}
<if test="csEventUserQueryPage.type == '0'">
AND d.clDid = b.cl_did
</if>
</if>
<if test="csEventUserQueryPage!=null and csEventUserQueryPage.level != null and csEventUserQueryPage.level !=''">
AND b.level IN
@@ -183,22 +211,27 @@
#{level}
</foreach>
</if>
<if test="csEventUserQueryPage!=null and csEventUserQueryPage.sortField != null">
<choose>
<when test="csEventUserQueryPage.sortField == 0">
order by b.start_time desc
</when>
<when test="csEventUserQueryPage.sortField == 1">
order by b.amplitude desc
</when>
<when test="csEventUserQueryPage.sortField == 2">
order by b.persist_time desc
</when>
<otherwise>
order by b.start_time desc
</otherwise>
</choose>
</if>
<choose>
<when test="csEventUserQueryPage!=null and csEventUserQueryPage.sortField != null">
<choose>
<when test="csEventUserQueryPage.sortField == 0">
order by b.start_time desc
</when>
<when test="csEventUserQueryPage.sortField == 1">
order by b.amplitude desc
</when>
<when test="csEventUserQueryPage.sortField == 2">
order by b.persist_time desc
</when>
<otherwise>
order by b.start_time desc
</otherwise>
</choose>
</when>
<otherwise>
order by b.start_time desc
</otherwise>
</choose>
</select>
@@ -250,4 +283,107 @@
</if>
order by b.start_time desc
</select>
<select id="queryTempEvent" resultType="java.lang.String">
SELECT
t1.event_id
FROM
cs_event_user t1 right join cs_event t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
and t2.type = 0
<if test="ids != null and ids.size > 0">
and t2.line_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
<select id="queryTempEventDetail" resultType="com.njcn.csharmonic.pojo.po.CsEventPO">
SELECT
t2.*
FROM
cs_event_user t1 right join cs_event t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
and t2.type = 0
<if test="ids != null and ids.size > 0">
and t2.line_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
and t2.start_time between #{startTime} and #{endTime}
</select>
<select id="queryAlarmEvent" resultType="java.lang.String">
SELECT
t1.event_id
FROM
cs_event_user t1 right join cs_alarm t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
<if test="ids != null and ids.size > 0">
and (
<foreach collection="ids" item="tag" separator=" OR ">
FIND_IN_SET(#{tag}, t2.dev_list) > 0
</foreach>
)
</if>
</select>
<select id="queryRunEvent" resultType="java.lang.String">
SELECT
t1.event_id
FROM
cs_event_user t1 right join cs_event t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
and t2.type = 2
<if test="ids != null and ids.size > 0">
and t2.device_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
<select id="queryTempHarmonic" resultType="java.lang.String">
SELECT
t1.event_id
FROM
cs_event_user t1 right join cs_harmonic t2 on t1.event_id = t2.id
WHERE
t1.user_id = #{userId}
and t1.`status`= 0
<if test="ids != null and ids.size > 0">
and t2.line_id in
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</if>
</select>
<select id="getEventCounts" resultType="com.njcn.csharmonic.pojo.vo.event.EventStatisticVO">
SELECT
SUM(CASE WHEN tag = 'Evt_Sys_DipStr' THEN 1 ELSE 0 END) AS eventDown,
SUM(CASE WHEN tag = 'Evt_Sys_IntrStr' THEN 1 ELSE 0 END) AS eventOff,
SUM(CASE WHEN tag = 'Evt_Sys_SwlStr' THEN 1 ELSE 0 END) AS eventUp,
COUNT(*) AS allNum
FROM
cs_event
WHERE
type = 0
AND start_time BETWEEN #{startTime} AND #{endTime}
AND device_id IN
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
</mapper>

View File

@@ -0,0 +1,47 @@
<?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.csharmonic.mapper.CsHarmonicMapper">
<select id="getHarmonicCounts" resultType="com.njcn.csharmonic.pojo.vo.HarmonicVO">
SELECT
COUNT(1) AS harmonicNums,
COUNT(DISTINCT TIME) AS overDays,
COUNT(DISTINCT line_id) AS overLineNums
FROM
cs_harmonic
WHERE
TIME BETWEEN #{startTime} AND #{endTime}
AND line_id IN
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
<select id="getOverDays" resultType="java.lang.String">
SELECT
DISTINCT time
FROM
cs_harmonic
WHERE
TIME BETWEEN #{startTime} AND #{endTime}
AND line_id IN
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
order by time asc
</select>
<select id="getLineHarmonicOverDays" resultType="com.njcn.csharmonic.pojo.vo.HarmonicVO$LineHarmonicOverDays">
SELECT
line_id lineId,
GROUP_CONCAT(DISTINCT time ORDER BY time SEPARATOR ', ') AS timeString
FROM cs_harmonic
WHERE TIME BETWEEN #{startTime} AND #{endTime}
AND line_id IN
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
GROUP BY line_id
</select>
</mapper>

View File

@@ -0,0 +1,5 @@
<?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.csharmonic.mapper.CsHarmonicPlanLineMapper">
</mapper>

View File

@@ -0,0 +1,5 @@
<?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.csharmonic.mapper.CsHarmonicPlanMapper">
</mapper>

View File

@@ -0,0 +1,113 @@
package com.njcn.csharmonic.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author xy
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class AppNotificationService {
private final EpdFeignClient epdFeignClient;
private final SendMessageUtil sendMessageUtil;
private final DeviceMessageFeignClient deviceMessageClient;
private final CsEventUserPOService csEventUserPOService;
@Async("eventNotificationExecutor")
public void asyncSaveEventUserAndNotify(String eventId
, List<String> eventUser
, DevDetailDTO devDetailDto
, LocalDateTime time
, Integer eventType
, Double amplitude
, Double persistTime) {
NoticeUserDto noticeUserDto = new NoticeUserDto();
NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
List<CsEventUserPO> result = new ArrayList<>();
eventUser.forEach(item -> {
CsEventUserPO csEventUser = new CsEventUserPO();
csEventUser.setUserId(item);
csEventUser.setStatus(0);
csEventUser.setEventId(eventId);
result.add(csEventUser);
});
DeviceMessageParam param = new DeviceMessageParam();
param.setUserList(eventUser);
param.setEventType(0);
List<User> users = deviceMessageClient.getSendUserByType(param).getData();
if (CollectionUtil.isNotEmpty(users)) {
List<String> devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
noticeUserDto.setPushClientId(devCodeList);
noticeUserDto.setTitle("暂态事件");
}
String eventName = epdFeignClient.findByName(getTag(eventType)).getData().getShowName();
String content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
+ "" + time.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂态事件,事件类型:"
+ eventName
+ ",特征幅值:" + amplitude + "%"
+ ",持续时间:" + persistTime + "s";
noticeUserDto.setContent(content);
payload.setType(0);
payload.setPath("/pages/index/message1?type=" + payload.getType());
noticeUserDto.setPayload(payload);
if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
List<String> filteredList = noticeUserDto.getPushClientId().stream()
.filter(s -> s != null && !s.isEmpty())
.distinct()
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(filteredList)) {
noticeUserDto.setPushClientId(filteredList);
sendMessageUtil.sendEventToUser(noticeUserDto);
}
}
if (CollectionUtil.isNotEmpty(result)) {
csEventUserPOService.saveBatch(result);
}
}
public String getTag(Integer type) {
String tag;
switch (type) {
case 1:
tag = "Evt_Sys_DipStr";
break;
case 2:
tag = "Evt_Sys_SwlStr";
break;
case 3:
tag = "Evt_Sys_IntrStr";
break;
case 4:
tag = "Transient";
break;
default:
tag = "Un_Know";
break;
}
return tag;
}
}

View File

@@ -70,8 +70,6 @@ public interface CsEventPOService extends IService<CsEventPO>{
List<CsEventPO> getEventByTime(List<String> lineList, String startTime, String endTime);
List<EventStatisticsVo> getEventStatistics(CsEventUserQueryParam param);
List<CsWarnDescVO> getEventDesc(List<String> lineIdList);
//获取设备告警事件详情

View File

@@ -9,6 +9,7 @@ import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.event.EventStatisticVO;
import com.njcn.web.pojo.param.BaseParam;
import java.util.List;
@@ -46,5 +47,6 @@ public interface CsEventUserPOService extends IService<CsEventUserPO>{
*/
List<CsEventUserPO> queryEventListByUserId(String userIndex,List<String> eventList);
EventStatisticVO queryAppEventCounts(CsEventUserQueryPage csEventUserQueryPage);
}

View File

@@ -1,5 +1,6 @@
package com.njcn.csharmonic.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csharmonic.pojo.po.CsAlarm;
@@ -17,7 +18,7 @@ import java.util.List;
*/
public interface ICsAlarmService extends IService<CsAlarm> {
List<AlarmVO> queryAlarmList(LineParamDTO param);
Page<AlarmVO> queryAlarmList(LineParamDTO param);
List<AlarmVO.AlarmDetail> queryAlarmDetail(LineParamDTO.DevParamDTO param);

View File

@@ -0,0 +1,48 @@
package com.njcn.csharmonic.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xy
* @since 2026-04-15
*/
public interface ICsHarmonicPlanLineService extends IService<CsHarmonicPlanLine> {
/**
* 根据方案ID查询关联的监测点
*
* @param id 方案ID
* @return 关联列表
*/
List<CsHarmonicPlanLine> getByPlanId(String id);
/**
* 新增方案与监测点关联
*
* @param param 参数
*/
void savePlanLines(CsHarmonicPlanLineParam param);
/**
* 根据监测点ID集合删除关联
*
* @param lineIds 监测点ID集合
*/
void deleteByLineIds(List<String> lineIds);
/**
* 根据监测点ID查询方案ID
*
* @param lineId 监测点ID
* @return 方案ID
*/
String getPlanIdByLineId(String lineId);
}

View File

@@ -0,0 +1,63 @@
package com.njcn.csharmonic.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csharmonic.param.CsHarmonicPlanParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xy
* @since 2026-04-15
*/
public interface ICsHarmonicPlanService extends IService<CsHarmonicPlan> {
/**
* 新增稳态指标方案(包含监测点关联)
*
* @param param 稳态指标方案参数
*/
void save(CsHarmonicPlanParam param);
/**
* 修改稳态指标方案(包含监测点关联)
*
* @param param 稳态指标方案参数
*/
void update(CsHarmonicPlanParam.UpdateCsHarmonicPlanParam param);
/**
* 删除稳态指标方案(同时删除监测点关联)
*
* @param ids 方案ID集合
*/
void deleteWithLines(List<String> ids);
/**
* 分页查询稳态指标方案
*
* @param param 查询参数
* @return 分页结果
*/
Page<CsHarmonicPlan> getPage(CsHarmonicPlanParam.QueryParam param);
/**
* 查询所有稳态指标方案(按sort降序)
*
* @return 稳态指标方案列表
*/
List<CsHarmonicPlan> listAllOrderBySort();
/**
* 根据方案ID查询详情(包含监测点列表)
*
* @param id 方案ID
* @return 方案详情
*/
CsHarmonicPlan getByIdWithLines(String id);
}

View File

@@ -1,5 +1,6 @@
package com.njcn.csharmonic.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
@@ -18,8 +19,12 @@ import java.util.List;
*/
public interface ICsHarmonicService extends IService<CsHarmonic> {
HarmonicVO queryAppList(LineParamDTO param);
Page<HarmonicVO.LineHarmonicDetail> queryAppList(LineParamDTO param);
List<HarmonicDetailVO> queryHarmonicDetail(LineParamDTO param);
HarmonicVO queryAppHarmonicCounts(LineParamDTO param);
Page<HarmonicVO.LineHarmonicOverDays> queryAppHarmonicLine(LineParamDTO param);
}

View File

@@ -0,0 +1,60 @@
package com.njcn.csharmonic.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.njcn.csdevice.api.SmsSendFeignClient;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.cssystem.api.AppMsgSetFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author xy
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsNotificationService {
private final AppMsgSetFeignClient appMsgSetFeignClient;
private final UserFeignClient userFeignClient;
private final SmsSendFeignClient smsSendFeignClient;
@Value("${msg.msg_sign:南京灿能电力}")
private String msgSign;
@Async("smsNotificationExecutor")
public void asyncSendSmsNotification(String deviceId
, DevDetailDTO devDetailDto
, LocalDateTime eventTime
, Double amplitude
, Double persistTime) {
List<String> userIdList = appMsgSetFeignClient.queryUserIdsByDeviceId(deviceId).getData();
if (CollectionUtil.isNotEmpty(userIdList)) {
List<User> userList = userFeignClient.getUserListByIds(userIdList).getData();
if (CollectionUtil.isNotEmpty(userList)) {
List<User> userList1 = userList.stream()
.filter(item -> StrUtil.isNotBlank(item.getPhone()) && Objects.equals(item.getSmsNotice(), 1))
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(userList1)) {
String msgContent = "" + msgSign + "" + devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
+ "" + eventTime.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂降事件"
+ ",特征幅值:" + amplitude + "%"
+ ",持续时间:" + persistTime + "s";
userList1.forEach(item -> {
smsSendFeignClient.sendSmsSimple(item.getPhone(), msgContent, "verify_code");
});
}
}
}
}
}

View File

@@ -1,15 +1,19 @@
package com.njcn.csharmonic.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
@@ -21,8 +25,10 @@ import com.njcn.csharmonic.pojo.vo.AlarmVO;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.service.ICsAlarmService;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@@ -51,11 +57,13 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
private final CsCommTerminalFeignClient csCommTerminalFeignClient;
private final CsEventPOService csEventPOService;
private final EpdFeignClient epdFeignClient;
private final EquipmentFeignClient equipmentFeignClient;
private final DictTreeFeignClient dictTreeFeignClient;
@Override
public List<AlarmVO> queryAlarmList(LineParamDTO param) {
List<AlarmVO> result = new ArrayList<>();
public Page<AlarmVO> queryAlarmList(LineParamDTO param) {
Page<AlarmVO> page1 = new Page<>();
Page<CsAlarm> page2 = new Page<> (param.getPageNum(), param.getPageSize());
List<CsLedger> lineLedger = csLedgerFeignClient.queryLine(param).getData();
if (CollectionUtil.isNotEmpty(lineLedger)) {
List<CsLedger> devLedger = new ArrayList<>();
@@ -69,7 +77,6 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
});
});
if (CollectionUtil.isNotEmpty(devLedger)) {
List<String> ownerDevList = csCommTerminalFeignClient.getDevIdsByUser(RequestUtil.getUserIndex()).getData();
List<String> devList = devLedger.stream().map(CsLedger::getPid).distinct().collect(Collectors.toList());
@@ -87,14 +94,15 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
queryWrapper.ge(StrUtil.isNotBlank(param.getTime()), CsAlarm::getTime, calculateMonthStart(param.getTime()))
.le(StrUtil.isNotBlank(param.getTime()), CsAlarm::getTime, calculateMonthEnd(param.getTime()))
.orderByDesc(CsAlarm::getTime);
//先获取设备通讯数据
List<CsAlarm> list = list(queryWrapper);
Page<CsAlarm> csAlarmPage = this.baseMapper.selectPage(page2,queryWrapper);
BeanUtil.copyProperties(csAlarmPage, page1);
List<CsAlarm> list = csAlarmPage.getRecords();
if (CollectionUtil.isNotEmpty(list)) {
//获取用户推送事件
List<CsEventUserPO> userEvents = csEventUserPOService.queryEventListByUserId(RequestUtil.getUserIndex(), list.stream().map(CsAlarm::getId).collect(Collectors.toList()));
List<String> finalDevList = devList;
result = list.stream()
List<AlarmVO> result = list.stream()
.map(alarm -> {
AlarmVO alarmVO = new AlarmVO();
alarmVO.setEventId(alarm.getId());
@@ -109,15 +117,68 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
alarmVO.setWarnNums(matchedDevIds.size());
alarmVO.setDevIds(matchedDevIds);
alarmVO.setIsRead(userEvents.stream().filter(item1->item1.getEventId().equals(alarm.getId())).findFirst().map(CsEventUserPO::getStatus).orElse(1));
int interruptCounts = 0;
int warnCounts = 0;
ObjectMapper objectMapper = new ObjectMapper();
List<List<String>> resultList;
List<List<String>> resultList2;
try {
resultList = objectMapper.readValue(alarm.getInterruptEvent(), new TypeReference<List<List<String>>>() {});
resultList2 = objectMapper.readValue(alarm.getAlarmEvent(), new TypeReference<List<List<String>>>() {});
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
for (String matchedDevId : matchedDevIds) {
for (int j = 0; j < devIds.length; j++) {
if (Objects.equals(matchedDevId, devIds[j])) {
interruptCounts = interruptCounts + (Objects.isNull(resultList.get(j)) ? 0 : resultList.get(j).get(0).split("").length);
warnCounts = warnCounts + (Objects.isNull(resultList2.get(j)) ? 0 : resultList2.get(j).size());
}
}
}
alarmVO.setInterruptCounts(interruptCounts);
alarmVO.setWarnCounts(warnCounts);
return alarmVO;
})
.filter(alarmVO -> alarmVO.getWarnNums() > 0)
.sorted((a1, a2) -> a2.getDate().compareTo(a1.getDate()))
.collect(Collectors.toList());
page1.setRecords(result);
}
// if (CollectionUtil.isNotEmpty(list)) {
// //获取用户推送事件
// List<CsEventUserPO> userEvents = csEventUserPOService.queryEventListByUserId(RequestUtil.getUserIndex(), list.stream().map(CsAlarm::getId).collect(Collectors.toList()));
//
// List<String> finalDevList = devList;
// List<AlarmVO> result = list.stream()
// .map(alarm -> {
// AlarmVO alarmVO = new AlarmVO();
// alarmVO.setEventId(alarm.getId());
// alarmVO.setDate(alarm.getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//
// String devListStr = alarm.getDevList();
// String[] devIds = devListStr.split(",");
// List<String> matchedDevIds = Arrays.stream(devIds)
// .filter(devId -> StrUtil.isNotBlank(devId.trim()))
// .filter(finalDevList::contains)
// .collect(Collectors.toList());
// alarmVO.setWarnNums(matchedDevIds.size());
// alarmVO.setDevIds(matchedDevIds);
// alarmVO.setIsRead(userEvents.stream().filter(item1->item1.getEventId().equals(alarm.getId())).findFirst().map(CsEventUserPO::getStatus).orElse(1));
// return alarmVO;
// })
// .filter(alarmVO -> alarmVO.getWarnNums() > 0)
// .sorted((a1, a2) -> a2.getDate().compareTo(a1.getDate()))
// .collect(Collectors.toList());
// page1.setRecords(result);
// }
}
}
return result;
return page1;
}
@Override
@@ -144,6 +205,10 @@ public class CsAlarmServiceImpl extends ServiceImpl<CsAlarmMapper, CsAlarm> impl
alarmDetail.setEngineeringName(ledgerMap.get(csLedgerVO.getPids().split(",")[1]).getName());
alarmDetail.setProjectName(ledgerMap.get(csLedgerVO.getPids().split(",")[2]).getName());
alarmDetail.setDevName(csLedgerVO.getName());
//添加设备类型
CsEquipmentDeliveryDTO dto = equipmentFeignClient.queryDeviceById(Collections.singletonList(csLedgerVO.getId())).getData().get(0);
SysDicTreePO po = dictTreeFeignClient.queryById(dto.getDevType()).getData();
alarmDetail.setDevType(Objects.isNull(po)?null:po.getCode());
if (ObjectUtil.isNotNull(alarm.getInterruptEvent())) {
String interruptEvent = alarm.getInterruptEvent();

View File

@@ -13,12 +13,10 @@ import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsLinePO;
@@ -32,13 +30,13 @@ import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.pojo.param.EventStatisticParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.CsEventVO;
import com.njcn.csharmonic.pojo.vo.CsWarnDescVO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.EventStatisticsVo;
import com.njcn.csharmonic.service.AppNotificationService;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.service.SmsNotificationService;
import com.njcn.event.common.mapper.WlRmpEventDetailMapper;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.component.WavePicComponent;
@@ -62,21 +60,18 @@ import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.user.api.AppInfoSetFeignClient;
import com.njcn.user.api.AppUserFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.po.app.AppInfoSet;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -124,14 +119,15 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
private final MinIoUtils minIoUtils;
private final DicDataFeignClient dicDataFeignClient;
private final WlRmpEventDetailMapper wlRmpEventDetailMapper;
private final AppUserFeignClient appUserFeignClient;
private final CsDeviceUserFeignClient csDeviceUserFeignClient;
private final UserFeignClient userFeignClient;
private final AppInfoSetFeignClient appInfoSetFeignClient;
private final CsLedgerFeignClient csLedgerFeignclient;
private final SendMessageUtil sendMessageUtil;
private final DeviceMessageFeignClient deviceMessageClient;
private final AppNotificationService appNotificationService;
private final SmsNotificationService smsNotificationService;
@Value("${msg.msg_sign:南京灿能电力}")
private String msgSign;
@Override
public List<EventDetailVO> queryEventList(CsEventUserQueryParam csEventUserQueryParam) {
@@ -159,12 +155,6 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
} else {
eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("3.1415926"));
}
//优化,删除监测点位置
// if (Objects.equals(temp.getEvtParamPosition(),"-") || Objects.isNull(temp.getEvtParamPosition())) {
// if (!Objects.isNull(temp.getLocation())) {
// temp.setEvtParamPosition(Objects.equals(temp.getLocation(),"grid")?"电网侧":"负载侧");
// }
// }
eventDataSetDTOS.add(eventDataSetDTO);
}
temp.setDataSet(eventDataSetDTOS);
@@ -422,48 +412,29 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
//同步数据到 r_mp_event_detail
insertEvent(uuid, param, time);
//根据设备获取主用户、子用户,设置事件未读数据
NoticeUserDto noticeUserDto = new NoticeUserDto();
NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
List<CsEventUserPO> result = new ArrayList<>();
List<String> eventUser = getEventUser(po.getDeviceId(),true);
//针对用户记录未读信息和推送告警
eventUser.forEach(item->{
CsEventUserPO csEventUser = new CsEventUserPO();
csEventUser.setUserId(item);
csEventUser.setStatus(0);
csEventUser.setEventId(uuid);
result.add(csEventUser);
});
List<User> users = getSendUser(eventUser,0);
if (CollectionUtil.isNotEmpty(users)){
List<String> devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
noticeUserDto.setPushClientId(devCodeList);
noticeUserDto.setTitle("暂态事件");
}
//根据设备获取主用户、子用户
List<String> eventUser = deviceMessageClient.getEventUserByDeviceId(po.getDeviceId(),true).getData();
//获取台账信息
String eventName = epdFeignClient.findByName(getTag(param.getEventType())).getData().getShowName();
DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(po.getDeviceId()).getData();
String content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName() + "" + time.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生" + eventName;
noticeUserDto.setContent(content);
payload.setType(0);
payload.setPath("/pages/index/message1?type="+payload.getType());
noticeUserDto.setPayload(payload);
LocalDateTime eventTime = LocalDateTime.parse(param.getStartTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MS_PATTERN));
if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
List<String> filteredList = noticeUserDto.getPushClientId().stream()
.filter(s -> s != null && !s.isEmpty())
.distinct()
.collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(filteredList)) {
noticeUserDto.setPushClientId(filteredList);
sendMessageUtil.sendEventToUser(noticeUserDto);
}
Double amplitudePercent = BigDecimal.valueOf(param.getAmplitude() * 100).setScale(2, RoundingMode.HALF_UP).doubleValue();
Double durationSeconds = BigDecimal.valueOf(param.getDuration()).setScale(2, RoundingMode.HALF_UP).doubleValue();
//异步处理事件用户关系和App消息推送
try {
appNotificationService.asyncSaveEventUserAndNotify(uuid, eventUser, devDetailDto, time, param.getEventType(), amplitudePercent, durationSeconds);
} catch (Exception e) {
log.error("异步保存事件用户和通知失败事件ID: {}", uuid, e);
}
//事件用户关系入库
if (CollectionUtil.isNotEmpty(result)){
csEventUserPOService.saveBatch(result);
//如果是暂降事件,异步发送短信通知
if (param.getEventType() == 1) {
try {
smsNotificationService.asyncSendSmsNotification(po.getDeviceId(), devDetailDto, eventTime, amplitudePercent, durationSeconds);
} catch (Exception e) {
log.error("异步发送短信通知失败事件ID: {}", uuid, e);
}
}
} else {
if (StrUtil.isNotBlank(param.getWavePath())) {
@@ -498,54 +469,6 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
return result;
}
public List<String> getEventUser(String devId,boolean isAdmin) {
List<User> adminUser = appUserFeignClient.getAdminInfo().getData();
List<String> adminList = adminUser.stream().map(User::getId).collect(Collectors.toList());
if (isAdmin) {
List<String> list = csDeviceUserFeignClient.findUserById(devId).getData();
adminList.addAll(list);
}
return adminList;
}
/**
* 获取所有打开推送的用户信息
*/
public List<User> getSendUser(List<String> userList,Integer type) {
List<User> users = new ArrayList<>();
List<String> result = new ArrayList<>();
List<AppInfoSet> appInfoSet = appInfoSetFeignClient.getListById(userList).getData();
switch (type) {
case 0:
result = appInfoSet.stream()
.filter(person -> person.getEventInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 1:
result = appInfoSet.stream()
.filter(person -> person.getHarmonicInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 2:
result = appInfoSet.stream()
.filter(person -> person.getRunInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
case 3:
result = appInfoSet.stream()
.filter(person -> person.getAlarmInfo() == 1)
.map(AppInfoSet::getUserId).collect(Collectors.toList());
break;
default:
break;
}
if (CollectionUtil.isNotEmpty(result)){
users = userFeignClient.appuserByIdList(result).getData();
}
return users;
}
public void insertEvent(String uuid, CldEventParam param, LocalDateTime time) {
RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO();
rmpEventDetailPO.setEventId(uuid);
@@ -567,13 +490,6 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
RmpEventDetailPO po = wlRmpEventDetailMapper.selectOne(wrapper);
po.setWavePath(param.getWavePath());
po.setFileFlag(1);
//根据事件获取暂态类型、暂态原因、暂态发生位置
//String ip = equipmentFeignClient.getDevByLineId(param.getMonitorId()).getData().getMac();
//EntityAdvancedData advancedData = commonEventWaveAnalysisService.analysis(po,ip);
//po.setAdvanceReason(advancedData.getSagReason()[0]);
//po.setAdvanceType(advancedData.getSagType()[0]);
wlRmpEventDetailMapper.updateById(po);
}
@@ -590,15 +506,6 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
return this.list(lambdaQueryWrapper);
}
@Override
public List<EventStatisticsVo> getEventStatistics(CsEventUserQueryParam param) {
return Collections.emptyList();
}
@Override
public List<CsWarnDescVO> getEventDesc(List<String> lineIdList) {
List<CsWarnDescVO> csWarnDescVOList = new ArrayList<>();
@@ -750,11 +657,23 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
WaveDataDTO waveDataDTO = this.analyseWave(eventId, iType);
//数据筛选,如果是双路电压的话会存在2个波形数据
List<WaveDataDetail> waveDataDetails = WaveUtil.filterWaveData(waveDataDTO);
String instantPath = wavePicComponent.generateInstantImageZl(waveDataDetails);
eventDetail.setInstantPics(instantPath);
if (StrUtil.isBlank(eventDetail.getRmsPics())) {
String rmsPath = wavePicComponent.generateRmsImageZl(waveDataDetails);
eventDetail.setRmsPics(rmsPath);
//单通道处理
if (ObjectUtils.isNotEmpty(waveDataDetails) && waveDataDetails.size() == 2) {
String instantPath = wavePicComponent.generateImageShun(waveDataDTO,waveDataDetails);
eventDetail.setInstantPics(instantPath);
if (StrUtil.isBlank(eventDetail.getRmsPics())) {
String rmsPath = wavePicComponent.generateImageRms(waveDataDTO,waveDataDetails);
eventDetail.setRmsPics(rmsPath);
}
}
//双通道处理
else if (ObjectUtils.isNotEmpty(waveDataDetails) && waveDataDetails.size() == 4) {
String instantPath = wavePicComponent.generateInstantImageZl(waveDataDetails);
eventDetail.setInstantPics(instantPath);
if (StrUtil.isBlank(eventDetail.getRmsPics())) {
String rmsPath = wavePicComponent.generateRmsImageZl(waveDataDetails);
eventDetail.setRmsPics(rmsPath);
}
}
this.updateById(eventDetail);
}

View File

@@ -10,6 +10,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
import com.njcn.csdevice.api.CsDeviceUserFeignClient;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.NodeFeignClient;
import com.njcn.csdevice.constant.DataParam;
@@ -25,14 +27,17 @@ import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.event.EventStatisticVO;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.influx.pojo.dto.EventDataSetDTO;
import com.njcn.influx.service.EvtDataService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.user.enums.AppRoleEnum;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
@@ -58,12 +63,15 @@ import java.util.stream.Collectors;
public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, CsEventUserPO> implements CsEventUserPOService{
private final DicDataFeignClient dicDataFeignClient;
private final DictTreeFeignClient dictTreeFeignClient;
private final CsLedgerFeignClient csLedgerFeignClient;
private final EvtDataService evtDataService;
private final EpdFeignClient epdFeignClient;
private final EleEvtFeignClient eleEvtFeignClient;
private final CsEventPOMapper csEventPOMapper;
private final NodeFeignClient nodeFeignClient;
private final CsDeviceUserFeignClient csDeviceUserFeignClient;
private final CsCommTerminalFeignClient csCommTerminalFeignClient;
@Override
public Integer queryEventCount(CsEventUserQueryParam csEventUserQueryParam) {
@@ -207,21 +215,39 @@ public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, C
csEventUserQueryParam.setUserId(RequestUtil.getUserIndex());
//getEventIds传空一键已读
if(CollectionUtil.isEmpty(csEventUserQueryParam.getEventIds())){
List<EventDetailVO> list = this.queryUserEventList(csEventUserQueryParam);
if(!CollectionUtils.isEmpty(list)){
List<String> collect = list.stream().map(EventDetailVO::getId).collect(Collectors.toList());
this.lambdaUpdate().in(CsEventUserPO::getEventId,collect).
eq(CsEventUserPO::getUserId,csEventUserQueryParam.getUserId()).
set(CsEventUserPO::getStatus,1).update();
//暂态数据和运行事件和之前一样逻辑
if (Objects.equals(csEventUserQueryParam.getType(), "0") || Objects.equals(csEventUserQueryParam.getType(), "2")) {
List<EventDetailVO> list = this.queryUserEventList(csEventUserQueryParam);
if(!CollectionUtils.isEmpty(list)){
List<String> collect = list.stream().map(EventDetailVO::getId).collect(Collectors.toList());
this.lambdaUpdate().in(CsEventUserPO::getEventId,collect).
eq(CsEventUserPO::getUserId,csEventUserQueryParam.getUserId()).
set(CsEventUserPO::getStatus,1).update();
}
}
}else {
//稳态
else if (Objects.equals(csEventUserQueryParam.getType(), "1")) {
List<String> harmonicList = csDeviceUserFeignClient.getIdList("1").getData();
if (CollectionUtil.isNotEmpty(harmonicList)) {
this.lambdaUpdate().in(CsEventUserPO::getEventId,harmonicList).
eq(CsEventUserPO::getUserId,RequestUtil.getUserIndex()).
set(CsEventUserPO::getStatus,1).update();
}
}
//运行告警
else if (Objects.equals(csEventUserQueryParam.getType(), "3")) {
List<String> alarmList = csDeviceUserFeignClient.getIdList("3").getData();
if (CollectionUtil.isNotEmpty(alarmList)) {
this.lambdaUpdate().in(CsEventUserPO::getEventId,alarmList).
eq(CsEventUserPO::getUserId,RequestUtil.getUserIndex()).
set(CsEventUserPO::getStatus,1).update();
}
}
} else {
this.lambdaUpdate().in(CsEventUserPO::getEventId,csEventUserQueryParam.getEventIds()).
eq(CsEventUserPO::getUserId,csEventUserQueryParam.getUserId()).
set(CsEventUserPO::getStatus,1).update();
}
}
@Override
@@ -331,6 +357,9 @@ public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, C
temp.setProjectName(devDetail.getProjectName());
temp.setEngineeringid(devDetail.getEngineeringid());
temp.setEngineeringName(devDetail.getEngineeringName());
//设备类型
SysDicTreePO po = dictTreeFeignClient.queryById(temp.getDevType()).getData();
temp.setDevType(Objects.isNull(po)?null:po.getCode());
//监测位置
temp.setEvtParamPosition(Objects.equals(temp.getLocation(), "grid") ? "电网侧" : "负载侧");
//暂态事件类型
@@ -344,218 +373,6 @@ public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, C
return returnpage;
}
// @Override
// public Page<EventDetailVO> queryEventpage(CsEventUserQueryPage csEventUserQueryPage) {
// Page<EventDetailVO> returnpage = new Page<> (csEventUserQueryPage.getPageNum ( ), csEventUserQueryPage.getPageSize ( ));
//
// csEventUserQueryPage.setUserId(RequestUtil.getUserIndex());
// String role = RequestUtil.getUserRole();
// if(Objects.equals(role, LogInfo.UNKNOWN_ROLE)){
// return returnpage;
// }
// List<String> strings = JSONArray.parseArray(role, String.class);
// if(CollectionUtils.isEmpty(strings)){
// return returnpage;
// }
// role=strings.get(0);
// if( Objects.equals(role, AppRoleEnum.APP_VIP_USER.getCode())&&Objects.equals(csEventUserQueryPage.getType(),"3")){
// csEventUserQueryPage.setLevel("3");
// }
//
// List<CsLedgerVO> data = csLedgerFeignClient.lineTree().getData();
// if (CollectionUtils.isEmpty(data)) {
// return returnpage;
// }
//
// // 获取第一层节点(根节点),从第二层开始才是真正的工程
// List<CsLedgerVO> firstLevelNodes = new ArrayList<>();
// for (CsLedgerVO rootNode : data) {
// List<CsLedgerVO> children = rootNode.getChildren();
// if (CollectionUtil.isNotEmpty(children)) {
// firstLevelNodes.addAll(children);
// }
// }
//
// if (CollectionUtils.isEmpty(firstLevelNodes)) {
// return returnpage;
// }
//
// // 缓存查询条件到局部变量
// String engineeringId = csEventUserQueryPage.getEngineeringid();
// String projectId = csEventUserQueryPage.getProjectId();
// String deviceId = csEventUserQueryPage.getDeviceId();
// String lineId = csEventUserQueryPage.getLineId();
//
// // 从第二层开始遍历:工程 -> 项目 -> 设备 -> 监测点
// List<String> collect = new ArrayList<>();
// for (CsLedgerVO engineering : firstLevelNodes) {
// // 过滤工程
// if (StringUtil.isNotBlank(engineeringId)
// && !Objects.equals(engineering.getId(), engineeringId)) {
// continue;
// }
//
// List<CsLedgerVO> projects = engineering.getChildren();
// if (CollectionUtils.isEmpty(projects)) {
// continue;
// }
//
// for (CsLedgerVO project : projects) {
// // 过滤项目
// if (StringUtil.isNotBlank(projectId)
// && !Objects.equals(project.getId(), projectId)) {
// continue;
// }
//
// List<CsLedgerVO> devices = project.getChildren();
// if (CollectionUtils.isEmpty(devices)) {
// continue;
// }
//
// for (CsLedgerVO device : devices) {
// // 过滤设备
// if (StringUtil.isNotBlank(deviceId)
// && !Objects.equals(device.getId(), deviceId)) {
// continue;
// }
//
// // 如果传了监测点 ID需要进一步过滤
// if (StringUtil.isNotBlank(lineId)) {
// List<CsLedgerVO> lines = device.getChildren();
// if (CollectionUtil.isNotEmpty(lines)) {
// boolean hasLine = lines.stream()
// .anyMatch(line -> Objects.equals(line.getId(), lineId));
// if (hasLine) {
// collect.add(device.getId());
// }
// }
// } else {
// // 没有传监测点 ID直接添加设备 ID
// collect.add(device.getId());
// }
// }
// }
// }
// if (CollectionUtils.isEmpty(collect)) {
// return returnpage;
// }
// //如果是游客用户,没有消息推送的数据,展示设备的所有数据
// if(strings.contains(AppRoleEnum.TOURIST.getCode())){
// returnpage = this.getBaseMapper().queryTouristEvent(returnpage, csEventUserQueryPage, collect, false);
// } else {
// returnpage = this.getBaseMapper().queryEventpage(returnpage, csEventUserQueryPage, collect, true);
// }
// // 先获取原始记录
// List<EventDetailVO> originalRecords = returnpage.getRecords();
// if (CollectionUtil.isNotEmpty(originalRecords)) {
// // 过滤出满足 lineId 条件的记录
// List<EventDetailVO> filteredRecords = new ArrayList<>();
// for (EventDetailVO temp : originalRecords) {
// // 如果没有传 lineId 或者 lineId 匹配,则处理该记录
// if (StringUtil.isBlank(csEventUserQueryPage.getLineId())
// || Objects.equals(temp.getLineId(), csEventUserQueryPage.getLineId())) {
//
// DevDetailDTO devDetail = csLedgerFeignClient.queryDevDetail(temp.getDeviceId()).getData();
// temp.setEquipmentName(devDetail.getEquipmentName());
// temp.setProjectId(devDetail.getProjectId());
// temp.setProjectName(devDetail.getProjectName());
// temp.setEngineeringid(devDetail.getEngineeringid());
// temp.setEngineeringName(devDetail.getEngineeringName());
//
// EleEpdPqd ele = epdFeignClient.findByName(temp.getTag()).getData();
// temp.setShowName(Objects.isNull(ele) ? temp.getTag() : ele.getShowName());
// temp.setCode(Objects.isNull(ele) ? null : ele.getDefaultValue());
//
// if (Objects.equals(csEventUserQueryPage.getType(), "0")) {
// List<EleEvtParm> data1 = eleEvtFeignClient.queryByPid(ele.getId()).getData();
// List<EventDataSetDTO> eventDataSetDTOS = new ArrayList<>();
// for (EleEvtParm eleEvtParm : data1) {
// EventDataSetDTO eventDataSetDTO = new EventDataSetDTO();
// BeanUtils.copyProperties(eleEvtParm, eventDataSetDTO);
// if (Objects.equals(eventDataSetDTO.getName(), "Evt_Param_Position")) {
// continue;
// }
// EventDataSetDTO evtData = evtDataService.getEventDataSet("evt_data", temp.getId(), eleEvtParm.getName());
// if (evtData == null) {
// eventDataSetDTO.setValue("-");
// } else {
// if (Objects.equals(eleEvtParm.getName(), "Evt_Param_VVaDepth") || Objects.equals(eleEvtParm.getName(), "Evt_Param_Tm")) {
// BigDecimal bd = new BigDecimal(evtData.getValue());
// bd = bd.setScale(2, RoundingMode.HALF_UP);
// eventDataSetDTO.setValue(Optional.ofNullable(bd.toString()).orElse("-"));
// } else {
// eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("-"));
// }
// }
// eventDataSetDTOS.add(eventDataSetDTO);
// }
// temp.setDataSet(eventDataSetDTOS);
//
// List<EventDataSetDTO> evtParamVVaDepth = eventDataSetDTOS.stream()
// .filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_VVaDepth"))
// .collect(Collectors.toList());
//
// if (CollectionUtil.isEmpty(evtParamVVaDepth)) {
// temp.setEvtParamVVaDepth("-");
// } else {
// if (Objects.equals(evtParamVVaDepth.get(0).getValue(),"-")) {
// temp.setEvtParamVVaDepth("-");
// } else {
// BigDecimal bd = new BigDecimal(evtParamVVaDepth.get(0).getValue());
// bd = bd.setScale(2, RoundingMode.HALF_UP);
// temp.setEvtParamVVaDepth(bd + (Objects.isNull(evtParamVVaDepth.get(0).getUnit()) ? "" : evtParamVVaDepth.get(0).getUnit()));
// }
// }
//
// List<EventDataSetDTO> evtParamPosition = eventDataSetDTOS.stream()
// .filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Position"))
// .collect(Collectors.toList());
// if (CollectionUtil.isEmpty(evtParamPosition)) {
// temp.setEvtParamPosition("-");
// } else {
// temp.setEvtParamPosition(evtParamPosition.get(0).getValue());
// }
// if (Objects.equals(temp.getEvtParamPosition(), "-")) {
// if (!Objects.isNull(temp.getLocation())) {
// temp.setEvtParamPosition(Objects.equals(temp.getLocation(), "grid") ? "电网侧" : "负载侧");
// }
// }
//
// List<EventDataSetDTO> evtParamTm = eventDataSetDTOS.stream()
// .filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Tm"))
// .collect(Collectors.toList());
// if (CollectionUtil.isEmpty(evtParamTm)) {
// temp.setEvtParamTm("-");
// } else {
// if (Objects.equals(evtParamTm.get(0).getValue(),"-")) {
// temp.setEvtParamTm("-");
// } else {
// BigDecimal bd = new BigDecimal(evtParamTm.get(0).getValue());
// bd = bd.setScale(2, RoundingMode.HALF_UP);
// temp.setEvtParamTm(bd + (Objects.isNull(evtParamTm.get(0).getUnit()) ? "" : evtParamTm.get(0).getUnit()));
// }
// }
//
// List<EventDataSetDTO> evtParamPhase = eventDataSetDTOS.stream()
// .filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Phase"))
// .collect(Collectors.toList());
// if (CollectionUtil.isEmpty(evtParamPhase)) {
// temp.setEvtParamPhase("-");
// } else {
// temp.setEvtParamPhase(evtParamPhase.get(0).getValue()
// + (Objects.isNull(evtParamPhase.get(0).getUnit()) ? "" : evtParamPhase.get(0).getUnit()));
// }
// }
// // 将处理后的记录添加到结果列表
// filteredRecords.add(temp);
// }
// }
// // 清空原来的记录,加入过滤后的记录
// returnpage.setRecords(filteredRecords);
// }
// return returnpage;
// }
@Override
public Page<EventDetailVO> queryEventPageWeb(CsEventUserQueryPage csEventUserQueryPage) {
Page<EventDetailVO> returnpage = new Page<> (csEventUserQueryPage.getPageNum ( ), csEventUserQueryPage.getPageSize ( ));
@@ -748,4 +565,99 @@ public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, C
queryWrapper.eq(CsEventUserPO::getUserId, userIndex).in(CsEventUserPO::getEventId, eventList);
return baseMapper.selectList(queryWrapper);
}
@Override
public EventStatisticVO queryAppEventCounts(CsEventUserQueryPage csEventUserQueryPage) {
EventStatisticVO result = new EventStatisticVO();
csEventUserQueryPage.setUserId(RequestUtil.getUserIndex());
String role = RequestUtil.getUserRole();
if(Objects.equals(role, LogInfo.UNKNOWN_ROLE)){
return result;
}
List<String> strings = JSONArray.parseArray(role, String.class);
if(CollectionUtils.isEmpty(strings)){
return result;
}
role=strings.get(0);
if( Objects.equals(role, AppRoleEnum.APP_VIP_USER.getCode())&&Objects.equals(csEventUserQueryPage.getType(),"3")){
csEventUserQueryPage.setLevel("3");
}
List<CsLedgerVO> data = csLedgerFeignClient.lineTree().getData();
if (CollectionUtils.isEmpty(data)) {
return result;
}
// 获取第一层节点(根节点),从第二层开始才是真正的工程
List<CsLedgerVO> firstLevelNodes = new ArrayList<>();
for (CsLedgerVO rootNode : data) {
List<CsLedgerVO> children = rootNode.getChildren();
if (CollectionUtil.isNotEmpty(children)) {
firstLevelNodes.addAll(children);
}
}
if (CollectionUtils.isEmpty(firstLevelNodes)) {
return result;
}
// 缓存查询条件到局部变量
String engineeringId = csEventUserQueryPage.getEngineeringid();
String projectId = csEventUserQueryPage.getProjectId();
String deviceId = csEventUserQueryPage.getDeviceId();
String lineId = csEventUserQueryPage.getLineId();
// 从第二层开始遍历:工程 -> 项目 -> 设备 -> 监测点
List<String> collect = new ArrayList<>();
for (CsLedgerVO engineering : firstLevelNodes) {
// 过滤工程
if (StringUtil.isNotBlank(engineeringId)
&& !Objects.equals(engineering.getId(), engineeringId)) {
continue;
}
List<CsLedgerVO> projects = engineering.getChildren();
if (CollectionUtils.isEmpty(projects)) {
continue;
}
for (CsLedgerVO project : projects) {
// 过滤项目
if (StringUtil.isNotBlank(projectId)
&& !Objects.equals(project.getId(), projectId)) {
continue;
}
List<CsLedgerVO> devices = project.getChildren();
if (CollectionUtils.isEmpty(devices)) {
continue;
}
for (CsLedgerVO device : devices) {
// 过滤设备
if (StringUtil.isNotBlank(deviceId)
&& !Objects.equals(device.getId(), deviceId)) {
continue;
}
// 如果传了监测点 ID需要进一步过滤
if (StringUtil.isNotBlank(lineId)) {
List<CsLedgerVO> lines = device.getChildren();
if (CollectionUtil.isNotEmpty(lines)) {
boolean hasLine = lines.stream()
.anyMatch(line -> Objects.equals(line.getId(), lineId));
if (hasLine) {
collect.add(device.getId());
}
}
} else {
// 没有传监测点 ID直接添加设备 ID
collect.add(device.getId());
}
}
}
}
if (CollectionUtils.isEmpty(collect)) {
return result;
} else {
result = baseMapper.getEventCounts(csEventUserQueryPage.getStartTime(),csEventUserQueryPage.getEndTime(),collect);
}
return result;
}
}

View File

@@ -0,0 +1,64 @@
package com.njcn.csharmonic.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csharmonic.mapper.CsHarmonicPlanLineMapper;
import com.njcn.csharmonic.param.CsHarmonicPlanLineParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
import com.njcn.csharmonic.service.ICsHarmonicPlanLineService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Service
@RequiredArgsConstructor
public class CsHarmonicPlanLineServiceImpl extends ServiceImpl<CsHarmonicPlanLineMapper, CsHarmonicPlanLine> implements ICsHarmonicPlanLineService {
@Override
public List<CsHarmonicPlanLine> getByPlanId(String id) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsHarmonicPlanLine::getId, id);
return this.list(wrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void savePlanLines(CsHarmonicPlanLineParam param) {
List<CsHarmonicPlanLine> planLineList = new ArrayList<>();
for (String lineId : param.getLineIds()) {
CsHarmonicPlanLine planLine = new CsHarmonicPlanLine();
planLine.setId(param.getId());
planLine.setLineId(lineId);
planLineList.add(planLine);
}
this.saveBatch(planLineList);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteByLineIds(List<String> lineIds) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.in(CsHarmonicPlanLine::getLineId, lineIds);
this.remove(wrapper);
}
@Override
public String getPlanIdByLineId(String lineId) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsHarmonicPlanLine::getLineId, lineId)
.last("LIMIT 1");
CsHarmonicPlanLine planLine = this.getOne(wrapper);
return planLine != null ? planLine.getId() : null;
}
}

View File

@@ -0,0 +1,134 @@
package com.njcn.csharmonic.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csharmonic.mapper.CsHarmonicPlanMapper;
import com.njcn.csharmonic.param.CsHarmonicPlanParam;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlan;
import com.njcn.csharmonic.pojo.po.CsHarmonicPlanLine;
import com.njcn.csharmonic.service.ICsHarmonicPlanLineService;
import com.njcn.csharmonic.service.ICsHarmonicPlanService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 服务实现类
* </p>
*
* @author xy
* @since 2026-04-15
*/
@Service
@RequiredArgsConstructor
public class CsHarmonicPlanServiceImpl extends ServiceImpl<CsHarmonicPlanMapper, CsHarmonicPlan> implements ICsHarmonicPlanService {
private final ICsHarmonicPlanLineService csHarmonicPlanLineService;
@Override
@Transactional(rollbackFor = Exception.class)
public void save(CsHarmonicPlanParam param) {
CsHarmonicPlan plan = new CsHarmonicPlan();
plan.setName(param.getName());
plan.setHarmonicTarget(param.getHarmonicTarget());
plan.setSort(param.getSort() != null ? param.getSort() : 0);
this.save(plan);
if (CollUtil.isNotEmpty(param.getLineList())) {
for (String lineId : param.getLineList()) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsHarmonicPlanLine::getLineId, lineId);
csHarmonicPlanLineService.remove(wrapper);
CsHarmonicPlanLine planLine = new CsHarmonicPlanLine();
planLine.setId(plan.getId());
planLine.setLineId(lineId);
csHarmonicPlanLineService.save(planLine);
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(CsHarmonicPlanParam.UpdateCsHarmonicPlanParam param) {
CsHarmonicPlan plan = this.getById(param.getId());
if (plan == null) {
throw new RuntimeException("稳态指标方案不存在");
}
plan.setName(param.getName());
plan.setHarmonicTarget(param.getHarmonicTarget());
plan.setSort(param.getSort() != null ? param.getSort() : plan.getSort());
this.updateById(plan);
if (CollUtil.isNotEmpty(param.getLineList())) {
LambdaQueryWrapper<CsHarmonicPlanLine> oldWrapper = new LambdaQueryWrapper<>();
oldWrapper.eq(CsHarmonicPlanLine::getId, param.getId());
csHarmonicPlanLineService.remove(oldWrapper);
for (String lineId : param.getLineList()) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CsHarmonicPlanLine::getLineId, lineId);
csHarmonicPlanLineService.remove(wrapper);
CsHarmonicPlanLine planLine = new CsHarmonicPlanLine();
planLine.setId(param.getId());
planLine.setLineId(lineId);
csHarmonicPlanLineService.save(planLine);
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteWithLines(List<String> ids) {
this.removeByIds(ids);
if (CollUtil.isNotEmpty(ids)) {
LambdaQueryWrapper<CsHarmonicPlanLine> wrapper = new LambdaQueryWrapper<>();
wrapper.in(CsHarmonicPlanLine::getId, ids);
List<CsHarmonicPlanLine> list = csHarmonicPlanLineService.list();
if (CollUtil.isNotEmpty(list)) {
throw new BusinessException("该方案下存在监测点,重新分配后再尝试删除!");
}
}
}
@Override
public Page<CsHarmonicPlan> getPage(CsHarmonicPlanParam.QueryParam param) {
Page<CsHarmonicPlan> page = new Page<>(param.getPageNum(), param.getPageSize());
LambdaQueryWrapper<CsHarmonicPlan> wrapper = new LambdaQueryWrapper<>();
wrapper.like(StrUtil.isNotBlank(param.getName()), CsHarmonicPlan::getName, param.getName())
.orderByAsc(CsHarmonicPlan::getSort)
.orderByAsc(CsHarmonicPlan::getCreateTime);
return this.page(page, wrapper);
}
@Override
public List<CsHarmonicPlan> listAllOrderBySort() {
LambdaQueryWrapper<CsHarmonicPlan> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByAsc(CsHarmonicPlan::getSort);
return this.list(wrapper);
}
@Override
public CsHarmonicPlan getByIdWithLines(String id) {
CsHarmonicPlan plan = this.getById(id);
if (plan != null) {
List<CsHarmonicPlanLine> planLines = csHarmonicPlanLineService.getByPlanId(id);
if (CollUtil.isNotEmpty(planLines)) {
List<String> lineIds = planLines.stream()
.map(CsHarmonicPlanLine::getLineId)
.collect(Collectors.toList());
plan.setLineList(lineIds);
}
}
return plan;
}
}

View File

@@ -1,9 +1,11 @@
package com.njcn.csharmonic.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -30,7 +32,6 @@ import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
@@ -46,13 +47,22 @@ import java.util.stream.Collectors;
@Service
public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmonic> implements ICsHarmonicService {
private static final Map<String, String> VALUE_TYPE_MAP = new HashMap<String, String>() {{
put("max", "最大值");
put("min", "最小值");
put("avg", "平均值");
put("cp95", "95%概率值");
}};
private final CsLedgerFeignClient csLedgerFeignClient;
private final CsEventUserPOService csEventUserPOService;
private final IRStatLimitRateDetailDService rStatLimitRateDetailDService;
private final CsCommTerminalFeignClient csCommTerminalFeignClient;
@Override
public HarmonicVO queryAppList(LineParamDTO param) {
public Page<HarmonicVO.LineHarmonicDetail> queryAppList(LineParamDTO param) {
Page<HarmonicVO.LineHarmonicDetail> result = new Page<>();
Page<CsHarmonic> page = new Page<> (param.getPageNum(), param.getPageSize());
HarmonicVO vo = new HarmonicVO();
List<CsLedger> lineLedger = csLedgerFeignClient.queryLine(param).getData();
if (CollectionUtil.isNotEmpty(lineLedger)) {
@@ -73,23 +83,17 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
.ge(StrUtil.isNotBlank(param.getTime()), CsHarmonic::getTime, PublicDataUtils.calculateMonthStart(param.getTime()))
.le(StrUtil.isNotBlank(param.getTime()), CsHarmonic::getTime, PublicDataUtils.calculateMonthEnd(param.getTime()))
.orderByDesc(CsHarmonic::getTime);
list = list(queryWrapper);
Page<CsHarmonic> csHarmonicPage = this.baseMapper.selectPage(page,queryWrapper);
BeanUtil.copyProperties(csHarmonicPage, result);
list = csHarmonicPage.getRecords();
}
if (CollectionUtil.isNotEmpty(list)) {
//获取所有台账数据
List<CsLedgerVO> ledgers = csLedgerFeignClient.getAllLedger().getData();
Map<String,CsLedgerVO> ledgerMap = ledgers.stream().collect(Collectors.toMap(CsLedgerVO::getId, item->item));
List<HarmonicVO.LineHarmonicDetail> lineHarmonicDetails = new ArrayList<>();
vo.setHarmonicNums(list.size());
//获取越限天数
Set<LocalDate> distinctTimes = list.stream().map(CsHarmonic::getTime).filter(Objects::nonNull).collect(Collectors.toSet());
int overDay = distinctTimes.size();
vo.setOverDays(overDay);
//获取监测点
Set<String> distinctLineIds = list.stream().map(CsHarmonic::getLineId).collect(Collectors.toSet());
int overLine = distinctLineIds.size();
vo.setOverLineNums(overLine);
//获取用户推送事件
List<CsEventUserPO> userEvents = csEventUserPOService.queryEventListByUserId(RequestUtil.getUserIndex(), list.stream().map(CsHarmonic::getId).collect(Collectors.toList()));
list.forEach(item->{
@@ -107,9 +111,10 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
lineHarmonicDetails.add(lineHarmonicDetail);
});
vo.setList(lineHarmonicDetails);
result.setRecords(lineHarmonicDetails);
}
}
return vo;
return result;
}
@Override
@@ -156,6 +161,85 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
return list;
}
@Override
public HarmonicVO queryAppHarmonicCounts(LineParamDTO param) {
HarmonicVO vo = new HarmonicVO();
List<CsLedger> lineLedger = csLedgerFeignClient.queryLine(param).getData();
if (CollectionUtil.isNotEmpty(lineLedger)) {
List<String> lineIds = lineLedger.stream().map(CsLedger::getId).collect(Collectors.toList());
//根据用户获取设备数据权限
List<String> ownerList = csCommTerminalFeignClient.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
List<String> combinedLineIds = new ArrayList<>();
if (CollectionUtil.isNotEmpty(ownerList)) {
combinedLineIds = lineIds.stream()
.filter(ownerList::contains)
.distinct()
.collect(Collectors.toList());
}
if (CollectionUtil.isNotEmpty(combinedLineIds)) {
//查询数量
vo = this.baseMapper.getHarmonicCounts(
PublicDataUtils.calculateMonthStart(param.getTime())
,PublicDataUtils.calculateMonthEnd(param.getTime())
,combinedLineIds);
//查询日期
List<String> overDays = this.baseMapper.getOverDays(
PublicDataUtils.calculateMonthStart(param.getTime())
,PublicDataUtils.calculateMonthEnd(param.getTime())
,combinedLineIds);
vo.setOverDaysList(overDays);
}
}
return vo;
}
@Override
public Page<HarmonicVO.LineHarmonicOverDays> queryAppHarmonicLine(LineParamDTO param) {
Page<HarmonicVO.LineHarmonicOverDays> page = new Page<> (param.getPageNum(), param.getPageSize());
List<CsLedger> lineLedger = csLedgerFeignClient.queryLine(param).getData();
if (CollectionUtil.isNotEmpty(lineLedger)) {
List<String> lineIds = lineLedger.stream().map(CsLedger::getId).collect(Collectors.toList());
//根据用户获取设备数据权限
List<String> ownerList = csCommTerminalFeignClient.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
List<String> combinedLineIds = new ArrayList<>();
if (CollectionUtil.isNotEmpty(ownerList)) {
combinedLineIds = lineIds.stream()
.filter(ownerList::contains)
.distinct()
.collect(Collectors.toList());
}
if (CollectionUtil.isNotEmpty(combinedLineIds)) {
page = this.baseMapper.getLineHarmonicOverDays(page
,PublicDataUtils.calculateMonthStart(param.getTime())
,PublicDataUtils.calculateMonthEnd(param.getTime())
,combinedLineIds);
List<HarmonicVO.LineHarmonicOverDays> lineHarmonicOverDays = page.getRecords();
if (CollectionUtil.isNotEmpty(lineHarmonicOverDays)) {
//获取所有台账数据
List<CsLedgerVO> ledgers = csLedgerFeignClient.getAllLedger().getData();
Map<String,CsLedgerVO> ledgerMap = ledgers.stream().collect(Collectors.toMap(CsLedgerVO::getId, item->item));
lineHarmonicOverDays.forEach(item->{
CsLedger ledger = lineLedger.stream().filter(item1->item1.getId().equals(item.getLineId())).findFirst().orElse(null);
item.setEngineeringName(ledgerMap.get(ledger.getPids().split(",")[1]).getName());
item.setProjectName(ledgerMap.get(ledger.getPids().split(",")[2]).getName());
item.setDevName(ledgerMap.get(ledger.getPids().split(",")[3]).getName());
item.setLineId(item.getLineId());
item.setLineName(ledger.getName());
item.setTimeList(Arrays.asList(item.getTimeString().split(", ")));
});
//对告警天数进行降序排序
lineHarmonicOverDays.sort((item1, item2) -> {
int size1 = item1.getTimeList() != null ? item1.getTimeList().size() : 0;
int size2 = item2.getTimeList() != null ? item2.getTimeList().size() : 0;
return Integer.compare(size2, size1);
});
page.setRecords(lineHarmonicOverDays);
}
}
}
return page;
}
/**
* 添加谐波数据到列表
@@ -221,7 +305,7 @@ public class CsHarmonicServiceImpl extends ServiceImpl<CsHarmonicMapper, CsHarmo
detail.setDataB(formatValue(values.get("B")));
detail.setDataC(formatValue(values.get("C")));
detail.setDataT(formatValue(values.get("T")));
detail.setValueType(phaseDataList.get(0).valueType);
detail.setValueType(VALUE_TYPE_MAP.get(phaseDataList.get(0).valueType));
detail.setOverLimitData(phaseDataList.get(0).overLimitValue);
detail.setHasT(values.containsKey("T"));
allDetails.add(detail);

View File

@@ -9,6 +9,7 @@ import com.njcn.csdevice.pojo.param.CsEngineeringQueryParm;
import com.njcn.csdevice.pojo.po.CsUserPins;
import com.njcn.csdevice.pojo.vo.CsEngineeringVO;
import com.njcn.csdevice.pojo.vo.EngineeringHomePageVO;
import com.njcn.csharmonic.mapper.CsEventUserPOMapper;
import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.service.HomePageService;
@@ -30,7 +31,7 @@ import java.util.stream.Collectors;
@Slf4j
public class HomePageServiceImpl implements HomePageService {
private final CsEventUserPOService csEventUserPOService;
private final CsEventUserPOMapper csEventUserPOMapper;
private final EngineeringFeignClient engineeringFeignClient;
private final CsLedgerFeignClient csLedgerFeignClient;
private final CsUserPinsFeignClient csUserPinsFeignClient;
@@ -48,11 +49,6 @@ public class HomePageServiceImpl implements HomePageService {
Map<String, List<DevDetailDTO>> devMap = Objects.isNull(devList) ? new HashMap<>() :
devList.stream().collect(Collectors.groupingBy(DevDetailDTO::getEngineeringid));
// 获取未读事件
List<UnReadEventDto> unReadEventList = csEventUserPOService.queryEngineeringEventCount(RequestUtil.getUserIndex());
Map<String, List<UnReadEventDto>> unReadEventMap = Objects.isNull(unReadEventList) ? new HashMap<>() :
unReadEventList.stream().collect(Collectors.groupingBy(UnReadEventDto::getDeviceId));
// 遍历工程列表,从内存中获取设备数据
engineeringList.forEach(item -> {
EngineeringHomePageVO vo = new EngineeringHomePageVO();
@@ -69,19 +65,26 @@ public class HomePageServiceImpl implements HomePageService {
vo.setOfflineDevTotal((int) status1Count);
vo.setSort(item.getSort());
// 未读的告警数量
int alarmTotal = Objects.isNull(devs) ? 0 : devs.stream()
.map(DevDetailDTO::getEquipmentId)
.filter(Objects::nonNull)
.mapToInt(deviceId -> {
List<UnReadEventDto> events = unReadEventMap.get(deviceId);
return Objects.isNull(events) ? 0 : events.stream()
.mapToInt(UnReadEventDto::getCount)
.sum();
})
.sum();
vo.setAlarmTotal(alarmTotal);
// 获取项目事件数量
int alarmTotal = 0;
if (CollectionUtil.isNotEmpty(devs) && !Objects.isNull(devs)) {
// 获取暂态未读事件
List<String> allLineIds = devs.stream()
.filter(dev -> CollectionUtil.isNotEmpty(dev.getLineList()))
.flatMap(dev -> dev.getLineList().stream())
.distinct()
.collect(Collectors.toList());
List<String> tempEventList = csEventUserPOMapper.queryTempEvent(RequestUtil.getUserIndex(),"","",allLineIds);
alarmTotal = alarmTotal + (CollectionUtil.isNotEmpty(tempEventList)?tempEventList.size():0);
// 获取稳态未读事件
if (CollectionUtil.isNotEmpty(allLineIds)) {
List<String> tempHarmonicList = csEventUserPOMapper.queryTempHarmonic(RequestUtil.getUserIndex(),"","",allLineIds);
alarmTotal = alarmTotal + (CollectionUtil.isNotEmpty(tempHarmonicList)?tempHarmonicList.size():0);
}
}
vo.setAlarmTotal(alarmTotal);
result.add(vo);
});

View File

@@ -48,7 +48,7 @@ public class RealDataServiceImpl implements RealDataService {
//判断设备类型 治理无线设备需要判断mqtt、云前置设备直接判断设备运行状态
CsEquipmentDeliveryPO dev = equipmentFeignClient.getDevByLineId(lineId).getData();
String devModelCode = dictTreeFeignClient.queryById(dev.getDevType()).getData().getCode();
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
if (dev.getRunStatus() == 1) {
throw new BusinessException("装置离线");
}
@@ -63,7 +63,7 @@ public class RealDataServiceImpl implements RealDataService {
//获取装置所用模板
CsLinePO po = csLineFeignClient.getById(lineId).getData();
String modelId = po.getDataModelId();
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
CsDataSet csDataSet = dataSetFeignClient.getBaseDataSet(modelId,1).getData();
askDeviceDataFeignClient.askCldRealData(dev.getId(),lineId,dev.getNodeId(),csDataSet.getIdx());
updateRedisUserSet("rtDataUserId:" + lineId, RequestUtil.getUserIndex(), 600L);
@@ -76,7 +76,7 @@ public class RealDataServiceImpl implements RealDataService {
//等待装置响应,获取询问结果
Thread.sleep(5000);
Object object;
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
object = redisUtil.getObjectByKey("devResponse:" + lineId);
} else {
object = redisUtil.getObjectByKey("devResponse");
@@ -105,7 +105,7 @@ public class RealDataServiceImpl implements RealDataService {
//判断设备类型 治理无线设备需要判断mqtt、云前置设备直接判断设备运行状态
CsEquipmentDeliveryPO dev = equipmentFeignClient.getDevByLineId(lineId).getData();
String devModelCode = dictTreeFeignClient.queryById(dev.getDevType()).getData().getCode();
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
if (dev.getRunStatus() == 1) {
throw new BusinessException("装置离线");
}
@@ -121,7 +121,7 @@ public class RealDataServiceImpl implements RealDataService {
CsLinePO po = csLineFeignClient.getById(lineId).getData();
String modelId = po.getDataModelId();
//根据指标来获取不同的数据集
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
CsDataSet csDataSet = dataSetFeignClient.getHarmonicDataSet(modelId,1,target).getData();
askDeviceDataFeignClient.askCldRealData(dev.getId(),lineId,dev.getNodeId(),csDataSet.getIdx());
} else {
@@ -131,7 +131,7 @@ public class RealDataServiceImpl implements RealDataService {
//等待装置响应,获取询问结果
Thread.sleep(2000);
Object object;
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode)) {
if (Objects.equals(DicDataEnum.DEV_CLD.getCode(),devModelCode) && Objects.equals(dev.getDevAccessMethod(),"CLD")) {
object = redisUtil.getObjectByKey("devResponse:" + lineId);
} else {
object = redisUtil.getObjectByKey("devResponse");

View File

@@ -1,6 +1,7 @@
package com.njcn.csreport.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
@@ -71,9 +72,9 @@ public class CsAppReportController extends BaseController {
@PostMapping("/getApplicationReport")
@ApiOperation("查询暂态报告申请记录")
@ApiImplicitParam(name = "param", value = "事件查询参数", required = true)
public HttpResult<List<ReportEventVO>> getApplicationReportList(@RequestBody LineParamDTO param) {
public HttpResult<Page<ReportEventVO>> getApplicationReportList(@RequestBody LineParamDTO param) {
String methodDescribe = getMethodDescribe("getApplicationReportList");
List<ReportEventVO> result = csAppReportService.getApplicationReportList(param);
Page<ReportEventVO> result = csAppReportService.getApplicationReportList(param);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
}

View File

@@ -1,5 +1,6 @@
package com.njcn.csreport.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csreport.pojo.po.CsAppReport;
@@ -24,7 +25,7 @@ public interface ICsAppReportService extends IService<CsAppReport> {
void applicationReport(LineParamDTO param);
List<ReportEventVO> getApplicationReportList(LineParamDTO param);
Page<ReportEventVO> getApplicationReportList(LineParamDTO param);
Boolean createEventReport(String id);

View File

@@ -3,10 +3,12 @@ package com.njcn.csreport.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
@@ -22,7 +24,9 @@ import com.njcn.csharmonic.api.SysExcelRelationFeignClient;
import com.njcn.csharmonic.enums.CsHarmonicResponseEnum;
import com.njcn.csharmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
import com.njcn.csharmonic.pojo.po.RStatLimitRateDPO;
import com.njcn.csharmonic.pojo.vo.HarmonicVO;
import com.njcn.csreport.mapper.CsAppReportMapper;
import com.njcn.csreport.pojo.po.CsAppReport;
import com.njcn.csreport.pojo.vo.ReportEventVO;
@@ -52,10 +56,11 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
@@ -97,12 +102,11 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
if (param.getTimeType() == 0) {
timeRanges = splitIntoDays(startLocalDate, endLocalDate);
} else {
timeRanges = splitIntoMonths(startLocalDate, endLocalDate);
timeRanges = splitIntoMonthsForCurrentYear(endLocalDate);
}
String queryStartTime = timeRanges.get(timeRanges.size() - 1).end.format(DateTimeFormatter.ISO_LOCAL_DATE);
String queryEndTime = timeRanges.get(0).start.format(DateTimeFormatter.ISO_LOCAL_DATE);
String queryStartTime = timeRanges.get(timeRanges.size() - 1).start.format(DateTimeFormatter.ISO_LOCAL_DATE);
String queryEndTime = timeRanges.get(0).end.format(DateTimeFormatter.ISO_LOCAL_DATE);
StatSubstationBizBaseParam rStatLimitQueryParam = new StatSubstationBizBaseParam();
rStatLimitQueryParam.setIds(Collections.singletonList(param.getLineId()));
@@ -200,11 +204,14 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
}
@Override
public List<ReportEventVO> getApplicationReportList(LineParamDTO param) {
public Page<ReportEventVO> getApplicationReportList(LineParamDTO param) {
Page<ReportEventVO> page = new Page<>();
Page<CsAppReport> page1 = new Page<> (param.getPageNum(), param.getPageSize());
List<ReportEventVO> result = new ArrayList<>();
LambdaQueryWrapper<CsAppReport> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(StringUtils.isNotBlank(param.getStartTime()),CsAppReport::getStartTime, param.getStartTime())
.eq(StringUtils.isNotBlank(param.getEndTime()),CsAppReport::getEndTime, param.getEndTime())
queryWrapper.between(CsAppReport::getCreateTime, param.getStartTime(), param.getEndTime())
.eq(CsAppReport::getReportType, 1)
.orderByDesc(CsAppReport::getCreateTime);
//获取当前用户
@@ -212,7 +219,11 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
if (!userVO.getType().equals(UserType.SUPER_ADMINISTRATOR) && !userVO.getType().equals(UserType.ADMINISTRATOR)) {
queryWrapper.eq(CsAppReport::getCreateBy, userVO.getId());
}
List<CsAppReport> list = this.list(queryWrapper);
Page<CsAppReport> page2 = this.baseMapper.selectPage(page1,queryWrapper);
BeanUtil.copyProperties(page2, page);
List<CsAppReport> list = page2.getRecords();
// List<CsAppReport> list = this.list(queryWrapper);
if (CollUtil.isNotEmpty(list)) {
list.forEach(item->{
ReportEventVO vo = new ReportEventVO();
@@ -221,8 +232,13 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
vo.setEventNums(item.getEventList().split(",").length);
vo.setFilePath(item.getFilePath());
vo.setIsComplete(Objects.isNull(item.getFilePath()) ? 0 : 1);
vo.setApplyUser(userVO.getName());
String applyUser = item.getCreateBy();
if (applyUser != null && !applyUser.isEmpty()) {
UserVO applyUserVo = userFeignClient.getUserById(applyUser).getData();
vo.setApplyUser(Objects.isNull(applyUserVo)? null : applyUserVo.getName());
} else {
vo.setApplyUser(null);
}
CsLinePO linePO = csLineFeignClient.getById(item.getLineId()).getData();
DevDetailDTO devDetailDTO = csLedgerFeignClient.queryDevDetail(linePO.getDeviceId()).getData();
vo.setLineName(linePO.getName());
@@ -231,9 +247,10 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
vo.setEngineeringName(devDetailDTO.getEngineeringName());
result.add(vo);
page.setRecords(result);
});
}
return result;
return page;
}
@Override
@@ -267,6 +284,7 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
List<CsLinePO> lineList = csLineFeignClient.queryLineById(lineIdList).getData();
Map<String,CsLinePO> lineMap = lineList.stream().collect(Collectors.toMap(CsLinePO::getLineId, item->item));
Map<String, AreaLineInfoVO> map = new HashMap<>();
AtomicReference<String> lineName = new AtomicReference<>();
eventList.forEach(item->{
CsLinePO po = lineMap.get(item.getLineId());
AreaLineInfoVO vo = new AreaLineInfoVO();
@@ -277,6 +295,7 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
vo.setIp(devDetailDTO.getDevMac());
vo.setLineId(po.getLineId());
vo.setNum(Objects.isNull(po.getLineNo())?po.getClDid():po.getLineNo());
lineName.set(po.getName());
vo.setLineName(po.getName());
vo.setPt1(po.getPtRatio().intValue());
vo.setPt2(Objects.isNull(po.getPt2Ratio())?1:po.getPt2Ratio().intValue());
@@ -286,7 +305,8 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
map.put(item.getId(),vo);
});
//step2: 生成事件报告
String filePath = commMonitorEventReportService.saveStableEventReport(eventIdList,map);
String fileName = "暂降事件报告_" + lineName.get() + LocalDateTime.now().format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN)) + ".docx";
String filePath = commMonitorEventReportService.saveStableEventReport(eventIdList,map,fileName);
//step3: 存储文件服务器
report.setFilePath(filePath);
return this.updateById(report);
@@ -378,39 +398,27 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
return ranges;
}
private List<TimeRange> splitIntoWeeks(LocalDate startDate, LocalDate endDate) {
List<TimeRange> weekRanges = new java.util.ArrayList<>();
LocalDate currentStart = startDate;
private List<TimeRange> splitIntoMonthsForCurrentYear(LocalDate endDate) {
List<TimeRange> timeRanges = new ArrayList<>();
LocalDate now = LocalDate.now();
int currentYear = now.getYear();
while (!currentStart.isAfter(endDate)) {
LocalDate currentEnd = currentStart.with(DayOfWeek.SUNDAY);
if (currentEnd.isAfter(endDate)) {
currentEnd = endDate;
for (int month = now.getMonthValue(); month >= 1; month--) {
LocalDate monthStart = LocalDate.of(currentYear, month, 1);
LocalDate monthEnd;
if (month == now.getMonthValue()) {
monthEnd = now;
} else {
monthEnd = monthStart.withDayOfMonth(monthStart.lengthOfMonth());
}
weekRanges.add(new TimeRange(currentStart, currentEnd));
currentStart = currentEnd.plusDays(1);
timeRanges.add(new TimeRange(monthStart, monthEnd));
}
return weekRanges;
}
private List<TimeRange> splitIntoMonths(LocalDate startDate, LocalDate endDate) {
List<TimeRange> timeRanges = new java.util.ArrayList<>();
LocalDate currentStart = startDate.withDayOfMonth(1);
while (!currentStart.isAfter(endDate)) {
LocalDate currentEnd = currentStart.withDayOfMonth(currentStart.lengthOfMonth());
if (currentEnd.isAfter(endDate)) {
currentEnd = endDate;
}
timeRanges.add(new TimeRange(currentStart, currentEnd));
currentStart = currentEnd.plusDays(1);
}
return timeRanges;
}
//fixme 代码较为冗余,后期可以采用反射的方式进行优化
private String buildOverLimitDesc(List<RStatLimitRateDPO> dataList) {
String tag = "";

View File

@@ -0,0 +1,24 @@
package com.njcn.cssystem.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.cssystem.api.fallback.AppMsgSetFeignClientFallbackFactory;
import com.njcn.cssystem.api.fallback.FeedBackFeignClientFallbackFactory;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_SYSTEM_BOOT, path = "/appMsgSet", fallbackFactory = AppMsgSetFeignClientFallbackFactory.class,contextId = "appMsgSet")
public interface AppMsgSetFeignClient {
@PostMapping("/queryUserIdsByDeviceId")
@ApiOperation("根据设备ID查询用户列表")
HttpResult<List<String>> queryUserIdsByDeviceId(@RequestParam("deviceId") @Validated String deviceId);
}

View File

@@ -0,0 +1,36 @@
package com.njcn.cssystem.api.fallback;
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.cssystem.api.AppMsgSetFeignClient;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author xy
*/
@Slf4j
@Component
public class AppMsgSetFeignClientFallbackFactory implements FallbackFactory<AppMsgSetFeignClient> {
@Override
public AppMsgSetFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new AppMsgSetFeignClient() {
@Override
public HttpResult<List<String>> queryUserIdsByDeviceId(String deviceId) {
log.error("{}异常,降级处理,异常为:{}","根据设备ID查询用户列表数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

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