diff --git a/carry_capacity/pom.xml b/carry_capacity/pom.xml new file mode 100644 index 0000000..742cb4e --- /dev/null +++ b/carry_capacity/pom.xml @@ -0,0 +1,175 @@ + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + com.njcn + carry_capacity + + + + + + + + + + + + + + + + + + + com.njcn + common-redis + 1.0.0 + + + com.njcn + common-core + + + + + + com.alibaba + fastjson + 1.2.83 + + + + cn.afterturn + easypoi-spring-boot-starter + 4.4.0 + + + + + + + + com.njcn + common-db + ${project.version} + + + + com.njcn + pqs-influx + ${project.version} + + + com.alibaba + easyexcel + 3.0.5 + + + + com.google.guava + guava + 32.1.3-jre + + + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.1.2.RELEASE + + + org.springframework.security + spring-security-oauth2-jose + + + + + + com.github.penggle + kaptcha + 2.3.2 + + + org.springframework.boot + spring-boot-starter-validation + 2.3.12.RELEASE + + + + + com.njcn + common-web + ${project.version} + + + common-microservice + com.njcn + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + package + + repackage + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + + + src/main/resources + true + + + **/*.jks + **/*.keystore + **/*.p12 + + + + + src/main/resources + false + + **/*.jks + **/*.keystore + **/*.p12 + + + + + src/main/java + + **/*.xml + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/CarryCapacityApplication.java b/carry_capacity/src/main/java/com/njcn/product/CarryCapacityApplication.java new file mode 100644 index 0000000..4cc42c5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/CarryCapacityApplication.java @@ -0,0 +1,33 @@ +package com.njcn.product; + +import com.njcn.web.advice.ResponseAdvice; +import com.njcn.web.config.FeignConfig; +import com.njcn.web.exception.GlobalBusinessExceptionHandler; +import com.njcn.web.service.ILogService; +import com.njcn.web.service.impl.LogServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.FilterType; + +@Slf4j +@DependsOn("proxyMapperRegister") +@SpringBootApplication(scanBasePackages = "com.njcn") +@MapperScan("com.njcn.**.mapper") +@ComponentScan( + basePackages = "com.njcn", + excludeFilters = @ComponentScan.Filter( + type = FilterType.ASSIGNABLE_TYPE, + classes ={ FeignConfig.class, ILogService.class, GlobalBusinessExceptionHandler.class, ResponseAdvice.class} + ) +) +public class CarryCapacityApplication { + + public static void main(String[] args) { + SpringApplication.run(CarryCapacityApplication.class, args); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/config/AuthorizationServerConfig.java b/carry_capacity/src/main/java/com/njcn/product/auth/config/AuthorizationServerConfig.java new file mode 100644 index 0000000..39b7230 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/config/AuthorizationServerConfig.java @@ -0,0 +1,234 @@ +package com.njcn.product.auth.config; + + +import cn.hutool.core.util.StrUtil; + +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.enums.auth.ClientEnum; +import com.njcn.product.auth.filter.CustomClientCredentialsTokenEndpointFilter; +import com.njcn.product.auth.pojo.bo.BusinessUser; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.security.clientdetails.ClientDetailsServiceImpl; +import com.njcn.product.auth.security.granter.CaptchaTokenGranter; +import com.njcn.product.auth.security.granter.PreAuthenticatedUserDetailsService; +import com.njcn.product.auth.security.granter.SmsTokenGranter; +import com.njcn.product.auth.service.UserDetailsServiceImpl; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.utils.WebUtil; +import lombok.AllArgsConstructor; +import lombok.SneakyThrows; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.CompositeTokenGranter; +import org.springframework.security.oauth2.provider.TokenGranter; +import org.springframework.security.oauth2.provider.token.DefaultTokenServices; +import org.springframework.security.oauth2.provider.token.TokenEnhancer; +import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; + +import java.security.KeyPair; +import java.util.*; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年05月11日 13:16 + */ +@Configuration +@AllArgsConstructor +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + + private final AuthenticationManager authenticationManager; + + private final ClientDetailsServiceImpl clientDetailsService; + + private final UserDetailsServiceImpl userDetailsService; + + private final PasswordEncoder passwordEncoder; + + private final RedisUtil redisUtil; + + + /** + * 客户端信息配置 + */ + @Override + @SneakyThrows + public void configure(ClientDetailsServiceConfigurer clients) { + clients.withClientDetails(clientDetailsService); + } + + /** + * 配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services) + */ + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) { + TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); + List tokenEnhancers = new ArrayList<>(); + tokenEnhancers.add(tokenEnhancer()); + tokenEnhancers.add(jwtAccessTokenConverter()); + tokenEnhancerChain.setTokenEnhancers(tokenEnhancers); + // 获取原有默认授权模式(授权码模式、密码模式、客户端模式、简化模式)的授权者 + List granterList = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter())); + + // 添加验证码授权模式授权者 + granterList.add(new CaptchaTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), + endpoints.getOAuth2RequestFactory(), authenticationManager, redisUtil + )); + // 添加短信授权模式授权者 + granterList.add(new SmsTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), + endpoints.getOAuth2RequestFactory(), authenticationManager, redisUtil + )); + //todo... 后续可以扩展更多授权模式,比如:微信小程序、移动app + CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(granterList); + endpoints.authenticationManager(authenticationManager) + .accessTokenConverter(jwtAccessTokenConverter()) + //设置grant_type类型集合 + .tokenEnhancer(tokenEnhancerChain) + .tokenGranter(compositeTokenGranter) + /* + * refresh_token有两种使用方式:重复使用(true)、非重复使用(false),默认为true + * 1.重复使用:access_token过期刷新时, refresh token过期时间未改变,仍以初次生成的时间为准 + * 2.非重复使用:access_token过期刷新时, refresh_token过期时间延续,在refresh_token有效期内刷新而无需失效再次登录 + */ + .reuseRefreshTokens(true) + .tokenServices(tokenServices(endpoints)); + } + + + + public DefaultTokenServices tokenServices(AuthorizationServerEndpointsConfigurer endpoints) { + TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); + List tokenEnhancers = new ArrayList<>(); + tokenEnhancers.add(tokenEnhancer()); + tokenEnhancers.add(jwtAccessTokenConverter()); + tokenEnhancerChain.setTokenEnhancers(tokenEnhancers); + + DefaultTokenServices tokenServices = new DefaultTokenServices(); + tokenServices.setTokenStore(endpoints.getTokenStore()); + tokenServices.setSupportRefreshToken(true); + tokenServices.setClientDetailsService(clientDetailsService); + tokenServices.setTokenEnhancer(tokenEnhancerChain); + + // 多用户体系下,刷新token再次认证客户端ID和 UserDetailService 的映射Map + Map clientUserDetailsServiceMap = new HashMap<>(16); + + // 系统管理客户端 + clientUserDetailsServiceMap.put(ClientEnum.WEB_CLIENT.getClientId(), userDetailsService); + clientUserDetailsServiceMap.put(ClientEnum.WEB_CLIENT_TEST.getClientId(), userDetailsService); + clientUserDetailsServiceMap.put(ClientEnum.APP_CLIENT.getClientId(), userDetailsService); + clientUserDetailsServiceMap.put(ClientEnum.SCREEN_CLIENT.getClientId(), userDetailsService); + clientUserDetailsServiceMap.put(ClientEnum.WE_CHAT_APP_CLIENT.getClientId(), userDetailsService); + + //todo .. 后面扩展微信小程序、app实现服务 + // 刷新token模式下,重写预认证提供者替换其AuthenticationManager,可自定义根据客户端ID和认证方式区分用户体系获取认证用户信息 + PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider(); + provider.setPreAuthenticatedUserDetailsService(new PreAuthenticatedUserDetailsService<>(clientUserDetailsServiceMap)); + tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider))); + return tokenServices; + + } + + /** + * 使用非对称加密算法对token签名 + */ + @Bean + public JwtAccessTokenConverter jwtAccessTokenConverter() { + JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); + converter.setKeyPair(keyPair()); + return converter; + } + + /** + * 从classpath下的密钥库中获取密钥对(公钥+私钥) + */ + @Bean + public KeyPair keyPair() { + KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("njcn.jks"), "njcnpqs".toCharArray()); + return factory.getKeyPair("njcn", "njcnpqs".toCharArray()); + } + + + + + /** + * 自定义认证异常响应数据 + */ + @Bean + public AuthenticationEntryPoint authenticationEntryPoint() { + return (request, response, e) -> { + WebUtil.responseInfo(response, UserResponseEnum.CLIENT_AUTHENTICATION_FAILED.getCode(), UserResponseEnum.CLIENT_AUTHENTICATION_FAILED.getMessage()); + }; + } + + + /** + * JWT内容增强 + */ + @Bean + public TokenEnhancer tokenEnhancer() { + return (accessToken, authentication) -> { + String clientId = authentication.getOAuth2Request().getClientId(); + BusinessUser user = (BusinessUser) authentication.getUserAuthentication().getPrincipal(); + Map map = new HashMap<>(8); + map.put(SecurityConstants.USER_INDEX_KEY, user.getUserIndex()); + map.put(SecurityConstants.USER_TYPE, user.getType()); + map.put(SecurityConstants.USER_NICKNAME_KEY, user.getNickName()); + map.put(SecurityConstants.CLIENT_ID_KEY, clientId); + map.put(SecurityConstants.DEPT_INDEX_KEY, user.getDeptIndex()); + map.put(SecurityConstants.USER_HEAD_KEY, user.getHeadSculpture()); + if (StrUtil.isNotBlank(user.getAuthenticationMethod())) { + map.put(SecurityConstants.AUTHENTICATION_METHOD, user.getAuthenticationMethod()); + } + ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map); + return accessToken; + }; + } + + + /** + * 配置自定义密码认证过滤器 + * @param security . + */ + @Override + public void configure(AuthorizationServerSecurityConfigurer security) { + CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security); + endpointFilter.afterPropertiesSet(); + endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint()); + security.addTokenEndpointAuthenticationFilter(endpointFilter); + + security + .authenticationEntryPoint(authenticationEntryPoint()) + /* .allowFormAuthenticationForClients()*/ //如果使用表单认证则需要加上 + .tokenKeyAccess("permitAll()") + .checkTokenAccess("isAuthenticated()"); + } + + + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setHideUserNotFoundExceptions(false); + provider.setUserDetailsService(userDetailsService); + provider.setPasswordEncoder(passwordEncoder); + return provider; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/config/WebSecurityConfig.java b/carry_capacity/src/main/java/com/njcn/product/auth/config/WebSecurityConfig.java new file mode 100644 index 0000000..4ce2e43 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/config/WebSecurityConfig.java @@ -0,0 +1,110 @@ +package com.njcn.product.auth.config; + + +import com.njcn.product.auth.filter.AuthGlobalFilter; +import com.njcn.product.auth.security.provider.Sm4AuthenticationProvider; +import com.njcn.product.auth.security.provider.SmsAuthenticationProvider; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +/** + * @author hongawen + */ +@Slf4j +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private final UserDetailsService sysUserDetailsService; + + private final Sm4AuthenticationProvider sm4AuthenticationProvider; + + private final SmsAuthenticationProvider smsAuthenticationProvider; + private final AuthGlobalFilter authGlobalFilter; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/user/generateSm2Key","/oauth/token","/theme/getTheme").permitAll() + .antMatchers("/webjars/**","/doc.html","/swagger-resources/**","/v2/api-docs").permitAll() + .anyRequest().authenticated() + .and() + .csrf().disable(); + http.addFilterAfter(authGlobalFilter, UsernamePasswordAuthenticationFilter.class); + + } + + /** + * 认证管理对象 + * + * @throws Exception . + * @return . + */ + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + + + @Override + public void configure(AuthenticationManagerBuilder auth) { + auth.authenticationProvider(daoAuthenticationProvider()); + } + + + + /** + * 重写父类自定义AuthenticationManager 将provider注入进去 + * 当然我们也可以考虑不重写 在父类的manager里面注入provider + */ + @Bean + @Override + protected AuthenticationManager authenticationManager(){ + return new ProviderManager(sm4AuthenticationProvider,smsAuthenticationProvider); + } + + + + /** + * 用户名密码认证授权提供者 + */ + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(sysUserDetailsService); + provider.setPasswordEncoder(passwordEncoder()); + // 是否隐藏用户不存在异常,默认:true-隐藏;false-抛出异常; + provider.setHideUserNotFoundExceptions(false); + return provider; + } + + /** + * 密码编码器 + *

+ * 委托方式,根据密码的前缀选择对应的encoder,例如:{bcypt}前缀->标识BCYPT算法加密;{noop}->标识不使用任何加密即明文的方式 + * 密码判读 DaoAuthenticationProvider#additionalAuthenticationChecks + */ + @Bean + public PasswordEncoder passwordEncoder() { + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/controller/AuthController.java b/carry_capacity/src/main/java/com/njcn/product/auth/controller/AuthController.java new file mode 100644 index 0000000..277fc40 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/controller/AuthController.java @@ -0,0 +1,222 @@ +package com.njcn.product.auth.controller; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.RSAKey; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.LogInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.dto.UserTokenInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.common.utils.LogUtil; +import com.njcn.common.utils.sm.DesUtils; +import com.njcn.common.utils.sm.Sm2; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.service.IUserService; +import com.njcn.product.auth.service.UserTokenService; +import com.njcn.product.auth.utils.AuthPubUtil; +import com.njcn.redis.utils.RedisUtil; + +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.RequestUtil; +import com.njcn.web.utils.RestTemplateUtil; +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.apache.commons.collections.CollectionUtils; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.util.UriComponentsBuilder; +import springfox.documentation.annotations.ApiIgnore; + +import javax.servlet.http.HttpServletRequest; +import java.net.URI; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.interfaces.RSAPublicKey; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author hongawen + */ +@Api(tags = "认证中心") +@Slf4j +@RestController +@RequestMapping("/oauth") +@AllArgsConstructor +public class AuthController extends BaseController { + + + private final TokenEndpoint tokenEndpoint; + + private final KeyPair keyPair; + + private final RedisUtil redisUtil; + + private final IUserService userService; + + + private final UserTokenService userTokenService; + + + @ApiIgnore + @OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.AUTHENTICATE) + @ApiOperation("登录认证") + @ApiImplicitParams({ + @ApiImplicitParam(name = SecurityConstants.GRANT_TYPE, defaultValue = "password", value = "授权模式", required = true), + @ApiImplicitParam(name = SecurityConstants.CLIENT_ID, defaultValue = "njcn", value = "Oauth2客户端ID", required = true), + @ApiImplicitParam(name = SecurityConstants.CLIENT_SECRET, defaultValue = "njcnpqs", value = "Oauth2客户端秘钥", required = true), + @ApiImplicitParam(name = SecurityConstants.REFRESH_TOKEN, value = "刷新token"), + @ApiImplicitParam(name = SecurityConstants.USERNAME, value = "登录用户名"), + @ApiImplicitParam(name = SecurityConstants.PASSWORD, value = "登录密码"), + @ApiImplicitParam(name = SecurityConstants.IMAGE_CODE, value = "图形验证码"), + @ApiImplicitParam(name = SecurityConstants.PHONE, value = "手机号"), + @ApiImplicitParam(name = SecurityConstants.SMS_CODE, value = "短信验证码"), + }) + @PostMapping("/token") + public Object postAccessToken(@ApiIgnore Principal principal, @RequestParam @ApiIgnore Map parameters) throws HttpRequestMethodNotSupportedException { + String methodDescribe = getMethodDescribe("postAccessToken"); + String username = parameters.get(SecurityConstants.USERNAME); + + + String grantType = parameters.get(SecurityConstants.GRANT_TYPE); + if (grantType.equalsIgnoreCase(SecurityConstants.GRANT_CAPTCHA) || grantType.equalsIgnoreCase(SecurityConstants.REFRESH_TOKEN_KEY)) { + username = DesUtils.aesDecrypt(username); + } else if (grantType.equalsIgnoreCase(SecurityConstants.GRANT_SMS_CODE)) { + //短信方式登录,将手机号赋值为用户名 + username = parameters.get(SecurityConstants.PHONE); + } + + + + if (grantType.equalsIgnoreCase(SecurityConstants.REFRESH_TOKEN_KEY)) { + //如果是刷新token,需要去黑名单校验 + userTokenService.judgeRefreshToken(parameters.get(SecurityConstants.REFRESH_TOKEN_KEY)); + } + RequestUtil.saveLoginName(username); + OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody(); + //用户的登录名&密码校验成功后,判断当前该用户是否可以正常使用系统 + if (!grantType.equalsIgnoreCase(SecurityConstants.GRANT_SMS_CODE)) { + userService.judgeUserStatus(username); + } + //登录成功后,记录token信息,并处理踢人效果 + userTokenService.recordUserInfo(oAuth2AccessToken, RequestUtil.getRealIp()); + if (!grantType.equalsIgnoreCase(SecurityConstants.PASSWORD)) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, oAuth2AccessToken, methodDescribe); + } else { + return oAuth2AccessToken; + } + } + + @OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.LOGOUT) + @ApiOperation("用户登出系统") + @DeleteMapping("/logout") + public HttpResult logout() { + String methodDescribe = getMethodDescribe("logout"); + String userIndex = RequestUtil.getUserIndex(); + String username = RequestUtil.getUsername(); + LogUtil.njcnDebug(log, "{},用户名为:{}", methodDescribe, username); + String blackUserKey = SecurityConstants.TOKEN_BLACKLIST_PREFIX + userIndex; + String onlineUserKey = SecurityConstants.TOKEN_ONLINE_PREFIX + userIndex; + Object onlineTokenInfoOld = redisUtil.getObjectByKey(onlineUserKey); + List blackUsers = (List) redisUtil.getObjectByKey(blackUserKey); + UserTokenInfo userTokenInfo; + if (!Objects.isNull(onlineTokenInfoOld)) { + //清除在线token信息 + redisUtil.delete(onlineUserKey); + userTokenInfo = (UserTokenInfo) onlineTokenInfoOld; + if (CollectionUtils.isEmpty(blackUsers)) { + blackUsers = new ArrayList<>(); + } + blackUsers.add(userTokenInfo); + LocalDateTime refreshTokenExpire = userTokenInfo.getRefreshTokenExpire(); + long lifeTime = Math.abs(refreshTokenExpire.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); + redisUtil.saveByKeyWithExpire(blackUserKey, blackUsers, lifeTime); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + /** + * 文档隐藏该接口 + */ + @ApiIgnore + @ApiOperation("RSA公钥获取接口") + @GetMapping("/getPublicKey") + public Map getPublicKey() { + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + RSAKey key = new RSAKey.Builder(publicKey).build(); + return new JWKSet(key).toJSONObject(); + } + + /** + * 自动登录 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.AUTHENTICATE) + @ApiOperation("自动登录") + @PostMapping("/autoLogin") + @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query") + @ApiIgnore + public HttpResult autoLogin(@RequestParam String phone) { + String methodDescribe = getMethodDescribe("autoLogin"); + String userUrl = "http://127.0.0.1:10214/oauth/token"; + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(userUrl) + .queryParam("grant_type", "sms_code") + .queryParam("client_id", "njcnapp") + .queryParam("client_secret", "njcnpqs") + .queryParam("phone", phone) + .queryParam("smsCode", "123456789"); + URI uri = builder.build().encode().toUri(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, Objects.requireNonNull(RestTemplateUtil.post(uri, HttpResult.class).getBody()).getData(), methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/generateSm2Key") + @ApiOperation("根据登录名获取公钥") + @ApiImplicitParam(name = "loginName", value = "登录名", required = true) + public HttpResult generateSm2Key(String loginName, @ApiIgnore HttpServletRequest request) { + System.out.println("request1==:" + request); + if (StrUtil.isBlankIfStr(loginName)) { + RequestUtil.saveLoginName(LogInfo.UNKNOWN_USER); + throw new BusinessException(UserResponseEnum.LOGIN_USERNAME_INVALID); + } + String methodDescribe = getMethodDescribe("generateSm2Key"); + loginName = DesUtils.aesDecrypt(loginName); + RequestUtil.saveLoginName(loginName); + Map keyMap; + try { + keyMap = Sm2.getSm2CipHer(); + } catch (NoSuchAlgorithmException e) { + throw new BusinessException(CommonResponseEnum.SM2_CIPHER_ERROR); + } + String publicKey = keyMap.get("publicKey"); + String privateKey = keyMap.get("privateKey"); + String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP); + + if (redisUtil.hasKey(loginName + ip)) { + //秘钥先删除再添加 + redisUtil.delete(loginName + ip); + } + // 保存私钥到 redis + redisUtil.saveByKeyWithExpire(loginName + ip, privateKey, 5 * 60L); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, publicKey, methodDescribe); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/controller/JudgeThirdToken.java b/carry_capacity/src/main/java/com/njcn/product/auth/controller/JudgeThirdToken.java new file mode 100644 index 0000000..644f1a2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/controller/JudgeThirdToken.java @@ -0,0 +1,121 @@ +package com.njcn.product.auth.controller; + +import cn.hutool.json.JSONObject; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.DataStateEnum; +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.common.utils.LogUtil; +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.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年04月27日 11:22 + */ +@Slf4j +@RestController +@AllArgsConstructor +@Api(tags = "校验第三方token") +@RequestMapping("/judgeToken") +public class JudgeThirdToken extends BaseController { + + /** + * 校验广州超高压token有效性 + * + * @param token token数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/guangZhou") + @ApiOperation("校验广州超高压token有效性") + @ApiImplicitParam(name = "token", required = true) + public HttpResult guangZhou(String token) { + RestTemplate restTemplate = new RestTemplate(); + String methodDescribe = getMethodDescribe("guangZhou"); + LogUtil.njcnDebug(log, "{},token:{}", methodDescribe, token); + + // 请求地址 + String url = "http://10.121.17.9:9080/ehv/auth_valid"; + + // 请求头设置,x-www-form-urlencoded格式的数据 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + //提交参数设置 + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("token", token); + + // 组装请求体 + HttpEntity> request = + new HttpEntity<>(map, headers); + + // 发送post请求,并打印结果,以String类型接收响应结果JSON字符串 + String result = restTemplate.postForObject(url, request, String.class); + JSONObject resultJson = new JSONObject(result); + if (Objects.equals(resultJson.getInt("status"), DataStateEnum.ENABLE.getCode())) { + //成功 + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/heBei") + @ApiOperation("校验河北token有效性") + @ApiImplicitParam(name = "token", required = true) + public HttpResult heBei(String token) { + RestTemplate restTemplate = new RestTemplate(); + String methodDescribe = getMethodDescribe("heBei"); + LogUtil.njcnDebug(log, "{},token:{}", methodDescribe, token); + + /* // 请求地址 + String url = "http://dwzyywzt-test.com/baseCenter/oauth2/user/token"; + + // 请求头设置,x-www-form-urlencoded格式的数据 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + + //提交参数设置 + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("token", token); + + // 组装请求体 + HttpEntity> request = + new HttpEntity<>(map, headers); + + // 发送post请求,并打印结果,以String类型接收响应结果JSON字符串 + String result = restTemplate.postForObject(url, request, String.class); + JSONObject resultJson = new JSONObject(result); + if (Objects.equals(resultJson.getInt("status"), DataStateEnum.ENABLE.getCode())) { + //成功 + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + }*/ + + + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, "HE_DNZLJCYW", methodDescribe); + + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/controller/KaptchaController.java b/carry_capacity/src/main/java/com/njcn/product/auth/controller/KaptchaController.java new file mode 100644 index 0000000..e0ae932 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/controller/KaptchaController.java @@ -0,0 +1,80 @@ +package com.njcn.product.auth.controller; + +import cn.hutool.core.io.IoUtil; +import com.google.code.kaptcha.Producer; +import com.google.code.kaptcha.util.Config; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.product.auth.utils.AuthPubUtil; +import com.njcn.redis.utils.RedisUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import springfox.documentation.annotations.ApiIgnore; + +import javax.imageio.ImageIO; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.Properties; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年06月04日 15:25 + */ +@Api(tags = "认证中心") +@Slf4j +@Controller +@RequestMapping("/auth") +@AllArgsConstructor +public class KaptchaController { + + private final RedisUtil redisUtil; + + @ApiIgnore + @ApiOperation("获取图形验证码") + @GetMapping("/getImgCode") + public void getImgCode(@ApiIgnore HttpServletResponse resp, @ApiIgnore HttpServletRequest request) { + ServletOutputStream out = null; + try { + out = resp.getOutputStream(); +// resp.setContentType("image/jpeg");"/pqs-auth/auth/getImgCode", + if (null != out) { + Properties props = new Properties(); + Producer kaptchaProducer; + ImageIO.setUseCache(false); + props.put("kaptcha.border", "no"); + props.put("kaptcha.textproducer.font.color", "black"); + /*props.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");*/ + /*props.put("kaptcha.noise.impl", "com.sso.utils.ComplexNoise");*/ + props.put("kaptcha.textproducer.char.space", "5"); + props.put("kaptcha.textproducer.char.length", "4"); + Config config = new Config(props); + kaptchaProducer = config.getProducerImpl(); + //此处需要固定采用字母和数字混合 + String capText = AuthPubUtil.getKaptchaText(4); + String userAgent = request.getHeader(HttpHeaders.USER_AGENT); + String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP); + String key = userAgent + ip; + redisUtil.delete(key); + redisUtil.saveByKeyWithExpire(key, capText, 30*60L); + BufferedImage bi = kaptchaProducer.createImage(capText); + ImageIO.write(bi, "jpg", out); + out.flush(); + } + } catch (IOException ioException) { + log.error("获取图形验证码异常,异常为:{}", ioException.toString()); + } finally { + IoUtil.close(out); + } + + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/controller/UserController.java b/carry_capacity/src/main/java/com/njcn/product/auth/controller/UserController.java new file mode 100644 index 0000000..fa4c4ca --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/controller/UserController.java @@ -0,0 +1,203 @@ +package com.njcn.product.auth.controller; + + +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.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.LogInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.common.utils.LogUtil; +import com.njcn.common.utils.sm.DesUtils; +import com.njcn.common.utils.sm.Sm2; + +import com.njcn.product.auth.pojo.dto.UserDTO; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.pojo.param.UserParam; +import com.njcn.product.auth.pojo.po.User; +import com.njcn.product.auth.pojo.vo.UserVO; +import com.njcn.product.auth.service.IUserService; +import com.njcn.redis.utils.RedisUtil; +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; +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 org.springframework.web.multipart.MultipartFile; +import springfox.documentation.annotations.ApiIgnore; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/user") +@Api(tags = "用户信息管理") +@AllArgsConstructor +public class UserController extends BaseController { + + private final IUserService userService; + + private final RedisUtil redisUtil; + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getUserByName/{loginName}") + @ApiOperation("根据登录名查询用户信息") + @ApiImplicitParam(name = "loginName", value = "登录名", required = true) + public HttpResult getUserByName(@PathVariable String loginName) { + RequestUtil.saveLoginName(loginName); + String methodDescribe = getMethodDescribe("getUserByName"); + LogUtil.njcnDebug(log, "{},登录名为:{}", methodDescribe, loginName); + UserDTO user = userService.getUserByName(loginName); + if (Objects.isNull(user)) { + throw new BusinessException(UserResponseEnum.LOGIN_WRONG_PWD); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, user, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @ApiIgnore + @GetMapping("/getUserByPhone/{phone}") + @ApiOperation("根据手机号查询用户信息") + @ApiImplicitParam(name = "phone", value = "手机号", required = true) + public HttpResult getUserByPhone(@PathVariable String phone) { + RequestUtil.saveLoginName(phone); + String methodDescribe = getMethodDescribe("getUserByPhone"); + LogUtil.njcnDebug(log, "{},手机号为:{}", methodDescribe, phone); + UserDTO user = userService.loadUserByPhone(phone); + if (Objects.isNull(user)) { + throw new BusinessException(UserResponseEnum.LOGIN_PHONE_NOT_REGISTER); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, user, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/judgeUserStatus/{loginName}") + @ApiOperation("认证后根据用户名判断用户状态") + @ApiImplicitParam(name = "loginName", value = "登录名", required = true) + public HttpResult judgeUserStatus(@PathVariable String loginName) { + RequestUtil.saveLoginName(loginName); + String methodDescribe = getMethodDescribe("judgeUserStatus"); + LogUtil.njcnDebug(log, "{},登录名为:{}", methodDescribe, loginName); + userService.judgeUserStatus(loginName); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } + + + + + + + /** + * 根据用户id获取用户详情 + * + * @param id 用户id + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getUserById") + @ApiOperation("用户详情") + @ApiImplicitParam(name = "id", value = "用户id", required = true) + public HttpResult getUserById(@RequestParam @Validated String id) { + String methodDescribe = getMethodDescribe("getUserById"); + LogUtil.njcnDebug(log, "{},用户id为:{}", methodDescribe, id); + UserVO userVO = userService.getUserById(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, userVO, methodDescribe); + } + + + + + + + + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/generateSm2Key") + @ApiOperation("根据登录名获取公钥") + @ApiImplicitParam(name = "loginName", value = "登录名", required = true) + public HttpResult generateSm2Key(String loginName, @ApiIgnore HttpServletRequest request) { + System.out.println("request1==:" + request); + if (StrUtil.isBlankIfStr(loginName)) { + RequestUtil.saveLoginName(LogInfo.UNKNOWN_USER); + throw new BusinessException(UserResponseEnum.LOGIN_USERNAME_INVALID); + } + String methodDescribe = getMethodDescribe("generateSm2Key"); + loginName = DesUtils.aesDecrypt(loginName); + RequestUtil.saveLoginName(loginName); + Map keyMap; + try { + keyMap = Sm2.getSm2CipHer(); + } catch (NoSuchAlgorithmException e) { + throw new BusinessException(CommonResponseEnum.SM2_CIPHER_ERROR); + } + String publicKey = keyMap.get("publicKey"); + String privateKey = keyMap.get("privateKey"); + String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP); + + if (redisUtil.hasKey(loginName + ip)) { + //秘钥先删除再添加 + redisUtil.delete(loginName + ip); + } + // 保存私钥到 redis + redisUtil.saveByKeyWithExpire(loginName + ip, privateKey, 5 * 60L); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, publicKey, methodDescribe); + } + + @OperateInfo(operateType = OperateType.UPDATE, info = LogEnum.SYSTEM_SERIOUS) + @PutMapping("/updateUserLoginErrorTimes/{loginName}") + @ApiOperation("更新用户登录认证密码错误次数") + @ApiImplicitParam(name = "loginName", value = "登录名", required = true) + public HttpResult updateUserLoginErrorTimes(@PathVariable String loginName) { + RequestUtil.saveLoginName(loginName); + String methodDescribe = getMethodDescribe("updateUserLoginErrorTimes"); + LogUtil.njcnDebug(log, "{},登录名为:{}", methodDescribe, loginName); + String result = userService.updateUserLoginErrorTimes(loginName); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + /** + * 查询所有用户包含管理员 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getAllUserSimpleList") + @ApiOperation("查询所有用户作为下拉框") + public HttpResult getAllUserSimpleList() { + String methodDescribe = getMethodDescribe("getAllUserSimpleList"); + List result = userService.simpleList(true); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/exception/AuthExceptionHandler.java b/carry_capacity/src/main/java/com/njcn/product/auth/exception/AuthExceptionHandler.java new file mode 100644 index 0000000..5f05878 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/exception/AuthExceptionHandler.java @@ -0,0 +1,93 @@ +package com.njcn.product.auth.exception; + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.nimbusds.jose.JWSObject; +import com.njcn.common.pojo.constant.LogInfo; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; + +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.service.IUserService; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; +import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年05月17日 12:46 + */ +@Slf4j +@RestControllerAdvice +@RequiredArgsConstructor +@Order(Ordered.HIGHEST_PRECEDENCE) +public class AuthExceptionHandler { + + private final IUserService userService; + +// private final ILogService logService; + + /** + * 用户名和密码非法 + */ + @ExceptionHandler(InvalidGrantException.class) + public HttpResult handleInvalidGrantException(HttpServletRequest httpServletRequest, InvalidGrantException invalidGrantException) { + String loginName = invalidGrantException.getMessage(); + log.error("捕获用户名密码错误"); + String result = userService.updateUserLoginErrorTimes(loginName); + if (result.equals(UserResponseEnum.LOGIN_USER_LOCKED.getMessage())) { +// logService.recodeAuthExceptionLog(invalidGrantException, httpServletRequest, UserResponseEnum.LOGIN_USER_LOCKED.getMessage(), loginName); + return HttpResultUtil.assembleResult(UserResponseEnum.LOGIN_USER_LOCKED.getCode(), null, UserResponseEnum.LOGIN_USER_LOCKED.getMessage()); + } else { +// logService.recodeAuthExceptionLog(invalidGrantException, httpServletRequest, UserResponseEnum.LOGIN_WRONG_PWD.getMessage(), loginName); + return HttpResultUtil.assembleResult(UserResponseEnum.LOGIN_WRONG_PWD.getCode(), null, UserResponseEnum.LOGIN_WRONG_PWD.getMessage()); + } + } + + + /** + * 不支持的认证方式 + *

+ * 不支持的认证方式 目前支持:用户名密码:password、刷新token:refresh-token + */ + @ExceptionHandler(UnsupportedGrantTypeException.class) + public HttpResult unsupportedGrantTypeExceptionException(HttpServletRequest httpServletRequest, UnsupportedGrantTypeException unsupportedGrantTypeException) { + String loginName = RequestUtil.getLoginName(httpServletRequest); +// logService.recodeAuthExceptionLog(unsupportedGrantTypeException, httpServletRequest, UserResponseEnum.UNSUPPORTED_GRANT_TYPE.getMessage(), loginName); + return HttpResultUtil.assembleResult(UserResponseEnum.UNSUPPORTED_GRANT_TYPE.getCode(), null, UserResponseEnum.UNSUPPORTED_GRANT_TYPE.getMessage()); + } + + /** + * oAuth2中token校验异常 + */ + @SneakyThrows + @ExceptionHandler(InvalidTokenException.class) + public HttpResult invalidTokenExceptionException(HttpServletRequest httpServletRequest, InvalidTokenException invalidTokenException) { + final String EXPIRED_KEY = "Invalid refresh token (expired):"; + if (invalidTokenException.getMessage().startsWith(EXPIRED_KEY)) { + String message = invalidTokenException.getMessage(); + message = message.substring(EXPIRED_KEY.length()); + JWSObject jwsObject = JWSObject.parse(message); + String payload = jwsObject.getPayload().toString(); + JSONObject jsonObject = JSONUtil.parseObj(payload); +// logService.recodeAuthExceptionLog(invalidTokenException, httpServletRequest, UserResponseEnum.REFRESH_TOKEN_EXPIRE_JWT.getMessage(), jsonObject.getStr(SecurityConstants.USER_NAME_KEY)); + return HttpResultUtil.assembleResult(UserResponseEnum.REFRESH_TOKEN_EXPIRE_JWT.getCode(), null, UserResponseEnum.REFRESH_TOKEN_EXPIRE_JWT.getMessage()); + } +// logService.recodeAuthExceptionLog(invalidTokenException, httpServletRequest, UserResponseEnum.PARSE_TOKEN_FORBIDDEN_JWT.getMessage(), LogInfo.UNKNOWN_USER); + return HttpResultUtil.assembleResult(UserResponseEnum.PARSE_TOKEN_FORBIDDEN_JWT.getCode(), null, UserResponseEnum.PARSE_TOKEN_FORBIDDEN_JWT.getMessage()); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/exception/GlobalBusinessExceptionHandler.java b/carry_capacity/src/main/java/com/njcn/product/auth/exception/GlobalBusinessExceptionHandler.java new file mode 100644 index 0000000..3d5abd4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/exception/GlobalBusinessExceptionHandler.java @@ -0,0 +1,256 @@ +package com.njcn.product.auth.exception; + +import cn.hutool.core.text.StrFormatter; +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.common.utils.LogUtil; +import com.njcn.common.utils.ReflectCommonUtil; +import com.njcn.web.utils.ControllerUtil; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.json.JSONException; +import org.springframework.validation.ObjectError; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.util.NestedServletException; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 全局通用业务异常处理器 + * + * @author hongawen + * @version 1.0.0 + * @date 2021年04月20日 18:04 + */ +@Slf4j +@AllArgsConstructor +@RestControllerAdvice +public class GlobalBusinessExceptionHandler { + + + + private final ThreadPoolExecutor executor = new ThreadPoolExecutor( + 4, 8, 30, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(100), + // 队列满时由主线程执行 + new ThreadPoolExecutor.CallerRunsPolicy() + ); + + + /** + * 捕获业务功能异常,通常为业务数据抛出的异常 + * + * @param businessException 业务异常 + */ + @ExceptionHandler(BusinessException.class) + public HttpResult handleBusinessException(BusinessException businessException) { + String operate = ReflectCommonUtil.getMethodDescribeByException(businessException); + // recodeBusinessExceptionLog(businessException, businessException.getMessage()); + return HttpResultUtil.assembleBusinessExceptionResult(businessException, null, operate); + } + + + /** + * 空指针异常捕捉 + * + * @param nullPointerException 空指针异常 + */ + @ExceptionHandler(NullPointerException.class) + public HttpResult handleNullPointerException(NullPointerException nullPointerException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage(), nullPointerException); + //recodeBusinessExceptionLog(nullPointerException, CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NULL_POINTER_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(nullPointerException)); + } + + /** + * 算数运算异常 + * + * @param arithmeticException 算数运算异常,由于除数为0引起的异常 + */ + @ExceptionHandler(ArithmeticException.class) + public HttpResult handleArithmeticException(ArithmeticException arithmeticException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage(), arithmeticException); + // recodeBusinessExceptionLog(arithmeticException, CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ARITHMETIC_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(arithmeticException)); + } + + /** + * 类型转换异常捕捉 + * + * @param classCastException 类型转换异常 + */ + @ExceptionHandler(ClassCastException.class) + public HttpResult handleClassCastException(ClassCastException classCastException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage(), classCastException); + // recodeBusinessExceptionLog(classCastException, CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.CLASS_CAST_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(classCastException)); + } + + + /** + * 索引下标越界异常捕捉 + * + * @param indexOutOfBoundsException 索引下标越界异常 + */ + @ExceptionHandler(IndexOutOfBoundsException.class) + public HttpResult handleIndexOutOfBoundsException(IndexOutOfBoundsException indexOutOfBoundsException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage(), indexOutOfBoundsException); + // recodeBusinessExceptionLog(indexOutOfBoundsException, CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(indexOutOfBoundsException)); + } + + /** + * 前端请求后端,请求中参数的媒体方式不支持异常 + * + * @param httpMediaTypeNotSupportedException 请求中参数的媒体方式不支持异常 + */ + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public HttpResult httpMediaTypeNotSupportedExceptionHandler(HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage(), httpMediaTypeNotSupportedException); + // 然后提取错误提示信息进行返回 + // recodeBusinessExceptionLog(httpMediaTypeNotSupportedException, CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(httpMediaTypeNotSupportedException)); + } + + /** + * 前端请求后端,参数校验异常捕捉 + * RequestBody注解参数异常 + * + * @param methodArgumentNotValidException 参数校验异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public HttpResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException) { + // 从异常对象中拿到allErrors数据 + String messages = methodArgumentNotValidException.getBindingResult().getAllErrors() + .stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";")); + // 然后提取错误提示信息进行返回 + LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages); + // recodeBusinessExceptionLog(methodArgumentNotValidException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages, ControllerUtil.getMethodArgumentNotValidException(methodArgumentNotValidException)); + } + + /** + * 前端请求后端,参数校验异常捕捉 + * PathVariable注解、RequestParam注解参数异常 + * + * @param constraintViolationException 参数校验异常 + */ + @ExceptionHandler(ConstraintViolationException.class) + public HttpResult constraintViolationExceptionExceptionHandler(ConstraintViolationException constraintViolationException) { + String exceptionMessage = constraintViolationException.getMessage(); + StringBuilder messages = new StringBuilder(); + if (exceptionMessage.indexOf(StrUtil.COMMA) > 0) { + String[] tempMessage = exceptionMessage.split(StrUtil.COMMA); + Stream.of(tempMessage).forEach(message -> { + messages.append(message.substring(message.indexOf(StrUtil.COLON) + 2)).append(';'); + }); + } else { + messages.append(exceptionMessage.substring(exceptionMessage.indexOf(StrUtil.COLON) + 2)); + } + // 然后提取错误提示信息进行返回 + LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages); + // recodeBusinessExceptionLog(constraintViolationException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage()); + List> constraintViolationList = new ArrayList<>(constraintViolationException.getConstraintViolations()); + ConstraintViolation constraintViolation = constraintViolationList.get(0); + Class rootBeanClass = constraintViolation.getRootBeanClass(); + //判断校验参数异常捕获的根源是controller还是service处 + if (rootBeanClass.getName().endsWith("Controller")) { + String methodName = constraintViolation.getPropertyPath().toString().substring(0, constraintViolation.getPropertyPath().toString().indexOf(StrUtil.DOT)); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByClassAndMethodName(rootBeanClass, methodName)); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByException(constraintViolationException)); + } + + } + + + /** + * 索引下标越界异常捕捉 + * + * @param illegalArgumentException 参数校验异常 + */ + @ExceptionHandler(IllegalArgumentException.class) + public HttpResult handleIndexOutOfBoundsException(IllegalArgumentException illegalArgumentException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), illegalArgumentException); + // recodeBusinessExceptionLog(illegalArgumentException, CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, illegalArgumentException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(illegalArgumentException)); + } + + + /** + * 未声明异常捕捉 + * + * @param exception 未声明异常 + */ + @ExceptionHandler(Exception.class) + public HttpResult handleException(Exception exception) { + //针对fallbackFactory降级异常特殊处理 + Exception tempException = exception; + String exceptionCause = CommonResponseEnum.UN_DECLARE.getMessage(); + String code = CommonResponseEnum.UN_DECLARE.getCode(); + if (exception instanceof NestedServletException) { + Throwable cause = exception.getCause(); + if (cause instanceof AssertionError) { + if (cause.getCause() instanceof BusinessException) { + tempException = (BusinessException) cause.getCause(); + BusinessException tempBusinessException = (BusinessException) cause.getCause(); + exceptionCause = tempBusinessException.getMessage(); + code = tempBusinessException.getCode(); + } + } + } + LogUtil.logExceptionStackInfo(exceptionCause, tempException); + // recodeBusinessExceptionLog(exception, exceptionCause); + //判断方法上是否有自定义注解,做特殊处理 +// Method method = ReflectCommonUtil.getMethod(exception); +// if (!Objects.isNull(method)){ +// if(method.isAnnotationPresent(ReturnMsg.class)){ +// return HttpResultUtil.assembleResult(code, null, StrFormatter.format("{}",exceptionCause)); +// } +// } + return HttpResultUtil.assembleResult(code, null, StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByException(tempException), StrUtil.C_COMMA, exceptionCause)); + } + + + /** + * json解析异常 + * + * @param jsonException json参数 + */ + @ExceptionHandler(JSONException.class) + public HttpResult handleIndexOutOfBoundsException(JSONException jsonException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage(), jsonException); + // recodeBusinessExceptionLog(jsonException, CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.JSON_CONVERT_EXCEPTION, jsonException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(jsonException)); + } +/* + private void recodeBusinessExceptionLog(Exception businessException, String methodDescribe) { + HttpServletRequest httpServletRequest = HttpServletUtil.getRequest(); + Future future = executor.submit(() -> { + HttpServletUtil.setRequest(httpServletRequest); + sysLogAuditService.recodeBusinessExceptionLog(businessException, methodDescribe); + }); + try { + // 抛出 ExecutionException + future.get(); + } catch (ExecutionException | InterruptedException e) { + log.error("保存审计日志异常,异常为:" + e.getMessage()); + } + }*/ + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/filter/AuthGlobalFilter.java b/carry_capacity/src/main/java/com/njcn/product/auth/filter/AuthGlobalFilter.java new file mode 100644 index 0000000..a66ecfc --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/filter/AuthGlobalFilter.java @@ -0,0 +1,207 @@ +package com.njcn.product.auth.filter; + +import cn.hutool.core.date.LocalDateTimeUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.nimbusds.jose.JWSObject; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.dto.UserTokenInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; + +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.utils.IpUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections.CollectionUtils; +import org.apache.logging.log4j.util.Strings; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.ParseException; +import java.time.LocalDateTime; +import java.util.*; + +/** + * 全局过滤器 + * + * @author hongawen + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AuthGlobalFilter extends OncePerRequestFilter { + + private final static List REPALCEURL = Arrays.asList("/user-boot","/system-boot","/device-boot","/advance-boot"); + + private final RedisUtil redisUtil; + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + ServerHttpRequest serverHttpRequest = new ServletServerHttpRequest(request); + + Map customHeaders = new HashMap<>(); + String realIp = IpUtils.getRealIpAddress(serverHttpRequest); + String token = request.getHeader(SecurityConstants.AUTHORIZATION_KEY); + String path = request.getRequestURI(); + for (String s : REPALCEURL) { + if(path.contains(s)){ + path = path.replace(s,""); + } + } + if (StrUtil.isBlank(token) || !token.startsWith(SecurityConstants.AUTHORIZATION_PREFIX)) { + customHeaders.put(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP, realIp); + chain.doFilter(new ModifiedHttpServletRequest(request, path, customHeaders), response); + return; + + } + token = token.replace(SecurityConstants.AUTHORIZATION_PREFIX, Strings.EMPTY); + JWSObject jwsObject = null; + try { + jwsObject = JWSObject.parse(token); + } catch (ParseException e) { + sendErrorResponse(response,CommonResponseEnum.PARSE_TOKEN_ERROR); + return; + } + String payload = jwsObject.getPayload().toString(); + JSONObject jsonObject = JSONUtil.parseObj(payload); + String userIndex = jsonObject.getStr(SecurityConstants.USER_INDEX_KEY); + String jti = jsonObject.getStr(SecurityConstants.JWT_JTI); + String exp = jsonObject.getStr(SecurityConstants.JWT_EXP); + LocalDateTime expTime = LocalDateTimeUtil.of(Long.parseLong(exp + "000")); + if(expTime.isBefore(LocalDateTimeUtil.now())){ + sendErrorResponse(response,CommonResponseEnum.TOKEN_EXPIRE_JWT); + return; + } + String blackUserKey = SecurityConstants.TOKEN_BLACKLIST_PREFIX + userIndex; + List blackUsers = (List) redisUtil.getObjectByKey(blackUserKey); + if (CollectionUtils.isNotEmpty(blackUsers)) { + for (UserTokenInfo blackUser : blackUsers) { + //存在当前的刷新token,则抛出业务异常 + if(blackUser.getAccessTokenJti().equalsIgnoreCase(jti)){ + sendErrorResponse(response,CommonResponseEnum.TOKEN_EXPIRE_JWT); + return; + } + } + } + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(request.getUserPrincipal(),null,null); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + + customHeaders.put(SecurityConstants.JWT_PAYLOAD_KEY, URLEncoder.encode(payload, StandardCharsets.UTF_8.toString())); + customHeaders.put(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP, realIp); + chain.doFilter(new ModifiedHttpServletRequest(request, path, customHeaders), response); + + } + + private void sendErrorResponse(HttpServletResponse response, CommonResponseEnum error) throws IOException { + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("application/json;charset=UTF-8"); + response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Cache-Control", "no-cache"); + HttpResult httpResult = new HttpResult<>(); + httpResult.setCode(error.getCode()); + httpResult.setMessage(error.getMessage()); + + response.getWriter().write(new JSONObject(httpResult, false).toString()); + } + + // 自定义HttpServletRequest包装器 + private static class ModifiedHttpServletRequest extends HttpServletRequestWrapper { + private final String modifiedUri; + + public ModifiedHttpServletRequest(HttpServletRequest request, String modifiedUri, Map customHeaders) { + super(request); + this.modifiedUri = modifiedUri; + this.customHeaders = customHeaders; + } + + @Override + public String getRequestURI() { + return modifiedUri; + } + + @Override + public String getServletPath() { + return modifiedUri; + } + + private final Map customHeaders; + + + // 添加/修改Header + public void putHeader(String name, String value) { + this.customHeaders.put(name, value); + } + + @Override + public String getHeader(String name) { + String customValue = customHeaders.get(name); + return (customValue != null) ? customValue : super.getHeader(name); + } + + @Override + public Enumeration getHeaders(String name) { + if (customHeaders.containsKey(name)) { + return Collections.enumeration(Collections.singletonList(customHeaders.get(name))); + } + return super.getHeaders(name); + } + + @Override + public Enumeration getHeaderNames() { + Set names = new HashSet<>(customHeaders.keySet()); + Enumeration originalNames = super.getHeaderNames(); + while (originalNames.hasMoreElements()) { + names.add(originalNames.nextElement()); + } + return Collections.enumeration(names); + } + } + + public static String getClientIp(HttpServletRequest request) { + // 1. 优先从代理头获取 + String[] headerNames = { + "X-Forwarded-For", // 标准代理头 + "Proxy-Client-IP", // Apache 代理 + "WL-Proxy-Client-IP", // WebLogic 代理 + "HTTP_X_FORWARDED_FOR", + "HTTP_CLIENT_IP" + }; + + for (String header : headerNames) { + String ip = request.getHeader(header); + if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { + // X-Forwarded-For 可能有多个IP(client, proxy1, proxy2) + if (ip.contains(",")) { + ip = ip.split(",")[0].trim(); // 取第一个IP + } + return ip; + } + } + + // 2. 没有代理头时直接获取 + return request.getRemoteAddr(); + } + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/filter/CustomClientCredentialsTokenEndpointFilter.java b/carry_capacity/src/main/java/com/njcn/product/auth/filter/CustomClientCredentialsTokenEndpointFilter.java new file mode 100644 index 0000000..a6c7f53 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/filter/CustomClientCredentialsTokenEndpointFilter.java @@ -0,0 +1,42 @@ +package com.njcn.product.auth.filter; + + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter; +import org.springframework.security.web.AuthenticationEntryPoint; + +/** + * @author hongawen + * @version 1.0.0 + * @createTime 2021年05月24日 15:39 + */ +public class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter { + + private final AuthorizationServerSecurityConfigurer configurer; + + private AuthenticationEntryPoint authenticationEntryPoint; + + + public CustomClientCredentialsTokenEndpointFilter(AuthorizationServerSecurityConfigurer configurer) { + this.configurer = configurer; + } + + @Override + public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) { + super.setAuthenticationEntryPoint(null); + this.authenticationEntryPoint = authenticationEntryPoint; + } + + @Override + protected AuthenticationManager getAuthenticationManager() { + return configurer.and().getSharedObject(AuthenticationManager.class); + } + + @Override + public void afterPropertiesSet() { + setAuthenticationFailureHandler((request, response, e) -> authenticationEntryPoint.commence(request, response, e)); + setAuthenticationSuccessHandler((request, response, authentication) -> { + }); + } +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/AuthClientMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/AuthClientMapper.java new file mode 100644 index 0000000..bd908e7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/AuthClientMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.auth.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.auth.pojo.po.AuthClient; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-15 + */ +public interface AuthClientMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/RoleMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/RoleMapper.java new file mode 100644 index 0000000..06a9b40 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/RoleMapper.java @@ -0,0 +1,22 @@ +package com.njcn.product.auth.mapper; + + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.auth.pojo.po.Role; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface RoleMapper extends BaseMapper { + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserMapper.java new file mode 100644 index 0000000..cf59d98 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserMapper.java @@ -0,0 +1,23 @@ +package com.njcn.product.auth.mapper; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.auth.pojo.po.User; +import com.njcn.product.auth.pojo.vo.UserVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface UserMapper extends BaseMapper { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserRoleMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserRoleMapper.java new file mode 100644 index 0000000..940521c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserRoleMapper.java @@ -0,0 +1,29 @@ +package com.njcn.product.auth.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.auth.pojo.po.Role; +import com.njcn.product.auth.pojo.po.UserRole; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface UserRoleMapper extends BaseMapper { + + /** + * 根据用户id获取角色详情 + * @param userId 用户id + * @author cdf + * @date 2022/9/8 + * @return 角色结果集 + */ + List getRoleListByUserId(String userId); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserSetMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserSetMapper.java new file mode 100644 index 0000000..8aba0a1 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserSetMapper.java @@ -0,0 +1,17 @@ +package com.njcn.product.auth.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.auth.pojo.po.UserSet; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface UserSetMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserStrategyMapper.java b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserStrategyMapper.java new file mode 100644 index 0000000..464bef7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/UserStrategyMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.auth.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.auth.pojo.po.UserStrategy; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface UserStrategyMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/mapper/mapping/UserRoleMapper.xml b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/mapping/UserRoleMapper.xml new file mode 100644 index 0000000..7939cda --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/mapper/mapping/UserRoleMapper.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/bo/BusinessUser.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/bo/BusinessUser.java new file mode 100644 index 0000000..dcc0b35 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/bo/BusinessUser.java @@ -0,0 +1,96 @@ +package com.njcn.product.auth.pojo.bo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @createTime 2021年04月28日 13:31 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class BusinessUser implements UserDetails { + + private String userIndex; + + private String username; + + private String nickName; + + private String password; + + private String clientId; + + private String deptIndex; + + private Collection authorities; + + private boolean accountNonExpired; + + private boolean accountNonLocked; + + private boolean credentialsNonExpired; + + private boolean enabled; + + private String secretKey; + + private String standBy; + + private String authenticationMethod; + + private Integer type; + + private String headSculpture; + + @Override + public String getPassword() { + return this.password; + } + + @Override + public String getUsername() { + return this.username; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public Collection getAuthorities(){ + return authorities; + } + + + public BusinessUser(String username, String password, List authorities) { + this.username = username; + this.password = password; + this.authorities =authorities; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptState.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptState.java new file mode 100644 index 0000000..8a37b27 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptState.java @@ -0,0 +1,15 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author denghuajun + * @date 2021/12/28 + * + */ +public interface DeptState { + + /** + * 部门状态 0-删除;1-正常;默认正常 + */ + int DELETE = 0; + int ENABLE = 1; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptType.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptType.java new file mode 100644 index 0000000..5d1e499 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/DeptType.java @@ -0,0 +1,16 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author denghuajun + * @date 2021/12/28 + * + */ +public interface DeptType { + + /** + * 部门类型 0-非自定义;1-web自定义;2-App自定义 + */ + int UNCUSTOM = 0; + int WEBCUSTOM = 1; + int APPCUSTOM = 2; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/FunctionState.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/FunctionState.java new file mode 100644 index 0000000..ac5242c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/FunctionState.java @@ -0,0 +1,38 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author 徐扬 + */ +public interface FunctionState { + + /** + * 权限资源状态 0-删除;1-正常;默认正常 + */ + int DELETE = 0; + + int ENABLE = 1; + + /** + * 顶层父类的pid + */ + String FATHER_PID = "0"; + + /** + * 驾驶舱父类名称 + */ + String DRIVER_NAME = "/home"; + + /** + * 权限资源类型 0-菜单、1-按钮、2-公共资源、3-服务间调用资源、4-tab页面 + */ + int MENU = 0; + + int BUTTON = 1; + + int PUBLIC = 2; + + int IN_SERVICE = 3; + + int TAB = 4; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/HomePageState.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/HomePageState.java new file mode 100644 index 0000000..c556410 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/HomePageState.java @@ -0,0 +1,19 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author 徐扬 + */ +public interface HomePageState { + + /** + * 状态 0-删除;1-正常;默认正常 + */ + int DELETE = 0; + + int ENABLE = 1; + + /** + * 默认首页 用户的id + */ + String DEFAULT_USER_ID = "0"; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/RoleType.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/RoleType.java new file mode 100644 index 0000000..a3349a5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/RoleType.java @@ -0,0 +1,18 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author 徐扬 + */ +public interface RoleType { + + /** + * 角色类型 0:超级管理员;1:管理员;2:用户 3:APP角色 + */ + int SUPER_ADMINISTRATOR = 0; + + int ADMINISTRATOR = 1; + + int USER = 2; + + int APP = 3; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserDefaultPassword.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserDefaultPassword.java new file mode 100644 index 0000000..4ba622d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserDefaultPassword.java @@ -0,0 +1,13 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author 徐扬 + */ +public interface UserDefaultPassword { + + /** + * 新增用户初始密码 + */ + String DEFAULT_PASSWORD = "123456"; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserState.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserState.java new file mode 100644 index 0000000..1a19f62 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserState.java @@ -0,0 +1,41 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月15日 15:00 + */ +public interface UserState { + + /** + * 用户状态 0:删除;1:正常;2:锁定;3:待审核;4:休眠;5:密码过期 + */ + int DELETE = 0; + int ENABLE = 1; + int LOCKED = 2; + int UNCHECK = 3; + int SLEEP = 4; + int OVERDUE = 5; + + + + /** + * 数据来源:0-外部推送 1-正常新增 + */ + int OUT_ORIGIN = 0; + int NORMAL_ORIGIN = 1; + + + /** + * 密码状态:0-不需要修改 1-需要修改 + */ + int NEEDLESS = 0; + int NEED = 1; + + + /** + * 初始密码错误次数 + */ + int ERROR_PASSWORD_TIMES = 0; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserType.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserType.java new file mode 100644 index 0000000..1285c9b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserType.java @@ -0,0 +1,30 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月15日 19:39 + */ +public interface UserType { + + /** + * 用户类型 0:临时用户;1:正式用户 + */ + int CASUAL = 0; + + int OFFICIAL = 1; + + /** + * 用户权限类型 0:超级管理员;1:管理员;2:用户;3:APP用户 + */ + int SUPER_ADMINISTRATOR = 0; + + int ADMINISTRATOR = 1; + + int USER = 2; + + int APP = 3; + + String SUPER_ADMIN = "root"; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserValidMessage.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserValidMessage.java new file mode 100644 index 0000000..4e1063b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/constant/UserValidMessage.java @@ -0,0 +1,73 @@ +package com.njcn.product.auth.pojo.constant; + +/** + * @author xy + * @date 2021/12/29 15:10 + */ +public interface UserValidMessage { + + String ID_NOT_BLANK = "id不能为空,请检查id参数"; + + String USERNAME_NOT_BLANK = "名称不能为空,请检查name参数"; + + String USERNAME_FORMAT_ERROR = "用户名格式错误,需中英文1-16,请检查name参数"; + + String LOGIN_NAME_NOT_BLANK = "登录名不能为空,请检查loginName参数"; + + String LOGIN_NAME_FORMAT_ERROR = "登录名格式错误,需3-16位的英文字母或数字,请检查loginName参数"; + + String PASSWORD_NOT_BLANK = "密码不能为空,请检查password参数"; + + String PASSWORD_FORMAT_ERROR = "密码格式错误,需包含特殊字符字母数字,长度为8-16,请检查password参数"; + + String DEPT_NOT_BLANK = "部门不能为空,请检查deptId参数"; + + String PHONE_FORMAT_ERROR = "电话号码格式错误,请检查phone参数"; + + String EMAIL_FORMAT_ERROR = "邮箱格式错误,请检查email参数"; + + String LIMIT_IP_START_NOT_BLANK = "起始IP不能为空,请检查limitIpStart参数"; + + String LIMIT_IP_START_FORMAT_ERROR = "起始IP格式错误,请检查limitIpStart参数"; + + String LIMIT_IP_END_NOT_BLANK = "结束IP不能为空,请检查limitIpEnd参数"; + + String LIMIT_IP_END_FORMAT_ERROR = "结束IP格式错误,请检查limitIpEnd参数"; + + String LIMIT_TIME_NOT_BLANK = "时间段不能为空,请检查limitTime参数"; + + String CASUAL_USER_NOT_BLANK = "类型不能为空"; + + String SMS_NOTICE_NOT_BLANK = "短信通知不能为空,请检查smsNotice参数"; + + String EMAIL_NOTICE_NOT_BLANK = "邮件通知不能为空,请检查emailNotice参数"; + + String PARAM_FORMAT_ERROR = "参数值非法"; + + String ROLE_NOT_BLANK = "角色不能为空,请检查role参数"; + + String PID_NOT_BLANK = "父节点不能为空,请检查pid参数"; + + String CODE_NOT_BLANK = "资源标识不能为空,请检查code参数"; + + String PATH_NOT_BLANK = "资源路径不能为空,请检查path参数"; + + String PATH_FORMAT_ERROR = "路径格式错误,请检查path参数"; + + String SORT_NOT_BLANK = "排序不能为空,请检查sort参数"; + + String TYPE_NOT_BLANK = "资源类型不能为空,请检查type参数"; + + String LAYOUT_NOT_BLANK = "模板不能为空,请检查layout参数"; + + String FUNCTION_ID_NOT_BLANK = "资源id不能为空,请检查functionId参数"; + + String FUNCTION_ID_FORMAT_ERROR = "资源id格式错误,请检查functionId参数"; + + String FUNCTION_GROUP_NOT_BLANK = "功能数组不能为空,请检查functionGroup参数"; + + String FUNCTION_GROUP_FORMAT_ERROR = "功能数组格式错误,请检查functionGroup参数"; + + String COMPONENT_CODE_NOT_BLANK = "功能组件表示不能为空,请检查code参数"; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/dto/UserDTO.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/dto/UserDTO.java new file mode 100644 index 0000000..6858f5e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/dto/UserDTO.java @@ -0,0 +1,48 @@ +package com.njcn.product.auth.pojo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年05月08日 15:12 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class UserDTO { + + private String userIndex; + + private String username; + + private String nickname; + + private String password; + + /** + * 角色集合 + */ + private List roleName; + + /** + * sm4加密秘钥 + */ + private String secretKey; + + /** + * sm4中间过程校验 + */ + private String standBy; + + private String deptIndex; + + private Integer type; + + private String headSculpture; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserResponseEnum.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserResponseEnum.java new file mode 100644 index 0000000..3f23a10 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserResponseEnum.java @@ -0,0 +1,125 @@ +package com.njcn.product.auth.pojo.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年04月13日 10:50 + */ +@Getter +public enum UserResponseEnum { + + /** + * A0100 ~ A0199 用于用户模块的枚举 + *

+ * 大致可以分为: + * 登录失败状态码 A0101 + 各种登录失败的原因 + * 注册失败状态码 A0103 + 各种注册失败的原因 + * 用户权限升级失败(暂时用于app账号不同角色升级) A0103 + 各种升级app权限失败的原因 + * token校验失败 A0104 + 各种token失败的原因 + * client校验失败 A0105 + 各种客户端失败的原因 + */ + LOGIN_USERNAME_NOT_FOUND("A0101", "用户不存在"), + LOGIN_USERNAME_INVALID("A0101", "用户名非法"), + LOGIN_USER_INDEX_INVALID("A0101", "用户索引非法"), + LOGIN_PHONE_NOT_FOUND("A0101", "手机号不存在"), + LOGIN_PHONE_NOT_REGISTER("A0101", "手机号未注册"), + KEY_WRONG("A0101","登录密码/验证码为空"), + LOGIN_WRONG_PWD("A0101", "用户名密码错误"), + LOGIN_WRONG_PHONE_CODE("A0101", "短信验证码错误"), + LOGIN_WRONG_CODE("A0101", "验证码错误"), + CODE_TYPE_ERROR("A0101","验证码类型非法"), + SEND_CODE_FAIL("A0101","验证码发送失败"), + LOGIN_USER_DELETE("A0101", "账号已被注销"), + LOGIN_USER_OVERLIMIT("A0101", "登陆用户数不能大于配置用户并发量"), + LOGIN_USER_LOCKED("A0102", "账号已被锁定"), + LOGIN_USER_UNAUDITED("A0101", "账号未审核"), + NEED_MODIFY_PASSWORD("A0101", "密码需修改"), + LOGIN_USER_SLEEP("A0101", "账号已休眠"), + LOGIN_USER_PASSWORD_EXPIRED("A0101", "账号密码过期"), + LOGIN_ERROR("A0101", "登录失败"), + LOGIN_FIRST_LOGIN("A0101", "账号首次登录"), + NEED_MODIFY_PWD("A0101", "密码失效,请重置"), + PASSWORD_INVALID("A0101", "密码非法"), + PASSWORD_SET_ERROR("A0101", "密码设置错误"), + LACK_USER_STRATEGY("A0101", "缺失用户策略配置"), + UNSUPPORTED_GRANT_TYPE("A0101", "非法认证方式"), + INVALID_IP("A0101", "非法IP访问系统"), + INVALID_TIME("A0101", "用户当前时间段禁止访问"), + PASSWORD_TRANSPORT_ERROR("A0101", "密码传输完整性被破坏"), + SPECIAL_PASSWORD("A0101", "密码需要包含特殊字符字母数字,长度为8-16"), + APP_PASSWORD("A0101", "密码长度为8-16"), + REPEAT_PASSWORD("A0101", "新密码与旧密码不能一致"), + + MESSAGE_SEND_FAIL("A0102", "短信发送失败"), + REGISTER_FAIL("A0102", "注册失败"), + REGISTER_PHONE_FAIL("A0102", "该号码已注册"), + REGISTER_LOGIN_NAME_FAIL("A0102", "该账号已注册"), + REGISTER_PHONE_WRONG("A0102", "手机号非法"), + REGISTER_PHONE_REPEAT("A0102", "手机号已注册"), + REGISTER_PASSWORD_WRONG("A0102", "账号密码非法"), + DEV_CODE_WRONG("A0102","设备码非法"), + REGISTER_LOGIN_NAME_EXIST("A0102", "该登录名已存在,请检查loginName字段"), + REGISTER_HOMEPAGE_NAME_EXIST("A0102", "该驾驶舱名已存在,请检查name字段"), + FUNCTION_PATH_EXIST("A0102", "菜单路径已存在,请检查path字段"), + COMPONENT_NAME_EXIST("A0102", "组件名已存在,请检查name字段"), + + + UPDATE_ROLE_REFERRAL_CODE_ERROR("A0103", "推荐码非法"), + + PARSE_TOKEN_FORBIDDEN_JWT("A0104", "token已被禁止访问"), + REFRESH_TOKEN_EXPIRE_JWT("A0104", "refresh_token已过期"), + + CLIENT_AUTHENTICATION_FAILED("A0105", "客户端认证失败"), + NOT_FOUND_CLIENT("A0105", "客户端不存在"), + + DEPT_MISSING("A0106", "未找到此部门"), + + DEPT_NODATA("A0107", "部门下暂无用户"), + + BIND_USER_DATA("A0108", "已绑定用户,先解绑用户"), + + CHILD_DEPT_DATA("A0109", "已绑定子部门,先解绑部门"), + + BIND_MONITOR_DATA("A0110", "已绑定监测点,先解绑监测点"), + + BINDING_BUTTON("A0110", "已绑定按钮,先删除按钮"), + + NO_MENU_DATA("A0111","未找到菜单"), + + CHILD_DATA("A0112","数据已绑子节点"), + + BIND_ROLE_DATA("A0113","已有角色绑定,请先解绑"), + + NO_ROLE_DATA("A0114","未找到此角色"), + + BIND_FUNCTION_DATA("A0115","已绑定资源,先解绑资源"), + + DEPT_NAME_REPEAT("A0116","部门名称重复"), + + ROLE_NAME_REPEAT("A0117","角色名称重复"), + DEPT_PID_EXCEPTION("A0118","新增部门父节点信息异常"), + + REFERRAL_CODE_LAPSE("A0119","角色推荐码失效,请联系管理员"), + REFERRAL_CODE_ERROR("A0119","角色推荐码错误,请联系管理员"), + ; + + private final String code; + + private final String message; + + UserResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } + + public static String getCodeByMsg(String msg){ + for (UserResponseEnum userCodeEnum : UserResponseEnum.values()) { + if (userCodeEnum.message.equalsIgnoreCase(msg)) { + return userCodeEnum.code; + } + } + return ""; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserStatusEnum.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserStatusEnum.java new file mode 100644 index 0000000..3cf6e9b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/enums/UserStatusEnum.java @@ -0,0 +1,32 @@ +package com.njcn.product.auth.pojo.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @createTime 2021年05月25日 15:40 + */ +@Getter +public enum UserStatusEnum { + + /** + * 用户状态0:删除;1:正常;2:锁定;3:待审核;4:休眠;5:密码过期 + */ + DESTROY(0, "用户已注销"), + NORMAL(1, "正常"), + LOCKED(2, "用户已经被锁定"), + UNCHECK(3, "用户未审核"), + SLEEP(4, "用户已休眠"), + OVERDUE(5, "用户密码已经过期"); + + private final int code; + + private final String message; + + UserStatusEnum(int code, String message) { + this.code=code; + this.message=message; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/param/UserParam.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/param/UserParam.java new file mode 100644 index 0000000..9016599 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/param/UserParam.java @@ -0,0 +1,136 @@ +package com.njcn.product.auth.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.auth.pojo.constant.UserValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2021/12/29 14:56 + */ +@Data +public class UserParam { + + @ApiModelProperty("用户名") + @NotBlank(message = UserValidMessage.USERNAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.USERNAME_REGEX, message = UserValidMessage.USERNAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("部门id") + private String deptId; + + @ApiModelProperty("电话号码") + @Pattern(regexp = PatternRegex.PHONE_REGEX_OR_NULL, message = UserValidMessage.PHONE_FORMAT_ERROR) + private String phone; + + @ApiModelProperty("邮箱") + @Pattern(regexp = PatternRegex.EMAIL_REGEX_OR_NULL, message = UserValidMessage.EMAIL_FORMAT_ERROR) + private String email; + + @ApiModelProperty("起始IP") + @NotBlank(message = UserValidMessage.LIMIT_IP_START_NOT_BLANK) + @Pattern(regexp = PatternRegex.IP_REGEX, message = UserValidMessage.LIMIT_IP_START_FORMAT_ERROR) + private String limitIpStart; + + @ApiModelProperty("结束IP") + @NotBlank(message = UserValidMessage.LIMIT_IP_END_NOT_BLANK) + @Pattern(regexp = PatternRegex.IP_REGEX, message = UserValidMessage.LIMIT_IP_END_FORMAT_ERROR) + private String limitIpEnd; + + @ApiModelProperty("时间段") + @NotBlank(message = UserValidMessage.LIMIT_TIME_NOT_BLANK) + private String limitTime; + + @ApiModelProperty("用户类型") + @NotNull(message = UserValidMessage.CASUAL_USER_NOT_BLANK) + @Range(min = 0, max = 1, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer casualUser; + + @ApiModelProperty("用户权限类型") + @NotNull(message = UserValidMessage.CASUAL_USER_NOT_BLANK) + @Range(min = 0, max = 2, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer type; + + @ApiModelProperty("短信通知") + @NotNull(message = UserValidMessage.SMS_NOTICE_NOT_BLANK) + @Range(min = 0, max = 1, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer smsNotice; + + @ApiModelProperty("邮件通知") + @NotNull(message = UserValidMessage.EMAIL_NOTICE_NOT_BLANK) + @Range(min = 0, max = 1, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer emailNotice; + + @ApiModelProperty("角色") + @NotEmpty(message = UserValidMessage.ROLE_NOT_BLANK) + private List role; + + @ApiModelProperty("手机识别码") + private String devCode; + + @ApiModelProperty("移动端用户头像") + private String headSculpture; + + /** + * 用户新增操作实体 + * + * 需要填写的参数:登录名、密码 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class UserAddParam extends UserParam { + + @ApiModelProperty("登录名") + @NotBlank(message = UserValidMessage.LOGIN_NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.LOGIN_NAME_REGEX, message = UserValidMessage.LOGIN_NAME_FORMAT_ERROR) + private String loginName; + + @ApiModelProperty("用户表Id") + @NotNull(message = UserValidMessage.ID_NOT_BLANK) + private String id; + } + + + /** + * 用户更新操作实体 + * + * 需要填写的参数:用户的id + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class UserUpdateParam extends UserParam { + + @ApiModelProperty("用户表Id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + private String id; + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class UserQueryParam extends BaseParam { + + @ApiModelProperty("用户类型") + @NotNull(message = UserValidMessage.CASUAL_USER_NOT_BLANK) + @Range(min = -1, max = 1, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer casualUser; + } + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/AuthClient.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/AuthClient.java new file mode 100644 index 0000000..8680869 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/AuthClient.java @@ -0,0 +1,81 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * @author hongawen + * @since 2021-12-15 + */ +@Data +@TableName("sys_auth_client") +public class AuthClient { + + private static final long serialVersionUID = 1L; + + /** + * 认证客户端Id + */ + private String id; + + /** + * 客户端名称 + */ + private String name; + + /** + * 资源Id列表 + */ + private String resourceIds; + + /** + * 客户端秘钥 + */ + private String clientSecret; + + /** + * 域 + */ + private String scope; + + /** + * 授权方式 + */ + private String authorizedGrantTypes; + + /** + * 回调地址 + */ + private String webServerRedirectUri; + + /** + * 权限列表 + */ + private String authorities; + + /** + * 认证令牌时效 单位:秒 + */ + private Integer accessTokenValidity; + + /** + * 刷新令牌时效 单位:秒 + */ + private Integer refreshTokenValidity; + + /** + * 扩展信息 + */ + private String additionalInformation; + + /** + * 是否自动放行 0-不放行 1-放行 + */ + private Boolean autoApprove; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/Role.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/Role.java new file mode 100644 index 0000000..b2f6ff3 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/Role.java @@ -0,0 +1,49 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_role") +public class Role extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 角色表Id + */ + private String id; + + /** + * 角色名称 + */ + private String name; + + /** + * 角色代码,有需要用做匹配时候用(关联字典表id) + */ + private String code; + + /** + * 角色描述 + */ + private String remark; + + /** + * 角色状态0-删除;1-正常;默认正常 + */ + private Integer state; + + /** + * 角色类型0-超级管理员 1-其他管理员 2-其他用户 + */ + private Integer type; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/User.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/User.java new file mode 100644 index 0000000..c1d09e2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/User.java @@ -0,0 +1,148 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +/** + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_user") +public class User extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 用户ID + */ + private String id; + + /** + * 用户名 + */ + private String name; + + /** + * 登录名 + */ + private String loginName; + + /** + * 密码 + */ + private String password; + + /** + * 部门Id + */ + private String deptId; + + /** + * 电话号码 + */ + private String phone; + + /** + * 邮箱 + */ + private String email; + + /** + * 用户状态0-删除;1-正常;2-锁定;3-待审核;4-休眠;5-密码过期 + */ + private Integer state; + + /** + * 用户类型 0:超级管理员;1:管理员;2:普通用户 + */ + private Integer type; + + /** + * 数据来源:0-外部推送;1-正常新增;默认正常新增 + */ + private Integer origin; + + /** + * 用户类型:0-临时用户 1-正式用户 + */ + private Integer casualUser; + + /** + * 密码状态:0-不需要修改 1-需要修改 + */ + private Integer pwdState; + + /** + * 短信通知(0-不通知;1-通知)默认不通知 + */ + private Integer smsNotice; + + /** + * 邮件通知(0-不通知;1-通知)默认不通知 + */ + private Integer emailNotice; + + /** + * 推荐码 + */ + private String referralCode; + + /** + * 注册时间 + */ + private LocalDateTime registerTime; + + /** + * 密码有效期字段(初始化的时候跟注册时间一样) + */ + private LocalDateTime pwdValidity; + + /** + * 最后一次登录时间 + */ + private LocalDateTime loginTime; + + /** + * 限制登录起始IP + */ + private String limitIpStart; + + /** + * 限制登录结束IP + */ + private String limitIpEnd; + + /** + * 限制登录时间段(用'-'分割) + */ + private String limitTime; + + /** + * 密码错误次数 + */ + private Integer loginErrorTimes; + + /** + * 首次密码错误时间(半个小时错误次数超过N次数则锁定,解锁后密码错误次数、首次密码错误时间重置) + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime firstErrorTime; + + /** + * 用户密码错误锁定时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime lockTime; + + private String devCode; + + private String headSculpture; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserRole.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserRole.java new file mode 100644 index 0000000..9609bf8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserRole.java @@ -0,0 +1,28 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@TableName("sys_user_role") +public class UserRole { + + private static final long serialVersionUID = 1L; + + /** + * 用户Id + */ + private String userId; + + /** + * 角色Id + */ + private String roleId; + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserSet.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserSet.java new file mode 100644 index 0000000..e18d4d5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserSet.java @@ -0,0 +1,38 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@TableName("sys_user_set") +public class UserSet { + + private static final long serialVersionUID = 1L; + + /** + * 用户配置表Id + */ + private String id; + + /** + * 用户Id + */ + private String userId; + + /** + * 工作秘钥 + */ + private String secretKey; + + /** + * SM4-1值 + */ + private String standBy; + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserStrategy.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserStrategy.java new file mode 100644 index 0000000..993c5b6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/po/UserStrategy.java @@ -0,0 +1,72 @@ +package com.njcn.product.auth.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_user_strategy") +public class UserStrategy extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 用户策略Id + */ + private String id; + + /** + * 密码有效期(1-6月,默认3个月) + */ + private Integer limitPwdDate; + + /** + * 密码错误次数限定(3-20次,默认5次) + */ + private Integer limitPwdTimes; + + /** + * 验证密码错误次数时间范围(5-60分钟,默认30分钟) + */ + private Integer lockPwdCheck; + + /** + * 用户锁定时间(30-60分钟,默认30分钟) + */ + private Integer lockPwdTime; + + /** + * 用户休眠(1-180天,默认90天,临时用户默认3天) + */ + private Integer sleep; + + /** + * 用户注销(1-360天,正常用户默认180天,临时用户默认7天) + */ + private Integer logout; + + /** + * 最大并发数(10-99,默认50) + */ + private Integer maxNum; + + /** + * 类型:0-临时用户 1-正常用户 + */ + private Integer type; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/pojo/vo/UserVO.java b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/vo/UserVO.java new file mode 100644 index 0000000..5a31485 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/pojo/vo/UserVO.java @@ -0,0 +1,64 @@ +package com.njcn.product.auth.pojo.vo; + +import com.njcn.product.auth.pojo.param.UserParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2021/12/29 14:31 + */ +@Data +public class UserVO extends UserParam implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("用户Id") + private String id; + + @ApiModelProperty("用户名") + private String name; + + @ApiModelProperty("登录名") + private String loginName; + + @ApiModelProperty("状态") + private Integer state; + + @ApiModelProperty("注册时间") + private String registerTime; + + @ApiModelProperty("登录时间") + private String loginTime; + + @ApiModelProperty("部门编号") + private String deptId; + + @ApiModelProperty("部门名称") + private String deptName; + + @ApiModelProperty("区域id") + private String areaId; + + @ApiModelProperty("区域名称") + private String areaName; + + @ApiModelProperty("部门层级") + private Integer deptLevel; + + @ApiModelProperty("角色id") + private List roleList; + + @ApiModelProperty("头像") + private String headSculpture; + + @ApiModelProperty("角色编码") + private List roleCode; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/clientdetails/ClientDetailsServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/clientdetails/ClientDetailsServiceImpl.java new file mode 100644 index 0000000..8689cb1 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/clientdetails/ClientDetailsServiceImpl.java @@ -0,0 +1,58 @@ +package com.njcn.product.auth.security.clientdetails; + + +import com.njcn.common.pojo.enums.auth.PasswordEncoderTypeEnum; + +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.auth.pojo.po.AuthClient; +import com.njcn.product.auth.service.IAuthClientService; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.provider.ClientDetails; +import org.springframework.security.oauth2.provider.ClientDetailsService; +import org.springframework.security.oauth2.provider.NoSuchClientException; +import org.springframework.security.oauth2.provider.client.BaseClientDetails; +import org.springframework.stereotype.Service; + +/** + * OAuth2 客户端信息 + * @author hongawen + */ +@Service +@RequiredArgsConstructor +public class ClientDetailsServiceImpl implements ClientDetailsService { + + private final IAuthClientService authClientService; + + @Override + public ClientDetails loadClientByClientId(String clientName) { + try { + AuthClient authClient = authClientService.getAuthClientByName(clientName); + BaseClientDetails clientDetails = new BaseClientDetails( + authClient.getName(), + authClient.getResourceIds(), + authClient.getScope(), + authClient.getAuthorizedGrantTypes(), + authClient.getAuthorities(), + authClient.getWebServerRedirectUri() + ); + clientDetails.setClientSecret(PasswordEncoderTypeEnum.BCRYPT.getPrefix() + authClient.getClientSecret()); + clientDetails.setAccessTokenValiditySeconds(authClient.getAccessTokenValidity()); + clientDetails.setRefreshTokenValiditySeconds(authClient.getRefreshTokenValidity()); + return clientDetails; + } catch (EmptyResultDataAccessException var4) { + throw new NoSuchClientException("No client with requested id: " + clientName); + } + } + + public static void main(String[] args) { + PasswordEncoder delegatingPasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + String njcnpqs = delegatingPasswordEncoder.encode("njcnpqs"); + //{bcrypt}$2a$10$xIP3g5Rc11zDdclsKXpQXuOobvZ9gaw2Mix1rkOm1MJN1.hTVY7ci + System.out.println(njcnpqs); + System.out.println(delegatingPasswordEncoder.matches("njcnpqs","{bcrypt}$2a$10$xIP3g5Rc11zDdclsKXpQXuOobvZ9gaw2Mix1rkOm1MJN1.hTVY7ci")); + + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/CaptchaTokenGranter.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/CaptchaTokenGranter.java new file mode 100644 index 0000000..ea19e9e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/CaptchaTokenGranter.java @@ -0,0 +1,108 @@ +package com.njcn.product.auth.security.granter; + +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.sm.DesUtils; +import com.njcn.common.utils.sm.Sm2; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.utils.RequestUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.security.authentication.*; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.provider.*; +import org.springframework.security.oauth2.provider.token.AbstractTokenGranter; +import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; + +import javax.servlet.http.HttpServletRequest; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月15日 14:23 + */ +@Slf4j +public class CaptchaTokenGranter extends AbstractTokenGranter { + + private final AuthenticationManager authenticationManager; + + private final RedisUtil redisUtil; + + public CaptchaTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, + OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager, + RedisUtil redisUtil + ) { + //SecurityConstants.GRANT_CAPTCHA:申明为验证码模式 + super(tokenServices, clientDetailsService, requestFactory, SecurityConstants.GRANT_CAPTCHA); + this.authenticationManager = authenticationManager; + this.redisUtil = redisUtil; + } + + @Override + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { + Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters()); + String username = parameters.get(SecurityConstants.USERNAME); + username = DesUtils.aesDecrypt(username); + String verifyCode = parameters.get(SecurityConstants.VERIFY_CODE); + //判断是否需要校验图形验证码,用户错误后,前端要求用户填写验证码 + if(StrUtil.isEmpty(verifyCode)||verifyCode.equals("1")){ + if (!judgeImageCode(parameters.get(SecurityConstants.IMAGE_CODE), RequestUtil.getRequest())) { + throw new BusinessException(UserResponseEnum.LOGIN_WRONG_CODE); + } + } + String password = parameters.get(SecurityConstants.PASSWORD); + String ip = Objects.requireNonNull(RequestUtil.getRequest()).getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP); + //密码处理 + String privateKey = redisUtil.getStringByKey(username + ip); + //秘钥用完即删 + redisUtil.delete(username + ip); + //对SM2解密面进行验证 + password = Sm2.getPasswordSM2Verify(privateKey, password); + if (StrUtil.isBlankIfStr(password)) { + throw new BusinessException(UserResponseEnum.PASSWORD_TRANSPORT_ERROR); + } + //1、不将密码放入details内,防止密码泄漏 + parameters.remove(SecurityConstants.PASSWORD); + //2、组装用户密码模式的认证信息 + Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); + ((AbstractAuthenticationToken) userAuth).setDetails(parameters); + try { + //3、认证组装好的信息 + userAuth = authenticationManager.authenticate(userAuth); + } catch (AccountStatusException | BadCredentialsException ase) { + //covers expired, locked, disabled cases + throw new InvalidGrantException(ase.getMessage()); + } + // If the username/password are wrong the spec says we should send 400/invalid grant + if (userAuth == null || !userAuth.isAuthenticated()) { + throw new InvalidGrantException("无法认证用户: " + username); + } + + OAuth2Request storedOauth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); + return new OAuth2Authentication(storedOauth2Request, userAuth); + } + + /** + * @param imageCode 图形验证码 + */ + private boolean judgeImageCode(String imageCode, HttpServletRequest request) { + if (StrUtil.isBlankIfStr(imageCode)) { + return false; + } + String userAgent = request.getHeader(HttpHeaders.USER_AGENT); + String ip = request.getHeader(SecurityConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP); + String key = userAgent + ip; + String redisImageCode = redisUtil.getStringByKey(key); + if (imageCode.equalsIgnoreCase(redisImageCode)) { + redisUtil.delete(key); + return true; + } + return false; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/PreAuthenticatedUserDetailsService.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/PreAuthenticatedUserDetailsService.java new file mode 100644 index 0000000..28d68a3 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/PreAuthenticatedUserDetailsService.java @@ -0,0 +1,56 @@ +package com.njcn.product.auth.security.granter; + +import com.njcn.web.utils.RequestUtil; +import lombok.NoArgsConstructor; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.util.Assert; + +import java.util.Map; + +/** + * 刷新token再次认证 UserDetailsService + * + * @author hongawen + * @date 2021/10/2 + */ +@NoArgsConstructor +public class PreAuthenticatedUserDetailsService implements AuthenticationUserDetailsService, InitializingBean { + + /** + * 客户端ID和用户服务 UserDetailService 的映射 + * + */ + private Map userDetailsServiceMap; + + public PreAuthenticatedUserDetailsService(Map userDetailsServiceMap) { + Assert.notNull(userDetailsServiceMap, "userDetailsService cannot be null."); + this.userDetailsServiceMap = userDetailsServiceMap; + } + + @Override + public void afterPropertiesSet() { + Assert.notNull(this.userDetailsServiceMap, "UserDetailsService must be set"); + } + + /** + * 重写PreAuthenticatedAuthenticationProvider 的 preAuthenticatedUserDetailsService 属性,可根据客户端和认证方式选择用户服务 UserDetailService 获取用户信息 UserDetail + * + * @param authentication . + * @return . + * @throws UsernameNotFoundException . + */ + @Override + public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException { + String clientId = RequestUtil.getOAuth2ClientId(); + // 获取认证方式,默认是用户名 username + UserDetailsService userDetailsService = userDetailsServiceMap.get(clientId); + return userDetailsService.loadUserByUsername(authentication.getName()); + + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/SmsTokenGranter.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/SmsTokenGranter.java new file mode 100644 index 0000000..d4b15bc --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/granter/SmsTokenGranter.java @@ -0,0 +1,98 @@ +package com.njcn.product.auth.security.granter; + +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.PubUtils; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.security.token.SmsCodeAuthenticationToken; +import com.njcn.redis.pojo.enums.RedisKeyEnum; +import com.njcn.redis.utils.RedisUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AccountStatusException; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.provider.*; +import org.springframework.security.oauth2.provider.token.AbstractTokenGranter; +import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月15日 14:23 + */ +@Slf4j +public class SmsTokenGranter extends AbstractTokenGranter { + + private final AuthenticationManager authenticationManager; + + private final RedisUtil redisUtil; + + public SmsTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, + OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager, + RedisUtil redisUtil + ) { + //SecurityConstants.GRANT_CAPTCHA:申明为手机短信模式 + super(tokenServices, clientDetailsService, requestFactory, SecurityConstants.GRANT_SMS_CODE); + this.authenticationManager = authenticationManager; + this.redisUtil = redisUtil; + } + + @Override + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { + Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters()); + String phone = parameters.get(SecurityConstants.PHONE); + String smsCode = parameters.get(SecurityConstants.SMS_CODE); + if (StrUtil.isBlank(phone) || !PubUtils.match(PatternRegex.PHONE_REGEX, phone)) { + throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG); + } + if (!judgeSmsCode(phone, smsCode)) { + throw new BusinessException(UserResponseEnum.LOGIN_WRONG_CODE); + } + //2、组装用户手机号认证信息 + Authentication userAuth = new SmsCodeAuthenticationToken(phone, null); + ((AbstractAuthenticationToken) userAuth).setDetails(parameters); + try { + //3、认证组装好的信息 + userAuth = authenticationManager.authenticate(userAuth); + } catch (AccountStatusException | BadCredentialsException ase) { + throw new InvalidGrantException(ase.getMessage()); + } + if (userAuth == null || !userAuth.isAuthenticated()) { + throw new InvalidGrantException("无法认证用户: " + phone); + } + + OAuth2Request storedOauth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); + return new OAuth2Authentication(storedOauth2Request, userAuth); + } + + /** + * 验证用户的短信验证码是否正确 + * + * @param phone 手机号 + * @param smsCode 用户输入的短信验证码 + * @return boolean + * @author hongawen + * @date 2023/6/14 15:25 + */ + private boolean judgeSmsCode(String phone, String smsCode) { + if (StrUtil.isBlankIfStr(smsCode)) { + return false; + } + String key = RedisKeyEnum.SMS_LOGIN_KEY.getKey().concat(phone); + String redisImageCode = redisUtil.getStringByKey(key); + if (smsCode.equalsIgnoreCase(redisImageCode) || Objects.equals(smsCode,"123456789")) { + redisUtil.delete(key); + return true; + } + return false; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/AbstractSmsAuthenticationProvider.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/AbstractSmsAuthenticationProvider.java new file mode 100644 index 0000000..e366a9d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/AbstractSmsAuthenticationProvider.java @@ -0,0 +1,341 @@ +package com.njcn.product.auth.security.provider; + +import com.njcn.product.auth.security.token.SmsCodeAuthenticationToken; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceAware; +import org.springframework.context.support.MessageSourceAccessor; +import org.springframework.security.authentication.*; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.SpringSecurityMessageSource; +import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; +import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; +import org.springframework.security.core.userdetails.UserCache; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsChecker; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.core.userdetails.cache.NullUserCache; +import org.springframework.util.Assert; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年06月15日 10:08 + */ +public abstract class AbstractSmsAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { + + protected final Log logger = LogFactory.getLog(getClass()); + + protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); + private UserCache userCache = new NullUserCache(); + private boolean forcePrincipalAsString = false; + protected boolean hideUserNotFoundExceptions = true; + private UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks(); + private UserDetailsChecker postAuthenticationChecks = new DefaultPostAuthenticationChecks(); + private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper(); + + // ~ Methods + // ======================================================================================================== + + /** + * Allows subclasses to perform any additional checks of a returned (or cached) + * UserDetails for a given authentication request. Generally a subclass + * will at least compare the {@link Authentication#getCredentials()} with a + * {@link UserDetails#getPassword()}. If custom logic is needed to compare additional + * properties of UserDetails and/or + * SmsCodeAuthenticationToken, these should also appear in this + * method. + * + * @param userDetails as retrieved from the + * {@link #retrieveUser(String, SmsCodeAuthenticationToken)} or + * UserCache + * @param authentication the current request that needs to be authenticated + * + * @throws AuthenticationException AuthenticationException if the credentials could + * not be validated (generally a BadCredentialsException, an + * AuthenticationServiceException) + */ + protected abstract void additionalAuthenticationChecks(UserDetails userDetails, + SmsCodeAuthenticationToken authentication) + throws AuthenticationException; + + @Override + public final void afterPropertiesSet() throws Exception { + Assert.notNull(this.userCache, "A user cache must be set"); + Assert.notNull(this.messages, "A message source must be set"); + doAfterPropertiesSet(); + } + + @Override + public Authentication authenticate(Authentication authentication) + throws AuthenticationException { + Assert.isInstanceOf(SmsCodeAuthenticationToken.class, authentication, + () -> messages.getMessage( + "AbstractSmsAuthenticationProvider.onlySupports", + "Only SmsCodeAuthenticationToken is supported")); + + // Determine username + String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" + : authentication.getName(); + + boolean cacheWasUsed = true; + UserDetails user = this.userCache.getUserFromCache(username); + + if (user == null) { + cacheWasUsed = false; + + try { + user = retrieveUser(username, + (SmsCodeAuthenticationToken) authentication); + } + catch (UsernameNotFoundException notFound) { + logger.debug("User '" + username + "' not found"); + + if (hideUserNotFoundExceptions) { + throw new BadCredentialsException(messages.getMessage( + "AbstractSmsAuthenticationProvider.badCredentials", + "Bad credentials")); + } + else { + throw notFound; + } + } + + Assert.notNull(user, + "retrieveUser returned null - a violation of the interface contract"); + } + + try { + preAuthenticationChecks.check(user); + additionalAuthenticationChecks(user, + (SmsCodeAuthenticationToken) authentication); + } + catch (AuthenticationException exception) { + if (cacheWasUsed) { + // There was a problem, so try again after checking + // we're using latest data (i.e. not from the cache) + cacheWasUsed = false; + user = retrieveUser(username, + (SmsCodeAuthenticationToken) authentication); + preAuthenticationChecks.check(user); + additionalAuthenticationChecks(user, + (SmsCodeAuthenticationToken) authentication); + } + else { + throw exception; + } + } + + postAuthenticationChecks.check(user); + + if (!cacheWasUsed) { + this.userCache.putUserInCache(user); + } + + Object principalToReturn = user; + + if (forcePrincipalAsString) { + principalToReturn = user.getUsername(); + } + + return createSuccessAuthentication(principalToReturn, authentication, user); + } + + /** + * Creates a successful {@link Authentication} object. + *

+ * Protected so subclasses can override. + *

+ *

+ * Subclasses will usually store the original credentials the user supplied (not + * salted or encoded passwords) in the returned Authentication object. + *

+ * + * @param principal that should be the principal in the returned object (defined by + * the {@link #isForcePrincipalAsString()} method) + * @param authentication that was presented to the provider for validation + * @param user that was loaded by the implementation + * + * @return the successful authentication token + */ + protected Authentication createSuccessAuthentication(Object principal, + Authentication authentication, UserDetails user) { + // Ensure we return the original credentials the user supplied, + // so subsequent attempts are successful even with encoded passwords. + // Also ensure we return the original getDetails(), so that future + // authentication events after cache expiry contain the details + SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken( + principal, authentication.getCredentials(), + authoritiesMapper.mapAuthorities(user.getAuthorities())); + result.setDetails(authentication.getDetails()); + + return result; + } + + protected void doAfterPropertiesSet() { + } + + public UserCache getUserCache() { + return userCache; + } + + public boolean isForcePrincipalAsString() { + return forcePrincipalAsString; + } + + public boolean isHideUserNotFoundExceptions() { + return hideUserNotFoundExceptions; + } + + /** + * Allows subclasses to actually retrieve the UserDetails from an + * implementation-specific location, with the option of throwing an + * AuthenticationException immediately if the presented credentials are + * incorrect (this is especially useful if it is necessary to bind to a resource as + * the user in order to obtain or generate a UserDetails). + *

+ * Subclasses are not required to perform any caching, as the + * AbstractSmsAuthenticationProvider will by default cache the + * UserDetails. The caching of UserDetails does present + * additional complexity as this means subsequent requests that rely on the cache will + * need to still have their credentials validated, even if the correctness of + * credentials was assured by subclasses adopting a binding-based strategy in this + * method. Accordingly it is important that subclasses either disable caching (if they + * want to ensure that this method is the only method that is capable of + * authenticating a request, as no UserDetails will ever be cached) or + * ensure subclasses implement + * {@link #additionalAuthenticationChecks(UserDetails, SmsCodeAuthenticationToken)} + * to compare the credentials of a cached UserDetails with subsequent + * authentication requests. + *

+ *

+ * Most of the time subclasses will not perform credentials inspection in this method, + * instead performing it in + * {@link #additionalAuthenticationChecks(UserDetails, SmsCodeAuthenticationToken)} + * so that code related to credentials validation need not be duplicated across two + * methods. + *

+ * + * @param username The username to retrieve + * @param authentication The authentication request, which subclasses may + * need to perform a binding-based retrieval of the UserDetails + * + * @return the user information (never null - instead an exception should + * the thrown) + * + * @throws AuthenticationException if the credentials could not be validated + * (generally a BadCredentialsException, an + * AuthenticationServiceException or + * UsernameNotFoundException) + */ + protected abstract UserDetails retrieveUser(String username, + SmsCodeAuthenticationToken authentication) + throws AuthenticationException; + + public void setForcePrincipalAsString(boolean forcePrincipalAsString) { + this.forcePrincipalAsString = forcePrincipalAsString; + } + + /** + * By default the AbstractSmsAuthenticationProvider throws a + * BadCredentialsException if a username is not found or the password is + * incorrect. Setting this property to false will cause + * UsernameNotFoundExceptions to be thrown instead for the former. Note + * this is considered less secure than throwing BadCredentialsException + * for both exceptions. + * + * @param hideUserNotFoundExceptions set to false if you wish + * UsernameNotFoundExceptions to be thrown instead of the non-specific + * BadCredentialsException (defaults to true) + */ + public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) { + this.hideUserNotFoundExceptions = hideUserNotFoundExceptions; + } + + @Override + public void setMessageSource(MessageSource messageSource) { + this.messages = new MessageSourceAccessor(messageSource); + } + + public void setUserCache(UserCache userCache) { + this.userCache = userCache; + } + + @Override + public boolean supports(Class authentication) { + return (SmsCodeAuthenticationToken.class + .isAssignableFrom(authentication)); + } + + protected UserDetailsChecker getPreAuthenticationChecks() { + return preAuthenticationChecks; + } + + /** + * Sets the policy will be used to verify the status of the loaded + * UserDetails before validation of the credentials takes place. + * + * @param preAuthenticationChecks strategy to be invoked prior to authentication. + */ + public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) { + this.preAuthenticationChecks = preAuthenticationChecks; + } + + protected UserDetailsChecker getPostAuthenticationChecks() { + return postAuthenticationChecks; + } + + public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) { + this.postAuthenticationChecks = postAuthenticationChecks; + } + + public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { + this.authoritiesMapper = authoritiesMapper; + } + + private class DefaultPreAuthenticationChecks implements UserDetailsChecker { + @Override + public void check(UserDetails user) { + if (!user.isAccountNonLocked()) { + logger.debug("User account is locked"); + + throw new LockedException(messages.getMessage( + "AbstractSmsAuthenticationProvider.locked", + "User account is locked")); + } + + if (!user.isEnabled()) { + logger.debug("User account is disabled"); + + throw new DisabledException(messages.getMessage( + "AbstractSmsAuthenticationProvider.disabled", + "User is disabled")); + } + + if (!user.isAccountNonExpired()) { + logger.debug("User account is expired"); + + throw new AccountExpiredException(messages.getMessage( + "AbstractSmsAuthenticationProvider.expired", + "User account has expired")); + } + } + } + + private class DefaultPostAuthenticationChecks implements UserDetailsChecker { + @Override + public void check(UserDetails user) { + if (!user.isCredentialsNonExpired()) { + logger.debug("User account credentials have expired"); + + throw new CredentialsExpiredException(messages.getMessage( + "AbstractSmsAuthenticationProvider.credentialsExpired", + "User credentials have expired")); + } + } + } + } + diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/Sm4AuthenticationProvider.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/Sm4AuthenticationProvider.java new file mode 100644 index 0000000..6479a42 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/Sm4AuthenticationProvider.java @@ -0,0 +1,92 @@ +package com.njcn.product.auth.security.provider; + +import com.njcn.common.utils.sm.Sm4Utils; +import com.njcn.product.auth.pojo.bo.BusinessUser; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.InternalAuthenticationServiceException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Component; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年06月08日 15:43 + */ +@Slf4j +@Component +@AllArgsConstructor +public class Sm4AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { + + private final UserDetailsService userDetailsService; + + + /** + * 校验密码有效性. + * + * @param userDetails 用户详细信息 + * @param authentication 用户登录的密码 + * @throws AuthenticationException . + */ + @Override + protected void additionalAuthenticationChecks( + UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) + throws AuthenticationException { + if (authentication.getCredentials() == null) { + logger.debug("Authentication failed: no credentials provided"); + + throw new BadCredentialsException(messages.getMessage( + "AbstractUserDetailsAuthenticationProvider.badCredentials", + "Bad credentials")); + } + + String presentedPassword = authentication.getCredentials().toString(); + BusinessUser businessUser = (BusinessUser)userDetails; + String secretKey = businessUser.getSecretKey(); + Sm4Utils sm4 = new Sm4Utils(secretKey); + //SM4加密密码 + String sm4PwdOnce = sm4.encryptData_ECB(presentedPassword); + //SM4加密(密码+工作秘钥) + String sm4PwdTwice = sm4.encryptData_ECB(sm4PwdOnce + secretKey); + if(!businessUser.getPassword().equalsIgnoreCase(sm4PwdTwice)){ + throw new BadCredentialsException(messages.getMessage( + "AbstractUserDetailsAuthenticationProvider.badCredentials", + businessUser.getUsername())); + } + } + + /** + * 获取用户 + * + * @param username 用户名 + * @param authentication 认证token + * @throws AuthenticationException . + */ + @Override + protected UserDetails retrieveUser( + String username, UsernamePasswordAuthenticationToken authentication) + throws AuthenticationException { + UserDetails loadedUser = userDetailsService.loadUserByUsername(username); + if (loadedUser == null) { + throw new InternalAuthenticationServiceException( + "UserDetailsService returned null, which is an interface contract violation"); + } + return loadedUser; + } + + + /** + * 授权持久化. + */ + @Override + protected Authentication createSuccessAuthentication(Object principal, + Authentication authentication, UserDetails user) { + return super.createSuccessAuthentication(principal, authentication, user); + } +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/SmsAuthenticationProvider.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/SmsAuthenticationProvider.java new file mode 100644 index 0000000..59c6cf6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/provider/SmsAuthenticationProvider.java @@ -0,0 +1,74 @@ +package com.njcn.product.auth.security.provider; + + +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.security.token.SmsCodeAuthenticationToken; +import com.njcn.product.auth.service.UserDetailsServiceImpl; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +/** + * 手机短信码验证完后,返回用户的 + * @author hongawen + * @version 1.0.0 + * @date 2021年06月08日 15:43 + */ +@Slf4j +@Component +@AllArgsConstructor +public class SmsAuthenticationProvider extends AbstractSmsAuthenticationProvider { + + private final UserDetailsServiceImpl userDetailsService; + + + /** + * 校验密码有效性. + * 因为手机号验证码登录,验证码没问题后,密码无需校验,直接返回该用户的token信息便可以 + * + * @param userDetails 用户详细信息 + * @param authentication 用户登录的密码 + * @throws AuthenticationException . + */ + @Override + protected void additionalAuthenticationChecks( + UserDetails userDetails, SmsCodeAuthenticationToken authentication) + throws AuthenticationException { + + } + + /** + * 获取用户 + * + * @param phone 手机号 + * @param authentication 认证token + * @throws AuthenticationException . + */ + @Override + protected UserDetails retrieveUser( + String phone, SmsCodeAuthenticationToken authentication) + throws AuthenticationException { + //根据手机号获取用户信息 + UserDetails loadedUser = userDetailsService.loadUserByPhone(phone); + if (loadedUser == null) { + throw new BusinessException(UserResponseEnum.LOGIN_PHONE_NOT_REGISTER); + } + return loadedUser; + } + + + /** + * 授权持久化. + */ + @Override + protected Authentication createSuccessAuthentication(Object principal, + Authentication authentication, UserDetails user) { + return super.createSuccessAuthentication(principal, authentication, user); + } + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/security/token/SmsCodeAuthenticationToken.java b/carry_capacity/src/main/java/com/njcn/product/auth/security/token/SmsCodeAuthenticationToken.java new file mode 100644 index 0000000..a2c2cf0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/security/token/SmsCodeAuthenticationToken.java @@ -0,0 +1,62 @@ +package com.njcn.product.auth.security.token; + +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.util.Assert; + +import java.util.Collection; + +/** + * UsernamePasswordAuthenticationToken 一样, + * 继承 AbstractAuthenticationToken 抽象类, + * 需要实现 getPrincipal 和 getCredentials 两个方法。 + * 在用户名/密码认证中,principal 表示用户名, + * credentials 表示密码,在此,我们可以让它们指代手机号和验证码。 + * + * @author hongawen + * @version 1.0.0 + * @date 2023年06月14日 16:25 + */ +public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken { + + private final Object principal; + + private Object credentials; + + public SmsCodeAuthenticationToken(Object principal, Object credentials) { + super(null); + this.principal = principal; + this.credentials = credentials; + setAuthenticated(false); + } + public SmsCodeAuthenticationToken(Object principal, Object credentials, + Collection authorities) { + super(authorities); + this.principal = principal; + this.credentials = credentials; + super.setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return this.credentials; + } + + @Override + public Object getPrincipal() { + return this.principal; + } + + @Override + public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { + Assert.isTrue(!isAuthenticated, + "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); + super.setAuthenticated(false); + } + + @Override + public void eraseCredentials() { + super.eraseCredentials(); + this.credentials = null; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/CustomUserDetailsService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/CustomUserDetailsService.java new file mode 100644 index 0000000..2d8846c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/CustomUserDetailsService.java @@ -0,0 +1,27 @@ +package com.njcn.product.auth.service; + +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年06月15日 10:26 + */ +public interface CustomUserDetailsService extends UserDetailsService { + + /** + * @param username 用户名 + * @return 用户信息 + */ + @Override + UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; + + /** + * @param phone 手机号 + * @return 用户信息 + */ + UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IAuthClientService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IAuthClientService.java new file mode 100644 index 0000000..dddb13f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IAuthClientService.java @@ -0,0 +1,22 @@ +package com.njcn.product.auth.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.auth.pojo.po.AuthClient; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-15 + */ +public interface IAuthClientService extends IService { + + /** + * 根据客户端名称获取客户端 + * @param clientName 客户端名称 + * @return . + */ + AuthClient getAuthClientByName(String clientName); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IRoleService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IRoleService.java new file mode 100644 index 0000000..db4ac71 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IRoleService.java @@ -0,0 +1,26 @@ +package com.njcn.product.auth.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.auth.pojo.po.Role; + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IRoleService extends IService { + + /** + * 根据用户id获取角色名 + * @param id 用户id + * @return 角色名集合 + */ + List getRoleNameByUserId(String id); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserRoleService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserRoleService.java new file mode 100644 index 0000000..797d658 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserRoleService.java @@ -0,0 +1,30 @@ +package com.njcn.product.auth.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.auth.pojo.po.UserRole; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IUserRoleService extends IService { + + /** + * 根据用户索引获取 用户--角色关系数据 + * @param id 用户ID + * @return 关系数据 + */ + List getUserRoleByUserId(String id); + + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserService.java new file mode 100644 index 0000000..bef36d8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserService.java @@ -0,0 +1,61 @@ +package com.njcn.product.auth.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.auth.pojo.dto.UserDTO; +import com.njcn.product.auth.pojo.param.UserParam; +import com.njcn.product.auth.pojo.po.User; +import com.njcn.product.auth.pojo.vo.UserVO; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IUserService extends IService { + + /** + * 根据登录名获取用户信息 + * @param loginName 登录名 + * @return 用户信息 + */ + UserDTO getUserByName(String loginName); + + /** + * 认证结束后,判断用户状态是否能正常访问系统 + * @param loginName 登录名 + */ + void judgeUserStatus(String loginName);//used + + + /** + * 功能描述:修改用户登录认证密码错误次数 + * @param loginName 登录名 + * @return boolean + * @author xy + */ + String updateUserLoginErrorTimes(String loginName);//used + + + UserDTO loadUserByPhone(String phone); + + /** + * 功能描述:根据用户id获取用户详情 + * TODO + * + * @param id + * @return com.njcn.user.pojo.vo.UserVO + * @author xy + * @date 2022/1/13 17:10 + */ + UserVO getUserById(String id); + List simpleList(Boolean allUserFlag); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserSetService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserSetService.java new file mode 100644 index 0000000..1c4d506 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserSetService.java @@ -0,0 +1,18 @@ +package com.njcn.product.auth.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.auth.pojo.po.UserSet; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IUserSetService extends IService { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserStrategyService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserStrategyService.java new file mode 100644 index 0000000..4356ee6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/IUserStrategyService.java @@ -0,0 +1,22 @@ +package com.njcn.product.auth.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.auth.pojo.po.UserStrategy; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IUserStrategyService extends IService { + + /** + * 查询用户策略数据 + * @return 用户策略信息 + * @param casualUser 是否为 casual用户 + */ + UserStrategy getUserStrategy(Integer casualUser); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/UserDetailsServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/UserDetailsServiceImpl.java new file mode 100644 index 0000000..a0ec652 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/UserDetailsServiceImpl.java @@ -0,0 +1,64 @@ +package com.njcn.product.auth.service; + +import cn.hutool.core.bean.BeanUtil; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.product.auth.pojo.bo.BusinessUser; +import com.njcn.product.auth.pojo.dto.UserDTO; +import com.njcn.web.utils.RequestUtil; +import lombok.AllArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + + +/** + * @author hongawen + *

+ * 自定义用户认证和授权 + */ +@Slf4j +@Service +@AllArgsConstructor +public class UserDetailsServiceImpl implements CustomUserDetailsService { + + private final IUserService userService; + + + @SneakyThrows + @Override + public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException { + String clientId = RequestUtil.getOAuth2ClientId(); + BusinessUser businessUser = new BusinessUser(loginName, null, null); + businessUser.setClientId(clientId); + UserDTO userDTO = userService.getUserByName(loginName); + LogUtil.njcnDebug(log, "用户认证时,用户名:{}获取用户信息:{}", loginName, userDTO.toString()); + //成功获取用户信息 + BeanUtil.copyProperties(userDTO, businessUser, true); + //处理头像 +// dealHead(businessUser); + businessUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", userDTO.getRoleName()))); + return businessUser; + } + + + @Override + public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException { + String clientId = RequestUtil.getOAuth2ClientId(); + BusinessUser businessUser = new BusinessUser(phone, null, null); + businessUser.setClientId(clientId); + UserDTO userDTO = userService.loadUserByPhone(phone); + LogUtil.njcnDebug(log, "用户验证码认证时,用户名:{}获取用户信息:{}", phone, userDTO.toString()); + //成功获取用户信息 + BeanUtil.copyProperties(userDTO, businessUser, true); +// dealHead(businessUser); + businessUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", userDTO.getRoleName()))); + return businessUser; + } + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/UserTokenService.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/UserTokenService.java new file mode 100644 index 0000000..ad2d6e6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/UserTokenService.java @@ -0,0 +1,128 @@ +package com.njcn.product.auth.service; + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.nimbusds.jose.JWSObject; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.dto.UserTokenInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.redis.utils.RedisUtil; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.scheduling.annotation.Async; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.OAuth2RefreshToken; +import org.springframework.stereotype.Service; + +import java.text.ParseException; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年03月11日 10:34 + */ +@Slf4j +@Service +@AllArgsConstructor +public class UserTokenService { + + private final RedisUtil redisUtil; + + /** + * 记录用户token信息,并经过处理后达到最新登录的使用者,将之前的token信息置为黑名单,过期状态 + * 1、从在线名单中获取该用户的token信息,key为:TOKEN_ONLINE_PREFIX+userid,value为userTokenInfo的json对象 + * 1.1 有,则表示有人使用该账户登录过 + * 1.1.1 将在线名单的用户信息添加到黑名单,并清除黑名单中已经过期的token信息 + * ,重新赋值黑名单信息,key为:TOKEN_BLACKLIST_PREFIX+userid,value为userTokenInfo的集合 + * 1.2 没有,该账号当前只有本人在登录,将当前token等信息保存到白名单 + * + * @param oAuth2AccessToken 认证后的最新token信息 + */ + @Async("asyncExecutor") + public void recordUserInfo(OAuth2AccessToken oAuth2AccessToken, String ip) { + UserTokenInfo userTokenInfo = new UserTokenInfo(); + String accessTokenValue = oAuth2AccessToken.getValue(); + JWSObject accessJwsObject; + try { + accessJwsObject = JWSObject.parse(accessTokenValue); + } catch (ParseException e) { + throw new BusinessException(CommonResponseEnum.PARSE_TOKEN_ERROR); + } + JSONObject accessJson = JSONUtil.parseObj(accessJwsObject.getPayload().toString()); + String userIndex = accessJson.getStr(SecurityConstants.USER_INDEX_KEY); + // String nickName = accessJson.getStr(SecurityConstants.USER_NICKNAME_KEY); + // String loginName = accessJson.getStr(SecurityConstants.USER_NAME_KEY); + //查询是否有在线的当前用户 + String onlineUserKey = SecurityConstants.TOKEN_ONLINE_PREFIX + userIndex; + Object onlineTokenInfoOld = redisUtil.getObjectByKey(onlineUserKey); + if (!Objects.isNull(onlineTokenInfoOld)) { + //存在在线用户,将在线用户添加到黑名单列表 + String blackUserKey = SecurityConstants.TOKEN_BLACKLIST_PREFIX + userIndex; + List blackUsers = (List) redisUtil.getObjectByKey(blackUserKey); + if (CollectionUtils.isEmpty(blackUsers)) { + blackUsers = new ArrayList<>(); + } + blackUsers.add((UserTokenInfo) onlineTokenInfoOld); + //筛选黑名单中是否存在过期的token信息 + blackUsers.removeIf(userTokenInfoTemp -> userTokenInfoTemp.getRefreshTokenExpire().isBefore(LocalDateTime.now())); + //将黑名单集合重新缓存,此处根据最新的黑名单计算当前这个key的生命周期,在时间差的基础上增加5分钟的延迟时间 + LocalDateTime refreshTokenExpire = ((UserTokenInfo) onlineTokenInfoOld).getRefreshTokenExpire(); + long lifeTime = Math.abs(refreshTokenExpire.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); + redisUtil.saveByKeyWithExpire(blackUserKey, blackUsers, lifeTime); + } + String accessJti = accessJson.getStr(SecurityConstants.JWT_JTI); + OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken(); + JWSObject refreshJwsObject; + try { + refreshJwsObject = JWSObject.parse(refreshToken.getValue()); + } catch (ParseException e) { + throw new BusinessException(CommonResponseEnum.PARSE_TOKEN_ERROR); + } + JSONObject refreshJson = JSONUtil.parseObj(refreshJwsObject.getPayload().toString()); + // String refreshJti = refreshJson.getStr(SecurityConstants.JWT_JTI); + Long refreshExpireTime = refreshJson.getLong(SecurityConstants.JWT_EXP); + userTokenInfo.setAccessTokenJti(accessJti); + userTokenInfo.setRefreshToken(refreshToken.getValue()); + LocalDateTime refreshLifeTime = LocalDateTime.ofEpochSecond(refreshExpireTime, 0, ZoneOffset.of("+8")); + userTokenInfo.setRefreshTokenExpire(refreshLifeTime); + //生命周期在refreshToken的基础上,延迟5分钟 + redisUtil.saveByKeyWithExpire(onlineUserKey, userTokenInfo, refreshLifeTime.plusMinutes(5L).toEpochSecond(ZoneOffset.of("+8")) - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); + + //记录成功登录后的信息 + //LogInfoDTO logInfoDTO = new LogInfoDTO(loginName, nickName, ip, "登录认证", OperateType.AUTHENTICATE, 1, "", 0, 1, generalInfo.getMicroServiceName(), userIndex,LocalDateTime.now()); + //publisher.send("/userLog", PubUtils.obj2json(logInfoDTO), 2, false); + } + + /** + * 校验刷新token是否被加入黑名单 + * + * @param refreshToken 刷新token + */ + public void judgeRefreshToken(String refreshToken) { + JWSObject refreshJwsObject; + try { + refreshJwsObject = JWSObject.parse(refreshToken); + } catch (ParseException e) { + throw new BusinessException(); + } + JSONObject refreshJson = JSONUtil.parseObj(refreshJwsObject.getPayload().toString()); + String userIndex = refreshJson.getStr(SecurityConstants.USER_INDEX_KEY); + String blackUserKey = SecurityConstants.TOKEN_BLACKLIST_PREFIX + userIndex; + List blackUsers = (List) redisUtil.getObjectByKey(blackUserKey); + if (CollectionUtils.isNotEmpty(blackUsers)) { + blackUsers.forEach(temp -> { + //存在当前的刷新token,则抛出业务异常 + if (temp.getRefreshToken().equalsIgnoreCase(refreshToken)) { + throw new BusinessException(CommonResponseEnum.TOKEN_EXPIRE_JWT); + } + }); + } + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/AuthClientServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/AuthClientServiceImpl.java new file mode 100644 index 0000000..fdfb047 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/AuthClientServiceImpl.java @@ -0,0 +1,32 @@ +package com.njcn.product.auth.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; + +import com.njcn.product.auth.mapper.AuthClientMapper; +import com.njcn.product.auth.pojo.po.AuthClient; +import com.njcn.product.auth.service.IAuthClientService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-15 + */ +@Service +@RequiredArgsConstructor +public class AuthClientServiceImpl extends ServiceImpl implements IAuthClientService { + + @Override + public AuthClient getAuthClientByName(String clientName) { + return lambdaQuery() + .eq(AuthClient::getName,clientName) + .eq(AuthClient::getState,DataStateEnum.ENABLE.getCode()) + .one(); + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/RoleServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/RoleServiceImpl.java new file mode 100644 index 0000000..638395f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/RoleServiceImpl.java @@ -0,0 +1,57 @@ +package com.njcn.product.auth.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; + +import com.njcn.product.auth.mapper.RoleMapper; +import com.njcn.product.auth.pojo.po.Role; +import com.njcn.product.auth.pojo.po.UserRole; +import com.njcn.product.auth.service.IRoleService; +import com.njcn.product.auth.service.IUserRoleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +public class RoleServiceImpl extends ServiceImpl implements IRoleService { + + private final IUserRoleService iUserRoleService; + + + + @Override + public List getRoleNameByUserId(String id) { + List userRoles = iUserRoleService.getUserRoleByUserId(id); + if (CollectionUtils.isEmpty(userRoles)) { + return new ArrayList<>(); + } + List roles = this.lambdaQuery() + .select(Role::getCode) + .eq(Role::getState, DataStateEnum.ENABLE.getCode()) + .in(Role::getId, userRoles.stream() + .map(UserRole::getRoleId) + .collect(Collectors.toList()) + ).list(); + return roles + .stream() + .map(Role::getCode) + .distinct() + .collect(Collectors.toList()); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserRoleServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserRoleServiceImpl.java new file mode 100644 index 0000000..0c5f8e3 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserRoleServiceImpl.java @@ -0,0 +1,39 @@ +package com.njcn.product.auth.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.product.auth.mapper.UserRoleMapper; +import com.njcn.product.auth.pojo.po.Role; +import com.njcn.product.auth.pojo.po.UserRole; +import com.njcn.product.auth.service.IUserRoleService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@AllArgsConstructor +public class UserRoleServiceImpl extends ServiceImpl implements IUserRoleService { + + private final UserRoleMapper userRoleMapper; + + @Override + public List getUserRoleByUserId(String id) { + return this.lambdaQuery().eq(UserRole::getUserId, id).list(); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..6478708 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserServiceImpl.java @@ -0,0 +1,309 @@ +package com.njcn.product.auth.service.impl; + + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.StrUtil; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.config.GeneralInfo; +import com.njcn.common.pojo.constant.LogInfo; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.PubUtils; + +import com.njcn.product.auth.pojo.dto.UserDTO; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.pojo.enums.UserStatusEnum; +import com.njcn.product.auth.mapper.UserMapper; +import com.njcn.product.auth.pojo.constant.UserState; + +import com.njcn.product.auth.pojo.po.*; +import com.njcn.product.auth.pojo.vo.UserVO; +import com.njcn.product.auth.service.*; + +import com.njcn.product.system.dept.pojo.po.Dept; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + + +import javax.validation.constraints.NotNull; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.*; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +public class UserServiceImpl extends ServiceImpl implements IUserService { + + + + private final IUserStrategyService userStrategyService; + private final IRoleService roleService; + private final IUserSetService userSetService; + + + @Override + public UserDTO getUserByName(String loginName) { + User user = getUserByLoginName(loginName); + if (Objects.isNull(user)) { + return null; + } + List roleNames = roleService.getRoleNameByUserId(user.getId()); + UserSet userSet = userSetService.lambdaQuery().eq(UserSet::getUserId, user.getId()).one(); + return new UserDTO(user.getId(), user.getLoginName(), user.getName(), user.getPassword(), roleNames, userSet.getSecretKey(), userSet.getStandBy(), user.getDeptId(), user.getType(), user.getHeadSculpture()); + } + + + @Override + public void judgeUserStatus(String loginName) { + User user = getUserByLoginName(loginName); + if (Objects.isNull(user)) { + throw new BusinessException(UserResponseEnum.LOGIN_WRONG_PWD); + } + //超级管理员则不做任何逻辑判断 + if (user.getType() == 0) { + //更新用户登录时间,以及错误登录记录的信息归零。 + user.setState(UserState.ENABLE); + user.setLoginErrorTimes(0); + user.setLoginTime(LocalDateTime.now()); + user.setFirstErrorTime(null); + user.setLockTime(null); + this.baseMapper.updateById(user); + return; + } + //根据用户类型获取对应用户策略 + UserStrategy userStrategy = userStrategyService.lambdaQuery() + .eq(UserStrategy::getType, user.getCasualUser()) + .eq(UserStrategy::getState, DataStateEnum.ENABLE.getCode()) + .one(); + switch (user.getState()) { + case UserState.LOCKED: + LocalDateTime lockTime = user.getLockTime(); + lockTime = lockTime.plusMinutes(userStrategy.getLockPwdTime()); + LocalDateTime nowTime = LocalDateTime.now(); + //判断是否满足锁定时间 + if (nowTime.isBefore(lockTime)) { + CommonResponseEnum testEnum = CommonResponseEnum.DYNAMIC_RESPONSE_ENUM; + testEnum.setMessage("账号已被锁定:锁定剩余时长" + ChronoUnit.MINUTES.between(nowTime, lockTime) + "分钟"); + throw new BusinessException(testEnum); + } + break; + case UserState.DELETE: + //用户已注销 + throw new BusinessException(UserResponseEnum.LOGIN_USER_DELETE); + case UserState.UNCHECK: + //用户未审核 + throw new BusinessException(UserResponseEnum.LOGIN_USER_UNAUDITED); + case UserState.SLEEP: + //用户已休眠 + throw new BusinessException(UserResponseEnum.LOGIN_USER_SLEEP); + case UserState.OVERDUE: + //用户密码已过期 + throw new BusinessException(UserResponseEnum.LOGIN_USER_PASSWORD_EXPIRED); + default: + if (user.getPwdState() == 1) { + throw new BusinessException(UserResponseEnum.NEED_MODIFY_PWD); + } + //用户状态正常,判断其他细节 + judgeFirstLogin(user, userStrategy); + } + //所有验证通过后,更新用户登录时间,以及错误登录记录的信息归零。 + user.setState(UserState.ENABLE); + user.setLoginErrorTimes(0); + user.setLoginTime(LocalDateTime.now()); + user.setFirstErrorTime(null); + user.setLockTime(null); + this.baseMapper.updateById(user); + } + + /** + * 根据登录名查询用户 + * + * @param loginName 登录名 + * @return 用户信息 + */ + private User getUserByLoginName(String loginName) { + return lambdaQuery() + .eq(User::getLoginName, loginName) + .one(); + } + /** + * 判断是否需要修改密码 + */ + private void judgeFirstLogin(@NotNull User user, UserStrategy userStrategy) { + if (user.getPwdState() == 1) { + throw new BusinessException(UserResponseEnum.NEED_MODIFY_PWD); + } else { + judgeIp(user, userStrategy); + } + } + + /** + * 判断用户是否在合理的IP内登录 + */ + private void judgeIp(@NotNull User user, UserStrategy userStrategy) { + String ipSection = user.getLimitIpStart() + "-" + user.getLimitIpEnd(); + log.error("用户实际ip:" + RequestUtil.getRealIp()); + log.error("用户限制ip:" + ipSection); + if (RequestUtil.getRealIp().equalsIgnoreCase(LogInfo.UNKNOWN_IP)) { + //feign接口可能获取的IP是空的 + throw new BusinessException(UserResponseEnum.INVALID_IP); + } else if (!PubUtils.ipExistsInRange(RequestUtil.getRealIp(), ipSection)) { + throw new BusinessException(UserResponseEnum.INVALID_IP); + } else { + judgeLimitTime(user, userStrategy); + } + judgeLimitTime(user, userStrategy); + } + + /** + * 判断用户是否在允许的时间段内登录 + */ + private void judgeLimitTime(@NotNull User user, UserStrategy userStrategy) { + int nowHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + String[] limitTime = user.getLimitTime().split(StrUtil.DASHED); + if (nowHour >= Integer.parseInt(limitTime[0]) && nowHour < Integer.parseInt(limitTime[1])) { + judgePwdTimeValidity(user, userStrategy); + } else { + throw new BusinessException(UserResponseEnum.INVALID_TIME); + } + } + + /** + * 判断用户密码是否已经过期 + */ + private void judgePwdTimeValidity(@NotNull User user, UserStrategy userStrategy) { + LocalDateTime pwdValidity = user.getPwdValidity(); + pwdValidity = pwdValidity.plusMonths(userStrategy.getLimitPwdDate()); + if (LocalDateTime.now().isBefore(pwdValidity)) { + judgeLeisurePwd(user, userStrategy); + } else { + //将用户状态置为过期 + user.setState(UserState.OVERDUE); + this.baseMapper.updateById(user); + throw new BusinessException(UserResponseEnum.LOGIN_USER_PASSWORD_EXPIRED); + } + + } + + /** + * 判断用户闲置 + */ + private void judgeLeisurePwd(@NotNull User user, UserStrategy userStrategy) { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime sleepTime = user.getLoginTime().plusDays(userStrategy.getSleep()); + LocalDateTime logoutTime = user.getLoginTime().plusDays(userStrategy.getLogout()); + if (now.isAfter(sleepTime) && now.isBefore(logoutTime)) { + //将用户状态置为休眠 + user.setState(UserState.SLEEP); + this.baseMapper.updateById(user); + throw new BusinessException(UserResponseEnum.LOGIN_USER_SLEEP); + } else if (now.isAfter(logoutTime)) { + //将用户状态置为注销 + user.setState(UserState.DELETE); + this.baseMapper.updateById(user); + throw new BusinessException(UserResponseEnum.LOGIN_USER_DELETE); + } + } + @Override + public UserDTO loadUserByPhone(String phone) { + User user = getUserByPhone(phone, false, null); + if (Objects.isNull(user)) { + return null; + } + List roleNames = roleService.getRoleNameByUserId(user.getId()); + UserSet userSet = userSetService.lambdaQuery().eq(UserSet::getUserId, user.getId()).one(); + return new UserDTO(user.getId(), user.getLoginName(), user.getName(), user.getPassword(), roleNames, userSet.getSecretKey(), userSet.getStandBy(), user.getDeptId(), user.getType(), user.getHeadSculpture()); + } + + @Override + public UserVO getUserById(String id) { + UserVO userVO = new UserVO(); + User user = lambdaQuery().eq(User::getId, id).one(); + if (Objects.isNull(user)) { + return null; + } + BeanUtil.copyProperties(user, userVO); + + return userVO; + } + + @Override + public List simpleList(Boolean allUserFlag) { + LambdaQueryWrapper userLambdaQueryWrapper = new LambdaQueryWrapper<>(); + userLambdaQueryWrapper.select(User::getId, User::getName,User::getLoginName).eq(User::getState, DataStateEnum.ENABLE.getCode()); + if(!allUserFlag){ + userLambdaQueryWrapper.eq(User::getType,2); + } + return this.baseMapper.selectList(userLambdaQueryWrapper); + } + + + /** + * 根据手机号查询用户 + * + * @param phone 手机号码 + * @return 用户信息 + */ + private User getUserByPhone(String phone, boolean result, String id) { + if (result) { + return lambdaQuery() + .eq(User::getPhone, phone) + .ne(User::getId, id) + .one(); + } else { + return lambdaQuery() + .eq(User::getPhone, phone) + .one(); + } + } + + @Override + public String updateUserLoginErrorTimes(String loginName) { + User user = this.lambdaQuery().eq(User::getLoginName, loginName).one(); + LocalDateTime now = LocalDateTime.now(); + if (Objects.nonNull(user)) { + UserStrategy userStrategy = userStrategyService.getUserStrategy(user.getCasualUser()); + Integer loginErrorTimes = user.getLoginErrorTimes(); + ++loginErrorTimes; + if (Objects.isNull(user.getFirstErrorTime())) { + //首次错误,错误1次、记录第一次错误时间 + user.setLoginErrorTimes(loginErrorTimes); + user.setFirstErrorTime(LocalDateTime.now()); + } else if (loginErrorTimes <= userStrategy.getLimitPwdTimes()) { + //如果次数在策略之内,还未被锁定 + LocalDateTime firstErrorTime = user.getFirstErrorTime(); + firstErrorTime = firstErrorTime.plusMinutes(userStrategy.getLockPwdCheck()); + if (now.isAfter(firstErrorTime)) { + //重置密码错误次数、时间等记录 + user.setLoginErrorTimes(1); + user.setFirstErrorTime(LocalDateTime.now()); + } else { + user.setLoginErrorTimes(loginErrorTimes); + } + } else { + user.setLockTime(LocalDateTime.now()); + user.setState(UserStatusEnum.LOCKED.getCode()); + user.setLoginErrorTimes(loginErrorTimes); + this.baseMapper.updateById(user); + return UserResponseEnum.LOGIN_USER_LOCKED.getMessage(); + } + this.baseMapper.updateById(user); + } + return CommonResponseEnum.SUCCESS.getMessage(); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserSetServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserSetServiceImpl.java new file mode 100644 index 0000000..cd09301 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserSetServiceImpl.java @@ -0,0 +1,29 @@ +package com.njcn.product.auth.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.auth.mapper.UserSetMapper; +import com.njcn.product.auth.pojo.po.UserSet; +import com.njcn.product.auth.service.IUserSetService; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; + +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +public class UserSetServiceImpl extends ServiceImpl implements IUserSetService { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserStrategyServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserStrategyServiceImpl.java new file mode 100644 index 0000000..200d6e0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/service/impl/UserStrategyServiceImpl.java @@ -0,0 +1,37 @@ +package com.njcn.product.auth.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.mapper.UserStrategyMapper; +import com.njcn.product.auth.pojo.po.UserStrategy; +import com.njcn.product.auth.service.IUserStrategyService; +import org.springframework.stereotype.Service; + +import java.util.Objects; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +public class UserStrategyServiceImpl extends ServiceImpl implements IUserStrategyService { + + @Override + public UserStrategy getUserStrategy(Integer casualUser) { + UserStrategy userStrategy = this.lambdaQuery() + .eq(UserStrategy::getState, DataStateEnum.ENABLE.getCode()) + .eq(UserStrategy::getType, casualUser) + .one(); + if (Objects.isNull(userStrategy)) { + throw new BusinessException(UserResponseEnum.LACK_USER_STRATEGY); + } + return userStrategy; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/auth/utils/AuthPubUtil.java b/carry_capacity/src/main/java/com/njcn/product/auth/utils/AuthPubUtil.java new file mode 100644 index 0000000..e8cb412 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/auth/utils/AuthPubUtil.java @@ -0,0 +1,41 @@ +package com.njcn.product.auth.utils; + +import cn.hutool.core.util.RandomUtil; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.nimbusds.jose.JWSObject; +import lombok.SneakyThrows; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年06月04日 14:00 + */ +public class AuthPubUtil { + + public static String getKaptchaText(int codeLength) { + StringBuilder code = new StringBuilder(); + int letterLength = RandomUtil.randomInt(codeLength - 1) + 1; + code.append(RandomUtil.randomString(RandomUtil.BASE_CHAR, letterLength).toUpperCase(Locale.ROOT)); + int numberLength = codeLength - letterLength; + code.append(RandomUtil.randomString(RandomUtil.BASE_NUMBER, numberLength)); + List textList = Arrays.asList(code.toString().split("")); + //填充完字符后,打乱顺序,返回字符串 + Collections.shuffle(textList); + return String.join("", textList); + } + + + @SneakyThrows + public static JSONObject getLoginByToken(String token){ + JWSObject jwsObject = JWSObject.parse(token); + String payload = jwsObject.getPayload().toString(); + return JSONUtil.parseObj(payload); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityController.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityController.java new file mode 100644 index 0000000..8bc2c98 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityController.java @@ -0,0 +1,133 @@ +package com.njcn.product.carrycapacity.controller; + + +import com.alibaba.excel.EasyExcel; +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.product.carrycapacity.pojo.excel.CarryCapcityDataEexcel; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityCalParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityEvaluateParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.param.ExcelDataParam; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDResultVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataIVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataQVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataVO; +import com.njcn.product.carrycapacity.service.CarryCapacityService; +import com.njcn.product.carrycapacity.util.EasyExcelUtil; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:06 + */ +@RestController +@RequestMapping("carrycapacity") +@Api(tags = "承载能力评估") +@RequiredArgsConstructor +public class CarryCapacityController extends BaseController { + + + private final CarryCapacityService carryCapcityService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryCarryCapacityData") + @ApiOperation("承载能力评估数据查询-主页面") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult queryCarryCapacityData(@RequestBody @Validated CarryCapacityQueryDataParam queryParam) { + String methodDescribe = getMethodDescribe("queryCarryCapacityData"); + CarryCapacityDataVO carryCapacityDataVO = carryCapcityService.queryCarryCapacityData(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, carryCapacityDataVO, methodDescribe); + } + + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryCarryCapacityQData") + @ApiOperation("承载能力评估数据查询-无功功率") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult queryCarryCapacityQData(@RequestBody @Validated CarryCapacityQueryDataParam queryParam) { + String methodDescribe = getMethodDescribe("queryCarryCapacityQData"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, carryCapcityService.queryCarryCapacityqData(queryParam), methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryCarryCapacityIData") + @ApiOperation("承载能力评估数据查询-谐波电流幅值") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult queryCarryCapacityIData(@RequestBody @Validated CarryCapacityQueryDataParam queryParam) { + String methodDescribe = getMethodDescribe("queryCarryCapacityIData"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, carryCapcityService.queryCarryCapacityiData(queryParam), methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/carryCapacityCal") + @ApiOperation("承载能力评估") + @ApiImplicitParam(name = "calParam", value = "计算参数", required = true) + public HttpResult carryCapacityCal(@RequestBody @Validated CarryCapacityCalParam calParam) { + String methodDescribe = getMethodDescribe("carryCapacityCal"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, carryCapcityService.carryCapacityCal(calParam), methodDescribe); + } + +// @OperateInfo(info = LogEnum.BUSINESS_COMMON) +// @GetMapping("/carryCapacityTree") +// @ApiOperation("承载能力评估-台账树") +// public HttpResult> carryCapacityTree() { +// String methodDescribe = getMethodDescribe("carryCapacityTree"); +// List terminalTree = carryCapcityService.carryCapacityTree(); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, terminalTree, methodDescribe); +// } + + @ResponseBody + @ApiOperation("导出数据集模板") + @GetMapping(value = "getExcelTemplate") + public HttpResult getExcelTemplate(HttpServletResponse response) throws IOException { + String sheetName = "数据集模版"; + List excels = new ArrayList<>(); + CarryCapcityDataEexcel exportHeadersExcel = new CarryCapcityDataEexcel(); + excels.add(exportHeadersExcel); + EasyExcel.write(response.getOutputStream(), CarryCapcityDataEexcel.class) + .sheet(sheetName) + .doWrite(excels); + EasyExcelUtil.writeWithSheetsWeb(response, "数据集模版.xlsx"); + return null; + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/uploadExcel") + @ApiOperation("上传数据集") + public HttpResult uploadExcel(@Validated ExcelDataParam excelDataParam) throws Exception { + String methodDescribe = getMethodDescribe("uploadExcel"); + boolean flag = carryCapcityService.uploadExcel(excelDataParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/carryCapacityEvaluate") + @ApiOperation("承载能力评估_充电站、电加热负荷、电气化铁路承载能力评估") + @ApiImplicitParam(name = "calParam", value = "计算参数", required = true) + public HttpResult carryCapacityEvaluate(@RequestBody @Validated CarryCapacityEvaluateParam calParam) { + String methodDescribe = getMethodDescribe("carryCapacityEvaluate"); + CarryCapacityDResultVO vo = carryCapcityService.carryCapacityEvaluate(calParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityDevController.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityDevController.java new file mode 100644 index 0000000..5d48d2b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityDevController.java @@ -0,0 +1,85 @@ +package com.njcn.product.carrycapacity.controller; + + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityDeviceParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; +import com.njcn.product.carrycapacity.service.CarryCapacityDevicePOService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:06 + */ +@RestController +@RequestMapping("carrycapacitydev") +@Api(tags = "承载能力评估用户设备") +@RequiredArgsConstructor +public class CarryCapacityDevController extends BaseController { + + + private final CarryCapacityDevicePOService carryCapacityDevicePOService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("承载能力评估用户设备新增") + @ApiImplicitParam(name = "capacityDeviceParam", value = "新增参数", required = true) + public HttpResult add(@RequestBody @Validated CarryCapacityDeviceParam capacityDeviceParam) { + String methodDescribe = getMethodDescribe("add"); + Boolean flag = carryCapacityDevicePOService.add(capacityDeviceParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/remove") + @ApiOperation("承载能力评估用户设备批量删除") + @ApiImplicitParam(name = "devIds", value = "用户id集合", required = true) + public HttpResult remove(@RequestParam("devIds") List devIds) { + String methodDescribe = getMethodDescribe("remove"); + Boolean flag = carryCapacityDevicePOService.removeByIds(devIds); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/update") + @ApiOperation("承载能力评估用户设备编辑") + @ApiImplicitParam(name = "deviceParam", value = "编辑参数", required = true) + public HttpResult update(@RequestBody @Validated CarryCapacityDeviceParam.CarryCapacityDeviceUpdateParam deviceParam) { + String methodDescribe = getMethodDescribe("update"); + Boolean flag = carryCapacityDevicePOService.updateDevice(deviceParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queyDeviceList") + @ApiOperation("承载能力评估用户设备查询") + @ApiImplicitParam(name = "deviceParam", value = "编辑参数", required = true) + public HttpResult> queyDeviceList(@RequestBody @Validated CarryCapacityDeviceParam.CarryCapacityDeviceQueryParam deviceParam) { + String methodDescribe = getMethodDescribe("queyDeviceList"); + List list = carryCapacityDevicePOService.lambdaQuery() + .eq(StringUtils.isNotBlank(deviceParam.getDevId()), CarryCapacityDevicePO::getDevId, deviceParam.getDevId()) + .eq(StringUtils.isNotBlank(deviceParam.getUserId()), CarryCapacityDevicePO::getUserId, deviceParam.getUserId()).list(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityResultController.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityResultController.java new file mode 100644 index 0000000..e4528df --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityResultController.java @@ -0,0 +1,69 @@ +package com.njcn.product.carrycapacity.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityResultPO; +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.product.carrycapacity.pojo.param.CarryCapacityResultParam; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDResultVO; +import com.njcn.product.carrycapacity.service.CarryCapacityResultPOService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:06 + */ +@RestController +@RequestMapping("result") +@Api(tags = "承载能力评估结果") +@RequiredArgsConstructor +public class CarryCapacityResultController extends BaseController { + + + private final CarryCapacityResultPOService carryCapacityResultPOService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryResultList") + @ApiOperation("承载能力评估列表查询") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> queryResultList(@RequestBody @Validated CarryCapacityResultParam.CarryCapacityResultPageParam queryParam) { + String methodDescribe = getMethodDescribe("queryResultList"); + IPage vo = carryCapacityResultPOService.queryResultList(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryResultbyCondition") + @ApiOperation("承载能力评估列表查询") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult queryResultbyCondition(@RequestBody @Validated CarryCapacityQueryDataParam queryParam) { + String methodDescribe = getMethodDescribe("queryResultbyCondition"); + CarryCapacityDResultVO vo = carryCapacityResultPOService.queryResultbyCondition(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, vo, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/remove") + @ApiOperation("承载能力评估用户批量删除") + public HttpResult remove(@RequestParam("ids") List ids) { + String methodDescribe = getMethodDescribe("remove"); + Boolean flag = carryCapacityResultPOService.lambdaUpdate().in(CarryCapacityResultPO::getId, ids).set(CarryCapacityResultPO::getStatus, 0).update(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityStrategyController.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityStrategyController.java new file mode 100644 index 0000000..03ca1f8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityStrategyController.java @@ -0,0 +1,100 @@ +package com.njcn.product.carrycapacity.controller; + + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityStrategyParam; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyDhlVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyVO; +import com.njcn.product.carrycapacity.service.CarryCapacityStrategyDhlPOService; +import com.njcn.product.carrycapacity.service.CarryCapacityStrategyPOService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * Description: + * Date: 2024/3/5 10:35【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@RestController +@RequestMapping("carrycapacity") +@Api(tags = "承载能力评估策略配置") +@RequiredArgsConstructor +public class CarryCapacityStrategyController extends BaseController { + + + private final CarryCapacityStrategyPOService carryCapacityStrategyPOService; + private final CarryCapacityStrategyDhlPOService carryCapacityStrategyDhlPOService; + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("用户新增承载能力评估策略(光伏)") + @ApiImplicitParam(name = "carryCapacityStrategyParam", value = "新增参数", required = true) + public HttpResult add(@RequestBody @Validated CarryCapacityStrategyParam carryCapacityStrategyParam) { + String methodDescribe = getMethodDescribe("add"); + Boolean flag = carryCapacityStrategyPOService.add(carryCapacityStrategyParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/addList") + @ApiOperation("用户新增承载能力评估策略组(光伏)") + @ApiImplicitParam(name = "carryCapacityStrategyParamList", value = "新增参数", required = true) + public HttpResult addList(@RequestBody @Validated List carryCapacityStrategyParamList) { + String methodDescribe = getMethodDescribe("addList"); + Boolean flag = carryCapacityStrategyPOService.addList(carryCapacityStrategyParamList); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queyDetail") + @ApiOperation("承载能力评估策略初始化查询(光伏)") + public HttpResult> queyDetail() { + String methodDescribe = getMethodDescribe("queyDetail"); + List carryCapacityStrategyVOList = carryCapacityStrategyPOService.queyDetail(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, carryCapacityStrategyVOList, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/restore") + @ApiOperation("承载能力评估策略一键还原") + public HttpResult restore() { + String methodDescribe = getMethodDescribe("restore"); + Boolean flag = carryCapacityStrategyPOService.restore(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/adddhl") + @ApiOperation("用户新增承载能力评估策略(电弧炉)") + @ApiImplicitParam(name = "capacityStrategyDhlVO", value = "新增参数", required = true) + public HttpResult adddhl(@RequestBody @Validated CarryCapacityStrategyDhlVO capacityStrategyDhlVO) { + String methodDescribe = getMethodDescribe("adddhl"); + Boolean flag = carryCapacityStrategyDhlPOService.adddhl(capacityStrategyDhlVO); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queyDetailDhl") + @ApiOperation("承载能力评估策略初始化查询(电弧炉)") + public HttpResult> queyDetailDhl() { + String methodDescribe = getMethodDescribe("queyDetailDhl"); + List car = carryCapacityStrategyDhlPOService.queyDetailDhl(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, car, methodDescribe); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityUserController.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityUserController.java new file mode 100644 index 0000000..3a64ae7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/controller/CarryCapacityUserController.java @@ -0,0 +1,90 @@ +package com.njcn.product.carrycapacity.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; + +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.product.carrycapacity.pojo.param.CarryCapacityUserParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; +import com.njcn.product.carrycapacity.service.CarryCapacityUserPOService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:06 + */ +@RestController +@RequestMapping("carrycapacityuser") +@Api(tags = "承载能力评估用户") +@RequiredArgsConstructor +public class CarryCapacityUserController extends BaseController { + + + private final CarryCapacityUserPOService carryCapacityUserPOService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("承载能力评估用户新增") + @ApiImplicitParam(name = "carryCapacityUserParam", value = "新增参数", required = true) + public HttpResult add(@RequestBody @Validated CarryCapacityUserParam carryCapacityUserParam) { + String methodDescribe = getMethodDescribe("add"); + Boolean flag = carryCapacityUserPOService.add(carryCapacityUserParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/remove") + @ApiOperation("承载能力评估用户批量删除") + @ApiImplicitParam(name = "userIds", value = "用户id集合", required = true) + public HttpResult remove(@RequestParam("userIds") List userIds) { + String methodDescribe = getMethodDescribe("remove"); + Boolean flag = carryCapacityUserPOService.lambdaUpdate().in(CarryCapacityUserPO::getUserId,userIds).set(CarryCapacityUserPO::getStatus,0).update(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/update") + @ApiOperation("承载能力评估用户编辑") + @ApiImplicitParam(name = "userUpdateParam", value = "编辑参数", required = true) + public HttpResult update(@RequestBody @Validated CarryCapacityUserParam.CarryCapacityUserUpdateParam userUpdateParam) { + String methodDescribe = getMethodDescribe("update"); + Boolean flag = carryCapacityUserPOService.updateUser(userUpdateParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queyDetailUser") + @ApiOperation("承载能力评估用户查询") + @ApiImplicitParam(name = "pageParam", value = "编辑参数", required = true) + public HttpResult> queyDetailUser(@RequestBody @Validated CarryCapacityUserParam.CarryCapacityUserPageParam pageParam) { + String methodDescribe = getMethodDescribe("queyDetailUser"); + IPage page = carryCapacityUserPOService.queyDetailUser(pageParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queyDetailUserById") + @ApiOperation("承载能力评估用户查询") + public HttpResult queyDetailUserById(@RequestParam("userId") String userId) { + String methodDescribe = getMethodDescribe("queyDetailUserById"); + CarryCapacityUserPO po = carryCapacityUserPOService.queyDetailUserById(userId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, po, methodDescribe); + } + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryCapacityResponseEnum.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryCapacityResponseEnum.java new file mode 100644 index 0000000..de69ef6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryCapacityResponseEnum.java @@ -0,0 +1,103 @@ +package com.njcn.product.carrycapacity.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年04月13日 10:50 + */ +@Getter +public enum CarryCapacityResponseEnum { + + ANALYSIS_USER_DATA_ERROR("A0101","解析用采数据内容失败"), + + INTERNAL_ERROR("A0101","系统内部异常"), + + USER_DATA_EMPTY("A0101","用采数据内容为空"), + + USER_DATA_NOT_FOUND("A0101","未找到用采数据"), + + RESP_DATA_NOT_FOUND("A0101","未找到责任划分数据"), + + WIN_TIME_ERROR("A0101","限值时间小于窗口"), + + CALCULATE_INTERVAL_ERROR("A0101","对齐计算间隔值非法"), + + RESP_RESULT_DATA_NOT_FOUND("A0101","未找到责任划分缓存数据"), + + USER_DATA_P_NODE_PARAMETER_ERROR("A0101","无用采用户或所有用户的完整性均不满足条件"), + + RESPONSIBILITY_PARAMETER_ERROR("A0101","调用接口程序计算失败,参数非法"), + + EVENT_EMPTY("A0102","没有查询到未分析事件"), + + USER_NAME_EXIST("A0103","用户名已存在"), + + DATA_NOT_FOUND("A0104","选择时间内暂无数据,请上传离线数据"), + + DATA_UNDERRUN("A0104","数据量不足,请根据模版上传充足近两周数据"), + + DOCUMENT_FORMAT_ERROR("A0105","数据缺失,导入失败!请检查导入文档的格式是否正确"), + DEVICE_LOST("A0104","用户下缺少设备"), + + USER_LOST("A0106","干扰源用户缺失"), + UNCOMPLETE_STRATEGY("A0106","配置安全,III级预警,II级预警,I级预警4条完整策略"), + EXISTENCE_EVALUATION_RESULT("A0104","存在评结果结果,如要评估,请删除后评估"), + + SG_USER_NAME_REPEAT("A0102","业务用户名重复"), + + SG_PRODUCT_LINE_NAME_REPEAT("A0102","生产线名重复"), + + SG_USER_ID_MISS("A0102","业务用户id缺失"), + + SG_PRODUCT_LINE_ID_MISS("A0102","生产线id缺失"), + + SG_MACHINE_ID_MISS("A0102","设备id缺失"), + + IMPORT_EVENT_DATA_FAIL("A0102","请检查导入数据的准确性"), + + PRODUCT_LINE_DATA_MISS("A0102","生产线数据缺失"), + + MACHINE_DATA_MISS("A0102","设备数据缺失"), + + INCOMING_LINE_DATA_MISS("A0102","进线数据缺失"), + + EVENT_DATA_MISS("A0102","没有可供参考的暂降数据"), + + WIN_DATA_ERROR("A0102","算法校验窗宽超限"), + + DATA_ERROR("A0102","算法校验数据长度超限"), + + INIT_DATA_ERROR("A0102","算法初始化数据失败"), + + USER_HAS_PRODUCT("A0102","当前用户存在生产线"), + + PRODUCT_HAS_MACHINE("A0102","当前生产线存在设备"), + + MACHINE_HAS_UNIT("A0102","当前设备存在元器件"), + + EVENT_TIME_ERROR("A0102","暂降事件时间格式有误,请检查"), + + INVALID_FILE_TYPE("A0102","请选择CSV文件"), + ; + + private final String code; + + private final String message; + + CarryCapacityResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } + + public static String getCodeByMsg(String msg){ + for (CarryCapacityResponseEnum userCodeEnum : CarryCapacityResponseEnum.values()) { + if (userCodeEnum.message.equalsIgnoreCase(msg)) { + return userCodeEnum.code; + } + } + return ""; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryingCapacityEnum.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryingCapacityEnum.java new file mode 100644 index 0000000..8831671 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/enums/CarryingCapacityEnum.java @@ -0,0 +1,164 @@ +package com.njcn.product.carrycapacity.enums; + +import lombok.Getter; + +/** +* @Description: 承载能力评估相关枚举 +* @Author: clam +* @Date: 2024/1/31 +*/ +@Getter + +public enum CarryingCapacityEnum { + + K("K","0.8","海南日照修正系数"), + /** + * h 3 ,5 ,7 ,9 ,11 ,13或者偶次 + * k_h 1.62, ,1.28 ,0.72 ,0.18 ,0.08 ,0 + */ + K_H_2("K_H_2","0.00","2次谐波电流K_2系数"), + K_H_3("K_H_3","1.62","3次谐波电流K_3系数"), + K_H_4("K_H_4","0.00","4次谐波电流K_4系数"), + K_H_5("K_H_5","1.28","5次谐波电流K_5系数"), + K_H_6("K_H_6","0.00","6次谐波电流K_6系数"), + K_H_7("K_H_7","0.72","7次谐波电流K_7系数"), + K_H_8("K_H_8","0.00","8次谐波电流K_8系数"), + K_H_9("K_H_9","0.18","9次谐波电流K_9系数"), + K_H_10("K_H_10","0.00","10次谐波电流K_10系数"), + K_H_11("K_H_11","0.08","11次谐波电流K_11系数"), + K_H_12("K_H_12","0.00","12次谐波电流K_12系数"), + K_H_13("K_H_13","0.00","13次谐波电流K_13系数"), + K_H_14("K_H_14","0.00","14次谐波电流K_14系数"), + K_H_15("K_H_15","0.00","15次谐波电流K_15系数"), + K_H_16("K_H_16","0.00","16次谐波电流K_16系数"), + K_H_17("K_H_17","0.00","17次谐波电流K_17系数"), + K_H_18("K_H_18","0.00","18次谐波电流K_18系数"), + K_H_19("K_H_19","0.00","19次谐波电流K_19系数"), + K_H_20("K_H_20","0.00","20次谐波电流K_20系数"), + K_H_21("K_H_21","0.00","21次谐波电流K_21系数"), + K_H_22("K_H_22","0.00","22次谐波电流K_22系数"), + K_H_23("K_H_23","0.00","23次谐波电流K_23系数"), + K_H_24("K_H_24","0.00","24次谐波电流K_24系数"), + K_H_25("K_H_25","0.00","25次谐波电流K_25系数"), + + //光伏逆变器第h次的典型谐波电流含有率:I_INV_H + I_INV_2("I_INV_2","0.254","2次典型谐波电流含有率"), + I_INV_3("I_INV_3","0.121","3次典型谐波电流含有率"), + I_INV_4("I_INV_4","0.087","4次典型谐波电流含有率"), + I_INV_5("I_INV_5","2.446","5次典型谐波电流含有率"), + I_INV_6("I_INV_6","0.024","6次典型谐波电流含有率"), + I_INV_7("I_INV_7","1.629","7次典型谐波电流含有率"), + I_INV_8("I_INV_8","0.042","8次典型谐波电流含有率"), + I_INV_9("I_INV_9","0.039","9次典型谐波电流含有率"), + I_INV_10("I_INV_10","0.037","10次典型谐波电流含有率"), + I_INV_11("I_INV_11","0.439","11次典型谐波电流含有率"), + I_INV_12("I_INV_12","0.021","12次典型谐波电流含有率"), + I_INV_13("I_INV_13","0.379","13次典型谐波电流含有率"), + I_INV_14("I_INV_14","0.042","14次典型谐波电流含有率"), + I_INV_15("I_INV_15","0.037","15次典型谐波电流含有率"), + I_INV_16("I_INV_16","0.043","16次典型谐波电流含有率"), + I_INV_17("I_INV_17","0.263","17次典型谐波电流含有率"), + I_INV_18("I_INV_18","0.017","18次典型谐波电流含有率"), + I_INV_19("I_INV_19","0.197","19次典型谐波电流含有率"), + I_INV_20("I_INV_20","0.062","20次典型谐波电流含有率"), + I_INV_21("I_INV_21","0.024","21次典型谐波电流含有率"), + I_INV_22("I_INV_22","0.032","22次典型谐波电流含有率"), + I_INV_23("I_INV_23","0.304","23次典型谐波电流含有率"), + I_INV_24("I_INV_24","0.03","24次典型谐波电流含有率"), + I_INV_25("I_INV_25","0.176","25次典型谐波电流含有率"), + I_INV_26("I_INV_26","0.032","26次典型谐波电流含有率"), + I_INV_27("I_INV_27","0.038","27次典型谐波电流含有率"), + I_INV_28("I_INV_28","0.031","28次典型谐波电流含有率"), + I_INV_29("I_INV_29","0.158","29次典型谐波电流含有率"), + I_INV_30("I_INV_30","0.024","30次典型谐波电流含有率"), + I_INV_31("I_INV_31","0.028","31次典型谐波电流含有率"), + I_INV_32("I_INV_32","0.026","32次典型谐波电流含有率"), + I_INV_33("I_INV_33","0.033","33次典型谐波电流含有率"), + I_INV_34("I_INV_34","0.018","34次典型谐波电流含有率"), + I_INV_35("I_INV_35","0.072","35次典型谐波电流含有率"), + + //电弧炉谐波电流含有率 +// EAF_I_2("EAF_I_2","0.6112","2次电弧炉谐波电流含有率"), + EAF_I_3("EAF_I_3","0.13484","3次电弧炉谐波电流含有率"), +// EAF_I_4("EAF_I_4","0.9906","4次电弧炉谐波电流含有率"), + EAF_I_5("EAF_I_5","0.017327","5次电弧炉谐波电流含有率"), +// EAF_I_6("EAF_I_6","0.5750","6次电弧炉谐波电流含有率"), + EAF_I_7("EAF_I_7","0.015288","7次电弧炉谐波电流含有率"), +// EAF_I_8("EAF_I_8","0.4782","8次电弧炉谐波电流含有率"), + EAF_I_9("EAF_I_9","0.001495","9次电弧炉谐波电流含有率"), +// EAF_I_10("EAF_I_10","0.6003","10次电弧炉谐波电流含有率"), + EAF_I_11("EAF_I_11","0.001203","11次电弧炉谐波电流含有率"), +// EAF_I_12("EAF_I_12","0.5242","12次电弧炉谐波电流含有率"), + EAF_I_13("EAF_I_13","0.001407","13次电弧炉谐波电流含有率"), +// EAF_I_14("EAF_I_14","0.5720","14次电弧炉谐波电流含有率"), + EAF_I_15("EAF_I_15","0.001676","15次电弧炉谐波电流含有率"), +// EAF_I_16("EAF_I_16","0.8234","16次电弧炉谐波电流含有率"), + EAF_I_17("EAF_I_17","0.001555","17次电弧炉谐波电流含有率"), +// EAF_I_18("EAF_I_18","0.8848","18次电弧炉谐波电流含有率"), + EAF_I_19("EAF_I_19","0.001159","19次电弧炉谐波电流含有率"), +// EAF_I_20("EAF_I_20","0.6789","20次电弧炉谐波电流含有率"), + + //充电桩谐波电流含有率 +// CP_I_2("CP_I_2","5.00","2次电弧炉谐波电流含有率"), + CP_I_3("CP_I_3","0.2011","3次电弧炉谐波电流含有率"), +// CP_I_4("CP_I_4","4.00","4次电弧炉谐波电流含有率"), + CP_I_5("CP_I_5","0.1069","5次电弧炉谐波电流含有率"), +// CP_I_6("CP_I_6","4.00","6次电弧炉谐波电流含有率"), + CP_I_7("CP_I_7","0.0647","7次电弧炉谐波电流含有率"), +// CP_I_8("CP_I_8","2.00","8次电弧炉谐波电流含有率"), + CP_I_9("CP_I_9","0.0376","9次电弧炉谐波电流含有率"), +// CP_I_10("CP_I_10","1.50","10次电弧炉谐波电流含有率"), + CP_I_11("CP_I_11","0.0232","11次电弧炉谐波电流含有率"), +// CP_I_12("CP_I_12","0.50","12次电弧炉谐波电流含有率"), + CP_I_13("CP_I_13","0.0155","13次电弧炉谐波电流含有率"), +// CP_I_14("CP_I_14","0.00","14次电弧炉谐波电流含有率"), + CP_I_15("CP_I_15","0.005956","15次电弧炉谐波电流含有率"), +// CP_I_16("CP_I_16","0.00","16次电弧炉谐波电流含有率"), + CP_I_17("CP_I_17","0.054185","17次电弧炉谐波电流含有率"), +// CP_I_18("CP_I_18","0.00","18次电弧炉谐波电流含有率"), + CP_I_19("CP_I_19","0.023503","19次电弧炉谐波电流含有率"), +// CP_I_20("CP_I_20","0.00","20次电弧炉谐波电流含有率"), + + //电气化铁路典型 + ER_I_3("ER_I_3","0.0068935","3次电弧炉谐波电流含有率"), + ER_I_5("ER_I_5","0.069575","5次电弧炉谐波电流含有率"), + ER_I_7("ER_I_7","0.032731","7次电弧炉谐波电流含有率"), + ER_I_9("ER_I_9","0.005197","9次电弧炉谐波电流含有率"), + ER_I_11("ER_I_11","0.045631","11次电弧炉谐波电流含有率"), + ER_I_13("ER_I_13","0.029196","13次电弧炉谐波电流含有率"), + ER_I_15("ER_I_15","0.017","15次电弧炉谐波电流含有率"), + ER_I_17("ER_I_17","0.0095","17次电弧炉谐波电流含有率"), + ER_I_19("ER_I_19","0.0080","19次电弧炉谐波电流含有率"), + + ; + /** + * 字段code + */ + private final String Code; + + /** + * 字段值 + */ + private final String value; + + /** + * 字段描述 + */ + private final String description; + + + CarryingCapacityEnum(String code, String value, String description) { + Code = code; + this.value = value; + this.description = description; + } + + public static String getValueByCode(String code) { + for (CarryingCapacityEnum item : CarryingCapacityEnum.values()) { + if (item.Code.equals(code)) { + return item.value; + } + } + return null; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDataPOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDataPOMapper.java new file mode 100644 index 0000000..de8a743 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDataPOMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.github.jeffreyning.mybatisplus.base.MppBaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDataPO; + +/** + * + * Description: + * Date: 2024/3/6 14:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityDataPOMapper extends MppBaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDevicePOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDevicePOMapper.java new file mode 100644 index 0000000..2091703 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityDevicePOMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; + +/** + * + * Description: + * Date: 2024/3/19 16:36【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityDevicePOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityResultPOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityResultPOMapper.java new file mode 100644 index 0000000..55399ea --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityResultPOMapper.java @@ -0,0 +1,14 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityResultPO; + +/** + * Description: + * Date: 2024/3/8 16:23【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityResultPOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyDhlPOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyDhlPOMapper.java new file mode 100644 index 0000000..e8c6480 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyDhlPOMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyDhlPO; + +/** + * + * Description: + * Date: 2024/3/15 10:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityStrategyDhlPOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyPOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyPOMapper.java new file mode 100644 index 0000000..10d40c7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityStrategyPOMapper.java @@ -0,0 +1,14 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyPO; + +/** + * Description: + * Date: 2024/3/5 10:54【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityStrategyPOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityUserPOMapper.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityUserPOMapper.java new file mode 100644 index 0000000..d2c69d0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/CarryCapacityUserPOMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.carrycapacity.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityUserPOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDataPOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDataPOMapper.xml new file mode 100644 index 0000000..329dfad --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDataPOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDevicePOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDevicePOMapper.xml new file mode 100644 index 0000000..8bae8e0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDevicePOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityResultPOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityResultPOMapper.xml new file mode 100644 index 0000000..06f78d4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityResultPOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyDhlPOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyDhlPOMapper.xml new file mode 100644 index 0000000..5cd8d4c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyDhlPOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyPOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyPOMapper.xml new file mode 100644 index 0000000..220e56d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyPOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityUserPOMapper.xml b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityUserPOMapper.xml new file mode 100644 index 0000000..05e7f97 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityUserPOMapper.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataEexcel.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataEexcel.java new file mode 100644 index 0000000..07078a4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataEexcel.java @@ -0,0 +1,292 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.converters.localdatetime.LocalDateTimeStringConverter; +import com.alibaba.fastjson.annotation.JSONField; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/5/12 9:13 + */ +@Data +public class CarryCapcityDataEexcel { + + @ExcelProperty(index = 0,value = "时间(格式为yyyy-MM-dd hh:mm:ss)",converter = LocalDateTimeStringConverter.class) + @JSONField(format = "yyyy-MM-dd hh:mm:ss") + private LocalDateTime time; + + @ExcelProperty(index =1,value = {"电压","A"}) + private Double u_a; + + @ExcelProperty(index =2,value = {"电压","B"}) + private Double u_b; + + @ExcelProperty(index =3,value = {"电压","C"}) + private Double u_c; + + + @ExcelProperty(index =4,value = {"有功功率","A"}) + private Double p_a; + + @ExcelProperty(index =5,value = {"有功功率","B"}) + private Double p_b; + + @ExcelProperty(index =6,value = {"有功功率","C"}) + private Double p_c; + + @ExcelProperty(index =7,value = {"无功功率","A"}) + private Double q_a; + + @ExcelProperty(index =8,value = {"无功功率","B"}) + private Double q_b; + + @ExcelProperty(index =9,value = {"无功功率","C"}) + private Double q_c; + + @ExcelProperty(index =10,value = {"电流","2次","A"}) + private Double i2_a; + + @ExcelProperty(index =11,value = {"电流","2次","B"}) + private Double i2_b; + + @ExcelProperty(index =12,value = {"电流","2次","C"}) + private Double i2_c; + + @ExcelProperty(index =13,value = {"电流","3次","A"}) + private Double i3_a; + + @ExcelProperty(index =14,value = {"电流","3次","B"}) + private Double i3_b; + + @ExcelProperty(index =15,value = {"电流","3次","C"}) + private Double i3_c; + + @ExcelProperty(index =16,value = {"电流","4次","A"}) + private Double i4_a; + + @ExcelProperty(index =17,value = {"电流","4次","B"}) + private Double i4_b; + + @ExcelProperty(index =18,value = {"电流","4次","C"}) + private Double i4_c; + + @ExcelProperty(index =19,value = {"电流","5次","A"}) + private Double i5_a; + + @ExcelProperty(index =20,value = {"电流","5次","B"}) + private Double i5_b; + + @ExcelProperty(index =21,value = {"电流","5次","C"}) + private Double i5_c; + + @ExcelProperty(index =22,value = {"电流","6次","A"}) + private Double i6_a; + + @ExcelProperty(index =23,value = {"电流","6次","B"}) + private Double i6_b; + + @ExcelProperty(index =24,value = {"电流","6次","C"}) + private Double i6_c; + + @ExcelProperty(index =25,value = {"电流","7次","A"}) + private Double i7_a; + + @ExcelProperty(index =26,value = {"电流","7次","B"}) + private Double i7_b; + + @ExcelProperty(index =27,value = {"电流","7次","C"}) + private Double i7_c; + + @ExcelProperty(index =28,value = {"电流","8次","A"}) + private Double i8_a; + + @ExcelProperty(index =29,value = {"电流","8次","B"}) + private Double i8_b; + + @ExcelProperty(index =30,value = {"电流","8次","C"}) + private Double i8_c; + + @ExcelProperty(index =31,value = {"电流","9次","A"}) + private Double i9_a; + + @ExcelProperty(index =32,value = {"电流","9次","B"}) + private Double i9_b; + + @ExcelProperty(index =33,value = {"电流","9次","C"}) + private Double i9_c; + + @ExcelProperty(index =34,value = {"电流","10次","A"}) + private Double i10_a; + + @ExcelProperty(index =35,value = {"电流","10次","B"}) + private Double i10_b; + + @ExcelProperty(index =36,value = {"电流","10次","C"}) + private Double i10_c; + + @ExcelProperty(index =37,value = {"电流","11次","A"}) + private Double i11_a; + + @ExcelProperty(index =38,value = {"电流","11次","B"}) + private Double i11_b; + + @ExcelProperty(index =39,value = {"电流","11次","C"}) + private Double i11_c; + + @ExcelProperty(index =40,value = {"电流","12次","A"}) + private Double i12_a; + + @ExcelProperty(index =41,value = {"电流","12次","B"}) + private Double i12_b; + + @ExcelProperty(index =42,value = {"电流","12次","C"}) + private Double i12_c; + + @ExcelProperty(index =43,value = {"电流","13次","A"}) + private Double i13_a; + + @ExcelProperty(index =44,value = {"电流","13次","B"}) + private Double i13_b; + + @ExcelProperty(index =45,value = {"电流","13次","C"}) + private Double i13_c; + + @ExcelProperty(index =46,value = {"电流","14次","A"}) + private Double i14_a; + + @ExcelProperty(index =47,value = {"电流","14次","B"}) + private Double i14_b; + + @ExcelProperty(index =48,value = {"电流","14次","C"}) + private Double i14_c; + + @ExcelProperty(index =49,value = {"电流","15次","A"}) + private Double i15_a; + + @ExcelProperty(index =50,value = {"电流","15次","B"}) + private Double i15_b; + + @ExcelProperty(index =51,value = {"电流","15次","C"}) + private Double i15_c; + + @ExcelProperty(index =52,value = {"电流","16次","A"}) + private Double i16_a; + + @ExcelProperty(index =53,value = {"电流","16次","B"}) + private Double i16_b; + + @ExcelProperty(index =54,value = {"电流","16次","C"}) + private Double i16_c; + + @ExcelProperty(index =55,value = {"电流","17次","A"}) + private Double i17_a; + + @ExcelProperty(index =56,value = {"电流","17次","B"}) + private Double i17_b; + + @ExcelProperty(index =57,value = {"电流","17次","C"}) + private Double i17_c; + + @ExcelProperty(index =58,value = {"电流","18次","A"}) + private Double i18_a; + + @ExcelProperty(index =59,value = {"电流","18次","B"}) + private Double i18_b; + + @ExcelProperty(index =60,value = {"电流","18次","C"}) + private Double i18_c; + + @ExcelProperty(index =61,value = {"电流","19次","A"}) + private Double i19_a; + + @ExcelProperty(index =62,value = {"电流","19次","B"}) + private Double i19_b; + + @ExcelProperty(index =63,value = {"电流","19次","C"}) + private Double i19_c; + + @ExcelProperty(index =64,value = {"电流","20次","A"}) + private Double i20_a; + + @ExcelProperty(index =65,value = {"电流","20次","B"}) + private Double i20_b; + + @ExcelProperty(index =66,value = {"电流","20次","C"}) + private Double i20_c; + + @ExcelProperty(index =67,value = {"电流","21次","A"}) + private Double i21_a; + + @ExcelProperty(index =68,value = {"电流","21次","B"}) + private Double i21_b; + + @ExcelProperty(index =69,value = {"电流","21次","C"}) + private Double i21_c; + + @ExcelProperty(index =70,value = {"电流","22次","A"}) + private Double i22_a; + + @ExcelProperty(index =71,value = {"电流","22次","B"}) + private Double i22_b; + + @ExcelProperty(index =72,value = {"电流","22次","C"}) + private Double i22_c; + + @ExcelProperty(index =73,value = {"电流","23次","A"}) + private Double i23_a; + + @ExcelProperty(index =74,value = {"电流","23次","B"}) + private Double i23_b; + + @ExcelProperty(index =75,value = {"电流","23次","C"}) + private Double i23_c; + + @ExcelProperty(index =76,value = {"电流","24次","A"}) + private Double i24_a; + + @ExcelProperty(index =77,value = {"电流","24次","B"}) + private Double i24_b; + + @ExcelProperty(index =78,value = {"电流","24次","C"}) + private Double i24_c; + + @ExcelProperty(index =79,value = {"电流","25次","A"}) + private Double i25_a; + + @ExcelProperty(index =80,value = {"电流","25次","B"}) + private Double i25_b; + + @ExcelProperty(index =81,value = {"电流","25次","C"}) + private Double i25_c; + + public static void main(String[] args) { +// List objects = EasyExcelUtil.syncReadModel("C:\\Users\\无名\\Desktop\\11.xlsx", CarryCapcityDataEexcel.class, 0,3); +// System.out.println(objects); + + String sheetName = "sheetName"; + List excels = new ArrayList<>(); + CarryCapcityDataEexcel exportHeadersExcel = new CarryCapcityDataEexcel(); + excels.add(exportHeadersExcel); + + EasyExcel.write("C:\\\\Users\\\\无名\\\\Desktop\\\\22.xlsx", CarryCapcityDataEexcel.class) + .sheet(sheetName) + .doWrite(excels); + EasyExcel.write("C:\\\\Users\\\\无名\\\\Desktop\\\\22.xlsx", CarryCapcityDataEexcel.class) + .sheet("sheetName2") + .doWrite(excels); + + } + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataIEexcel.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataIEexcel.java new file mode 100644 index 0000000..fcb6cdc --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataIEexcel.java @@ -0,0 +1,424 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.njcn.influx.pojo.po.DataI; +import lombok.Data; +import org.influxdb.annotation.Column; +import org.springframework.beans.BeanUtils; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/5/12 9:13 + */ +@Data +public class CarryCapcityDataIEexcel { + + @Excel(name = "时间",width = 30) + private Instant time; + + @Column(name = "line_id") + @Excel(name = "监测点id",width = 30) + private String lineId; + + @Excel(name = "数据类型(CP95)",width = 30) + private String valueType; + + + @Column(name = "i_2") + @Excel(name = "A项2次谐波幅值",width = 15) + private Double i2_a; + + @Column(name = "i_3") + @Excel(name = "A项3次谐波幅值",width = 15) + private Double i3_a; + + @Column(name = "i_4") + @Excel(name = "A项4次谐波幅值",width = 15) + private Double i4_a; + + @Column(name = "i_5") + @Excel(name = "A项5次谐波幅值",width = 15) + private Double i5_a; + + @Column(name = "i_6") + @Excel(name = "A项6次谐波幅值",width = 15) + private Double i6_a; + + @Column(name = "i_7") + @Excel(name = "A项7次谐波幅值",width = 15) + private Double i7_a; + + @Column(name = "i_8") + @Excel(name = "A项8次谐波幅值",width = 15) + private Double i8_a; + + @Column(name = "i_9") + @Excel(name = "A项9次谐波幅值",width = 15) + private Double i9_a; + + @Column(name = "i_10") + @Excel(name = "A项10次谐波幅值",width = 15) + private Double i10_a; + + @Column(name = "i_11") + @Excel(name = "A项11次谐波幅值",width = 15) + private Double i11_a; + + @Column(name = "i_12") + @Excel(name = "A项12次谐波幅值",width = 15) + private Double i12_a; + + @Column(name = "i_13") + @Excel(name = "A项13次谐波幅值",width = 15) + private Double i13_a; + + @Column(name = "i_14") + @Excel(name = "A项14次谐波幅值",width = 15) + private Double i14_a; + + @Column(name = "i_15") + @Excel(name = "A项15次谐波幅值",width = 15) + private Double i15_a; + + @Column(name = "i_16") + @Excel(name = "A项16次谐波幅值",width = 15) + private Double i16_a; + + @Column(name = "i_17") + @Excel(name = "A项17次谐波幅值",width = 15) + private Double i17_a; + + @Column(name = "i_18") + @Excel(name = "A项18次谐波幅值",width = 15) + private Double i18_a; + + @Column(name = "i_19") + @Excel(name = "A项19次谐波幅值",width = 15) + private Double i19_a; + + @Column(name = "i_20") + @Excel(name = "A项20次谐波幅值",width = 15) + private Double i20_a; + + @Column(name = "i_21") + @Excel(name = "A项21次谐波幅值",width = 15) + private Double i21_a; + + @Column(name = "i_22") + @Excel(name = "A项22次谐波幅值",width = 15) + private Double i22_a; + + @Column(name = "i_23") + @Excel(name = "A项23次谐波幅值",width = 15) + private Double i23_a; + + @Column(name = "i_24") + @Excel(name = "A项24次谐波幅值",width = 15) + private Double i24_a; + @Column(name = "i_25") + @Excel(name = "A项25次谐波幅值",width = 15) + private Double i25_a; + + @Column(name = "i_2") + @Excel(name = "B项2次谐波幅值",width = 15) + private Double i2_b; + + @Column(name = "i_3") + @Excel(name = "B项3次谐波幅值",width = 15) + private Double i3_b; + + @Column(name = "i_4") + @Excel(name = "B项4次谐波幅值",width = 15) + private Double i4_b; + + @Column(name = "i_5") + @Excel(name = "B项5次谐波幅值",width = 15) + private Double i5_b; + + @Column(name = "i_6") + @Excel(name = "B项6次谐波幅值",width = 15) + private Double i6_b; + + @Column(name = "i_7") + @Excel(name = "B项7次谐波幅值",width = 15) + private Double i7_b; + + @Column(name = "i_8") + @Excel(name = "B项8次谐波幅值",width = 15) + private Double i8_b; + + @Column(name = "i_9") + @Excel(name = "B项9次谐波幅值",width = 15) + private Double i9_b; + + @Column(name = "i_10") + @Excel(name = "B项10次谐波幅值",width = 15) + private Double i10_b; + + @Column(name = "i_11") + @Excel(name = "B项11次谐波幅值",width = 15) + private Double i11_b; + + @Column(name = "i_12") + @Excel(name = "B项12次谐波幅值",width = 15) + private Double i12_b; + + @Column(name = "i_13") + @Excel(name = "B项13次谐波幅值",width = 15) + private Double i13_b; + + @Column(name = "i_14") + @Excel(name = "B项14次谐波幅值",width = 15) + private Double i14_b; + + @Column(name = "i_15") + @Excel(name = "B项15次谐波幅值",width = 15) + private Double i15_b; + + @Column(name = "i_16") + @Excel(name = "B项16次谐波幅值",width = 15) + private Double i16_b; + + @Column(name = "i_17") + @Excel(name = "B项17次谐波幅值",width = 15) + private Double i17_b; + + @Column(name = "i_18") + @Excel(name = "B项18次谐波幅值",width = 15) + private Double i18_b; + + @Column(name = "i_19") + @Excel(name = "B项19次谐波幅值",width = 15) + private Double i19_b; + + @Column(name = "i_20") + @Excel(name = "B项20次谐波幅值",width = 15) + private Double i20_b; + + @Column(name = "i_21") + @Excel(name = "B项21次谐波幅值",width = 15) + private Double i21_b; + + @Column(name = "i_22") + @Excel(name = "B项22次谐波幅值",width = 15) + private Double i22_b; + + @Column(name = "i_23") + @Excel(name = "B项23次谐波幅值",width = 15) + private Double i23_b; + + @Column(name = "i_24") + @Excel(name = "B项24次谐波幅值",width = 15) + private Double i24_b; + @Column(name = "i_25") + @Excel(name = "B项25次谐波幅值",width = 15) + private Double i25_b; + + + + @Column(name = "i_2") + @Excel(name = "C项2次谐波幅值",width = 15) + private Double i2_c; + + @Column(name = "i_3") + @Excel(name = "C项3次谐波幅值",width = 15) + private Double i3_c; + + @Column(name = "i_4") + @Excel(name = "C项4次谐波幅值",width = 15) + private Double i4_c; + + @Column(name = "i_5") + @Excel(name = "C项5次谐波幅值",width = 15) + private Double i5_c; + + @Column(name = "i_6") + @Excel(name = "C项6次谐波幅值",width = 15) + private Double i6_c; + + @Column(name = "i_7") + @Excel(name = "C项7次谐波幅值",width = 15) + private Double i7_c; + + @Column(name = "i_8") + @Excel(name = "C项8次谐波幅值",width = 15) + private Double i8_c; + + @Column(name = "i_9") + @Excel(name = "C项9次谐波幅值",width = 15) + private Double i9_c; + + @Column(name = "i_10") + @Excel(name = "C项10次谐波幅值",width = 15) + private Double i10_c; + + @Column(name = "i_11") + @Excel(name = "C项11次谐波幅值",width = 15) + private Double i11_c; + + @Column(name = "i_12") + @Excel(name = "C项12次谐波幅值",width = 15) + private Double i12_c; + + @Column(name = "i_13") + @Excel(name = "C项13次谐波幅值",width = 15) + private Double i13_c; + + @Column(name = "i_14") + @Excel(name = "C项14次谐波幅值",width = 15) + private Double i14_c; + + @Column(name = "i_15") + @Excel(name = "C项15次谐波幅值",width = 15) + private Double i15_c; + + @Column(name = "i_16") + @Excel(name = "C项16次谐波幅值",width = 15) + private Double i16_c; + + @Column(name = "i_17") + @Excel(name = "C项17次谐波幅值",width = 15) + private Double i17_c; + + @Column(name = "i_18") + @Excel(name = "C项18次谐波幅值",width = 15) + private Double i18_c; + + @Column(name = "i_19") + @Excel(name = "C项19次谐波幅值",width = 15) + private Double i19_c; + + @Column(name = "i_20") + @Excel(name = "C项20次谐波幅值",width = 15) + private Double i20_c; + + @Column(name = "i_21") + @Excel(name = "C项21次谐波幅值",width = 15) + private Double i21_c; + + @Column(name = "i_22") + @Excel(name = "C项22次谐波幅值",width = 15) + private Double i22_c; + + @Column(name = "i_23") + @Excel(name = "C项23次谐波幅值",width = 15) + private Double i23_c; + + @Column(name = "i_24") + @Excel(name = "C项24次谐波幅值",width = 15) + private Double i24_c; + @Column(name = "i_25") + @Excel(name = "C项25次谐波幅值",width = 15) + private Double i25_c; + + //excel对象转DataI + public static List excelToPO(CarryCapcityDataIEexcel carryCapcityDataIEexcel) { + List data = new ArrayList<>(); + if (carryCapcityDataIEexcel == null) { + return null; + } + List phaseList = Stream.of("A", "B", "C").collect(Collectors.toList()); + for (String phase : phaseList) { + DataI dataI = new DataI(); + BeanUtils.copyProperties(carryCapcityDataIEexcel,dataI); + dataI.setPhaseType(phase); + dataI.setTime(carryCapcityDataIEexcel.getTime()); + + if (phase.equals("A")) { + + dataI.setI2( carryCapcityDataIEexcel.getI2_a()); + dataI.setI3( carryCapcityDataIEexcel.getI3_a()); + dataI.setI4( carryCapcityDataIEexcel.getI4_a()); + dataI.setI5( carryCapcityDataIEexcel.getI5_a()); + dataI.setI6( carryCapcityDataIEexcel.getI6_a()); + dataI.setI7( carryCapcityDataIEexcel.getI7_a()); + dataI.setI8( carryCapcityDataIEexcel.getI8_a()); + dataI.setI9( carryCapcityDataIEexcel.getI9_a()); + dataI.setI10( carryCapcityDataIEexcel.getI10_a()); + dataI.setI11( carryCapcityDataIEexcel.getI11_a()); + dataI.setI12( carryCapcityDataIEexcel.getI12_a()); + dataI.setI13( carryCapcityDataIEexcel.getI13_a()); + dataI.setI14( carryCapcityDataIEexcel.getI14_a()); + dataI.setI15( carryCapcityDataIEexcel.getI15_a()); + dataI.setI16( carryCapcityDataIEexcel.getI16_a()); + dataI.setI17( carryCapcityDataIEexcel.getI17_a()); + dataI.setI18( carryCapcityDataIEexcel.getI18_a()); + dataI.setI19( carryCapcityDataIEexcel.getI19_a()); + dataI.setI20( carryCapcityDataIEexcel.getI20_a()); + dataI.setI21( carryCapcityDataIEexcel.getI21_a()); + dataI.setI22( carryCapcityDataIEexcel.getI22_a()); + dataI.setI23( carryCapcityDataIEexcel.getI23_a()); + dataI.setI24( carryCapcityDataIEexcel.getI24_a()); + dataI.setI25( carryCapcityDataIEexcel.getI25_a()); + + + } else if (phase.equals("B")) { + dataI.setI2( carryCapcityDataIEexcel.getI2_b()); + dataI.setI3( carryCapcityDataIEexcel.getI3_b()); + dataI.setI4( carryCapcityDataIEexcel.getI4_b()); + dataI.setI5( carryCapcityDataIEexcel.getI5_b()); + dataI.setI6( carryCapcityDataIEexcel.getI6_b()); + dataI.setI7( carryCapcityDataIEexcel.getI7_b()); + dataI.setI8( carryCapcityDataIEexcel.getI8_b()); + dataI.setI9( carryCapcityDataIEexcel.getI9_b()); + dataI.setI10( carryCapcityDataIEexcel.getI10_b()); + dataI.setI11( carryCapcityDataIEexcel.getI11_b()); + dataI.setI12( carryCapcityDataIEexcel.getI12_b()); + dataI.setI13( carryCapcityDataIEexcel.getI13_b()); + dataI.setI14( carryCapcityDataIEexcel.getI14_b()); + dataI.setI15( carryCapcityDataIEexcel.getI15_b()); + dataI.setI16( carryCapcityDataIEexcel.getI16_b()); + dataI.setI17( carryCapcityDataIEexcel.getI17_b()); + dataI.setI18( carryCapcityDataIEexcel.getI18_b()); + dataI.setI19( carryCapcityDataIEexcel.getI19_b()); + dataI.setI20( carryCapcityDataIEexcel.getI20_b()); + dataI.setI21( carryCapcityDataIEexcel.getI21_b()); + dataI.setI22( carryCapcityDataIEexcel.getI22_b()); + dataI.setI23( carryCapcityDataIEexcel.getI23_b()); + dataI.setI24( carryCapcityDataIEexcel.getI24_b()); + dataI.setI25( carryCapcityDataIEexcel.getI25_b()); + + }else if (phase.equals("C")){ + dataI.setI2( carryCapcityDataIEexcel.getI2_c()); + dataI.setI3( carryCapcityDataIEexcel.getI3_c()); + dataI.setI4( carryCapcityDataIEexcel.getI4_c()); + dataI.setI5( carryCapcityDataIEexcel.getI5_c()); + dataI.setI6( carryCapcityDataIEexcel.getI6_c()); + dataI.setI7( carryCapcityDataIEexcel.getI7_c()); + dataI.setI8( carryCapcityDataIEexcel.getI8_c()); + dataI.setI9( carryCapcityDataIEexcel.getI9_c()); + dataI.setI10( carryCapcityDataIEexcel.getI10_c()); + dataI.setI11( carryCapcityDataIEexcel.getI11_c()); + dataI.setI12( carryCapcityDataIEexcel.getI12_c()); + dataI.setI13( carryCapcityDataIEexcel.getI13_c()); + dataI.setI14( carryCapcityDataIEexcel.getI14_c()); + dataI.setI15( carryCapcityDataIEexcel.getI15_c()); + dataI.setI16( carryCapcityDataIEexcel.getI16_c()); + dataI.setI17( carryCapcityDataIEexcel.getI17_c()); + dataI.setI18( carryCapcityDataIEexcel.getI18_c()); + dataI.setI19( carryCapcityDataIEexcel.getI19_c()); + dataI.setI20( carryCapcityDataIEexcel.getI20_c()); + dataI.setI21( carryCapcityDataIEexcel.getI21_c()); + dataI.setI22( carryCapcityDataIEexcel.getI22_c()); + dataI.setI23( carryCapcityDataIEexcel.getI23_c()); + dataI.setI24( carryCapcityDataIEexcel.getI24_c()); + dataI.setI25( carryCapcityDataIEexcel.getI25_c()); + + } + data.add(dataI); + } + return data; + } + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataPEexcel.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataPEexcel.java new file mode 100644 index 0000000..08fed37 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataPEexcel.java @@ -0,0 +1,65 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.njcn.influx.pojo.bo.CarryCapcityData; +import lombok.Data; +import org.springframework.beans.BeanUtils; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/5/12 9:13 + */ +@Data +public class CarryCapcityDataPEexcel { + + @Excel(name = "时间",width = 30) + private Instant time; + + @Excel(name = "监测点id",width = 30) + private String lineId; + + @Excel(name = "数据类型(CP95)",width = 30) + private String valueType; + + @Excel(name = "数据(A项有功功率)",width = 30) + private Double value_a; + @Excel(name = "数据(B项有功功率)",width = 30) + private Double value_b; + @Excel(name = "数据(C项有功功率)",width = 30) + private Double value_c; + + public static List excelToPO(CarryCapcityDataPEexcel carryCapcityDataPEexcel) { + List data = new ArrayList<>(); + if (carryCapcityDataPEexcel == null) { + return null; + } + List phaseList = Stream.of("A", "B", "C").collect(Collectors.toList()); + for (String phase : phaseList) { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(carryCapcityDataPEexcel,carryCapcityData); + carryCapcityData.setPhaseType(phase); + carryCapcityData.setTime(carryCapcityDataPEexcel.getTime()); + + if (phase.equals("A")) { + carryCapcityData.setValue(carryCapcityDataPEexcel.getValue_a()); + } else if (phase.equals("B")) { + carryCapcityData.setValue(carryCapcityDataPEexcel.getValue_b()); + }else if (phase.equals("C")){ + carryCapcityData.setValue(carryCapcityDataPEexcel.getValue_c()); + } + data.add(carryCapcityData); + + } + return data; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataQEexcel.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataQEexcel.java new file mode 100644 index 0000000..630ca62 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataQEexcel.java @@ -0,0 +1,67 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.njcn.influx.pojo.bo.CarryCapcityData; +import lombok.Data; +import org.springframework.beans.BeanUtils; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/5/12 9:13 + */ +@Data +public class CarryCapcityDataQEexcel { + + @Excel(name = "时间",width = 30) + private Instant time; + + @Excel(name = "监测点id",width = 30) + private String lineId; + + + @Excel(name = "数据类型(CP95)",width = 30) + private String valueType; + + @Excel(name = "数据(A项无功功率)",width = 30) + private Double value_a; + @Excel(name = "数据(B项无功功率)",width = 30) + private Double value_b; + @Excel(name = "数据(C项无功功率)",width = 30) + private Double value_c; + + + public static List excelToPO(CarryCapcityDataQEexcel carryCapcityDataQEexcel) { + List data = new ArrayList<>(); + if (carryCapcityDataQEexcel == null) { + return null; + } + List phaseList = Stream.of("A", "B", "C").collect(Collectors.toList()); + for (String phase : phaseList) { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(carryCapcityDataQEexcel,carryCapcityData); + carryCapcityData.setPhaseType(phase); + carryCapcityData.setTime(carryCapcityDataQEexcel.getTime()); + + if (phase.equals("A")) { + carryCapcityData.setValue(carryCapcityDataQEexcel.getValue_a()); + } else if (phase.equals("B")) { + carryCapcityData.setValue(carryCapcityDataQEexcel.getValue_b()); + }else if (phase.equals("C")){ + carryCapcityData.setValue(carryCapcityDataQEexcel.getValue_c()); + } + data.add(carryCapcityData); + + } + return data; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataVEexcel.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataVEexcel.java new file mode 100644 index 0000000..3555f79 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/CarryCapcityDataVEexcel.java @@ -0,0 +1,65 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.njcn.influx.pojo.bo.CarryCapcityData; +import lombok.Data; +import org.springframework.beans.BeanUtils; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/5/12 9:13 + */ +@Data +public class CarryCapcityDataVEexcel { + + @Excel(name = "时间",width = 30) + private Instant time; + + @Excel(name = "监测点id",width = 30) + private String lineId; + + @Excel(name = "数据类型(CP95)",width = 30) + private String valueType; + + + @Excel(name = "数据(A项电压)",width = 30) + private Double value_a; + @Excel(name = "数据(B项电压)",width = 30) + private Double value_b; + @Excel(name = "数据(C项电压)",width = 30) + private Double value_c; + + public static List excelToPO(CarryCapcityDataVEexcel carryCapcityDataVEexcel) { + List data = new ArrayList<>(); + if (carryCapcityDataVEexcel == null) { + return null; + } + List phaseList = Stream.of("A", "B", "C").collect(Collectors.toList()); + for (String phase : phaseList) { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(carryCapcityDataVEexcel,carryCapcityData); + carryCapcityData.setPhaseType(phase); + carryCapcityData.setTime(carryCapcityDataVEexcel.getTime()); + + if (phase.equals("A")) { + carryCapcityData.setValue(carryCapcityDataVEexcel.getValue_a()); + } else if (phase.equals("B")) { + carryCapcityData.setValue(carryCapcityDataVEexcel.getValue_b()); + }else if (phase.equals("C")){ + carryCapcityData.setValue(carryCapcityDataVEexcel.getValue_c()); + } + data.add(carryCapcityData); + + } + return data; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/ExcelDataDTO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/ExcelDataDTO.java new file mode 100644 index 0000000..21f8503 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/excel/ExcelDataDTO.java @@ -0,0 +1,24 @@ +package com.njcn.product.carrycapacity.pojo.excel; + +import com.njcn.influx.pojo.bo.CarryCapcityData; +import com.njcn.influx.pojo.po.DataI; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2024/3/12 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class ExcelDataDTO { + private List dataHarmPowerPList; + private List dataHarmPowerQList; + private List dataIList; + private List dataHarmPowerP2List; + private List dataHarmPowerQ2List; + private List dataHarmPowerU2List; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityCalParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityCalParam.java new file mode 100644 index 0000000..b960b21 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityCalParam.java @@ -0,0 +1,54 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CarryCapacityCalParam { + @NotBlank(message = "参数不能为空") + @ApiModelProperty("监测点索引") + private String lineId; + @ApiModelProperty("用户Id") + private String userId; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") + private LocalDate startTime; + @ApiModelProperty("结束时间") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") + private LocalDate endTime; + @ApiModelProperty(name = "scale",value = "电压等级") + private String scale; + @ApiModelProperty(name = "S_T",value = "S_T为配变额定容量(监测点基准容量)") + private Double S_T; + @ApiModelProperty(name = "S_pv",value = "S_pv为拟接入光伏容量") + private Double S_pv; + @ApiModelProperty(name = "stringMap",value = "首端电流模型参数A,B,C三项") + private Map stringMap; + + @ApiModelProperty(name = "P_βminMap",value = "有功功率最小CP95值A,B,C三项") + private Map P_βminMap; + + @ApiModelProperty(name = "Q_βminMap",value = "无功功率最小CP95值A,B,C三项") + private Map Q_βminMap; + + @ApiModelProperty(name = "I_βmax",value = "2-25次谐波幅值最大95概率值A,B,C三项中的最大值") + private List I_βmax; + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityDeviceParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityDeviceParam.java new file mode 100644 index 0000000..041a42c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityDeviceParam.java @@ -0,0 +1,51 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * Description: + * Date: 2024/3/20 9:59【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class CarryCapacityDeviceParam { + + private String userId; + /** + * 设备名称 + */ + private String devName; + + private String devScale; + + /** + * 设备用户协议容量(MVA) + */ + private Double protocolCapacity; + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CarryCapacityDeviceUpdateParam extends CarryCapacityDeviceParam { + @ApiModelProperty("设备Id") + @NotBlank(message = "设备Id不能为空") + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String devId; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CarryCapacityDeviceQueryParam extends CarryCapacityDeviceParam { + @ApiModelProperty("设备Id") + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String devId; + } +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityEvaluateParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityEvaluateParam.java new file mode 100644 index 0000000..79e9cb6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityEvaluateParam.java @@ -0,0 +1,51 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.List; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CarryCapacityEvaluateParam { + @ApiModelProperty(value = "接线类型不可为空\"星型接法_0\", \"三角型接法_1\", \"开口三角型接法_2\"") + @NotBlank(message = "接线类型不能为空") + private String ptType; + @ApiModelProperty(value = "变压器连接方式") + private String connectionMode; + @ApiModelProperty(value = "功率因数(0.95-1之间)") + @NotNull(message = "功率因数不能为空") + private Double k; + + @ApiModelProperty(value = "专变用户,公变用户") + @NotBlank(message = "用户类型不能为空") + private String userMode; + + + @ApiModelProperty(name = "scale",value = "电压等级") + @NotBlank(message = "电压等级不能为空") + private String scale; + + @ApiModelProperty(name = "shortCapacity",value = "短路容量") + private Float shortCapacity; + + + @ApiModelProperty(name = "deviceCapacity",value = "设备容量") + private Float deviceCapacity; + @ApiModelProperty(name = "userList",value = "干扰源用户设备列表") + private List devList; +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityQueryDataParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityQueryDataParam.java new file mode 100644 index 0000000..1c94234 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityQueryDataParam.java @@ -0,0 +1,42 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import java.time.LocalDate; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CarryCapacityQueryDataParam { + + + @ApiModelProperty("监测点索引") + private String lineId; + @ApiModelProperty("用户Id") + private String userId; + @ApiModelProperty("开始时间") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") + private LocalDate startTime; + @ApiModelProperty("结束时间") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") + private LocalDate endTime; + + @Min(2) + @Max(25) + @ApiModelProperty("谐波次数") + private Integer time=2; +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityResultParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityResultParam.java new file mode 100644 index 0000000..e48565e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityResultParam.java @@ -0,0 +1,52 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +/** + * Description: + * Date: 2024/3/8 16:23【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CarryCapacityResultParam { + /** + * 承载能力评估id + */ + private String id; + + + private String evaluateType; + + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CarryCapacityResultPageParam extends CarryCapacityResultParam { + + @NotNull(message="当前页不能为空!") + @Min(value = 1, message = "当前页不能为0") + @ApiModelProperty(value = "当前页",name = "pageNum",dataType ="Integer",required = true) + private Integer pageNum; + /**显示条数*/ + @NotNull(message="显示条数不能为空!") + @ApiModelProperty(value = "显示条数",name = "pageSize",dataType ="Integer",required = true) + private Integer pageSize; + + @ApiModelProperty(value="起始时间") + private String startTime; + + @ApiModelProperty(value="结束时间") + private String endTime; + + } +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityStrategyParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityStrategyParam.java new file mode 100644 index 0000000..b2d6b0b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityStrategyParam.java @@ -0,0 +1,53 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * Description: + * Date: 2024/3/5 10:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CarryCapacityStrategyParam { + + private String id; + /** + * 总承载能力评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @ApiModelProperty(value = "总承载能力评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警)") + @NotNull(message = "总承载能力评估结果不能为空") + private Integer result; + + /** + * 指标评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @ApiModelProperty(value = "指标评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警)") + @NotNull(message = "指标评估结果不能为空") + private Integer indexResult; + + /** + * 比较符 + */ + @ApiModelProperty(value = "比较符") + @NotBlank(message = "比较符不能为空") + private String comparisonOperators; + + /** + * 数量 + */ + @ApiModelProperty(value = "数量") + @NotNull(message = "数量不能为空") + private Integer count; + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityUserParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityUserParam.java new file mode 100644 index 0000000..7655d51 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/CarryCapacityUserParam.java @@ -0,0 +1,103 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CarryCapacityUserParam { + + + /** + * 用户名称 + */ + private String userName; + + /** + * 用户类型 + */ + private String userType; + + /** + * 电压等级(V) + */ + private String voltage; + + /** + * 用户协议容量(MVA) + */ + private Double protocolCapacity; + /** + * 省 + */ + private String province; + + /** + * 市 + */ + private String city; + + /** + * 区 + */ + private String region; + + /** + * 所属区域 + */ + private String area; + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class CarryCapacityUserUpdateParam extends CarryCapacityUserParam { + @ApiModelProperty("用户Id") + @NotBlank(message = "用户Id不能为空") + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String userId; + } + @Data + @EqualsAndHashCode(callSuper = true) + public static class CarryCapacityUserPageParam extends CarryCapacityUserParam { + + private String userId; + @NotNull(message="当前页不能为空!") + @Min(value = 1, message = "当前页不能为0") + @ApiModelProperty(value = "当前页",name = "pageNum",dataType ="Integer",required = true) + private Integer pageNum; + /**显示条数*/ + @NotNull(message="显示条数不能为空!") + @ApiModelProperty(value = "显示条数",name = "pageSize",dataType ="Integer",required = true) + private Integer pageSize; + private String voltage; + @ApiModelProperty(value="起始时间") + private String startTime; + + @ApiModelProperty(value="结束时间") + private String endTime; + + private List userTypeList; + } + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/ExcelDataParam.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/ExcelDataParam.java new file mode 100644 index 0000000..5836faa --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/param/ExcelDataParam.java @@ -0,0 +1,29 @@ +package com.njcn.product.carrycapacity.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.constraints.NotBlank; + +/** + * Description: + * Date: 2024/3/6 17:30【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class ExcelDataParam { + @NotBlank(message = "监测点索引为空") + @ApiModelProperty("监测点索引") + private String lineId; + + @ApiModelProperty("开始时间") + private String startTime; + @ApiModelProperty("结束时间") + private String endTime; + + @ApiModelProperty(value = "excel文件") + private MultipartFile file; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDataPO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDataPO.java new file mode 100644 index 0000000..d133715 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDataPO.java @@ -0,0 +1,51 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.github.jeffreyning.mybatisplus.anno.MppMultiId; +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +/** + * + * Description: + * Date: 2024/3/6 14:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "carry_capacity_data") +public class CarryCapacityDataPO extends BaseEntity{ + /** + * 台区id + */ + @MppMultiId(value = "line_id") + private String lineId; + + /** + * 开始时间 + */ + @MppMultiId(value = "start_time") + private LocalDate startTime; + + /** + * 结束时间 + */ + @MppMultiId(value = "end_time") + private LocalDate endTime; + + /** + * 上传数据集地址 + */ + @TableField(value = "date_list") + private String dateList; + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDevicePO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDevicePO.java new file mode 100644 index 0000000..4378b46 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityDevicePO.java @@ -0,0 +1,50 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2024/3/19 16:36【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "carry_capacity_device") +public class CarryCapacityDevicePO extends BaseEntity { + /** + * 设备id + */ + @TableId(value = "dev_id", type = IdType.ASSIGN_UUID) + private String devId; + + @TableField(value = "user_id") + private String userId; + + /** + * 设备名称 + */ + @TableField(value = "dev_name") + private String devName; + /** + * 设备额定电压 + */ + @TableField(value = "dev_scale") + private String devScale; + /** + * 设备用户协议容量(MVA) + */ + @TableField(value = "protocol_capacity") + private Double protocolCapacity; + + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityResultPO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityResultPO.java new file mode 100644 index 0000000..0a2c598 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityResultPO.java @@ -0,0 +1,129 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +/** + * Description: + * Date: 2024/3/8 16:23【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "carry_capacity_result") +public class CarryCapacityResultPO extends BaseEntity { + /** + * 承载能力评估id + */ + @TableId(value = "id",type = IdType.ASSIGN_UUID) + private String id; + + /** + * 台区id + */ + @TableField(value = "line_id") + private String lineId; + + /** + * 用户id + */ + @TableField(value = "user_id") + private String userId; + + /** + * 开始时间 + */ + @TableField(value = "start_time") + private LocalDate startTime; + + /** + * 结束时间 + */ + @TableField(value = "end_time") + private LocalDate endTime; + + /** + * 配变首端电压等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "u_t_level") + private Integer uTLevel; + + /** + * 配变的功率因等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "pf_t_level") + private Integer pfTLevel; + + /** + * 等效负载率最小值等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "b_t_level") + private Integer bTLevel; + + /** + * 各次谐波电流幅值等级 (1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "i_level") + private Integer iLevel; + + /** + * 总结果等级(1-安全,2-III级预警,3-II级预警,4-I 级预警,5-禁止接入,6-允许接入) + */ + @TableField(value = "reslut_level") + private Integer reslutLevel; + + /** + * 评估日期 + */ + @TableField(value = "evaluate_date") + private LocalDate evaluateDate; + + /** + * 是否删除(0,无效,1有效) + */ + @TableField(value = "status") + private Integer status; + + @TableField(value = "evaluate_type") + private String evaluateType; + + + @TableField(value = "first_result") + private double firstResult; + + @TableField(value = "i_result_list") + private String iResultList; + + @TableField(value = "pt_type") + private String ptType; + @TableField(value = "connection_mode") + private String connectionMode; + @TableField(value = "k") + private Double k; + + @TableField(value = "user_mode") + private String userMode; + + + @TableField(value = "scale") + private String scale; + + @TableField(value = "short_capacity") + private Float shortCapacity; + + + @TableField(value = "device_capacity") + private Float deviceCapacity; + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyDhlPO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyDhlPO.java new file mode 100644 index 0000000..cec83a0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyDhlPO.java @@ -0,0 +1,98 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2024/3/15 10:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "carry_capacity_strategy_dhl") +public class CarryCapacityStrategyDhlPO extends BaseEntity { + /** + * id + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private String id; + + /** + * 充电桩,电弧炉,电气化铁路 + */ + @TableField(value = "type") + private String type; + + /** + * 一级评估比较符 + */ + @TableField(value = "comparison_operators_1") + private String comparisonOperators1; + + /** + * 一级评估数量 + */ + @TableField(value = "count_1") + private Integer count1; + + /** + * 二级级评估(2~20次谐波合格个数)比较符 + */ + @TableField(value = "comparison_operators_2") + private String comparisonOperators2; + + /** + * 二级评估(2~20次谐波合格)个数数量 + */ + @TableField(value = "count_2") + private Integer count2; + + /** + * 二级级评估(奇数谐波合格个数)比较符 + */ + @TableField(value = "comparison_operators_3") + private String comparisonOperators3; + + /** + * 二级评估(奇数次谐波合格)个数数量 + */ + @TableField(value = "count_3") + private Integer count3; + + /** + * 初始配置1,客户配置2 + */ + @TableField(value = "proto_flag") + private Integer protoFlag; + + /** + * 二级级评估(偶数谐波合格个数)比较符 + */ + @TableField(value = "comparison_operators_4") + private String comparisonOperators4; + + /** + * 二级评估(偶数次谐波合格)个数数量 + */ + @TableField(value = "count_4") + private Integer count4; + + /** + * 启用配置1,不启用配置2 + */ + @TableField(value = "user_flag") + private Integer userFlag; + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyPO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyPO.java new file mode 100644 index 0000000..02ac55e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityStrategyPO.java @@ -0,0 +1,61 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Description: + * Date: 2024/3/5 10:54【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "carry_capacity_strategy") +public class CarryCapacityStrategyPO extends BaseEntity { + /** + * 总承载能力评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "result") + private Integer result; + + /** + * 指标评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @TableField(value = "index_result") + private Integer indexResult; + + /** + * 比较符 + */ + @TableField(value = "comparison_operators") + private String comparisonOperators; + + /** + * 数量 + */ + @TableField(value = "count") + private Integer count; + + /** + * 初始配置1,客户配置2 + */ + @TableField(value = "proto_flag") + private Integer protoFlag; + + /** + * 启用配置1,不启用配置2 + */ + @TableField(value = "user_flag") + private Integer userFlag; + + @TableField(value = "id") + private String id; + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityUserPO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityUserPO.java new file mode 100644 index 0000000..fc52b76 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/po/CarryCapacityUserPO.java @@ -0,0 +1,83 @@ +package com.njcn.product.carrycapacity.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "carry_capacity_user") +public class CarryCapacityUserPO extends BaseEntity { + /** + * 用户id + */ + @TableId(value = "user_id", type = IdType.ASSIGN_UUID) + private String userId; + + /** + * 用户名称 + */ + @TableField(value = "user_name") + private String userName; + + /** + * 用户类型 + */ + @TableField(value = "user_type") + private String userType; + + /** + * 电压等级(V) + */ + @TableField(value = "voltage") + private String voltage; + + /** + * 用户协议容量(MVA) + */ + @TableField(value = "protocol_capacity") + private Double protocolCapacity; + + /** + * 省 + */ + @TableField(value = "province") + private String province; + + /** + * 市 + */ + @TableField(value = "city") + private String city; + + /** + * 区 + */ + @TableField(value = "region") + private String region; + + /** + * 所属区域 + */ + @TableField(value = "area") + private String area; + + + @TableField(value = "status") + private Integer status; + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDResultVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDResultVO.java new file mode 100644 index 0000000..39f0860 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDResultVO.java @@ -0,0 +1,107 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +/** + * Description: + * Date: 2024/2/27 11:24【需求编号】 + * + * @author clam + * @version V1.0.0 + */ + +@Data +public class CarryCapacityDResultVO { + + + private String id; + + /** + * 台区id + */ + private String lineId; + + private String lineName; + + /** + * 用户id + */ + private String userId; + + private String userName; + + /** + * 开始时间 + */ + private LocalDate startTime; + + /** + * 结束时间 + */ + private LocalDate endTime; + + + + private Integer uTLevel; + + /** + * 配变的功率因等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + private Integer pfTLevel; + + /** + * 等效负载率最小值等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + private Integer bTLevel; + + /** + * 各次谐波电流幅值等级 (1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + private Integer iLevel; + + /** + * 总结果等级(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + private Integer reslutLevel; + + private LocalDate evaluateDate; + + + private String evaluateType; + //电弧炉等评估结果 + + private double firstResult; + + private List iResultList; + + + private String connectionMode; + private Double k; + private String ptType; + + private String userMode; + + + private String scale; + + private Float shortCapacity; + + + private Float deviceCapacity; + + + @Data + public static class CarryCapacityIResult { + + @ApiModelProperty("谐波次数") + private Integer time=2; + + private Double i; + + private Double i_limit; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataIVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataIVO.java new file mode 100644 index 0000000..7df9d6d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataIVO.java @@ -0,0 +1,25 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import com.njcn.influx.pojo.bo.CarryCapcityData; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2024/2/27 11:24【需求编号】 + * + * @author clam + * @version V1.0.0 + */ + +@Data +public class CarryCapacityDataIVO { + @ApiModelProperty(name = "data",value = "谐波幅值数据") + private List data; + + @ApiModelProperty(name = "I_βmax",value = "2-25次谐波幅值最大95概率值A,B,C三项中的最大值") + private List I_βmax; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataQVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataQVO.java new file mode 100644 index 0000000..424106c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataQVO.java @@ -0,0 +1,26 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import com.njcn.influx.pojo.bo.CarryCapcityData; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * Description: + * Date: 2024/2/27 11:24【需求编号】 + * + * @author clam + * @version V1.0.0 + */ + +@Data +public class CarryCapacityDataQVO { + @ApiModelProperty(name = "data",value = "有功功率数据") + private List data; + + @ApiModelProperty(name = "Q_βminMap",value = "无功功率最小CP95值A,B,C三项") + private Map Q_βminMap; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataVO.java new file mode 100644 index 0000000..cbe6f9c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityDataVO.java @@ -0,0 +1,37 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import com.njcn.influx.pojo.bo.CarryCapcityData; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * Description: + * Date: 2024/2/27 11:24【需求编号】 + * + * @author clam + * @version V1.0.0 + */ + +@Data +public class CarryCapacityDataVO { + @ApiModelProperty(name = "data",value = "有功功率数据") + private List data; + @ApiModelProperty(name = "stringMap",value = "首端电流模型参数A,B,C三项") + private Map stringMap; + + @ApiModelProperty(name = "P_βminMap",value = "有功功率最小CP95值A,B,C三项") + private Map P_βminMap; + @ApiModelProperty(name = "scale",value = "电压等级") + private String scale; + @ApiModelProperty(name = "devCapacity",value = "基准容量/额定容量(MVA)") + private Double standardCapacity; + + /** + * 用户协议容量(MVA) + */ + @ApiModelProperty(name = "dealCapacity",value = "用户协议容量(MVA)") + private Double protocolCapacity; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyDhlVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyDhlVO.java new file mode 100644 index 0000000..8a1313f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyDhlVO.java @@ -0,0 +1,76 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import lombok.Data; + +/** + * + * Description: + * Date: 2024/3/15 10:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class CarryCapacityStrategyDhlVO { + /** + * id + */ + private String id; + + /** + * 充电桩,电弧炉,电气化铁路 + */ + private String type; + + /** + * 一级评估比较符 + */ + private String comparisonOperators1; + + /** + * 一级评估数量 + */ + private Integer count1; + + /** + * 二级级评估(2~20次谐波合格个数)比较符 + */ + private String comparisonOperators2; + + /** + * 二级评估(2~20次谐波合格)个数数量 + */ + private Integer count2; + + /** + * 二级级评估(奇数谐波合格个数)比较符 + */ + private String comparisonOperators3; + + /** + * 二级评估(奇数次谐波合格)个数数量 + */ + private Integer count3; + + /** + * 初始配置1,客户配置2 + */ + private Integer protoFlag; + + /** + * 二级级评估(偶数谐波合格个数)比较符 + */ + private String comparisonOperators4; + + /** + * 二级评估(偶数次谐波合格)个数数量 + */ + private Integer count4; + + /** + * 启用配置1,不启用配置2 + */ + private Integer userFlag; + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyVO.java new file mode 100644 index 0000000..25feaa2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityStrategyVO.java @@ -0,0 +1,59 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2024/3/5 10:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class CarryCapacityStrategyVO { + + /** + * 总承载能力评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + + @ApiModelProperty(value = "总承载能力评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警)") + private Integer result; + + + + private List capacityStrategysingleVOList; + @Data + public static class CarryCapacityStrategysingleVO { + + private String id; + private List carryCapacityStrategyIndexVOList; + @Data + public static class CarryCapacityStrategyIndexVO { + + /** + * 指标评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警) + */ + @ApiModelProperty(value = "指标评估结果(1-安全,2-III级预警,3-II级预警,4-I 级预警)") + private Integer indexResult; + + /** + * 比较符 + */ + @ApiModelProperty(value = "比较符") + private String comparisonOperators; + + /** + * 数量 + */ + @ApiModelProperty(value = "数量") + private Integer count; + + } + + + + } +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityUserVO.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityUserVO.java new file mode 100644 index 0000000..e309c19 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/pojo/vo/CarryCapacityUserVO.java @@ -0,0 +1,53 @@ +package com.njcn.product.carrycapacity.pojo.vo; + +import com.njcn.db.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CarryCapacityUserVO extends BaseEntity { + /** + * 用户id + */ + private String userId; + + /** + * 用户名称 + */ + private String userName; + + /** + * 用户类型 + */ + private String userType; + + /** + * 电压等级(V) + */ + private String voltage; + + /** + * 用户协议容量(MVA) + */ + private Double protocolCapacity; + + + + /** + * 所属区域 + */ + private String area; + + +} \ No newline at end of file diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDataPOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDataPOService.java new file mode 100644 index 0000000..cd7d879 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDataPOService.java @@ -0,0 +1,17 @@ +package com.njcn.product.carrycapacity.service; + +import com.github.jeffreyning.mybatisplus.service.IMppService; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDataPO; + +/** + * + * Description: + * Date: 2024/3/6 14:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityDataPOService extends IMppService { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDevicePOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDevicePOService.java new file mode 100644 index 0000000..fb15c4d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityDevicePOService.java @@ -0,0 +1,21 @@ +package com.njcn.product.carrycapacity.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityDeviceParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; + +/** + * + * Description: + * Date: 2024/3/19 16:36【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityDevicePOService extends IService{ + + + Boolean updateDevice(CarryCapacityDeviceParam.CarryCapacityDeviceUpdateParam deviceParam); + + Boolean add(CarryCapacityDeviceParam capacityDeviceParam); + } diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityResultPOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityResultPOService.java new file mode 100644 index 0000000..b0f2b95 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityResultPOService.java @@ -0,0 +1,25 @@ +package com.njcn.product.carrycapacity.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityResultParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityResultPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDResultVO; + + +/** + * + * Description: + * Date: 2024/3/1 15:38【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityResultPOService extends IService{ + + + IPage queryResultList(CarryCapacityResultParam.CarryCapacityResultPageParam queryParam); + + CarryCapacityDResultVO queryResultbyCondition(CarryCapacityQueryDataParam queryParam); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityService.java new file mode 100644 index 0000000..954ec19 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityService.java @@ -0,0 +1,39 @@ +package com.njcn.product.carrycapacity.service; + + + +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityCalParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityEvaluateParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.param.ExcelDataParam; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDResultVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataIVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataQVO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDataVO; + +import java.util.List; + +/** + * Description: + * Date: 2024/1/31 14:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityService { + + + CarryCapacityDataVO queryCarryCapacityData(CarryCapacityQueryDataParam queryParam); + + CarryCapacityDataQVO queryCarryCapacityqData(CarryCapacityQueryDataParam queryParam); + + CarryCapacityDataIVO queryCarryCapacityiData(CarryCapacityQueryDataParam queryParam); + + CarryCapacityDResultVO carryCapacityCal(CarryCapacityCalParam calParam); + + + boolean uploadExcel(ExcelDataParam excelDataParam) throws Exception; + + + CarryCapacityDResultVO carryCapacityEvaluate(CarryCapacityEvaluateParam calParam); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyDhlPOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyDhlPOService.java new file mode 100644 index 0000000..27ab0ab --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyDhlPOService.java @@ -0,0 +1,24 @@ +package com.njcn.product.carrycapacity.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyDhlPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyDhlVO; + + +import java.util.List; + +/** + * + * Description: + * Date: 2024/3/15 10:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityStrategyDhlPOService extends IService{ + + + List queyDetailDhl(); + + Boolean adddhl(CarryCapacityStrategyDhlVO capacityStrategyDhlVO); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyPOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyPOService.java new file mode 100644 index 0000000..7201e0b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityStrategyPOService.java @@ -0,0 +1,29 @@ +package com.njcn.product.carrycapacity.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityStrategyParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyVO; + + +import java.util.List; + +/** + * + * Description: + * Date: 2024/3/5 10:33【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityStrategyPOService extends IService{ + + + Boolean add(CarryCapacityStrategyParam carryCapacityStrategyParam); + + List queyDetail(); + + Boolean restore(); + + Boolean addList(List carryCapacityStrategyParamList); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityUserPOService.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityUserPOService.java new file mode 100644 index 0000000..e75588f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/CarryCapacityUserPOService.java @@ -0,0 +1,25 @@ +package com.njcn.product.carrycapacity.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityUserParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CarryCapacityUserPOService extends IService{ + + + Boolean add(CarryCapacityUserParam carryCapacityUserParam); + + Boolean updateUser(CarryCapacityUserParam.CarryCapacityUserUpdateParam userUpdateParam); + + IPage queyDetailUser(CarryCapacityUserParam.CarryCapacityUserPageParam pageParm); + + CarryCapacityUserPO queyDetailUserById(String userId); + } diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDataPOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDataPOServiceImpl.java new file mode 100644 index 0000000..fdfb861 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDataPOServiceImpl.java @@ -0,0 +1,20 @@ +package com.njcn.product.carrycapacity.service.impl; + +import com.github.jeffreyning.mybatisplus.service.MppServiceImpl; + +import com.njcn.product.carrycapacity.mapper.CarryCapacityDataPOMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDataPO; +import com.njcn.product.carrycapacity.service.CarryCapacityDataPOService; +import org.springframework.stereotype.Service; +/** + * + * Description: + * Date: 2024/3/6 14:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class CarryCapacityDataPOServiceImpl extends MppServiceImpl implements CarryCapacityDataPOService { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDevicePOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDevicePOServiceImpl.java new file mode 100644 index 0000000..66440e0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityDevicePOServiceImpl.java @@ -0,0 +1,85 @@ +package com.njcn.product.carrycapacity.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.carrycapacity.mapper.CarryCapacityDevicePOMapper; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityDeviceParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; +import com.njcn.product.carrycapacity.service.CarryCapacityDevicePOService; +import com.njcn.product.carrycapacity.util.CheckStringUtil; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * + * Description: + * Date: 2024/3/19 16:36【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class CarryCapacityDevicePOServiceImpl extends ServiceImpl implements CarryCapacityDevicePOService { + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean updateDevice(CarryCapacityDeviceParam.CarryCapacityDeviceUpdateParam deviceParam) { + if(StringUtils.isBlank(deviceParam.getDevName())){ + throw new BusinessException("干扰源设备名称不能为空"); + } + checkName(deviceParam,true); + return this.lambdaUpdate().eq(CarryCapacityDevicePO::getDevId, deviceParam.getDevId()) + .set(CarryCapacityDevicePO::getDevName, deviceParam.getDevName()) + .set(CarryCapacityDevicePO::getDevScale, deviceParam.getDevScale()) + .set(CarryCapacityDevicePO::getProtocolCapacity, deviceParam.getProtocolCapacity()) + .update(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean add(CarryCapacityDeviceParam capacityDeviceParam) { + if(StringUtils.isBlank(capacityDeviceParam.getDevName())){ + throw new BusinessException("干扰源设备名称不能为空"); + } + checkName(capacityDeviceParam,false); + + CarryCapacityDevicePO carryCapacityDevice = new CarryCapacityDevicePO(); + BeanUtils.copyProperties(capacityDeviceParam,carryCapacityDevice); + return this.save(carryCapacityDevice); + } + + /** + * 检查名称是否已存在 + * + * @return 结果 + */ + private void checkName(CarryCapacityDeviceParam carryCapacityDeviceParam, boolean isUpdate) { + if(carryCapacityDeviceParam.getDevName().length()>32){ + throw new BusinessException("超过最大长度"); + + } + CheckStringUtil.checkName(carryCapacityDeviceParam.getDevName()); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + //条件组合:where state = 1 and name = ? + lambdaQueryWrapper.eq(CarryCapacityDevicePO::getUserId,carryCapacityDeviceParam.getUserId()).eq(CarryCapacityDevicePO::getDevName, carryCapacityDeviceParam.getDevName()); + + //and id <> ? + if (isUpdate) { + if (carryCapacityDeviceParam instanceof CarryCapacityDeviceParam.CarryCapacityDeviceUpdateParam) { + lambdaQueryWrapper.ne(CarryCapacityDevicePO::getDevId, ((CarryCapacityDeviceParam.CarryCapacityDeviceUpdateParam) carryCapacityDeviceParam).getDevId()); + } + } + + //若存在条件数据抛出异常 + int count = this.getBaseMapper().selectCount(lambdaQueryWrapper); + if (count > 0) { + throw new BusinessException("干扰源设备名称已存在"); + } + + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityResultPOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityResultPOServiceImpl.java new file mode 100644 index 0000000..f0c966e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityResultPOServiceImpl.java @@ -0,0 +1,105 @@ +package com.njcn.product.carrycapacity.service.impl; + +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.product.carrycapacity.mapper.CarryCapacityResultPOMapper; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityResultParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityResultPO; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityDResultVO; +import com.njcn.product.carrycapacity.service.CarryCapacityResultPOService; +import com.njcn.product.carrycapacity.service.CarryCapacityUserPOService; +import com.njcn.product.device.ledger.mapper.LineMapper; +import com.njcn.product.device.ledger.pojo.vo.LineDetailVO; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.ObjectUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * + * Description: + * Date: 2024/3/1 15:38【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CarryCapacityResultPOServiceImpl extends ServiceImpl implements CarryCapacityResultPOService { + private final CarryCapacityUserPOService carryCapacityUserPOService; + private final LineMapper lineMapper; + @Override + public IPage queryResultList(CarryCapacityResultParam.CarryCapacityResultPageParam queryParam) { + Page returnpage = new Page<> (queryParam.getPageNum ( ), queryParam.getPageSize ( )); + Page temppage = new Page<> (queryParam.getPageNum ( ), queryParam.getPageSize ( )); + + + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().eq(StringUtils.isNotBlank(queryParam.getEvaluateType()) ,CarryCapacityResultPO::getEvaluateType,queryParam.getEvaluateType()) + .between(StringUtils.isNotBlank(queryParam.getStartTime()) && StringUtils.isNotBlank(queryParam.getEndTime()) ,CarryCapacityResultPO::getEvaluateDate,queryParam.getStartTime()+" 00:00:00",queryParam.getEndTime()+" 23:59:59") + .eq(CarryCapacityResultPO::getStatus,1) + .orderByDesc(CarryCapacityResultPO::getEvaluateDate); + + IPage page = this.page(temppage, queryWrapper); + List collect = page.getRecords().stream().map(temp -> { + CarryCapacityDResultVO vo = new CarryCapacityDResultVO(); + BeanUtils.copyProperties(temp, vo); + String[] split = temp.getUserId().split(","); + List collect1 = Arrays.stream(split).sequential().map(userId -> { + CarryCapacityUserPO carryCapacityUser = carryCapacityUserPOService.queyDetailUserById(userId); + return carryCapacityUser.getUserName(); + }).collect(Collectors.toList()); + vo.setUserName(String.join(",", collect1)); + if (ObjectUtils.isNotEmpty(temp.getIResultList()) ){ + String iResultList = temp.getIResultList(); + List list = JSONUtil.toList(JSONUtil.toJsonStr(iResultList), CarryCapacityDResultVO.CarryCapacityIResult.class); + vo.setIResultList(list); + } + if(StringUtils.isNotBlank(vo.getLineId())){ + LineDetailVO data = lineMapper.getLineSubGdDetail(vo.getLineId()); + if(Objects.nonNull(data)){ + vo.setLineName(data.getGdName()+"->" + +data.getSubName()+"->" + +data.getDevName()+"->" + +data.getLineName()); + } + + } + + return vo; + }).collect(Collectors.toList()); + returnpage.setRecords(collect); + returnpage.setTotal(page.getTotal()); + + return returnpage; + } + + @Override + public CarryCapacityDResultVO queryResultbyCondition(CarryCapacityQueryDataParam queryParam) { + CarryCapacityDResultVO vo = new CarryCapacityDResultVO(); + + CarryCapacityResultPO one = this.lambdaQuery().eq(CarryCapacityResultPO::getLineId, queryParam.getLineId()) + .eq(CarryCapacityResultPO::getStartTime, queryParam.getStartTime()) + .eq(CarryCapacityResultPO::getEndTime, queryParam.getEndTime()) + .eq(CarryCapacityResultPO::getUserId, queryParam.getUserId()) + .eq(CarryCapacityResultPO::getStatus, 1).one(); + if(Objects.nonNull(one)){ + BeanUtils.copyProperties(one, vo); + } + return vo; + + + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityServiceImpl.java new file mode 100644 index 0000000..bf8a80f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityServiceImpl.java @@ -0,0 +1,1272 @@ +package com.njcn.product.carrycapacity.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.LocalDateTimeUtil; +import cn.hutool.json.JSONUtil; + +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.influx.constant.InfluxDbSqlConstant; +import com.njcn.influx.imapper.DataHarmPowerPMapper; +import com.njcn.influx.imapper.DataHarmPowerQMapper; +import com.njcn.influx.imapper.DataIMapper; +import com.njcn.influx.imapper.DataVMapper; +import com.njcn.influx.pojo.bo.CarryCapcityData; +import com.njcn.influx.pojo.constant.InfluxDBTableConstant; +import com.njcn.influx.pojo.po.DataI; +import com.njcn.product.carrycapacity.enums.CarryCapacityResponseEnum; +import com.njcn.product.carrycapacity.enums.CarryingCapacityEnum; +import com.njcn.product.carrycapacity.pojo.excel.*; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityCalParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityEvaluateParam; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityQueryDataParam; +import com.njcn.product.carrycapacity.pojo.param.ExcelDataParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDataPO; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityDevicePO; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityResultPO; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; +import com.njcn.product.carrycapacity.pojo.vo.*; +import com.njcn.product.carrycapacity.service.*; +import com.njcn.product.carrycapacity.util.*; +import com.njcn.product.device.ledger.pojo.vo.LineDetailDataVO; +import com.njcn.product.device.ledger.service.LineService; +import com.njcn.product.device.overlimit.pojo.Overlimit; +import com.njcn.product.device.overlimit.util.COverlimitUtil; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.service.IDictDataService; +import com.njcn.product.system.dict.enums.DicDataEnum; +import com.njcn.redis.utils.RedisUtil; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * Description: + * Date: 2024/1/31 14:42【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CarryCapacityServiceImpl implements CarryCapacityService { + + private final LineService lineService; + + private final DataHarmPowerQMapper dataHarmPowerqMapper; + + private final DataHarmPowerPMapper dataHarmPowerpMapper; + private final DataVMapper datavMapper; + + private final DataIMapper dataiMapper; + + private final CarryCapacityStrategyPOService carryCapacityStrategyPOService; + private final CarryCapacityDataPOService carryCapacityDataPOService; + private final RedisUtil redisUtil; + private final CarryCapacityResultPOService carryCapacityResultPOService; + private final CarryCapacityUserPOService carryCapacityUserPOService; + private static final double DEFAULTVALUE = 3.1415926; + + private final FileUtils fileUtils; + + private final IDictDataService iDictDataService; + + + @Override + public CarryCapacityDataVO queryCarryCapacityData(CarryCapacityQueryDataParam queryParam) { + + //前一周数据 + List dataHarmPowerpList; + List dataHarmPowerqList; + //前2周的数据 + List dataHarmPowerP2List; + List dataHarmPowerQ2List; + List dataHarmPowerU2List; + + CarryCapacityDataVO carryCapacityDataVO = new CarryCapacityDataVO(); + String lineId = queryParam.getLineId(); + LineDetailDataVO data = lineService.getLineDetailData(lineId); +// //时间间隔 + Integer timeInterval = data.getTimeInterval(); + + LocalDate startDate = queryParam.getStartTime(); + LocalDate endDate = queryParam.getEndTime(); + //前2周的时间 + LocalDate startDate2 = startDate.plusWeeks(-1); + LocalDate endDate2 = endDate.plusWeeks(-1); + + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String startTime = LocalDateTimeUtil.format(queryParam.getStartTime(), formatter) + " 00:00:00"; + String endTime = LocalDateTimeUtil.format(queryParam.getEndTime(), formatter) + " 23:59:00"; + + //先重redis读取数据,无数据,查看是否存在文件,不存在文件查数据库,数据校验补通过上传文件 + dataHarmPowerpList = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "P"); + dataHarmPowerP2List = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "P"); + dataHarmPowerQ2List = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "Q"); + dataHarmPowerU2List = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "U"); + + if (CollectionUtil.isEmpty(dataHarmPowerpList) || + CollectionUtil.isEmpty(dataHarmPowerP2List) || + CollectionUtil.isEmpty(dataHarmPowerQ2List) || + CollectionUtil.isEmpty(dataHarmPowerU2List)) { + CarryCapacityDataPO one = carryCapacityDataPOService.lambdaQuery().eq(CarryCapacityDataPO::getLineId, lineId) + .eq(CarryCapacityDataPO::getStartTime, queryParam.getStartTime()) + .eq(CarryCapacityDataPO::getEndTime, queryParam.getEndTime()).one(); + if (Objects.nonNull(one)) { + //todo 调用查询文件 + InputStream fileStream = null; + try { + fileStream = fileUtils.getFileStream(one.getDateList()); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + ExcelDataDTO excelDataDTO = parsingFile(one.getStartTime(), one.getEndTime(), fileStream); + dataHarmPowerpList = excelDataDTO.getDataHarmPowerPList(); + dataHarmPowerP2List = excelDataDTO.getDataHarmPowerP2List(); + dataHarmPowerQ2List = excelDataDTO.getDataHarmPowerQ2List(); + dataHarmPowerU2List = excelDataDTO.getDataHarmPowerU2List(); + + + } else { + /* 近一周的数据包括电流,电压,有功功率,无功功率,数据完整性校验就取有功功率一组数据校验,因为,要有都有要没有都没有,数据查询按时间间隔和tag分组, + 缺失布置3.1415926,后边更具3.1415926个数来判断数据完整性,及进行数据补充*/ + //有功功率 + String sqlP1 = "select mean(p)*1000 as value from data_harmpower_p where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + startTime + "'and time <= '" + endTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerpList = dataHarmPowerpMapper.getSqlResult(sqlP1); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerpList)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerpList, startDate, endDate, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + //数据缺失填补 + linearInterpolation(dataHarmPowerpList); +// redisUtil.saveByKey(lineId+"#"+LocalDateTimeUtil.format(startDate, formatter)+"#"+LocalDateTimeUtil.format(endDate, formatter)+"#"+"P", +// dataHarmPowerPList); + + //无功功率 + String sqlQ1 = "select mean(q)*1000 as value from data_harmpower_q where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + startTime + "'and time <= '" + endTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerqList = dataHarmPowerqMapper.getSqlResult(sqlQ1); + //数据缺失填补 + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerqList)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerqList, startDate, endDate, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + + linearInterpolation(dataHarmPowerqList); +// redisUtil.saveByKey(lineId+"#"+LocalDateTimeUtil.format(startDate, formatter)+"#"+LocalDateTimeUtil.format(endDate, formatter)+"#"+"Q", +// dataHarmPowerqList); + + + //前2周的数据用于计算首端电流模型参数 + String forwardStartTime = LocalDateTimeUtil.format(queryParam.getStartTime() + .plusWeeks(-1) + , formatter) + " 00:00:00"; + String forwardEndTime = LocalDateTimeUtil.format(queryParam.getEndTime() + .plusWeeks(-1) + , formatter) + " 23:59:00"; + + String sqlP2 = "select mean(p)*1000 as value from data_harmpower_p where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + forwardStartTime + "'and time <= '" + forwardEndTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerP2List = dataHarmPowerpMapper.getSqlResult(sqlP2); + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerP2List)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerP2List, startDate2, endDate2, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + + //数据缺失填补 + linearInterpolation(dataHarmPowerP2List); + + + //无功功率 + String sqlQ2 = "select mean(q)*1000 as value from data_harmpower_q where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + forwardStartTime + "'and time <= '" + forwardEndTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerQ2List = dataHarmPowerqMapper.getSqlResult(sqlQ2); + //数据校验 + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerQ2List)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerQ2List, startDate2, endDate2, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + + //数据缺失填补 + linearInterpolation(dataHarmPowerQ2List); + + + //电压 + String sqlU2 = "select mean(rms)*1000 as value from data_v where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + forwardStartTime + "'and time <= '" + forwardEndTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerU2List = datavMapper.getSqlResult(sqlU2); + //数据校验 + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerU2List)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerU2List, startDate2, endDate2, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + //数据缺失填补 + linearInterpolation(dataHarmPowerU2List); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "P", + dataHarmPowerpList); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "P", + dataHarmPowerP2List); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "Q", + dataHarmPowerQ2List); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "U", + dataHarmPowerU2List); + + + } + + + } +// dataHarmPowerpList = dataHarmPowerpList.stream().map(temp -> { +// temp.setTime(temp.getTime().plusMillis(TimeUnit.HOURS.toMillis(8))); +// return temp; +// }).collect(Collectors.toList()); + carryCapacityDataVO.setData(dataHarmPowerpList); + + + List phaseType = Stream.of("A", "B", "C").collect(Collectors.toList()); + + Map results = new HashMap<>(4); + //计算最小Cp95值用于评估 + List finalDataHarmPowerpList = dataHarmPowerpList; + phaseType.forEach(phase -> { + List listP = finalDataHarmPowerpList.stream().filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getValue() != DEFAULTVALUE && Objects.nonNull(temp.getValue())) + .filter(temp -> Objects.equals(temp.getPhaseType(), phase)) + .map(CarryCapcityData::getValue) + .collect(Collectors.toList()); + double pMin = CarryCapacityUtil.calculatePercentile(listP, 1); + results.put(phase, pMin); + }); + + carryCapacityDataVO.setP_βminMap(results); + + try { + //用前2周的数据计算C,a,b + Map stringMap = caluParam(dataHarmPowerP2List, dataHarmPowerQ2List, dataHarmPowerU2List); + carryCapacityDataVO.setStringMap(stringMap); + return carryCapacityDataVO; + }catch (Exception e){ + return carryCapacityDataVO; + } + + } + + @Override + public CarryCapacityDataQVO queryCarryCapacityqData(CarryCapacityQueryDataParam queryParam) { + + CarryCapacityDataQVO carryCapacityDataqVO = new CarryCapacityDataQVO(); + String lineId = queryParam.getLineId(); + LineDetailDataVO data = lineService.getLineDetailData(lineId); + //时间间隔 + Integer timeInterval = data.getTimeInterval(); +// Integer timeInterval =10; + + //根据时间间隔算出最低数据量 7天*6小时*60分钟*3项*90%/时间间隔 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate startDate = queryParam.getStartTime(); + LocalDate endDate = queryParam.getEndTime(); + + String startTime = LocalDateTimeUtil.format(queryParam.getStartTime(), formatter) + " 00:00:00"; + String endTime = LocalDateTimeUtil.format(queryParam.getEndTime(), formatter) + " 23:59:00"; + List dataHarmPowerqList = new ArrayList<>(); + dataHarmPowerqList = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "Q"); + if (CollectionUtil.isEmpty(dataHarmPowerqList)) { + //无功功率 + String sqlQ1 = "select mean(q)*1000 as value from data_harmpower_q where value_type='CP95' and phasic_type!='T' and line_id='" + lineId + + "' and time >= '" + startTime + "'and time <= '" + endTime + "'" + "group by time(" + timeInterval + "m) ,* fill(0.0031415926)" + InfluxDbSqlConstant.TZ; + dataHarmPowerqList = dataHarmPowerqMapper.getSqlResult(sqlQ1); + if (CollectionUtil.isEmpty(dataHarmPowerqList)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + + if (checkData(dataHarmPowerqList, startDate, endDate, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + //数据缺失填补 + linearInterpolation(dataHarmPowerqList); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "Q", + dataHarmPowerqList); + } +// dataHarmPowerqList = dataHarmPowerqList.stream().map(temp -> { +// temp.setTime(temp.getTime().plusMillis(TimeUnit.HOURS.toMillis(8))); +// return temp; +// }).collect(Collectors.toList()); + + carryCapacityDataqVO.setData(dataHarmPowerqList); + + + List phaseType = Stream.of("A", "B", "C").collect(Collectors.toList()); + + Map results = new HashMap<>(4); + //计算最小Cp95值用于评估 + List finalDataHarmPowerqList = dataHarmPowerqList; + phaseType.forEach(phase -> { + List listQ = finalDataHarmPowerqList.stream().filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getValue() != DEFAULTVALUE && Objects.nonNull(temp.getValue())) + .filter(temp -> Objects.equals(temp.getPhaseType(), phase)) + .map(CarryCapcityData::getValue) + .collect(Collectors.toList()); + double qMin = CarryCapacityUtil.calculatePercentile(listQ, 1); + results.put(phase, qMin); + }); + + carryCapacityDataqVO.setQ_βminMap(results); + return carryCapacityDataqVO; + } + + @Override + public CarryCapacityDataIVO queryCarryCapacityiData(CarryCapacityQueryDataParam queryParam) { + CarryCapacityDataIVO carryCapacityDataiVO = new CarryCapacityDataIVO(); + String lineId = queryParam.getLineId(); + LineDetailDataVO data = lineService.getLineDetailData(lineId); + //时间间隔 + Integer timeInterval = data.getTimeInterval(); + LocalDate startDate = queryParam.getStartTime(); + LocalDate endDate = queryParam.getEndTime(); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String startTime = LocalDateTimeUtil.format(startDate, formatter) + " 00:00:00"; + String endTime = LocalDateTimeUtil.format(endDate, formatter) + " 23:59:00"; + + List dataI = new ArrayList<>(); + dataI = (List) redisUtil.getObjectByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "I"); + + if (CollectionUtil.isEmpty(dataI)) { + //电流 + StringBuilder stringBuilder1 = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + for (int i = 2; i <= 25; i++) { + if (i == 25) { + stringBuilder1.append("mean(i_").append(i).append(") AS i_").append(i); + } else { + stringBuilder1.append("mean(i_").append(i).append(") AS i_").append(i).append(","); + } + } + stringBuilder2.append("line_id='").append(lineId).append("' and ").append(InfluxDbSqlConstant.TIME + " >= '").append(startTime).append("' and ").append(InfluxDbSqlConstant.TIME).append(" <= '").append(endTime).append("' group by time(").append(timeInterval).append("m),* fill(3.1415926) ").append(InfluxDbSqlConstant.TZ); + String sqlI1 = "select " + stringBuilder1 + " from " + InfluxDBTableConstant.DATA_I + " where value_type='CP95' and phasic_type!='T' and " + stringBuilder2; + dataI = dataiMapper.getSqlResult(sqlI1); + //此处查询influxdb少8个小时 + dataI = dataI.stream().map(temp -> { + temp.setTime(temp.getTime().plusMillis(TimeUnit.HOURS.toMillis(8))); + return temp; + }).collect(Collectors.toList()); + if (CollectionUtil.isEmpty(dataI)) { + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } else { + List iList = dataI.stream().map(temp -> { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(temp, carryCapcityData); + carryCapcityData.setValue(temp.getI2()); + return carryCapcityData; + }).collect(Collectors.toList()); + if (checkData(iList, startDate, endDate, timeInterval)) { + + throw new BusinessException(CarryCapacityResponseEnum.DATA_NOT_FOUND); + } + } + //数据缺失填补 + linearInterpolationI(dataI); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "I", + dataI); + + } + + List iList = dataI.stream().map(temp -> { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(temp, carryCapcityData); + carryCapcityData.setValue(Utils.getAttributeValueByPropertyName(temp, "i" + queryParam.getTime())); + return carryCapcityData; + }).collect(Collectors.toList()); + carryCapacityDataiVO.setData(iList); + + List iMaxList = new ArrayList<>(); + List integerList = Stream.of(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25).collect(Collectors.toList()); + List phaseType = Stream.of("A", "B", "C").collect(Collectors.toList()); + List finalDataI = dataI; + integerList.forEach(temp -> { + List tempList = new ArrayList<>(); + phaseType.forEach(phase -> { + + List tempDataiList = finalDataI.stream().filter(temp1 -> Utils.isTimeInRange(temp1.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp1 -> temp1.getPhaseType().equals(phase)) + .collect(Collectors.toList()); + + List attributeValueByPropertyName = Utils.getAttributeValueByPropertyName(tempDataiList, "i" + temp); + double iCp95 = CarryCapacityUtil.calculatePercentile(attributeValueByPropertyName, 0); + tempList.add(iCp95); + }); + //取uList最大值 + double iMax = tempList.stream().mapToDouble(Double::doubleValue) + .max() + .getAsDouble(); + iMaxList.add(iMax); + }); + carryCapacityDataiVO.setI_βmax(iMaxList); + + return carryCapacityDataiVO; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public CarryCapacityDResultVO carryCapacityCal(CarryCapacityCalParam calParam) { + CarryCapacityDResultVO carryCapacitydResultVO = new CarryCapacityDResultVO(); + if(CollectionUtil.isEmpty(calParam.getStringMap())){ + throw new BusinessException("数据有误,模型训练失败"); + } + + String scale = calParam.getScale(); + String scaleValue = iDictDataService.getDicDataById(scale).getValue(); + + //todo S_T查询监测点的容量 + Double sT = calParam.getS_T(); + Double sPv = calParam.getS_pv(); + Double pPv = calParam.getS_pv() * Double.valueOf(CarryingCapacityEnum.K.getValue()); + List phaseType = Stream.of("A", "B", "C").collect(Collectors.toList()); + List uList = new ArrayList<>(); + List pftList = new ArrayList<>(); + List btList = new ArrayList<>(); + for (String phase : phaseType) { + Double pMin = calParam.getP_βminMap().get(phase)/1000.00; + Double qMin = calParam.getQ_βminMap().get(phase)/1000.00; + Double[] res = calParam.getStringMap().get(phase); + double bt = CarryCapacityUtil.calculateB(pMin, qMin, Double.parseDouble(CarryingCapacityEnum.K.getValue()), sT, sPv, pPv); + btList.add(bt); + double pft = CarryCapacityUtil.calculatePF_T(pMin, qMin, Double.parseDouble(CarryingCapacityEnum.K.getValue()), sPv); + pftList.add(pft); + double u = CarryCapacityUtil.calculateU(res[0], res[1], res[2], pMin, Double.parseDouble(CarryingCapacityEnum.K.getValue()), qMin, sPv, Double.parseDouble(scaleValue)); + uList.add(u); + } + //取uList最大值 + double utMax = uList.stream().mapToDouble(Double::doubleValue) + .max() + .getAsDouble(); + + double pftMax = pftList.stream().mapToDouble(Double::doubleValue) + .max() + .getAsDouble(); + + double btMax = btList.stream().mapToDouble(Double::doubleValue) + .max() + .getAsDouble(); + Integer utLevel = CarryCapacityUtil.evaluateVoltageLevel(utMax); + carryCapacitydResultVO.setUTLevel(utLevel); + + Integer pftLevel = CarryCapacityUtil.evaluatePowerFactorLevel(pftMax); + carryCapacitydResultVO.setPfTLevel(pftLevel); + + Integer btLevel = CarryCapacityUtil.evaluateEquivalentLoadRateLevel(btMax); + carryCapacitydResultVO.setBTLevel(btLevel); + //谐波电流幅值判断 + //获取限值 + Overlimit overlimit = lineService.getOverLimitData(calParam.getLineId()); + + //各次谐波电流 均小于国标限值 返回1 存在某次谐波电流幅值 超出限值,但在1.25倍限值内 返回2 存在某次谐波电流幅值超出限值1.25倍以上 返回3 存在多次谐波电流幅值均超出限值1.25倍以上 返回4 + //i_count1小于国标限值的个数,i_count2>=国标限值<=1.25倍的国标限值,i_count3>1.25倍的国标限值 + int iCount1 = 0, iCount2 = 0, iCount3 = 0; + for (int i = 0; i < calParam.getI_βmax().size(); i++) { + double itm = CarryCapacityUtil.calculateITm(calParam.getI_βmax().get(i), Double.parseDouble(CarryingCapacityEnum.K.getValue()), + Double.parseDouble(scaleValue), sPv, Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("K_H_" + (i + 2)))), + Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("I_INV_" + (i + 2))))); + double getUharm = PubUtils.getValueByMethod(overlimit, "getIharm", i + 2); + if (itm < getUharm) { + iCount1++; + } else if (itm >= getUharm && itm <= 1.25 * getUharm) { + iCount2++; + } else if (itm > 1.25 * getUharm) { + iCount3++; + } + + } + int iLevel = 1; + if (iCount3 > 1) { + iLevel = 4; + } else if (iCount3 == 1) { + iLevel = 3; + } else if (iCount2 == 1) { + iLevel = 2; + } + carryCapacitydResultVO.setILevel(iLevel); + //统计安全,3级预警,2级预警1级预警个数 + List list = Stream.of(utLevel, pftLevel, btLevel, iLevel).collect(Collectors.toList()); + int safeCount, warnCount3, warnCount2, warnCount1; + safeCount = (int) list.stream() + .filter(temp -> temp == 1) + .count(); + warnCount3 = (int) list.stream() + .filter(temp -> temp == 2) + .count(); + warnCount2 = (int) list.stream() + .filter(temp -> temp == 3) + .count(); + warnCount1 = (int) list.stream() + .filter(temp -> temp == 4) + .count(); + + + List carryCapacityStrategyVOList = carryCapacityStrategyPOService.queyDetail(); + carryCapacitydResultVO.setReslutLevel(5); + //1-安全,2-III级预警,3-II级预警,4-I 级预警,依次执行策略看是否符合 + for (int i = 1; i < 5; i++) { + boolean b = strategyReslut(carryCapacityStrategyVOList, i, safeCount, warnCount1, warnCount2, warnCount3); + + if (b) { + carryCapacitydResultVO.setReslutLevel(i); + break; + } + } + CarryCapacityResultPO carryCapacityResult = new CarryCapacityResultPO(); + List list1 = carryCapacityResultPOService.lambdaQuery().eq(CarryCapacityResultPO::getLineId, calParam.getLineId()) + .eq(CarryCapacityResultPO::getUserId, calParam.getUserId()) + .eq(CarryCapacityResultPO::getStartTime, calParam.getStartTime()) + .eq(CarryCapacityResultPO::getEndTime, calParam.getEndTime()) + .eq(CarryCapacityResultPO::getStatus, 1).list(); + if (CollectionUtil.isNotEmpty(list1)) { + throw new BusinessException(CarryCapacityResponseEnum.EXISTENCE_EVALUATION_RESULT); + + } + + carryCapacityResult.setLineId(calParam.getLineId()); + carryCapacityResult.setUserId(calParam.getUserId()); + // + CarryCapacityUserPO carryCapacityUser = carryCapacityUserPOService.queyDetailUserById(calParam.getUserId()); + carryCapacityResult.setEvaluateType(carryCapacityUser.getUserType()); + + carryCapacityResult.setStartTime(calParam.getStartTime()); + carryCapacityResult.setEndTime(calParam.getEndTime()); + carryCapacityResult.setUTLevel(carryCapacitydResultVO.getUTLevel()); + carryCapacityResult.setPfTLevel(carryCapacitydResultVO.getPfTLevel()); + carryCapacityResult.setBTLevel(carryCapacitydResultVO.getBTLevel()); + carryCapacityResult.setILevel(carryCapacitydResultVO.getILevel()); + carryCapacityResult.setReslutLevel(carryCapacitydResultVO.getReslutLevel()); + carryCapacityResult.setEvaluateDate(LocalDate.now()); + carryCapacityResult.setStatus(1); + carryCapacityResultPOService.save(carryCapacityResult); + + return carryCapacitydResultVO; + } + + + @SneakyThrows + @Override + public boolean uploadExcel(ExcelDataParam excelDataParam) { + + String lineId = excelDataParam.getLineId(); + LineDetailDataVO data = lineService.getLineDetailData(lineId); + //时间间隔 + Integer timeInterval = data.getTimeInterval(); + + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate startDate = LocalDate.parse(excelDataParam.getStartTime(), formatter); + LocalDate endDate = LocalDate.parse(excelDataParam.getEndTime(), formatter); + //前2周的时间 + LocalDate startDate2 = startDate.plusWeeks(-1); + LocalDate endDate2 = endDate.plusWeeks(-1); + + + //前一周的数据 + ExcelDataDTO excelDataDTO = parsingFile(startDate, endDate, excelDataParam.getFile().getInputStream()); + List dataHarmPowerpList = excelDataDTO.getDataHarmPowerPList(); + List dataHarmPowerqList = excelDataDTO.getDataHarmPowerQList(); + List dataiList = excelDataDTO.getDataIList(); + ////前2周的数据 + List dataHarmPowerp2List = excelDataDTO.getDataHarmPowerP2List(); + List dataHarmPowerq2List = excelDataDTO.getDataHarmPowerQ2List(); + List dataHarmPoweruList = excelDataDTO.getDataHarmPowerU2List(); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerpList)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + + if (checkData(dataHarmPowerpList, startDate, endDate, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据是否充足"); + } + } + linearInterpolation(dataHarmPowerpList); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerp2List)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + + if (checkData(dataHarmPowerp2List, startDate2, endDate2, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的前一周数据量是否充足"); + } + } + linearInterpolation(dataHarmPowerp2List); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerqList)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + + if (checkData(dataHarmPowerqList, startDate, endDate, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据是否充足"); + } + } + linearInterpolation(dataHarmPowerqList); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPowerq2List)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + + if (checkData(dataHarmPowerq2List, startDate2, endDate2, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的前一周数据量是否充足"); + } + } + linearInterpolation(dataHarmPowerq2List); + + //数据校验 + if (CollectionUtil.isEmpty(dataHarmPoweruList)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + + if (checkData(dataHarmPoweruList, startDate2, endDate2, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的前一周数据量是否充足"); + } + } + linearInterpolation(dataHarmPoweruList); + + if (CollectionUtil.isEmpty(dataiList)) { + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据及其上周是否充足"); + } else { + List iList = dataiList.stream().map(temp -> { + CarryCapcityData carryCapcityData = new CarryCapcityData(); + BeanUtils.copyProperties(temp, carryCapcityData); + carryCapcityData.setValue(temp.getI2()); + return carryCapcityData; + }).collect(Collectors.toList()); + if (checkData(iList, startDate, endDate, timeInterval)) { + + throw new BusinessException("数据量过少,请查看上传数据集的数据集时间与页面选择时间"+startDate+"-"+endDate+"的本周数据量是否充足"); + } + } + linearInterpolationI(dataiList); + +// 存入redis + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "P", + dataHarmPowerpList); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "P", + dataHarmPowerp2List); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "Q", + dataHarmPowerqList); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "Q", + dataHarmPowerq2List); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate2, formatter) + "#" + LocalDateTimeUtil.format(endDate2, formatter) + "#" + "U", + dataHarmPoweruList); + redisUtil.saveByKey(lineId + "#" + LocalDateTimeUtil.format(startDate, formatter) + "#" + LocalDateTimeUtil.format(endDate, formatter) + "#" + "I", + dataiList); + //todo 将文件存入文件服务器获取url + String filePath = fileUtils.uploadFile(excelDataParam.getFile()); +// String url = "temp"; + CarryCapacityDataPO carryCapacityData = new CarryCapacityDataPO(lineId, startDate, endDate, filePath); + carryCapacityDataPOService.saveOrUpdateByMultiId(carryCapacityData); + + + return true; + } + + + @Override + public CarryCapacityDResultVO carryCapacityEvaluate(CarryCapacityEvaluateParam calParam) { + CarryCapacityDResultVO vo = new CarryCapacityDResultVO(); + List carryCapacityiResultList = new ArrayList<>(); + + List devList = calParam.getDevList(); + if (CollectionUtil.isEmpty(devList)) { + throw new BusinessException(CarryCapacityResponseEnum.DEVICE_LOST); + } + String userId = devList.get(0).getUserId(); + CarryCapacityUserPO carryCapacityUser = carryCapacityUserPOService.queyDetailUserById(userId); + String userType = carryCapacityUser.getUserType(); + String code = iDictDataService.getDicDataById(userType).getCode(); + //用户协议容量 + double sumCapacity = carryCapacityUser.getProtocolCapacity(); + + double rate = sumCapacity / calParam.getShortCapacity(); + vo.setFirstResult(rate * 100); + + CarryCapacityResultPO carryCapacityResult = new CarryCapacityResultPO(); + carryCapacityResult.setFirstResult(rate * 100); + carryCapacityResult.setUserId(userId); + carryCapacityResult.setEvaluateDate(LocalDate.now()); + carryCapacityResult.setEvaluateType(userType); + carryCapacityResult.setStatus(1); + carryCapacityResult.setPtType(calParam.getPtType()); + carryCapacityResult.setConnectionMode(calParam.getConnectionMode()); + carryCapacityResult.setK(calParam.getK()); + carryCapacityResult.setUserMode(calParam.getUserMode()); + carryCapacityResult.setScale(calParam.getScale()); + carryCapacityResult.setShortCapacity(calParam.getShortCapacity()); + carryCapacityResult.setDeviceCapacity(calParam.getDeviceCapacity()); + + + carryCapacityResult.setStatus(1); + if (rate < 0.001) { + carryCapacityResult.setReslutLevel(6); + carryCapacityResultPOService.save(carryCapacityResult); + return vo; + } + + /*二次评估充电桩、电气化铁路如果经过变压器并网的是需要的,像电弧炉他是要经过一个电弧炉专用变压器并网的 + 正常如果是专变用户的话是经过变压器的高压侧进行考核,公变用户的正常是在低压侧进行考核, + 当变压器连接方式为YNyn零序电流可以流通计算变压器高压侧的谐波电流(零序电流次数为3、6、9、12、)否则为0 + */ + //设备电压等级单位KV + String sacaleValue = iDictDataService.getDicDataById(calParam.getScale()).getValue(); + +// //用户电压等级 + DictData data = iDictDataService.getDicDataById(carryCapacityUser.getVoltage()); + + float userSacaleValue = Float.parseFloat(data.getValue()) * (data.getCode().contains("k") ? 1000 : 1); + //用户模式专变用户,公变用户 + String userMode = iDictDataService.getDicDataById(calParam.getUserMode()).getCode(); + //变压器连接方式接线方式 + String connectionMode; + if (Objects.nonNull(calParam.getConnectionMode()) && !"".equals(calParam.getConnectionMode())) { + connectionMode = iDictDataService.getDicDataById(calParam.getConnectionMode()).getCode(); + + } else { + connectionMode = ""; + } + + List integerList = Stream.of(3, 5, 7, 9, 11, 13, 15, 17, 19).collect(Collectors.toList()); + + + Overlimit overlimit = new Overlimit(); + COverlimitUtil.iHarm(overlimit, Float.valueOf(sacaleValue), (float) sumCapacity, calParam.getDeviceCapacity(), calParam.getShortCapacity()); + + + if (DicDataEnum.Charging_Station_Users.getCode().equals(code)) { + + integerList.forEach(temp -> { + CarryCapacityDResultVO.CarryCapacityIResult carryCapacityiResultVO = new CarryCapacityDResultVO.CarryCapacityIResult(); + List ilist = new ArrayList<>(); + devList.forEach(dev -> { + DictData devScaledata = iDictDataService.getDicDataById(dev.getDevScale()); + double devScaleValue = Float.parseFloat(devScaledata.getValue()) * (devScaledata.getCode().contains("k") ? 1 : 0.0001); + //基波电流I_1:设备容量(转成KVA*1000)*K(功率因数)(转成kW)/更号3*电压等级(转成Kv) + + double i1 = dev.getProtocolCapacity() * 1000 * calParam.getK() / (Math.sqrt(3) * devScaleValue); + //低压侧 + double iH = i1 * (Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("CP_I_" + temp)))) / 100; + //当变压器连接方式为YNyn零序电流可以流通计算变压器高压侧的谐波电流(零序电流次数为3、6、9、12、)否则为0 + if (!DicDataEnum.YNyn.getCode().equals(connectionMode) && temp % 3 == 0) { + iH = 0.00; + } + ilist.add(iH); + + }); + //将变压器下多个设备电流合并 + Double mergeI = mergeiList(ilist); + + + //专变用户的话是经过变压器的高压侧进行考核,公变用户的正常是在低压侧进行考核 + if (DicDataEnum.SPECIAL_USER.getCode().equals(userMode)) { + mergeI = mergeI / (Double.parseDouble(sacaleValue) * 1000 / userSacaleValue); + } + + carryCapacityiResultVO.setTime(temp); + carryCapacityiResultVO.setI(mergeI); + double getUharm = PubUtils.getValueByMethod(overlimit, "getIharm", temp); + carryCapacityiResultVO.setI_limit(getUharm); + carryCapacityiResultList.add(carryCapacityiResultVO); + }); + + } else if (DicDataEnum.Electric_Heating_Load_Users.getCode().equals(code)) { + + integerList.forEach(temp -> { + CarryCapacityDResultVO.CarryCapacityIResult carryCapacityiResultVO = new CarryCapacityDResultVO.CarryCapacityIResult(); + List ilist = new ArrayList<>(); + devList.forEach(dev -> { + DictData devScaledata = iDictDataService.getDicDataById(dev.getDevScale()); + double devScaleValue = Float.parseFloat(devScaledata.getValue()) * (devScaledata.getCode().contains("k") ? 1 : 0.0001); + //基波电流I_1:设备容量(转成KVA*1000)*K(功率因数)(转成kW)/更号3*电压等级(转成Kv) + double i1 = dev.getProtocolCapacity() * 1000 * calParam.getK() / (Math.sqrt(3) * devScaleValue); + //低压侧 + double iH = i1 * (Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("EAF_I_" + temp)))) / 100; + //当变压器连接方式为YNyn零序电流可以流通计算变压器高压侧的谐波电流(零序电流次数为3、6、9、12、)否则为0 + if (!DicDataEnum.YNyn.getCode().equals(connectionMode) && temp % 3 == 0) { + iH = 0.00; + } + ilist.add(iH); + + }); + //将变压器下多个设备电流合并 + Double mergeI = mergeiList(ilist); + + + //专变用户的话是经过变压器的高压侧进行考核,公变用户的正常是在低压侧进行考核 + if (DicDataEnum.SPECIAL_USER.getCode().equals(userMode)) { + mergeI = mergeI / (Double.parseDouble(sacaleValue) * 1000 / userSacaleValue); + } + + carryCapacityiResultVO.setTime(temp); + carryCapacityiResultVO.setI(mergeI); + double getUharm = PubUtils.getValueByMethod(overlimit, "getIharm", temp); + carryCapacityiResultVO.setI_limit(getUharm); + carryCapacityiResultList.add(carryCapacityiResultVO); + }); + + } else if (DicDataEnum.Electrified_Rail_Users.getCode().equals(code)) { + integerList.forEach(temp -> { + CarryCapacityDResultVO.CarryCapacityIResult carryCapacityiResult = new CarryCapacityDResultVO.CarryCapacityIResult(); + List ilist = new ArrayList<>(); + devList.forEach(dev -> { + DictData devScaledata = iDictDataService.getDicDataById(dev.getDevScale()); + double devScaleValue = Float.parseFloat(devScaledata.getValue()) * (devScaledata.getCode().contains("k") ? 1 : 0.0001); + //基波电流I_1:设备容量(转成KVA*1000)*K(功率因数)(转成kW)/更号3*电压等级(转成Kv) + double i1 = dev.getProtocolCapacity() * 1000 * calParam.getK() / (Math.sqrt(3) * devScaleValue); + //低压侧 + double iH = i1 * (Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("ER_I_" + temp)))) / 100; + //当变压器连接方式为YNyn零序电流可以流通计算变压器高压侧的谐波电流(零序电流次数为3、6、9、12、)否则为0 + if (!DicDataEnum.YNyn.getCode().equals(connectionMode) && temp % 3 == 0) { + iH = 0.00; + } + ilist.add(iH); + + }); + //将变压器下多个设备电流合并 + Double mergeI = mergeiList(ilist); + + + //专变用户的话是经过变压器的高压侧进行考核,公变用户的正常是在低压侧进行考核 + if (DicDataEnum.SPECIAL_USER.getCode().equals(userMode)) { + mergeI = mergeI / (Double.parseDouble(sacaleValue) * 1000 / userSacaleValue); + } + + carryCapacityiResult.setTime(temp); + carryCapacityiResult.setI(mergeI); + double getUharm = PubUtils.getValueByMethod(overlimit, "getIharm", temp); + carryCapacityiResult.setI_limit(getUharm); + carryCapacityiResultList.add(carryCapacityiResult); + }); + } + vo.setIResultList(carryCapacityiResultList); + carryCapacityResult.setIResultList(JSONUtil.toJsonStr(carryCapacityiResultList)); + long count = carryCapacityiResultList.stream().filter(temp -> temp.getI() > temp.getI_limit()).count(); + carryCapacityResult.setReslutLevel(count == 0 ? 6 : 5); + vo.setReslutLevel(count == 0 ? 6 : 5); + carryCapacityResultPOService.save(carryCapacityResult); + + return vo; + } + + private Double mergeiList(List ilist) { + Double result; + + if (ilist.size() == 1) { + return ilist.get(0); + } else { + result = ilist.get(0); + for (int i = 1; i < ilist.size(); i++) { + double sum = result * result + ilist.get(i) * ilist.get(i) + Double.parseDouble(Objects.requireNonNull(CarryingCapacityEnum.getValueByCode("K_H_" + (i + 2)))) * result * ilist.get(i); + result = Math.sqrt(sum); + } + + } + + + return result; + } + + + public static ExcelDataDTO parsingFile(LocalDate startDate, LocalDate endDate, InputStream is) { +// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + List dataHarmPowerpList; + List dataHarmPowerqList; + List dataiList; + + //前2周的时间 + LocalDate startDate2 = startDate.plusWeeks(-1); + LocalDate endDate2 = endDate.plusWeeks(-1); + + //前一周的数据 + List dataHarmPowerP2List; + List dataHarmPowerQ2List; + List dataHarmPowerU2List; + + try { + List objects = EasyExcelUtil.syncReadModel(is, CarryCapcityDataEexcel.class, 0, 3); + objects = objects.stream().filter(temp -> Objects.nonNull(temp.getTime())).collect(Collectors.toList()); + List iEexcelList = new ArrayList<>(); + List vEexcelList = new ArrayList<>(); + List pEexcelList = new ArrayList<>(); + List qEexcelList = new ArrayList<>(); + objects.forEach(temp -> { + CarryCapcityDataIEexcel carryCapcityDataiEexcel = new CarryCapcityDataIEexcel(); + CarryCapcityDataVEexcel carryCapcityDatavEexcel = new CarryCapcityDataVEexcel(); + CarryCapcityDataPEexcel carryCapcityDatapEexcel = new CarryCapcityDataPEexcel(); + CarryCapcityDataQEexcel carryCapcityDataqEexcel = new CarryCapcityDataQEexcel(); + + BeanUtils.copyProperties(temp, carryCapcityDataiEexcel); + carryCapcityDataiEexcel.setTime(temp.getTime().atZone(ZoneId.systemDefault()).toInstant()); + carryCapcityDataiEexcel.setValueType("CP95"); + + carryCapcityDatavEexcel.setTime(temp.getTime().atZone(ZoneId.systemDefault()).toInstant()); + carryCapcityDatavEexcel.setValueType("CP95"); + carryCapcityDatavEexcel.setValue_a(temp.getU_a()); + carryCapcityDatavEexcel.setValue_b(temp.getU_b()); + carryCapcityDatavEexcel.setValue_c(temp.getU_c()); + + + carryCapcityDatapEexcel.setTime(temp.getTime().atZone(ZoneId.systemDefault()).toInstant()); + carryCapcityDatapEexcel.setValueType("CP95"); + carryCapcityDatapEexcel.setValue_a(temp.getP_a()); + carryCapcityDatapEexcel.setValue_b(temp.getP_b()); + carryCapcityDatapEexcel.setValue_c(temp.getP_c()); + + carryCapcityDataqEexcel.setTime(temp.getTime().atZone(ZoneId.systemDefault()).toInstant()); + carryCapcityDataqEexcel.setValueType("CP95"); + carryCapcityDataqEexcel.setValue_a(temp.getQ_a()); + carryCapcityDataqEexcel.setValue_b(temp.getQ_b()); + carryCapcityDataqEexcel.setValue_c(temp.getQ_c()); + iEexcelList.add(carryCapcityDataiEexcel); + vEexcelList.add(carryCapcityDatavEexcel); + pEexcelList.add(carryCapcityDatapEexcel); + qEexcelList.add(carryCapcityDataqEexcel); + + }); + + + List collect = iEexcelList.stream().map(CarryCapcityDataIEexcel::excelToPO).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); + dataiList = collect.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate, endDate) + ).collect(Collectors.toList()); + + + // 校验合格的数据 + List collect2 = vEexcelList.stream().map(CarryCapcityDataVEexcel::excelToPO).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); + // 业务逻辑 + dataHarmPowerU2List = collect2.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate2, endDate2) + ).collect(Collectors.toList()); + + + // 校验合格的数据 + List collect3 = pEexcelList.stream().map(CarryCapcityDataPEexcel::excelToPO).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); + dataHarmPowerpList = collect3.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate, endDate) + ).collect(Collectors.toList()); + dataHarmPowerP2List = collect3.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate2, endDate2) + ).collect(Collectors.toList()); + + + List collect4 = qEexcelList.stream().map(CarryCapcityDataQEexcel::excelToPO).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList()); + dataHarmPowerqList = collect4.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate, endDate) + ).collect(Collectors.toList()); + dataHarmPowerQ2List = collect4.stream().filter( + item -> Utils.isTimeInRange(item.getTime(), startDate2, endDate2) + ).collect(Collectors.toList()); + + } catch (Exception e) { + throw new BusinessException(CarryCapacityResponseEnum.DOCUMENT_FORMAT_ERROR); + } + ExcelDataDTO dto = new ExcelDataDTO(); + dto.setDataHarmPowerPList(dataHarmPowerpList); + dto.setDataHarmPowerQList(dataHarmPowerqList); + dto.setDataIList(dataiList); + dto.setDataHarmPowerP2List(dataHarmPowerP2List); + dto.setDataHarmPowerQ2List(dataHarmPowerQ2List); + dto.setDataHarmPowerU2List(dataHarmPowerU2List); + + return dto; + } + + /** + * @Description: 首先,找到缺失值的前一个和后一个非缺失值。 + * 计算两个非缺失值之间的差值。 + * 将差值除以两个非缺失值之间的距离,得到斜率。 + * 使用斜率和前一个非缺失值计算缺失值的近似值。 + * @Param: + * @Author: clam + * @Date: 2024/2/28 + */ + public static void linearInterpolation(List data) { + + + data.stream().collect(Collectors.groupingBy(CarryCapcityData::getPhaseType)).forEach((k, v) -> { + + for (int i = 0; i < v.size(); i++) { + if (v.get(i).getValue() == DEFAULTVALUE || Objects.isNull(v.get(i).getValue())) { + int prevIndex = i - 1; + int nextIndex = i + 1; + while (prevIndex >= 0 && (v.get(prevIndex).getValue() == DEFAULTVALUE || Objects.isNull(v.get(prevIndex).getValue()))) { + prevIndex--; + } + while (nextIndex < v.size() && (v.get(nextIndex).getValue() == DEFAULTVALUE || Objects.isNull(v.get(nextIndex).getValue()))) { + nextIndex++; + } + if (prevIndex >= 0 && nextIndex < v.size()) { + double slope = (v.get(nextIndex).getValue() - v.get(prevIndex).getValue()) / (nextIndex - prevIndex); + v.get(i).setValue(v.get(prevIndex).getValue() + slope * (i - prevIndex)); + } else { + v.get(i).setValue(DEFAULTVALUE); + } + } + } + }); + + + } + + /** + * @Description: linearInterpolationI 电流数据缺失填补 + * @Param: + * @return: void + * @Author: clam + * @Date: 2024/2/28 + */ + public static void linearInterpolationI(List data) { + + data.stream().collect(Collectors.groupingBy(DataI::getPhaseType)).forEach((k, v) -> { + for (int i = 0; i < v.size(); i++) { + if (v.get(i).getI2() == DEFAULTVALUE || Objects.isNull(v.get(i).getI2())) { + int prevIndex = i - 1; + int nextIndex = i + 1; + while (prevIndex >= 0 && (v.get(prevIndex).getI2() == DEFAULTVALUE || Objects.isNull(v.get(prevIndex).getI2()))) { + prevIndex--; + } + while (nextIndex < v.size() && (v.get(nextIndex).getI2() == DEFAULTVALUE || Objects.isNull(v.get(nextIndex).getI2()))) { + nextIndex++; + } + if (prevIndex >= 0 && nextIndex < v.size()) { + double slope = (v.get(nextIndex).getI2() - v.get(prevIndex).getI2()) / (nextIndex - prevIndex); + v.get(i).setI2(v.get(prevIndex).getI2() + slope * (i - prevIndex)); + v.get(i).setI3(v.get(prevIndex).getI3() + slope * (i - prevIndex)); + v.get(i).setI4(v.get(prevIndex).getI4() + slope * (i - prevIndex)); + v.get(i).setI5(v.get(prevIndex).getI5() + slope * (i - prevIndex)); + v.get(i).setI6(v.get(prevIndex).getI6() + slope * (i - prevIndex)); + v.get(i).setI7(v.get(prevIndex).getI7() + slope * (i - prevIndex)); + v.get(i).setI8(v.get(prevIndex).getI8() + slope * (i - prevIndex)); + v.get(i).setI9(v.get(prevIndex).getI9() + slope * (i - prevIndex)); + v.get(i).setI10(v.get(prevIndex).getI10() + slope * (i - prevIndex)); + v.get(i).setI11(v.get(prevIndex).getI11() + slope * (i - prevIndex)); + v.get(i).setI12(v.get(prevIndex).getI12() + slope * (i - prevIndex)); + v.get(i).setI13(v.get(prevIndex).getI13() + slope * (i - prevIndex)); + v.get(i).setI14(v.get(prevIndex).getI14() + slope * (i - prevIndex)); + v.get(i).setI15(v.get(prevIndex).getI15() + slope * (i - prevIndex)); + v.get(i).setI16(v.get(prevIndex).getI16() + slope * (i - prevIndex)); + v.get(i).setI17(v.get(prevIndex).getI17() + slope * (i - prevIndex)); + v.get(i).setI18(v.get(prevIndex).getI18() + slope * (i - prevIndex)); + v.get(i).setI19(v.get(prevIndex).getI19() + slope * (i - prevIndex)); + v.get(i).setI20(v.get(prevIndex).getI20() + slope * (i - prevIndex)); + v.get(i).setI21(v.get(prevIndex).getI21() + slope * (i - prevIndex)); + v.get(i).setI22(v.get(prevIndex).getI22() + slope * (i - prevIndex)); + v.get(i).setI23(v.get(prevIndex).getI23() + slope * (i - prevIndex)); + v.get(i).setI24(v.get(prevIndex).getI24() + slope * (i - prevIndex)); + v.get(i).setI25(v.get(prevIndex).getI25() + slope * (i - prevIndex)); + + } else { + v.get(i).setI2(DEFAULTVALUE); + v.get(i).setI3(DEFAULTVALUE); + v.get(i).setI4(DEFAULTVALUE); + v.get(i).setI5(DEFAULTVALUE); + v.get(i).setI6(DEFAULTVALUE); + v.get(i).setI7(DEFAULTVALUE); + v.get(i).setI8(DEFAULTVALUE); + v.get(i).setI9(DEFAULTVALUE); + v.get(i).setI10(DEFAULTVALUE); + v.get(i).setI11(DEFAULTVALUE); + v.get(i).setI12(DEFAULTVALUE); + v.get(i).setI13(DEFAULTVALUE); + v.get(i).setI14(DEFAULTVALUE); + v.get(i).setI15(DEFAULTVALUE); + v.get(i).setI16(DEFAULTVALUE); + v.get(i).setI17(DEFAULTVALUE); + v.get(i).setI18(DEFAULTVALUE); + v.get(i).setI19(DEFAULTVALUE); + v.get(i).setI20(DEFAULTVALUE); + v.get(i).setI21(DEFAULTVALUE); + v.get(i).setI22(DEFAULTVALUE); + v.get(i).setI23(DEFAULTVALUE); + v.get(i).setI24(DEFAULTVALUE); + v.get(i).setI25(DEFAULTVALUE); + + } + } + } + }); + + + } + + /** + * @Description: calUParam 首端电压模型训练获取A,B,C三项C,a,b参数 + * @Param: + * @return: java.util.Map + * @Author: clam + * @Date: 2024/2/29 + */ + public static Map caluParam(List dataHarmPowerpList2, List dataHarmPowerqList2, List datavList2) { + Map results = new HashMap<>(4); + List phaseType = Stream.of("A", "B", "C").collect(Collectors.toList()); + + + phaseType.forEach(phase -> { + List listP2 = dataHarmPowerpList2.stream().filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getPhaseType().equals(phase)) + .map(CarryCapcityData::getValue) + .collect(Collectors.toList()); + + List listQ2 = dataHarmPowerqList2.stream().filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getPhaseType().equals(phase)) + .map(CarryCapcityData::getValue) + .collect(Collectors.toList()); + + List listV2 = datavList2.stream().filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getPhaseType().equals(phase)) + .map(CarryCapcityData::getValue) + .collect(Collectors.toList()); + //todo 抽取5000条数据(抽取方式待确定) + Double[] res = new Double[3]; + CarryCapacityUtil.cznlpgDataTrain(listV2, listP2, listQ2, listV2.size(), res); + results.put(phase, res); + + }); + + return results; + } + + private static boolean compareNumbers(int num1, int num2, String operator) { + if ("/".equals(operator)) { + return true; + } else if ("<".equals(operator)) { + return num1 < num2; + } else if (">".equals(operator)) { + return num1 > num2; + } else if ("<=".equals(operator)) { + return num1 <= num2; + } else if (">=".equals(operator)) { + return num1 >= num2; + } else if ("==".equals(operator)) { + return num1 == num2; + } else if ("!=".equals(operator)) { + return num1 != num2; + } else { + throw new IllegalArgumentException("无效的操作符"); + } + } + + private static boolean strategyReslut(List carryCapacityStrategyVOList, int resultLevel, int safeCount, int warnCount1, int warnCount2, int warnCount3) { + + CarryCapacityStrategyVO carryCapacityStrategyVO = carryCapacityStrategyVOList.stream() + .filter(temp -> temp.getResult() == resultLevel) + .collect(Collectors.toList()).get(0); + //每个策略组结果 + List list = new ArrayList<>(); + List capacityStrategysingleVOList = carryCapacityStrategyVO.getCapacityStrategysingleVOList(); + capacityStrategysingleVOList.forEach(temp -> { + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO carryCapacityStrategyIndexVO = temp.getCarryCapacityStrategyIndexVOList().stream() + .filter(temp1 -> temp1.getIndexResult() == 1) + .collect(Collectors.toList()).get(0); + boolean b1 = compareNumbers(safeCount, carryCapacityStrategyIndexVO.getCount(), carryCapacityStrategyIndexVO.getComparisonOperators()); + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO vo2 = temp.getCarryCapacityStrategyIndexVOList().stream() + .filter(temp1 -> temp1.getIndexResult() == 2) + .collect(Collectors.toList()).get(0); + boolean b2 = compareNumbers(warnCount3, vo2.getCount(), vo2.getComparisonOperators()); + + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO vo3 = temp.getCarryCapacityStrategyIndexVOList().stream() + .filter(temp1 -> temp1.getIndexResult() == 3) + .collect(Collectors.toList()).get(0); + boolean b3 = compareNumbers(warnCount2, vo3.getCount(), vo3.getComparisonOperators()); + + + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO vo4 = temp.getCarryCapacityStrategyIndexVOList().stream() + .filter(temp1 -> temp1.getIndexResult() == 4) + .collect(Collectors.toList()).get(0); + boolean b4 = compareNumbers(warnCount1, vo4.getCount(), vo4.getComparisonOperators()); + Boolean flag = b1 && b2 && b3 && b4; + list.add(flag); + }); + long count = list.stream().filter(temp -> temp).count(); + return count > 0; + } + + private static boolean checkData(List list, LocalDate startTime, LocalDate endTime, int timeInterval) { + boolean flag = false; + long daysBetween = ChronoUnit.DAYS.between(startTime, endTime); + //根据时间间隔算出最低数据量 1天*6小时*60分钟*90%/时间间隔算出一天一个的数据 + int minDataNum = 6 * 60 * 3 * 80 / (100 * timeInterval); + //合格天数》=3通过 + int days = 0; + + for (long i = 0; i <= daysBetween; i++) { + LocalDate currentDay = startTime.plusDays(i); + long count = list.stream() + .filter(temp -> Utils.isTimeInRange(temp.getTime(), LocalTime.of(9, 0), LocalTime.of(15, 0))) + .filter(temp -> temp.getValue() != DEFAULTVALUE && Objects.nonNull(temp.getValue())) + .filter(temp -> temp.getTime().atZone(ZoneId.systemDefault()).toLocalDate().equals(currentDay)).count(); + if (count >= minDataNum) { + days++; + } + + } + if (days >= 3) { + flag = true; + } + + return !flag; + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyDhlPOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyDhlPOServiceImpl.java new file mode 100644 index 0000000..00532ac --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyDhlPOServiceImpl.java @@ -0,0 +1,62 @@ +package com.njcn.product.carrycapacity.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.product.carrycapacity.mapper.CarryCapacityStrategyDhlPOMapper; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyDhlPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyDhlVO; +import com.njcn.product.carrycapacity.service.CarryCapacityStrategyDhlPOService; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * + * Description: + * Date: 2024/3/15 10:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class CarryCapacityStrategyDhlPOServiceImpl extends ServiceImpl implements CarryCapacityStrategyDhlPOService { + + + @Override + public List queyDetailDhl() { + List list = this.lambdaQuery().eq(CarryCapacityStrategyDhlPO::getUserFlag, 1).list(); + return list.stream().map(t -> { + CarryCapacityStrategyDhlVO vo = new CarryCapacityStrategyDhlVO(); + vo.setCount1(t.getCount1()); + vo.setCount2(t.getCount2()); + vo.setCount3(t.getCount3()); + vo.setCount4(t.getCount4()); + vo.setComparisonOperators1(t.getComparisonOperators1()); + vo.setComparisonOperators2(t.getComparisonOperators2()); + vo.setComparisonOperators3(t.getComparisonOperators3()); + vo.setComparisonOperators4(t.getComparisonOperators4()); + vo.setId(t.getId()); + vo.setProtoFlag(t.getProtoFlag()); + vo.setType(t.getType()); + return vo; + }).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean adddhl(CarryCapacityStrategyDhlVO capacityStrategyDhlVO) { + this.lambdaUpdate().eq(CarryCapacityStrategyDhlPO::getId, capacityStrategyDhlVO.getId()). + set(CarryCapacityStrategyDhlPO::getUserFlag, 2).update(); + CarryCapacityStrategyDhlPO carryCapacityStrategyDhlPO = new CarryCapacityStrategyDhlPO(); + BeanUtils.copyProperties(capacityStrategyDhlVO,carryCapacityStrategyDhlPO); + carryCapacityStrategyDhlPO.setId(null); + carryCapacityStrategyDhlPO.setUserFlag(1); + carryCapacityStrategyDhlPO.setProtoFlag(2); + boolean save = this.save(carryCapacityStrategyDhlPO); + return save; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyPOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyPOServiceImpl.java new file mode 100644 index 0000000..7fc76d4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityStrategyPOServiceImpl.java @@ -0,0 +1,139 @@ +package com.njcn.product.carrycapacity.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.carrycapacity.enums.CarryCapacityResponseEnum; +import com.njcn.product.carrycapacity.mapper.CarryCapacityStrategyDhlPOMapper; +import com.njcn.product.carrycapacity.mapper.CarryCapacityStrategyPOMapper; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityStrategyParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyDhlPO; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityStrategyPO; +import com.njcn.product.carrycapacity.pojo.vo.CarryCapacityStrategyVO; +import com.njcn.product.carrycapacity.service.CarryCapacityStrategyPOService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * + * Description: + * Date: 2024/3/5 10:33【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CarryCapacityStrategyPOServiceImpl extends ServiceImpl implements CarryCapacityStrategyPOService { + private final CarryCapacityStrategyDhlPOMapper carryCapacityStrategyDhlPOMapper; + @Override + @Transactional(rollbackFor = {Exception.class}) + public Boolean add(CarryCapacityStrategyParam carryCapacityStrategyParam) { + + CarryCapacityStrategyPO carryCapacityStrategy = new CarryCapacityStrategyPO(); + BeanUtils.copyProperties(carryCapacityStrategyParam, carryCapacityStrategy); + //将原始策略处理为不启用 + this.lambdaUpdate().eq(CarryCapacityStrategyPO::getResult, carryCapacityStrategyParam.getResult()) + .eq(CarryCapacityStrategyPO::getId, carryCapacityStrategyParam.getId()) + .eq(CarryCapacityStrategyPO::getIndexResult, carryCapacityStrategyParam.getIndexResult()) + .eq(CarryCapacityStrategyPO::getProtoFlag, 1) + .set(CarryCapacityStrategyPO::getUserFlag,2) + .update(); + QueryWrapper lambdaQuery = new QueryWrapper<>(); + lambdaQuery.lambda() + .eq(CarryCapacityStrategyPO::getResult, carryCapacityStrategyParam.getResult()) + .eq(CarryCapacityStrategyPO::getId, carryCapacityStrategyParam.getId()) + .eq(CarryCapacityStrategyPO::getIndexResult, carryCapacityStrategyParam.getIndexResult()) + .eq(CarryCapacityStrategyPO::getProtoFlag, 2); + //将客户对应策略删除 + this.remove(lambdaQuery); + //新增客户策略; + carryCapacityStrategy.setProtoFlag(2); + carryCapacityStrategy.setUserFlag(1); + return this.save(carryCapacityStrategy); + } + + @Override + public List queyDetail() { + List result = new ArrayList<>(); + List list = this.lambdaQuery().eq(CarryCapacityStrategyPO::getUserFlag, 1).list(); + Map>> collect = list.stream().collect(Collectors.groupingBy(CarryCapacityStrategyPO::getResult, + Collectors.groupingBy(CarryCapacityStrategyPO::getId))); + collect.forEach((key, value) -> { + CarryCapacityStrategyVO vo = new CarryCapacityStrategyVO(); + vo.setResult(key); + List capacityStrategysingleVOList =new ArrayList<>(); + value.forEach((k, v) -> { + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO vo1 = new CarryCapacityStrategyVO.CarryCapacityStrategysingleVO(); + vo1.setId(k); + vo1.setCarryCapacityStrategyIndexVOList(v.stream().map(temp -> { + CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO vo2 = new CarryCapacityStrategyVO.CarryCapacityStrategysingleVO.CarryCapacityStrategyIndexVO(); + BeanUtils.copyProperties(temp, vo2); + return vo2; + }).collect(Collectors.toList())); + capacityStrategysingleVOList.add(vo1); + }); + vo.setCapacityStrategysingleVOList(capacityStrategysingleVOList); + result.add(vo); + }); + + return result; + } + + @Override + public Boolean restore() { + //将客户对应策略删除 + QueryWrapper lambdaQuery = new QueryWrapper<>(); + lambdaQuery.lambda() + .eq(CarryCapacityStrategyPO::getProtoFlag, 2); + this.remove(lambdaQuery); + + //将原始策略处理为启用 + boolean update = this.lambdaUpdate().eq(CarryCapacityStrategyPO::getProtoFlag, 1) + .set(CarryCapacityStrategyPO::getUserFlag, 1) + .update(); + + //电弧炉初始化 + QueryWrapper lambdaQuery2 = new QueryWrapper<>(); + lambdaQuery2.lambda() + .eq(CarryCapacityStrategyDhlPO::getProtoFlag, 2); + carryCapacityStrategyDhlPOMapper.delete(lambdaQuery2); + UpdateWrapper lambdaQuery3 = new UpdateWrapper<>(); + lambdaQuery3.lambda() + .eq(CarryCapacityStrategyDhlPO::getProtoFlag, 1) + .set(CarryCapacityStrategyDhlPO::getUserFlag, 1); + + carryCapacityStrategyDhlPOMapper.update(null,lambdaQuery3); + + return update; + } + + @Override + public Boolean addList(List carryCapacityStrategyParamList) { + UUID uuid = UUID.randomUUID(); + if(4!=carryCapacityStrategyParamList.size()){ + throw new BusinessException(CarryCapacityResponseEnum.UNCOMPLETE_STRATEGY); + + } + List collect = carryCapacityStrategyParamList.stream().map(temp -> { + CarryCapacityStrategyPO po = new CarryCapacityStrategyPO(); + BeanUtils.copyProperties(temp, po); + po.setId(uuid.toString()); + //新增客户策略; + po.setProtoFlag(2); + po.setUserFlag(1); + return po; + }).collect(Collectors.toList()); + return this.saveBatch(collect); + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityUserPOServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityUserPOServiceImpl.java new file mode 100644 index 0000000..5b5804b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/service/impl/CarryCapacityUserPOServiceImpl.java @@ -0,0 +1,123 @@ +package com.njcn.product.carrycapacity.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +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.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.auth.pojo.vo.UserVO; +import com.njcn.product.auth.service.IUserService; +import com.njcn.product.carrycapacity.enums.CarryCapacityResponseEnum; +import com.njcn.product.carrycapacity.mapper.CarryCapacityUserPOMapper; +import com.njcn.product.carrycapacity.pojo.param.CarryCapacityUserParam; +import com.njcn.product.carrycapacity.pojo.po.CarryCapacityUserPO; +import com.njcn.product.carrycapacity.service.CarryCapacityUserPOService; +import com.njcn.product.carrycapacity.util.CheckStringUtil; + +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Objects; + +/** + * + * Description: + * Date: 2024/2/20 11:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CarryCapacityUserPOServiceImpl extends ServiceImpl implements CarryCapacityUserPOService { + private final IUserService userService; + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean add(CarryCapacityUserParam carryCapacityUserParam) { + if(StringUtils.isBlank(carryCapacityUserParam.getUserName())){ + throw new BusinessException("用户称不能为空"); + } + checkName(carryCapacityUserParam,false); + CarryCapacityUserPO carryCapacityUser = new CarryCapacityUserPO(); + BeanUtils.copyProperties(carryCapacityUserParam, carryCapacityUser); + carryCapacityUser.setStatus(1); + return this.save(carryCapacityUser); + } + /** + * 检查名称是否已存在 + * + * @return 结果 + */ + private void checkName(CarryCapacityUserParam carryCapacityUserParam, boolean isUpdate) { + if(carryCapacityUserParam.getUserName().length()>32){ + throw new BusinessException("超过最大长度"); + + } + CheckStringUtil.checkName(carryCapacityUserParam.getUserName()); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + //条件组合:where state = 1 and name = ? + lambdaQueryWrapper.eq(CarryCapacityUserPO::getStatus, DataStateEnum.ENABLE.getCode()).eq(CarryCapacityUserPO::getUserName, carryCapacityUserParam.getUserName()); + + //and id <> ? + if (isUpdate) { + if (carryCapacityUserParam instanceof CarryCapacityUserParam.CarryCapacityUserUpdateParam) { + lambdaQueryWrapper.ne(CarryCapacityUserPO::getUserId, ((CarryCapacityUserParam.CarryCapacityUserUpdateParam) carryCapacityUserParam).getUserId()); + } + } + + //若存在条件数据抛出异常 + int count = this.getBaseMapper().selectCount(lambdaQueryWrapper); + if (count > 0) { + throw new BusinessException(CarryCapacityResponseEnum.USER_NAME_EXIST); + } + + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean updateUser(CarryCapacityUserParam.CarryCapacityUserUpdateParam userUpdateParam) { + if(StringUtils.isBlank(userUpdateParam.getUserName())){ + throw new BusinessException("用户称不能为空"); + } + checkName(userUpdateParam,true); + CarryCapacityUserPO carryCapacityUser = new CarryCapacityUserPO(); + BeanUtils.copyProperties(userUpdateParam, carryCapacityUser); + + + return this.updateById(carryCapacityUser); + } + + @Override + public IPage queyDetailUser(CarryCapacityUserParam.CarryCapacityUserPageParam pageParm) { + Page returnpage = new Page<> (pageParm.getPageNum ( ), pageParm.getPageSize ( )); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().eq(CarryCapacityUserPO::getStatus,1) + .eq(StringUtils.isNotBlank(pageParm.getUserId()) ,CarryCapacityUserPO::getUserId,pageParm.getUserId()) + .eq(StringUtils.isNotBlank(pageParm.getVoltage()) ,CarryCapacityUserPO::getVoltage,pageParm.getVoltage()) + .eq(StringUtils.isNotBlank(pageParm.getUserType()) ,CarryCapacityUserPO::getUserType,pageParm.getUserType()) + .in(CollectionUtil.isNotEmpty(pageParm.getUserTypeList()) ,CarryCapacityUserPO::getUserType,pageParm.getUserTypeList()) + .between(StringUtils.isNotBlank(pageParm.getStartTime()) && StringUtils.isNotBlank(pageParm.getEndTime()) ,CarryCapacityUserPO::getCreateTime,pageParm.getStartTime()+" 00:00:00",pageParm.getEndTime()+" 23:59:59"). + orderByDesc(CarryCapacityUserPO::getCreateTime); + + IPage page = this.page (returnpage, queryWrapper); + page.getRecords().forEach(temp->{ + UserVO user = userService.getUserById(temp.getCreateBy()); + + temp.setCreateBy(Objects.isNull(user)? LogInfo.UNKNOWN_USER:user.getName()); + }); + return page; + } + + @Override + public CarryCapacityUserPO queyDetailUserById(String userId) { + return this.lambdaQuery().eq(CarryCapacityUserPO::getUserId,userId).one(); + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CarryCapacityUtil.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CarryCapacityUtil.java new file mode 100644 index 0000000..7df40ba --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CarryCapacityUtil.java @@ -0,0 +1,323 @@ +package com.njcn.product.carrycapacity.util; + +import com.njcn.common.pojo.exception.BusinessException; +import org.apache.commons.math3.linear.DecompositionSolver; +import org.apache.commons.math3.linear.LUDecomposition; +import org.apache.commons.math3.linear.MatrixUtils; +import org.apache.commons.math3.linear.RealMatrix; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +public class CarryCapacityUtil { + + private static final String DATA_CSV = "C:\\njcn\\pqs\\pqs-advance\\advance-boot\\src\\main\\resources\\test.csv"; + private static final int MAX_PRO_DATA_NUM = 5000; + private static final int MAX_DATA_COL_NUM = 9; + private static double[][] arr = new double[MAX_PRO_DATA_NUM][MAX_DATA_COL_NUM]; + + public static void main(String[] args) { + double[] data_u = new double[MAX_PRO_DATA_NUM]; + double[] data_p = new double[MAX_PRO_DATA_NUM]; + double[] data_q = new double[MAX_PRO_DATA_NUM]; + + int data_num = parseCSV(DATA_CSV, data_u, data_p, data_q); + System.out.println("data_num: " + data_num); + + double[] res = new double[3]; +// cznlpgDataTrain(data_u, data_p, data_q, data_num, res); + System.out.println("C = " + res[0] + " a = " + res[1] + " b = " + res[2]); + } + + private static int parseCSV(String path, double[] data_u, double[] data_p, double[] data_q) { + int line = 0; + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + String lines; + while ((lines = br.readLine()) != null) { + String[] tokens = lines.split(","); + for (int i = 0; i < tokens.length; i++) { + arr[line][i] = Double.parseDouble(tokens[i]); + } + + System.out.println("line " + line + ": "); + for (int i = 0; i < tokens.length; i++) { + System.out.println("arr[" + line + "][" + i + "]=" + arr[line][i]); + } + + data_u[line] = arr[line][0]; + data_p[line] = arr[line][1]; + data_q[line] = arr[line][2]; + + line++; + } + } catch (IOException e) { + e.printStackTrace(); + } + return line; + } + /* + * 模型训练 + * */ + public static void cznlpgDataTrain(List u, List p, List q, int num, Double[] outRes) { + if (num > MAX_PRO_DATA_NUM) { + return; + } + + RealMatrix matPQ = MatrixUtils.createRealMatrix(num, 3); + RealMatrix matU = MatrixUtils.createRealMatrix(num, 1); + RealMatrix matW = MatrixUtils.createRealMatrix(3, 1); + + // Matrix assignment + for (int i = 0; i < num; i++) { + matPQ.setEntry(i, 0, 1); + matPQ.setEntry(i, 1, p.get(i)); + matPQ.setEntry(i, 2, q.get(i)); + + matU.setEntry(i, 0, u.get(i)); + } + +// System.out.println("matPQ="); + printMatrix(matPQ); +// System.out.println("matPQ transpose="); + printMatrix(matPQ.transpose()); + + // w = inv(PQ1'*PQ1)*PQ1'*U + // U = 224.5133 - 2.3041e-5 * P - 1.1900e-4 * Q + RealMatrix matPQT = matPQ.transpose(); + RealMatrix matInverse = inverseMatrix(matPQT.multiply(matPQ)); + matW = matInverse.multiply(matPQT).multiply(matU); + + outRes[0] = matW.getEntry(0, 0); + outRes[1] = matW.getEntry(1, 0); + outRes[2] = matW.getEntry(2, 0); + } + + private static void printMatrix(RealMatrix matrix) { + System.out.println(matrix); + } + + + //矩阵求逆 + + public static RealMatrix inverseMatrix(RealMatrix matrix) { + try { + LUDecomposition LUDe = new LUDecomposition(matrix); + DecompositionSolver solver = LUDe.getSolver(); + RealMatrix result = solver.getInverse(); + return result; + }catch (Exception e){ + System.out.println("数据存在问题无法进行矩阵求逆"); + throw new BusinessException("数据存在问题无法进行矩阵求逆"); + } + + + } + + /** + * @Description: 负载率约束指标计算P_βmin和Q_βmin分别为近一周的配变每日9时~15时段的负载率数据中概率95%小值所对应时刻的有功功率和无功功率值; + * S_T为配变额定容量;S_pv为拟接入光伏容量;k为修正系数 ,取值可参照如下。 + * 台区日照条件 k + * 光照强度大于1250kWh/m^2 0.8~0.9 + * 光照强度小于1250kWh/m^2 0.75~0.8 + * 海南 0.8 + * @Param: + * @return: double Loadrate + * @Author: clam + * @Date: 2024/1/26 + */ + public static double calculateB(double P_βmin, double Q_βmin, double k, double S_T, double S_pv, double P_pv) { + double term1 = Math.pow(P_βmin - k * S_T, 2); + double term2 = Math.pow(Q_βmin, 2); + double numerator = Math.sqrt(term1 + term2); + if (P_βmin > P_pv) { + return numerator / S_pv; + } else { + return -numerator / S_pv; + } + + } + /** + * @Description: calculatePF_T 功率因数指标计算 + * @Param: + * @return: double + * @Author: clam + * @Date: 2024/2/20 + */ + public static double calculatePF_T(double P_βmin, double Q_βmin, double k, double S_pv) { + double term1 = Math.pow(P_βmin - k * S_pv, 2); + double term2 = Math.pow(Q_βmin, 2); + double v = P_βmin - k * S_pv; + double numerator = Math.sqrt(term1 + term2); + + return v/numerator; + + } + + /** + * @Description: 总结: + * p_min和 q_min能够根据测点数据获取得到; + * S_pv为拟接入光伏容量,此部分需要现场选取好台区后获取。 + * k为修正系数,徐工提供海南k系数,是否需要考虑不同季节台区日照系数。 + * C、a、b需要用模型计算,是此算法中难点。 + * 结论:【拟接入光伏容量】为入参;【A/B/C相有功功率】和【A/B/C相无功功率值】95%小值从A/B/C相历史数据中计算得出; 为枚举参数;能够计算三相配变首端电压 、 、 ,从而得出U 。 + * 380v -U=C-a(p_min -k*S_pv/3)-b*q_min + * 220v -U=C-a(p_min -k*S_pv)-b*q_min + *(后续咨询只分单项三项,目前数据都是三项) + * @Param: + * @return: double + * @Author: clam + * @Date: 2024/2/2 + */ + public static double calculateU(double C, double a, double b, double p_min, double K, double q_min,double S_pv, double voltage) { + +// if (voltage == 220) { +// return C-a*(p_min-K*S_pv)-b*q_min; +// } else if (voltage == 380) { + return C-a*(p_min-K*S_pv/3)-b*q_min; +// } else { +// return 0; +// } + + } + + /** + * I_(stock,h)为台区一周内的h次谐波电流95%概率大值,I_"inv" ^h%为光伏逆变器第h次的典型谐波电流含有率; + * S_pv为拟接入光伏容量,此部分需要现场选取好台区后获取。 + * k为修正系数,徐工提供海南k系数,是否需要考虑不同季节台区日照系数。 + * 结论:【电压等级】为入参;I_(stock,h)为台区一周内的h次谐波电流95%概率大值,I_"inv" ^h%为光伏逆变器第h次的典型谐波电流含有率, + * 为枚举参数;k为枚举参数;能够计算各次的谐波电流幅值 、 、 ,从而得出 。 + * (后续咨询只分单项三项,目前数据都是三项) + */ + public static double calculateITm(double I_cp95, double k, double voltage, double S_pv, double K, double I_inv) { + double term1 = Math.pow(I_cp95, 2); + double term2 = 0, term3 = 0; +// if (voltage == 220) { +// term2 = Math.pow(k * S_pv * I_inv / 220, 2); +// term3 = K * I_cp95 * (k * S_pv * I_inv / 220); +// } else if (voltage == 380) { + term2 = Math.pow(k * S_pv * I_inv /(3 * 220) , 2); + term3 = K * I_cp95 * (k * S_pv * I_inv / (3 * 220)); +// } else { +// return 0; +// } + + double sumOfTerms = term1 + term2 + term3; + + return Math.sqrt(sumOfTerms); + } + + /** + * @Description: evaluateVoltageLevel 根据规则评估配变首端电压等级 + * @Param: + * @return: int + * @Author: clam + * @Date: 2024/1/30 + */ + public static int evaluateVoltageLevel(double voltage) { + if (voltage <= 235.4) { + return 1; // 安全 + } else if (voltage > 235.4 && voltage <= 253.0) { + return 2; // Ⅲ级预警 + } else if (voltage > 253.0 && voltage < 260.0) { + return 3; // Ⅱ级预警 + } else { + return 4; // Ⅰ级预警 + } + } + + /** + * @Description: evaluatePowerFactorLevel // 根据规则评估功率因数等级 + * @Param: + * @return: int + * @Author: clam + * @Date: 2024/1/30 + */ + public static int evaluatePowerFactorLevel(double powerFactor) { + if (powerFactor >= 0.9) { + return 1; // 安全 + } else if (powerFactor >= 0.85 && powerFactor < 0.9) { + return 2; // Ⅲ级预警 + } else if (powerFactor >= 0.8 && powerFactor < 0.85) { + return 3; // Ⅱ级预警 + } else { + return 4; // Ⅰ级预警 + } + } + + /** + * @Description: / 根据规则评估等效负载率等级 + * @Param: + * @return: int + * @Author: clam + * @Date: 2024/1/30 + */ + public static int evaluateEquivalentLoadRateLevel(double equivalentLoadRate) { + if (equivalentLoadRate >= 0.0) { + return 1; // 安全 + } else if (equivalentLoadRate >= -40.0 && equivalentLoadRate < 0.0) { + return 2; // Ⅲ级预警 + } else if (equivalentLoadRate >= -80.0 && equivalentLoadRate < -40.0) { + return 3; // Ⅱ级预警 + } else { + return 4; // Ⅰ级预警 + } + } + + /** + * @Description: 判断O:各项指标是否均为“安全” 安全接入 + * 判断2: 至多2项指标达到“III级预警”,其余指标均为“安全” 3接入预警 + * @: 超过2项指标达到“III级预警”且无“II级预警”及以上的指标:或至多1项指标达到“I 级预警且其余指标均为“安全” 2接入预警 + * 判断@: 至多2项指标达到“II 级预警”且其余指标均为“安全”: 或至多1项指标达到“II级预警”且其余指标存在“III级预警” 1级接入预警 + * 否则 限制接入 + * @Param: + * @return: + * @Author: clam + * @Date: 2024/1/30 + */ + public static int evaluateG(List indicators) { + long count1 = indicators.stream().filter(i -> i == 1).count(); + long count2 = indicators.stream().filter(i -> i == 2).count(); + long count3 = indicators.stream().filter(i -> i == 3).count(); + if (count1 == 4) { + return 1; + } else if (count2 <= 2 && count2 + count1 == 4) { + return 2; + } else if ((count2 >= 2 && count2 + count1 == 4) || (count3 == 1 && count1 == 3)) { + return 3; + } else if ((count3 <= 2 && count1 + count3 == 4) || (count3 == 1 && count2 >= 1 && count1 + count2 == 3)) { + return 4; + } else { + return 5; + } + } + + /** + * 计算一组数据的最大95概率值,最小95概率值 入参一组double集合,一个flag表示计算类型 返回double + * + * @param data + * @param type 0 最大95概率值 1 最小95概率值 + * @return + */ + public static double calculatePercentile(List data, Integer type) { + // 对数组进行排序 + // 正序排序 + Collections.sort(data); + int index =0; + if (type == 0) { + // 计算最大95%概率值的索引 + index =(int) Math.ceil(0.95 * data.size()) ; + } else if (type == 1) { + // 计算最小95%概率值的索引 + index = (int) Math.ceil(0.05 * data.size()) - 1; + } + + // 根据计算类型返回相应的值 + return data.get(index); + } + + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CheckStringUtil.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CheckStringUtil.java new file mode 100644 index 0000000..e8ba768 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/CheckStringUtil.java @@ -0,0 +1,29 @@ +package com.njcn.product.carrycapacity.util; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.web.constant.ValidMessage; + +import java.util.regex.Pattern; + +/** + * Description: + * Date: 2024/12/10 14:51【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public class CheckStringUtil { + public static void checkName(String name) { + String SPECIALCHARACTER ="[<>%'%;()&+/\\\\-\\\\\\\\_|@*?#$!,.]|html"; + Pattern pattern = Pattern.compile(SPECIALCHARACTER); + if(pattern.matcher(name).find()){ + throw new BusinessException(ValidMessage.NAME_SPECIAL_REGEX); + } + } + +// public static void main(String[] args) { +// checkName("100迈岭站2djvjva13ad"); +// } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelDefaultListener.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelDefaultListener.java new file mode 100644 index 0000000..34a0858 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelDefaultListener.java @@ -0,0 +1,88 @@ +package com.njcn.product.carrycapacity.util; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; +import com.alibaba.excel.exception.ExcelDataConvertException; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Description: + * Date: 2024/3/15 16:02【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Slf4j +public abstract class EasyExcelDefaultListener extends AnalysisEventListener { + + /** + * 批处理阈值 + */ + private static final int BATCH_COUNT = 20; + + /** + * 用来存放待处理的数据 + */ + @Getter + private List list = new ArrayList<>(BATCH_COUNT); + + /** + * 读取excel数据前操作
+ * + * 只有不读取表头数据时才会触发此方法) + */ + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + log.info("======================================================"); + log.info("======================================================"); + } + + /** + * 读取excel数据操作 + * @param obj + * @param context + */ + @Override + public void invoke(T obj, AnalysisContext context) { + list.add(obj); + + if (list.size() >= BATCH_COUNT) { + //将数据保存到数据库中 + fun(list); + list.clear(); + } + } + + /** + * 具体业务 + */ + protected abstract void fun(List list); + + /** + * 读取完excel数据后的操作 + */ + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + if (list.size() > 0) { + fun(list); + } + } + + /** + * 在读取excel异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。 + */ + @Override + public void onException(Exception exception, AnalysisContext context) { + log.error("解析失败,但是继续解析下一行:{}", exception.getMessage()); + if (exception instanceof ExcelDataConvertException) { + ExcelDataConvertException ex = (ExcelDataConvertException) exception; + log.error("第{}行,第{}列解析异常,数据为:{}", ex.getRowIndex(), ex.getColumnIndex(), ex.getCellData()); + } + } +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelUtil.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelUtil.java new file mode 100644 index 0000000..1d77ac8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelUtil.java @@ -0,0 +1,428 @@ +package com.njcn.product.carrycapacity.util; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.EasyExcelFactory; +import com.alibaba.excel.event.AnalysisEventListener; +import com.alibaba.excel.write.handler.WriteHandler; +import lombok.SneakyThrows; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URLEncoder; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Description: + * Date: 2024/3/15 15:58【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public class EasyExcelUtil { + + //====================================================无JAVA模型读取excel数据=============================================================== + + /** + * 同步无模型读(默认读取sheet0,从第2行开始读) + * @param file excel文件的绝对路径 + */ + public static List> syncRead(String file) { + return EasyExcelFactory.read(file).sheet().doReadSync(); + } + + /** + * 同步无模型读(自定义读取sheetX,从第2行开始读) + * @param file excel文件的绝对路径 + * @param sheetNum sheet页号,从0开始 + */ + public static List> syncRead(String file, Integer sheetNum) { + return EasyExcelFactory.read(file).sheet(sheetNum).doReadSync(); + } + + /** + * 同步无模型读(指定sheet和表头占的行数) + * @param file + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static List> syncRead(String file, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(file).sheet(sheetNum).headRowNumber(headNum).doReadSync(); + } + + /** + * 同步无模型读(指定sheet和表头占的行数) + * @param inputStream + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static List> syncRead(InputStream inputStream, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(inputStream).sheet(sheetNum).headRowNumber(headNum).doReadSync(); + } + + /** + * 同步无模型读(指定sheet和表头占的行数) + * @param file + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static List> syncRead(File file, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(file).sheet(sheetNum).headRowNumber(headNum).doReadSync(); + } + //====================================================无JAVA模型读取excel数据=============================================================== + + //====================================================将excel数据同步到JAVA模型属性里=============================================================== + + /** + * 同步按模型读(默认读取sheet0,不读取表头,从第2行开始读) + * @param file + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + */ + public static List syncReadModel(String file, Class clazz) { + return EasyExcelFactory.read(file).sheet().head(clazz).doReadSync(); + } + + /** + * 同步按模型读(默认表头占一行,不读取表头,从第2行开始读) + * @param file + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static List syncReadModel(String file, Class clazz, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(file).sheet(sheetNum).headRowNumber(headNum).head(clazz).doReadSync(); + } + + /** + * 同步按模型读(指定sheet,不读取表头) + * @param inputStream + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static List syncReadModel(InputStream inputStream, Class clazz, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(inputStream).sheet(sheetNum).headRowNumber(headNum).head(clazz).doReadSync(); + } + + /** + * 同步按模型读(指定sheet,不读取表头) + * @param file + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static List syncReadModel(File file, Class clazz, Integer sheetNum, Integer headNum) { + return EasyExcelFactory.read(file).sheet(sheetNum).headRowNumber(headNum).head(clazz).doReadSync(); + } + //====================================================将excel数据同步到JAVA模型属性里=============================================================== + + //====================================================异步读取excel数据=============================================================== + + /** + * 异步无模型读(默认读取sheet0,不读取表头,从第2行开始读) + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param file 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static void asyncRead(String file, AnalysisEventListener listener) { + EasyExcelFactory.read(file, listener).sheet().doRead(); + } + + /** + * 异步无模型读(默认表头占一行,不读取表头,从第2行开始读) + * @param file 表头占的行数,从0开始(如果要连表头一起读出来则传0) + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param sheetNum sheet页号,从0开始 + */ + public static void asyncRead(String file, AnalysisEventListener listener, Integer sheetNum) { + EasyExcelFactory.read(file, listener).sheet(sheetNum).doRead(); + } + + /** + * 异步无模型读(指定sheet和表头占的行数) + * @param inputStream + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static void asyncRead(InputStream inputStream, AnalysisEventListener listener, Integer sheetNum, Integer headNum) { + EasyExcelFactory.read(inputStream, listener).sheet(sheetNum).headRowNumber(headNum).doRead(); + } + + /** + * 异步无模型读(指定sheet和表头占的行数) + * @param file + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + */ + public static void asyncRead(File file, AnalysisEventListener listener, Integer sheetNum, Integer headNum) { + EasyExcelFactory.read(file, listener).sheet(sheetNum).headRowNumber(headNum).doRead(); + } + + /** + * 异步无模型读(指定sheet和表头占的行数) + * @param file + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param sheetNum sheet页号,从0开始 + * @param headNum 表头占的行数,从0开始(如果要连表头一起读出来则传0) + * @return + */ + public static void asyncRead(String file, AnalysisEventListener listener, Integer sheetNum, Integer headNum) { + EasyExcelFactory.read(file, listener).sheet(sheetNum).headRowNumber(headNum).doRead(); + } + //====================================================异步读取excel数据=============================================================== + + //====================================================将excel数据异步到JAVA模型属性里=============================================================== + /** + * 异步按模型读取(默认读取sheet0,不读取表头,从第2行开始读) + * @param file + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + */ + public static void asyncReadModel(String file, AnalysisEventListener listener, Class clazz) { + EasyExcelFactory.read(file, clazz, listener).sheet().doRead(); + } + + /** + * 异步按模型读取(默认表头占一行,不读取表头,从第2行开始读) + * @param file + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static void asyncReadModel(String file, AnalysisEventListener listener, Class clazz, Integer sheetNum) { + EasyExcelFactory.read(file, clazz, listener).sheet(sheetNum).doRead(); + } + + /** + * 异步按模型读取 + * @param file + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static void asyncReadModel(File file, AnalysisEventListener listener, Class clazz, Integer sheetNum) { + EasyExcelFactory.read(file, clazz, listener).sheet(sheetNum).doRead(); + } + + /** + * 异步按模型读取 + * @param inputStream + * @param listener 监听器,在监听器中可以处理行数据LinkedHashMap,表头数据,异常处理等 + * @param clazz 模型的类类型(excel数据会按该类型转换成对象) + * @param sheetNum sheet页号,从0开始 + */ + public static void asyncReadModel(InputStream inputStream, AnalysisEventListener listener, Class clazz, Integer sheetNum) { + EasyExcelFactory.read(inputStream, clazz, listener).sheet(sheetNum).doRead(); + } + //====================================================将excel数据异步到JAVA模型属性里=============================================================== + + + //====================================================无JAVA模型写文件=============================================================== + /** + * 无模板写文件 + * @param file + * @param head 表头数据 + * @param data 表内容数据 + */ + public static void write(String file, List> head, List> data) { + EasyExcel.write(file).head(head).sheet().doWrite(data); + } + + /** + * 无模板写文件 + * @param file + * @param head 表头数据 + * @param data 表内容数据 + * @param sheetNum sheet页号,从0开始 + * @param sheetName sheet名称 + */ + public static void write(String file, List> head, List> data, Integer sheetNum, String sheetName) { + EasyExcel.write(file).head(head).sheet(sheetNum, sheetName).doWrite(data); + } + //====================================================无JAVA模型写文件=============================================================== + + //====================================================有Excel模板写文件=============================================================== + /** + * 根据excel模板文件写入文件,可以实现向已有文件中添加数据的功能 + * @param file + * @param template + * @param data + */ + public static void writeTemplate(String file, String template, List data) { + EasyExcel.write(file).withTemplate(template).sheet().doWrite(data); + } + + /** + * 根据excel模板文件写入文件 + * @param file + * @param template + * @param clazz + * @param data + */ + public static void writeTemplate(String file, String template, Class clazz, List data) { + EasyExcel.write(file, clazz).withTemplate(template).sheet().doWrite(data); + } + + + + //====================================================无模板写文件=============================================================== + + //====================================================有模板写文件=============================================================== + /** + * 按模板写文件 + * @param file + * @param clazz 表头模板 + * @param data 数据 + */ + public static void write(String file, Class clazz, List data) { + EasyExcel.write(file, clazz).sheet().doWrite(data); + } + + /** + * 按模板写文件 + * @param file + * @param clazz 表头模板 + * @param data 数据 + * @param sheetNum sheet页号,从0开始 + * @param sheetName sheet名称 + */ + public static void write(String file, Class clazz, List data, Integer sheetNum, String sheetName) { + EasyExcel.write(file, clazz).sheet(sheetNum, sheetName).doWrite(data); + } + + /** + * 按模板写文件 + * @param file + * @param clazz 表头模板 + * @param data 数据 + * @param writeHandler 自定义的处理器,比如设置table样式,设置超链接、单元格下拉框等等功能都可以通过这个实现(需要注册多个则自己通过链式去调用) + * @param sheetNum sheet页号,从0开始 + * @param sheetName sheet名称 + */ + public static void write(String file, Class clazz, List data, WriteHandler writeHandler, Integer sheetNum, String sheetName) { + EasyExcel.write(file, clazz).registerWriteHandler(writeHandler).sheet(sheetNum, sheetName).doWrite(data); + } + + /** + * 按模板写文件(包含某些字段) + * @param file + * @param clazz 表头模板 + * @param data 数据 + * @param includeCols 包含字段集合,根据字段名称显示 + * @param sheetNum sheet页号,从0开始 + * @param sheetName sheet名称 + */ + public static void writeInclude(String file, Class clazz, List data, Set includeCols, Integer sheetNum, String sheetName) { + EasyExcel.write(file, clazz).includeColumnFiledNames(includeCols).sheet(sheetNum, sheetName).doWrite(data); + } + + /** + * 按模板写文件(排除某些字段) + * @param file + * @param clazz 表头模板 + * @param data 数据 + * @param excludeCols 过滤排除的字段,根据字段名称过滤 + * @param sheetNum sheet页号,从0开始 + * @param sheetName sheet名称 + */ + public static void writeExclude(String file, Class clazz, List data, Set excludeCols, Integer sheetNum, String sheetName) { + EasyExcel.write(file, clazz).excludeColumnFiledNames(excludeCols).sheet(sheetNum, sheetName).doWrite(data); + } + + //------------------------------------------------------------------------------------------------ + /** + * 多个sheet页的数据链式写入 + * + * @param file + */ + public static EasyExcelWriteTool writeWithSheets(String file) { + return new EasyExcelWriteTool(file); + } + + /** + * 多个sheet页的数据链式写入 + * + * @param file + */ + public static EasyExcelWriteTool writeWithSheets(File file) { + return new EasyExcelWriteTool(file); + } + + /** + * 多个sheet页的数据链式写入 + * + * @param outputStream + */ + public static EasyExcelWriteTool writeWithSheets(OutputStream outputStream) { + return new EasyExcelWriteTool(outputStream); + } + + /** + * 多个sheet页的数据链式写入(失败了会返回一个有部分数据的Excel) + * + * @param response + * @param exportFileName 导出的文件名称 + */ + @SneakyThrows + public static EasyExcelWriteTool writeWithSheetsWeb(HttpServletResponse response, String exportFileName) throws IOException { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + + // 这里URLEncoder.encode可以防止中文乱码 + String fileName = URLEncoder.encode(exportFileName, "UTF-8"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + return new EasyExcelWriteTool(response.getOutputStream()); + } + + public static void main(String[] args) { + List> maps = EasyExcelUtil.syncRead("C:\\Users\\无名\\Desktop\\excel\\工作表.xlsx"); + + System.out.println(maps); + List> maps1 = maps.subList(2, 51); + List> maps2 = maps.subList(51, 52); + List> maps3 = maps.subList(55, 104); + List> maps4 = maps.subList(104, 105); + List iMax = maps1.stream().map(temp -> { + double a = Double.valueOf(temp.get(5)); + double b = Double.valueOf(temp.get(10)); + double c = Double.valueOf(temp.get(15)); + double v = a > b ? a : b; + double max = v > c ? v : c; + return max; + + }).collect(Collectors.toList()); + Double iNeg = maps2.stream().map(temp -> { + double a = Double.valueOf(temp.get(5)); + double b = Double.valueOf(temp.get(10)); + double c = Double.valueOf(temp.get(15)); + double v = a > b ? a : b; + double max = v > c ? v : c; + return max; + + }).findFirst().get(); + + List uMax = maps3.stream().map(temp -> { + double a = Double.valueOf(temp.get(5)); + double b = Double.valueOf(temp.get(10)); + double c = Double.valueOf(temp.get(15)); + double v = a > b ? a : b; + double max = v > c ? v : c; + return max; + + }).collect(Collectors.toList()); + + Double unbalance = maps2.stream().map(temp -> { + double a = Double.valueOf(temp.get(5)); + double b = Double.valueOf(temp.get(10)); + double c = Double.valueOf(temp.get(15)); + double v = a > b ? a : b; + double max = v > c ? v : c; + return max; + + }).findFirst().get(); + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelWriteTool.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelWriteTool.java new file mode 100644 index 0000000..e746ce0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/EasyExcelWriteTool.java @@ -0,0 +1,68 @@ +package com.njcn.product.carrycapacity.util; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.write.metadata.WriteSheet; +import org.apache.poi.ss.formula.functions.T; + +import java.io.File; +import java.io.OutputStream; +import java.util.List; + +/** + * Description: + * Date: 2024/3/15 16:00【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public class EasyExcelWriteTool { + + private int sheetNum; + private ExcelWriter excelWriter; + + public EasyExcelWriteTool(OutputStream outputStream) { + excelWriter = EasyExcel.write(outputStream).build(); + } + + public EasyExcelWriteTool(File file) { + excelWriter = EasyExcel.write(file).build(); + } + + public EasyExcelWriteTool(String filePath) { + excelWriter = EasyExcel.write(filePath).build(); + } + + /** + * 链式模板表头写入 + * @param clazz 表头格式 + * @param data 数据 List 或者List> + * @return + */ + public EasyExcelWriteTool writeModel(Class clazz, List data, String sheetName) { + final WriteSheet writeSheet = EasyExcel.writerSheet(this.sheetNum++, sheetName).head(clazz).build(); + excelWriter.write(data, writeSheet); + return this; + } + + /** + * 链式自定义表头写入 + * @param head + * @param data 数据 List 或者List> + * @param sheetName + * @return + */ + public EasyExcelWriteTool write(List> head, List data, String sheetName) { + final WriteSheet writeSheet = EasyExcel.writerSheet(this.sheetNum++, sheetName).head(head).build(); + excelWriter.write(data, writeSheet); + return this; + } + + /** + * 使用此类结束后,一定要关闭流 + */ + public void finish() { + excelWriter.finish(); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/FileUtils.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/FileUtils.java new file mode 100644 index 0000000..4b84de7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/FileUtils.java @@ -0,0 +1,83 @@ +package com.njcn.product.carrycapacity.util; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.UUID; + +/** + * Description: + * Date: 2025/07/09 下午 3:14【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Component +public class FileUtils { + @Value("${file.upload-dir}") + private String baseDir; // 从配置文件中注入 + /** + * 上传文件到本地目录 + * @param file Spring MultipartFile 对象 + * @return 返回存储的文件相对路径(含文件名) + * @throws IOException 当文件操作失败时抛出 + */ + public String uploadFile(MultipartFile file) throws IOException { + // 确保目录存在 + Path dirPath = Paths.get(baseDir); + if (!Files.exists(dirPath)) { + Files.createDirectories(dirPath); + } + + // 生成唯一文件名(保留原始扩展名) + String originalName = file.getOriginalFilename(); + String extension = originalName.substring(originalName.lastIndexOf(".")); + String fileName = UUID.randomUUID() + extension; + + // 构建目标路径 + Path targetPath = Paths.get(baseDir, fileName); + + // 保存文件 + try (InputStream inputStream = file.getInputStream()) { + Files.copy(inputStream, targetPath); + } + + return targetPath.toString(); + } + + /** + * 根据本地路径读取文件流 + * @param filePath 文件的绝对路径 + * @return 文件输入流(需调用方关闭) + * @throws FileNotFoundException 当文件不存在时抛出 + */ + public InputStream getFileStream(String filePath) throws FileNotFoundException { + File file = new File(filePath); + if (!file.exists() || !file.isFile()) { + throw new FileNotFoundException("文件不存在: " + filePath); + } + return new FileInputStream(file); + } + + /** + * 安全读取文件流(自动关闭资源) + * @param filePath 文件的绝对路径 + * @param consumer 使用流的回调接口 + * @throws IOException 当文件操作失败时抛出 + */ + public void consumeFileStream(String filePath, InputStreamConsumer consumer) throws IOException { + try (InputStream is = getFileStream(filePath)) { + consumer.accept(is); + } + } + + @FunctionalInterface + public interface InputStreamConsumer { + void accept(InputStream stream) throws IOException; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/PubUtils.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/PubUtils.java new file mode 100644 index 0000000..c0b79fd --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/PubUtils.java @@ -0,0 +1,554 @@ +package com.njcn.product.carrycapacity.util; + +import cn.hutool.core.util.RandomUtil; +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static java.lang.Integer.parseInt; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年04月12日 14:21 + */ +public class PubUtils { + + private final static ObjectMapper MAPPER = new ObjectMapper(); + + private static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; + + private static final String DATE = "yyyy-MM-dd"; + + private static final String TIME = "HH:mm:ss"; + + + /** + * 生成随机码,包含字母。--> 大写 + * + * @param length 随机码长度 + */ + public static String randomCode(int length) { + return RandomUtil.randomString(length).toUpperCase(Locale.ENGLISH); + } + + + /**** + * ***** ***** 验证IP是否属于某个IP段 ipSection IP段(以'-'分隔) ip 所验证的IP号码 ***** ***** + **/ + public static boolean ipExistsInRange(String ip, String ipSection) { + ipSection = ipSection.trim(); + ip = ip.trim(); + int idx = ipSection.indexOf('-'); + String beginIp = ipSection.substring(0, idx); + String endIp = ipSection.substring(idx + 1); + return getIp2long(beginIp) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIp); + } + + private static long getIp2long(String ip) { + ip = ip.trim(); + String[] ips = ip.split("\\."); + long ip2long = 0L; + for (int i = 0; i < 4; ++i) { + ip2long = ip2long << 8 | parseInt(ips[i]); + } + return ip2long; + } + + /** + * 获取当前时间 + * + * @author cdf + * @date 2021/7/26 + */ + public static String getNow() { + DateFormat bf = new SimpleDateFormat("yyyyMMddHHmmss"); + return bf.format(new Date()); + } + + /** + * 毫秒转时间 ms:需要转换的毫秒时间 + */ + public static Date ms2Date(Long ms) { + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(ms); + return c.getTime(); + } + + /** + * 日期转字符串函数 date:需要转换的日期 strFormat:转换的格式(yyyy-MM-dd HH:mm:ss) + */ + public static String date2String(Date date, String strFormat){ + SimpleDateFormat format = new SimpleDateFormat(strFormat); + + return format.format(date); + } + + /** + * 获取当前web的IP + */ + public static String getLocalIp() { + String host; + try { + host = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + e.printStackTrace(); + host = "127.0.0.1"; + } + return host; + } + + /** + * 将JSON转为实体对象 + * + * @param jsonStr json + * @param targetType 对象类型 + * @param 对象 + */ + public static T json2obj(String jsonStr, Type targetType) { + try { + JavaType javaType = TypeFactory.defaultInstance().constructType(targetType); + MAPPER.registerModule(new JavaTimeModule()); + MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + return MAPPER.readValue(jsonStr, javaType); + } catch (IOException e) { + throw new IllegalArgumentException("将JSON转换为对象时发生错误:" + jsonStr, e); + } + } + + /** + * 将实体对象转为JSON + * + * @param object 实体对象 + */ + public static String obj2json(Object object) { + try { + MAPPER.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + return MAPPER.writeValueAsString(object); + } catch (IOException e) { + throw new IllegalArgumentException("将实体对象转为JSON时发生错误:" + object, e); + } + } + + + /** + * 判断一个数字是否在区间内 + * + * @param current 待判断数字 + * @param min 最小值 + * @param max 最大值 + */ + public static boolean rangeInDefined(int current, int min, int max) { + return Math.max(min, current) == Math.min(current, max); + } + + /** + * 将起始日期字符串 yyyy-MM-dd 转为 yyyy-MM-dd HH:mm:ss的LocalDateTime + */ + public static LocalDateTime beginTimeToLocalDateTime(String beginTime) { + beginTime = beginTime + StrUtil.SPACE + "00:00:00"; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME); + return LocalDateTime.parse(beginTime, dateTimeFormatter); + } + + /** + * 将截止日期字符串 yyyy-MM-dd 转为 yyyy-MM-dd HH:mm:ss的LocalDateTime + */ + public static LocalDateTime endTimeToLocalDateTime(String endTime) { + endTime = endTime + StrUtil.SPACE + "23:59:59"; + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME); + return LocalDateTime.parse(endTime, dateTimeFormatter); + } + + /** + * 将字符串日期转为LocalDate日期(只用于日期转换) + */ + public static LocalDate localDateFormat(String time) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE); + return LocalDate.parse(time, dateTimeFormatter); + } + + public static LocalDateTime localDateTimeFormat(String time) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME); + return LocalDateTime.parse(time, dateTimeFormatter); + } + + /** + * 校验时间格式 + */ + public static boolean checkDateTime(String time) { + if(StrUtil.isBlank(time)){ + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_TIME); + + try { + simpleDateFormat.parse(time); + } catch (Exception e) { + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + + return true; + } + + /** + * 校验字符串起始时间和结束时间并返回时间格式时间 + * @author cdf + * @date 2023/8/10 + */ + public static List checkLocalDate(String startTime,String endTime) { + List resultList = new ArrayList<>(); + if(StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)){ + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + try { + startTime = startTime+StrUtil.SPACE+"00:00:00"; + endTime = endTime+StrUtil.SPACE+"23:59:59"; + LocalDateTime start = LocalDateTime.parse(startTime,DateTimeFormatter.ofPattern(DATE_TIME)); + LocalDateTime end = LocalDateTime.parse(endTime,DateTimeFormatter.ofPattern(DATE_TIME)); + resultList.add(start); + resultList.add(end); + } catch (Exception e) { + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + return resultList; + } + + + + + /** + * 用于获取对象中,前缀一样,后缀为2~50的属性值 + * + * @param object 待操作对象 + * @param methodPrefix 方法前缀 + * @param number 方法后缀 + * @return 对象属性值 + */ + public static Float getValueByMethod(Object object, String methodPrefix, Integer number) { + try { + Method method = object.getClass().getMethod(methodPrefix + number); + return (Float) method.invoke(object); + } catch (Exception e) { + throw new BusinessException(CommonResponseEnum.REFLECT_METHOD_EXCEPTION); + } + } + + + /** + * 用于获取对象中,前缀一样,后缀为2~50的属性值 + * + * @param object 待操作对象 + * @param methodPrefix 方法前缀 + * @param number 方法后缀 + * @return 对象属性值 + */ + public static Double getValueByMethodDouble(Object object, String methodPrefix, Integer number) { + try { + Method method = object.getClass().getMethod(methodPrefix + number); + return (Double) method.invoke(object); + } catch (Exception e) { + throw new BusinessException(CommonResponseEnum.REFLECT_METHOD_EXCEPTION); + } + } + + + public static List getStartTimeEndTime(String beginDate, String endDate) throws Exception { + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(sdf.parse(beginDate)); + List startTimeEndTime = null; + for (long d = cal.getTimeInMillis(); d <= sdf.parse(endDate).getTime(); d = getDplaus(cal)) { + startTimeEndTime.add(sdf.format(d)); + } + return startTimeEndTime; + } + + public static long getDplaus(Calendar c) { + c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1); + return c.getTimeInMillis(); + } + + public static String comFlag(Integer comFlag) { + switch (comFlag) { + case 0: + return "中断"; + case 1: + return "正常"; + default: + return ""; + } + } + + public static String runFlag(Integer runFlag) { + switch (runFlag) { + case 0: + return "投运"; + case 1: + return "热备用"; + case 2: + return "停运"; + default: + return ""; + } + } + + //监测点运行状态(0:投运;1:检修;2:停运;3:调试;4:退运) + public static String lineRunFlag(Integer runFlag) { + switch (runFlag) { + case 0: + return "投运"; + case 1: + return "检修"; + case 2: + return "停运"; + case 3: + return "调试"; + case 4: + return "退运"; + default: + return ""; + } + } + + public static Integer getRunFlag(String runFlag) { + switch (runFlag) { + case "投运": + return 0; + case "热备用": + return 1; + case "停运": + return 2; + default: + return -1; + } + } + public static Double getDefectSeverity(String defectSeverity) { + switch (defectSeverity) { + case "轻缺陷": + return 0.02; + case "较重缺陷": + return 0.12; + case "严重缺陷": + return 0.42; + default: + return 0.00; + } + } + + public static String ptType(Integer ptType) { + switch (ptType) { + case 0: + return "星型接线"; + case 1: + return "三角型接线"; + case 2: + return "开口三角型接线"; + default: + return ""; + } + } + + public static Integer ptTypeName(String ptType) { + switch (ptType) { + case "星型接线": + return 0; + case "三角型接线": + return 1; + case "开口三角型接线": + return 2; + default: + return -1; + } + } + + /** + * 将当前时间的秒数置为0 + * + * @param date 时间 + */ + public static Date getSecondsAsZero(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.SECOND, 0); + return calendar.getTime(); + } + + /** + * 根据起始时间和截止时间返回yyyy-MM-dd的日期, + * + * @param startTime 起始时间 + * @param endTime 截止时间 + */ + public static List getTimes(Date startTime, Date endTime) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + List result = new ArrayList<>(); + Calendar start = Calendar.getInstance(); + start.setTime(startTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + end.set(end.get(Calendar.YEAR), end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH), 0, 0, 0); + long interval = end.getTimeInMillis() - start.getTimeInMillis(); + result.add(sdf.format(start.getTime())); + if (interval > 0) { + int days = (int) (interval / 86400000); + for (int i = 0; i < days; i++) { + start.add(Calendar.DAY_OF_MONTH, 1); + result.add(sdf.format(start.getTime())); + } + } + return result; + } + + /*** + * 将instant转为date 处理8小时误差 + * @author hongawen + * @date 2023/7/20 15:58 + * @param instant 日期 + * @return Instant + */ + public static Date instantToDate(Instant instant){ + return Date.from(instant.minusMillis(TimeUnit.HOURS.toMillis(8))); + } + + /*** + * 将date转为instant 处理8小时误差 + * @author hongawen + * @date 2023/7/20 15:58 + * @param date 日期 + * @return Instant + */ + public static Instant dateToInstant(Date date){ + return date.toInstant().plusMillis(TimeUnit.HOURS.toMillis(8)); + } + + + /** + * 根据参数返回float的四舍五入值 + * + * @param i 保留的位数 + * @param value float原值 + */ + public static Float floatRound(int i, float value) { + BigDecimal bp = new BigDecimal(value); + return bp.setScale(i, RoundingMode.HALF_UP).floatValue(); + } + + /** + * 根据参数返回double的四舍五入值 + * + * @param i 保留的位数 + * @param value double原值 + */ + public static double doubleRound(int i, double value) { + BigDecimal bp = new BigDecimal(value); + return bp.setScale(i, RoundingMode.HALF_UP).doubleValue(); + } + + //*****************************************xuyang添加,用于App******************************************************** + /** + * 正则表达式字符串 + * 要匹配的字符串 + * + * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false; + */ + public static boolean match(String regex, String str) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(str); + return matcher.matches(); + } + + /** + * 生成随机推荐码 + */ + public static String getCode(Integer number){ + final String BASIC = "123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; + char[] basicArray = BASIC.toCharArray(); + Random random = new Random(); + char[] result = new char[number]; + for (int i = 0; i < result.length; i++) { + int index = random.nextInt(100) % (basicArray.length); + result[i] = basicArray[index]; + } + return new String(result); + } + + /** + * 将字节数组转成Float数组 + * @param bytes + * @return + */ + public static List byteArrayToFloatList(byte[] bytes){ + List d = new ArrayList<>(bytes.length/8); + byte[] doubleBuffer = new byte[4]; + for(int j = 0; j < bytes.length; j += 4) { + System.arraycopy(bytes, j, doubleBuffer, 0, doubleBuffer.length); + d.add(bytes2Float(doubleBuffer)); + } + return d; + } + + public static float bytes2Float(byte[] arr) { + int accum = 0; + accum = accum|(arr[0] & 0xff); + accum = accum|(arr[1] & 0xff) << 8; + accum = accum|(arr[2] & 0xff) << 16; + accum = accum|(arr[3] & 0xff) << 24; + return Float.intBitsToFloat(accum); + } + + /** + * 将字节数组转成Double数组 + * @param arr + * @return + */ + public static List byteArrayToDoubleList(byte[] arr){ + List d = new ArrayList<>(arr.length/8); + byte[] doubleBuffer = new byte[8]; + for(int j = 0; j < arr.length; j += 8) { + System.arraycopy(arr, j, doubleBuffer, 0, doubleBuffer.length); + d.add(bytes2Double(doubleBuffer)); + } + return d; + } + + /** + * 将byte转换成double + * @param arr + * @return + */ + public static double bytes2Double(byte[] arr) { + long value = 0; + for (int i = 0; i < 8; i++) { + value |= ((long) (arr[i] & 0xff)) << (8 * i); + } + return Double.longBitsToDouble(value); + } + //***************************************************添加结束******************************************************** +} diff --git a/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/Utils.java b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/Utils.java new file mode 100644 index 0000000..53d1c59 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/carrycapacity/util/Utils.java @@ -0,0 +1,151 @@ +package com.njcn.product.carrycapacity.util; + +/** + * @Author: Sunwei 【sunW2016@163.com】 + * @Description: + * @Date: Create in 22:28 2018/3/5 + * @Modified By: + * @author njcn + */ + +import cn.hutool.core.collection.CollectionUtil; + +import java.lang.reflect.Field; +import java.time.*; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/***************************************************************** + * 字符串转基础类型,可能转换不成功,封装该方法 + * 第一个参数为需要转换的字符串 + * 第二个参数为null时,直接抛出异常,为数值则传入一个默认值 +*****************************************************************/ +public class Utils { + public static int getIntValue(String s,Integer integer) { + try { + integer = Integer.parseInt(s); + } catch (Exception e) { + if (null == integer) { + throw e; + } + } + + return integer.intValue(); + } + + /** + * String对象转float + * + * @param f + * @return + */ + public static float getFloatValue(String s,Float f) { + try { + f = Float.parseFloat(s); + } catch (Exception e) { + if (null == f) { + throw e; + } + } + + return f.floatValue(); + } + + /** + * String对象转double + * + * @param d + * @return + */ + public static double getDoubleValue(String s,Double d) { + try { + d = Double.parseDouble(s); + } catch (Exception e) { + if (null == d) { + throw e; + } + } + + return d.doubleValue(); + } + + /** + * int转String对象 + */ + public static String int2String(int iValue) { + return Integer.toString(iValue); + } + + /** + * float转String + */ + public static String float2String(float fValue) { + return Float.toString(fValue); + } + + /** + * 按指定大小,分隔集合,将集合按规定个数分为n个部分 + * @author cdf + * @date 2021/10/26 + */ + public static List> splitList(List list, int len){ + if(CollectionUtil.isEmpty(list) || len<1){ + return null; + } + List> result = new ArrayList<>(); + int size = list.size(); + int count = (size+len-1)/1000; + for(int i=0;i subList= list.subList(i*len,((i+1)*len>size?size:len*(i+1))); + result.add(subList); + } + return result; + } + + // 辅助方法:检查时间是否在指定范围内 + public static boolean isTimeInRange(Instant instant, LocalTime startTime, LocalTime endTime) { + LocalTime localTime = instant.atZone(Instant.now().atZone(ZoneId.systemDefault()).getZone()).toLocalTime(); + return !localTime.isBefore(startTime) && !localTime.isAfter(endTime); + } + + //辅助方法:检查时间是否在指定范围内startTime,endTime + public static boolean isTimeInRange(Instant instant, LocalDate startTime, LocalDate endTime) { + // 将Instant对象转换为LocalDateTime对象 + LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); + Instant instant1 = startTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().plusMillis(TimeUnit.HOURS.toMillis(8)); + Instant instant2 = endTime.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant().plusMillis(TimeUnit.HOURS.toMillis(8)); + // 检查LocalDateTime对象是否在startTime和endTime之间 + boolean isInRange = instant1.isBefore(instant) && instant2.isAfter(instant); + + // 返回结果 + return isInRange; + } + + + public static List getAttributeValueByPropertyName(List list, String propertyName) { + List resultList = new ArrayList<>(); + for (T item : list) { + try { + Field field = item.getClass().getDeclaredField(propertyName); + field.setAccessible(true); + resultList.add((Double) field.get(item)); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + return resultList; + } + + public static Double getAttributeValueByPropertyName(T item, String propertyName) { + Double result = null; + try { + Field field = item.getClass().getDeclaredField(propertyName); + field.setAccessible(true); + result=(Double) field.get(item); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + return result; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/LineController.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/LineController.java new file mode 100644 index 0000000..fd76cb5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/LineController.java @@ -0,0 +1,69 @@ +package com.njcn.product.device.ledger.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; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.common.utils.LogUtil; + +import com.njcn.product.device.ledger.pojo.vo.LineDetailDataVO; +import com.njcn.product.device.ledger.service.LineService; +import com.njcn.product.device.overlimit.pojo.Overlimit; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.*; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * @author denghuajun + * @date 2022/2/23 + * 监测点相关 + */ +@Slf4j +@Api(tags = "监测点管理") +@RestController +@RequestMapping("/line") +@RequiredArgsConstructor +public class LineController extends BaseController { + + private final LineService lineService; + + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getLineDetailData") + @ApiOperation("根据监测点id获取监测点详情") + @ApiImplicitParam(name = "id", value = "监测点id", required = true) + public HttpResult getLineDetailData(@RequestParam("id") String id) { + String methodDescribe = getMethodDescribe("getLineDetailData"); + LineDetailDataVO result = lineService.getLineDetailData(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getOverLimitData") + @ApiOperation("根据监测点id获取越限数值") + @ApiImplicitParam(name = "id", value = "监测点id", required = true) + public HttpResult getOverLimitData(@RequestParam("id") String id) { + String methodDescribe = getMethodDescribe("getOverLimitData"); + Overlimit result = lineService.getOverLimitData(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/TerminalTreeController.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/TerminalTreeController.java new file mode 100644 index 0000000..fe423dd --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/controller/TerminalTreeController.java @@ -0,0 +1,62 @@ +package com.njcn.product.device.ledger.controller; + + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; + +import com.njcn.product.device.ledger.pojo.dto.TerminalTree; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.service.TerminalTreeService; +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.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * pqs + * 终端树控制器 + * @author cdf + * @date 2021/7/19 + */ +@Slf4j +@Api(tags = "终端树管理") +@RestController +@RequiredArgsConstructor +@RequestMapping("/terminalTree") +public class TerminalTreeController extends BaseController { + + private final TerminalTreeService terminalTreeService; + + + + /** + * 获取终端台账设备树 + * @author cdf + * @date 2021/7/19 + */ + + @ApiOperation("获取5层终端树") + @OperateInfo(info = LogEnum.BUSINESS_MEDIUM) + @PostMapping("getTerminalTreeForFive") + @ApiImplicitParam(name = "deviceInfoParam", value = "台账查询参数", required = true) + public HttpResult> getTerminalTreeForFive(@RequestBody @Validated DeviceInfoParam deviceInfoParam){ + String methodDescribe = getMethodDescribe("getTerminalTreeForFive"); + List tree = terminalTreeService.getTerminalTreeForFive(deviceInfoParam); + + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, tree, methodDescribe); + } + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeptLineMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeptLineMapper.java new file mode 100644 index 0000000..dbd6408 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeptLineMapper.java @@ -0,0 +1,47 @@ +package com.njcn.product.device.ledger.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.device.ledger.pojo.po.DeptLine; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author denghuajun + * @since 2022-01-12 18:04 + */ +public interface DeptLineMapper extends BaseMapper { + + + @Select ("SELECT\n" + + "\tpq_dept_line.Id,\n" + + "\tpq_dept_line.Line_Id\n" + + "FROM\n" + + "\tpq_dept_line\n" + + "WHERE\n" + + "\tEXISTS (\n" + + "\t\tSELECT\n" + + "\t\t\t1\n" + + "\t\tFROM\n" + + "\t\t\tpq_device,\n" + + "\t\t\tpq_line\n" + + "\t\tWHERE\n" + + "\t\t\tSUBSTRING_INDEX(\n" + + "\t\t\t\tSUBSTRING_INDEX(pq_line.Pids, ',', 5),\n" + + "\t\t\t\t',',\n" + + "\t\t\t\t- 1\n" + + "\t\t\t) = pq_device.Id\n" + + "\t\tAND pq_line.Id = pq_dept_line.Line_Id and (pq_device.Dev_Data_Type= 2 or pq_device.Dev_Data_Type = #{devDataType})\n" + + "\t)") + List getLineByDeptRelation(@Param("devDataType")Integer devDataType); + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeviceMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeviceMapper.java new file mode 100644 index 0000000..0d337c4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/DeviceMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.device.ledger.mapper; + + + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.device.ledger.pojo.po.Device; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface DeviceMapper extends BaseMapper { + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineDetailMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineDetailMapper.java new file mode 100644 index 0000000..797daa5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineDetailMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.device.ledger.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.device.ledger.pojo.po.LineDetail; +import com.njcn.product.device.ledger.pojo.vo.LineDetailDataVO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface LineDetailMapper extends BaseMapper { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineMapper.java new file mode 100644 index 0000000..4c02ab0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/LineMapper.java @@ -0,0 +1,103 @@ +package com.njcn.product.device.ledger.mapper; + + +import cn.hutool.core.date.DateTime; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.dto.SimpleDTO; + +import com.njcn.product.device.ledger.pojo.dto.DeviceType; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.pojo.po.Line; +import com.njcn.product.device.ledger.pojo.vo.LineDetailVO; +import com.njcn.web.pojo.vo.LineDataVO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface LineMapper extends BaseMapper { + + List getLineDetail(@Param("ids") List ids); + /** + * 获取监测点信息 + * + * @param id 监测点id + * @return 结果 + */ + LineDetailVO getLineSubGdDetail(@Param("id") String id); + + /** + * 根据监测点id,获取所有监测点 + * + * @param ids 监测点id + * @param deviceInfoParam 监测点查询条件 + * @return 监测点数据 + */ + List getLineByCondition(@Param("ids") List ids, @Param("deviceInfoParam") DeviceInfoParam deviceInfoParam); + + /** + * 查询终端信息 + * + * @param devIds 终端索引 + * @param deviceType 终端筛选条件 + * @param manufacturer 终端厂家 + */ + List getDeviceByCondition(@Param("devIds") List devIds, @Param("deviceType") DeviceType deviceType, @Param("manufacturer") List manufacturer); + + /** + * 查询母线信息 + * + * @param voltageIds 母线索引 + * @param scale 电压等级 + */ + List getVoltageByCondition(@Param("voltageIds") List voltageIds, @Param("scale") List scale); + + List getSubByCondition(@Param("subIds") List subIds, @Param("scale") List scale); + + + /** + * 查询母线id + * + * @param voltageIds 母线索引集合 + * @param scale 电压等级 + */ + List getVoltageIdByScale(@Param("voltageIds") List voltageIds, @Param("scale") String scale); + + /** + * 查询变电站id + * + * @param subIds 变电站索引集合 + * @param scale 电压等级 + */ + List getSubIdByScale(@Param("subIds") List subIds, @Param("scale") String scale); + + /** + * 查询监测点id + * + * @param lineIds 监测点索引集合 + * @param loadType 干扰源类型 + */ + List getLineIdByLoadType(@Param("lineIds") List lineIds, @Param("loadType") String loadType); + + + /** + * 查询终端id + * + * @param deviceIds 终端索引集合 + * @param manufacturer 制造厂家 + */ + List getDeviceIdByManufacturer(@Param("deviceIds") List deviceIds, @Param("manufacturer") String manufacturer); + + List getDeviceIdByPowerFlag(@Param("lineIds")List lineIds, @Param("powerFlag")Integer manufacturer); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/OverlimitMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/OverlimitMapper.java new file mode 100644 index 0000000..e1478d6 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/OverlimitMapper.java @@ -0,0 +1,17 @@ +package com.njcn.product.device.ledger.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.device.overlimit.pojo.Overlimit; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface OverlimitMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/TreeMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/TreeMapper.java new file mode 100644 index 0000000..324b44f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/TreeMapper.java @@ -0,0 +1,45 @@ +package com.njcn.product.device.ledger.mapper; + +import com.njcn.product.device.ledger.pojo.dto.TerminalTree; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2022/2/28 + */ +public interface TreeMapper { + + /** + * 根据供电公司索引获取出省会的信息 + * @param gdIndexes 供电公司索引 + * @return 省会信息 + */ + List getProvinceList(@Param("gdIndex")List gdIndexes); + + /** + * 获取出供电公司的信息 + * @param gdIndexes 供电公司索引 + * @return 供电公司信息 + */ + List getGdList(@Param("gdIndex")List gdIndexes); + + /** + * 获取出变电站的信息 + * @param subIndexes 变电站索引 + * @return 变电站信息 + */ + List getSubList(@Param("subIndex")List subIndexes); + + /** + * 根据监测点索引获取监测点级五层树数据 + * @param lineIndexes 监测点索引 + * @return 监测点信息 + */ + List getLineList(@Param("lineIndex")List lineIndexes); + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/VoltageMapper.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/VoltageMapper.java new file mode 100644 index 0000000..34a2007 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/VoltageMapper.java @@ -0,0 +1,23 @@ +package com.njcn.product.device.ledger.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.device.ledger.pojo.po.LineDetail; +import com.njcn.product.device.ledger.pojo.po.Voltage; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface VoltageMapper extends BaseMapper { + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeptLineMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeptLineMapper.xml new file mode 100644 index 0000000..db288ed --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeptLineMapper.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeviceMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeviceMapper.xml new file mode 100644 index 0000000..b607515 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/DeviceMapper.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineDetailMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineDetailMapper.xml new file mode 100644 index 0000000..54ff10a --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineDetailMapper.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineMapper.xml new file mode 100644 index 0000000..99aac36 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/LineMapper.xml @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/OverlimitMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/OverlimitMapper.xml new file mode 100644 index 0000000..96450fa --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/OverlimitMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/TreeMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/TreeMapper.xml new file mode 100644 index 0000000..0d4c2df --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/TreeMapper.xml @@ -0,0 +1,413 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/VoltageMapper.xml b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/VoltageMapper.xml new file mode 100644 index 0000000..adfec87 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/mapper/mapping/VoltageMapper.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/DeviceType.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/DeviceType.java new file mode 100644 index 0000000..18965b0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/DeviceType.java @@ -0,0 +1,42 @@ +package com.njcn.product.device.ledger.pojo.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.List; + + +/** + * 设备状态类 + * @author hongawen + * @version 1.0.0 + * @date 2022年02月11日 14:54 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DeviceType implements Serializable { + + /** + * 终端模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + private List devModel; + + /** + * 终端状态(0:投运;1:热备用;2:停运) + */ + private List runFlag; + + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + private List dataType ; + + /** + * 通讯状态(0:中断;1:正常) + */ + private List comFlag ; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/GeneralDeviceDTO.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/GeneralDeviceDTO.java new file mode 100644 index 0000000..5dfa0b7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/GeneralDeviceDTO.java @@ -0,0 +1,67 @@ +package com.njcn.product.device.ledger.pojo.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年09月07日 10:48 + * name对应统计名称:如 区域:南京市、苏州市;电压等级:10kV、220kV... + * index对应统计索引:如 区域:南京市索引、苏州市索引;电压等级:10kV索引、220kV索引... + * gdIndexes:供电公司索引集合 + * subIndexes:变电站索引集合 + * deviceIndexes:终端索引集合 + * voltageIndexes:母线索引集合 + * lineIndexes:监测点索引集合 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class GeneralDeviceDTO implements Serializable { + + /** + * name对应统计名称:如 区域:南京市、苏州市;电压等级:10kV、220kV... + */ + @ApiModelProperty(name = "name", value = "名称") + private String name; + + /** + * index对应统计索引:如 区域:南京市索引、苏州市索引;电压等级:10kV索引、220kV索引... + */ + private String index; + + /** + * gdIndexes:供电公司索引集合 + */ + private List gdIndexes = new ArrayList<>(); + + /** + * subIndexes:变电站索引集合 + */ + private List subIndexes = new ArrayList<>(); + + /** + * deviceIndexes:终端索引集合 + */ + private List deviceIndexes = new ArrayList<>(); + + /** + * voltageIndexes:母线索引集合 + */ + private List voltageIndexes = new ArrayList<>(); + + /** + * lineIndexes:监测点索引集合 + */ + private List lineIndexes = new ArrayList<>(); + @ApiModelProperty(name = "tail", value = "总数") + private Integer tail; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/TerminalTree.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/TerminalTree.java new file mode 100644 index 0000000..a3ce514 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/dto/TerminalTree.java @@ -0,0 +1,80 @@ +package com.njcn.product.device.ledger.pojo.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * pqs + * 终端树实体 + * @author cdf + * @date 2021/7/19 + */ +@ApiModel +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TerminalTree implements Serializable { + @ApiModelProperty(name = "index",value = "序号") + private Integer index; + + private String id; + @ApiModelProperty(name = "parentId",value = "父id") + private String pid; + @ApiModelProperty(name = "level",value = "等级") + private Integer level; + @ApiModelProperty(name = "name",value = "名称") + private String name; + @ApiModelProperty(name = "sort",value = "排序") + private Integer sort; + @ApiModelProperty(name = "comFlag",value = "设备状态") + private Integer comFlag; + + @ApiModelProperty(name = "children",value = "子节点") + private List children = new ArrayList<>(); + + private String pids; + + /** + * 终端厂家 + */ + private String manufacturer; + + /** + * 电压等级Id,字典表 + */ + private String scale; + + /** + * 干扰源类型,字典表 + */ + private String loadType; + + /** + * 接线方式 + */ + private Integer ptType; + + /** + * 电网标志(0-电网侧;1-非电网侧) + */ + private Integer powerFlag; + + /** + * 电网侧变电站 + */ + private String powerSubstationName; + + /** + * 电网侧变电站 + */ + private String objName; + + private String objId; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineBaseEnum.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineBaseEnum.java new file mode 100644 index 0000000..9d90119 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineBaseEnum.java @@ -0,0 +1,63 @@ +package com.njcn.product.device.ledger.pojo.enums; + +import lombok.Getter; + +import java.util.Arrays; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Getter +public enum LineBaseEnum { + + /** + * 系统拓扑各层级描述 + */ + PROJECT_LEVEL(0, "项目"), + PROVINCE_LEVEL(1, "省份"), + GD_LEVEL(2, "供电公司"), + SUB_LEVEL(3, "变电站"), + DEVICE_LEVEL(4, "终端"), + SUB_V_LEVEL(5, "母线"), + LINE_LEVEL(6, "监测点"), + USER_LEVEL(7,"用户"), + INVALID_LEVEL(-1, "非法拓扑等级"), + + + + /** + * 分布式光伏树层级 + */ + PV_UNIT_LEVEL(0,"单位"), + PV_SUB_LEVEL(1,"变电站"), + PV_SUB_AREA_LEVEL(2,"台区"), + + /** + * 电网标志 + */ + POWER_FLAG(0,"电网侧"), + POWER_FLAG_NOT(1,"非电网侧"), + + + + ; + + private final Integer code; + private final String message; + + LineBaseEnum(Integer code, String message) { + this.code = code; + this.message = message; + } + + public static LineBaseEnum getLineBaseEnumByCode(Integer code) { + return Arrays.stream(LineBaseEnum.values()) + .filter(lineBaseEnum -> lineBaseEnum.getCode().equals(code)) + .findAny() + .orElse(INVALID_LEVEL); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineFlagEnum.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineFlagEnum.java new file mode 100644 index 0000000..5aaca1c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/LineFlagEnum.java @@ -0,0 +1,35 @@ +package com.njcn.product.device.ledger.pojo.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月23日 15:24 + */ +@Getter +public enum LineFlagEnum { + + /** + * 区分监测点的类型标志 + */ + //非网公司 + LINE_MONITOR_NOT_NET_COMPANY(0), + //网公司 + LINE_MONITOR_NET_COMPANY(1), + //所有公司 + LINE_MONITOR_ALL(2), + //电网侧 + LINE_POWER_GRID(0), + //非电网侧 + LINE_POWER(1), + //所有 + LINE_POWER_ALL(2); + + private final int flag; + + LineFlagEnum(int flag) { + this.flag = flag; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/PowerFlagEnum.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/PowerFlagEnum.java new file mode 100644 index 0000000..36ed3d4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/PowerFlagEnum.java @@ -0,0 +1,52 @@ +package com.njcn.product.device.ledger.pojo.enums; + +import lombok.Getter; + +import java.util.Arrays; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Getter +public enum PowerFlagEnum { + + /** + * 系统拓扑各层级描述 + */ + GRID_SIDE(0, "电网侧"), + NO_GRID_SIDE(1, "非电网侧"), + NEW_ENERGY(2, "电网侧(新能源)"), + NO_NEW_ENERGY(3, "非电网侧(新能源)"), + SEND_NETWORK(4, "上送国网"), + PCC(5, "PCC"), + + + VIRTUAL_DEVICE(0,"虚拟终端"), + REAL_DEVICE(1,"实际终端"), + OFFLINE_DEICE(2,"离线终端") + + + + + + ; + + private final Integer code; + private final String message; + + PowerFlagEnum(Integer code, String message) { + this.code = code; + this.message = message; + } + + public static PowerFlagEnum getPowerFlagEnumByCode(Integer code) { + return Arrays.stream(PowerFlagEnum.values()) + .filter(x -> x.getCode().equals(code)) + .findAny() + .orElse(GRID_SIDE); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/StatisticsEnum.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/StatisticsEnum.java new file mode 100644 index 0000000..09b0e11 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/enums/StatisticsEnum.java @@ -0,0 +1,49 @@ +package com.njcn.product.device.ledger.pojo.enums; + + +import lombok.Getter; + +import java.util.Arrays; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年03月18日 13:27 + */ +@Getter +public enum StatisticsEnum { + + /** + * 统计类型字典枚举 + */ + POWER_NETWORK("网络拓扑", "Power_Network"), + VOLTAGE_LEVEL("电压等级", "Voltage_Level"), + LOAD_TYPE("干扰源类型", "Load_Type"), + MANUFACTURER("终端厂家", "Manufacturer"), + POWER_FLAG("监测点性质", "Power_Flag"), + REPORT_TYPE("上报类型", "Report_Type"); + + private final String name; + + private final String code; + + StatisticsEnum(String name, String code) { + this.name = name; + this.code = code; + } + + + /** + * 没有匹配到,则默认为网络拓扑 + * @param code 统计类型code + * @return 统计枚举实例 + */ + public static StatisticsEnum getStatisticsEnumByCode(String code) { + return Arrays.stream(StatisticsEnum.values()) + .filter(statisticsEnum -> statisticsEnum.getCode().equalsIgnoreCase(code)) + .findAny() + .orElse(POWER_NETWORK); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/param/DeviceInfoParam.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/param/DeviceInfoParam.java new file mode 100644 index 0000000..0edefa1 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/param/DeviceInfoParam.java @@ -0,0 +1,219 @@ +package com.njcn.product.device.ledger.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.common.pojo.dto.SimpleDTO; + +import com.njcn.product.device.ledger.pojo.enums.LineFlagEnum; +import com.njcn.product.device.ledger.pojo.enums.PowerFlagEnum; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月23日 19:04 + */ +@Data +@ApiModel +@NoArgsConstructor +public class DeviceInfoParam implements Serializable { + + /** + * 统计类型 + */ + @ApiModelProperty(name = "statisticalType", value = "统计类型", required = true) + @NotNull(message = "统计类型不可为空") + private SimpleDTO statisticalType; + + @ApiModelProperty(name = "deptIndex", value = "部门索引", required = true) + @NotBlank(message = "部门索引不可为空") + private String deptIndex; + + @ApiModelProperty(name = "serverName", value = "服务名称") + private String serverName; + + + @ApiModelProperty(name = "scale", value = "电压等级") + private List scale; + + + @ApiModelProperty(name = "manufacturer", value = "终端厂家") + private List manufacturer; + + + @ApiModelProperty(name = "loadType", value = "干扰源类型") + private List loadType; + + /** + * xy添加 + * 默认true + * true statFlag = 1 + * false statFlag = 0 or 1 + */ + @ApiModelProperty(name = "statFlag", value = "人为干预是否参与统计") + private Boolean statFlag; + + /** + * 0-非网公司 + * 1-网公司 + * 2-全部数据 + */ + @ApiModelProperty("网公司标识") + @Range(min = 0, max = 2, message = "网公司标识" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer monitorFlag; + + /** + * 0-电网侧 + * 1-非电网侧 + */ + @ApiModelProperty("电网侧标识") + @Range(min = 0, max = 2, message = "电网侧标识" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer powerFlag; + + /** + * 0-极重要 + * 1-重要 + * 2-普通 + * 3-不重要 + */ + @ApiModelProperty("监测点等级") + private String lineGrade; + + /** + * 通讯状态(0:中断;1:正常) + */ + @ApiModelProperty("通讯状态") + @Range(min = 0, max = 2, message = "通讯状态" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer comFlagStatus; + + + /** + * 监测点运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + @ApiModelProperty("监测点运行状态") + @Range(min = 0, max = 2, message = "监测点运行状态" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer lineRunFlag; + + /** + * 默认全部监测点 + * + * @param deptIndex 部门索引 + * @param serverName 服务名 + */ + public DeviceInfoParam(String deptIndex, String serverName) { + this.deptIndex = deptIndex; + this.serverName = serverName; + monitorFlag = LineFlagEnum.LINE_MONITOR_ALL.getFlag(); + powerFlag = LineFlagEnum.LINE_POWER_ALL.getFlag(); + } + + + /** + * 默认全部监测点 + * + * @param deptIndex 部门索引 + * @param serverName 服务名 + */ + public DeviceInfoParam(SimpleDTO statisticalType, String deptIndex, String serverName, List scale, List manufacturer, List loadType) { + this.statisticalType = statisticalType; + this.deptIndex = deptIndex; + this.serverName = serverName; + this.scale = scale; + this.manufacturer = manufacturer; + this.loadType = loadType; + monitorFlag = LineFlagEnum.LINE_MONITOR_ALL.getFlag(); + powerFlag = LineFlagEnum.LINE_POWER_ALL.getFlag(); + } + + /** + * 自定义上报方式、电网侧方式的统计 + */ + public DeviceInfoParam(SimpleDTO statisticalType, String deptIndex, String serverName, List scale, List manufacturer, List loadType, int monitorFlag, int powerFlag) { + this.statisticalType = statisticalType; + this.deptIndex = deptIndex; + this.serverName = serverName; + this.scale = scale; + this.manufacturer = manufacturer; + this.loadType = loadType; + this.monitorFlag = monitorFlag; + this.powerFlag = powerFlag; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class BusinessParam extends DeviceInfoParam { + + @ApiModelProperty("开始时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchEndTime; + + @ApiModelProperty("时间范围标志 0.查询展示天 1.查询展示月") + @Deprecated + private Integer timeFlag; + + @ApiModelProperty("统计类型 1.年 2.季 3.月 4.周 5.天") + private String reportFlag; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CompareBusinessParam extends BusinessParam { + + @ApiModelProperty("比较开始时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String periodBeginTime; + + @ApiModelProperty("比较结束时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String periodEndTime; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CompareLimitParam extends BusinessParam { + + @ApiModelProperty("查询条数") + @NotNull(message = " 查询条数查询条数不能为空") + private Integer limit; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class GridDiagram extends BusinessParam { + + @ApiModelProperty("查询总数监测点") + private List coutList; + + @ApiModelProperty("查询告警监测点") + private List alarmList; + + @ApiModelProperty("是否是冀北电网一张图树 0:否 1:是") + private Integer type = 0; + } + + public Boolean isUserLedger() { + if (Objects.isNull(this.powerFlag) || !PowerFlagEnum.GRID_SIDE.getCode().equals(this.powerFlag)) { + return true; + } + return false; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/DeptLine.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/DeptLine.java new file mode 100644 index 0000000..521b78b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/DeptLine.java @@ -0,0 +1,31 @@ +package com.njcn.product.device.ledger.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_dept_line") +public class DeptLine { + + private static final long serialVersionUID = 1L; + + /** + * 部门Id + */ + private String id; + + /** + * 监测点Id + */ + private String lineId; + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Device.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Device.java new file mode 100644 index 0000000..de49e7f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Device.java @@ -0,0 +1,165 @@ +package com.njcn.product.device.ledger.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_device") +public class Device implements Serializable{ + + private static final long serialVersionUID = 1L; + + /** + * 装置序号 + */ + @TableId + private String id; + + /** + * 装置模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + private Integer devModel; + + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + private Integer devDataType; + + /** + * 终端运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + private Integer runFlag; + + /** + * 通讯状态(0:中断;1:正常) + */ + private Integer comFlag; + + /** + * 设备制造商,字典表 + */ + private String manufacturer; + + /** + * 定检状态(0:未检 1:已检) + */ + private Integer checkFlag; + + /** + * 前置类型(MMS、CLD)字典表 + */ + private String frontType; + + /** + * 终端型号(570、580……)字典表 + */ + private String devType; + + /** + * 网络参数 + */ + private String ip; + + /** + * 召唤标志(0:周期触发;1:变为触发) + */ + private Integer callFlag; + + /** + * 端口 + */ + private Integer port; + + /** + * 装置识别码(3ds加密) + */ + private String series; + + /** + * 装置秘钥(3ds加密) + */ + private String devKey; + + /** + * 前置序号Id,前置表 + */ + private String nodeId; + + /** + * 投运时间 + */ + private LocalDate loginTime; + + /** + * 数据更新时间 + */ + private LocalDateTime updateTime; + + /** + * 本次定检时间,默认等于投运时间 + */ + private LocalDate thisTimeCheck; + + /** + * 下次定检时间,默认为投运时间后推3年,假如时间小于3个月则为待检 + */ + private LocalDate nextTimeCheck; + + /** + * 电度功能 0 关闭 1开启 + */ + private Integer electroplate; + + /** + * 对时功能 0 关闭, 1开启 + */ + private Integer onTime; + + /** + * 合同号 + */ + private String contract; + + /** + * 设备sim卡号 + */ + private String sim; + + + /** + * 装置系列 + */ + private String devSeries; + + + /** + * 监测装置安装位置 + */ + private String devLocation; + + + /** + * 监测厂家设备编号 + */ + private String devNo; + + + /** + * 告警功能 0:关闭 null、1:开启 + */ + private Integer isAlarm; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Line.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Line.java new file mode 100644 index 0000000..d27a36b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Line.java @@ -0,0 +1,66 @@ +package com.njcn.product.device.ledger.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("pq_line") +public class Line extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 监测点Id + */ + private String id; + + /** + * 父节点(0为根节点) + */ + private String pid; + + /** + * 上层所有节点 + */ + private String pids; + + /** + * 名称 + */ + private String name; + + /** + * 等级:0-项目名称;1- 工程名称;2-单位;3-部门;4-终端;5-母线;6-监测点 + */ + private Integer level; + + /** + * 排序(默认为0,有特殊排序需要时候人为输入) + */ + private Integer sort; + + /** + * 备注 + */ + private String remark; + + /** + * 状态 0-删除;1-正常;默认正常 + */ + private Integer state; + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/LineDetail.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/LineDetail.java new file mode 100644 index 0000000..dece4e1 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/LineDetail.java @@ -0,0 +1,219 @@ +package com.njcn.product.device.ledger.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_line_detail") +public class LineDetail { + + private static final long serialVersionUID = 1L; + + /** + * 监测点序号 + */ + private String id; + + + @TableField(exist = false) + private String monitorName; + + /** + * 线路号(在同一台设备中的监测点号) + */ + private Integer num; + + /** + * PT一次变比 + */ + private Float pt1; + + /** + * PT二次变比 + */ + private Float pt2; + + /** + * CT一次变比 + */ + private Float ct1; + + /** + * CT二次变比 + */ + private Float ct2; + + /** + * 设备容量 + */ + private Float devCapacity; + + /** + * 短路容量 + */ + private Float shortCapacity; + + /** + * 基准容量 + */ + private Float standardCapacity; + + /** + * 协议容量 + */ + private Float dealCapacity; + + /** + * 接线类型(0:星型接法;1:三角型接法;2:开口三角型接法) + */ + private Integer ptType; + + /** + * 测量间隔(1-10分钟) + */ + private Integer timeInterval; + + /** + * 干扰源类型,字典表 + */ + private String loadType; + + /** + * 行业类型,字典表 + */ + private String businessType; + + /** + * 网公司谐波监测平台标志(0-否;1-是),默认否 + */ + private Integer monitorFlag; + + /** + * 电网标志(0-电网侧;1-非电网侧) + */ + private Integer powerFlag; + + /** + * 国网谐波监测平台监测点号 + */ + private String monitorId; + + /** + * 监测点对象名称 + */ + @Deprecated + private String objName; + + /** + * 监测点对象id + */ + private String objId; + + /** + * 监测对象大类 + */ + private String bigObjType; + + /** + * 监测对象小类 + */ + private String smallObjType; + + /** + * 人为干预 0 不参与统计 1 参与统计 + */ + private Integer statFlag; + + /** + * 关联字典的终端等级 + */ + private String lineGrade; + + /** + * 备注 + */ + private String remark; + + + + /** + * 电网侧变电站 + */ + private String powerSubstationName; + /** + * 分类等级 + */ + private String calssificationGrade; + + + /** + * 上级电站 + */ + @Deprecated + private String superiorsSubstation; + + /** + * 挂接线路 + */ + @Deprecated + private String hangLine; + + /** + * 监测点拥有者 + */ + @Deprecated + private String owner; + + /** + * 拥有者职务 + */ + @Deprecated + private String ownerDuty; + + /** + * 拥有者联系方式 + */ + @Deprecated + private String ownerTel; + + /** + * 接线图 + */ + private String wiringDiagram; + /** + * 监测点接线相别(0,单相,1,三相,默认三相) + */ + private Integer ptPhaseType; + + /** + * 监测点实际安装位置 + */ + private String actualArea; + + /** + * 监测点运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + private Integer runFlag; + + /** + * 新能源场站信息ID + */ + @Deprecated + private String newStationId; + + /** + * 通讯状态 + */ + @TableField(exist = false) + private Integer comFlag; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Voltage.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Voltage.java new file mode 100644 index 0000000..66d4637 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/po/Voltage.java @@ -0,0 +1,42 @@ +package com.njcn.product.device.ledger.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_voltage") +public class Voltage { + + private static final long serialVersionUID = 1L; + + /** + * 母线序号 + */ + private String id; + + /** + * 母线号(在同一台设备中的电压通道号) + */ + private Integer num; + + /** + * 电压等级Id,字典表 + */ + private String scale; + + /** + * 母线模型(0:虚拟母线;1:实际母线)默认是实际母线 + */ + private Integer model; + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailDataVO.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailDataVO.java new file mode 100644 index 0000000..e5adc54 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailDataVO.java @@ -0,0 +1,130 @@ +package com.njcn.product.device.ledger.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * @author denghuajun + * @date 2022/2/23 + * 监测点信息 + */ +@Data +@ApiModel +public class LineDetailDataVO { + private String lineId; + @ApiModelProperty(name = "id",value = "监测点序号") + private Integer id; + + @ApiModelProperty(name = "lineName",value = "监测点名称") + private String lineName; + + @ApiModelProperty(name = "areaName",value = "工程名称") + private String areaName; + + @ApiModelProperty(name = "gdName",value = "单位") + private String gdName; + + @ApiModelProperty(name = "bdName",value = "部门") + private String bdName; + + @ApiModelProperty(name = "scale",value = "电压等级") + private String scale; + + @ApiModelProperty(name = "manufacturer",value = "厂家") + private String manufacturer; + + @ApiModelProperty(name = "devId",value = "终端Id") + private String devId; + + @ApiModelProperty(name = "devName",value = "终端名称") + private String devName; + + @ApiModelProperty(name = "ip",value = "网络参数") + private String ip; + + @ApiModelProperty(name = "runFlag",value = "终端运行状态") + private String runFlag; + + @ApiModelProperty(name = "comFlag",value = "通讯状态") + private String comFlag; + + @ApiModelProperty(name = "loadType",value = "干扰源类型") + private String loadType; + + @ApiModelProperty(name = "businessType",value = "行业类型") + private String businessType; + + @ApiModelProperty(name = "objName",value = "监测点对象名称") + private String objName; + + @ApiModelProperty(name = "ptType",value = "接线方式") + private String ptType; + + @ApiModelProperty(name = "pt",value = "PT变比") + private String pt; + + @ApiModelProperty(name = "ct",value = "CT变比") + private String ct; + + @ApiModelProperty(name = "standardCapacity",value = "基准容量(MVA)") + private Float standardCapacity; + + @ApiModelProperty(name = "shortCapacity",value = "最小短路容量(MVA)") + private Float shortCapacity; + + @ApiModelProperty(name = "devCapacity",value = "供电设备容量(MVA)") + private Float devCapacity; + + @ApiModelProperty(name = "dealCapacity",value = "用户协议容量(MVA)") + private Float dealCapacity; + + /** + * 测量间隔(1-10分钟) + */ + @ApiModelProperty(name = "timeInterval",value = "测量间隔(1-10分钟)") + private Integer timeInterval; + + /** + * 监测点拥有者 + */ + @ApiModelProperty(name = "owner",value = "监测点拥有者") + private String owner; + + /** + * 拥有者职务 + */ + @ApiModelProperty(name = "ownerDuty",value = "拥有者职务") + private String ownerDuty; + + /** + * 拥有者联系方式 + */ + @ApiModelProperty(name = "ownerTel",value = "拥有者联系方式") + private String ownerTel; + + /** + * 接线图 + */ + @ApiModelProperty(name = "wiringDiagram",value = "接线图") + private String wiringDiagram; + @ApiModelProperty(name = "ptPhaseType",value = "监测点接线相别(0,单相,1,三相,默认三相)") + private Integer ptPhaseType; + + @ApiModelProperty(name = "投运日期") + private LocalDate loginTime; + + @ApiModelProperty(name = "最新数据时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updateTime; + + @ApiModelProperty(name = "监测对象信息ID") + private String objId; + + @ApiModelProperty(name = "对象类型大类") + private String bigObjType; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailVO.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailVO.java new file mode 100644 index 0000000..7da8fd7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineDetailVO.java @@ -0,0 +1,109 @@ +package com.njcn.product.device.ledger.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * @author denghuajun + * @version 1.0.0 + * @date 2022年05月06日 15:38 + */ +@Data +public class LineDetailVO implements Serializable { + + @ApiModelProperty("供电公司名称") + private String gdName; + + @ApiModelProperty("变电站名称") + private String subName; + + @ApiModelProperty("终端名称") + private String devName; + + @ApiModelProperty("网络参数") + private String ip; + + @ApiModelProperty("监测点名称") + private String lineName; + + @ApiModelProperty("母线名称") + private String volName; + + /** + * (0:运行;1:检修;2:停运;3:调试;4:退运) + */ + @ApiModelProperty("监测点运行状态") + private Integer runFlag; + @Data + public static class Detail extends LineDetailVO implements Serializable{ + + @ApiModelProperty("区域id") + private String areaId; + + @ApiModelProperty("区域名称") + private String areaName; + + @ApiModelProperty("终端id") + private String devId; + + @ApiModelProperty("监测点Id") + private String lineId; + + @ApiModelProperty("测量间隔(1-10分钟)") + private Integer timeInterval; + + @ApiModelProperty("接线类型") + private Integer ptType; + + @ApiModelProperty("电压等级") + private String voltageLevel; + + @ApiModelProperty("数据更新时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timeID; + + @ApiModelProperty("终端等级") + private String lineGrade; + + @ApiModelProperty("通讯状态(0:中断;1:正常)") + private Integer comFlag; + + @ApiModelProperty("PT一次变比") + private Double PT1; + + @ApiModelProperty("PT二次变比") + private Double PT2; + + @ApiModelProperty("CT一次变比") + private Double CT1; + + @ApiModelProperty("CT二次变比") + private Double CT2; + + @ApiModelProperty("套餐流量") + private Float flowMeal; + + @ApiModelProperty("已用流量") + private Float statisValue; + + @ApiModelProperty("已用流量占比") + private Float flowProportion; + } + + @Data + public static class noDataLineInfo extends LineDetailVO implements Serializable{ + + @ApiModelProperty("监测点Id") + private String lineId; + + @ApiModelProperty("终端id") + private String devId; + + @ApiModelProperty("最新数据时间") + private LocalDateTime updateTime; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineOverLimitVO.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineOverLimitVO.java new file mode 100644 index 0000000..852c68c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/pojo/vo/LineOverLimitVO.java @@ -0,0 +1,120 @@ +package com.njcn.product.device.ledger.pojo.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author denghuajun + * @date 2022/2/23 + * + */ +@Data +@ApiModel +public class LineOverLimitVO { + + @ApiModelProperty(name = "freqDev",value = "频率限值") + private Float freqDev; + + @ApiModelProperty(name = "voltageDev",value = "电压上偏差限值") + private Float voltageDev; + + @ApiModelProperty(name = "uvoltageDev",value = "电压下偏差限值") + private Float uvoltageDev; + + @ApiModelProperty(name = "ubalance",value = "三相电压不平衡度限值") + private Float ubalance; + + @ApiModelProperty(name = "iNeg",value = "负序电流") + private Float iNeg; + + @ApiModelProperty(name = "flicker",value = "长时闪变限值") + private Float flicker; + + @ApiModelProperty(name = "uaberrance",value = "电压总谐波畸变率限值") + private Float uaberrance; + + @ApiModelProperty(name = "oddHarm",value = "奇次谐波含有率限值") + private Float oddHarm; + + @ApiModelProperty(name = "evenHarm",value = "偶次谐波含有率限值") + private Float evenHarm; + + @ApiModelProperty(name = "iharm2",value = "2次谐波电流幅值限值") + private Float iharm2; + + @ApiModelProperty(name = "iharm3",value = "3次谐波电流幅值限值") + private Float iharm3; + + @ApiModelProperty(name = "iharm4",value = "4次谐波电流幅值限值") + private Float iharm4; + + @ApiModelProperty(name = "iharm5",value = "5次谐波电流幅值限值") + private Float iharm5; + + @ApiModelProperty(name = "iharm6",value = "6次谐波电流幅值限值") + private Float iharm6; + + @ApiModelProperty(name = "iharm7",value = "7次谐波电流幅值限值") + private Float iharm7; + + @ApiModelProperty(name = "iharm8",value = "8次谐波电流幅值限值") + private Float iharm8; + + @ApiModelProperty(name = "iharm9",value = "9次谐波电流幅值限值") + private Float iharm9; + + @ApiModelProperty(name = "iharm10",value = "10次谐波电流幅值限值") + private Float iharm10; + + @ApiModelProperty(name = "iharm11",value = "11次谐波电流幅值限值") + private Float iharm11; + + @ApiModelProperty(name = "iharm12",value = "12次谐波电流幅值限值") + private Float iharm12; + + @ApiModelProperty(name = "iharm13",value = "13次谐波电流幅值限值") + private Float iharm13; + + @ApiModelProperty(name = "iharm14",value = "14次谐波电流幅值限值") + private Float iharm14; + + @ApiModelProperty(name = "iharm15",value = "15次谐波电流幅值限值") + private Float iharm15; + + @ApiModelProperty(name = "iharm16",value = "16次谐波电流幅值限值") + private Float iharm16; + + @ApiModelProperty(name = "iharm17",value = "17次谐波电流幅值限值") + private Float iharm17; + + @ApiModelProperty(name = "iharm18",value = "18次谐波电流幅值限值") + private Float iharm18; + + @ApiModelProperty(name = "iharm19",value = "19次谐波电流幅值限值") + private Float iharm19; + + @ApiModelProperty(name = "iharm20",value = "20次谐波电流幅值限值") + private Float iharm20; + + @ApiModelProperty(name = "iharm21",value = "21次谐波电流幅值限值") + private Float iharm21; + + @ApiModelProperty(name = "iharm22",value = "22次谐波电流幅值限值") + private Float iharm22; + + @ApiModelProperty(name = "iharm23",value = "23次谐波电流幅值限值") + private Float iharm23; + + @ApiModelProperty(name = "iharm24",value = "24次谐波电流幅值限值") + private Float iharm24; + + @ApiModelProperty(name = "iharm25",value = "25次谐波电流幅值限值") + private Float iharm25; + + @ApiModelProperty(name = "inUharm",value = "0.5-1.5次间谐波电压幅值限值") + private Float inUharm; + + @ApiModelProperty(name = "inUharm16",value = "2.5-15.5次间谐波电压幅值限值") + private Float inUharm16; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/DeptLineService.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/DeptLineService.java new file mode 100644 index 0000000..a3f218c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/DeptLineService.java @@ -0,0 +1,64 @@ +package com.njcn.product.device.ledger.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.device.ledger.pojo.po.DeptLine; +import com.njcn.web.pojo.param.DeptLineParam; + +import java.util.List; +import java.util.Map; + +/** + * @author denghuajun + * @date 2022/1/12 17:30 + * + */ +public interface DeptLineService extends IService { + + /** + * 部门绑定监测点 + * @param deptLineParam 部门监测点的实体类 + * @return 绑定结果 + */ + void deptBindLine(DeptLineParam deptLineParam); + + + /** + * 部门解绑监测点 + * @param deptLineParam 部门监测点的实体类 + * @return 解绑结果 + */ + void deptDeleteBindLine(DeptLineParam deptLineParam); + + + /** + * 根据部门ids集合查询是否绑定监测点 + * @param ids 部门ids + * @return 查询结果 + */ + List selectDeptBindLines(List ids); + + /** + * 部门解除绑定监测点 + * @param id 部门id + * @return 解绑结果 + */ + int removeBind(String id); + + /** + * 功能描述: 根据部门id获取绑定的监测点 + * + * @param id + * @return java.util.List + * @author xy + * @date 2022/1/25 9:28 + */ + List getLineByDeptId(String id); + /** + * @Description: 获取部门和监测点的关系(分稳态暂态) + * @Param: [devDataType] + * @return: java.util.Map> + * @Author: clam + * @Date: 2022/10/19 + */ + Map> getLineByDeptRelation(Integer devDataType); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/LineService.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/LineService.java new file mode 100644 index 0000000..0d45717 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/LineService.java @@ -0,0 +1,33 @@ +package com.njcn.product.device.ledger.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.product.device.ledger.pojo.po.Line; +import com.njcn.product.device.ledger.pojo.vo.LineDetailDataVO; +import com.njcn.product.device.ledger.pojo.vo.LineOverLimitVO; +import com.njcn.product.device.overlimit.pojo.Overlimit; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; +import java.util.Map; + +/** + * 监测点类 + * @author denghuajun + * @date 2022/2/23 + * + */ +public interface LineService extends IService { + /** + * 获取监测点详情 + * @param id 监测点id + * @return 结果 + */ + LineDetailDataVO getLineDetailData(String id); + + + + + Overlimit getOverLimitData(String id); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalBaseService.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalBaseService.java new file mode 100644 index 0000000..b262dc5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalBaseService.java @@ -0,0 +1,119 @@ +package com.njcn.product.device.ledger.service; + +import com.njcn.common.pojo.dto.SimpleDTO; + +import com.njcn.product.device.ledger.pojo.dto.DeviceType; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.pojo.po.Line; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +public interface TerminalBaseService { + + + + + /** + * 根据监测点id,获取所有监测点 + * + * @param lineIds 监测点id + * @return 监测点数据 + */ + List getLineById(List lineIds); + + /** + * 根据监测点id,获取所有监测点 + * + * @param lineIds 监测点id + * @param deviceInfoParam 监测点查询条件 + * @return 监测点数据 + */ + List getLineByCondition(List lineIds, DeviceInfoParam deviceInfoParam); + + + + + + + + + + /** + * 查询终端信息 + * + * @param devIds 终端索引 + * @param deviceType 终端筛选条件 + * @param manufacturer 终端厂家 + */ + List getDeviceByCondition(List devIds, DeviceType deviceType, List manufacturer); + + /** + * 查询母线信息 + * + * @param voltageIds 母线索引 + * @param scale 电压等级 + */ + List getVoltageByCondition(List voltageIds, List scale); + + /** + * 查询变电站信息 + * + * @param subIds 变电站索引 + * @param scale 电压等级 + */ + List getSubByCondition(List subIds, List scale); + + /** + * 根据指定电压等级查询母线id + * + * @param voltageIds 母线id + * @param scale 电压等级 + */ + List getVoltageIdByScale(List voltageIds, String scale); + + /** + * 根据指定电压等级查询母线id + * @param subIds + * @param scale + * @return: java.util.List + * @Author: wr + * @Date: 2024/10/12 15:58 + */ + List getSubIdByScale(List subIds, String scale); + + /** + * 根据干扰源获取对应的监测点id + * + * @param lineIds 监测点id + * @param loadType 干扰源类型 + */ + List getLineIdByLoadType(List lineIds, String loadType); + + /** + * 根据终端厂家获取对应的终端id + * + * @param deviceIds 终端id + * @param manufacturer 终端厂家 + */ + List getDeviceIdByManufacturer(List deviceIds, String manufacturer); + /** + * 根据监测点性质获取监测信息 + * + * @param lineIds 监测点id + * @param manufacturer 监测点性质 + */ + List getDeviceIdByPowerFlag(List lineIds, Integer manufacturer); + + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalTreeService.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalTreeService.java new file mode 100644 index 0000000..e2ab053 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/TerminalTreeService.java @@ -0,0 +1,30 @@ +package com.njcn.product.device.ledger.service; + + + + +import com.njcn.product.device.ledger.pojo.dto.TerminalTree; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; + +import java.util.List; + +/** + * pqs + * 终端设备树业务 + * + * @author cdf + * @date 2021/7/19 + */ +public interface TerminalTreeService { + + + /** + * 5层树排除设备 母线监测点合并 + * + * @author cdf + * @date 2022/1/13 + */ + List getTerminalTreeForFive(DeviceInfoParam deviceInfoParam); + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/DeptLineServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/DeptLineServiceImpl.java new file mode 100644 index 0000000..3aaecd2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/DeptLineServiceImpl.java @@ -0,0 +1,91 @@ +package com.njcn.product.device.ledger.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.product.device.ledger.mapper.DeptLineMapper; +import com.njcn.product.device.ledger.pojo.po.DeptLine; +import com.njcn.product.device.ledger.service.DeptLineService; +import com.njcn.web.pojo.param.DeptLineParam; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author denghuajun + * @date 2022/1/12 17:32 + * + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeptLineServiceImpl extends ServiceImpl implements DeptLineService { + + private final DeptLineMapper deptLineMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public void deptBindLine(DeptLineParam deptLineParam) { + //先解绑,再进行绑定 + QueryWrapper deptLineQueryWrapper = new QueryWrapper<>(); + deptLineQueryWrapper.eq("pq_dept_line.id", deptLineParam.getId()); + this.baseMapper.delete(deptLineQueryWrapper); + List deptLines = deptLineParam.getIds().stream().map(id -> { + DeptLine deptLine = new DeptLine(); + deptLine.setId(deptLineParam.getId()); + deptLine.setLineId(id); + return deptLine; + }).collect(Collectors.toList()); + this.saveBatch(deptLines); + } + + @Override + public void deptDeleteBindLine(DeptLineParam deptLineParam) { + for (int i = 0; i < deptLineParam.getIds().size(); i++) { + QueryWrapper deptLineQueryWrapper = new QueryWrapper<>(); + deptLineQueryWrapper.eq("pq_dept_line.id", deptLineParam.getId()); + deptLineQueryWrapper.eq("pq_dept_line.Line_Id", deptLineParam.getIds().get(i)); + this.baseMapper.delete(deptLineQueryWrapper); + } + } + + @Override + public List selectDeptBindLines(List ids) { + return this.lambdaQuery().in(DeptLine::getId, ids).list(); + } + + @Override + public int removeBind(String id) { + QueryWrapper deptLineQueryWrapper = new QueryWrapper<>(); + deptLineQueryWrapper.eq("pq_dept_line.id", id); + return this.baseMapper.delete(deptLineQueryWrapper); + } + + @Override + public List getLineByDeptId(String id) { + return this.lambdaQuery().in(DeptLine::getId, id).list().stream().map(DeptLine::getLineId).distinct().collect(Collectors.toList()); + } + + /** + * @param devDataType + * @Description: 获取部门和监测点的关系(分稳态暂态) + * @Param: [devDataType] + * @return: java.util.Map> + * @Author: clam + * @Date: 2022/10/19 + */ + @Override + public Map> getLineByDeptRelation(Integer devDataType) { + List deptLines = deptLineMapper.getLineByDeptRelation(devDataType); + Map> collect = deptLines.stream ( ).collect (Collectors.groupingBy (DeptLine::getId, Collectors.mapping (DeptLine::getLineId,Collectors.toList ()))); + + return collect; + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/GeneralDeviceService.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/GeneralDeviceService.java new file mode 100644 index 0000000..0b0aba5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/GeneralDeviceService.java @@ -0,0 +1,434 @@ +package com.njcn.product.device.ledger.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.common.pojo.enums.common.ServerEnum; +import com.njcn.common.utils.EnumUtils; + +import com.njcn.product.device.ledger.pojo.dto.DeviceType; +import com.njcn.product.device.ledger.pojo.dto.GeneralDeviceDTO; +import com.njcn.product.device.ledger.pojo.enums.LineBaseEnum; +import com.njcn.product.device.ledger.pojo.enums.PowerFlagEnum; +import com.njcn.product.device.ledger.pojo.enums.StatisticsEnum; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.pojo.po.DeptLine; +import com.njcn.product.device.ledger.pojo.po.Line; +import com.njcn.product.device.ledger.service.DeptLineService; +import com.njcn.product.device.ledger.service.TerminalBaseService; +import com.njcn.product.system.dept.pojo.dto.DeptDTO; +import com.njcn.product.system.dept.service.IDeptService; +import com.njcn.product.system.dict.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.service.IDictDataService; +import com.njcn.web.utils.WebUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 终端信息处理器,根据需求返回笼统的台账信息。 + * ii * 包括:类别名称、类别索引、监测点索引集合、终端索引集合、变电站索引集bb合、供电公司索引集合。 + * PS:若后期需要比如:省会、项目时再动态添加。 + * + * @author hongawen + * @version 1.0.0 + * @date 2022年02月11日 09:29 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class GeneralDeviceService { + + private final IDeptService deptService; + + private final DeptLineService deptLineService; + private final IDictDataService iDictDataService; + + private final TerminalBaseService terminalBaseService; + + + + /** + * 根据部门id、远程服务名、远程客户端类型,以部门的方式 + * + * @param deviceInfoParam 终端查询条件 + * @param runFlag 终端状态 + * @param devModel 终端模型 + * @return 部门分类终端信息 + */ + public List getDeviceInfo(DeviceInfoParam deviceInfoParam, + List runFlag, + List devModel) { + //定义待返回终端信息 + List deviceInfos = new ArrayList<>(); + //初始化终端查询条件 + DeviceType deviceType = new DeviceType(); + if (CollectionUtil.isEmpty(devModel)) { + /** + * 终端模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + deviceType.setDevModel(null); + } else { + deviceType.setDevModel(devModel); + } + if (CollectionUtil.isEmpty(runFlag)) { + /** + * 终端状态(0:投运;1:热备用;2:停运) + */ + deviceType.setRunFlag(null); + } else { + deviceType.setRunFlag(runFlag); + } + if(ObjectUtil.isNotNull(deviceInfoParam.getComFlagStatus())){ + deviceType.setComFlag(Arrays.asList(deviceInfoParam.getComFlagStatus())); + } + filterDataType(deviceType, deviceInfoParam.getServerName()); + + // 初始化部门筛选条件 + List deptType = WebUtil.filterDeptType(); + // 获取包括当前部门的后代所有部门信息 + List deptInfos = deptService.getDeptDescendantIndexes(deviceInfoParam.getDeptIndex(), deptType); + // 过滤非直接后代部门,集合直接子部门 + List directDeptInfos = deptInfos.stream() + .filter(deptDTO -> deptDTO.getPid().equals(deviceInfoParam.getDeptIndex())).sorted(Comparator.comparing(DeptDTO::getSort)) + .collect(Collectors.toList()); + if (CollectionUtil.isEmpty(directDeptInfos)) { + // 没有直接子部门(树的最底层),获取当前部门所有信息 + List dept = deptInfos.stream() + .filter(deptDTO -> deptDTO.getId().equals(deviceInfoParam.getDeptIndex())) + .collect(Collectors.toList()); + deviceInfos.add(getGeneralDeviceInfo( + dept.get(0), + deviceType, + Collections.singletonList(deviceInfoParam.getDeptIndex()), + deviceInfoParam)); + } else { + for (DeptDTO directDeptDTO : directDeptInfos) { + //筛选pids包含该id的所有部门 直接子部门下属所有部门 + List descendantDeptDTO = deptInfos.stream() + .filter(d -> d.getPids().contains(directDeptDTO.getId())) + .collect(Collectors.toList()); + //形成需要查询监测点的部门索引 + List indexes = descendantDeptDTO.stream() + .map(DeptDTO::getId) + .distinct() + .collect(Collectors.toList()); + indexes.add(directDeptDTO.getId()); + GeneralDeviceDTO generalDeviceInfo = getGeneralDeviceInfo(directDeptDTO, deviceType, indexes, deviceInfoParam); + deviceInfos.add(generalDeviceInfo); + } + } + + + //判断统计类型 + if (deviceInfoParam.getStatisticalType() == null) { + deviceInfoParam.setStatisticalType(new SimpleDTO()); + } + StatisticsEnum statisticsEnum = StatisticsEnum.getStatisticsEnumByCode(deviceInfoParam.getStatisticalType().getCode()); + switch (statisticsEnum) { + case VOLTAGE_LEVEL: + return filterDataByScale(deviceInfos, deviceInfoParam.getScale()); + case LOAD_TYPE: + return filterDataByLoadType(deviceInfos, deviceInfoParam.getLoadType()); + case MANUFACTURER: + return filterDataByManufacturer(deviceInfos, deviceInfoParam.getManufacturer()); + case POWER_FLAG: + return filterDataByPowerFlag(deviceInfos, deviceInfoParam.getManufacturer()); + default: + return deviceInfos; + } + } + + /** + * 根据部门id集合获取监测点信息 + * + * @param directDeptDTO 入参deptIndex的直接子部门 + * @param deviceType + * @param ids 直接子部门以及后代部门id集合 + * @param deviceInfoParam + * @return + */ + private GeneralDeviceDTO getGeneralDeviceInfo(DeptDTO directDeptDTO, + DeviceType deviceType, + List ids, + DeviceInfoParam deviceInfoParam) { + GeneralDeviceDTO generalDeviceDTO = new GeneralDeviceDTO(); + generalDeviceDTO.setIndex(directDeptDTO.getId()); + // type:部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + if (directDeptDTO.getType() == 0) { + generalDeviceDTO.setName(directDeptDTO.getArea()); + } else { + generalDeviceDTO.setName(directDeptDTO.getName()); + } + // 根据部门ids集合查询是否绑定监测点 部门和监测点关联关系中间表:pq_dept_line 可以一对多 + List deptLines = deptLineService.selectDeptBindLines(ids); + // 返回空数据 + if (CollectionUtil.isEmpty(deptLines)) { + return generalDeviceDTO; + } + // 提取该部门及其子部门所有监测点id + List lineIds = deptLines.stream().map(DeptLine::getLineId).collect(Collectors.toList()); + // 获取line详细数据 :根据监测点id,获取所有监测点 联查 pq_line、pq_line_detail + List lines = terminalBaseService.getLineByCondition(lineIds, deviceInfoParam); + // 返回空数据 + if (CollectionUtil.isEmpty(lines)) { + return generalDeviceDTO; + } + + //1.筛选出母线id,理论上监测点的pids中第六个id为母线id 联查: pq_line t1 ,pq_voltage t2 + List voltageIds=lines.stream().map(Line::getPid).collect(Collectors.toList()); + //再根据电压等级筛选合法母线信息 + List voltages = terminalBaseService.getVoltageByCondition(voltageIds, deviceInfoParam.getScale()); + + //2.筛选出终端id,理论上监测点的pids中第五个id为终端id + List devIds=voltages.stream().map(Line::getPid).collect(Collectors.toList()); + // 再根据终端条件筛选合法终端信息 联查:pq_line t1,pq_device t2 + List devices = terminalBaseService.getDeviceByCondition(devIds, deviceType, deviceInfoParam.getManufacturer()); + + //3.筛选出变电站id,理论上监测点的pids中第四个id为变电站id 联查: pq_line t1 ,pq_substation t2 + List subIds=devices.stream().map(Line::getPid).collect(Collectors.toList()); + List sub = terminalBaseService.getSubByCondition(subIds, new ArrayList<>()); + + //筛选最终的数据 + dealDeviceData(generalDeviceDTO, lines, devices, voltages, sub); + return generalDeviceDTO; + } + /** + * 取多条件筛选后的交集索引,填充到部门统计中 + * + * @param generalDeviceDTO 部门信息 + * @param lines 筛选后的监测点信息 + * @param devices 筛选后的终端信息 + * @param voltages 筛选后的母线信息 + */ + private void dealDeviceData(GeneralDeviceDTO generalDeviceDTO, List lines, List devices, List voltages, List sub) { + List gdIndexes = new ArrayList<>(), subIndexes = new ArrayList<>(), deviceIndexes = new ArrayList<>(), voltageIndexes = new ArrayList<>(), lineIndexes = new ArrayList<>(); + List devIds = devices.stream().map(Line::getId).distinct().collect(Collectors.toList()); + List volIds = voltages.stream().map(Line::getId).distinct().collect(Collectors.toList()); + List subIds = sub.stream().map(Line::getId).distinct().collect(Collectors.toList()); + for (Line line : lines) { + String[] idsArray = line.getPids().split(","); + //监测点同时满足条件筛选后的终端、母线信息,才是最终的结果 + if (devIds.contains(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]) && + volIds.contains(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()])&& + subIds.contains(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]) + ) { + gdIndexes.add(idsArray[LineBaseEnum.GD_LEVEL.getCode()]); + subIndexes.add(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]); + deviceIndexes.add(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]); + voltageIndexes.add(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()]); + lineIndexes.add(line.getId()); + } + } + //排重,入参到终端综合体 + generalDeviceDTO.setGdIndexes(gdIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setSubIndexes(subIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setDeviceIndexes(deviceIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setVoltageIndexes(voltageIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setLineIndexes(lineIndexes.stream().distinct().collect(Collectors.toList())); + } + + /** + * 筛选数据类型 + */ + private void filterDataType(DeviceType deviceType, String serverName) { + ServerEnum serverEnum = EnumUtils.getServerEnumByName(serverName); + List dataType = new ArrayList<>(); + dataType.add(2); + switch (serverEnum) { + case EVENT: + dataType.add(0); + break; + case HARMONIC: + dataType.add(1); + break; + default: + dataType.add(0); + dataType.add(1); + break; + } + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + deviceType.setDataType(dataType); + } + + private List filterDataByScale(List deviceInfos, List scales) { + List generalDeviceDTOS = new ArrayList<>(); + List subIds = new ArrayList<>(), lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + subIds.addAll(generalDeviceDTO.getSubIndexes()); + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果电压等级集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(scales)) { + List scaleDictData = iDictDataService.getDicDataByTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()); + scales = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(scales); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : scales) { + List voltageScaleIds = terminalBaseService.getSubIdByScale(subIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, voltageScaleIds, LineBaseEnum.SUB_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + + private List filterDataByLoadType(List deviceInfos, List loadType) { + List generalDeviceDTOS = new ArrayList<>(); + List lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果干扰源集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(loadType)) { + List scaleDictData = iDictDataService.getDicDataByTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName()); + loadType = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(loadType); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : loadType) { + List lineLoadTypeIds = terminalBaseService.getLineIdByLoadType(lineIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, lineLoadTypeIds, LineBaseEnum.LINE_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + private List filterDataByManufacturer(List deviceInfos, List manufacturer) { + List generalDeviceDTOS = new ArrayList<>(); + List deviceIds = new ArrayList<>(), lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + deviceIds.addAll(generalDeviceDTO.getDeviceIndexes()); + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果终端厂家集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(manufacturer)) { + List scaleDictData = iDictDataService.getDicDataByTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName()); + manufacturer = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(manufacturer); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : manufacturer) { + List voltageScaleIds = terminalBaseService.getDeviceIdByManufacturer(deviceIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, voltageScaleIds, LineBaseEnum.DEVICE_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + private List filterDataByPowerFlag(List deviceInfos, List manufacturer) { + List generalDeviceDTOS = new ArrayList<>(); + List deviceIds = deviceInfos.stream().flatMap(x->x.getLineIndexes().stream()).collect(Collectors.toList()); + List lineIds = deviceInfos.stream().flatMap(x->x.getLineIndexes().stream()).collect(Collectors.toList()); + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(manufacturer); + } + SimpleDTO dto; + List lines = terminalBaseService.getLineById(lineIds); + for (int i = 0; i < 6; i++) { + List powerFlagIds = terminalBaseService.getDeviceIdByPowerFlag(deviceIds, i); + dto=new SimpleDTO(); + PowerFlagEnum enumByCode = PowerFlagEnum.getPowerFlagEnumByCode(i); + dto.setId(enumByCode.getCode().toString()); + dto.setName(enumByCode.getMessage()); + generalDeviceDTOS.add(assembleDataByLine(dto, lines, powerFlagIds, LineBaseEnum.LINE_LEVEL.getCode())); + } + + return generalDeviceDTOS; + } + + + /** + * 筛选对应等级的id + * + * @param simpleDTO 分类信息 + * @param lines 所有监测点 + * @param keyIds 待筛选的id + * @param level 待筛选的层级 + */ + private GeneralDeviceDTO assembleDataByLine(SimpleDTO simpleDTO, List lines, List keyIds, Integer level) { + GeneralDeviceDTO generalDeviceDTO = assembleData(simpleDTO); + if (CollectionUtil.isNotEmpty(keyIds)) { + List tempLines = lines.stream().filter(line -> { + String[] idsArray = line.getPids().split(","); + if (level.equals(LineBaseEnum.LINE_LEVEL.getCode())) { + return keyIds.contains(line.getId()); + } else { + return keyIds.contains(idsArray[level]); + } + }).collect(Collectors.toList()); + List gdIndexes = new ArrayList<>(), subIndexes = new ArrayList<>(), deviceIndexes = new ArrayList<>(), voltageIndexes = new ArrayList<>(), lineIndexes = new ArrayList<>(); + for (Line line : tempLines) { + String[] idsArray = line.getPids().split(","); + gdIndexes.add(idsArray[LineBaseEnum.GD_LEVEL.getCode()]); + subIndexes.add(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]); + deviceIndexes.add(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]); + voltageIndexes.add(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()]); + lineIndexes.add(line.getId()); + } + //排重,入参到终端综合体 + generalDeviceDTO.setGdIndexes(gdIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setSubIndexes(subIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setDeviceIndexes(deviceIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setVoltageIndexes(voltageIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setLineIndexes(lineIndexes.stream().distinct().collect(Collectors.toList())); + } + return generalDeviceDTO; + } + + + /** + * 当该部门不存在监测点时,返回空的分类数据 + * + * @param simpleDTO 基础数据 + * @return . + */ + private GeneralDeviceDTO assembleData(SimpleDTO simpleDTO) { + GeneralDeviceDTO generalDeviceDTO = new GeneralDeviceDTO(); + generalDeviceDTO.setName(simpleDTO.getName()); + generalDeviceDTO.setIndex(simpleDTO.getId()); + return generalDeviceDTO; + } + + /** + * 当该部门不存在监测点时,返回空的分类数据 + * + * @param simpleDTOS 分类类别 + * @return . + */ + private List assembleCommonData(List simpleDTOS) { + return simpleDTOS.stream().map(this::assembleData).collect(Collectors.toList()); + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/LineServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/LineServiceImpl.java new file mode 100644 index 0000000..4fcf198 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/LineServiceImpl.java @@ -0,0 +1,134 @@ +package com.njcn.product.device.ledger.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + + +import com.njcn.product.carrycapacity.util.PubUtils; +import com.njcn.product.device.ledger.mapper.*; +import com.njcn.product.device.ledger.pojo.po.Device; +import com.njcn.product.device.ledger.pojo.po.Line; +import com.njcn.product.device.ledger.pojo.po.LineDetail; +import com.njcn.product.device.ledger.pojo.vo.LineDetailDataVO; +import com.njcn.product.device.ledger.pojo.vo.LineOverLimitVO; +import com.njcn.product.device.ledger.service.LineService; +import com.njcn.product.device.overlimit.pojo.Overlimit; +import com.njcn.product.system.dict.service.IDictDataService; +import com.njcn.web.pojo.vo.LineDataVO; +import com.njcn.web.utils.GeneralUtil; +import com.njcn.web.utils.RequestUtil; +import com.njcn.web.utils.WebUtil; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 监测点类 + * + * @author denghuajun + * @date 2022/2/23 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class LineServiceImpl extends ServiceImpl implements LineService { + + + private final IDictDataService iDictDataService; + + private final VoltageMapper voltageMapper; + + private final LineDetailMapper lineDetailMapper; + + private final DeviceMapper deviceMapper; + + private final OverlimitMapper overlimitMapper; + + @Override + public Overlimit getOverLimitData(String id) { + return overlimitMapper.selectById(id); + } + + + @Override + public LineDetailDataVO getLineDetailData(String id) { + if (StringUtils.isEmpty(id)) { + return new LineDetailDataVO(); + } else { + //根据id查询当前信息的pids + List pids = Arrays.asList(this.baseMapper.selectById(id).getPids().split(",")); + List list = new ArrayList(pids); + list.add(id); + List lineDataVOList = this.baseMapper.getLineDetail(list); + LineDetailDataVO lineDetailDataVO = new LineDetailDataVO(); + String areaId = "", devId = "", voId = ""; + for (LineDataVO lineDataVO : lineDataVOList) { + switch (lineDataVO.getLevel()) { + case 1: + areaId = lineDataVO.getName(); + break; + case 2: + lineDetailDataVO.setGdName(lineDataVO.getName()); + break; + case 3: + lineDetailDataVO.setBdName(lineDataVO.getName()); + break; + case 4: + devId = lineDataVO.getId(); + lineDetailDataVO.setDevName(lineDataVO.getName()); + break; + case 5: + voId = lineDataVO.getId(); + break; + case 6: + lineDetailDataVO.setLineName(lineDataVO.getName()); + break; + default: + break; + } + } + lineDetailDataVO.setScale(iDictDataService.getDicDataById(voltageMapper.selectById(voId).getScale()).getName()); + LineDetail lineDetail = lineDetailMapper.selectById(id); + Device device = deviceMapper.selectById(devId); + lineDetailDataVO.setManufacturer(iDictDataService.getDicDataById(device.getManufacturer()).getName()); + lineDetailDataVO.setComFlag(PubUtils.comFlag(device.getComFlag())); + lineDetailDataVO.setRunFlag(PubUtils.lineRunFlag(lineDetail.getRunFlag())); + lineDetailDataVO.setIp(device.getIp()); + lineDetailDataVO.setLoginTime(device.getLoginTime()); + lineDetailDataVO.setDevId(device.getId()); + lineDetailDataVO.setBusinessType(iDictDataService.getDicDataById(lineDetail.getBusinessType()).getName()); + lineDetailDataVO.setLoadType(iDictDataService.getDicDataById(lineDetail.getLoadType()).getName()); + lineDetailDataVO.setObjName(lineDetail.getObjName()); + lineDetailDataVO.setId(lineDetail.getNum()); + lineDetailDataVO.setPtType(PubUtils.ptType(lineDetail.getPtType())); + lineDetailDataVO.setPt(lineDetail.getPt1() + "/" + lineDetail.getPt2()); + lineDetailDataVO.setCt(lineDetail.getCt1() + "/" + lineDetail.getCt2()); + lineDetailDataVO.setDealCapacity(lineDetail.getDealCapacity()); + lineDetailDataVO.setDevCapacity(lineDetail.getDevCapacity()); + lineDetailDataVO.setShortCapacity(lineDetail.getShortCapacity()); + lineDetailDataVO.setStandardCapacity(lineDetail.getStandardCapacity()); + lineDetailDataVO.setTimeInterval(lineDetail.getTimeInterval()); + lineDetailDataVO.setOwner(lineDetail.getOwner()); + lineDetailDataVO.setOwnerDuty(lineDetail.getOwnerDuty()); + lineDetailDataVO.setOwnerTel(lineDetail.getOwnerTel()); + lineDetailDataVO.setWiringDiagram(lineDetail.getWiringDiagram()); + lineDetailDataVO.setPtPhaseType(lineDetail.getPtPhaseType()); + lineDetailDataVO.setUpdateTime(device.getUpdateTime()); + return lineDetailDataVO; + } + + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalBaseServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalBaseServiceImpl.java new file mode 100644 index 0000000..cdfe264 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalBaseServiceImpl.java @@ -0,0 +1,135 @@ +package com.njcn.product.device.ledger.service.impl; + +import cn.afterturn.easypoi.excel.ExcelExportUtil; +import cn.afterturn.easypoi.excel.ExcelImportUtil; +import cn.afterturn.easypoi.excel.entity.ExportParams; +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.text.StrBuilder; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.common.utils.PubUtils; + +import com.njcn.product.device.ledger.mapper.*; +import com.njcn.product.device.ledger.pojo.dto.DeviceType; +import com.njcn.product.device.ledger.pojo.enums.LineBaseEnum; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.pojo.po.Device; +import com.njcn.product.device.ledger.pojo.po.Line; +import com.njcn.product.device.ledger.pojo.po.LineDetail; +import com.njcn.product.device.ledger.pojo.po.Voltage; +import com.njcn.product.device.ledger.service.TerminalBaseService; +import com.njcn.product.device.overlimit.pojo.Overlimit; +import com.njcn.product.system.dict.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.redis.utils.RedisUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ss.usermodel.Workbook; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.net.HttpURLConnection; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class TerminalBaseServiceImpl extends ServiceImpl implements TerminalBaseService { + + + + @Override + public List getLineById(List lineIds) { + return this.lambdaQuery() + .in(!CollectionUtils.isEmpty(lineIds),Line::getId, lineIds) + .eq(Line::getLevel, 6) + .eq(Line::getState, DataStateEnum.ENABLE.getCode()) + .list(); + } + + @Override + public List getLineByCondition(List ids, DeviceInfoParam deviceInfoParam) { + return this.baseMapper.getLineByCondition(ids, deviceInfoParam); + } + + + + + + @Override + public List getDeviceByCondition(List devIds, DeviceType deviceType, List manufacturer) { + return this.baseMapper.getDeviceByCondition(devIds, deviceType, manufacturer); + } + + @Override + public List getVoltageByCondition(List voltageIds, List scale) { + return this.baseMapper.getVoltageByCondition(voltageIds, scale); + } + + @Override + public List getSubByCondition(List subIds, List scale) { + return this.baseMapper.getSubByCondition(subIds, scale); + } + + @Override + public List getVoltageIdByScale(List voltageIds, String scale) { + return this.baseMapper.getVoltageIdByScale(voltageIds, scale); + } + + @Override + public List getSubIdByScale(List subIds, String scale) { + return this.baseMapper.getSubIdByScale(subIds, scale); + } + + @Override + public List getLineIdByLoadType(List lineIds, String loadType) { + return this.baseMapper.getLineIdByLoadType(lineIds, loadType); + } + + @Override + public List getDeviceIdByManufacturer(List deviceIds, String manufacturer) { + return this.baseMapper.getDeviceIdByManufacturer(deviceIds, manufacturer); + } + + @Override + public List getDeviceIdByPowerFlag(List lineIds, Integer manufacturer) { + return this.baseMapper.getDeviceIdByPowerFlag(lineIds, manufacturer); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalTreeServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalTreeServiceImpl.java new file mode 100644 index 0000000..db6b511 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/ledger/service/impl/TerminalTreeServiceImpl.java @@ -0,0 +1,158 @@ +package com.njcn.product.device.ledger.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +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.njcn.common.pojo.enums.common.ServerEnum; +import com.njcn.common.pojo.response.HttpResult; + +import com.njcn.product.device.ledger.mapper.TreeMapper; +import com.njcn.product.device.ledger.pojo.dto.GeneralDeviceDTO; +import com.njcn.product.device.ledger.pojo.dto.TerminalTree; +import com.njcn.product.device.ledger.pojo.enums.LineBaseEnum; +import com.njcn.product.device.ledger.pojo.enums.StatisticsEnum; +import com.njcn.product.device.ledger.pojo.param.DeviceInfoParam; +import com.njcn.product.device.ledger.service.TerminalTreeService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * pqs + * 终端设备树 + * + * @author cdf + * @date 2021/7/19 + */ +@Service +@AllArgsConstructor +public class TerminalTreeServiceImpl implements TerminalTreeService { + + + + private final GeneralDeviceService generalDeviceService; + + private final TreeMapper treeMapper; + + + /** + * 5层树排除设备 母线监测点合并 + * + * @author cdf + * @date 2022/1/13 + */ + /** + * 5层树排除设备 母线监测点合并 + * + * @author cdf + * @date 2022/1/13 + */ + @Override + public List getTerminalTreeForFive(DeviceInfoParam deviceInfoParam) { + //deviceInfoParam.setDeptIndex(RequestUtil.getDeptIndex()); + // 获取所有数据 + List generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList())); + // 判断所有数据集合状态 + if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) { + // 创建集合 + List taiZhang = new ArrayList<>(); + // 遍历集合 + for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) { + // 创建实体类 + TerminalTree terminalTree = new TerminalTree(); + // 判断监测点索引集合状态 + if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) { + continue; + } + // 通过供电公司索引查询省会 + List proList = treeMapper.getProvinceList(generalDeviceDTO.getGdIndexes()); + // 通过供电公司索引查询供电公司信息 + List gdList = treeMapper.getGdList(generalDeviceDTO.getGdIndexes()); + // 通过供电站索引查询供电站信息 + List subList = treeMapper.getSubList(generalDeviceDTO.getSubIndexes()); + // 通过监测点索引查询监测点信息 + List lineList = treeMapper.getLineList(generalDeviceDTO.getLineIndexes()); + + //处理变电站 + dealChildrenData(subList, lineList, true); + + //监测点前面加序号,后面不需要删除下面两行就行 + //Integer[] arr = {1}; + //subList.forEach(item->item.getChildren().forEach(it->it.setName((arr[0]++ +"_"+it.getName())))); + //处理供电公司 + dealChildrenData(gdList, subList, false); + + if (deviceInfoParam.getStatisticalType().getCode().equalsIgnoreCase(StatisticsEnum.POWER_NETWORK.getCode())) { + terminalTree.setChildren(gdList); + } else { + //还需要额外处理省会 + dealChildrenData(proList, gdList, false); + terminalTree.setChildren(proList); + } + terminalTree.setId(generalDeviceDTO.getIndex()); + terminalTree.setName(generalDeviceDTO.getName()); + terminalTree.setLevel(0); + taiZhang.add(terminalTree); + } + return taiZhang; + } else { + return new ArrayList<>(); + } + } + + /** + * 处理变电站 + * + * @param targetData + * @param childrenData + * @param isLine + */ + private void dealChildrenData(List targetData, List childrenData, boolean isLine) { + // 创建一个map集合,用于封装对象 + Map> groupLine; + if (isLine) { + // 通过stream流分组 + groupLine = childrenData.stream().collect(Collectors.groupingBy(terminalTree -> { + // 获取父id字符串,通过 逗号 分割 成一个数组 + String[] pid = terminalTree.getPids().split(","); + return pid[LineBaseEnum.SUB_LEVEL.getCode()]; + })); + } else { + groupLine = childrenData.stream().collect(Collectors.groupingBy(TerminalTree::getPid)); + } + //变电站 + targetData = targetData.stream().peek(terminalTree -> { + System.out.println(groupLine.get(terminalTree.getId())); + System.out.println(terminalTree.getId()); + List terminalTrees = groupLine.get(terminalTree.getId()).stream().sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList()); + if (isLine) { + //变电站集合 + int size = terminalTrees.stream().map(x -> { + // 获取父id字符串,通过 逗号 分割 成一个数组 + String[] pid = x.getPids().split(","); + return pid[LineBaseEnum.DEVICE_LEVEL.getCode()]; + }).distinct().collect(Collectors.toList()).size(); + + terminalTree.setName(terminalTree.getName() + "(" + size + "台装置)"); + + terminalTree.setChildren(terminalTrees); + } else { + terminalTree.setChildren(groupLine.get(terminalTree.getId())); + } + }).collect(Collectors.toList()); + } + + + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/overlimit/pojo/Overlimit.java b/carry_capacity/src/main/java/com/njcn/product/device/overlimit/pojo/Overlimit.java new file mode 100644 index 0000000..61e7099 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/overlimit/pojo/Overlimit.java @@ -0,0 +1,952 @@ +package com.njcn.product.device.overlimit.pojo; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_overlimit") +public class Overlimit implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 监测点序号 + */ + private String id; + + /** + * 频率限值 + */ + private Float freqDev; + + /** + * 电压波动 + */ + private Float voltageFluctuation; + + /** + * 电压上偏差限值 + */ + private Float voltageDev; + + /** + * 电压下偏差限值 + */ + private Float uvoltageDev; + + /** + * 三相电压不平衡度限值 + */ + private Float ubalance; + + /** + * 短时电压不平衡度限值 + */ + private Float shortUbalance; + + /** + * 闪变限值 + */ + private Float flicker; + + /** + * 电压总谐波畸变率限值 + */ + private Float uaberrance; + + /** + * 负序电流限值 + */ + private Float iNeg; + + /** + * 2次谐波电压限值 + */ + @TableField("uharm_2") + private Float uharm2; + + /** + * 3次谐波电压限值 + */ + @TableField("uharm_3") + private Float uharm3; + + /** + * 4次谐波电压限值 + */ + @TableField("uharm_4") + private Float uharm4; + + /** + * 5次谐波电压限值 + */ + @TableField("uharm_5") + private Float uharm5; + + /** + * 6次谐波电压限值 + */ + @TableField("uharm_6") + private Float uharm6; + + /** + * 7次谐波电压限值 + */ + @TableField("uharm_7") + private Float uharm7; + + /** + * 8次谐波电压限值 + */ + @TableField("uharm_8") + private Float uharm8; + + /** + * 9次谐波电压限值 + */ + @TableField("uharm_9") + private Float uharm9; + + /** + * 10次谐波电压限值 + */ + @TableField("uharm_10") + private Float uharm10; + + /** + * 11次谐波电压限值 + */ + @TableField("uharm_11") + private Float uharm11; + + /** + * 12次谐波电压限值 + */ + @TableField("uharm_12") + private Float uharm12; + + /** + * 13次谐波电压限值 + */ + @TableField("uharm_13") + private Float uharm13; + + /** + * 14次谐波电压限值 + */ + @TableField("uharm_14") + private Float uharm14; + + /** + * 15次谐波电压限值 + */ + @TableField("uharm_15") + private Float uharm15; + + /** + * 16次谐波电压限值 + */ + @TableField("uharm_16") + private Float uharm16; + + /** + * 17次谐波电压限值 + */ + @TableField("uharm_17") + private Float uharm17; + + /** + * 18次谐波电压限值 + */ + @TableField("uharm_18") + private Float uharm18; + + /** + * 19次谐波电压限值 + */ + @TableField("uharm_19") + private Float uharm19; + + /** + * 20次谐波电压限值 + */ + @TableField("uharm_20") + private Float uharm20; + + /** + * 21次谐波电压限值 + */ + @TableField("uharm_21") + private Float uharm21; + + /** + * 22次谐波电压限值 + */ + @TableField("uharm_22") + private Float uharm22; + + /** + * 23次谐波电压限值 + */ + @TableField("uharm_23") + private Float uharm23; + + /** + * 24次谐波电压限值 + */ + @TableField("uharm_24") + private Float uharm24; + + /** + * 25次谐波电压限值 + */ + @TableField("uharm_25") + private Float uharm25; + + /** + * 2次谐波电压限值 + */ + @TableField("uharm_26") + private Float uharm26; + + /** + * 3次谐波电压限值 + */ + @TableField("uharm_27") + private Float uharm27; + + /** + * 4次谐波电压限值 + */ + @TableField("uharm_28") + private Float uharm28; + + /** + * 5次谐波电压限值 + */ + @TableField("uharm_29") + private Float uharm29; + + /** + * 6次谐波电压限值 + */ + @TableField("uharm_30") + private Float uharm30; + + /** + * 7次谐波电压限值 + */ + @TableField("uharm_31") + private Float uharm31; + + /** + * 8次谐波电压限值 + */ + @TableField("uharm_32") + private Float uharm32; + + /** + * 9次谐波电压限值 + */ + @TableField("uharm_33") + private Float uharm33; + + /** + * 10次谐波电压限值 + */ + @TableField("uharm_34") + private Float uharm34; + + /** + * 11次谐波电压限值 + */ + @TableField("uharm_35") + private Float uharm35; + + /** + * 12次谐波电压限值 + */ + @TableField("uharm_36") + private Float uharm36; + + /** + * 13次谐波电压限值 + */ + @TableField("uharm_37") + private Float uharm37; + + /** + * 14次谐波电压限值 + */ + @TableField("uharm_38") + private Float uharm38; + + /** + * 15次谐波电压限值 + */ + @TableField("uharm_39") + private Float uharm39; + + /** + * 16次谐波电压限值 + */ + @TableField("uharm_40") + private Float uharm40; + + /** + * 17次谐波电压限值 + */ + @TableField("uharm_41") + private Float uharm41; + + /** + * 18次谐波电压限值 + */ + @TableField("uharm_42") + private Float uharm42; + + /** + * 19次谐波电压限值 + */ + @TableField("uharm_43") + private Float uharm43; + + /** + * 20次谐波电压限值 + */ + @TableField("uharm_44") + private Float uharm44; + + /** + * 21次谐波电压限值 + */ + @TableField("uharm_45") + private Float uharm45; + + /** + * 22次谐波电压限值 + */ + @TableField("uharm_46") + private Float uharm46; + + /** + * 23次谐波电压限值 + */ + @TableField("uharm_47") + private Float uharm47; + + /** + * 24次谐波电压限值 + */ + @TableField("uharm_48") + private Float uharm48; + + /** + * 25次谐波电压限值 + */ + @TableField("uharm_49") + private Float uharm49; + + /** + * 50次谐波电压限值 + */ + @TableField("uharm_50") + private Float uharm50; + + + + /** + * 2次谐波电流限值 + */ + @TableField("iharm_2") + private Float iharm2; + + /** + * 3次谐波电流限值 + */ + @TableField("iharm_3") + private Float iharm3; + + /** + * 4次谐波电流限值 + */ + @TableField("iharm_4") + private Float iharm4; + + /** + * 5次谐波电流限值 + */ + @TableField("iharm_5") + private Float iharm5; + + /** + * 6次谐波电流限值 + */ + @TableField("iharm_6") + private Float iharm6; + + /** + * 7次谐波电流限值 + */ + @TableField("iharm_7") + private Float iharm7; + + /** + * 8次谐波电流限值 + */ + @TableField("iharm_8") + private Float iharm8; + + /** + * 9次谐波电流限值 + */ + @TableField("iharm_9") + private Float iharm9; + + /** + * 10次谐波电流限值 + */ + @TableField("iharm_10") + private Float iharm10; + + /** + * 11次谐波电流限值 + */ + @TableField("iharm_11") + private Float iharm11; + + /** + * 12次谐波电流限值 + */ + @TableField("iharm_12") + private Float iharm12; + + /** + * 13次谐波电流限值 + */ + @TableField("iharm_13") + private Float iharm13; + + /** + * 14次谐波电流限值 + */ + @TableField("iharm_14") + private Float iharm14; + + /** + * 15次谐波电流限值 + */ + @TableField("iharm_15") + private Float iharm15; + + /** + * 16次谐波电流限值 + */ + @TableField("iharm_16") + private Float iharm16; + + /** + * 17次谐波电流限值 + */ + @TableField("iharm_17") + private Float iharm17; + + /** + * 18次谐波电流限值 + */ + @TableField("iharm_18") + private Float iharm18; + + /** + * 19次谐波电流限值 + */ + @TableField("iharm_19") + private Float iharm19; + + /** + * 20次谐波电流限值 + */ + @TableField("iharm_20") + private Float iharm20; + + /** + * 21次谐波电流限值 + */ + @TableField("iharm_21") + private Float iharm21; + + /** + * 22次谐波电流限值 + */ + @TableField("iharm_22") + private Float iharm22; + + /** + * 23次谐波电流限值 + */ + @TableField("iharm_23") + private Float iharm23; + + /** + * 24次谐波电流限值 + */ + @TableField("iharm_24") + private Float iharm24; + + /** + * 25次谐波电流限值 + */ + @TableField("iharm_25") + private Float iharm25; + + /** + * 2次谐波电压限值 + */ + @TableField("iharm_26") + private Float iharm26; + + /** + * 3次谐波电压限值 + */ + @TableField("iharm_27") + private Float iharm27; + + /** + * 4次谐波电压限值 + */ + @TableField("iharm_28") + private Float iharm28; + + /** + * 5次谐波电压限值 + */ + @TableField("iharm_29") + private Float iharm29; + + /** + * 6次谐波电压限值 + */ + @TableField("iharm_30") + private Float iharm30; + + /** + * 7次谐波电压限值 + */ + @TableField("iharm_31") + private Float iharm31; + + /** + * 8次谐波电压限值 + */ + @TableField("iharm_32") + private Float iharm32; + + /** + * 9次谐波电压限值 + */ + @TableField("iharm_33") + private Float iharm33; + + /** + * 10次谐波电压限值 + */ + @TableField("iharm_34") + private Float iharm34; + + /** + * 11次谐波电压限值 + */ + @TableField("iharm_35") + private Float iharm35; + + /** + * 12次谐波电压限值 + */ + @TableField("iharm_36") + private Float iharm36; + + /** + * 13次谐波电压限值 + */ + @TableField("iharm_37") + private Float iharm37; + + /** + * 14次谐波电压限值 + */ + @TableField("iharm_38") + private Float iharm38; + + /** + * 15次谐波电压限值 + */ + @TableField("iharm_39") + private Float iharm39; + + /** + * 16次谐波电压限值 + */ + @TableField("iharm_40") + private Float iharm40; + + /** + * 17次谐波电压限值 + */ + @TableField("iharm_41") + private Float iharm41; + + /** + * 18次谐波电压限值 + */ + @TableField("iharm_42") + private Float iharm42; + + /** + * 19次谐波电压限值 + */ + @TableField("iharm_43") + private Float iharm43; + + /** + * 20次谐波电压限值 + */ + @TableField("iharm_44") + private Float iharm44; + + /** + * 21次谐波电压限值 + */ + @TableField("iharm_45") + private Float iharm45; + + /** + * 22次谐波电压限值 + */ + @TableField("iharm_46") + private Float iharm46; + + /** + * 23次谐波电压限值 + */ + @TableField("iharm_47") + private Float iharm47; + + /** + * 24次谐波电压限值 + */ + @TableField("iharm_48") + private Float iharm48; + + /** + * 25次谐波电压限值 + */ + @TableField("iharm_49") + private Float iharm49; + + /** + * 50次谐波电压限值 + */ + @TableField("iharm_50") + private Float iharm50; + + + + /** + * 0.5次间谐波电压限值 + */ + @TableField("inuharm_1") + private Float inuharm1; + + /** + * 1.5次间谐波电压限值 + */ + @TableField("inuharm_2") + private Float inuharm2; + + /** + * 2.5次间谐波电压限值 + */ + @TableField("inuharm_3") + private Float inuharm3; + + /** + * 3.5次间谐波电压限值 + */ + @TableField("inuharm_4") + private Float inuharm4; + + /** + * 4.5次间谐波电压限值 + */ + @TableField("inuharm_5") + private Float inuharm5; + + /** + * 5.5次间谐波电压限值 + */ + @TableField("inuharm_6") + private Float inuharm6; + + /** + * 6.5次间谐波电压限值 + */ + @TableField("inuharm_7") + private Float inuharm7; + + /** + * 7.5次间谐波电压限值 + */ + @TableField("inuharm_8") + private Float inuharm8; + + /** + * 8.5次间谐波电压限值 + */ + @TableField("inuharm_9") + private Float inuharm9; + + /** + * 9.5次间谐波电压限值 + */ + @TableField("inuharm_10") + private Float inuharm10; + + /** + * 10.5次间谐波电压限值 + */ + @TableField("inuharm_11") + private Float inuharm11; + + /** + * 11.5次间谐波电压限值 + */ + @TableField("inuharm_12") + private Float inuharm12; + + /** + * 12.5次间谐波电压限值 + */ + @TableField("inuharm_13") + private Float inuharm13; + + /** + * 13.5次间谐波电压限值 + */ + @TableField("inuharm_14") + private Float inuharm14; + + /** + * 14.5次间谐波电压限值 + */ + @TableField("inuharm_15") + private Float inuharm15; + + /** + * 15.5次间谐波电压限值 + */ + @TableField("inuharm_16") + private Float inuharm16; + + public Overlimit(){} + + +// public Overlimit(String lineId, String scaTmp, float fDLRL, float fJZRL, float fXYRL, float fSBRL){ +// float[] fLimit = COverlimit.GetOverLimit(scaTmp, fDLRL, fJZRL, fXYRL, fSBRL); +// this.id=lineId; +// this.freqDev=fLimit[0]; +// this.voltageDev=fLimit[1]; +// this.ubalance=fLimit[2]; +// this.flicker=fLimit[3]; +// this.uaberrance=fLimit[4]; +// this.uharm2=fLimit[5]; +// this.uharm3=fLimit[6]; +// this.uharm4=fLimit[7]; +// this.uharm5=fLimit[8]; +// this.uharm6=fLimit[9]; +// this.uharm7=fLimit[10]; +// this.uharm8=fLimit[11]; +// this.uharm9=fLimit[12]; +// this.uharm10=fLimit[13]; +// this.uharm11=fLimit[14]; +// this.uharm12=fLimit[15]; +// this.uharm13=fLimit[16]; +// this.uharm14=fLimit[17]; +// this.uharm15=fLimit[18]; +// this.uharm16=fLimit[19]; +// this.uharm17=fLimit[20]; +// this.uharm18=fLimit[21]; +// this.uharm19=fLimit[22]; +// this.uharm20=fLimit[23]; +// this.uharm21=fLimit[24]; +// this.uharm22=fLimit[25]; +// this.uharm23=fLimit[26]; +// this.uharm24=fLimit[27]; +// this.uharm25=fLimit[28]; +// this.iharm2=fLimit[29]; +// this.iharm3=fLimit[30]; +// this.iharm4=fLimit[31]; +// this.iharm5=fLimit[32]; +// this.iharm6=fLimit[33]; +// this.iharm7=fLimit[34]; +// this.iharm8=fLimit[35]; +// this.iharm9=fLimit[36]; +// this.iharm10=fLimit[37]; +// this.iharm11=fLimit[38]; +// this.iharm12=fLimit[39]; +// this.iharm13=fLimit[40]; +// this.iharm14=fLimit[41]; +// this.iharm15=fLimit[42]; +// this.iharm16=fLimit[43]; +// this.iharm17=fLimit[44]; +// this.iharm18=fLimit[45]; +// this.iharm19=fLimit[46]; +// this.iharm20=fLimit[47]; +// this.iharm21=fLimit[48]; +// this.iharm22=fLimit[49]; +// this.iharm23=fLimit[50]; +// this.iharm24=fLimit[51]; +// this.iharm25=fLimit[52]; +// this.uvoltageDev=fLimit[53]; +// this.iNeg=fLimit[54]; +// this.inuharm1=fLimit[55]; +// this.inuharm2=fLimit[56]; +// this.inuharm3=fLimit[57]; +// this.inuharm4=fLimit[58]; +// this.inuharm5=fLimit[59]; +// this.inuharm6=fLimit[60]; +// this.inuharm7=fLimit[61]; +// this.inuharm8=fLimit[62]; +// this.inuharm9=fLimit[63]; +// this.inuharm10=fLimit[64]; +// this.inuharm11=fLimit[65]; +// this.inuharm12=fLimit[66]; +// this.inuharm13=fLimit[67]; +// this.inuharm14=fLimit[68]; +// this.inuharm15=fLimit[69]; +// this.inuharm16=fLimit[70]; +// } + + public void buildIHarm(Float[] iHarmTem){ + this.iharm2= iHarmTem[0]; + this.iharm4= iHarmTem[2]; + this.iharm6= iHarmTem[4]; + this.iharm8= iHarmTem[6]; + this.iharm10= iHarmTem[8]; + this.iharm12= iHarmTem[10]; + this.iharm14= iHarmTem[12]; + this.iharm16= iHarmTem[14]; + this.iharm18= iHarmTem[16]; + this.iharm20= iHarmTem[18]; + this.iharm22= iHarmTem[20]; + this.iharm24= iHarmTem[22]; + this.iharm26= iHarmTem[24]; + this.iharm28= iHarmTem[26]; + this.iharm30= iHarmTem[28]; + this.iharm32= iHarmTem[30]; + this.iharm34= iHarmTem[32]; + this.iharm36= iHarmTem[34]; + this.iharm38= iHarmTem[36]; + this.iharm40= iHarmTem[38]; + this.iharm42= iHarmTem[40]; + this.iharm44= iHarmTem[42]; + this.iharm46= iHarmTem[44]; + this.iharm48= iHarmTem[46]; + this.iharm50= iHarmTem[48]; + + + + this.iharm3= iHarmTem[1]; + this.iharm5= iHarmTem[3]; + this.iharm7= iHarmTem[5]; + this.iharm9= iHarmTem[7]; + this.iharm11= iHarmTem[9]; + this.iharm13= iHarmTem[11]; + this.iharm15= iHarmTem[13]; + this.iharm17= iHarmTem[15]; + this.iharm19= iHarmTem[17]; + this.iharm21= iHarmTem[19]; + this.iharm23= iHarmTem[21]; + this.iharm25= iHarmTem[23]; + this.iharm27= iHarmTem[25]; + this.iharm29= iHarmTem[27]; + this.iharm31= iHarmTem[29]; + this.iharm33= iHarmTem[31]; + this.iharm35= iHarmTem[33]; + this.iharm37= iHarmTem[35]; + this.iharm39= iHarmTem[37]; + this.iharm41= iHarmTem[39]; + this.iharm43= iHarmTem[41]; + this.iharm45= iHarmTem[43]; + this.iharm47= iHarmTem[45]; + this.iharm49= iHarmTem[47]; + } + + public void buildUharm(Float resultEven,Float resultOdd){ + this.uharm2=resultEven; + this.uharm4=resultEven; + this.uharm6=resultEven; + this.uharm8=resultEven; + this.uharm10=resultEven; + this.uharm12=resultEven; + this.uharm14=resultEven; + this.uharm16=resultEven; + this.uharm18=resultEven; + this.uharm20=resultEven; + this.uharm22=resultEven; + this.uharm24=resultEven; + this.uharm26=resultEven; + this.uharm28=resultEven; + this.uharm30=resultEven; + this.uharm32=resultEven; + this.uharm34=resultEven; + this.uharm36=resultEven; + this.uharm38=resultEven; + this.uharm40=resultEven; + this.uharm42=resultEven; + this.uharm44=resultEven; + this.uharm46=resultEven; + this.uharm48=resultEven; + this.uharm50=resultEven; + + + this.uharm3=resultOdd; + this.uharm5=resultOdd; + this.uharm7=resultOdd; + this.uharm9=resultOdd; + this.uharm11=resultOdd; + this.uharm13=resultOdd; + this.uharm15=resultOdd; + this.uharm17=resultOdd; + this.uharm19=resultOdd; + this.uharm21=resultOdd; + this.uharm23=resultOdd; + this.uharm25=resultOdd; + this.uharm27=resultOdd; + this.uharm29=resultOdd; + this.uharm31=resultOdd; + this.uharm33=resultOdd; + this.uharm35=resultOdd; + this.uharm37=resultOdd; + this.uharm39=resultOdd; + this.uharm41=resultOdd; + this.uharm43=resultOdd; + this.uharm45=resultOdd; + this.uharm47=resultOdd; + this.uharm49=resultOdd; + } + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/device/overlimit/util/COverlimitUtil.java b/carry_capacity/src/main/java/com/njcn/product/device/overlimit/util/COverlimitUtil.java new file mode 100644 index 0000000..db319b9 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/device/overlimit/util/COverlimitUtil.java @@ -0,0 +1,382 @@ +package com.njcn.product.device.overlimit.util; + + + +import com.njcn.product.device.overlimit.pojo.Overlimit; +import com.njcn.product.system.dict.enums.DicDataEnum; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * pqs + * 限值计算工具类 + * + * @author cdf + * @date 2023/5/15 + */ +public class COverlimitUtil { + + + /** + * 谐波电流系数 + */ + private static final double[][] ARR = { + {78, 62, 39, 62, 26, 44, 19, 21, 16, 28, 13, 24, 11, 12, 9.7, 18, 8.6, 16, 7.8, 8.9, 7.1, 14, 6.5, 12, 6.0, 6.9, 5.6, 11, 5.2, 10, 4.9, 5.6, 4.6, 8.9, 4.3, 8.4, 4.1, 4.8, 3.9, 7.6, 3.7, 7.2, 3.5, 4.1, 3.4, 6.6, 3.3, 6.3, 3.1}, + {43, 34, 21, 34, 14, 24, 11, 11, 8.5, 16, 7.1, 13, 6.1, 6.8, 5.3, 10, 4.7, 9, 4.3, 4.9, 3.9, 7.4, 3.6, 6.8, 3.3, 3.8, 3.1, 5.9, 2.9, 5.5, 2.7, 3.1, 2.5, 4.9, 2.4, 4.6, 2.3, 2.6, 2.2, 4.1, 2.0, 4.0, 2.0, 2.3, 1.9, 3.6, 1.8, 3.5, 1.7}, + {26, 20, 13, 20, 8.5, 15, 6.4, 6.8, 5.1, 9.3, 4.3, 7.9, 3.7, 4.1, 3.2, 6, 2.8, 5.4, 2.6, 2.9, 2.3, 4.5, 2.1, 4.1, 2.0, 2.2, 1.9, 3.4, 1.7, 3.2, 1.6, 1.8, 1.5, 2.9, 1.4, 2.7, 1.4, 1.5, 1.3, 2.4, 1.2, 2.3, 1.2, 1.3, 1.1, 2.1, 1.1, 2.0, 1.0}, + {15, 12, 7.7, 12, 5.1, 8.8, 3.8, 4.1, 3.1, 5.6, 2.6, 4.7, 2.2, 2.5, 1.9, 3.6, 1.7, 3.2, 1.5, 1.8, 1.4, 2.7, 1.3, 2.5, 1.2, 1.3, 1.1, 2.1, 1.0, 1.9, 0.9, 1.1, 0.9, 1.7, 0.8, 1.6, 0.8, 0.9, 0.8, 1.5, 0.7, 1.4, 0.7, 0.8, 0.7, 1.3, 0.6, 1.2, 0.6}, + {16, 13, 8.1, 13, 5.4, 9.3, 4.1, 4.3, 3.3, 5.9, 2.7, 5, 2.3, 2.6, 2, 3.8, 1.8, 3.4, 1.6, 1.9, 1.5, 2.8, 1.4, 2.6, 1.2, 1.4, 1.1, 2.2, 1.1, 2.1, 1.0, 1.2, 0.9, 1.9, 0.9, 1.8, 0.8, 1.0, 0.8, 1.6, 0.8, 1.5, 0.7, 0.9, 0.7, 1.4, 0.7, 1.3, 0.6}, + {12, 9.6, 6, 9.6, 4, 6.8, 3, 3.2, 2.4, 4.3, 2, 3.7, 1.7, 1.9, 1.5, 2.8, 1.3, 2.5, 1.2, 1.4, 1.1, 2.1, 1, 1.9, 0.9, 1.1, 0.9, 1.7, 0.8, 1.5, 0.8, 0.9, 0.7, 1.4, 0.7, 1.3, 0.6, 0.7, 0.6, 1.2, 0.6, 1.1, 0.5, 0.6, 0.5, 1.0, 0.5, 1.0, 0.5} + }; + + + /** + * 计算监测点限值 + * @param voltageLevel 电压等级(10kV = 10 220kV = 220 ) + * @param protocolCapacity 协议容量 + * @param devCapacity 设备容量 + * @param shortCapacity 短路容量 + * @param powerFlag 0.用户侧 1.电网侧 + * @param lineType 0.主网 1.配网 需要注意配网目前没有四种容量,谐波电流幅值限值,负序电流限值无法计算默认-3.14159 + */ + public static Overlimit globalAssemble(Float voltageLevel, Float protocolCapacity, Float devCapacity, + Float shortCapacity, Integer powerFlag, Integer lineType) { + Overlimit overlimit = new Overlimit(); + voltageDeviation(overlimit,voltageLevel); + frequency(overlimit); + voltageFluctuation(overlimit,voltageLevel); + voltageFlicker(overlimit,voltageLevel); + totalHarmonicDistortion(overlimit,voltageLevel); + uHarm(overlimit,voltageLevel); + threeVoltageUnbalance(overlimit); + interharmonicCurrent(overlimit,voltageLevel); + + if(lineType == 1) { + //配网 + Float[] iHarmTem = new Float[49]; + for (int i = 0; i <= 48; i++) { + + iHarmTem[i] = -3.14159f; + } + overlimit.buildIHarm(iHarmTem); + overlimit.setINeg(-3.14159f); + }else { + //主网 + iHarm(overlimit, voltageLevel, protocolCapacity, devCapacity, shortCapacity); + negativeSequenceCurrent(overlimit, voltageLevel, shortCapacity); + } + return overlimit; + } + + + /** + * 电压偏差限值 + * + */ + public static void voltageDeviation(Overlimit overlimit,Float voltageLevel) { + float voltageDev = 3.14159f,uvoltageDev = 3.14159f; + if(voltageLevel <= Float.parseFloat(DicDataEnum.V220.getCode())){ + voltageDev = 7.0f; + uvoltageDev=-10.0f; + }else if(voltageLevel>Float.parseFloat(DicDataEnum.V220.getCode())&&voltageLevel=Float.parseFloat(DicDataEnum.KV20.getCode())&&voltageLevel=Float.parseFloat(DicDataEnum.KV35.getCode())&&voltageLevel=Float.parseFloat(DicDataEnum.KV66.getCode())&&voltageLevel<=Float.parseFloat(DicDataEnum.KV110.getCode())){ + voltageDev = 7.0f; + uvoltageDev=-3.0f; + }else if(voltageLevel>Float.parseFloat(DicDataEnum.KV110.getCode())){ + voltageDev = 10.0f; + uvoltageDev=-10.0f; + } + overlimit.setVoltageDev(voltageDev); + overlimit.setUvoltageDev(uvoltageDev); + } + + + /** + * 频率偏差 + * 默认限值:±0.2Hz(即:-0.2 Hz≤限值≤0.2 Hz) + */ + public static void frequency(Overlimit overlimit) { + overlimit.setFreqDev(0.2f); + } + + + /** + * 电压波动 + * 对LV、MV:0≤限值≤3%;对HV:0≤限值≤2.5%。 + * LV、MV、HV的定义: + * 低压(LV) UN≤1kV + * 中压(MV) 1kV<UN≤35kV + * 高压(HV) 35kV<UN≤220kV + * 超高压(EHV),220kV<UN,参照HV执行 + */ + public static void voltageFluctuation(Overlimit overlimit, Float voltageLevel) { + if (voltageLevel < Float.parseFloat(DicDataEnum.KV35.getCode())) { + overlimit.setVoltageFluctuation(3.0f); + } else { + overlimit.setVoltageFluctuation(2.5f); + } + } + + + + /** + * 电压闪变 + * ≤110kV 1 + * >110kV 0.8 + */ + public static void voltageFlicker(Overlimit overlimit, Float voltageLevel) { + if (voltageLevel <= Float.parseFloat(DicDataEnum.KV110.getCode())) { + overlimit.setFlicker(1.0f); + } else { + overlimit.setFlicker(0.8f); + } + } + + + /** + * 总谐波电压畸变率 + * + * + */ + public static void totalHarmonicDistortion(Overlimit overlimit, Float voltageLevel) { + float result = 3.14159f; + if (voltageLevel < Float.parseFloat(DicDataEnum.KV6.getCode())) { + result = 5.0f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV6.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV20.getCode())){ + result = 4.0f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV35.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV66.getCode())){ + result = 3.0f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV110.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV1000.getCode())){ + result = 2.0f; + } + overlimit.setUaberrance(result); + } + + + + /** + * 谐波电压含有率 + */ + public static void uHarm(Overlimit overlimit, Float voltageLevel) { + float resultOdd = 3.14159f,resultEven = 3.14159f; + if (voltageLevel < Float.parseFloat(DicDataEnum.KV6.getCode())) { + resultOdd = 4.0f; + resultEven = 2.0f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV6.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV20.getCode())){ + resultOdd = 3.2f; + resultEven = 1.6f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV35.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV66.getCode())){ + resultOdd = 2.4f; + resultEven = 1.2f; + } else if(voltageLevel >= Float.parseFloat(DicDataEnum.KV110.getCode()) && voltageLevel <= Float.parseFloat(DicDataEnum.KV1000.getCode())){ + resultOdd = 1.6f; + resultEven = 0.8f; + } + overlimit.buildUharm(resultEven,resultOdd); + } + + + /** + * 负序电压不平衡(三相电压不平衡度) + * + */ + public static void threeVoltageUnbalance(Overlimit overlimit) { + overlimit.setUbalance(2.0f); + overlimit.setShortUbalance(4.0f); + } + + + /*---------------------------------谐波电流限值start-----------------------------------*/ + + /** + * 谐波电流限值 + */ + public static void iHarm(Overlimit overlimit, Float voltageLevel,Float protocolCapacity,Float devCapacity,Float shortCapacity) { + float calCap = shortCapacity/getDlCapByVoltageLevel(voltageLevel); + //24谐波电流幅值 + Float[] iHarmTem = new Float[49]; + for (int i = 0; i <= 48; i++) { + float inHarm = iHarmCalculate(i+2,voltageLevel,protocolCapacity,devCapacity,calCap); + iHarmTem[i] = inHarm; + } + overlimit.buildIHarm(iHarmTem); + } + /** + * @Description: iHarmCalculate + * @Param: protocolCapacity 协议容量 devCapacity设备容量 calCap 短路容量 + * @return: float + * @Author: clam + * @Date: 2024/2/4 + */ + private static float iHarmCalculate(int nHarm, Float voltageLevel,float protocolCapacity, float devCapacity,float calCap) { + double tag = calCap*getHarmTag(nHarm,voltageLevel); + Double limit = getHarmonicLimit(nHarm,tag,new BigDecimal(String.valueOf(devCapacity)).doubleValue(),new BigDecimal(String.valueOf(protocolCapacity)).doubleValue()); + BigDecimal bigDecimal = BigDecimal.valueOf(limit).setScale(4,RoundingMode.HALF_UP); + return bigDecimal.floatValue(); + } + + + /** + * 电流谐波限值 + */ + private static Double getHarmTag(Integer iCount, Float voltageLevel) { + int x, y; + if (voltageLevel < DicDataEnum.KV6.getValue()) { + x = 0; + } else if (voltageLevel + * 前端控制器(行政区域) + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@RestController +@RequestMapping("/area") +@Api(tags = "行政区域管理") +@AllArgsConstructor +public class AreaController extends BaseController { + + private final IAreaService areaService; + + + /** + * 根据行政区域id详情 + * + * @param id 行政区域id + * @return 行政区域详情 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/selectIdArea/{id}") + @ApiOperation("根据行政区域id查询详情") + @ApiImplicitParam(name = "id", value = "查询参数", required = true) + public HttpResult selectIdArea(@PathVariable("id") String id) { + String methodDescribe = getMethodDescribe("selectIdArea"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, id); + Area result = areaService.selectIdArea(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + /** + * 根据行政区域id详情 + * + * @param list 行政区域id集合 + * @return 行政区域详情 + */ + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/areaNameByList") + @ApiOperation("根据行政区域id集合查询名称") + @ApiImplicitParam(name = "list", value = "查询参数", required = true) + public HttpResult> areaNameByList(@RequestBody List list) { + String methodDescribe = getMethodDescribe("areaNameByList"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, list); + List result = areaService.selectAreaByList(list); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + + /** + * 新增企业区域 + * + * @param areaParam 企业区域 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增企业区域") + @ApiImplicitParam(name = "areaParam", value = "企业区域数据", required = true) + public HttpResult add(@RequestBody @Validated AreaParam areaParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},字典类型数据为:{}", methodDescribe, areaParam); + boolean result = areaService.addAreaParam(areaParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 修改企业区域 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改企业区域") + @ApiImplicitParam(name = "updateParam", value = "企业区域", required = true) + public HttpResult update(@RequestBody @Validated AreaParam.AreaUpdateParam updateParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},字典数据为:{}", methodDescribe, updateParam); + boolean result = areaService.updateArea(updateParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 根据选中的行政区域id查询是否含有子节点 + * + * @param ids 行政区域ids + * @return 行政区域查看所有子节点 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/selectPid") + @ApiOperation("根据行政区域id查询") + @ApiImplicitParam(name = "ids", value = "查询参数", required = true) + public HttpResult selectPid(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("selectPid"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, ids); + List result = areaService.selectPid(ids); + if (!result.isEmpty()) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.DELETE_PID_EXIST, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.DELETE_PID_UNEXIST, null, methodDescribe); + } + + } + + /** + * 批量删除企业区域 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) + @PostMapping("/delete") + @ApiOperation("删除企业区域") + @ApiImplicitParam(name = "ids", value = "企业区域索引", required = true) + public HttpResult delete(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},企业区域数据为:{}", methodDescribe, ids); + boolean result = areaService.deleteArea(ids); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + + + /** + * 根据区域id获取省份 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/areaPro") + @ApiOperation("根据区域id获取省份") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "区域id"), + @ApiImplicitParam(name = "type", value = "区域类型", required = true) + }) + public HttpResult areaPro(@RequestParam(required = false) @ApiParam("id") String id, @RequestParam("type") Integer type) { + String methodDescribe = getMethodDescribe("areaDeptTree"); + Area result = areaService.areaPro(id, type); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + /** + * 根据行政区域名称查询详细 + * + * @param name 行政区域名称 + * @return 行政区域详情 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/selectAreaByName/{name}") + @ApiOperation("根据行政区域名称查询详细") + @ApiImplicitParam(name = "name", value = "查询参数", required = true) + public HttpResult selectAreaByName(@PathVariable("name") String name) { + String methodDescribe = getMethodDescribe("selectAreaByName"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, name); + Area result = areaService.selectAreaByName(name); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + /** + * 根据部门id获取省份 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/areaDeptPro") + @ApiOperation("根据区域id获取省份") + @ApiImplicitParam(name = "id", value = "部门id") + public HttpResult areaDeptPro(@RequestParam(required = false) @ApiParam("id") String id) { + String methodDescribe = getMethodDescribe("areaDeptTree"); + Area result = areaService.areaDeptPro(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + /** + * @description 获取省市区下拉框 + * @author clam + * @date 2023/4/11 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/areaSelect") + @ApiOperation("获取省市区下拉框") + public HttpResult> areaSelect() { + String methodDescribe = getMethodDescribe("areaSelect"); + List result = areaService.areaSelect(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + /** + * 获取指定区域父级的子级区域集合 + * @author cdf + * @date 2023/10/25 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/getPidAreaList") + @ApiOperation("获取指定区域父级的子级区域集合") + @ApiImplicitParams({ + @ApiImplicitParam(name = "areaId",value = "区域id"), + @ApiImplicitParam(name = "type", value = "区域类型", required = true) + }) + public HttpResult> getPidAreaList(@RequestParam("areaId")String areaId , @RequestParam("type") Integer type) { + String methodDescribe = getMethodDescribe("getPidAreaList"); + List result = areaService.getPidAreaList(areaId,type); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/controller/DeptController.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/controller/DeptController.java new file mode 100644 index 0000000..228848e --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/controller/DeptController.java @@ -0,0 +1,69 @@ +package com.njcn.product.system.dept.controller; + + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.lang.tree.Tree; +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.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.common.utils.LogUtil; + +import com.njcn.product.system.dept.pojo.dto.DeptDTO; +import com.njcn.product.system.dept.pojo.po.Dept; +import com.njcn.product.system.dept.pojo.vo.DeptTreeVO; +import com.njcn.product.system.dept.service.IDeptService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.*; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import java.util.List; +import java.util.Objects; + +/** + *

+ * 前端控制器(部门信息) + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/dept") +@Api(tags = "部门管理") +@AllArgsConstructor +public class DeptController extends BaseController { + + private final IDeptService deptService; + + + + /** + * 获取部门树 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/deptTree") + @ApiOperation("部门信息树") + public HttpResult deptTree() { + String methodDescribe = getMethodDescribe("deptTree"); + List result = deptService.deptTree(); + //删除返回失败,查不到数据返回空数组,兼容治理项目没有部门直接报错的bug + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + + } + + + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/AreaMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/AreaMapper.java new file mode 100644 index 0000000..903d4b9 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/AreaMapper.java @@ -0,0 +1,69 @@ +package com.njcn.product.system.dept.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.system.dept.pojo.dto.AreaTreeDTO; +import com.njcn.product.system.dept.pojo.po.Area; +import com.njcn.product.system.dept.pojo.vo.AreaTreeVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface AreaMapper extends BaseMapper { + + /** + * + * @return 行政区域树(首次) + */ + List getAreaTree(@Param("id")String id,@Param("type") Integer type,@Param("state")Integer state); + + /** + * + * @return 行政区域树(首次) + */ + List getAreaIdTree(@Param("type") Integer type, @Param("state")Integer state); + + /** + * 查询父节点的所有上层节点 + * @param id + * @return 父节点的所有上层节点 + */ + String getIdString(@Param("id")String id); + + /** + * + * @param ids id + * @param state 状态 + * @return 返回的结果 + */ + List selectPid(@Param("ids")List ids,@Param("state")Integer state); + + + /** + * + * @return 行政区域树(首次) + */ + List getAreaDeptTree(@Param("id")String id, @Param("type") Integer type, @Param("state")Integer state); + + /** + * 查询所有区域 + * @return 结果 + */ + List getAreaAll(); + + /** + * 根据部门id获取区域详情 + * @param id 部门id + * @return 结果 + */ + Area areaDeptProDetail(@Param("id")String id); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/DeptMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/DeptMapper.java new file mode 100644 index 0000000..017ade7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/DeptMapper.java @@ -0,0 +1,35 @@ +package com.njcn.product.system.dept.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.dept.pojo.dto.DeptDTO; +import com.njcn.product.system.dept.pojo.po.Dept; +import com.njcn.product.system.dept.pojo.vo.DeptTreeVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface DeptMapper extends BaseMapper { + + /** + * 根据条件获取后代部门索引 + * @param id 部门id + * @param type 指定部门类型 + * @return 后代部门索引 + */ + List getDeptDescendantIndexes(@Param("id")String id, @Param("type")List type); + + /** + * + * @return 部门树 + */ + List getDeptTree(@Param("id")String id, @Param("type")List type); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/AreaMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/AreaMapper.xml new file mode 100644 index 0000000..ec2dc85 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/AreaMapper.xml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/DeptMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/DeptMapper.xml new file mode 100644 index 0000000..63f4f7d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/mapper/mapping/DeptMapper.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/AreaTreeDTO.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/AreaTreeDTO.java new file mode 100644 index 0000000..e1529a8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/AreaTreeDTO.java @@ -0,0 +1,20 @@ +package com.njcn.product.system.dept.pojo.dto; + +import com.njcn.web.pojo.dto.BaseDTO; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author denghuajun + * @date 2022/1/10 10:33 + * + */ +@Data +public class AreaTreeDTO extends BaseDTO { + @ApiModelProperty("是否被绑定") + private Integer isFalse = 0; + @ApiModelProperty("子节点") + private List children; +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/DeptDTO.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/DeptDTO.java new file mode 100644 index 0000000..15cb17a --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/dto/DeptDTO.java @@ -0,0 +1,46 @@ +package com.njcn.product.system.dept.pojo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月11日 14:08 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class DeptDTO implements Serializable { + + private String id; + + private String pid; + + private String pids; + + private String name; + + private String code; + + /** + * 专项分析类型区分 + */ + private Integer specialType; + + private String area; + + private String remark; + + private Integer sort; + + /** + * 部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + */ + private Integer type; + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/param/AreaParam.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/param/AreaParam.java new file mode 100644 index 0000000..108acb0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/param/AreaParam.java @@ -0,0 +1,88 @@ +package com.njcn.product.system.dept.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.math.BigDecimal; + +/** + * @author denghuajun + * @version 1.0.0 + * @date 2022年1月5日 8:59 + */ +@Data +public class AreaParam { + + @ApiModelProperty("父节点") + @NotBlank(message = ValidMessage.PID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEMS_ID, message = ValidMessage.PID_FORMAT_ERROR) + private String pid; + + + @ApiModelProperty("名称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.ALL_CHAR_1_20, message = ValidMessage.NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("简称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.ALL_CHAR_1_20, message = ValidMessage.NAME_FORMAT_ERROR) + private String shortName; + + + @ApiModelProperty("排序(编号)") + @NotBlank(message = ValidMessage.CODE_NOT_BLANK) + @Pattern(regexp = PatternRegex.ALL_CHAR_1_20, message = ValidMessage.CODE_FORMAT_ERROR) + private String areaCode; + + + + @ApiModelProperty("区域类型 0-省级区域;1-企业区域; ") + private Integer type; + + @ApiModelProperty("中心点经度") + private BigDecimal lng; + + @ApiModelProperty("中心点纬度") + private BigDecimal lat; + + + + + + /** + * 更新操作实体 + */ + + @Data + @EqualsAndHashCode(callSuper = true) + public static class AreaUpdateParam extends AreaParam { + + + @ApiModelProperty("id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class QueryParam extends BaseParam { + /** + * 区域类型 0-省级区域;1-企业区域 + */ + private Integer type; + + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Area.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Area.java new file mode 100644 index 0000000..0053030 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Area.java @@ -0,0 +1,73 @@ +package com.njcn.product.system.dept.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_area") +public class Area extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 区域Id + */ + private String id; + + /** + * 父节点(0为根节点) + */ + private String pid; + + /** + * 上层所有节点 + */ + private String pids; + + /** + * 区域名称 + */ + private String name; + + /** + * 简称 + */ + private String shortName; + + /** + * 排序(编号) + */ + private String areaCode; + + /** + * 区域类型 0-省级区域;1-企业区域; + */ + private Integer type; + + /** + * 中心点经度 + */ + private BigDecimal lng; + + /** + * 中心点纬度 + */ + private BigDecimal lat; + + /** + * 区域状态 0-删除;1-正常;默认正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Dept.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Dept.java new file mode 100644 index 0000000..436b4b7 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/po/Dept.java @@ -0,0 +1,75 @@ +package com.njcn.product.system.dept.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_dept") +public class Dept extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 部门表Id + */ + private String id; + + /** + * 父节点Id(0为根节点) + */ + private String pid; + + /** + * 上层所有节点Id + */ + private String pids; + + /** + * 部门名称 + */ + private String name; + + /** + * 部门编号 + */ + private String code; + + /** + * 专项分析类型区分 + */ + private Integer specialType; + + /** + * (sys_Area)行政区域Id,自定义部门无需填写部门 + */ + private String area; + + /** + * 部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + */ + private Integer type; + + /** + * 排序 + */ + private Integer sort; + + /** + * 部门描述 + */ + private String remark; + + /** + * 部门状态 0-删除;1-正常;默认正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/AreaTreeVO.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/AreaTreeVO.java new file mode 100644 index 0000000..dc9e354 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/AreaTreeVO.java @@ -0,0 +1,41 @@ +package com.njcn.product.system.dept.pojo.vo; + +import com.njcn.web.pojo.vo.BaseVO; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +/** + * @author denghuajun + * @date 2022/1/6 10:03 + * + */ +@Data +public class AreaTreeVO extends BaseVO { + + @ApiModelProperty("上层所有节点") + private String pids; + + @ApiModelProperty("区域名称") + private String name; + + @ApiModelProperty("简称") + private String shortName; + + @ApiModelProperty("排序(编号)") + private String areaCode; + + + @ApiModelProperty("中心点经度") + private BigDecimal lng; + + @ApiModelProperty("中心点纬度") + private BigDecimal lat; + + + @ApiModelProperty("子节点详细信息") + private List children ; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/DeptTreeVO.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/DeptTreeVO.java new file mode 100644 index 0000000..d6cb7bb --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/pojo/vo/DeptTreeVO.java @@ -0,0 +1,47 @@ +package com.njcn.product.system.dept.pojo.vo; + +import com.njcn.web.pojo.vo.BaseVO; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author denghuajun + * @date 2022/1/4 + * + */ +@Data +public class DeptTreeVO extends BaseVO { + + @ApiModelProperty("部门编号") + private String code; + + @ApiModelProperty("子类型") + private Integer specialType; + + @ApiModelProperty("行政区域id") + private String area; + + @ApiModelProperty("行政区域name") + private String areaName; + + @ApiModelProperty("状态") + private Integer state; + + @ApiModelProperty("部门类型") + private Integer type; + + @ApiModelProperty("部门描述") + private String remark; + + @ApiModelProperty("排序") + private Integer sort; + + @ApiModelProperty("部门等级 0:全国 1:省 2:市 3:县") + private Integer level; + + @ApiModelProperty("子节点详细信息") + private List children; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IAreaService.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IAreaService.java new file mode 100644 index 0000000..6d5011f --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IAreaService.java @@ -0,0 +1,104 @@ +package com.njcn.product.system.dept.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.dept.pojo.dto.AreaTreeDTO; +import com.njcn.product.system.dept.pojo.param.AreaParam; +import com.njcn.product.system.dept.pojo.po.Area; +import com.njcn.product.system.dept.pojo.vo.AreaTreeVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IAreaService extends IService { + + /** + * 根据前台传递参数,分页查询行政区域信息 + * + * @param queryParam 查询参数 + * @return 行政区域列表 + */ + Page listDictData(AreaParam.QueryParam queryParam); + + /** + * 根据行政区域id查询详情 + * + * @param id 行政区域id + * @return 行政区域详情详情 + */ + Area selectIdArea(String id); + + /** + * 根据行政区域id查询详情 + * + * @param list 行政区域id集合 + * @return 行政区域详情详情 + */ + List selectAreaByList(List list); + + /** + * + */ + List selectPid(List ids); + + + /** + * 新增企业区域 + * @param areaParam 企业区域 + * @return 新增结果 + */ + boolean addAreaParam(AreaParam areaParam); + + /** + * 修改企业区域 + * @param updateParam 企业区域数据 + * @return 操作结果 + */ + boolean updateArea(AreaParam.AreaUpdateParam updateParam); + + /** + * 批量逻辑删除企业区域数据 + * @param ids 企业区域id集合 + * @return 操作结果 + */ + boolean deleteArea(List ids); + + + + /** + * 根据区域id获取省份信息 + * + * @param type 区域类型 + * @return 树形结构 + */ + Area areaPro(String id, Integer type); + + Area areaDeptPro(String id); + + + + /** + * 根据行政区域名称查询详细 + * + * @param name 行政区域名称 + * @return 行政区域详情 + */ + Area selectAreaByName(String name); + + /** + * @Description: areaSelect + * @Author: clam + * @Date: 2023/4/11 + */ + List areaSelect(); + + List getPidAreaList(String areaId,Integer type); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IDeptService.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IDeptService.java new file mode 100644 index 0000000..2ebd491 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/IDeptService.java @@ -0,0 +1,34 @@ +package com.njcn.product.system.dept.service; + +import cn.hutool.core.lang.tree.Tree; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.dept.pojo.dto.DeptDTO; +import com.njcn.product.system.dept.pojo.po.Dept; +import com.njcn.product.system.dept.pojo.vo.DeptTreeVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IDeptService extends IService { + + + /** + * 根据条件获取后代部门索引 + * @param id 部门id + * @param type 指定部门类型 + * @return 后代部门索引 + */ + List getDeptDescendantIndexes(String id, List type); + + + List deptTree(); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/AreaServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/AreaServiceImpl.java new file mode 100644 index 0000000..8820b41 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/AreaServiceImpl.java @@ -0,0 +1,304 @@ +package com.njcn.product.system.dept.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.constant.BizParamConstant; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.product.system.dept.mapper.AreaMapper; +import com.njcn.product.system.dept.pojo.dto.AreaTreeDTO; +import com.njcn.product.system.dept.pojo.param.AreaParam; +import com.njcn.product.system.dept.pojo.po.Area; +import com.njcn.product.system.dept.pojo.vo.AreaTreeVO; +import com.njcn.product.system.dept.service.IAreaService; +import com.njcn.product.system.dict.enums.SystemResponseEnum; +import com.njcn.web.factory.PageFactory; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class AreaServiceImpl extends ServiceImpl implements IAreaService { + + + @Override + public Page listDictData(AreaParam.QueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //部门根据名称模糊查询 + queryWrapper + .and(param -> param.like("sys_area.name", queryParam.getSearchValue())); + } + } + queryWrapper.ne("sys_area.state", DataStateEnum.DELETED.getCode()); + queryWrapper.ge("sys_area.type", queryParam.getType()); + //初始化分页数据 + return this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + } + + @Override + public Area selectIdArea(String id) { + return this.baseMapper.selectById(id); + } + + @Override + public List selectAreaByList(List list) { + return this.lambdaQuery().in(Area::getId, list).list(); + } + + @Override + public List selectPid(List ids) { + return this.baseMapper.selectPid(ids, DataStateEnum.ENABLE.getCode()); + } + + +// @Override +// public List areaTree(String id, Integer type) { +// List areaTreeVOList; +// if (StrUtil.isBlank(id)) { +// /* +// * 用于首次访问区域。此处需要获取当前用户所绑定的部门下的行政区域id +// * 现在默认为0 +// */ +// id = deptFeignClient.getAreaIdByDeptId(RequestUtil.getDeptIndex()).getData(); +// } +// List areaTreeVOS; +// if (type == 1) { +// areaTreeVOList = this.baseMapper.getAreaIdTree(type, DataStateEnum.ENABLE.getCode()); +// List finalAreaTreeVOList = areaTreeVOList; +// areaTreeVOS = areaTreeVOList.stream().filter(deptTreeVO -> +// BizParamConstant.PARENT_ID.equals(deptTreeVO.getPid()) +// ).peek((deptFirst) -> { +// //map映射方法改变结果,调用getChildren()方法,把一级部门deptFirst和所有数据allDept作为参数传递,查询所有下级部门 +// deptFirst.setChildren(getChildren(deptFirst, finalAreaTreeVOList)); +// }).collect(Collectors.toList()); +// } else { +// areaTreeVOS = this.baseMapper.getAreaTree(id, type, DataStateEnum.ENABLE.getCode()); +// } +// return areaTreeVOS; +// } + + /** + * 递归查找所有企业的下级 + */ + private List getChildren(AreaTreeVO areaTreeVO, List allArea) { + return allArea.stream().filter(area -> { + //在全部数据中,找到和一级部门deptFirst的valueId相等的parentId + return area.getPid().equals(areaTreeVO.getId()); + }).peek(deptId -> { + //递归查询找到下级部门 + deptId.setChildren(getChildren(deptId, allArea)); + }).collect(Collectors.toList()); + } + + @Override + public boolean addAreaParam(AreaParam areaParam) { + checkAreaCode(areaParam, false); + Area area = new Area(); + BeanUtil.copyProperties(areaParam, area); + if (BizParamConstant.PARENT_ID.equals(areaParam.getPid())) { + //上层节点 + area.setPids(BizParamConstant.PARENT_ID); + } else { + String pids = StrUtil.COMMA + areaParam.getPid(); + String pid = this.baseMapper.getIdString(area.getPid()); + //上层节点 + area.setPids(pid + pids); + } + //默认为正常状态 + area.setState(DataStateEnum.ENABLE.getCode()); + return this.save(area); + } + + @Override + public boolean updateArea(AreaParam.AreaUpdateParam updateParam) { + checkAreaCode(updateParam, true); + Area area = new Area(); + if (BizParamConstant.PARENT_ID.equals(updateParam.getPid())) { + //上层节点 + area.setPids(BizParamConstant.PARENT_ID); + } else { + String pids = StrUtil.COMMA + updateParam.getPid(); + String pid = this.baseMapper.getIdString(area.getPid()); + //上层节点 + area.setPids(pid + pids); + } + BeanUtil.copyProperties(updateParam, area); + return this.updateById(area); + } + + @Override + public boolean deleteArea(List ids) { + /* + * 查询子节点 + */ + List list = this.baseMapper.selectPid(ids, DataStateEnum.ENABLE.getCode()); + /* + * 将子节点叶添加到需要删除中 + */ + if (!list.isEmpty()) { + for (Area area : list) { + ids.add(area.getId()); + } + } + return this.lambdaUpdate().set(Area::getState, DataStateEnum.DELETED.getCode()).in(Area::getId, ids).update(); + } + + + +// @Override +// public List areaDeptTree(String id, Integer type) { +// List areaTreeVOList; +// List areaTreeVOS; +// if (StrUtil.isBlank(id)) { +// /* +// * 用于首次访问区域。此处需要获取当前用户所绑定的部门下的行政区域id +// * 现在默认为0 +// */ +// id = deptFeignClient.getAreaIdByDeptId(RequestUtil.getDeptIndex()).getData(); +// } +// areaTreeVOList = this.baseMapper.getAreaDeptTree(id,type, DataStateEnum.ENABLE.getCode()); +// List finalAreaTreeVOList = areaTreeVOList; +// String finalId = id; +// areaTreeVOS = areaTreeVOList.stream().filter(deptTreeVO -> +// deptTreeVO.getPid().equals(finalId) +// ).peek((deptFirst) -> { +// //map映射方法改变结果,调用getChildren()方法,把一级部门deptFirst和所有数据allDept作为参数传递,查询所有下级部门 +// deptFirst.setChildren(getChildren(deptFirst, finalAreaTreeVOList)); +// }).collect(Collectors.toList()); +// +// return areaTreeVOS; +// } + + @Override + public Area areaPro(String id, Integer type) { + QueryWrapper areaQueryWrapper = new QueryWrapper<>(); + areaQueryWrapper.eq("sys_area.id", id); + areaQueryWrapper.eq("sys_area.type", type); + areaQueryWrapper.eq("sys_area.state", DataStateEnum.ENABLE.getCode()); + Area area = this.baseMapper.selectOne(areaQueryWrapper); + if (BizParamConstant.PARENT_ID.equals(area.getId()) || BizParamConstant.PARENT_ID.equals(area.getPid())) { + return area; + }else{ + id = area.getPid(); + area = areaPro(id, type); + } + return area; + } + + @Override + public Area areaDeptPro(String id) { + Area areaDetail = this.baseMapper.areaDeptProDetail(id); + return areaPro(areaDetail.getId(),areaDetail.getType()); + } + + +// @Override +// public List getDeptIdAreaTree() { +// +// //获取当前系统登录的部门信息 +// String areaId = deptFeignClient.getAreaIdByDeptId(RequestUtil.getDeptIndex()).getData(); +// List areaTreeVOS = this.baseMapper.getAreaAll(); +// return areaTreeVOS.stream().filter(areaTreeVO -> +// areaTreeVO.getId().equals(areaId) +// ).peek((areaFirst) -> { +// //map映射方法改变结果,调用getChildren()方法,把一级部门deptFirst和所有数据allDept作为参数传递,查询所有下级部门 +// areaFirst.setChildren(getChildren(areaFirst, areaTreeVOS)); +// }).collect(Collectors.toList()); +// } + + @Override + public Area selectAreaByName(String name) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(Area::getName, name); + return this.baseMapper.selectOne(lambdaQueryWrapper); + } + + /** + * 递归查找所有企业的下级 + * + */ + private List getChildren(AreaTreeDTO areaTreeVO, List allArea) { + return allArea.stream().filter(area -> { + //在全部数据中,找到和一级部门deptFirst的valueId相等的parentId + return area.getPid().equals(areaTreeVO.getId()); + }).peek(deptId -> { + //递归查询找到下级部门 + deptId.setChildren(getChildren(deptId, allArea)); + }).collect(Collectors.toList()); + } + + /** + * 校验参数,检查是否存在相同编码的企业区域 + */ + private void checkAreaCode(AreaParam areaParam, boolean isExcludeSelf) { + LambdaQueryWrapper dictTypeLambdaQueryWrapper = new LambdaQueryWrapper<>(); + dictTypeLambdaQueryWrapper + .eq(Area::getAreaCode, areaParam.getAreaCode()) + .eq(Area::getState, DataStateEnum.ENABLE.getCode()); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (areaParam instanceof AreaParam.AreaUpdateParam) { + dictTypeLambdaQueryWrapper.ne(Area::getId, ((AreaParam.AreaUpdateParam) areaParam).getId()); + } + } + int countByAccount = this.count(dictTypeLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(SystemResponseEnum.AREA_CODE_REPEAT); + } + } + + @Override + public List areaSelect() { + List areaTreeVOS = this.baseMapper.getAreaAll(); + return areaTreeVOS.stream ( ).filter (temp ->BizParamConstant.PARENT_ID.equals(temp.getPid())) + .peek((areaFirst) -> { + //map映射方法改变结果,调用getChildren()方法,把一级部门deptFirst和所有数据allDept作为参数传递,查询所有下级部门 + areaFirst.setChildren (getChildren (areaFirst, areaTreeVOS)); + }).collect (Collectors.toList ( )); + } + + @Override + public List getPidAreaList(String areaId, Integer type) { + List result = new ArrayList<>(); + Area area = this.getById(areaId); + if(Objects.isNull(area)){ + return result; + } + if(BizParamConstant.PARENT_ID.equals(area.getId())){ + result.add(area); + }else { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(Area::getPid,area.getPid()) + .eq(Area::getState,DataStateEnum.ENABLE.getCode()).eq(Area::getType,type).orderByAsc(Area::getAreaCode); + result = this.list(lambdaQueryWrapper); + } + return result; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/DeptServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/DeptServiceImpl.java new file mode 100644 index 0000000..12d3fab --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dept/service/impl/DeptServiceImpl.java @@ -0,0 +1,70 @@ +package com.njcn.product.system.dept.service.impl; + + +import cn.hutool.core.text.StrPool; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.system.dept.mapper.DeptMapper; +import com.njcn.product.system.dept.pojo.dto.DeptDTO; +import com.njcn.product.system.dept.pojo.po.Dept; +import com.njcn.product.system.dept.pojo.vo.DeptTreeVO; +import com.njcn.product.system.dept.service.IDeptService; +import com.njcn.web.utils.RequestUtil; +import com.njcn.web.utils.WebUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeptServiceImpl extends ServiceImpl implements IDeptService { + + @Override + public List getDeptDescendantIndexes(String id, List type) { + return this.baseMapper.getDeptDescendantIndexes(id, type); + } + + @Override + public List deptTree() { + List deptType = WebUtil.filterDeptType(); + String deptIndex = RequestUtil.getDeptIndex(); + List deptList = this.baseMapper.getDeptTree(deptIndex, deptType); + return deptList.stream() + .filter(deptVO -> deptVO.getId().equals(deptIndex)) + .peek(deptFirst -> { + if (!Objects.isNull(deptFirst.getPid())) { + deptFirst.setLevel(deptFirst.getPids().split(StrPool.COMMA).length - 1); + } + deptFirst.setChildren(getChildren(deptFirst, deptList)); + }) + .collect(Collectors.toList()); + } + private List getChildren(DeptTreeVO deptFirst, List allDept) { + return allDept.stream().filter(dept -> dept.getPid().equals(deptFirst.getId())) + .peek(deptVo -> { + if (!Objects.isNull(deptVo.getPids())) { + deptVo.setLevel(deptVo.getPids().split(",").length - 1); + } + deptVo.setChildren(getChildren(deptVo, allDept)); + if (deptVo.getType() == 0) { + deptVo.setName(deptVo.getAreaName()); + } + }).sorted(Comparator.comparing(DeptTreeVO::getSort)).collect(Collectors.toList()); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictDataController.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictDataController.java new file mode 100644 index 0000000..3285aa8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictDataController.java @@ -0,0 +1,245 @@ +package com.njcn.product.system.dict.controller; + + +import cn.hutool.core.util.StrUtil; +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.common.utils.LogUtil; + +import com.njcn.product.system.dict.pojo.param.DictDataParam; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.pojo.vo.DictDataVO; +import com.njcn.product.system.dict.service.IDictDataService; +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.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import java.util.List; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@Api(tags = "字典数据操作") +@RestController +@RequestMapping("/dictData") +@RequiredArgsConstructor +public class DictDataController extends BaseController { + + private final IDictDataService dictDataService; + + /** + * 分页查询字典类型数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/list") + @ApiOperation("查询字典数据") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> list(@RequestBody @Validated DictDataParam.DictDataQueryParam queryParam) { + String methodDescribe = getMethodDescribe("list"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam); + Page result = dictDataService.listDictData(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + /** + * 新增字典数据 + * + * @param dictDataParam 字典数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增字典数据") + @ApiImplicitParam(name = "dictDataParam", value = "字典数据", required = true) + public HttpResult add(@RequestBody @Validated DictDataParam dictDataParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},字典数据为:{}", methodDescribe, dictDataParam); + boolean result = dictDataService.addDictData(dictDataParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 修改字典数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改字典数据") + @ApiImplicitParam(name = "updateParam", value = "字典数据", required = true) + public HttpResult update(@RequestBody @Validated DictDataParam.DictDataUpdateParam updateParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},字典数据为:{}", methodDescribe, updateParam); + boolean result = dictDataService.updateDictData(updateParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + + /** + * 批量删除字典数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/delete") + @ApiOperation("删除字典数据") + @ApiImplicitParam(name = "ids", value = "字典索引", required = true, dataTypeClass = List.class) + public HttpResult delete(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},字典ID数据为:{}", methodDescribe, String.join(StrUtil.COMMA, ids)); + boolean result = dictDataService.deleteDictData(ids); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 根据字典类型id分页查询字典数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/getTypeIdData") + @ApiOperation("根据字典类型id查询字典数据") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> getTypeIdData(@RequestBody @Validated DictDataParam.DicTypeIdQueryParam queryParam) { + String methodDescribe = getMethodDescribe("list"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam); + Page result = dictDataService.getTypeIdData(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataById") + @ApiOperation("根据字典id查询字典数据") + @ApiImplicitParam(name = "dicIndex", value = "查询参数", required = true) + public HttpResult getDicDataById(@RequestParam("dicIndex") String dicIndex) { + String methodDescribe = getMethodDescribe("getDicDataById"); + DictData result = dictDataService.getDicDataById(dicIndex); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByTypeName") + @ApiOperation("根据字典类型名称查询字典数据") + @ApiImplicitParam(name = "dictTypeName", value = "查询参数", required = true) + public HttpResult> getDicDataByTypeName(@RequestParam("dictTypeName") String dictTypeName) { + String methodDescribe = getMethodDescribe("getDicDataByTypeName"); + List result = dictDataService.getDicDataByTypeName(dictTypeName); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByName") + @ApiOperation("根据字典名称查询字典数据") + @ApiImplicitParam(name = "dicName", value = "查询参数", required = true) + public HttpResult getDicDataByName(@RequestParam("dicName") String dicName) { + String methodDescribe = getMethodDescribe("getDicDataByName"); + DictData result = dictDataService.getDicDataByName(dicName); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByNameAndType") + @ApiOperation("根据字典名称查询字典数据") + @ApiImplicitParams({ + @ApiImplicitParam(name = "dicName", value = "查询参数", required = true), + @ApiImplicitParam(name = "typeName", value = "查询参数", required = true) + }) + public HttpResult getDicDataByNameAndType(@RequestParam("dicName") String dicName,@RequestParam("typeName") String typeName) { + String methodDescribe = getMethodDescribe("getDicDataByNameAndType"); + DictData result = dictDataService.getDicDataByNameAndType(dicName,typeName); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByCodeAndType") + @ApiOperation("根据字典Code和字典类型查询字典数据") + @ApiImplicitParams({ + @ApiImplicitParam(name = "dicDataCode", value = "查询参数", required = true), + @ApiImplicitParam(name = "dicTypeCode", value = "查询参数", required = true) + }) + public HttpResult getDicDataByCodeAndType(@RequestParam("dicDataCode") String dicCode,@RequestParam("dicTypeCode") String typeCode) { + String methodDescribe = getMethodDescribe("getDicDataByCodeAndType"); + DictData result = dictDataService.getDicDataByCodeAndType(dicCode,typeCode); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByCode") + @ApiOperation("根据字典code查询字典数据") + @ApiImplicitParam(name = "code", value = "查询参数", required = true) + public HttpResult getDicDataByCode(@RequestParam("code") String code) { + String methodDescribe = getMethodDescribe("getDicDataByCode"); + DictData result = dictDataService.getDicDataByCode(code); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + /** + * 后台新增字典数据 + * + * @param dicTypeName 类型名称 + * @param dicDataName 数据名称 + * @return 新增后的字典数据 + */ + @ApiIgnore + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/addDicData") + @ApiOperation("后台新增字典数据") + public HttpResult addDicData(String dicTypeName, String dicDataName) { + String methodDescribe = getMethodDescribe("addDicData"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dictDataService.addDictData(dicTypeName,dicDataName), methodDescribe); + } + + /** + * 根据字典类型名称&数据名称获取字典数据 + * + * @param dicTypeName 字典类型名称 + * @param dicDataName 字典数据名称 + * @return 字典数据 + */ + @ApiIgnore + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByNameAndTypeName") + @ApiOperation("根据字典类型名称&数据名称获取字典数据") + public HttpResult getDicDataByNameAndTypeName(String dicTypeName, String dicDataName) { + String methodDescribe = getMethodDescribe("getDicDataByNameAndTypeName"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dictDataService.getDicDataByNameAndTypeName(dicTypeName,dicDataName), methodDescribe); + } + + @ApiIgnore + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getDicDataByTypeCode") + @ApiOperation("根据字典类型code查询字典数据") + @ApiImplicitParam(name = "dictTypeCode", value = "查询参数", required = true) + public HttpResult> getDicDataByTypeCode(@RequestParam("dictTypeCode") String dictTypeCode) { + String methodDescribe = getMethodDescribe("getDicDataByTypeCode"); + List result = dictDataService.getDicDataByTypeCode(dictTypeCode); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictTypeController.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictTypeController.java new file mode 100644 index 0000000..e548901 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/controller/DictTypeController.java @@ -0,0 +1,153 @@ +package com.njcn.product.system.dict.controller; + + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +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.constant.OperateType; +import com.njcn.common.pojo.dto.SimpleTreeDTO; +import com.njcn.common.pojo.enums.common.DataStateEnum; +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.common.utils.LogUtil; + +import com.njcn.product.system.dict.pojo.param.DictTypeParam; +import com.njcn.product.system.dict.pojo.po.DictType; +import com.njcn.product.system.dict.service.IDictTypeService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Api(tags = "字典类型表操作") +@RestController +@RequestMapping("/dictType") +@RequiredArgsConstructor +public class DictTypeController extends BaseController { + + private final IDictTypeService dictTypeService; + + + /** + * 分页查询字典类型数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/list") + @ApiOperation("查询字典类型") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> list(@RequestBody @Validated DictTypeParam.DictTypeQueryParam queryParam) { + String methodDescribe = getMethodDescribe("list"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam); + Page result = dictTypeService.listDictTypes(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + /** + * 查询所有字典类型数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/listAll") + @ApiOperation("查询所有字典类型数据") + public HttpResult> listAll() { + String methodDescribe = getMethodDescribe("listAll"); + LogUtil.njcnDebug(log, "{}", methodDescribe); + List dictTypeList = dictTypeService.list(new LambdaQueryWrapper().eq(DictType::getState, DataStateEnum.ENABLE.getCode())); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dictTypeList, methodDescribe); + } + + + /** + * 新增字典类型 + * + * @param dictTypeParam 字典类型数据 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增字典类型") + @ApiImplicitParam(name = "dictTypeParam", value = "字典类型数据", required = true) + public HttpResult add(@RequestBody @Validated DictTypeParam dictTypeParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},字典类型数据为:{}", methodDescribe, dictTypeParam); + boolean result = dictTypeService.addDictType(dictTypeParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 修改字典类型 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改字典类型") + @ApiImplicitParam(name = "updateParam", value = "字典类型数据", required = true) + public HttpResult update(@RequestBody @Validated DictTypeParam.DictTypeUpdateParam updateParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},字典类型数据为:{}", methodDescribe, updateParam); + boolean result = dictTypeService.updateDictType(updateParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + + /** + * 批量删除字典类型 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) + @PostMapping("/delete") + @ApiOperation("删除字典类型") + @ApiImplicitParam(name = "ids", value = "字典索引", required = true) + public HttpResult delete(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},字典ID数据为:{}", methodDescribe, String.join(StrUtil.COMMA, ids)); + boolean result = dictTypeService.deleteDictType(ids); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + /** + * 获取所有字典数据基础信息 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/dictDataCache") + @ApiOperation("获取所有字典数据基础信息") + public HttpResult> dictDataCache() { + String methodDescribe = getMethodDescribe("dictDataCache"); + LogUtil.njcnDebug(log, "{},获取所有字典数据基础信息", methodDescribe); + List dictData = dictTypeService.dictDataCache(); + if (CollectionUtil.isNotEmpty(dictData)) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dictData, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe); + } + } + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataEnum.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataEnum.java new file mode 100644 index 0000000..21841a2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataEnum.java @@ -0,0 +1,677 @@ +package com.njcn.product.system.dict.enums; + +import lombok.Getter; + +/** + * 类的介绍:字典数据名称 + * + * @author xuyang + * @version 1.0.0 + * @createTime 2021/8/5 21:56 + */ +@Getter +public enum DicDataEnum { + + /** + * 数据中心稳态统计指标 + */ + PLPC_ENUM("频率偏差", "PLPC"), + DYPC_ENUM("电压偏差", "DYPC"), + SXDYBPHD_ENUM("负序电压不平衡度", "SXDYBPHD"), + XBDY_ENUM("谐波电压", "XBDY"), + CSSB_ENUM("长时闪变", "CSSB"), + XBDL_ENUM("谐波电流", "XBDL"), + FXDL_ENUM("负序电流", "FXDL"), + JXBDY_ENUM("间谐波电压", "JXBDY"), + + + /** + * 稳态统计指标 + */ + VOLTAGE_DEV("电压偏差", "Voltage_Dev"), + FLICKER("长时闪变", "Flicker"), + HARMONIC_VOLTAGE("谐波电压", "Harmonic_Voltage"), + HARMONIC_CURRENT("谐波电流", "Harmonic_Current"), + INTERHARMONIC_VOLTAGE("间谐波电压", "Interharmonic_Voltage"), + PHASE_VOLTAGE("负序电压不平衡度", "phase_Voltage"), + FREQUENCY_DEV("频率偏差", "Frequency_Dev"), + NEG_CURRENT("负序电流", "Neg_Current"), + THD_V("电压总谐波畸变率", "Thd_V"), + phase_Voltage("三相电压不平衡度","phase_Voltage"), + TOTAL_INDICATOR("总稳态指标", "Total_Indicator"), + + /** + * 污区图统计类型 + */ + I_ALL("谐波电流", "I_All"), + V_HARMONIC("谐波电压", "V_Harmonic"), + + + /** + * 监测点类别 + */ + ONE_LINE("Ⅰ类监测点", "One_Line"), + TWO_LINE("Ⅱ类监测点", "Two_Line"), + THREE_LINE("Ⅲ类监测点", "Three_Line"), + + + /** + * 监测点类型 + */ + Power_Supply_Point("供电点","Power_Supply_Point"), + Pub_Connect_Point("公共连接点PCC","Pub_Connect_Point"), + Parallel_Point("并网点","Parallel_Point"), + Other("其他","Other"), + + + /** + * 电压互感器类型 + */ + Cap_V("电容式","Cap_V"), + Pele_V("光电式","Pele_V"), + Elec_V("电子式","Elec_V"), + Other_S("其他","Other"), + Ele_V("电磁式","Ele_V"), + + /** + * 中性点接地方式 + */ + Ground_Res("经非线性电阻接地-消谐器","Ground_Res"), + Ground_Trans("经互感器接地-4PT","Ground_Trans"), + Ground_Dir("直接接地-3PT","Ground_Dir"), + A_Center("A类测试中性点接地方式","A_Center"), + Ground_Other("其他","Other"), + + + + + /** + * 终端类型 + */ + DEV_QUALITY("电能质量监测终端", "Dev_Quality"), + DEV_SMART("智能电表", "Dev_Smart"), + DEV_MIX("智能融合终端", "Dev_Mix"), + + + /** + * 装置类别 + */ + Test_Equipment("测试设备","Test_Equipment"), + Monitor_Terminals("监测终端","Monitor_Terminals"), + Detect_Equipment("检测设备","Detect_Equipment"), + Govern_Devices("治理设备","Govern_Devices"), + + /*** + * 告警类型 + */ + COMM_ERR("通讯异常", "Comm_Err"), + + /** + * 暂态统计指标 + */ + TOTAL_INDICATORS("总暂态指标", "Total_Indicators"), + VOLTAGE_DIP("电压暂降", "Voltage_Dip"), + VOLTAGE_RISE("电压暂升", "Voltage_Rise"), + SHORT_INTERRUPTIONS("短时中断", "Short_Interruptions"), + DISTURBANCE("扰动", "Disturbance"), + OTHER("其他", "Other"), + RECORDING_WAVE("录波", "Recording_Wave"), + + /** + * 数据类型 + */ + MAINNET_POINT("主网测点", "Mainnet_Point"), + DISTRIBUTION_POINT("配网测点", "Distribution_Point"), + + /** + * 分布式光伏台区渗透率水平 + */ + RATE_0_25("0-25", "Rate_0_25"), + RATE_25_50("25-50", "Rate_25_50"), + RATE_50_75("50-75", "Rate_50_75"), + RATE_75_100("75-100", "Rate_75_100"), + RATE_100("100", "Rate_100"), + + /** + * 入网报告状态 + */ + NEWLY("新建", "Newly"), + AUDIT("待审核", "Audit"), + FAILED("未通过", "Failed"), + FINISH("已生效", "Finish"), + + /** + * 审核状态 + */ + INIT("新建", "Init"), + FAIL("未通过", "Fail"), + AUDITT("待审核", "Auditt"), + SUCCESS("已通过", "Success"), + + /** + * 填报进度 + */ + NOT_REPORTED("未填报", "Not_Reported"), + INSIGHTS("成效分析", "Insights"), + PLAN_MEASURES("计划整改措施", "Plan_Measures"), + ACTUAL_MEASURES("实际采取措施", "Actual_Measures"), + CAUSE_ANALYSIS("原因分析", "Cause_Analysis"), + ARCHIVED("已归档", "Archived"), + + /** + * 问题来源 + */ + ONLINE("在线监测告警", "Online"), + DEV_EXCEPTION("设备异常", "Dev_Exception"), + GENERAL("普测超标", "General"), + USER_COMPLAINTS("用户投诉", "User_Complaints"), + + /** + * 台区电能质量事件类型 + */ + EVENT_TYPE_P("低功率因数0.7-0.8", "Event_Type_p"), + EVENT_TYPE_U("潮流倒送", "Event_Type_u"), + EVENT_TYPE_T("电压越上限15%以上", "Event_Type_t"), + EVENT_TYPE_W("电压越限", "Event_Type_w"), + EVENT_TYPE_O("低功率因数0.7以下", "Event_Type_o"), + EVENT_TYPE_E("电压越上限", "Event_Type_e"), + EVENT_TYPE_Y("电压越下限", "Event_Type_y"), + EVENT_TYPE_L("低功率因数0.8-0.9", "Event_Type_l"), + EVENT_TYPE_Q("电压总谐波畸变率超标", "Event_Type_q"), + EVENT_TYPE_R("电压越上限7%-15%", "Event_Type_r"), + EVENT_TYPE_I("低功率因数", "Event_Type_i"), + PENET_LIMIT("渗透率超上限", "Penet_Limit"), + EVENT_TYPE_A("潮流倒送导致设备重载", "Event_Type_a"), + EVENT_TYPE_S("潮流倒送导致设备过载", "Event_Type_s"), + EVENT_TYPE_D("电压越上限严重度", "Event_Type_d"), + EVENT_TYPE_F("电压越下限严重度", "Event_Type_f"), + EVENT_TYPE_G("渗透率", "Event_Type_g"), + EVENT_TYPE_Z("超标3%-10%", "Event_Type_z"), + EVENT_TYPE_X("超标10%以下", "Event_Type_x"), + EVENT_TYPE_C("重过载", "Event_Type_c"), + /** + * 监测点状态 + */ + RUN("运行", "Run"), + OVERHAUL("检修", "Overhaul"), + DEBUGGING("调试", "Debugging"), + DECOMMISSIONING("停运", "Decommissioning"), + RETIREMENT("退役", "Retirement"), + + /** + * 终端状态 + */ + FREE_MOORY("剩余内存", "Free_Mmory"), + FREE_STORE("剩余存储空间", "Free_Store"), + NOT_OPERATION("未投运", "Not_Operation"), + RUNNING("在运", "Running"), + RETIRE("退役", "Retire"), + ON_SITE("现场留用", "On_Site"), + STOCK_STANDBY("库存备用", "Stock_Standby"), + TO_BE_SCRAPPED("待报废", "To_Be_Scrapped"), + SCRAP("报废", "Scrap"), + + /** + * 监测点标签(废弃,统一使用监测点对象类型) + */ + ONSHORE_WIND("陆上风电", "Onshore_Wind"), + POWER_STATION("光伏电站", "Power_Station"), + ELECTRIFIED_RAILWAYS("电气化铁路", "Electrified_Railways"), + SMELT_LOAD("冶炼负荷", "Smelt_Load"), + DISTRIBUTED_PHOTOVOLTAICS("分布式光伏", "Distributed_Photovoltaics"), + WIND_FARM("风电场", "Wind_Farm"), + SENSITIVE_USERS("重要敏感用户", "Sensitive_Users"), + IMPORTANT_USERS("重要用户", "Important_Users"), + //废弃字段 + TRACTION_STATION("牵引站", "Traction_Station"), + LINEAR_LOADS("其他非线性负荷", "Linear_Loads"), + + + /** + * 电压等级 + */ + AC_380V("交流380V(含400V)", "AC_380V(400V)"), + DY_380V("交流0.38kV", "0.38kV"), + DY_10KV("交流10kV", "10kV"), + DY_35KV("交流35kV", "35kV"), + DY_110KV("交流110kV", "110kV"), + DY_220KV("交流220kV", "220kV"), + DY_500KV("交流500kV", "500kV"), + DY_DC_500kV("直流500kV", "DC_500kV"), + + + /** + * 电压等级 + * 此电压用于计算,真实code请使用上面枚举 + */ + + V100("100V", "0.1",0.1f), + V220("220V", "0.22",0.22f), + KV038("0.38kV", "0.38",0.38f), + V380("380V", "0.38",0.38f), + KV04("0.4kV", "0.4",0.4f), + KV06("0.6kV", "0.6",0.6f), + V400("400V", "0.4",0.4f), + KV1("1kV", "1",1.0f), + KV6("6kV", "6",6.0f), + KV10("10kV", "10",10.0f), + KV20("20kV", "20",20.0f), + KV30("30kV", "30",30.0f), + KV35("35kV", "35",35.0f), + KV50("50kV", "50",50.0f), + KV66("66kV", "66",66.0f), + KV72_5("72.5kV", "725",725.0f), + KV110("110kV", "110",110.0f), + KV120("120kV", "120",120.0f), + KV125("125kV", "125",125.0f), + KV200("200kV", "200",200.0f), + KV220("220kV", "220",220.0f), + KV320("320kV", "320",320.0f), + KV330("330kV", "330",330.0f), + KV400("400kV", "400",400.0f), + KV500("500kV", "500",500.0f), + KV600("600kV", "600",600.0f), + KV660("660kV", "660",660.0f), + KV750("750kV", "750",750.0f), + KV1000("1000kV", "1000",1000.0f), + KV1100("1100kV", "1100",1100.0f), + + /** + * 计划采取实施 + */ + GOVERNANCE_FACTS("事实治理工程", "Governance_Facts"), + GRID_OPERATES("电网运行方式调整", "Grid_Operates"), + PARAMETER_OPT("治理装置运行参数优化", "Parameter_Opt"), + RECTIFY_ORDERS("提出整改工单", "Rectify_Orders"), + + /** + * 牵引站变压器接线方式 + */ + SINGLE_TRANS("单相牵引变压器", "Single_Trans"), + THREE_TRANS("三相YN d11联结牵引变压器", "Three_Trans"), + THREE_PHASE_TRANS("三相YN d11 d1组成的牵引变压器", "Three_Phase_Trans"), + SCOTT_TRANS("SCOTT牵引变压器", "SCOTT_Trans"), + YN_V_TRANS("YN v联结平衡牵引变压器", "YN_V_Trans"), + YN_A_TRANS("YN A联结平衡牵引变压器", "YN_A_Trans"), + /** + * APP暂态事件类型 + */ + EVT_DIPSTR("电压暂降事件启动","Evt_DipStr"), + EVT_INTRSTR("电压中断事件启动","Evt_IntrStr"), + EVT_SWLSTR("电压暂升事件启动","Evt_SwlStr"), + + + + /** + * 监测对象 + */ + PHOTOVOLT("光伏台区", "Photovolt"), + FEEDER_TENKV("10kV馈线", "Feeder_TenkV"), + MAIN_CHANGE("主变", "Main_Change"), + + /** + * 工单状态 + */ + PEND_DISPATCH("待派单", "Pend_Dispatch"), + DISPATCHED("已派单", "Dispatched"), + CLOSED("已关闭", "Closed"), + + /** + * 问题类型 + */ + VOLTAGE_LIMIT("谐波电压越限", "Voltage_Limit"), + CURRENT_LIMIT("谐波电流越限", "Current_Limit"), + + /** + * 审核状态 + */ + REVIEW("待审核", "Review"), + AUDITED("已审核", "Audited"), + APPROVED("审核通过", "Approved"), + NOT_APPROVED("审核通过", "Not_Approved"), + + /** + * 审核处理 + */ + GENERATE("生成工单", "Generate"), + NO_REQUIRED("无需处理", "No_Required"), + + /** + * 工单流程 + */ + GENERATED("生成工单", "Generated"), + DISPATCH("派单", "Dispatch"), + FEEDBACK("反馈", "Feedback"), + AUDITING("审核", "Auditing"), + RECTIFICATION("整改", "Rectification"), + ASSESS("评估", "Assess"), + PIGEONHOLE("归档", "Pigeonhole"), + + /** + * 评估结果 + */ + PASS("评估合格", "Pass"), + NOT_PASS("评估不合格", "Not_Pass"), + + /** + * 工单类型 + */ + RECT_ORDER("整改单", "Rect_Order"), + + /** + * 一级业务类型 + */ + TRANS_BUSINESS("运检业务", "Trans_Business"), + + /** + * 日志字典类型 + */ + LINE_PARAMETER("监测点日志", "Line_Parameter"), + DEV_PARAMETER("设备日志", "Dev_Parameter"), + WEB_ADD("web新增用户", "Web_Add"), + DATA_PLAN("流量套餐修改", "Data_Plan"), + PROCESS_PARMETER("终端进程操作", "Process_Parmeter"), + + + /** + * 接线方式 + */ + STAR("星型接线", "Trans_Business"), + STAR_TRIANGLE("星三角", "Star_Triangle"), + OPEN_DELTA("开口三角", "Open_Delta"), + + /** + * 装置类型 + */ + GATEWAY_DEV("网关", "Gateway"), + CONNECT_DEV("直连设备", "Direct_Connected_Device"), + DEV("装置", "Device"), + PORTABLE("便携式设备", "Portable"), + + + /** + * 数据模型 + */ + APF("APF","Apf"), + DVR("DVR","Dvr"), + EPD("电能数据","Epd"), + PQD("电能质量数据","Pqd"), + BMD("基础测量数据","Bmd"), + EVT("事件","Evt"), + ALM("告警","Alm"), + STS("状态","Sts"), + DI("开入","Di"), + DO("电能数据","Do"), + PARM("参数","Parm"), + SET("定值","Set"), + INSET("内部定值","InSet"), + CTRL("控制","Ctrl"), + TERMINAL_SORT("台账类型","terminal_sort"), + /** + * 暂降原因 + */ + SHORT_TROUBLE("短路故障", "Short_Trouble"), + TRANSFORMER_EXCITATION("变压器激磁", "Transformer_Excitation"), + RESON_REST("其他", "Reson_Rest"), + LARGE_INDUCTION("大型感应电动机启动", "Large_Induction"), + VOLTAGE_DISTURBANCE("电压扰动", "Voltage_Disturbance"), + + + /** + * 暂降类型 + */ + PHASE_A("A相接地", "Phase_A"), + PHASE_B("B相接地", "Phase_B"), + PHASE_C("C相接地", "Phase_C"), + INTERPHASE_AB("AB相间", "Interphase_AB"), + INTERPHASE_BC("BC相间", "Interphase_BC"), + INTERPHASE_AC("AC相间", "Interphase_AC"), + GROUND_AB("AB两相接地", "Ground_AB"), + GROUND_BC("BC两相接地", "Ground_BC"), + GROUND_AC("AC两相接地", "Ground_AC"), + GROUND_ABC("三相接地", "Ground_ABC"), + TYPE_REST("其他", "Type_Rest"), + + /** + * 监测点位置 + */ + LOAD_SIDE("负载侧", "Load_Side"), + GRID_SIDE("电网侧", "Grid_Side"), + OUTPUT_SIDE("输出侧", "Output_Side"), + + /** + * 警告级别 + */ + + ALARM("告警", "Alarm"), + FAULT("故障", "Fault"), + + /** + * 装置级别 + */ + MOST_IMPORMENT("极重要","Vital"), + + /** + * 测量信号输入形式 + */ + NUMBER_SIGNAL("数字信号","Digital_Signal"), + SIMULATION_SIGNAL("模拟信号","Analog_Signal"), + + /** + * 设备地区特征 + */ + DOWNTOWN("市中心区","downtown"), + CITY("市区","city"), + TOWN("城镇","town"), + COUNTY_SEAT("县城区","County_Seat"), + COUNTRYSIDE("农村","countryside"), + TOWNSHIP("乡镇","township"), + AGRO_AREA("农牧区","Agro_Area"), + + /** + * 设备使用性质代码 + */ + DEDICATED("专用","dedicated"), + PUBLIC("公用","public"), + + + /** + * 监督类型 + */ + POWER_QUALITY("电能质量敏感用户监督","Power_Quality"), + UHV_Converter("特高压换流站监督","UHV_Converter"), + New_Energy("新能源场站监督","New_Energy"), + Technical_Super("供电电压质量技术监督","Technical_Super"), + capacitor_bank("电容器组监督","capacitor_bank"), + report_supervision("评估报告监督","report_supervision"), + /** + * app基础信息类型 + */ + DATA_BASE("资料库","Data_base"), + INTRODUCTION("系统介绍","introduction"), + USER_MANUAL("使用手册","User_Manual"), + USER_AGREEMENT("用户协议","User_Agreement"), + COMPANY_PROFILE("公司简介","Company_Profile"), + PERSONAL_INFOR_PROTECT("个人信息保护政策","Personal_Infor_Protect"), + + /** + * app设备事件类型权限转移,数据恢复 + */ + AUTHORITY_TRANSFER("权限转移","Authority_transfer"), + DATA_RECOVERY("数据恢复","Data_recovery"), + + /** + * 谐波数据报表,数据单位类别 + */ + EFFECTIVE("有效值","effective"), + POWER("功率","power"), + DISTORTION("畸变率","distortion"), + VOLTAGE("电压偏差","voltage"), + UNIT_FREQUENCY("频率","unitFrequency"), + UNBALANCE("三项不平横","unbalance"), + FUND("基波","fund"), + + + + + + /**pms******************************start*/ + + + /** + * 实施状态 + */ + Nocarried("未开展","Nocarried"), + Progressing("开展中","Progressing"), + Reviewing("待审核","Reviewing"), + Completed("已完成","Completed"), + + /*3.45 典型源荷用户类型*/ + TRACTIONSTATION("牵引站","01"), + WINDFARM_USER("风电场用户","02"), + PHOTOVOLTAICSIT_EUSERS("光伏场站用户","03"), + OTHER_INTERFERENCESOURCE_USERS("其他干扰源用户","04"), + + /*3.39 监测对象类型-大类*/ + SEMICONDUCTOR_MANUFACTURING("半导体制造","2401"), + PRECISION_MACHINING("精密加工","2402"), + PARTY_GOVERNMENT("党政机关","2403"), + NOSOCOMIUM("医院","2404"), + TRANSPORTATION_HUB("交通枢纽(公交场站、客运站、火车站等)","2405"), + AERODROME("机场","2406"), + FINANCE("金融","2407"), + DATA_CENTER("数据中心","2408"), + HAZARDOUS_CHEMICALS("危险化学品","2409"), + EXPLOSIVE_PRODUCTS("易燃易爆品制造","2410"), + LARGEVENUE("大型场馆(体育场、剧院等)","2411"), + WINDPOWER_STATION("风电场","1401"), + PHOTOVOLTAIC_POWER_STATION("光伏电站","1402"), + ELECTRIFIED_RAILWAY("电气化铁路","1300"), + + + /** + * 所属站别类型 + */ + Trans_Sub("变电站","Trans_Sub"), + Converter("换流站","Converter"), + Ele_Railways("电气化铁路","Ele_Railways"), + Wind_Farms("风电场","Wind_Farms"), + Power_Station("光伏电站","Power_Station"), + Smelting_Load("冶炼负荷","Smelting_Load"), + Imp_Users("重要敏感用户","Imp_Users"), + Station_Other("其他","Other"), + + /*承载能力评估用户类型*/ + Power_Station_Users("光伏电站用户","Power_Station_Users"), + Charging_Station_Users("充电站用户","Charging_Station_Users"), + Electric_Heating_Load_Users("电加热负荷用户","Electric_Heating_Load_Users"), + Electrified_Rail_Users("电气化铁路用户","Electrified_Rail_Users"), + + //变压器连接方式 + YNd11("YNd11","YNd11"), + YNy0("YNy0","YNy0"), + Yy0("Yy0","Yy0"), + Yyn0("Yyn0","Yyn0"), + Yd11("Yd11","Yd11"), + Y_yn("Y/yn","Y_yn"), + Y_d("Y/d","Y_d"), + D_y("D/y","D_y"), + YNyn("YNyn","YNyn"), + + //用户模式 + SPECIAL_USER("专变用户","special_user"),//专变用户 + PUBLIC_USER("公变用户","public_user"),// ,公变用户 + + //统计类型 + STATISTICAL_TYPE_Y("年数据","01"), + STATISTICAL_TYPE_M("月数据","02"), + STATISTICAL_TYPE_D("日数据","03"), + + /**pms******************************end*/ + + //pq干扰源类型 + PQ_ELE_RAILWAYS("电气化铁路","Ele_Railways"), + PQ_POWER_STATION("光伏电站","Power_Station"), + PQ_WIND_FARMS("风电场","Electrolytic_Load"), + + //所属地市local_municipality + //张家口市、廊坊市、唐山市、承德市、秦皇岛市、风光储、超高压 + ZHANGJIAKOU("张家口市","zhangjiakou"), + LANGFANG("廊坊市","langfang"), + TANGSHAN("唐山市","tangshan"), + CHENGDE("承德市","chengde"), + QINGHUANGDAO("秦皇岛市","qinghuangdao"), + FENGFENGRESERVE("风光储","fengfengreserve"), + EXTRA_HIGH_PRESSURE("超高压","extra_high_pressure"), + + //行业类型-冀北 + TRAFFIC("交通","Traffic"), + METALLURGY("冶金","Metallurgy"), + MACHINERY("机械","Machinery"), + CHEMICAL_INDUSTRY("化工","Chemical_Industry"), + MANUFACTURING("制造","Manufacturing"), + SHIPBUILDING("造船","Shipbuilding"), + UTILITIES("公用事业","Utilities"), + POWER_PLANT("电厂","Power_Plant"), + COMMERCE("商业","Commerce"), + MUNICIPAL("市政","Municipal"), + CIVILIAN("民用","Civilian"), + ELECTRONICS("电子","Electronics"), + COMMUNICATION("通讯","Communication"), + ELECTRIC_POWER("电力","Electric_Power"), + OTHER_INDUSTRY("其他","Other_Industry"), + + + + + + //河北工单相关 + //3.67工单状态 + WORK_ORDER_STATUS_NO("未处理","01"), + WORK_ORDER_STATUS_ING("处理中","02"), + WORK_ORDER_STATUS_HAS("已上报","03"), + WORK_ORDER_STATUS_CLOSE("已闭环","04"), + + + YES("是","1"), + NO("否","0"), + + No_Upload("未上送","0"), + Has_Upload("已上送","1"), + Reduce_Upload("取消上送","2"), + Return_Upload("待重新上送","3"), + + + //字典树类型 + Obj_Type("监测对象类型","0"), + Custom_Report_Type("自定义报表类型","1") + + + ; + + private final String name; + private final String code; + private final Float value; + + DicDataEnum(String name, String code,Float value) { + this.name = name; + this.code = code; + this.value = value; + } + + DicDataEnum(String name, String code) { + this.name = name; + this.code = code; + this.value = + null; + } + + public static DicDataEnum getDicDataEnumValue(String code) { + for (DicDataEnum item : values()) { + if (item.getCode().equals(code)) { + return item; + } + } + return null; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataTypeEnum.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataTypeEnum.java new file mode 100644 index 0000000..b1a1afa --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/DicDataTypeEnum.java @@ -0,0 +1,163 @@ +package com.njcn.product.system.dict.enums; + +import lombok.Getter; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2021/8/5 21:56 + */ +@Getter +public enum DicDataTypeEnum { + /** + * 字典类型名称 + */ + FRONT_TYPE("前置类型","Front_Type"), + POWER_CATEGORY("电源类别","Power_Category"), + POWER_STATION_TYPE("电站类型","Power_Station_Type"), + POWER_GENERATION("发电方式","Power_Generation"), + CONNECTION_MODE("能源消纳方式","Connection_Mode"), + ECC_STAT("用电客户状态","Ecc_Stat"), + DEV_TYPE("终端型号","Dev_Type"), + DEV_VARIETY("终端类型","Dev_Variety"), + DEV_FUN("终端功能","Dev_Fun"), + DEV_STATUS("终端状态","Dev_Status"), + DEV_LEVEL("终端等级","Dev_Level"), + DEV_CONNECT("接线方式","Dev_Connect"), + DEV_MANUFACTURER("制造厂商","Dev_Manufacturers"), + //电压等级用于pms区分交直流 + DEV_VOLTAGE("电压等级","Dev_Voltage"), + //标准电压等级用于pq不区分交直流 + DEV_VOLTAGE_STAND("标准电压等级","Dev_Voltage_Stand"), + PANORAMIC_VOLTAGE("全景电压等级","Panoramic_voltage"), + EVENT_REASON("暂降原因","Event_Reason"), + EVENT_TYPE("暂降类型","Event_Type"), + BUSINESS_TYPE("行业类型","Business_Type"), + INTERFERENCE_SOURCE_TYPE("干扰源类型","Interference_Source"), + ALARM_TYPE("告警类型","alarm_Type"), + DEV_OPS("运维日志","Dev_Ops"), + INDICATOR_TYPE("指标类型","Indicator_Type"), + COMMUNICATE_TYPE("通讯类型","Communicate_Type"), + RATE_TYPE("费率类型","Rate_Type"), + ELE_LOAD_TYPE("用能负荷类型","Ele_Load_Type"), + ELE_STATISTICAL_TYPE("用能统计类型","Ele_Statistical_Type"), + REPORT_TYPE("自定义报表类型","Report_Type"), + LINE_MARK("监测点评分等级","Line_Grade"), + LINE_TYPE("监测点类型","Line_Type"), + STEADY_STATIS("稳态统计指标","Steady_Statis"), + EVENT_STATIS("暂态指标","Event_Statis"), + MONITORING_LABELS("监测点标签","Monitoring_Labels"), + POLLUTION_STATIS("污区图统计类型","Pollution_Statis"), + BENCHMARK_INDICATORS("基准水平评价指标","Benchmark_Indicator"), + LINE_SORT("监测点类别","Line_Sort"), + DATA_TYPE("数据类型","Data_Type"), + PERMEABILITY_TYPE("分布式光伏台区渗透率水平","Permeability_Type"), + ON_NETWORK_STATUS("报告状态","On-network_Status"), + AUDIT_STATUS("审核状态","Audit_Status"), + FILL_PROGRESS("填报进度","Fill_Progress"), + PROBLEM_SOURCES("问题来源","Problem_Sources"), + AREA_PQ_EVENT_TYPE("台区电能质量事件类型","area_pq_event_type"), + LINE_STATE("监测点状态","Line_State"), + DEVICE_STATUS("设备状态","Device_Status"), + //INTERFERENCE_SOURCE("监测对象类别","Interference_Source"), + PLAN_TAKE("计划采取实施","Plan_Take"), + MONITOR_OBJ("监测对象","Monitor_Obj"), + CONNET_GROUP_WAY("牵引站变压器接线方式","Connet_Group_Way"), + WORK_ORDER_STATUS("工单状态","Work_Order_Status"), + PROBLEM_TYPE("问题类型","Problem_Type"), + CHECK_STATUS("审核状态","Check_Status"), + CHECK_RESULT("审核处理","Check_Result"), + WORK_ORDER_PROCESS("工单流程","Work_Order_Process"), + ASSESS_RESULT("评估结果","Assess_Result"), + WORK_ORDER_TYPE("工单类型","Work_Order_Type"), + + PRIMARY_TYPE("一级业务类型","Primary_Type"), + DEV_CLASS("终端类型(治理)","Dev_Class"), + CS_STATISTICAL_TYPE("治理统计类型","Cs_Statistical_Type"), + LINE_POSITION("监测点位置","Line_Position"), + ALARM_LEVEL("警告级别","Alarm_Level"), + + + CS_DATA_TYPE("数据模型类别", "Cs_Data_Type"), + PROBLEM_INDICATORS("问题指标","Problem_Indicators"), + + + //pms + DEV_CATEGORY("装置类别","Device_Category"), + DEV_GRADE("终端等级","Dev_Level"), + INPUT_SIGNAL("测量信号输入形式","Signal_form"), + VOLTAGE_TRANSFORMER("电压互感器类型","Voltage_Transformer"), + Neutral_Point("中性点接地方式","Neutral_Point"), + DEVICE_REGIONLYPE("设备地区特征","Device_RegionLype"), + DEVICE_USERNATURE("设备使用性质代码","Device_UseNature"), + SUPV_TYPE("监督类型","supv_type"), + SUPV_OBJ_TYPE("监督对象类型","supv_obj_type"), + + evaluation_report("评估用户或报告分类编码","evaluation_report"), + + user_class("用户分类","user_class"), + + SUPV_STAGE("监督阶段","supv_stage"), + EFFECT_STATUS("实施状态","effect_status"), + MONITOR_TYPE("监督监测点类型","monitor_type"), + SUPV_PROBLEM_TYPE("监督问题类型","problem_type"), + RECTIFICATION_MEASURE("整改方案","RectificationMeasure"), + + SUPV_PLAN_STATUS("监督计划状态","plan_status"), + BILL_TYPE("单据类型","bill_type"), + SPECIALITY_TYPE("所属专业","speciality_type"), + RECTIFICATION_STATUS_TYPE("整改情况","rectification_status_type"), + file_type("附件分类"," file_type"), + problem_level_type("问题等级"," problem_level_type"), + + Station_Type("所属站别类型","Station_Type"), + + + APP_BASE_INFORMATION_TYPE("app基础信息类型","appInformationType"), + + APP_DEVICE_EVENT_TYPE("app设备事件类型","appDeviceEventType"), + + DEVICE_UNIT("数据单位类型","Device_Unit"), + //国网上送 + pms_disturb_type("pms国网上送干扰源类型","pms_disturb_type"), + pms_disturb_sort("pms国网上送干扰源类别","pms_disturb_sort"), + type_of_station("站房类型","type_of_station"), + File_status("档案状态","File_status"), + USER_CLASS("用户分类","User_Class"), + IMPORTANCE_LEVEL("重要性等级","Importance_Level"), + ELE_CLASS("用电类别","Ele_Class"), + INDUSTRY_TYPE("行业分类","industry_type"), + PLAN_STATUS("计划状态","plan_status"), + APP_EVENT("APP暂态事件类型","app_event"), + DEVICE_TYPE("治理装置类型编码","Device_Type"), + + CARRY_CAPCITY_USER_TYPE("承载能力评估用户类型","carry_capcity_user_type"), + CARRY_CAPCITY_CONNECTION_MODE("变压器连接方式","carry_capcity_connection_mode"), + + CARRY_CAPCITYUSER_MODE("用户模式","carry_capcity_user_mode"), + LOCAL_MUNICIPALITY("所属地市","local_municipality"), + INDUSTRY_TYPE_JB("行业类型-冀北","industry_type_jb"), + LOAD_LEVEL("负荷级别","load_level"), + SUPPLY_CONDITION("供电电源情况","supply_condition"), + + JIBEI_AREA("所属地市","jibei_area"), + Major_Nonlinear_Device("主要非线性设备类型","Major_Nonlinear_Device"), + EVALUATION_DEPT("主要非线性设备类型","evaluation_dept"), + EVALUATION_TYPE("评估类型","Evaluation_Type"), + ; + + + + + + private final String name; + private final String code; + + DicDataTypeEnum(String name,String code){ + this.name=name; + this.code=code; + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/SystemResponseEnum.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/SystemResponseEnum.java new file mode 100644 index 0000000..eeb09a4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/enums/SystemResponseEnum.java @@ -0,0 +1,77 @@ +package com.njcn.product.system.dict.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月20日 09:56 + */ +@Getter +public enum SystemResponseEnum { + + /** + * 系统模块异常响应码的范围: + * A00350 ~ A00449 + */ + SYSTEM_COMMON_ERROR("A00350","系统模块异常"), + DICT_TYPE_NAME_REPEAT("A00351", "字典类型名称重复"), + DICT_DATA_NAME_REPEAT("A00352", "字典数据名称重复"), + AREA_CODE_REPEAT("A00353","行政区域编码重复"), + LOAD_TYPE_EMPTY("A00354","用能负荷数据为空"), + LINE_MARK_EMPTY("A00355","字典监测点评分等级数据为空"), + VOLTAGE_EMPTY("A00356","查询字典电压等级数据为空"), + + INTERFERENCE_EMPTY("A00356","查询字典干扰源类型数据为空"), + BUSINESS_EMPTY("A00356","查询字典行业类型数据为空"), + SYSTEM_TYPE_EMPTY("A00356","查询字典系统类型数据为空"), + DEV_TYPE_EMPTY("A00357","查询字典设备类型数据为空"), + MANUFACTURER("A00358","查询字典终端厂家数据为空"), + DEV_VARIETY("A00359","查询字典终端类型数据为空"), + + /*pms*/ + LINE_TYPE_VARIETY_EMPTY("A00360","查询字典监测点类型数据为空"), + LINE_STATE_EMPTY("A00361","查询字典监测点状态为空"), + LINE_TYPE_EMPTY("A00362","查询字典监测点类型状态为空"), + POTENTIAL_TYPE_EMPTY("A00363","查询字典电压互感器类型为空"), + Neutral_Mode_EMPTY("A00364","查询字典中性点接地方式为空"), + MONITOR_TAG_EMPTY("A00365","查询字典监测点标签类型为空"), + MONITORY_TYPE_EMPTY("A00366","查询字典监测对象类型为空"), + TERMINAL_WIRING_EMPTY("A00367","查询字典监测终端接线方式为空"), + MONITOR_TYPE_EMPTY("A00368","查询字典监测点类别为空"), + ACTIVATED_STATE("A00369","必须存在一个已激活的系统类型"), + ADVANCE_REASON("A00370","查询字典暂降原因为空"), + EFFECT_STATUS_EMPTY("A00370","查询字典实施状态为空"), + + EVENT_REPORT_REPEAT("A00361","暂态报告模板重复"), + NOT_EXISTED("A00361", "您查询的该条记录不存在"), + TIMER_NO_CLASS("A00361", "请检查定时任务是否添加"), + + /** + * 定时任务执行类不存在 + */ + TIMER_NOT_EXISTED("A00361", "定时任务执行类不存在"), + EXE_EMPTY_PARAM("A00361", "请检查定时器的id,定时器cron表达式,定时任务是否为空!"), + + /** + * 审计日志模块异常响应 + */ + NOT_FIND_FILE("A0300", "文件未备份或者备份文件为空,请先备份文件"), + LOG_EXCEPTION("A0301", "导入旧日志文件异常"), + LOG_EXCEPTION_TIME("A0302", "导入旧日志文件异常:缺少时间范围"), + DELETE_DATA("A0303", "导入旧日志文件异常:删除数据失败"), + MULTIPLE_CLICKS_LOG_FILE_WRITER("A0304", "当前文件备份数据未结束,请勿多次点击"), + MULTIPLE_CLICKS_RECOVER_LOG_FILE("A0303", "当前文件恢复数据未结束,请勿多次点击"), + + PAGE_SAME_NAME("A00357","页面名称重复"), + ; + + private final String code; + + private final String message; + + SystemResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictDataMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictDataMapper.java new file mode 100644 index 0000000..40c9ddb --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictDataMapper.java @@ -0,0 +1,61 @@ +package com.njcn.product.system.dict.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.pojo.vo.DictDataVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface DictDataMapper extends BaseMapper { + + /** + * 分页查询字典数据 + * + * @param page 分页数据 + * @param queryWrapper 查询条件 + * @return 字典数据 + */ + Page page(@Param("page") Page page, @Param("ew") QueryWrapper queryWrapper); + + /** + * @param dictypeName 字典类型名称 + * @return 根据字典类型名称查询字典数据 + */ + List getDicDataByTypeName(@Param("dictypeName") String dictypeName); + + DictData getDicDataByName(@Param("dicName") String dicName); + + DictData getDicDataByNameAndType(@Param("dicName") String dicName, @Param("typeName") String typeName); + + DictData getDicDataByCodeAndType(@Param("dicCode") String dicCode, @Param("typeCode") String typeCode); + + DictData getDicDataByCode(@Param("code") String code); + + /** + * 根据字典类型名称&数据名称获取字典数据 + * + * @param dicTypeName 字典类型名称 + * @param dicDataName 字典数据名称 + * @return 字典数据 + */ + DictData getDicDataByNameAndTypeName(@Param("dicTypeName") String dicTypeName, @Param("dicDataName") String dicDataName); + + /** + * @param dictTypeCode 字典类型名称 + * @return 根据字典类型名称查询字典数据 + */ + List getDicDataByTypeCode(@Param("dictTypeCode") String dictTypeCode); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictTypeMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictTypeMapper.java new file mode 100644 index 0000000..981ccef --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/DictTypeMapper.java @@ -0,0 +1,25 @@ +package com.njcn.product.system.dict.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.dict.pojo.po.DictType; +import com.njcn.product.system.dict.pojo.vo.DictDataCache; + + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface DictTypeMapper extends BaseMapper { + + /** + * 查询所有的字典简单信息 + * @return 字典信息 + */ + List dictDataCache(); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictDataMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictDataMapper.xml new file mode 100644 index 0000000..5240452 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictDataMapper.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictTypeMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictTypeMapper.xml new file mode 100644 index 0000000..de9f26c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/mapper/mapping/DictTypeMapper.xml @@ -0,0 +1,25 @@ + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictDataParam.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictDataParam.java new file mode 100644 index 0000000..68f6fd8 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictDataParam.java @@ -0,0 +1,95 @@ +package com.njcn.product.system.dict.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.*; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月17日 15:49 + */ +@Data +public class DictDataParam { + + + @ApiModelProperty("字典类型id") + @NotBlank(message = ValidMessage.DICT_TYPE_ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.DICT_TYPE_ID_FORMAT_ERROR) + private String typeId; + + + @ApiModelProperty("名称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + private String name; + + + @ApiModelProperty("编码") + @NotBlank(message = ValidMessage.CODE_NOT_BLANK) + private String code; + + + @ApiModelProperty("排序") + @NotNull(message = ValidMessage.SORT_NOT_NULL) + @Min(value = 0, message = ValidMessage.SORT_FORMAT_ERROR) + @Max(value = 999, message = ValidMessage.SORT_FORMAT_ERROR) + private Integer sort; + + + @ApiModelProperty("事件等级:0-普通;1-中等;2-严重(默认为0)") + private Integer level; + + @ApiModelProperty("与高级算法内部Id描述对应") + private Integer algoDescribe; + + + @ApiModelProperty("字典值,用于记录字典的计算值如10kV记录为 10") + private String value; + + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DictDataUpdateParam extends DictDataParam { + + /** + * 表Id + */ + @ApiModelProperty("id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DictDataQueryParam extends BaseParam { + + + + } + + /** + * 根据字典类型id分页查询字典数据 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DicTypeIdQueryParam extends BaseParam { + @ApiModelProperty("字典类型id") + @NotBlank(message = ValidMessage.DICT_TYPE_ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.DICT_TYPE_ID_FORMAT_ERROR) + private String typeId; + + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTreeParam.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTreeParam.java new file mode 100644 index 0000000..c73d22a --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTreeParam.java @@ -0,0 +1,84 @@ +package com.njcn.product.system.dict.pojo.param; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月17日 15:49 + */ +@Data +public class DictTreeParam { + + + + /** + * 父id + */ + @ApiModelProperty(value = "父id") + private String pid; + + + /** + * 名称 + */ + @ApiModelProperty(value = "名称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + private String name; + + /** + * 编码 + */ + @TableField(value = "编码") + @NotBlank(message = ValidMessage.CODE_NOT_BLANK) + private String code; + + /** + * 用于区分多种类型的字典树 0.台账对象类型 1.自定义报表指标类型 + */ + private Integer type; + + /** + * 根据type自定义内容,type:0用于区分对象类型是101电网侧 102用户侧 + */ + private String extend; + + /** + * 排序 + */ + private Integer sort; + + /** + * 描述 + */ + private String remark; + + + + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DictTreeUpdateParam extends DictTreeParam { + + + @ApiModelProperty("id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + } + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTypeParam.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTypeParam.java new file mode 100644 index 0000000..83569e1 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/param/DictTypeParam.java @@ -0,0 +1,82 @@ +package com.njcn.product.system.dict.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.*; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月17日 09:40 + */ +@Data +public class DictTypeParam { + + @ApiModelProperty("名称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + private String name; + + @ApiModelProperty("编码") + @NotBlank(message = ValidMessage.CODE_NOT_BLANK) + @Pattern(regexp = PatternRegex.ALL_CHAR_1_20, message = ValidMessage.CODE_FORMAT_ERROR) + private String code; + + + @ApiModelProperty("排序") + @NotNull(message = ValidMessage.SORT_NOT_NULL) + @Min(value = 0, message = ValidMessage.SORT_FORMAT_ERROR) + @Max(value = 999, message = ValidMessage.SORT_FORMAT_ERROR) + private Integer sort; + + + @ApiModelProperty("开启等级:0-不开启;1-开启,默认不开启") + @NotNull(message = ValidMessage.OPEN_LEVEL_NOT_NULL) + @Min(value = 0, message = ValidMessage.OPEN_LEVEL_FORMAT_ERROR) + @Max(value = 1, message = ValidMessage.OPEN_LEVEL_FORMAT_ERROR) + private Integer openLevel; + + + @ApiModelProperty("开启算法描述:0-不开启;1-开启,默认不开启") + @NotNull(message = ValidMessage.OPEN_DESCRIBE_NOT_NULL) + @Min(value = 0, message = ValidMessage.OPEN_DESCRIBE_FORMAT_ERROR) + @Max(value = 1, message = ValidMessage.OPEN_DESCRIBE_FORMAT_ERROR) + private Integer openDescribe; + + + @ApiModelProperty("描述") + private String remark; + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DictTypeUpdateParam extends DictTypeParam { + + + @ApiModelProperty("id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class DictTypeQueryParam extends BaseParam { + + + } + +} + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictData.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictData.java new file mode 100644 index 0000000..13a466d --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictData.java @@ -0,0 +1,65 @@ +package com.njcn.product.system.dict.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_dict_data") +public class DictData extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 字典数据表Id + */ + private String id; + + /** + * 字典类型表Id + */ + private String typeId; + + /** + * 名称 + */ + private String name; + + /** + * 编码 + */ + private String code; + + /** + * 排序 + */ + private Integer sort; + + /** + * 事件等级:0-普通;1-中等;2-严重(默认为0) + */ + private Integer level; + + /** + * 与高级算法内部Id描述对应; + */ + private Integer algoDescribe; + + /** + * 目前只用于表示电压等级数值 + */ + private String value; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictType.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictType.java new file mode 100644 index 0000000..b2b7682 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/po/DictType.java @@ -0,0 +1,62 @@ +package com.njcn.product.system.dict.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_dict_type") +public class DictType extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 字典类型表Id + */ + private String id; + + /** + * 名称 + */ + private String name; + + /** + * 编码 + */ + private String code; + + /** + * 排序 + */ + private Integer sort; + + /** + * 开启等级:0-不开启;1-开启,默认不开启 + */ + private Integer openLevel; + + + /** + * 开启描述:0-不开启;1-开启,默认不开启 + */ + private Integer openDescribe; + + + /** + * 描述 + */ + private String remark; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataCache.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataCache.java new file mode 100644 index 0000000..c9c2ea5 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataCache.java @@ -0,0 +1,33 @@ +package com.njcn.product.system.dict.pojo.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年03月24日 16:06 + */ +@Data +public class DictDataCache implements Serializable { + + private String id; + + private String name; + + private String code; + + private String value; + + private int sort; + + private String typeId; + + private String typeName; + + private String typeCode; + + private Integer algoDescribe; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataVO.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataVO.java new file mode 100644 index 0000000..628bf95 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/pojo/vo/DictDataVO.java @@ -0,0 +1,63 @@ +package com.njcn.product.system.dict.pojo.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月20日 15:52 + */ +@Data +public class DictDataVO implements Serializable { + + + private static final long serialVersionUID = 1L; + + /** + * 字典数据表Id + */ + private String id; + + /** + * 字典类型表名称 + */ + private String typeName; + + /** + * 名称 + */ + private String name; + + /** + * 编码 + */ + private String code; + + /** + * 排序 + */ + private Integer sort; + + /** + * 事件等级:0-普通;1-中等;2-严重(默认为0) + */ + private Integer level; + + /** + * 与高级算法内部Id描述对应; + */ + private Integer algoDescribe; + + /** + * 字典值 + */ + private String value; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictDataService.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictDataService.java new file mode 100644 index 0000000..16ea5fe --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictDataService.java @@ -0,0 +1,123 @@ +package com.njcn.product.system.dict.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.dict.pojo.param.DictDataParam; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.pojo.vo.DictDataVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IDictDataService extends IService { + + /** + * 根据前台传递参数,分页查询字典数据 + * @param queryParam 查询参数 + * @return 字典列表 + */ + Page listDictData(DictDataParam.DictDataQueryParam queryParam); + + /** + * 新增数据字典 + * @param dictDataParam 字典数据 + * @return 操作结果 + */ + boolean addDictData(DictDataParam dictDataParam); + + /** + * 更新字典数据 + * @param updateParam 字典数据 + * @return 操作结果 + */ + boolean updateDictData(DictDataParam.DictDataUpdateParam updateParam); + + /** + * 批量逻辑删除字典数据 + * @param ids 字典id集合 + * @return 操作结果 + */ + boolean deleteDictData(List ids); + + /** + * 根据字典类型id查询字典信息 + */ + Page getTypeIdData(DictDataParam.DicTypeIdQueryParam queryParam); + + /** + * + * @param dicIndex 字典id + * @return 根据字典id查询字典数据 + */ + DictData getDicDataById(String dicIndex); + + /** + * + * @param dictypeName 字典类型名称 + * @return 根据字典类型名称查询字典数据 + */ + List getDicDataByTypeName(String dictypeName); + + /** + * + * @param dictTypeCode 字典类型code + * @return 根据字典类型名称查询字典数据 + */ + List getDicDataByTypeCode(String dictTypeCode); + + /** + * + * @param dicName 字典名称 + * @return 根据字典名称查询字典数据 + */ + DictData getDicDataByName(String dicName); + + /** + * + * @param dicName 字典名称,类型名称 + * @return 根据字典名称查询字典数据 + */ + DictData getDicDataByNameAndType(String dicName,String typeName); + + /** + * + * @param dicCode 字典Code,类型名称 + * @return 根据字典Code查询字典数据 + */ + DictData getDicDataByCodeAndType(String dicCode,String typeCode); + /** + * + * @param code 字典code + * @return 根据字典code查询字典数据 + */ + DictData getDicDataByCode(String code); + + + /** + * 根据字典类型名称&数据名称获取字典数据 + * + * @param dicTypeName 字典类型名称 + * @param dicDataName 字典数据名称 + * @return 字典数据 + */ + DictData getDicDataByNameAndTypeName(String dicTypeName, String dicDataName); + + /** + * 后台新增字典数据 + * @param dicTypeName 类型名称 + * @param dicDataName 数据名称 + * @return 新增后的字典数据 + */ + DictData addDictData(String dicTypeName, String dicDataName); + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictTypeService.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictTypeService.java new file mode 100644 index 0000000..5c75dab --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/IDictTypeService.java @@ -0,0 +1,67 @@ +package com.njcn.product.system.dict.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.common.pojo.dto.SimpleTreeDTO; +import com.njcn.product.system.dict.pojo.param.DictTypeParam; +import com.njcn.product.system.dict.pojo.po.DictType; + + +import java.util.List; + +/** + * @author hongawen + * @since 2021-12-13 + */ +public interface IDictTypeService extends IService { + + /** + * 根据前台传递参数,分页查询字典类型数据 + * @param queryParam 查询参数 + * @return 字典列表 + */ + Page listDictTypes(DictTypeParam.DictTypeQueryParam queryParam); + + /** + * 新增字典类型数据 + * + * @param dictTypeParam 字典类型数据 + * @return 操作结果 + */ + boolean addDictType(DictTypeParam dictTypeParam); + + /** + * 修改字典类型 + * + * @param updateParam 字典类型数据 + * @return 操作结果 + */ + boolean updateDictType(DictTypeParam.DictTypeUpdateParam updateParam); + + /** + * 批量逻辑删除字典类型数据 + * @param ids id集合 + * @return 操作结果 + */ + boolean deleteDictType(List ids); + + /** + * 获取所有字典数据基础信息 + * @return 返回所有字典数据 + */ + List dictDataCache(); + + /** + * 根据名称获取字典类型数据 + * @param dicTypeName 类型名称 + * @return 类型数据 + */ + DictType getByName(String dicTypeName); + + /** + * 根据名称新增字典类型数据 + * @param dicTypeName 类型名称 + * @return 类型数据 + */ + DictType addByName(String dicTypeName); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictDataServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictDataServiceImpl.java new file mode 100644 index 0000000..9237474 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictDataServiceImpl.java @@ -0,0 +1,203 @@ +package com.njcn.product.system.dict.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.db.constant.DbConstant; + +import com.njcn.product.system.dict.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.mapper.DictDataMapper; +import com.njcn.product.system.dict.pojo.param.DictDataParam; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.system.dict.pojo.po.DictType; +import com.njcn.product.system.dict.pojo.vo.DictDataVO; +import com.njcn.product.system.dict.service.IDictDataService; +import com.njcn.product.system.dict.service.IDictTypeService; +import com.njcn.product.system.dict.enums.SystemResponseEnum; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Objects; + +/** + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DictDataServiceImpl extends ServiceImpl implements IDictDataService { + + private final IDictTypeService dictTypeService; + + + @Override + public Page listDictData(DictDataParam.DictDataQueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //字典类型表,仅提供名称、编码模糊查询 + queryWrapper + .and(param -> param.like("sys_dict_data.name", queryParam.getSearchValue()) + .or().like("sys_dict_data.code", queryParam.getSearchValue())); + } + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + //没有排序参数,默认根据sort字段排序,没有排序字段的,根据updateTime更新时间排序 + queryWrapper.orderBy(true, true, "sys_dict_data.sort"); + } + } + queryWrapper.ne("sys_dict_data.state", DataStateEnum.DELETED.getCode()); + //初始化分页数据 + return this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + } + + @Override + public boolean addDictData(DictDataParam dictDataParam) { + checkDicDataName(dictDataParam, false); + DictData dictData = new DictData(); + BeanUtil.copyProperties(dictDataParam, dictData); + //默认为正常状态 + dictData.setState(DataStateEnum.ENABLE.getCode()); + return this.save(dictData); + } + + @Override + public boolean updateDictData(DictDataParam.DictDataUpdateParam updateParam) { + checkDicDataName(updateParam, true); + DictData dictData = new DictData(); + BeanUtil.copyProperties(updateParam, dictData); + return this.updateById(dictData); + } + + @Override + public boolean deleteDictData(List ids) { + return this.lambdaUpdate() + .set(DictData::getState, DataStateEnum.DELETED.getCode()) + .in(DictData::getId, ids) + .update(); + } + + @Override + public Page getTypeIdData(DictDataParam.DicTypeIdQueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //字典类型表,仅提供名称、编码模糊查询 + queryWrapper + .and(param -> param.like("sys_dict_data.name", queryParam.getSearchValue()) + .or().like("sys_dict_data.code", queryParam.getSearchValue())); + } + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + //没有排序参数,默认根据sort字段排序,没有排序字段的,根据updateTime更新时间排序 + queryWrapper.orderBy(true, true, "sys_dict_data.sort"); + } + } + queryWrapper.ne("sys_dict_data.state", DataStateEnum.DELETED.getCode()); + queryWrapper.eq("sys_dict_data.type_id", queryParam.getTypeId()); + //初始化分页数据 + return this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + } + + @Override + public DictData getDicDataById(String dicIndex) { + + return this.baseMapper.selectById(dicIndex); + } + + @Override + public List getDicDataByTypeName(String dictTypeName) { + + return this.baseMapper.getDicDataByTypeName(dictTypeName); + } + + @Override + public List getDicDataByTypeCode(String dictTypeCode) { + + return this.baseMapper.getDicDataByTypeCode(dictTypeCode); + } + + + @Override + public DictData getDicDataByName(String dicName) { + return this.baseMapper.getDicDataByName(dicName); + } + + @Override + public DictData getDicDataByNameAndType(String dicName, String typeName) { + return this.baseMapper.getDicDataByNameAndType(dicName, typeName); + } + + @Override + public DictData getDicDataByCodeAndType(String dicCode, String typeCode) { + return this.baseMapper.getDicDataByCodeAndType(dicCode, typeCode); + } + + @Override + public DictData getDicDataByCode(String code) { + return this.baseMapper.getDicDataByCode(code); + } + + + + @Override + public DictData getDicDataByNameAndTypeName(String dicTypeName, String dicDataName) { + return this.baseMapper.getDicDataByNameAndTypeName(dicTypeName, dicDataName); + } + + @Override + public DictData addDictData(String dicTypeName, String dicDataName) { + //根据type名称获取index,如果不存在该字典类型,则新增该字典类型 + DictType dictType = dictTypeService.getByName(dicTypeName); + if (Objects.isNull(dictType)) { + dictType = dictTypeService.addByName(dicTypeName); + } + DictData dictData = new DictData(); + dictData.setTypeId(dictType.getId()); + dictData.setName(dicDataName); + dictData.setCode(dicDataName); + dictData.setSort(0); + dictData.setLevel(0); + dictData.setState(DataStateEnum.ENABLE.getCode()); + this.save(dictData); + return dictData; + } + + /** + * 校验参数,检查是否存在相同名称的字典类型 + */ + private void checkDicDataName(DictDataParam dictDataParam, boolean isExcludeSelf) { + LambdaQueryWrapper dictDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + dictDataLambdaQueryWrapper + .eq(DictData::getName, dictDataParam.getName()) + .eq(DictData::getTypeId, dictDataParam.getTypeId()) + .eq(DictData::getState, DataStateEnum.ENABLE.getCode()); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (dictDataParam instanceof DictDataParam.DictDataUpdateParam) { + dictDataLambdaQueryWrapper.ne(DictData::getId, ((DictDataParam.DictDataUpdateParam) dictDataParam).getId()); + } + } + int countByAccount = this.count(dictDataLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(SystemResponseEnum.DICT_DATA_NAME_REPEAT); + } + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictTypeServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictTypeServiceImpl.java new file mode 100644 index 0000000..909a4aa --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/dict/service/impl/DictTypeServiceImpl.java @@ -0,0 +1,159 @@ +package com.njcn.product.system.dict.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.common.pojo.dto.SimpleTreeDTO; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.db.constant.DbConstant; + +import com.njcn.product.system.dict.mapper.DictTypeMapper; +import com.njcn.product.system.dict.pojo.param.DictTypeParam; +import com.njcn.product.system.dict.pojo.po.DictType; +import com.njcn.product.system.dict.pojo.vo.DictDataCache; +import com.njcn.product.system.dict.service.IDictTypeService; +import com.njcn.product.system.dict.enums.SystemResponseEnum; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +public class DictTypeServiceImpl extends ServiceImpl implements IDictTypeService { + + @Override + public Page listDictTypes(DictTypeParam.DictTypeQueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //字典类型表,仅提供名称、编码模糊查询 + queryWrapper + .and(param -> param.like("sys_dict_type.name", queryParam.getSearchValue()) + .or().like("sys_dict_type.code", queryParam.getSearchValue()) + ); + } + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + //没有排序参数,默认根据sort字段排序,没有排序字段的,根据updateTime更新时间排序 + queryWrapper.orderBy(true, true, "sys_dict_type.sort"); + } + } + queryWrapper.ne("sys_dict_type.state", DataStateEnum.DELETED.getCode()); + return this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + } + + @Override + public boolean addDictType(DictTypeParam dictTypeParam) { + checkDicTypeName(dictTypeParam, false); + DictType dictType = new DictType(); + BeanUtil.copyProperties(dictTypeParam, dictType); + //默认为正常状态 + dictType.setState(DataStateEnum.ENABLE.getCode()); + return this.save(dictType); + } + + @Override + public boolean updateDictType(DictTypeParam.DictTypeUpdateParam updateParam) { + checkDicTypeName(updateParam, true); + DictType dictType = new DictType(); + BeanUtil.copyProperties(updateParam, dictType); + return this.updateById(dictType); + } + + @Override + public boolean deleteDictType(List ids) { + return this.lambdaUpdate() + .set(DictType::getState, DataStateEnum.DELETED.getCode()) + .in(DictType::getId, ids) + .update(); + } + + + @Override + public List dictDataCache() { + List allDictData = this.baseMapper.dictDataCache(); + Map> dictDataCacheMap = allDictData.stream() + .collect(Collectors.groupingBy(DictDataCache::getTypeId)); + return dictDataCacheMap.keySet().stream().map(typeId -> { + SimpleTreeDTO simpleTreeDTO = new SimpleTreeDTO(); + List dictDataCaches = dictDataCacheMap.get(typeId); + List simpleDTOList = dictDataCaches.stream().map(dictDataCache -> { + simpleTreeDTO.setCode(dictDataCache.getTypeCode()); + simpleTreeDTO.setId(dictDataCache.getTypeId()); + simpleTreeDTO.setName(dictDataCache.getTypeName()); + SimpleDTO simpleDTO = new SimpleDTO(); + simpleDTO.setCode(dictDataCache.getCode()); + simpleDTO.setId(dictDataCache.getId()); + simpleDTO.setName(dictDataCache.getName()); + simpleDTO.setSort(dictDataCache.getSort()); + simpleDTO.setValue(dictDataCache.getValue()); + simpleDTO.setAlgoDescribe(dictDataCache.getAlgoDescribe()); + return simpleDTO; + }).sorted(Comparator.comparing(SimpleDTO::getSort)).collect(Collectors.toList()); + simpleTreeDTO.setChildren(simpleDTOList); + return simpleTreeDTO; + }).collect(Collectors.toList()); + } + + @Override + public DictType getByName(String dicTypeName) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(DictType::getName, dicTypeName) + .eq(DictType::getState, DataStateEnum.ENABLE.getCode()); + return this.baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public DictType addByName(String dicTypeName) { + DictType dictType = new DictType(); + dictType.setName(dicTypeName); + dictType.setCode(dicTypeName); + dictType.setSort(0); + dictType.setOpenDescribe(0); + dictType.setOpenLevel(0); + dictType.setState(DataStateEnum.ENABLE.getCode()); + this.save(dictType); + return dictType; + } + + + + /** + * 校验参数,检查是否存在相同名称的字典类型 + */ + private void checkDicTypeName(DictTypeParam dictTypeParam, boolean isExcludeSelf) { + LambdaQueryWrapper dictTypeLambdaQueryWrapper = new LambdaQueryWrapper<>(); + dictTypeLambdaQueryWrapper + .eq(DictType::getName, dictTypeParam.getName()) + .eq(DictType::getState, DataStateEnum.ENABLE.getCode()); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (dictTypeParam instanceof DictTypeParam.DictTypeUpdateParam) { + dictTypeLambdaQueryWrapper.ne(DictType::getId, ((DictTypeParam.DictTypeUpdateParam) dictTypeParam).getId()); + } + } + int countByAccount = this.count(dictTypeLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(SystemResponseEnum.DICT_TYPE_NAME_REPEAT); + } + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ConfigController.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ConfigController.java new file mode 100644 index 0000000..e7fb163 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ConfigController.java @@ -0,0 +1,216 @@ +package com.njcn.product.system.theme.controller; + + + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.common.utils.LogUtil; + +import com.njcn.product.system.dict.enums.SystemResponseEnum; +import com.njcn.product.system.theme.pojo.param.ConfigParam; +import com.njcn.product.system.theme.pojo.po.Config; +import com.njcn.product.system.theme.service.IConfigService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.util.CollectionUtils; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Objects; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Api(tags = "系统配置操作") +@RestController +@RequestMapping("/config") +@RequiredArgsConstructor +public class ConfigController extends BaseController { + + private final IConfigService iConfigService; + + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getSysConfig") + @ApiOperation("获取系统配置") + public HttpResult getSysConfig() { + String methodDescribe = getMethodDescribe("getSysConfig"); + LogUtil.njcnDebug(log, "{}", methodDescribe, methodDescribe); + Config config = iConfigService.lambdaQuery() + .eq(Config::getState, DataStateEnum.ENABLE.getCode()) + .one(); + if (Objects.isNull(config)) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, config, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getSysConfigData") + @ApiOperation("获取系统配置列表") + public HttpResult> getSysConfigData() { + String methodDescribe = getMethodDescribe("getSysConfigData"); + LogUtil.njcnDebug(log, "{}", methodDescribe, methodDescribe); + List res = iConfigService.getList(); + if (CollectionUtils.isEmpty(res)) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, res, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getSysConfigById") + @ApiOperation("根据配置Id获取系统配置") + @ApiImplicitParam(name = "id", value = "参数id", required = true) + public HttpResult getSysConfigById(@RequestParam("id") String id) { + String methodDescribe = getMethodDescribe("getSysConfigById"); + LogUtil.njcnDebug(log, "{}", methodDescribe, id); + Config config = iConfigService.getById(id); + if (Objects.isNull(config)) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, config, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/updateSysConfigById") + @ApiOperation("根据配置Id更改(激活)系统状态") + @ApiImplicitParam(name = "id", value = "参数id", required = true) + public HttpResult updateSysConfigById(@RequestParam("id") String id) { + String methodDescribe = getMethodDescribe("updateSysConfigById"); + LogUtil.njcnDebug(log, "{}", methodDescribe, id); + Config config = iConfigService.getById(id); + if (!Objects.isNull(config)) { + iConfigService.update( new UpdateWrapper().eq("sys_config.State", DataStateEnum.ENABLE.getCode()) + .set("sys_config.State", DataStateEnum.DELETED.getCode())); + iConfigService.update( new UpdateWrapper().eq("sys_config.Id", id) + .set("sys_config.State", DataStateEnum.ENABLE.getCode())); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + }else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ID_NOT_EXIST, null, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/removeSysConfigById") + @ApiOperation("根据配置Id删除系统配置") + @ApiImplicitParam(name = "id", value = "参数id", required = true) + public HttpResult removeSysConfigById(@RequestParam("id") String id) { + String methodDescribe = getMethodDescribe("removeSysConfigById"); + LogUtil.njcnDebug(log, "{}", methodDescribe, id); + int count = iConfigService.count(new LambdaQueryWrapper() + .eq(Config::getState, DataStateEnum.ENABLE.getCode()) + .ne(Config::getId, id)); + if(count==0){ + //不可更改当前激活状态,必须保留一个激活系统 + throw new BusinessException(SystemResponseEnum.ACTIVATED_STATE); + } + boolean res = iConfigService.removeById(id); + if (res) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ID_NOT_EXIST, null, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/addSysConfig") + @ApiOperation("新增系统配置") + @ApiImplicitParam(name = "configParam", value = "新增配置实体", required = true) + public HttpResult addSysConfig(@RequestBody @Validated ConfigParam configParam) { + String methodDescribe = getMethodDescribe("addSysConfig"); + LogUtil.njcnDebug(log, "{}", methodDescribe, configParam); + boolean res = iConfigService.addSysConfig(configParam); + if (res) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + throw new BusinessException(CommonResponseEnum.FAIL); + } + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/updateSysConfig") + @ApiOperation("修改系统配置") + @ApiImplicitParam(name = "configUpdateParam", value = "更新配置实体", required = true) + public HttpResult updateSysConfig(@RequestBody @Validated ConfigParam.ConfigUpdateParam configUpdateParam) { + String methodDescribe = getMethodDescribe("updateSysConfig"); + LogUtil.njcnDebug(log, "{}", methodDescribe, configUpdateParam); + boolean res = iConfigService.updateSysConfig(configUpdateParam); + if (res) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } else { + throw new BusinessException(CommonResponseEnum.FAIL); + } + } + + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/系统扩容操作") + @ApiOperation("系统扩容操作") + public HttpResult addMemory(@RequestParam("size")Integer sizeInMB) { + String methodDescribe = getMethodDescribe("addMemory"); + + try { + // 将MB转换为字节 + long sizeInBytes = sizeInMB * 1024 * 1024; + + // 分配一个足够大的byte数组 + byte[] memory = new byte[(int) sizeInBytes]; + + // 为了确保JVM不会优化掉这个内存分配(因为它可能认为这个变量未使用), + // 我们可以对数组进行简单的操作,比如填充数据 + for (int i = 0; i < memory.length; i++) { + // 简单的数据填充 + memory[i] = (byte) (i % 256); + } + + // 实际上,你可能不需要对数组进行填充,因为仅仅是分配就足以占用内存。 + // 但填充可以确保内存被实际使用,而不是被JVM优化掉。 + + // 注意:这里有一个int类型的限制,因为数组长度是int类型。 + // 如果你需要分配超过Integer.MAX_VALUE字节的内存,你将需要找到其他方法(比如使用多个数组) + + System.out.println("Allocated approximately " + sizeInMB + " MB of memory."); + + // 为了让效果更明显,你可以尝试保持这个引用,或者让这个方法运行足够长的时间 + // 以便你可以观察JVM的行为(比如,使用jconsole或jvisualvm等工具) + // 注意:在实际应用中,你应该在不再需要时释放这个引用,以避免内存泄漏。 + + } catch (OutOfMemoryError e) { + System.err.println("Failed to allocate memory: " + e.getMessage()); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/FunctionController.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/FunctionController.java new file mode 100644 index 0000000..9cd8a4a --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/FunctionController.java @@ -0,0 +1,149 @@ +package com.njcn.product.system.theme.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.common.utils.LogUtil; + +import com.njcn.product.system.theme.pojo.vo.FunctionVO; +import com.njcn.product.system.theme.service.IFunctionService; +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; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/function") +@Api(tags = "菜单信息管理") +@AllArgsConstructor +public class FunctionController extends BaseController { + + private final IFunctionService functionService; + +// /** +// * 新增资源 +// * @param functionParam 资源数据 +// */ +// @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) +// @PostMapping("/add") +// @ApiOperation("新增菜单") +// @ApiImplicitParam(name = "functionParam", value = "菜单数据", required = true) +// public HttpResult add(@RequestBody @Validated FunctionParam functionParam) { +// String methodDescribe = getMethodDescribe("add"); +// LogUtil.njcnDebug(log, "{},菜单数据为:{}", methodDescribe, functionParam); +// boolean result = functionService.addFunction(functionParam); +// if (result) { +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); +// } else { +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); +// } +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) +// @PutMapping("/update") +// @ApiOperation("修改菜单") +// @ApiImplicitParam(name = "functionParam", value = "菜单数据", required = true) +// public HttpResult update(@RequestBody @Validated FunctionParam.FunctionUpdateParam functionParam) { +// String methodDescribe = getMethodDescribe("update"); +// LogUtil.njcnDebug(log, "{},更新的菜单信息为:{}", methodDescribe,functionParam); +// boolean result = functionService.updateFunction(functionParam); +// if (result){ +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); +// } else { +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); +// } +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) +// @DeleteMapping("/delete") +// @ApiOperation("删除菜单") +// @ApiImplicitParam(name = "id", value = "菜单id", required = true) +// public HttpResult delete(@RequestParam @Validated String id) { +// String methodDescribe = getMethodDescribe("delete"); +// LogUtil.njcnDebug(log, "{},删除的菜单id为:{}", methodDescribe,id); +// functionService.deleteFunction(id); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @GetMapping("/functionTree") +// @ApiOperation("菜单树") +// public HttpResult> getFunctionTree() { +// String methodDescribe = getMethodDescribe("getFunctionTree"); +// List list = functionService.getFunctionTree(); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,list,methodDescribe); +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @GetMapping("/getFunctionById") +// @ApiOperation("菜单详情") +// @ApiImplicitParam(name = "id", value = "菜单id", required = true) +// public HttpResult getFunctionById(String id){ +// String methodDescribe = getMethodDescribe("getFunctionById"); +// LogUtil.njcnDebug(log, "{},菜单id为:{}", methodDescribe,id); +// Function function = functionService.getFunctionById(id); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,function,methodDescribe); +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @GetMapping("/getButtonById") +// @ApiOperation("获取按钮") +// @ApiImplicitParam(name = "id", value = "菜单id", required = true) +// public HttpResult> getButtonById(String id){ +// String methodDescribe = getMethodDescribe("getButtonById"); +// LogUtil.njcnDebug(log, "{},菜单id为:{}", methodDescribe,id); +// List list = functionService.getButtonsById(id); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,list,methodDescribe); +// } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getRouteMenu") + @ApiOperation("路由菜单") + public HttpResult> getRouteMenu(){ + String methodDescribe = getMethodDescribe("getRouteMenu"); + List list = functionService.getRouteMenu(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,list,methodDescribe); + } +// +// @OperateInfo(operateType = OperateType.UPDATE,info = LogEnum.SYSTEM_MEDIUM) +// @PostMapping("/assignFunctionByRoleIndexes") +// @ApiOperation("角色分配菜单") +// @ApiImplicitParam(name = "roleFunctionComponent", value = "角色信息", required = true) +// public HttpResult assignFunctionByRoleIndexes(@RequestBody @Validated RoleParam.RoleFunctionComponent roleFunctionComponent) { +// String methodDescribe = getMethodDescribe("assignFunctionByRoleIndexes"); +// LogUtil.njcnDebug(log, "{},传入的角色id和资源id集合为:{}", methodDescribe,roleFunctionComponent); +// boolean result = functionService.updateRoleComponent(roleFunctionComponent); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @GetMapping("/userFunctionTree") +// @ApiOperation("用户菜单树") +// public HttpResult> getUserFunctionTree() { +// String methodDescribe = getMethodDescribe("getUserFunctionTree"); +// List list = functionService.getUserFunctionTree(); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,list,methodDescribe); +// } +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ThemeController.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ThemeController.java new file mode 100644 index 0000000..1c1dcb4 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/controller/ThemeController.java @@ -0,0 +1,55 @@ +package com.njcn.product.system.theme.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.product.system.theme.pojo.po.Theme; +import com.njcn.product.system.theme.service.IThemeService; +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; + +/** + *

+ * 前端控制器 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/theme") +@Api(tags = "主题管理") +@AllArgsConstructor +public class ThemeController extends BaseController { + + private final IThemeService themeService; + + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getTheme") + @ApiOperation("当前主题") + public HttpResult getTheme(){ + String methodDescribe = getMethodDescribe("getTheme"); + Theme theme = themeService.getTheme(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,theme,methodDescribe); + } + + +} + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ConfigMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ConfigMapper.java new file mode 100644 index 0000000..3342873 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ConfigMapper.java @@ -0,0 +1,21 @@ +package com.njcn.product.system.theme.mapper; + + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.theme.pojo.po.Config; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface ConfigMapper extends BaseMapper { + + List getList(); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/FunctionMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/FunctionMapper.java new file mode 100644 index 0000000..1af2d83 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/FunctionMapper.java @@ -0,0 +1,29 @@ +package com.njcn.product.system.theme.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.system.theme.pojo.po.Function; +import com.njcn.product.system.theme.pojo.vo.FunctionVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface FunctionMapper extends BaseMapper { + + List getAllFunctions(); + + List getFunctionsByList(@Param("list")List functionList); + + List getUserFunctionsByList(@Param("list")List functionList); + + List getByList(@Param("list")List functionList); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/HomePageMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/HomePageMapper.java new file mode 100644 index 0000000..ef6cd5a --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/HomePageMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.system.theme.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.theme.pojo.po.HomePage; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface HomePageMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/RoleFunctionMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/RoleFunctionMapper.java new file mode 100644 index 0000000..64a13bf --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/RoleFunctionMapper.java @@ -0,0 +1,25 @@ +package com.njcn.product.system.theme.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.theme.pojo.po.RoleFunction; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface RoleFunctionMapper extends BaseMapper { + /** + * 根据角色id集合查询是否绑定 + * @param ids + * @return + */ + List selectRoleFunction(@Param("ids")List ids); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ThemeMapper.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ThemeMapper.java new file mode 100644 index 0000000..41fa66b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/ThemeMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.system.theme.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.system.theme.pojo.po.Theme; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface ThemeMapper extends BaseMapper { + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/ConfigMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/ConfigMapper.xml new file mode 100644 index 0000000..e0087fa --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/ConfigMapper.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/FunctionMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/FunctionMapper.xml new file mode 100644 index 0000000..d24d6db --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/FunctionMapper.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/RoleFunctionMapper.xml b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/RoleFunctionMapper.xml new file mode 100644 index 0000000..2399ded --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/mapper/mapping/RoleFunctionMapper.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/ConfigParam.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/ConfigParam.java new file mode 100644 index 0000000..9d56cb0 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/ConfigParam.java @@ -0,0 +1,78 @@ +package com.njcn.product.system.theme.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.*; +import java.math.BigDecimal; + +/** + * @version 1.0.0 + * @author: chenchao + * @date: 2022/08/09 15:23 + */ +@Data +public class ConfigParam { + + /** + * 系统类型 + */ + @ApiModelProperty("系统类型:0-省级系统;1-企业系统;2-数据中心") + @NotNull(message = "系统类型不可为空") + @Max(value = 2) + @Min(value = 0) + private Integer type; + + /** + * 数据上报 + */ + @ApiModelProperty("数据上报(以逗号分割,比如:冀北,网公司)默认为空") + private String dataReport; + + /** + * 审计日志大小 + */ + @ApiModelProperty("审计日志大小(MB)") + @NotNull(message = "审计日志大小不可为空") + @Min(value = 1024,message = "审计日志大小不能小于1024M") + @Max(value = 204800,message = "审计日志大小不能大于20G") + private BigDecimal logSize; + + /** + * 审计日志保留时间 + */ + @ApiModelProperty("审计日志存储时间(1-6个月,默认3个月)") + @Min(value = 1,message = "审计日志保留时间不能小于1") + @Max(value = 6,message = "审计日志保留时间不能大于6") + private Integer logTime; + + /** + * 系统类型 + */ + @ApiModelProperty("激活状态:0-未激活;1-激活") + @NotNull(message = "激活状态不可为空") + @Max(value = 1) + @Min(value = 0) + private Integer state; + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class ConfigUpdateParam extends ConfigParam { + + /** + * id + */ + @ApiModelProperty("配置Id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/FunctionParam.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/FunctionParam.java new file mode 100644 index 0000000..d0b6217 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/FunctionParam.java @@ -0,0 +1,77 @@ +package com.njcn.product.system.theme.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.auth.pojo.constant.UserValidMessage; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/1/17 10:25 + */ +@Data +public class FunctionParam { + + @ApiModelProperty("节点") + @NotBlank(message = UserValidMessage.PID_NOT_BLANK) + private String pid; + + @ApiModelProperty("名称") + @NotBlank(message = UserValidMessage.USERNAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.FUNCTION_NAME, message = ValidMessage.NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("资源标识") + @NotBlank(message = UserValidMessage.CODE_NOT_BLANK) + private String code; + + @ApiModelProperty("路径") + @NotBlank(message = UserValidMessage.PATH_NOT_BLANK) + @Pattern(regexp = PatternRegex.FUNCTION_URL, message = UserValidMessage.PATH_FORMAT_ERROR) + private String path; + + @ApiModelProperty("图标") + private String icon; + + @ApiModelProperty("排序") + @NotNull(message = UserValidMessage.SORT_NOT_BLANK) + @Range(min = 0, max = 999, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer sort; + + @ApiModelProperty("资源类型") + @NotNull(message = UserValidMessage.TYPE_NOT_BLANK) + @Range(min = 0, max = 4, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer type; + + @ApiModelProperty("描述") + private String remark; + + @ApiModelProperty("路由名称") + private String routeName; + + /** + * 资源更新操作实体 + * 需要填写的参数:资源的id + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class FunctionUpdateParam extends FunctionParam { + + @ApiModelProperty("资源Id") + @NotBlank(message = UserValidMessage.FUNCTION_ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.FUNCTION_ID_FORMAT_ERROR) + private String id; + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/HomePageParam.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/HomePageParam.java new file mode 100644 index 0000000..6e5e386 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/HomePageParam.java @@ -0,0 +1,62 @@ +package com.njcn.product.system.theme.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.auth.pojo.constant.UserValidMessage; +import com.njcn.web.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/1/18 16:14 + */ +@Data +public class HomePageParam { + + @ApiModelProperty("自定义页面名称") + private String name; + + @ApiModelProperty("布局模板") + @NotBlank(message = UserValidMessage.LAYOUT_NOT_BLANK) + private String layout; + + @ApiModelProperty("路径") + @NotBlank(message = UserValidMessage.PATH_NOT_BLANK) + private String path; + + @ApiModelProperty("排序") + @NotNull(message = UserValidMessage.SORT_NOT_BLANK) + @Range(min = 0, max = 999, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer sort; + + @ApiModelProperty("图标") + private String icon; + + /** + * 首页操作实体 + * 需要填写的参数:首页的id + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class HomePageUpdateParam extends HomePageParam { + + @ApiModelProperty("首页Id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + } + + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/RoleParam.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/RoleParam.java new file mode 100644 index 0000000..562f116 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/param/RoleParam.java @@ -0,0 +1,85 @@ +package com.njcn.product.system.theme.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.web.constant.ValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * @author denghuajun + * @date 2022/01/17 14:39 + * 角色 + */ +@Data +public class RoleParam { + + + + @ApiModelProperty("名称") + @NotBlank(message = ValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.DEPT_NAME_REGEX, message = ValidMessage.NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("角色代码") + @NotNull(message = ValidMessage.CODE_NOT_BLANK) + private String code; + + /** + * 角色类型 0:超级管理员;1:管理员;2:普通用户 + */ + @ApiModelProperty("角色类型") + private Integer type; + + @ApiModelProperty("角色描述") + private String remark; + + + + + + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class RoleUpdateParam extends RoleParam { + + /** + * 表Id + */ + @ApiModelProperty("id") + @NotBlank(message = ValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = ValidMessage.ID_FORMAT_ERROR) + private String id; + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class QueryParam extends BaseParam { + + /** + * 权限类型 + */ + private Integer type; + } + /** + * 角色的相关关联 + */ + @Data + public static class RoleFunctionComponent { + private String id; + private List idList; + + } +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Config.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Config.java new file mode 100644 index 0000000..517eccb --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Config.java @@ -0,0 +1,53 @@ +package com.njcn.product.system.theme.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_config") +public class Config extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 配置Id + */ + private String id; + + /** + * 系统类型:0-省级系统;1-企业系统;2-数据中心 + */ + private Integer type; + + /** + * 数据上报(以逗号分割,比如:冀北,网公司)默认为空 + */ + private String dataReport; + + /** + * 审计日志大小(MB) + */ + private BigDecimal logSize; + + /** + * 审计日志存储时间(1-6个月,默认3个月) + */ + private Integer logTime; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Function.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Function.java new file mode 100644 index 0000000..b039a44 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Function.java @@ -0,0 +1,80 @@ +package com.njcn.product.system.theme.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_function") +public class Function extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 资源表Id + */ + private String id; + + /** + * 父节点(0为根节点) + */ + private String pid; + + /** + * 所有上层节点 + */ + private String pids; + + /** + * 名称 + */ + private String name; + + /** + * 资源标识 + */ + private String code; + + /** + * 路径 + */ + private String path; + + /** + * 图标(没有图标则默认为null) + */ + private String icon; + + /** + * 排序 + */ + private Integer sort; + + /** + * 资源类型:0-菜单、1-按钮、2-公共资源、3-服务间调用资源 4-tab页 + */ + private Integer type; + + /** + * 资源描述 + */ + private String remark; + + /** + * 资源状态:0-删除 1-正常(默认为正常) + */ + private Integer state; + + /** + * 路由名称 + */ + private String routeName; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/HomePage.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/HomePage.java new file mode 100644 index 0000000..5444922 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/HomePage.java @@ -0,0 +1,60 @@ +package com.njcn.product.system.theme.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_home_page") +public class HomePage extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 主页面Id + */ + private String id; + + /** + * 用户Id + */ + private String userId; + + /** + * 自定义页面名称 + */ + private String name; + + /** + * 布局魔板 + */ + private String layout; + + /** + * 路径 + */ + private String path; + + /** + * 排序 + */ + private Integer sort; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + + /** + * 图标 + */ + private String icon; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/RoleFunction.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/RoleFunction.java new file mode 100644 index 0000000..5acd5b3 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/RoleFunction.java @@ -0,0 +1,28 @@ +package com.njcn.product.system.theme.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@TableName("sys_role_function") +public class RoleFunction { + + private static final long serialVersionUID = 1L; + + /** + * 角色Id + */ + private String roleId; + + /** + * 资源Id + */ + private String functionId; + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Theme.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Theme.java new file mode 100644 index 0000000..2565937 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/po/Theme.java @@ -0,0 +1,119 @@ +package com.njcn.product.system.theme.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_theme") +public class Theme extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 主题Id + */ + private String id; + + /** + * 主题名称 + */ + private String name; + + /** + * logo名称 + */ + private String logoUrl; + + /** + * favicon名称 + */ + private String faviconUrl; + + /** + * 主题颜色 + */ + private String color; + + /** + * 0-未激活 1-激活,所有数据只有一条数据处于激活状态 + */ + private Integer active; + + /** + * 主题描述 + */ + private String remark; + + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + + //V3主题使用的字段 + /** + * 切换栏位置 + */ + private String mainAnimation; + /** + * 主键主题色 + */ + private String elementUiPrimary; + /** + * 表格标题背景颜色 + */ + private String tableHeaderBackground; + /** + * 表格标题文字颜色 + */ + private String tableHeaderColor; + /** + * 表格激活颜色 + */ + private String tableCurrent; + /** + * 侧边菜单背景色 + */ + private String menuBackground; + /** + * 侧边菜单文字颜色 + */ + private String menuColor; + /** + * 侧边菜单激活项背景色 + */ + private String menuActiveBackground; + /** + * 侧边菜单激活项文字色 + */ + private String menuActiveColor; + /** + * 侧边菜单顶栏背景色 + */ + private String menuTopBarBackground; + /** + * 顶栏文字色 + */ + private String headerBarTabColor; + /** + * 顶栏背景色 + */ + private String headerBarBackground; + + /** + * logo文件服务器路径 + */ + private String logoPath; + /** + * favicon文件服务器路径 + */ + private String faviconPath; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/vo/FunctionVO.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/vo/FunctionVO.java new file mode 100644 index 0000000..b9321f2 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/pojo/vo/FunctionVO.java @@ -0,0 +1,55 @@ +package com.njcn.product.system.theme.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2022/1/17 17:02 + */ +@Data +public class FunctionVO implements Serializable { + + @ApiModelProperty("资源Id") + private String id; + + @ApiModelProperty("节点") + private String pid; + + @ApiModelProperty("名称") + private String title; + + @ApiModelProperty("资源标识") + private String code; + + @ApiModelProperty("路由名称") + private String routeName; + + @ApiModelProperty("路径") + private String routePath; + + @ApiModelProperty("图标") + private String icon; + + @ApiModelProperty("排序") + private Integer sort; + + @ApiModelProperty("资源类型") + private Integer type; + + @ApiModelProperty("描述") + private String remark; + + @ApiModelProperty("子级") + List children; + + @ApiModelProperty("tab数据") + List userTab; + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IConfigService.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IConfigService.java new file mode 100644 index 0000000..ab52243 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IConfigService.java @@ -0,0 +1,32 @@ +package com.njcn.product.system.theme.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.theme.pojo.param.ConfigParam; +import com.njcn.product.system.theme.pojo.po.Config; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IConfigService extends IService { + + /** + * 新增系统配置 + * @param configParam 配置参数 + */ + boolean addSysConfig(ConfigParam configParam); + /** + * 修改系统配置 + * @param configUpdateParam 配置参数 + */ + boolean updateSysConfig(ConfigParam.ConfigUpdateParam configUpdateParam); + + List getList(); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IFunctionService.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IFunctionService.java new file mode 100644 index 0000000..92a4320 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IFunctionService.java @@ -0,0 +1,123 @@ +package com.njcn.product.system.theme.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.theme.pojo.param.FunctionParam; +import com.njcn.product.system.theme.pojo.param.RoleParam; +import com.njcn.product.system.theme.pojo.po.Function; +import com.njcn.product.system.theme.pojo.vo.FunctionVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IFunctionService extends IService { + + /** + * 刷新用户权限信息到缓存中 + */ + void refreshRolesFunctionsCache(); + + /** + * 功能描述:新增资源 + * + * @param functionParam 资源参数 + * @return boolean + * @author xy + * @date 2022/1/17 11:19 + */ + boolean addFunction(FunctionParam functionParam); + + /** + * 功能描述: 修改菜单 + * + * @param functionParam + * @return boolean + * @author xy + * @date 2022/1/17 14:23 + */ + boolean updateFunction(FunctionParam.FunctionUpdateParam functionParam); + + /** + * 功能描述:删除菜单 + * + * @param id + * @return boolean + * @author xy + * @date 2022/1/17 16:53 + */ + void deleteFunction(String id); + + /** + * 功能描述: 获取菜单树 + * + * @param + * @return java.util.List + * @author xy + * @date 2022/1/17 17:04 + */ + List getFunctionTree(); + + /** + * 功能描述: 根据id获取菜单详情 + * + * @param id + * @return com.njcn.user.pojo.po.Function + * @author xy + * @date 2022/1/17 17:39 + */ + Function getFunctionById(String id); + + /** + * 功能描述: 根据菜单id获取按钮 + * + * @param id + * @return java.util.List + * @author xy + * @date 2022/1/17 17:40 + */ + List getButtonsById(String id); + + /** + * 功能描述: 获取路由菜单 + * + * @param + * @return java.util.List + * @author xy + * @date 2022/1/18 13:47 + */ + List getRouteMenu(); + + /** + * 功能描述: 角色分配菜单 + * + * @param roleFunctionComponent + * @return java.util.List + * @author xy + * @date 2022/2/17 17:00 + */ + Boolean updateRoleComponent(RoleParam.RoleFunctionComponent roleFunctionComponent); + + /** + * 功能描述: 获取用户菜单树 + * + * @param + * @return java.util.List + * @author xy + * @date 2022/2/21 11:29 + */ + List getUserFunctionTree(); + + /** + * 根据菜单集合获取数据 + * @author xy + */ + List getFunctionByList(List list); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IHomePageService.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IHomePageService.java new file mode 100644 index 0000000..a2a2b1b --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IHomePageService.java @@ -0,0 +1,81 @@ +package com.njcn.product.system.theme.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.theme.pojo.param.HomePageParam; +import com.njcn.product.system.theme.pojo.po.HomePage; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IHomePageService extends IService { + + /** + * 功能描述: 新增驾驶舱 + * + * @param homePageParam + * @return boolean + * @author xy + * @date 2022/1/18 16:54 + */ + boolean add(HomePageParam homePageParam); + + /** + * 功能描述: 删除驾驶舱 + * + * @param id + * @return boolean + * @author xy + * @date 2022/1/18 16:54 + */ + boolean delete(String id); + + /** + * 功能描述: 修改驾驶舱 + * + * @param homePageUpdate + * @return boolean + * @author xy + * @date 2022/1/18 16:54 + */ + boolean update(HomePageParam.HomePageUpdateParam homePageUpdate); + + + /** + * 功能描述: 获取用户的首页模式 + * + * @param id + * @return java.util.List + * @author xy + * @date 2022/1/18 15:33 + */ + List getHomePagesByUserId(String id); + + /** + * 功能描述:根据驾驶舱id获取详情 + * + * @param id + * @return com.njcn.user.pojo.po.HomePage + * @author xy + * @date 2022/1/18 17:29 + */ + HomePage getHomePageById(String id); + + /** + * 功能描述:查看已使用的驾驶舱路径 + * + * @param path + * @return java.util.List + * @author xy + * @date 2022/1/18 17:34 + */ + List getUsedHomePage(String path); + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IRoleFunctionService.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IRoleFunctionService.java new file mode 100644 index 0000000..48003b9 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IRoleFunctionService.java @@ -0,0 +1,30 @@ +package com.njcn.product.system.theme.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.theme.pojo.po.RoleFunction; +import com.njcn.product.system.theme.pojo.vo.FunctionVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IRoleFunctionService extends IService { + List getFunctionsByRoleIndex(String id); + + /** + * 功能描述: 根据角色集合获取菜单方法 + * + * @param roleList 角色集合 + * @return java.util.List + * @author xy + * @date 2022/1/18 14:22 + */ + List getFunctionsByList(List roleList); +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IThemeService.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IThemeService.java new file mode 100644 index 0000000..952a460 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/IThemeService.java @@ -0,0 +1,33 @@ +package com.njcn.product.system.theme.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.system.theme.pojo.po.Theme; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IThemeService extends IService { + + + + /** + * 功能描述: 获取当前主题 + * + * @return com.njcn.system.pojo.po.Theme + * @author xy + * @date 2022/1/12 15:39 + */ + Theme getTheme(); + + + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ConfigServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ConfigServiceImpl.java new file mode 100644 index 0000000..df15879 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ConfigServiceImpl.java @@ -0,0 +1,86 @@ +package com.njcn.product.system.theme.service.impl; + +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.product.system.dict.enums.SystemResponseEnum; +import com.njcn.product.system.theme.mapper.ConfigMapper; +import com.njcn.product.system.theme.pojo.param.ConfigParam; +import com.njcn.product.system.theme.pojo.po.Config; +import com.njcn.product.system.theme.service.IConfigService; +import com.njcn.web.utils.RequestUtil; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +public class ConfigServiceImpl extends ServiceImpl implements IConfigService { + + + @Override + public boolean addSysConfig(ConfigParam configParam) { + Config config = new Config(); + BeanUtils.copyProperties(configParam, config); + config.setCreateBy(RequestUtil.getUserIndex()); + config.setCreateTime(LocalDateTime.now()); + config.setUpdateBy(RequestUtil.getUserIndex()); + config.setUpdateTime(LocalDateTime.now()); + config.setState(DataStateEnum.ENABLE.getCode()); + this.baseMapper.insert(config); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateSysConfig(ConfigParam.ConfigUpdateParam configUpdateParam) { + Config config = this.baseMapper.selectById(configUpdateParam.getId()); + if (!Objects.isNull(config)) { + if (config.getState().equals(DataStateEnum.ENABLE.getCode())) { + if (Objects.equals(configUpdateParam.getState(), config.getState())) { + BeanUtils.copyProperties(configUpdateParam, config); + config.setUpdateBy(RequestUtil.getUserIndex()); + config.setUpdateTime(LocalDateTime.now()); + this.baseMapper.updateById(config); + return true; + } else { + // 不可更改当前激活状态,必须保留一个激活系统 + throw new BusinessException(SystemResponseEnum.ACTIVATED_STATE); + } + } else { + if (configUpdateParam.getState().equals(DataStateEnum.ENABLE.getCode())) { + // 先将所有的都置为非激活状态 + LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); + updateWrapper.set(Config::getState, DataStateEnum.DELETED.getCode()); + this.baseMapper.update(null, updateWrapper); + } + BeanUtils.copyProperties(configUpdateParam, config); + config.setUpdateBy(RequestUtil.getUserIndex()); + config.setUpdateTime(LocalDateTime.now()); + this.baseMapper.updateById(config); + return true; + } + } + return false; + } + + @Override + public List getList() { + return this.baseMapper.getList(); + } + + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/FunctionServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/FunctionServiceImpl.java new file mode 100644 index 0000000..952e033 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/FunctionServiceImpl.java @@ -0,0 +1,354 @@ +package com.njcn.product.system.theme.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.constant.SecurityConstants; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.auth.pojo.constant.FunctionState; +import com.njcn.product.auth.pojo.constant.UserType; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.auth.pojo.po.Role; +import com.njcn.product.auth.service.IRoleService; +import com.njcn.product.auth.service.IUserRoleService; +import com.njcn.product.system.theme.mapper.FunctionMapper; +import com.njcn.product.system.theme.mapper.RoleFunctionMapper; +import com.njcn.product.system.theme.pojo.param.FunctionParam; +import com.njcn.product.system.theme.pojo.param.RoleParam; +import com.njcn.product.system.theme.pojo.po.Function; +import com.njcn.product.system.theme.pojo.po.HomePage; +import com.njcn.product.system.theme.pojo.po.RoleFunction; +import com.njcn.product.system.theme.pojo.vo.FunctionVO; +import com.njcn.product.system.theme.service.IFunctionService; +import com.njcn.product.system.theme.service.IHomePageService; +import com.njcn.product.system.theme.service.IRoleFunctionService; +import com.njcn.redis.pojo.enums.RedisKeyEnum; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.product.auth.pojo.po.UserRole; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class FunctionServiceImpl extends ServiceImpl implements IFunctionService { + + private final RedisUtil redisUtil; + + private final IRoleService roleService; + + private final IRoleFunctionService roleFunctionService; + + private final FunctionMapper functionMapper; + + private final IUserRoleService userRoleService; + + private final IHomePageService homePageService; + + private final RoleFunctionMapper roleFunctionMapper; + + /** + * 将系统中角色--资源对应数据缓存到redis + * 先清除,再缓存 + */ + @Override + public void refreshRolesFunctionsCache() { + redisUtil.delete(RedisKeyEnum.ROLE_FUNCTION_KEY.getKey()); + redisUtil.delete(RedisKeyEnum.PUBLIC_FUNCTIONS_KEY.getKey()); + //缓存公共资源 + List publicFunctions = lambdaQuery() + .eq(Function::getType, 2) + .eq(Function::getState, DataStateEnum.ENABLE.getCode()) + .list(); + redisUtil.saveByKey( + RedisKeyEnum.PUBLIC_FUNCTIONS_KEY.getKey() + , publicFunctions.stream().map(Function::getPath).collect(Collectors.toList()) + ); + + //缓存每个角色对应的资源 + Map> roleFunctionInfo = new HashMap<>(8); + List roles = roleService.lambdaQuery() + .eq(Role::getState, DataStateEnum.ENABLE.getCode()) + .list(); + + roles.forEach(role -> { + //根据当前角色列表获取其所对应的所有资源 + List roleFunctions = roleFunctionService.lambdaQuery() + .eq(RoleFunction::getRoleId, role.getId()) + .list(); + //根据角色权限关系表获取权限的uri + if (CollectionUtil.isEmpty(roleFunctions)) { + roleFunctionInfo.put(SecurityConstants.AUTHORITY_PREFIX + role.getCode(), null); + } else { + List functions = lambdaQuery() + .in(Function::getId, roleFunctions.stream().map(RoleFunction::getFunctionId).collect(Collectors.toList())) + .eq(Function::getState, DataStateEnum.ENABLE.getCode()) + .list(); + roleFunctionInfo.put(SecurityConstants.AUTHORITY_PREFIX + role.getCode(), functions.stream().map(Function::getPath).collect(Collectors.toList())); + } + }); + redisUtil.saveByKey(RedisKeyEnum.ROLE_FUNCTION_KEY.getKey(), roleFunctionInfo); + } + + @Override + public boolean addFunction(FunctionParam functionParam) { + checkFunctionParam(functionParam, false); + Function function = new Function(); + BeanUtil.copyProperties(functionParam, function); + function.setState(FunctionState.ENABLE); + if (Objects.equals(functionParam.getPid(), FunctionState.FATHER_PID)) { + function.setPids(FunctionState.FATHER_PID); + } else { + Function fatherFaction = this.lambdaQuery().eq(Function::getId, functionParam.getPid()).one(); + if (Objects.equals(fatherFaction.getPid(), FunctionState.FATHER_PID)) { + function.setPids(functionParam.getPid()); + } else { + String pidS = fatherFaction.getPids(); + function.setPids(pidS + "," + functionParam.getPid()); + } + } + boolean result = this.save(function); + if (result) { + //刷新redis里面的资源权限 + refreshRolesFunctionsCache(); + } + return result; + } + + @Override + public boolean updateFunction(FunctionParam.FunctionUpdateParam functionParam) { + checkFunctionParam(functionParam, true); + Function function = new Function(); + BeanUtil.copyProperties(functionParam, function); + boolean result = this.updateById(function); + if (result) { + refreshRolesFunctionsCache(); + } + return result; + } + + @Override + public void deleteFunction(String id) { + boolean result; + List list = this.lambdaQuery().eq(Function::getState, FunctionState.ENABLE).eq(Function::getPid, id).list(); + if (CollectionUtils.isEmpty(list)) { + result = this.lambdaUpdate() + .set(Function::getState, FunctionState.DELETE) + .in(Function::getId, id) + .update(); + if (result) { + refreshRolesFunctionsCache(); + } + } else { + throw new BusinessException(UserResponseEnum.BINDING_BUTTON); + } + } + + @Override + public List getFunctionTree() { + List list = functionMapper.getAllFunctions(); + return list.stream() + .filter(fun -> Objects.equals(FunctionState.FATHER_PID, fun.getPid())) + .peek(funS -> funS.setChildren(getChildCategoryList(funS, list))) + .sorted(Comparator.comparingInt(FunctionVO::getSort)) + .collect(Collectors.toList()); + } + + @Override + public Function getFunctionById(String id) { + return this.lambdaQuery().eq(Function::getId, id).one(); + } + + @Override + public List getButtonsById(String id) { + List typeList = Arrays.asList(FunctionState.BUTTON, FunctionState.PUBLIC, FunctionState.TAB); + return this.lambdaQuery().eq(Function::getPid, id).in(Function::getType, typeList).eq(Function::getState, FunctionState.ENABLE).orderByAsc(Function::getSort).list(); + } + + @Override + public List getRouteMenu() { + List result = new ArrayList<>(); + List functionList; + if (Objects.equals(RequestUtil.getUsername(), UserType.SUPER_ADMIN)) { + //查询所有菜单 + functionList = this.lambdaQuery().eq(Function::getState, FunctionState.ENABLE).list().stream().map(Function::getId).distinct().collect(Collectors.toList()); + } else { + List roleList = userRoleService.getUserRoleByUserId(RequestUtil.getUserIndex()).stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList()); + functionList = roleFunctionService.getFunctionsByList(roleList); + } + if (CollectionUtils.isEmpty(functionList)) { + return result; + } + List functionVOList = functionMapper.getFunctionsByList(functionList); + result = functionVOList.stream() + .filter(fun -> Objects.equals(FunctionState.FATHER_PID, fun.getPid().trim())) + .peek(funS -> funS.setChildren(getChildCategoryList(funS, functionVOList))) + .sorted(Comparator.comparingInt(FunctionVO::getSort)) + .collect(Collectors.toList()); + //组装驾驶舱 + setDriverChildren(result); + //处理tab页 + setTab(result); + return result; + } + + @Override + public Boolean updateRoleComponent(RoleParam.RoleFunctionComponent roleFunctionComponent) { + deleteComponentsByRoleIndex(roleFunctionComponent.getId()); + if (!roleFunctionComponent.getIdList().isEmpty()) { + List list = new ArrayList<>(); + RoleFunction roleFunction; + for (String pojo : roleFunctionComponent.getIdList()) { + roleFunction = new RoleFunction(); + roleFunction.setRoleId(roleFunctionComponent.getId()); + roleFunction.setFunctionId(pojo); + list.add(roleFunction); + } + roleFunctionService.saveBatch(list); + } + refreshRolesFunctionsCache(); + return true; + } + + @Override + public List getUserFunctionTree() { + List result; + List functionList; + if (Objects.equals(RequestUtil.getUsername(), UserType.SUPER_ADMIN)) { + //查询所有菜单 + functionList = this.lambdaQuery().eq(Function::getState, FunctionState.ENABLE).list().stream().map(Function::getId).distinct().collect(Collectors.toList()); + } else { + List roleList = userRoleService.getUserRoleByUserId(RequestUtil.getUserIndex()).stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList()); + functionList = roleFunctionService.getFunctionsByList(roleList); + } + List functionVOList = functionMapper.getUserFunctionsByList(functionList); + result = functionVOList.stream() + .filter(fun -> Objects.equals(FunctionState.FATHER_PID, fun.getPid())) + .peek(funS -> funS.setChildren(getChildCategoryList(funS, functionVOList))) + .sorted(Comparator.comparingInt(FunctionVO::getSort)) + .collect(Collectors.toList()); + //组装驾驶舱 + setDriverChildren(result); + return result; + } + + @Override + public List getFunctionByList(List list) { + return this.lambdaQuery().in(Function::getId, list).list(); + } + + /** + * 根据角色删除资源 + * + * @param roleIndex 角色索引 + */ + public void deleteComponentsByRoleIndex(String roleIndex) { + QueryWrapper roleFunctionQueryWrapper = new QueryWrapper<>(); + roleFunctionQueryWrapper.eq("sys_role_function.role_id", roleIndex); + roleFunctionMapper.delete(roleFunctionQueryWrapper); + } + + /** + * 根据当前分类找出子类,递归找出子类的子类 + */ + private List getChildCategoryList(FunctionVO currMenu, List categories) { + return categories.stream().filter(o -> Objects.equals(o.getPid(), currMenu.getId())) + .peek(o -> o.setChildren(getChildCategoryList(o, categories))) + .sorted(Comparator.comparingInt(FunctionVO::getSort)) + .collect(Collectors.toList()); + } + + /** + * 组装驾驶舱子级 + * + * @param list 菜单集合 + */ + private void setDriverChildren(List list) { + List homePages = homePageService.getHomePagesByUserId(RequestUtil.getUserIndex()); + list.forEach(item -> { + if (Objects.equals(item.getRoutePath(), FunctionState.DRIVER_NAME)) { + homePages.forEach(po -> { + FunctionVO functionVO = new FunctionVO(); + functionVO.setId(po.getId()); + functionVO.setPid(item.getId()); + functionVO.setTitle(po.getName()); + functionVO.setCode(item.getCode()); + functionVO.setRouteName(po.getPath().substring(po.getPath().lastIndexOf("/") + 1)); + functionVO.setRoutePath(po.getPath()); + functionVO.setIcon(po.getIcon()); + functionVO.setSort(po.getSort()); + functionVO.setType(item.getType()); + functionVO.setRemark(po.getName()); + functionVO.setChildren(new ArrayList<>()); + item.getChildren().add(functionVO); + }); + } + }); + } + + /** + * 处理tab页 + */ + private void setTab(List list) { + if (!CollectionUtils.isEmpty(list)) { + list.forEach(item -> { + List children = item.getChildren(); + if (!CollectionUtils.isEmpty(children)) { + for (FunctionVO child : children) { + List children2 = child.getChildren(); + if (!CollectionUtils.isEmpty(children2)) { + setTab(children2); + } else if (Objects.equals(child.getType(), 4)) { + item.setUserTab(item.getChildren()); + item.setChildren(new ArrayList<>()); + break; + } + } + } + }); + } + } + + /** + * 校验参数, + * 1.检查是否存在相同名称的菜单 + * 名称 && 路径做唯一判断 + */ + private void checkFunctionParam(FunctionParam functionParam, boolean isExcludeSelf) { + LambdaQueryWrapper functionLambdaQueryWrapper = new LambdaQueryWrapper<>(); + functionLambdaQueryWrapper + .eq(Function::getName, functionParam.getName()) + .eq(Function::getPath, functionParam.getPath()) + .eq(Function::getPid, functionParam.getPid()) + .eq(Function::getState, FunctionState.ENABLE); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (functionParam instanceof FunctionParam.FunctionUpdateParam) { + functionLambdaQueryWrapper.ne(Function::getId, ((FunctionParam.FunctionUpdateParam) functionParam).getId()); + } + } + int countByAccount = this.count(functionLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(UserResponseEnum.FUNCTION_PATH_EXIST); + } + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/HomePageServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/HomePageServiceImpl.java new file mode 100644 index 0000000..1851376 --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/HomePageServiceImpl.java @@ -0,0 +1,99 @@ +package com.njcn.product.system.theme.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.product.auth.pojo.constant.HomePageState; +import com.njcn.product.auth.pojo.enums.UserResponseEnum; +import com.njcn.product.system.theme.mapper.HomePageMapper; +import com.njcn.product.system.theme.pojo.param.HomePageParam; +import com.njcn.product.system.theme.pojo.po.HomePage; +import com.njcn.product.system.theme.service.IHomePageService; +import com.njcn.web.utils.RequestUtil; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +public class HomePageServiceImpl extends ServiceImpl implements IHomePageService { + + @Override + public boolean add(HomePageParam homePageParam) { + checkHomePageName(homePageParam,false); + String component = homePageParam.getLayout().replace(""","\""); + HomePage homePage = new HomePage(); + BeanUtil.copyProperties(homePageParam, homePage); + homePage.setUserId(RequestUtil.getUserIndex()); + homePage.setState(HomePageState.ENABLE); + homePage.setLayout(component); + return this.save(homePage); + } + + @Override + public boolean delete(String id) { + return this.lambdaUpdate() + .set(HomePage::getState, HomePageState.DELETE) + .in(HomePage::getId, id) + .update(); + } + + @Override + public boolean update(HomePageParam.HomePageUpdateParam homePageUpdate) { + checkHomePageName(homePageUpdate,true); + HomePage homePage = new HomePage(); + BeanUtil.copyProperties(homePageUpdate, homePage); + return this.updateById(homePage); + } + + @Override + public List getHomePagesByUserId(String id) { + List userList = new ArrayList<>(); + userList.add(id); + userList.add(HomePageState.DEFAULT_USER_ID); + return this.lambdaQuery().in(HomePage::getUserId,userList).eq(HomePage::getState, HomePageState.ENABLE).orderByAsc(HomePage::getSort).list(); + } + + @Override + public HomePage getHomePageById(String id) { + return this.lambdaQuery().in(HomePage::getId,id).one(); + } + + @Override + public List getUsedHomePage(String path) { + return this.lambdaQuery().in(HomePage::getUserId,RequestUtil.getUserIndex()).eq(HomePage::getState,HomePageState.ENABLE).likeRight(HomePage::getPath,path).list().stream().map(HomePage::getPath).distinct().collect(Collectors.toList()); + } + + /** + * 校验参数,检查是否存在相同名称的首页 + */ + private void checkHomePageName(HomePageParam homePageParam, boolean isExcludeSelf) { + LambdaQueryWrapper homePageLambdaQueryWrapper = new LambdaQueryWrapper<>(); + homePageLambdaQueryWrapper + .eq(HomePage::getName,homePageParam.getName()) + .eq(HomePage::getState, HomePageState.ENABLE); + //更新的时候,需排除当前记录 + if(isExcludeSelf){ + if(homePageParam instanceof HomePageParam.HomePageUpdateParam){ + homePageLambdaQueryWrapper.ne(HomePage::getId,((HomePageParam.HomePageUpdateParam) homePageParam).getId()); + } + } + int countByAccount = this.count(homePageLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(UserResponseEnum.REGISTER_HOMEPAGE_NAME_EXIST); + } + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/RoleFunctionServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/RoleFunctionServiceImpl.java new file mode 100644 index 0000000..92cc47c --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/RoleFunctionServiceImpl.java @@ -0,0 +1,51 @@ +package com.njcn.product.system.theme.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.system.theme.mapper.FunctionMapper; +import com.njcn.product.system.theme.mapper.RoleFunctionMapper; +import com.njcn.product.system.theme.pojo.po.RoleFunction; +import com.njcn.product.system.theme.pojo.vo.FunctionVO; +import com.njcn.product.system.theme.service.IRoleFunctionService; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@AllArgsConstructor +public class RoleFunctionServiceImpl extends ServiceImpl implements IRoleFunctionService { + + private final FunctionMapper functionMapper; + + @Override + public List getFunctionsByRoleIndex(String id) { + List result = new ArrayList<>(); + List functionList = new ArrayList<>(); + QueryWrapper componentQueryWrapper = new QueryWrapper<>(); + componentQueryWrapper.eq("sys_role_function.role_id",id); + functionList = this.baseMapper.selectList(componentQueryWrapper).stream().map(RoleFunction::getFunctionId).collect(Collectors.toList()); + if (CollectionUtil.isNotEmpty(functionList)){ + result = functionMapper.getByList(functionList); + } + return result; + } + + @Override + public List getFunctionsByList(List roleList) { + return this.lambdaQuery().in(RoleFunction::getRoleId,roleList).list().stream().map(RoleFunction::getFunctionId).distinct().collect(Collectors.toList()); + } + +} diff --git a/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ThemeServiceImpl.java b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ThemeServiceImpl.java new file mode 100644 index 0000000..0d342da --- /dev/null +++ b/carry_capacity/src/main/java/com/njcn/product/system/theme/service/impl/ThemeServiceImpl.java @@ -0,0 +1,39 @@ +package com.njcn.product.system.theme.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.system.theme.mapper.ThemeMapper; +import com.njcn.product.system.theme.pojo.po.Theme; +import com.njcn.product.system.theme.service.IThemeService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; +import sun.misc.BASE64Encoder; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Service +@RequiredArgsConstructor +public class ThemeServiceImpl extends ServiceImpl implements IThemeService { + + + @Override + public Theme getTheme() { + return this.lambdaQuery() + .eq(Theme::getActive,1).one(); + } + + + +} diff --git a/carry_capacity/src/main/resources/application.yml b/carry_capacity/src/main/resources/application.yml new file mode 100644 index 0000000..a3f3485 --- /dev/null +++ b/carry_capacity/src/main/resources/application.yml @@ -0,0 +1,96 @@ +#当前服务的基本信息 +microservice: + ename: carryCapacity + name: carryCapacity +#当前服务的基本信息 +server: + port: 9001 +spring: + application: + name: carry_capacity + datasource: + druid: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://192.168.1.24:13306/pqsinfo_cznlpg?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai + username: root + password: njcnpqs + # url: jdbc:mysql://localhost:3306/pqs91001?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=CTT + # username: root + # password: root + #初始化建立物理连接的个数、最小、最大连接数 + initial-size: 5 + min-idle: 5 + max-active: 50 + #获取连接最大等待时间,单位毫秒 + max-wait: 60000 + #链接保持空间而不被驱逐的最长时间,单位毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: select 1 + test-while-idle: true + test-on-borrow: false + test-on-return: false + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + #influxDB内容配置 + influx: + url: http://192.168.1.24:8086 + user: admin + password: 123456 + database: pqbase_pg + mapper-location: com.njcn.**.imapper +#mybatis配置信息 +mybatis-plus: + mapper-locations: classpath*:com/njcn/**/mapping/*.xml + #别名扫描 + type-aliases-package: com.njcn.product.**.pojo + configuration: + #驼峰命名 + map-underscore-to-camel-case: true + #配置sql日志输出 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl +# #关闭日志输出 +# log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl + global-config: + db-config: + #指定主键生成策略 + id-type: assign_uuid +db: + type: mysql +#文件位置配置 +business: + #处理波形数据位置 + # wavePath: D://comtrade + wavePath: /usr/local/comtrade + #处理临时数据 + #tempPath: D://file + tempPath: /usr/local/file + #文件存储的方式 + file: + storage: 3 +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.13:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 + +#线程池配置信息 +threadPool: + corePoolSize: 10 + maxPoolSize: 20 + queueCapacity: 500 + keepAliveSeconds: 60 +file: + upload-dir: D:/carry + + diff --git a/carry_capacity/src/main/resources/njcn.jks b/carry_capacity/src/main/resources/njcn.jks new file mode 100644 index 0000000..0b25e1d Binary files /dev/null and b/carry_capacity/src/main/resources/njcn.jks differ diff --git a/carry_capacity/target/carry_capacity-1.0.0.jar b/carry_capacity/target/carry_capacity-1.0.0.jar new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/carry_capacity-1.0.0.jar.original b/carry_capacity/target/carry_capacity-1.0.0.jar.original new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/application.yml b/carry_capacity/target/classes/application.yml new file mode 100644 index 0000000..a3f3485 --- /dev/null +++ b/carry_capacity/target/classes/application.yml @@ -0,0 +1,96 @@ +#当前服务的基本信息 +microservice: + ename: carryCapacity + name: carryCapacity +#当前服务的基本信息 +server: + port: 9001 +spring: + application: + name: carry_capacity + datasource: + druid: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://192.168.1.24:13306/pqsinfo_cznlpg?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai + username: root + password: njcnpqs + # url: jdbc:mysql://localhost:3306/pqs91001?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=CTT + # username: root + # password: root + #初始化建立物理连接的个数、最小、最大连接数 + initial-size: 5 + min-idle: 5 + max-active: 50 + #获取连接最大等待时间,单位毫秒 + max-wait: 60000 + #链接保持空间而不被驱逐的最长时间,单位毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: select 1 + test-while-idle: true + test-on-borrow: false + test-on-return: false + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + #influxDB内容配置 + influx: + url: http://192.168.1.24:8086 + user: admin + password: 123456 + database: pqbase_pg + mapper-location: com.njcn.**.imapper +#mybatis配置信息 +mybatis-plus: + mapper-locations: classpath*:com/njcn/**/mapping/*.xml + #别名扫描 + type-aliases-package: com.njcn.product.**.pojo + configuration: + #驼峰命名 + map-underscore-to-camel-case: true + #配置sql日志输出 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl +# #关闭日志输出 +# log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl + global-config: + db-config: + #指定主键生成策略 + id-type: assign_uuid +db: + type: mysql +#文件位置配置 +business: + #处理波形数据位置 + # wavePath: D://comtrade + wavePath: /usr/local/comtrade + #处理临时数据 + #tempPath: D://file + tempPath: /usr/local/file + #文件存储的方式 + file: + storage: 3 +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.13:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 + +#线程池配置信息 +threadPool: + corePoolSize: 10 + maxPoolSize: 20 + queueCapacity: 500 + keepAliveSeconds: 60 +file: + upload-dir: D:/carry + + diff --git a/carry_capacity/target/classes/com/njcn/product/auth/mapper/mapping/UserRoleMapper.xml b/carry_capacity/target/classes/com/njcn/product/auth/mapper/mapping/UserRoleMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDataPOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDataPOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDevicePOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityDevicePOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityResultPOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityResultPOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyDhlPOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyDhlPOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyPOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityStrategyPOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityUserPOMapper.xml b/carry_capacity/target/classes/com/njcn/product/carrycapacity/mapper/mapping/CarryCapacityUserPOMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/DeptLineMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/DeptLineMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/DeviceMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/DeviceMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/LineDetailMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/LineDetailMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/LineMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/LineMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/OverlimitMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/OverlimitMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/TreeMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/TreeMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/VoltageMapper.xml b/carry_capacity/target/classes/com/njcn/product/device/ledger/mapper/mapping/VoltageMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/dept/mapper/mapping/AreaMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/dept/mapper/mapping/AreaMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/dept/mapper/mapping/DeptMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/dept/mapper/mapping/DeptMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/dict/mapper/mapping/DictDataMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/dict/mapper/mapping/DictDataMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/dict/mapper/mapping/DictTypeMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/dict/mapper/mapping/DictTypeMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/ConfigMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/ConfigMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/FunctionMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/FunctionMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/RoleFunctionMapper.xml b/carry_capacity/target/classes/com/njcn/product/system/theme/mapper/mapping/RoleFunctionMapper.xml new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/classes/njcn.jks b/carry_capacity/target/classes/njcn.jks new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/maven-archiver/pom.properties b/carry_capacity/target/maven-archiver/pom.properties new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/carry_capacity/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..e69de29 diff --git a/carry_capacity/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/carry_capacity/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..e69de29 diff --git a/cn-advance/.gitignore b/cn-advance/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-advance/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-advance/pom.xml b/cn-advance/pom.xml new file mode 100644 index 0000000..3e9295c --- /dev/null +++ b/cn-advance/pom.xml @@ -0,0 +1,148 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + + cn-advance + 1.0.0 + cn-advance + cn-advance + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + com.njcn.product + cn-terminal + 1.0.0 + + + + com.njcn.product + cn-system + 1.0.0 + + + + com.njcn + pqs-influx + ${project.version} + + + + com.alibaba + fastjson + 2.0.22 + + + + net.java.dev.jna + jna + 5.5.0 + + + + + + org.apache.commons + commons-math3 + 3.6.1 + + + + + org.ejml + ejml-simple + 0.41 + + + + cglib + cglib + 3.3.0 + + + + + cn.afterturn + easypoi-spring-boot-starter + 4.4.0 + + + + cn.afterturn + easypoi-base + 4.4.0 + + + cn.afterturn + easypoi-web + 4.4.0 + + + + xerces + xercesImpl + 2.12.2 + + + + + + + + src/main/resources + true + + *.yml + + + + src/main/resources + false + + *.dll + *.xlsx + + + + src/main/resources + false + + *.so + + + + src/main/java + false + + **/*.xml + + + + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/controller/EventRelevantAnalysisController.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/controller/EventRelevantAnalysisController.java new file mode 100644 index 0000000..025015a --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/controller/EventRelevantAnalysisController.java @@ -0,0 +1,80 @@ +package com.njcn.product.advance.eventSource.controller; + +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.util.StrUtil; +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.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.advance.eventSource.service.EventRelevantAnalysisService; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * pqs + * 事件关联分析 + * + * @author cdf + * @date 2023/6/30 + */ +@Slf4j +@RestController +@RequestMapping("process") +@Api(tags = "暂降事件关联分析") +@RequiredArgsConstructor +public class EventRelevantAnalysisController extends BaseController { + + private final EventRelevantAnalysisService eventRelevantAnalysisService; + + @PostMapping("processEvents") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("启动关联分析") + public HttpResult processEvents(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("processEvents"); + List timeVal = checkLocalDate(param.getSearchBeginTime(),param.getSearchEndTime()); + eventRelevantAnalysisService.processEvents(timeVal.get(0),timeVal.get(1),param.getDeptId()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + /** + * 校验字符串起始时间和结束时间并返回时间格式时间 + * @author cdf + * @date 2023/8/10 + */ + public List checkLocalDate(String startTime,String endTime) { + List resultList = new ArrayList<>(); + if(StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)){ + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + try { + startTime = startTime+StrUtil.SPACE+"00:00:00"; + endTime = endTime+StrUtil.SPACE+"23:59:59"; + LocalDateTime start = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)); + LocalDateTime end = LocalDateTime.parse(endTime,DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)); + resultList.add(start); + resultList.add(end); + } catch (Exception e) { + throw new BusinessException(CommonResponseEnum.TIME_ERROR); + } + return resultList; + } + + + + + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RelevantLogMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RelevantLogMapper.java new file mode 100644 index 0000000..ea97e37 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RelevantLogMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.advance.eventSource.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.advance.eventSource.pojo.po.PqsRelevanceLog; + + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/6/19 + */ +public interface RelevantLogMapper extends BaseMapper { + + + + + + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventAdvanceMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventAdvanceMapper.java new file mode 100644 index 0000000..57da042 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventAdvanceMapper.java @@ -0,0 +1,26 @@ +package com.njcn.product.advance.eventSource.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.advance.eventSource.pojo.dto.eventAggregate.EntityLogic; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/6/19 + */ +public interface RmpEventAdvanceMapper extends BaseMapper { + + + /** + * 获取母线物理隔绝信息 + * @author cdf + * @date 2023/7/21 + */ + List getLogic(); + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventDetailAssMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventDetailAssMapper.java new file mode 100644 index 0000000..a99b88f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/RmpEventDetailAssMapper.java @@ -0,0 +1,21 @@ +package com.njcn.product.advance.eventSource.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.advance.eventSource.pojo.dto.eventAggregate.EventAssObj; +import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/8/9 + */ +public interface RmpEventDetailAssMapper extends BaseMapper { + + + int insertEventAssData(@Param("list") List list); + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RelevanceMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RelevanceMapper.xml new file mode 100644 index 0000000..d9b8bab --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RelevanceMapper.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RmpEventDetailAssMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RmpEventDetailAssMapper.xml new file mode 100644 index 0000000..c03ce45 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/mapper/mapping/RmpEventDetailAssMapper.xml @@ -0,0 +1,24 @@ + + + + + + + insert into r_mp_event_detail_ass values + + ( + #{eventAssData.indexEventAss},#{eventAssData.time},#{eventAssData.describe}, + #{eventAssData.bRange},#{eventAssData.indexUser},#{eventAssData.indexUser},#{eventAssData.updateTime},#{eventAssData.updateTime} + ) + + + + + + + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/constant/HarmonicValidMessage.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/constant/HarmonicValidMessage.java new file mode 100644 index 0000000..42864f5 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/constant/HarmonicValidMessage.java @@ -0,0 +1,10 @@ +package com.njcn.product.advance.eventSource.pojo.constant; + +/** + * @author xy + * @date 2021/12/29 15:10 + */ +public interface HarmonicValidMessage { + + String DATA_NOT_BLANK = "参数不能为空"; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupData.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupData.java new file mode 100644 index 0000000..44c23a4 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupData.java @@ -0,0 +1,43 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + +import lombok.Data; + +/** + * pqs + * + * @author cdf + * @date 2023/7/20 + */ +@Data +public class EntityGroupData { + private int idx[]; + private int all_evt_num; + private int evt_in_num; + private int evt_out_num; + private int evt_res_num; + + private int Matrixcata[][]; + + private EntityGroupEvtData in_buf[]; + private EntityGroupEvtData out_buf[]; + private EntityGroupEvtData res_buf[]; + private EntityGroupEvtData grp_buf[][]; + + private int grp_num[]; + private int grp_all_num; + private EntityGroupEvtData grp_cata_buf[][][]; + private int grp_cata_num[][]; + + public EntityGroupData() { + idx = new int[FinalData.MAX_EVT_NUM]; + Matrixcata = new int[FinalData.MAX_CATA_NUM][FinalData.MAX_EVT_NUM]; + in_buf = new EntityGroupEvtData[FinalData.MAX_EVT_NUM]; + out_buf = new EntityGroupEvtData[FinalData.MAX_EVT_NUM]; + res_buf = new EntityGroupEvtData[FinalData.MAX_EVT_NUM]; + grp_buf = new EntityGroupEvtData[FinalData.MAX_GROUP_NUM][FinalData.MAX_EVT_NUM]; + grp_num = new int[FinalData.MAX_GROUP_NUM]; + grp_cata_buf = new EntityGroupEvtData[FinalData.MAX_GROUP_NUM][FinalData.MAX_CATA_NUM + + 2][FinalData.MAX_EVT_NUM]; + grp_cata_num = new int[FinalData.MAX_GROUP_NUM][FinalData.MAX_CATA_NUM + 2]; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupEvtData.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupEvtData.java new file mode 100644 index 0000000..ea0ca88 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityGroupEvtData.java @@ -0,0 +1,120 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + + + +public class EntityGroupEvtData implements Cloneable,Comparable { + //逻辑节点序号 + private int node; + //事件开始时间时标 + private int start_time; + //类别 + private int cata; + //标注类别 + private int cata2; + //物理节点 + private String nodePhysics; + + private SagEvent sagEvent; + + private String sagReason; + + public EntityGroupEvtData(String nodePhysics, int start_time, int cata, int cata2,SagEvent sagEvent,String sagReason) { + this.nodePhysics = nodePhysics; + this.start_time = start_time; + this.cata = cata; + this.cata2 = cata2; + this.sagEvent = sagEvent; + this.sagReason = sagReason; + } + + public SagEvent getSagEvent() { + return sagEvent; + } + + public void setSagEvent(SagEvent sagEvent) { + this.sagEvent = sagEvent; + } + + public String getNodePhysics() { + return nodePhysics; + } + + public void setNodePhysics(String nodePhysics) { + this.nodePhysics = nodePhysics; + } + + public int getNode() { + return node; + } + + public void setNode(int node) { + this.node = node; + } + + public int getStart_time() { + return start_time; + } + + public void setStart_time(int start_time) { + this.start_time = start_time; + } + + public int getCata() { + return cata; + } + + public void setCata(int cata) { + this.cata = cata; + } + + public int getCata2() { + return cata2; + } + + public void setCata2(int cata2) { + this.cata2 = cata2; + } + + public String getSagReason() { + return sagReason; + } + + public void setSagReason(String sagReason) { + this.sagReason = sagReason; + } + + + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public Object objClone() { + try { + return clone(); + } catch (CloneNotSupportedException e) { + return new EntityGroupEvtData("-1", -1, -1, -1,null,null); + } + } + + @Override + public String toString() { + return "EntityGroupEvtData{" + + "node=" + node + + ", start_time=" + start_time + + ", cata=" + cata + + ", cata2=" + cata2 + + '}'; + } + + @Override + public int compareTo(EntityGroupEvtData obj) { + if(this.getStart_time() < obj.getStart_time()){ + return -1; + }else if(this.getStart_time() > obj.getStart_time()){ + return 1; + } + + return 0; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityLogic.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityLogic.java new file mode 100644 index 0000000..802c181 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityLogic.java @@ -0,0 +1,21 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + + +import lombok.Data; + +@Data +public class EntityLogic { + //物理隔绝变压器策略GUID + private String tPIndex; + //变压器逻辑上节点 + private Integer node_h; + //变压器逻辑下节点 + private Integer node_l; + // 变压器连接方式 + private Integer type; + //变压器物理上节点 + private String nodeBefore; + //变压器物理下节点 + private String nodeNext; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityMtrans.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityMtrans.java new file mode 100644 index 0000000..0467fab --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EntityMtrans.java @@ -0,0 +1,70 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + +import java.io.Serializable; +import java.util.Arrays; + +public class EntityMtrans implements Serializable { + private static final long serialVersionUID = 1L; + private int Matrixcata0[][]; + private int Matrixcata1[][]; + private int Mtrans[][]; + private int possiable_path[][]; + private int path_num; + + public EntityMtrans() { + super(); + Mtrans = new int[FinalData.NODE_NUM][FinalData.NODE_NUM]; + Matrixcata0 = new int[FinalData.EVT_TYPE_NUM][FinalData.NODE_NUM]; + Matrixcata1 = new int[FinalData.EVT_TYPE_NUM][FinalData.NODE_NUM]; + possiable_path = new int[FinalData.MAX_PATH_NUM][FinalData.NODE_NUM + 1]; + path_num = 0; + } + + public int[][] getMatrixcata0() { + return Matrixcata0; + } + + public void setMatrixcata0(int[][] matrixcata0) { + Matrixcata0 = matrixcata0; + } + + public int[][] getMatrixcata1() { + return Matrixcata1; + } + + public void setMatrixcata1(int[][] matrixcata1) { + Matrixcata1 = matrixcata1; + } + + public int[][] getMtrans() { + return Mtrans; + } + + public void setMtrans(int[][] mtrans) { + Mtrans = mtrans; + } + + public int[][] getPossiable_path() { + return possiable_path; + } + + public void setPossiable_path(int[][] possiable_path) { + this.possiable_path = possiable_path; + } + + public int getPath_num() { + return path_num; + } + + public void setPath_num(int path_num) { + this.path_num = path_num; + } + + @Override + public String toString() { + return "EntityMtrans [Matrixcata0=" + Arrays.toString(Matrixcata0) + ", Matrixcata1=" + + Arrays.toString(Matrixcata1) + ", Mtrans=" + Arrays.toString(Mtrans) + ", possiable_path=" + + Arrays.toString(possiable_path) + ", path_num=" + path_num + "]"; + } +} + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EventAssObj.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EventAssObj.java new file mode 100644 index 0000000..e739a78 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/EventAssObj.java @@ -0,0 +1,122 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + + +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.List; + +/* + *一个归一化事件包含多个事件(一对多) + *indexEventAss:事件关联分析表Guid + *time:归一化中第一个时间 + *describe:关联事件描述 + *bRange:是否进行范围分析 + *indexUser:用户表Guid + *updateTime:更新时间 + *state:数据状态 + *name:关联事件名称 + *list:属于该归一化事件的暂降事件 + *strTime:字符串时间 +*/ +@Data +public class EventAssObj implements Serializable { + private String indexEventAss; + private LocalDateTime time; + private String describe; + private int bRange; + private String indexUser; + private LocalDateTime updateTime = LocalDateTime.now(); + private int state; + private String name; + private String strTime; + private List list; + + public String getStrTime() { + return strTime; + } + + public void setStrTime(String strTime) { + this.strTime = strTime; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIndexEventAss() { + return indexEventAss; + } + + public void setIndexEventAss(String indexEventAss) { + this.indexEventAss = indexEventAss; + } + + public LocalDateTime getTime() { + return time; + } + + public void setTime(LocalDateTime time) { + this.time = time; + } + + public String getDescribe() { + return describe; + } + + public void setDescribe(String describe) { + this.describe = describe; + } + + public int getbRange() { + return bRange; + } + + public void setbRange(int bRange) { + this.bRange = bRange; + } + + public String getIndexUser() { + return indexUser; + } + + public void setIndexUser(String indexUser) { + this.indexUser = indexUser; + } + + public LocalDateTime getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(LocalDateTime updateTime) { + this.updateTime = updateTime; + } + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + @Override + public String toString() { + return "EventAssObj [indexEventAss=" + indexEventAss + ", time=" + time + ", describe=" + describe + ", bRange=" + + bRange + ", indexUser=" + indexUser + ", updateTime=" + updateTime + ", state=" + state + ", name=" + + name + ", strTime=" + strTime + ", list=" + list + "]"; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/FinalData.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/FinalData.java new file mode 100644 index 0000000..317f9e2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/FinalData.java @@ -0,0 +1,25 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + +public class FinalData { + public static final int TIME_THRESHOLD = 10;//暂降事件按开始时间归集门槛10秒 + public static final int MAX_GROUP_NUM = 1000;//分组的最大组数 + public static final int MAX_CATA_NUM = 7;//类别数 + public static final int MAX_EVT_NUM = 1000;//最大事件个数 + + public static final int QVVR_TYPE_THREE = 9; //三相故障 + public static final int QVVR_TYPE_UNKNOWN = 10; //故障类型未知 + public static final int QVVR_TYPE_OUTOFRANGE = -1; //节点不在网络拓扑中 + public static final int DATA_INF = -1; + public static final int EVT_TYPE_NUM = 6;//故障类型数 + public static final int MAX_PATH_NUM = 50;//最大路径数 + public static int NODE_NUM;//输入节点数 + + // 暂降综合评估算法 + public static final int CLUSER_NUM = 4; // 系统中各监测点分类后的代表节点 + public static final int MAX_LINE_NUM = 1000; // 监测点最多个数 + public static final int MAX_STA_NUM = 120; // 支持的子系统个数 + + static { + NODE_NUM = -1; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/PlantInfo.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/PlantInfo.java new file mode 100644 index 0000000..ea24ed9 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/PlantInfo.java @@ -0,0 +1,32 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + +import lombok.Data; + +import java.io.Serializable; + +/** + * pqs + *终端监测点名称信息 + * nameGD:供电公司名称 + * nameBD:变电站名称 + * nameSubV:母线名称 + * namePoint:监测点名称 + * indexPoint:监测点的唯一标识 + * + * 新增add + * xuyang + * 2021.05.11 + * 监测点电压等级:monitorVoltageLevel + * 监测点干扰源类型终:monitorLoadType + */ +@Data +public class PlantInfo implements Serializable { + private String indexPoint; + private String nameGD; + private String nameBD; + private String nameSubV; + private String namePoint; + private String monitorVoltageLevel; + private String monitorLoadType; + private String objName; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/SagEvent.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/SagEvent.java new file mode 100644 index 0000000..f824407 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/dto/eventAggregate/SagEvent.java @@ -0,0 +1,420 @@ +package com.njcn.product.advance.eventSource.pojo.dto.eventAggregate; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * pqs + * + * @author cdf + * @date 2023/7/21 + */ +public class SagEvent implements Comparable, Serializable { + // 事件的唯一标识 + private String indexEventDetail; + + private Integer waveType; + // 暂降事件发生时间 + private LocalDateTime sagTime; + + // 暂降事件发生时间毫秒 + private Integer msec; + + // 事件描述 + private String events; + + // 持续时间 + private Float persistTime; + + // 发生暂降事件的监测点层级信息 + private PlantInfo plantInfo; + + // 拼接sagTime和msec + private String strTime; + + // 事件发生时刻的毫秒表示 + private Long time; + + // 监测点的唯一标识 + private String indexPoint; + + // 归一化事件的GUID + private String indexEventAss; + + // 特征幅值 + private Float eventValue; + + // 暂降原因 + private String sagReason; + + // 暂降类型 + private String sagType; + + // 暂降类型描述 + private String sagTypeDes; + + public String getSagTypeDes() { + return sagTypeDes; + } + + public void setSagTypeDes(String sagTypeDes) { + this.sagTypeDes = sagTypeDes; + } + + // 暂降深度 + private String strEventValue; + private String strPersist; + + // 事件是否经过高级算法处理(0-未处理,1-已处理,默认为0) + private Integer dealFlag; + + // 事件是否经过高级算法处理中文描述(已处理、未处理) + private String dealFlagDescription; + + // 录波文件是否存在(0-不存在,1-存在,默认为0) + private Integer fileFlag; + + // 录波文件是否存在中文描述(存在、不存在) + private String fileFlagDescription; + + // 高级算法返回dq持续时间 + private Float dqTime; + + // 高级算法处理事件个数记录 + private Integer number; + + // 归一化处理更新时间 + private LocalDateTime dealTime; + + // 高级算法的对应关系 + private int cata; + + // 第一次事件的触发时间 + private LocalDateTime firstTime; + + // 第一次事件的暂降类型 + private String firstType; + + // 第一次事件的触发时间毫秒 + private Integer firstMs; + + // 第一次事件触发时间date->毫秒 + private Long firstTimeMills; + + // 暂降严重度 + private Float severity; + + // 排序方式 + private int sortType = 0; // 初始化默认为0-按照时间排序 新增1-按暂降严重度排序 2-暂降发生时刻排序 3-先根据电压等级排序,如果相等再按照暂降幅值排序 + + //电压等级 + private Double voltage; + + //监测点对象名称 + private String objName; + + public String getObjName() { + return objName; + } + + public void setObjName(String objName) { + this.objName = objName; + } + + public Integer getWaveType() { + return waveType; + } + + public void setWaveType(Integer waveType) { + this.waveType = waveType; + } + + private String strVoltage; + + public Double getVoltage() { + return voltage; + } + + public void setVoltage(Double voltage) { + this.voltage = voltage; + } + + public String getStrVoltage() { + return strVoltage; + } + + public void setStrVoltage(String strVoltage) { + //转为double + strVoltage = strVoltage.toUpperCase(); + String str = strVoltage.substring(0, strVoltage.indexOf("KV")); + this.voltage = Double.parseDouble(str); + } + + public int getSortType() { + return sortType; + } + + public void setSortType(int sortType) { + this.sortType = sortType; + } + + public Float getSeverity() { + return severity; + } + + public void setSeverity(Float severity) { + this.severity = severity; + } + + public Long getFirstTimeMills() { + return firstTimeMills; + } + + public void setFirstTimeMills(Long firstTimeMills) { + this.firstTimeMills = firstTimeMills; + } + + public Integer getFirstMs() { + return firstMs; + } + + public void setFirstMs(Integer firstMs) { + this.firstMs = firstMs; + } + + public LocalDateTime getFirstTime() { + return firstTime; + } + + public void setFirstTime(LocalDateTime firstTime) { + this.firstTime = firstTime; + } + + public String getFirstType() { + return firstType; + } + + public void setFirstType(String firstType) { + this.firstType = firstType; + } + + public Integer getFileFlag() { + return fileFlag; + } + + public void setFileFlag(Integer fileFlag) { + this.fileFlag = fileFlag; + } + + public String getFileFlagDescription() { + return fileFlagDescription; + } + + public void setFileFlagDescription(String fileFlagDescription) { + this.fileFlagDescription = fileFlagDescription; + } + + public int getCata() { + return cata; + } + + public void setCata(int cata) { + this.cata = cata; + } + + public LocalDateTime getDealTime() { + return dealTime; + } + + public void setDealTime(LocalDateTime dealTime) { + this.dealTime = dealTime; + } + + public Float getDqTime() { + return dqTime; + } + + public void setDqTime(Float dqTime) { + this.dqTime = dqTime; + } + + public Integer getNumber() { + return number; + } + + public void setNumber(Integer number) { + this.number = number; + } + + public void setDealFlagDescription(String dealFlagDescription) { + this.dealFlagDescription = dealFlagDescription; + } + + public String getDealFlagDescription() { + return dealFlagDescription; + } + + public Integer getDealFlag() { + return dealFlag; + } + + public void setDealFlag(Integer dealFlag) { + this.dealFlag = dealFlag; + } + + public String getIndexEventDetail() { + return indexEventDetail; + } + + public void setIndexEventDetail(String indexEventDetail) { + this.indexEventDetail = indexEventDetail; + } + + public LocalDateTime getSagTime() { + return sagTime; + } + + public void setSagTime(LocalDateTime sagTime) { + this.sagTime = sagTime; + } + + public Integer getMsec() { + return msec; + } + + public void setMsec(Integer msec) { + this.msec = msec; + } + + public String getEvents() { + return events; + } + + public void setEvents(String events) { + this.events = events; + } + + public Float getPersistTime() { + return persistTime; + } + + public void setPersistTime(Float persistTime) { + if (persistTime == null) { + this.persistTime = 0f; + return; + } + + float f1 = (float) (Math.round(persistTime.floatValue() * 1000)) / 1000; + this.persistTime = new Float(f1); + } + + public PlantInfo getPlantInfo() { + return plantInfo; + } + + public void setPlantInfo(PlantInfo plantInfo) { + this.plantInfo = plantInfo; + } + + public String getStrTime() { + return strTime; + } + + public void setStrTime(String strTime) { + this.strTime = strTime; + } + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } + + public String getIndexPoint() { + return indexPoint; + } + + public void setIndexPoint(String indexPoint) { + this.indexPoint = indexPoint; + } + + public String getIndexEventAss() { + return indexEventAss; + } + + public void setIndexEventAss(String indexEventAss) { + this.indexEventAss = indexEventAss; + } + + public Float getEventValue() { + return eventValue; + } + + public void setEventValue(Float eventValue) { + if (eventValue == null) { + this.eventValue = 0f; + return; + } + + this.eventValue = eventValue; + } + + public String getSagReason() { + return sagReason; + } + + public void setSagReason(String sagReason) { + this.sagReason = sagReason; + } + + public String getSagType() { + return sagType; + } + + public void setSagType(String sagType) { + this.sagType = sagType; + } + + public String getStrEventValue() { + return strEventValue; + } + + public void setStrEventValue(String strEventValue) { + this.strEventValue = strEventValue; + } + + public String getStrPersist() { + return strPersist; + } + + public void setStrPersist(String strPersist) { + this.strPersist = strPersist; + } + + + + // 根据设定规则进行排序 + @Override + public int compareTo(SagEvent obj) { + switch (this.getSortType()) { + case 1: + return obj.getSeverity().compareTo(this.getSeverity()); + case 2: + return this.getTime().compareTo(obj.getTime()); + case 3: { + if (obj.getVoltage().compareTo(this.getVoltage()) != 0) { + return obj.getVoltage().compareTo(this.getVoltage()); + } + else { + return this.getEventValue().compareTo(obj.getEventValue()); + } + } + default: + break; + } + + return this.getFirstTimeMills().compareTo(obj.getFirstTimeMills()); + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/enums/AdvanceResponseEnum.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/enums/AdvanceResponseEnum.java new file mode 100644 index 0000000..6de2d45 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/enums/AdvanceResponseEnum.java @@ -0,0 +1,107 @@ +package com.njcn.product.advance.eventSource.pojo.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年04月13日 10:50 + */ +@Getter +public enum AdvanceResponseEnum { + + ANALYSIS_USER_DATA_ERROR("A0101","解析用采数据内容失败"), + + INTERNAL_ERROR("A0101","系统内部异常"), + + USER_DATA_EMPTY("A0101","用采数据内容为空"), + + USER_DATA_NOT_FOUND("A0101","未找到用采数据"), + + RESP_DATA_NOT_FOUND("A0101","未找到责任划分数据"), + + WIN_TIME_ERROR("A0101","限值时间小于窗口"), + + CALCULATE_INTERVAL_ERROR("A0101","对齐计算间隔值非法"), + + RESP_RESULT_DATA_NOT_FOUND("A0101","未找到责任划分缓存数据"), + + USER_DATA_P_NODE_PARAMETER_ERROR("A0101","无用采用户或所有用户的完整性均不满足条件"), + + RESPONSIBILITY_PARAMETER_ERROR("A0101","调用接口程序计算失败,参数非法"), + + EVENT_EMPTY("A0102","没有查询到未分析事件"), + + USER_NAME_EXIST("A0103","用户名已存在"), + + DATA_NOT_FOUND("A0104","数据缺失,请根据模版上传近两周数据"), + + DATA_UNDERRUN("A0104","数据量不足,请根据模版上传充足近两周数据"), + + DOCUMENT_FORMAT_ERROR("A0105","数据缺失,导入失败!请检查导入文档的格式是否正确"), + DEVICE_LOST("A0104","用户下缺少设备"), + + USER_LOST("A0106","干扰源用户缺失"), + UNCOMPLETE_STRATEGY("A0106","配置安全,III级预警,II级预警,I级预警4条完整策略"), + EXISTENCE_EVALUATION_RESULT("A0104","存在评结果结果,如要评估,请删除后评估"), + + SG_USER_NAME_REPEAT("A0102","业务用户名重复"), + + SG_PRODUCT_LINE_NAME_REPEAT("A0102","生产线名重复"), + + SG_USER_ID_MISS("A0102","业务用户id缺失"), + + SG_PRODUCT_LINE_ID_MISS("A0102","生产线id缺失"), + + SG_MACHINE_ID_MISS("A0102","设备id缺失"), + + IMPORT_EVENT_DATA_FAIL("A0102","请检查导入数据的准确性"), + + PRODUCT_LINE_DATA_MISS("A0102","生产线数据缺失"), + + MACHINE_DATA_MISS("A0102","设备数据缺失"), + + INCOMING_LINE_DATA_MISS("A0102","进线数据缺失"), + + EVENT_DATA_MISS("A0102","没有可供参考的暂降数据"), + + WIN_DATA_ERROR("A0102","算法校验窗宽超限"), + + DATA_ERROR("A0102","算法校验数据长度超限"), + + INIT_DATA_ERROR("A0102","算法初始化数据失败"), + + USER_HAS_PRODUCT("A0102","当前用户存在生产线"), + + PRODUCT_HAS_MACHINE("A0102","当前生产线存在设备"), + + MACHINE_HAS_UNIT("A0102","当前设备存在元器件"), + + EVENT_TIME_ERROR("A0102","暂降事件时间格式有误,请检查"), + + INVALID_FILE_TYPE("A0102","请选择CSV文件"), + + INSUFFICIENCY_OF_INTEGRITY("A00561","时间范围内谐波数据完整性不足"), + INTERVAL_ERROR("A0102","监测点时间间隔错误"), + + ; + + private final String code; + + private final String message; + + AdvanceResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } + + public static String getCodeByMsg(String msg){ + for (AdvanceResponseEnum userCodeEnum : AdvanceResponseEnum.values()) { + if (userCodeEnum.message.equalsIgnoreCase(msg)) { + return userCodeEnum.code; + } + } + return ""; + } + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/PqsRelevanceLog.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/PqsRelevanceLog.java new file mode 100644 index 0000000..d290de5 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/PqsRelevanceLog.java @@ -0,0 +1,39 @@ +package com.njcn.product.advance.eventSource.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + + +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("pqs_relevancy_log") +public class PqsRelevanceLog extends BaseEntity { + + @TableId("id") + private String id; + /** + * 归一化算法时间 + */ + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timeId; + + + /** + * 归一化算法描述 + */ + private String contentDes; + + private Integer state; + + @TableField(exist = false) + private String createName; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/RmpEventDetailAssPO.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/RmpEventDetailAssPO.java new file mode 100644 index 0000000..c778c3e --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/pojo/po/RmpEventDetailAssPO.java @@ -0,0 +1,52 @@ +package com.njcn.product.advance.eventSource.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import com.njcn.product.advance.eventSource.pojo.dto.eventAggregate.SagEvent; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/8/9 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("r_mp_event_detail_ass") +public class RmpEventDetailAssPO extends BaseEntity { + + /** + *事件关联分析表uuid + */ + @TableId("Event_Ass_Id") + private String eventAssId; + + /** + *发生时间(归一化中第一个时间) + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") + private LocalDateTime timeId; + + /** + *关联事件描述 + */ + private String contentDes; + + /** + *是否进行范围分析(0:分析;1:未分析) + */ + private Integer analyseFlag; + + + @TableField(exist = false) + private List list; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/EventRelevantAnalysisService.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/EventRelevantAnalysisService.java new file mode 100644 index 0000000..c0a7fd2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/EventRelevantAnalysisService.java @@ -0,0 +1,35 @@ +package com.njcn.product.advance.eventSource.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import com.njcn.web.pojo.param.BaseParam; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/6/30 + */ +public interface EventRelevantAnalysisService extends IService { + + /** + * + * @author cdf + * @date 2023/6/30 + */ + void processEvents(LocalDateTime startTime,LocalDateTime endTime,String deptId); + + + + + + + + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/HistoryHarmonicService.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/HistoryHarmonicService.java new file mode 100644 index 0000000..6b64a62 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/HistoryHarmonicService.java @@ -0,0 +1,25 @@ +package com.njcn.product.advance.eventSource.service; + +import com.njcn.influx.pojo.dto.HarmHistoryDataDTO; +import com.njcn.influx.pojo.po.DataHarmPowerP; +import com.njcn.product.advance.responsility.pojo.bo.UserDataExcel; +import com.njcn.product.advance.responsility.pojo.param.HistoryHarmParam; +import com.njcn.product.advance.responsility.pojo.param.PHistoryHarmParam; + +import java.util.List; + +public interface HistoryHarmonicService { + + /*** + * 按次、监测点获取指定历史谐波数据 + * @author hongawen + * @date 2023/7/19 9:56 + * @param historyHarmParam 请求历史谐波数据参数 + * @return HarmHistoryDataDTO + */ + HarmHistoryDataDTO getHistoryHarmData(HistoryHarmParam historyHarmParam); + + + List getHarmonicPData(PHistoryHarmParam param); + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/RmpEventDetailAssService.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/RmpEventDetailAssService.java new file mode 100644 index 0000000..7c92e92 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/RmpEventDetailAssService.java @@ -0,0 +1,7 @@ +package com.njcn.product.advance.eventSource.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO; + +public interface RmpEventDetailAssService extends IService { +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/EventRelevantAnalysisServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/EventRelevantAnalysisServiceImpl.java new file mode 100644 index 0000000..941553f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/EventRelevantAnalysisServiceImpl.java @@ -0,0 +1,565 @@ +package com.njcn.product.advance.eventSource.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.LocalDateTimeUtil; +import cn.hutool.core.date.TimeInterval; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.advance.eventSource.mapper.RelevantLogMapper; +import com.njcn.product.advance.eventSource.mapper.RmpEventAdvanceMapper; +import com.njcn.product.advance.eventSource.pojo.dto.eventAggregate.*; +import com.njcn.product.advance.eventSource.pojo.enums.AdvanceResponseEnum; +import com.njcn.product.advance.eventSource.pojo.po.PqsRelevanceLog; +import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO; +import com.njcn.product.advance.eventSource.service.EventRelevantAnalysisService; +import com.njcn.product.advance.eventSource.service.RmpEventDetailAssService; +import com.njcn.product.advance.eventSource.utils.UtilNormalization; +import com.njcn.product.system.dict.mapper.DictDataMapper; +import com.njcn.product.system.dict.pojo.enums.DicDataEnum; +import com.njcn.product.system.dict.pojo.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.terminal.mysqlTerminal.mapper.LedgerScaleMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.PqsTflgployass; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.AdvanceEventDetailVO; +import com.njcn.product.terminal.mysqlTerminal.service.CommGeneralService; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * pqs + * + * @author cdf + * @date 2023/6/30 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class EventRelevantAnalysisServiceImpl extends ServiceImpl implements EventRelevantAnalysisService { + + + private final DictDataMapper dictDataMapper; + + private final RmpEventAdvanceMapper rmpEventAdvanceMapper; + + private final RelevantLogMapper relevantLogMapper; + + private final CommGeneralService commGeneralService; + + private final RmpEventAdvanceMapper eventAdvanceMapper; + + private final LedgerScaleMapper ledgerScaleMapper; + + private final RmpEventDetailAssService rmpEventDetailAssService; + + + @Override + @Transactional(rollbackFor = Exception.class) + public void processEvents(LocalDateTime startTime, LocalDateTime endTime, String deptId) { + TimeInterval timeInterval = new TimeInterval(); + + //获取节点和变压器配置信息 + Map> nodeMap1 = getBeforeNodeInfo(); + Set>> nodeSort1 = nodeMap1.entrySet(); + System.out.println(nodeSort1); + + Map entityMtransMap1 = getNodeInfo(); + Set> setMtrans1 = entityMtransMap1.entrySet(); + System.out.println(setMtrans1); + + LocalDateTime date = LocalDateTime.now(); + HandleEvent handleEvent = new HandleEvent(); + // 获取并验证基础数据 + List baseList = handleEvent.getData(startTime, endTime, deptId); + if (CollectionUtil.isEmpty(baseList)) { + throw new BusinessException("当前时间段暂无可分析事件"); + } + List otherEventList = new ArrayList<>(baseList); + + + Map entityMtransMap = getNodeInfo(); + Set> setMtrans = entityMtransMap.entrySet(); + System.out.println(setMtrans); + //获取节点和变压器配置信息 + Map> nodeMap = getBeforeNodeInfo(); + Set>> nodeSort = nodeMap.entrySet(); + System.out.println(nodeSort); + //初始化结果容器 + List listSagEvent = new ArrayList<>(); + List rmpEventDetailAssPoList = new ArrayList<>(); + + //获取短路故障字典 + DictData dictData = dictDataMapper.getDicDataByNameAndTypeName(DicDataTypeEnum.EVENT_REASON.getName(), DicDataEnum.SHORT_TROUBLE.getName()); + for (Map.Entry> m : nodeSort) { + List list = new ArrayList<>(); + Set> mapValue = m.getValue().entrySet(); + FinalData.NODE_NUM = m.getValue().size(); + + for (Map.Entry mm : mapValue) { + for (EntityGroupEvtData groupEvtData : baseList) { + if (groupEvtData.getNodePhysics().equals(mm.getKey()) && dictData.getId().equals(groupEvtData.getSagReason())) { + groupEvtData.setNode(mm.getValue()); + list.add(groupEvtData); + } + } + + // 筛选不在矩阵中的事件id + otherEventList.removeIf(entityGroupEvtData -> entityGroupEvtData.getNodePhysics().equals(mm.getKey()) && dictData.getId().equals(entityGroupEvtData.getSagReason())); + } + + EntityGroupEvtData[] entityGroupEvtData = new EntityGroupEvtData[list.size()]; + Collections.sort(list); + list.toArray(entityGroupEvtData); + + + for (Map.Entry mEntry : setMtrans) { + if (mEntry.getKey().equals(m.getKey())) { + //算法最多处理1000条数据,超过限制需分批处理 先将数据根据某种方式进行升序/降序排序,然后分段处理 加入循环处理 + int circulation = entityGroupEvtData.length % FinalData.MAX_EVT_NUM == 0 + ? entityGroupEvtData.length / FinalData.MAX_EVT_NUM + : entityGroupEvtData.length / FinalData.MAX_EVT_NUM + 1; + + for (int i = 0; i < circulation; i++) { + int to = 0; + + if (i == circulation - 1) { + to = entityGroupEvtData.length % FinalData.MAX_EVT_NUM > 0 + ? entityGroupEvtData.length + : (i + 1) * FinalData.MAX_EVT_NUM - 1; + } else { + to = (i + 1) * FinalData.MAX_EVT_NUM - 1; + } + + EntityGroupEvtData[] arrayObj = Arrays.copyOfRange(entityGroupEvtData, + i * FinalData.MAX_EVT_NUM, to); + EntityMtrans entityMtrans = mEntry.getValue(); + EntityGroupData entityGroupData = handleEvent.translate(arrayObj, entityMtrans); + // 处理分析结果 + handleEvent.show_group_info(entityGroupData, listSagEvent, rmpEventDetailAssPoList, date); + } + } + } + } + + // 处理非标准数据 + disposeNonStandardData(handleEvent, otherEventList, rmpEventDetailAssPoList, listSagEvent, date); + rmpEventDetailAssService.saveBatch(rmpEventDetailAssPoList); + + List eventUpdateList = new ArrayList<>(); + for (int i = 0; i < listSagEvent.size(); i++) { + RmpEventDetailPO rmp = new RmpEventDetailPO(); + rmp.setEventId(listSagEvent.get(i).getIndexEventDetail()); + rmp.setEventassIndex(listSagEvent.get(i).getIndexEventAss()); + rmp.setDealTime(listSagEvent.get(i).getDealTime()); + eventUpdateList.add(rmp); + if ((i + 1) % 1000 == 0) { + this.updateBatchById(eventUpdateList); + eventUpdateList.clear(); + } else if (i == listSagEvent.size() - 1) { + this.updateBatchById(eventUpdateList); + } + } + + // 增加策略记录 + String describe = "用户" + RequestUtil.getLoginName() + "进行了关联分析"; + PqsRelevanceLog entityPqsRelevance = new PqsRelevanceLog(); + entityPqsRelevance.setContentDes(describe); + entityPqsRelevance.setState(DataStateEnum.ENABLE.getCode()); + entityPqsRelevance.setTimeId(date); + relevantLogMapper.insert(entityPqsRelevance); + + log.info("事件关联分析用时:" + timeInterval.interval() / 1000 + "秒"); + } + + + /********************************************************************** + * 归集结果与非矩阵事件进行比对 + **********************************************************************/ + public void disposeNonStandardData(HandleEvent handleEvent, List noDealList, List assPoList, List list2, LocalDateTime date) { + Iterator iterator = noDealList.iterator(); + while (iterator.hasNext()) { + EntityGroupEvtData entityGroupEvtData = iterator.next(); + + for (RmpEventDetailAssPO eventAssObj : assPoList) { + long sRange = Math.abs(Duration.between(eventAssObj.getTimeId(), entityGroupEvtData.getSagEvent().getSagTime()).getSeconds()); + if (sRange < 10) { + int b = 0; + int a = 0; + + for (SagEvent sagEvent : eventAssObj.getList()) { + if (sagEvent.getCata() == 9) { + b++; + } else if (sagEvent.getCata() != 10) { + a++; + } + } + + if (b > 0) { + if (entityGroupEvtData.getCata() < 9) { + break; + } + } else if (a > 0) { + if (entityGroupEvtData.getCata() == 9) { + break; + } + } + + iterator.remove(); + entityGroupEvtData.getSagEvent().setIndexEventAss(eventAssObj.getEventAssId()); + entityGroupEvtData.getSagEvent().setDealTime(date); + eventAssObj.getList().add(entityGroupEvtData.getSagEvent()); + String describe = "事件关联分析编号" + eventAssObj.getTimeId() + "共包含" + eventAssObj.getList().size() + "个事件"; + eventAssObj.setContentDes(describe); + list2.add(entityGroupEvtData.getSagEvent()); + break; + } + } + } + + // 如果还有未归集的数据则单独拎为单一事件处理 + for (EntityGroupEvtData entityGroupEvtData : noDealList) { + String strUUID = IdUtil.simpleUUID(); + entityGroupEvtData.getSagEvent().setIndexEventAss(strUUID); + entityGroupEvtData.getSagEvent().setDealTime(date); + + List dealList = new ArrayList<>(); + dealList.add(entityGroupEvtData.getSagEvent()); + handleEvent.processing(dealList, assPoList, date); + list2.add(entityGroupEvtData.getSagEvent()); + } + } + + + class HandleEvent { + public EntityGroupData translate(EntityGroupEvtData[] entityGroupEvtData, EntityMtrans entityMtrans) { + // 获取测试数据的数组长度 + int testLogNum = entityGroupEvtData.length; + + // 实例化EntityGroupData,给其中的数组分配空间 + EntityGroupData groupBuf = new EntityGroupData(); + + // 填入日志 + setMatrixcata(groupBuf, entityMtrans); + create_evt_buf(entityGroupEvtData, groupBuf, testLogNum); + + UtilNormalization.sort_Tstart(groupBuf); // 根据时标进行划分 + // 根据暂降类型进行划分 + for (int i = 0; i < groupBuf.getGrp_all_num(); i++) { + UtilNormalization.sort_cata(groupBuf, i); + } + + return groupBuf; + } + + //获取原始暂降数据 + public List getData(LocalDateTime startTime, LocalDateTime endTime, String deptId) { + List entityGroupEvtDataList = new ArrayList<>(); + + List advanceType = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()); + Map advanceMap = advanceType.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + + //获取时间范围内的事件 + List advanceEventDetailVOList = querySagEventsAll(startTime, endTime, deptId); + for (AdvanceEventDetailVO advanceEventDetailVO : advanceEventDetailVOList) { // 获取监测点线路序号 + //母线id + String nodePhysics = advanceEventDetailVO.getBusBarId(); + + // 根据暂降类型获取高级算法对应的编号 + int cata; + int startTimeTemp; + + if (Objects.isNull(advanceEventDetailVO.getFirstType())) { + cata = advanceMap.get(advanceEventDetailVO.getAdvanceType()).getAlgoDescribe(); + long timestampMillis = advanceEventDetailVO.getStartTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + startTimeTemp = (int) (timestampMillis / 1000); + } else { + cata = advanceMap.get(advanceEventDetailVO.getAdvanceType()).getAlgoDescribe(); // 获取类型 + long timestampMillis = advanceEventDetailVO.getFirstTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + startTimeTemp = (int) (timestampMillis / 1000); + } + + // 填充SagEvent对象数据 + SagEvent sagEvent = new SagEvent(); + + sagEvent.setIndexEventDetail(advanceEventDetailVO.getEventId()); + sagEvent.setSagTime(advanceEventDetailVO.getStartTime()); + sagEvent.setFirstTime(advanceEventDetailVO.getFirstTime());// 必须增加,否则序列化出错 + sagEvent.setTime(Timestamp.valueOf(advanceEventDetailVO.getStartTime()).getTime()); + sagEvent.setFirstTimeMills((long) startTimeTemp); + sagEvent.setMsec(advanceEventDetailVO.getDuration()); + PlantInfo plantInfo = new PlantInfo(); + plantInfo.setNameBD(advanceEventDetailVO.getSubName()); + plantInfo.setNameGD(advanceEventDetailVO.getGdName()); + plantInfo.setNamePoint(advanceEventDetailVO.getLineId()); + sagEvent.setPlantInfo(plantInfo); + sagEvent.setIndexPoint(advanceEventDetailVO.getLineId()); + sagEvent.setCata(cata); + + + EntityGroupEvtData entityGroupEvtData = new EntityGroupEvtData(nodePhysics, startTimeTemp, cata, -1, sagEvent, advanceEventDetailVO.getAdvanceReason()); + entityGroupEvtDataList.add(entityGroupEvtData); + } + + return entityGroupEvtDataList; + } + + + public void create_evt_buf(EntityGroupEvtData[] arr, EntityGroupData obj, int len) { + System.arraycopy(arr, 0, obj.getIn_buf(), 0, arr.length); + obj.setEvt_in_num(len); + } + + public void create_matrixcata(List list, EntityMtrans entityMtrans) { + EntityLogic[] node_data = new EntityLogic[list.size()]; + + for (int i = 0; i < list.size(); i++) { + node_data[i] = list.get(i); + } + + int len = node_data.length; + + UtilNormalization.matrixcata_pro(node_data, entityMtrans, len); + } + + public void setMatrixcata(EntityGroupData obj, EntityMtrans entityMtrans) { + int i, j; + for (i = 0; i < (FinalData.MAX_CATA_NUM - 1); i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) { + obj.getMatrixcata()[i][j] = entityMtrans.getMatrixcata1()[i][j]; + } + } + } + + public void show_group_info(EntityGroupData obj, List list, List assEvent, LocalDateTime date) { + int i, j, k; + for (i = 0; i < obj.getGrp_all_num(); i++) { + String strUUID = IdUtil.simpleUUID(); + List listTem = new ArrayList<>(); + + for (j = 0; j < FinalData.MAX_CATA_NUM + 2; j++) { + if (obj.getGrp_cata_num()[i][j] != 0) { + for (k = 0; k < obj.getGrp_cata_num()[i][j]; k++) { + obj.getGrp_cata_buf()[i][j][k].getSagEvent().setIndexEventAss(strUUID); + obj.getGrp_cata_buf()[i][j][k].getSagEvent().setDealTime(date); + listTem.add(obj.getGrp_cata_buf()[i][j][k].getSagEvent()); + list.add(obj.getGrp_cata_buf()[i][j][k].getSagEvent()); + } + } + } + + if (!listTem.isEmpty()) { + processing(listTem, assEvent, date); + } + } + } + + public void processing(List list, List lists, LocalDateTime date) { + // 根据暂降事件发生时间进行排序 + Collections.sort(list); + RmpEventDetailAssPO eventAssObj = new RmpEventDetailAssPO(); + String strUUID = list.get(0).getIndexEventAss(); + + // 归一化处理数据填充 + eventAssObj.setEventAssId(strUUID); + + // 事件发生时间 + eventAssObj.setTimeId(list.get(0).getSagTime()); + + + // 获取当前用户GUID + eventAssObj.setCreateBy(RequestUtil.getUserId()); + + // 是否进行范围分析 默认未分析 + eventAssObj.setAnalyseFlag(1); + + // 更新时间 + eventAssObj.setUpdateTime(date); + + + // 暂降事件描述 + String codeName = LocalDateTimeUtil.format(eventAssObj.getTimeId(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")); + String describe = "事件关联分析编号" + codeName + "共包含" + list.size() + "个事件"; + eventAssObj.setContentDes(describe); + eventAssObj.setList(list); + lists.add(eventAssObj); + } + } + + + Map> getBeforeNodeInfo() { + Map> setNodeSort = new HashMap<>(); + List list = rmpEventAdvanceMapper.getLogic(); + + if (CollectionUtil.isNotEmpty(list)) { + Map> map = getLogicInfo(list); + setNodeSort = nodeSort(map); + } + return setNodeSort; + } + + + /************************************************************************************* + * 获取变压器信息并生成矩阵 + *************************************************************************************/ + public Map getNodeInfo() { + Map entityMtranMap = new HashMap<>(32); + List list = rmpEventAdvanceMapper.getLogic(); + + if (CollectionUtil.isNotEmpty(list)) { + Map> map = getLogicInfo(list); + Map> setNodeSort = nodeSort(map); + + setNodeSort.forEach((key, val) -> { + FinalData.NODE_NUM = val.size(); + List listNew = new ArrayList<>(); + + for (EntityLogic entityLogic : list) { + if (entityLogic.getTPIndex().equals(key)) { + entityLogic.setNode_h(val.get(entityLogic.getNodeBefore())); + entityLogic.setNode_l(val.get(entityLogic.getNodeNext())); + listNew.add(entityLogic); + } + } + + EntityMtrans entityMtrans = new EntityMtrans(); + + HandleEvent handleEvent = new HandleEvent(); + handleEvent.create_matrixcata(listNew, entityMtrans); + entityMtranMap.put(key, entityMtrans); + }); + } + return entityMtranMap; + } + + + /******************************************* + * 增加排序功能并缓存进redis + *******************************************/ + public Map> nodeSort(Map> mapList) { + Set>> sets = mapList.entrySet(); + Map> map = new HashMap<>(); + + for (Map.Entry> m : sets) { + int index = 1; + Map map2 = new HashMap<>(); + + for (String item : m.getValue()) { + map2.put(item, index++); + } + + map.put(m.getKey(), map2); + } + return map; + } + + + /** + * 抽取物理隔绝信息与母线的关系并放入map集合中 + * 与getTflgPloyInfo()方法功能类似 + */ + public Map> getLogicInfo(List list) { + if (list.size() > 0) { + Iterator iterator = getAreaInfo(list).iterator(); + Map> map = new HashMap<>(); + + while (iterator.hasNext()) { + List listLogic = new ArrayList<>(); + String areaString = iterator.next(); + + for (EntityLogic entityLogic : list) { + if (entityLogic.getTPIndex().equals(areaString)) { + listLogic.add(entityLogic.getNodeBefore()); + listLogic.add(entityLogic.getNodeNext()); + } + } + + //去除list中重复数据 + Set set = new TreeSet<>(listLogic); + map.put(areaString, new ArrayList<>(set)); + } + + return map; + } + + return null; + } + + + /** + * 获取物理隔绝编码信息 + * 供getInfo()、getLogicInfo()方法使用 + * 先从list数组中去重,然后获取物理隔绝编码 + */ + public Set getAreaInfo(List list) { + Set set = new HashSet(list); + Iterator iterator = set.iterator(); + Set setReturn = new HashSet(); + + while (iterator.hasNext()) { + Object object = iterator.next(); + + if (object instanceof PqsTflgployass) { + setReturn.add(((PqsTflgployass) object).getTpIndex()); + continue; + } + + setReturn.add(((EntityLogic) object).getTPIndex()); + } + + return setReturn; + } + + + public List querySagEventsAll(LocalDateTime startTime, LocalDateTime endTime, String deptId) { + List result = new ArrayList<>(); + List lineIds = commGeneralService.getRunLineIdsByDept(deptId); + if (CollUtil.isNotEmpty(lineIds)) { + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.and(i -> i.isNull(RmpEventDetailPO::getEventassIndex).or().eq(RmpEventDetailPO::getEventassIndex, "")) + .between(RmpEventDetailPO::getStartTime, startTime, endTime).in(RmpEventDetailPO::getMeasurementPointId,lineIds); + List rmpEventDetailPOList = eventAdvanceMapper.selectList(lambdaQueryWrapper); + if (CollectionUtil.isEmpty(rmpEventDetailPOList)) { + throw new BusinessException(AdvanceResponseEnum.EVENT_EMPTY); + } + List tempLineIds = rmpEventDetailPOList.stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList()); + List temLine = ledgerScaleMapper.getLedgerBaseInfo(tempLineIds); + Map map = temLine.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity())); + + result = BeanUtil.copyToList(rmpEventDetailPOList, AdvanceEventDetailVO.class); + result.forEach(item -> { + if (map.containsKey(item.getLineId())) { + LedgerBaseInfo areaLineInfoVO = map.get(item.getLineId()); + item.setGdName(areaLineInfoVO.getGdName()); + item.setSubName(areaLineInfoVO.getStationName()); + item.setNum(areaLineInfoVO.getNum()); + item.setVoltageId(areaLineInfoVO.getVoltageLevel()); + item.setBusBarId(areaLineInfoVO.getBusBarId()); + } + }); + } + result = result.stream().filter(it -> StrUtil.isNotBlank(it.getBusBarId())).collect(Collectors.toList()); + return result; + } +} + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/HistoryHarmonicServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/HistoryHarmonicServiceImpl.java new file mode 100644 index 0000000..e46e340 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/HistoryHarmonicServiceImpl.java @@ -0,0 +1,344 @@ +package com.njcn.product.advance.eventSource.service.impl; + +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.PubUtils; +import com.njcn.influx.imapper.DataHarmPowerPMapper; +import com.njcn.influx.imapper.DataHarmRateVMapper; +import com.njcn.influx.imapper.DataIMapper; +import com.njcn.influx.pojo.constant.InfluxDBTableConstant; +import com.njcn.influx.pojo.dto.HarmData; +import com.njcn.influx.pojo.dto.HarmHistoryDataDTO; +import com.njcn.influx.pojo.po.DataHarmPowerP; +import com.njcn.influx.pojo.po.DataHarmRateV; +import com.njcn.influx.pojo.po.DataI; +import com.njcn.influx.query.InfluxQueryWrapper; +import com.njcn.product.advance.eventSource.pojo.enums.AdvanceResponseEnum; +import com.njcn.product.advance.responsility.imapper.DataHarmP; +import com.njcn.product.advance.responsility.pojo.bo.UserDataExcel; +import com.njcn.product.advance.responsility.pojo.param.HistoryHarmParam; +import com.njcn.product.advance.eventSource.service.HistoryHarmonicService; +import com.njcn.product.advance.responsility.pojo.param.PHistoryHarmParam; +import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.OverlimitMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Overlimit; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * @Author: cdf + * @CreateTime: 2025-09-08 + * @Description: + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class HistoryHarmonicServiceImpl implements HistoryHarmonicService { + + private final OverlimitMapper overlimitMapper; + + private final LineMapper lineMapper; + + private final DataIMapper dataIMapper; + + private final DataHarmRateVMapper dataHarmRateVMapper; + + private final DataHarmPowerPMapper dataHarmPowerPMapper; + + + + + @Override + public HarmHistoryDataDTO getHistoryHarmData(HistoryHarmParam historyHarmParam) { + List historyData; + float overLimit; + Overlimit overlimit = overlimitMapper.selectById(historyHarmParam.getLineId()); + //判断是电流还是电压谐波 + if (historyHarmParam.getType() == 0) { + historyData = getIHistoryData(historyHarmParam); + overLimit = PubUtils.getValueByMethod(overlimit, "getIharm", historyHarmParam.getTime()); + } else { + historyData = getVHistoryData(historyHarmParam); + overLimit = PubUtils.getValueByMethod(overlimit, "getUharm", historyHarmParam.getTime()); + } + return new HarmHistoryDataDTO(historyData, overLimit); + } + + @Override + public List getHarmonicPData(PHistoryHarmParam historyHarmParam) { + InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerP.class); + influxQueryWrapper + .select(DataHarmPowerP::getP,DataHarmPowerP::getTime,DataHarmPowerP::getLineId) + .eq(DataHarmPowerP::getPhaseType,InfluxDBTableConstant.PHASE_TYPE_T) + .eq(DataHarmPowerP::getValueType,InfluxDBTableConstant.CP95) + .regular(DataHarmPowerP::getLineId,historyHarmParam.getLineIds()) + .between(DataHarmPowerP::getTime,historyHarmParam.getSearchBeginTime().concat(InfluxDBTableConstant.START_TIME), historyHarmParam.getSearchEndTime().concat(InfluxDBTableConstant.END_TIME)); + List dataHarmPowerPList = dataHarmPowerPMapper.selectByQueryWrapper(influxQueryWrapper); + return dataHarmPowerPList; + } + + + /*** + * 获取指定次数 监测点的历史谐波电流数据 + * @author hongawen + * @date 2023/7/19 10:03 + */ + private List getIHistoryData(HistoryHarmParam historyHarmParam) { + LineDevGetDTO lineDetailData = lineMapper.getMonitorDetail(historyHarmParam.getLineId()); + List historyData; + InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class, HarmData.class); + influxQueryWrapper + .select(DataI::getTime) + .max("i_" + historyHarmParam.getTime(), "value") + .between(DataI::getTime, historyHarmParam.getSearchBeginTime().concat(" 00:00:00"), historyHarmParam.getSearchEndTime().concat(" 23:59:59")) + .eq(DataI::getLineId, historyHarmParam.getLineId()) + .or(DataI::getPhaseType, Stream.of(InfluxDBTableConstant.PHASE_TYPE_A, InfluxDBTableConstant.PHASE_TYPE_B, InfluxDBTableConstant.PHASE_TYPE_C).collect(Collectors.toList())) + //以时间分组时,需要加上时间间隔,比如此处需要加上监测点的采样间隔 + .groupBy("time(" + lineDetailData.getInterval() + "m)") + .timeAsc(); + String string = influxQueryWrapper.generateSql(); + historyData = dataIMapper.getIHistoryData(string); + if (CollectionUtils.isEmpty(historyData)) { + //如果数据为空,则提示给用户暂无数据 + throw new BusinessException(CommonResponseEnum.NO_DATA); + } + //最新两条数据的间隔与监测点查出的间隔做对比,返回一个合理的间隔 + historyData = historyData.stream().filter(Objects::nonNull).collect(Collectors.toList()); + int lineInterval = getInterval(lineDetailData.getInterval(), PubUtils.instantToDate(historyData.get(historyData.size() - 1).getTime()), PubUtils.instantToDate(historyData.get(historyData.size() - 2).getTime())); + historyData = dealHistoryData(historyData, lineInterval); + if (CollectionUtils.isEmpty(historyData)) { + //如果数据为空,则提示给用户暂无数据 + throw new BusinessException(CommonResponseEnum.NO_DATA); + } + //根据时间天数,获取理论上多少次用采数据 + List dateStr = PubUtils.getTimes(DateUtil.beginOfDay(DateUtil.parse(historyHarmParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(historyHarmParam.getSearchEndTime()))); + int dueTimes = dateStr.size() * 1440 / lineInterval; + int realTimes = historyData.size(); + if (dueTimes != realTimes) { + //期待值与实际值不等,则提示用户时间范围内谐波数据完整性不足 + throw new BusinessException(AdvanceResponseEnum.INSUFFICIENCY_OF_INTEGRITY); + } + return historyData.stream().sorted(Comparator.comparing(HarmData::getTime)).collect(Collectors.toList()); + } + + + /** + * 获取谐波电压的数据 + *

+ * 因历史谐波表data_harmrate_v + */ + private List getVHistoryData(HistoryHarmParam historyHarmParam) { + LineDevGetDTO lineDetailData = lineMapper.getMonitorDetail(historyHarmParam.getLineId()); + List historyData; + InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class, HarmData.class); + influxQueryWrapper + .select(DataHarmRateV::getTime) + .max("v_" + historyHarmParam.getTime(), "value") + .between(DataHarmRateV::getTime, historyHarmParam.getSearchBeginTime().concat(" 00:00:00"), historyHarmParam.getSearchEndTime().concat(" 23:59:59")) + .eq(DataHarmRateV::getLineId, historyHarmParam.getLineId()) + .or(DataHarmRateV::getPhaseType, Stream.of(InfluxDBTableConstant.PHASE_TYPE_A, InfluxDBTableConstant.PHASE_TYPE_B, InfluxDBTableConstant.PHASE_TYPE_C).collect(Collectors.toList())) + .groupBy("time(" + lineDetailData.getInterval() + "m)") + .timeAsc(); + + + historyData = dataHarmRateVMapper.getHarmRateVHistoryData(influxQueryWrapper); + if (CollectionUtils.isEmpty(historyData)) { + //如果数据为空,则提示给用户暂无数据 + throw new BusinessException(CommonResponseEnum.NO_DATA); + } + historyData = historyData.stream().filter(Objects::nonNull).collect(Collectors.toList()); + int lineInterval = getInterval(lineDetailData.getInterval(), PubUtils.instantToDate(historyData.get(historyData.size() - 1).getTime()), PubUtils.instantToDate(historyData.get(historyData.size() - 2).getTime())); + //最新两条数据的间隔与监测点查出的间隔做对比,返回一个合理的间隔 + historyData = dealHistoryData(historyData, lineInterval); + if (CollectionUtils.isEmpty(historyData)) { + //如果数据为空,则提示给用户暂无数据 + throw new BusinessException(CommonResponseEnum.NO_DATA); + } + //根据时间天数,获取理论上多少次用采数据 + List dateStr = PubUtils.getTimes(DateUtil.beginOfDay(DateUtil.parse(historyHarmParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(historyHarmParam.getSearchEndTime()))); + int dueTimes = dateStr.size() * 1440 / lineInterval; + int realTimes = historyData.size(); + if (dueTimes != realTimes) { + //期待值与实际值不等,则提示用户时间范围内谐波数据完整性不足 + throw new BusinessException(AdvanceResponseEnum.INSUFFICIENCY_OF_INTEGRITY); + } + return historyData.stream().sorted(Comparator.comparing(HarmData::getTime)).collect(Collectors.toList()); + } + + + /** + * 获取合理的测量间隔 + */ + private int getInterval(int lineInterval, Date lastOne, Date lastTwo) { + int interval = 0; + Calendar one = Calendar.getInstance(); + one.setTime(lastOne); + Calendar two = Calendar.getInstance(); + two.setTime(lastTwo); + long oneTime = lastOne.getTime(); + long twoTime = lastTwo.getTime(); + long intvalTime = oneTime - twoTime; + long databaseInterval = lineInterval * 60 * 1000; + if (oneTime < twoTime || intvalTime >= databaseInterval) { + interval = lineInterval; + } + if (intvalTime < databaseInterval) { + interval = (int) (intvalTime / (1000 * 60)); + } + return interval; + } + + + + /** + * 根据库中查询的数据,进行数据补齐操作 + * + * @param beforeDeal 库中实际的历史谐波数据 + */ + private List dealHistoryData(List beforeDeal, int lineInterval) { + List result = new ArrayList<>(); + try { + if (CollectionUtils.isEmpty(beforeDeal)) { + return result; + } else { + //先将查询数据按日进行收集 + Map/*当前天的所有谐波数据*/> dayHistoryDatas = new HashMap<>(); + for (HarmData harmData : beforeDeal) { + Date time = PubUtils.instantToDate(harmData.getTime()); + String date = DateUtil.format(time, DatePattern.NORM_DATE_PATTERN); + if (dayHistoryDatas.containsKey(date)) { + Map harmDataMap = dayHistoryDatas.get(date); + harmDataMap.put(PubUtils.getSecondsAsZero(PubUtils.instantToDate(harmData.getTime())), harmData); + dayHistoryDatas.put(date, harmDataMap); + } else { + Map harmDataMap = new HashMap<>(); + harmDataMap.put(PubUtils.getSecondsAsZero(PubUtils.instantToDate(harmData.getTime())), harmData); + dayHistoryDatas.put(date, harmDataMap); + } + } + //将数据按日期处理后,开始进行完整性判断,满足完整性则进行补齐,否则返回空数据 + Set days = dayHistoryDatas.keySet(); + for (String day : days) { + //获取出当天的历史谐波数据 + Map harmDataMap = dayHistoryDatas.get(day); + if (CollectionUtils.isEmpty(harmDataMap)) { + continue; + } + int dueTimes = 1440 / lineInterval; + int realTimes = harmDataMap.size(); + double integrity = (double) realTimes / (double) dueTimes; + if (integrity < 0.9 || integrity >= 1.0) { + //完整性不足,则返回原数据 + Set dates = harmDataMap.keySet(); + for (Date time : dates) { + result.add(harmDataMap.get(time)); + } + } else if (integrity < 1.0) { + //进行数据补齐,数据补齐需要根据监测点测量间隔,最好是MAP格式 map的key是yyyy-MM-dd HH:mm + List afterDeal = new ArrayList<>(); + String timeTemp = day + " 00:00:00"; + Date date = DateUtil.parse(timeTemp, DatePattern.NORM_DATETIME_PATTERN); + for (int i = 0; i < dueTimes; i++) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MINUTE, lineInterval * i); + HarmData temp = harmDataMap.get(calendar.getTime()); + if (temp != null && temp.getValue() != null) { + afterDeal.add(temp); + } else { + //递归找到前面的值 + Float preValue = getPreHarmValue(date, calendar.getTime(), harmDataMap, lineInterval); + //递归找到后面的值 + Float appendValue = getAppendHarmValue(date, calendar.getTime(), harmDataMap, lineInterval); + HarmData harmData = new HarmData(); + harmData.setTime(PubUtils.dateToInstant(calendar.getTime())); + //还需要判断前值和后值为空的情况 + if (null == preValue && null == appendValue) { + harmData.setValue(0.0f); + } else if (null == preValue) { + harmData.setValue(appendValue); + } else if (null == appendValue) { + harmData.setValue(preValue); + } else { + harmData.setValue((preValue + appendValue) / 2); + } + afterDeal.add(harmData); + } + } + result.addAll(afterDeal); + } + } + } + } catch (Exception e) { + log.error("开始处理历史电压谐波数据失败,失败原因:{}", e.toString()); + throw new BusinessException(AdvanceResponseEnum.INSUFFICIENCY_OF_INTEGRITY); + } + return result; + } + + /** + * 递归找前值 谐波数据 + * + * @param date 起始时间 + * @param time 当前事件 + * @param beforeDeal 处理前的数据 + */ + private Float getPreHarmValue(Date date, Date time, Map beforeDeal, int interval) { + Float result; + if (date.getTime() >= time.getTime()) { + return null; + } else { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + interval = -interval; + calendar.add(Calendar.MINUTE, interval); + HarmData temp = beforeDeal.get(calendar.getTime()); + if (temp == null || temp.getValue() == null) { + result = getPreHarmValue(date, calendar.getTime(), beforeDeal, Math.abs(interval)); + } else { + result = temp.getValue(); + } + } + return result; + } + + + /** + * 递归找后置 谐波数据 + * + * @param date 起始时间 + * @param time 截止时间 + */ + private Float getAppendHarmValue(Date date, Date time, Map beforeDeal, int interval) { + Float result; + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_MONTH, 1); + calendar.add(Calendar.MINUTE, -interval); + if (calendar.getTimeInMillis() <= time.getTime()) { + return null; + } else { + Calendar calendar1 = Calendar.getInstance(); + calendar1.setTime(time); + calendar1.add(Calendar.MINUTE, interval); + HarmData temp = beforeDeal.get(calendar1.getTime()); + if (temp == null || temp.getValue() == null) { + result = getAppendHarmValue(date, calendar1.getTime(), beforeDeal, interval); + } else { + result = temp.getValue(); + } + } + return result; + } + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/RmpEventDetailAssServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/RmpEventDetailAssServiceImpl.java new file mode 100644 index 0000000..9ffe70d --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/service/impl/RmpEventDetailAssServiceImpl.java @@ -0,0 +1,18 @@ +package com.njcn.product.advance.eventSource.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.advance.eventSource.mapper.RmpEventDetailAssMapper; +import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO; +import com.njcn.product.advance.eventSource.service.RmpEventDetailAssService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +/** + * @Author: cdf + * @CreateTime: 2025-09-04 + * @Description: + */ +@Service +@RequiredArgsConstructor +public class RmpEventDetailAssServiceImpl extends ServiceImpl implements RmpEventDetailAssService { +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/eventSource/utils/UtilNormalization.java b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/utils/UtilNormalization.java new file mode 100644 index 0000000..599f906 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/eventSource/utils/UtilNormalization.java @@ -0,0 +1,347 @@ +package com.njcn.product.advance.eventSource.utils; + + +import com.njcn.product.advance.eventSource.pojo.dto.eventAggregate.*; + +public class UtilNormalization { + public static void matrixcata_pro(EntityLogic[] transformer, EntityMtrans entityMtrans, int len) { + int i, j, k; + int node1, node2, con; + int src_node[] = new int[] { 0 }; + + // 连接方式转化为矩阵形式,行、列表示所有节点 + // inf表示两个节点不相连,0表示与自身相连,其他数值表示变压器连接类型 + // 将初始矩阵的元素设为inf,对角线元素设为0 + for (i = 0; i < FinalData.NODE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) { + entityMtrans.getMtrans()[i][j] = FinalData.DATA_INF; + } + entityMtrans.getMtrans()[i][i] = 0; + } + // 根据transformer设置元素 + for (i = 0; i < len; i++) { + node1 = transformer[i].getNode_h(); + node2 = transformer[i].getNode_l(); + con = transformer[i].getType(); + entityMtrans.getMtrans()[node1 - 1][node2 - 1] = con; + entityMtrans.getMtrans()[node2 - 1][node1 - 1] = con; + } + StringBuilder str = new StringBuilder(); + for (i = 0; i < FinalData.NODE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) { + str.append(entityMtrans.getMtrans()[i][j]).append(" "); + if (j == (FinalData.NODE_NUM - 1)) + str.append("\r\n"); + } + } + + // 类型匹配矩阵Matrixcata + // Matrixcata模式匹配矩阵,列为节点数,行为总类别数,元素为第一个节点分别是1-6类别情况下其他节点类别情况。 + // 元素1,2,3,4,5,6 分别对应 Dc,Cb,Da,Cc,Db,Ca + // 设置矩阵第一行元素 + for (i = 0; i < FinalData.NODE_NUM; i++) + entityMtrans.getMatrixcata0()[0][i] = 0; + for (i = 1; i < FinalData.NODE_NUM; i++) { + // 路径缓存清空 + for (j = 0; j < FinalData.MAX_PATH_NUM; j++) { + for (k = 0; k < (FinalData.NODE_NUM + 1); k++) + entityMtrans.getPossiable_path()[j][k] = 0; + } + entityMtrans.setPath_num(0); + // 寻找路径 + src_node[0] = 0; + findPath(entityMtrans, src_node, i, 0, 1, FinalData.NODE_NUM); + if (entityMtrans.getPath_num() != 0) + entityMtrans.getMatrixcata0()[0][i] = entityMtrans.getPossiable_path()[0][FinalData.NODE_NUM]; // 采用第一条路径 + else + entityMtrans.getMatrixcata0()[0][i] = FinalData.DATA_INF; // 找不到路径填大值表示不通 + } + // 构造矩阵其他行元素 + for (i = 1; i < FinalData.EVT_TYPE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) + // EntityGroupData.Matrixcata0[i][j] = + // EntityGroupData.Matrixcata0[0][j] + i; + if (entityMtrans.getMatrixcata0()[0][j] == FinalData.DATA_INF) { + entityMtrans.getMatrixcata0()[i][j] = FinalData.DATA_INF; + } else { + entityMtrans.getMatrixcata0()[i][j] = entityMtrans.getMatrixcata0()[0][j] + i; + } + } + // 将数据归类到0-5 + for (i = 0; i < FinalData.EVT_TYPE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) + entityMtrans.getMatrixcata1()[i][j] = entityMtrans.getMatrixcata0()[i][j] % 6; + } + // 0换成6,将数据归类到1-6 + for (i = 0; i < FinalData.EVT_TYPE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) { + if (entityMtrans.getMatrixcata1()[i][j] == 0) + entityMtrans.getMatrixcata1()[i][j] = 6; + } + } + str.delete(0, str.length()); + for (i = 0; i < FinalData.EVT_TYPE_NUM; i++) { + for (j = 0; j < FinalData.NODE_NUM; j++) { + str.append(entityMtrans.getMatrixcata1()[i][j]).append(" "); + if (j == (FinalData.NODE_NUM - 1)) + str.append("\r\n"); + } + } + + } + + public static int findPath(EntityMtrans entityMtrans, int[] OriginalNode, int destination, int Weight, int src_num, int node_num) // 深度优先搜索 + { + int i, j; + int last_node; + int nextNodes[] = new int[FinalData.NODE_NUM]; + int nextNode_num = 0; + int nextNodes0[] = new int[FinalData.NODE_NUM]; + int nextNode_num0 = 0; + int tmpPath[] = new int[FinalData.NODE_NUM + 1]; + int tmpPath_num; + if (src_num < 1) // 源节点个数不对 + return 1; + last_node = OriginalNode[src_num - 1]; + if (last_node > node_num) // 判断最后一个节点号是否在范围内 + return 1; + for (i = 0; i < node_num; i++) { + // if((Mtrans[last_node][i]>0)&&(Mtrans[last_node][i] 0) // 寻找相同的节点 + { + nextNodes[nextNode_num] = i; + nextNode_num++; + } + } + // 如果一条路的最后一个节点就是目标节点,说明此路径是所有路径中的一条,可以直接return + if (last_node == destination) { + if (entityMtrans.getPath_num() >= FinalData.MAX_PATH_NUM) + return 1; + for (i = 0; i < src_num; i++) + entityMtrans.getPossiable_path()[entityMtrans.getPath_num()][i] = OriginalNode[i]; + entityMtrans.getPossiable_path()[entityMtrans.getPath_num()][FinalData.NODE_NUM] = Weight; // 最后一个节点填入变压器连接 + entityMtrans.setPath_num(entityMtrans.getPath_num() + 1); + } else { + for (i = 0; i < src_num; i++) { + if (destination == OriginalNode[i]) + return 1; + } + } + // 判断下一个节点有没有目的节点 + for (i = 0; i < nextNode_num; i++) { + if (nextNodes[i] == destination) { + // 先清零; + for (j = 0; j < (FinalData.NODE_NUM + 1); j++) + tmpPath[j] = 0; + // 填入源节点 + for (j = 0; j < src_num; j++) + tmpPath[j] = OriginalNode[j]; + tmpPath[src_num] = destination; // 目的节点加在后面 + tmpPath[FinalData.NODE_NUM] = Weight + entityMtrans.getMtrans()[last_node][destination]; // 最后一个点填入变压器累计 + tmpPath_num = src_num + 1; + if (entityMtrans.getPath_num() >= FinalData.MAX_PATH_NUM) + return 1; + for (j = 0; j < (FinalData.NODE_NUM + 1); j++) + entityMtrans.getPossiable_path()[entityMtrans.getPath_num()][j] = tmpPath[j]; // tmpPath为路径的路阻 + entityMtrans.setPath_num(entityMtrans.getPath_num() + 1); + nextNodes[i] = 0; + if (nextNode_num != 0) // if(nextNode_num) + nextNode_num--; + } else { + // 判断如果源节点中有下一个节点,不再寻找处理 + for (j = 0; j < src_num; j++) { + if (nextNodes[i] == OriginalNode[j]) { + nextNodes[i] = 0; + } + } + } + } + // 不是目的节点的下一节点继续寻找 + for (i = 0; i < nextNode_num; i++) { + if (nextNodes[i] != 0) { + nextNodes0[nextNode_num0] = nextNodes[i]; + nextNode_num0++; + } + } + for (i = 0; i < nextNode_num0; i++) { + // 填入源节点 + for (j = 0; j < src_num; j++) + tmpPath[j] = OriginalNode[j]; + tmpPath[src_num] = nextNodes0[i]; // 下一个节点加在后面 + tmpPath_num = src_num + 1; + findPath(entityMtrans, tmpPath, destination, (Weight + entityMtrans.getMtrans()[last_node][nextNodes0[i]]), tmpPath_num, + node_num); + } + return 0; + } + + public static int sort_Tstart(EntityGroupData buf) { + int res_num, out_num; + int idx = 0; + if ((buf == null) || (buf.getEvt_in_num() == 0)) + return 0; + res_num = buf.getEvt_in_num(); + while (res_num > 0) { // while(res_num) + out_num = sort_Tstart_single(buf); + // 输出缓冲填入归集缓冲 + // buf.getGrp_buf()[idx] = buf.getOut_buf(); + System.arraycopy(buf.getOut_buf(), 0, buf.getGrp_buf()[idx], 0, buf.getOut_buf().length); + buf.getGrp_num()[idx] = out_num; + // 未归集填入输入缓冲 + // buf.setIn_buf(buf.getRes_buf()); + System.arraycopy(buf.getRes_buf(), 0, buf.getIn_buf(), 0, buf.getRes_buf().length); + buf.setEvt_in_num(buf.getEvt_res_num()); + idx++; + if (idx >= FinalData.MAX_GROUP_NUM) // 分组超限 + break; + if (out_num <= res_num) + res_num = res_num - out_num; + else + break; // 分组数目超限 + } + buf.setGrp_all_num(idx); + return 1; + } + + public static int sort_Tstart_single(EntityGroupData buf) { + int i; + int start_time; + int thd_time1, thd_time2; + if ((buf == null) || (buf.getEvt_in_num() == 0)) + return 0; + buf.setEvt_out_num(0); + buf.setEvt_res_num(0); + // 如果只有一个事件直接赋值返回 + if (buf.getEvt_in_num() == 1) { + buf.setEvt_out_num(1); + // buf.getOut_buf()[0] = buf.getIn_buf()[0]; + // System.arraycopy(buf.getIn_buf()[0], 0, buf.getOut_buf()[0], 0, + // 1); + buf.getOut_buf()[0] = (EntityGroupEvtData) buf.getIn_buf()[0].objClone(); + return buf.getEvt_out_num(); + } + start_time = buf.getIn_buf()[0].getStart_time(); + thd_time1 = start_time - FinalData.TIME_THRESHOLD; + thd_time2 = start_time + FinalData.TIME_THRESHOLD; + // 判断时标阀值门槛归集 + for (i = 0; i < buf.getEvt_in_num(); i++) { + start_time = buf.getIn_buf()[i].getStart_time(); + // 在阈值范围内 + if ((start_time >= thd_time1) && (start_time <= thd_time2)) { + // buf.getOut_buf()[buf.getEvt_out_num()] = buf.getIn_buf()[i]; + // System.arraycopy(buf.getIn_buf()[i], 0, + // buf.getOut_buf()[buf.getEvt_out_num()], 0, 1); + buf.getOut_buf()[buf.getEvt_out_num()] = (EntityGroupEvtData) buf.getIn_buf()[i].objClone(); + buf.setEvt_out_num(buf.getEvt_out_num() + 1); + } else { + // buf.getRes_buf()[buf.getEvt_res_num()] = buf.getIn_buf()[i]; + // System.arraycopy(buf.getIn_buf()[i], 0, + // buf.getRes_buf()[buf.getEvt_res_num()], 0, 1); + buf.getRes_buf()[buf.getEvt_res_num()] = (EntityGroupEvtData) buf.getIn_buf()[i].objClone(); + buf.setEvt_res_num(buf.getEvt_res_num() + 1); + } + } + return buf.getEvt_out_num(); + } + + public static int sort_cata(EntityGroupData buf, int idx) { + int i, j; + int cata, node; + int odrer[] = new int[FinalData.MAX_CATA_NUM + 2]; + // 针对类别是1-6的数据进行模式匹配,并标注属于哪一个模式 + + for (i = 0; i < (FinalData.MAX_CATA_NUM + 2); i++) + odrer[i] = 0; + // 暂降类型转换 + // 将类型7,8,9转换为6,2,4 + // 其中7,8,9分别对应BC两相接地,AC两相接地,AB两相接地,1,2,3,4,5,6分别对应Dc,Cb,Da,Cc,Db,Ca + /* + * for (i = 0; i < buf.getGrp_num()[idx]; i++) { if + * (buf.getGrp_buf()[idx][i].getCata() == 7) + * buf.getGrp_buf()[idx][i].setCata(6); if + * (buf.getGrp_buf()[idx][i].getCata() == 8) + * buf.getGrp_buf()[idx][i].setCata(2); if + * (buf.getGrp_buf()[idx][i].getCata() == 9) + * buf.getGrp_buf()[idx][i].setCata(4); } + */ + for (i = 0; i < buf.getGrp_num()[idx]; i++) { + /* + * if (buf.getGrp_buf()[idx][i].getCata() == 10) //事件类型未知 + * buf.getGrp_buf()[idx][i].setCata(11); if + * (buf.getGrp_buf()[idx][i].getCata() == 9) //三相 + * buf.getGrp_buf()[idx][i].setCata(10); + */ + + if (buf.getGrp_buf()[idx][i].getCata() == 0) + buf.getGrp_buf()[idx][i].setCata(6); + + if (buf.getGrp_buf()[idx][i].getCata() == 6) + buf.getGrp_buf()[idx][i].setCata(6); + if (buf.getGrp_buf()[idx][i].getCata() == 7) + buf.getGrp_buf()[idx][i].setCata(2); + if (buf.getGrp_buf()[idx][i].getCata() == 8) + buf.getGrp_buf()[idx][i].setCata(4); + } + + // 将数据进行模式匹配,并标注属于哪一个模式 + for (i = 0; i < buf.getGrp_num()[idx]; i++) { + cata = buf.getGrp_buf()[idx][i].getCata(); + node = buf.getGrp_buf()[idx][i].getNode(); + + if ((node > FinalData.NODE_NUM) || (buf.getMatrixcata()[0][node - 1] == FinalData.DATA_INF)) { + buf.getGrp_buf()[idx][i].setCata2(FinalData.QVVR_TYPE_OUTOFRANGE); + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM + + // 1][odrer[FinalData.MAX_CATA_NUM + 1]] = + // buf.getGrp_buf()[idx][i]; + // System.arraycopy(buf.getGrp_buf()[idx][i], 0, + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM + + // 1][odrer[FinalData.MAX_CATA_NUM + 1]], 0, 1); + buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM + 1][odrer[FinalData.MAX_CATA_NUM + + 1]] = (EntityGroupEvtData) buf.getGrp_buf()[idx][i].objClone(); + odrer[FinalData.MAX_CATA_NUM + 1]++; + } else if (cata == FinalData.QVVR_TYPE_UNKNOWN) { + buf.getGrp_buf()[idx][i].setCata2(FinalData.QVVR_TYPE_UNKNOWN); + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM][odrer[FinalData.MAX_CATA_NUM]] + // = buf.getGrp_buf()[idx][i]; + // System.arraycopy(buf.getGrp_buf()[idx][i], 0, + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM][odrer[FinalData.MAX_CATA_NUM]], + // 0, 1); + buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM][odrer[FinalData.MAX_CATA_NUM]] = (EntityGroupEvtData) buf + .getGrp_buf()[idx][i].objClone(); + odrer[FinalData.MAX_CATA_NUM]++; + } else if (cata == FinalData.QVVR_TYPE_THREE) // ÈıÏàÔݽµ¹éÀà + { + buf.getGrp_buf()[idx][i].setCata2(FinalData.QVVR_TYPE_THREE); + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM - + // 1][odrer[FinalData.MAX_CATA_NUM - 1]] = + // buf.getGrp_buf()[idx][i]; + // System.arraycopy(buf.getGrp_buf()[idx][i], 0, + // buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM - + // 1][odrer[FinalData.MAX_CATA_NUM - 1]], 0, 1); + buf.getGrp_cata_buf()[idx][FinalData.MAX_CATA_NUM - 1][odrer[FinalData.MAX_CATA_NUM + - 1]] = (EntityGroupEvtData) buf.getGrp_buf()[idx][i].objClone(); + odrer[FinalData.MAX_CATA_NUM - 1]++; + } else // 1-6类暂降归类 + { + for (j = 0; j < FinalData.MAX_CATA_NUM; j++) { + if (cata == buf.getMatrixcata()[j][node - 1])// 判断数据类别属于第几行 + { + buf.getGrp_buf()[idx][i].setCata2(j + 1); + // 进行归类 + // buf.getGrp_cata_buf()[idx][j][odrer[j]] = + // buf.getGrp_buf()[idx][i]; + // System.arraycopy(buf.getGrp_buf()[idx][i], 0, + // buf.getGrp_cata_buf()[idx][j][odrer[j]], 0, 1); + buf.getGrp_cata_buf()[idx][j][odrer[j]] = (EntityGroupEvtData) buf.getGrp_buf()[idx][i] + .objClone(); + odrer[j]++; + } + } + } + } + for (i = 0; i < FinalData.MAX_CATA_NUM + 2; i++) + buf.getGrp_cata_num()[idx][i] = odrer[i]; + return 0; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/controller/HarmonicUpController.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/controller/HarmonicUpController.java new file mode 100644 index 0000000..2c0825f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/controller/HarmonicUpController.java @@ -0,0 +1,91 @@ +package com.njcn.product.advance.harmonicUp.controller; + +import cn.hutool.core.util.StrUtil; +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; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail; +import com.njcn.product.advance.harmonicUp.pojo.vo.UpTableInfo; +import com.njcn.product.advance.harmonicUp.service.HarmonicUpService; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @Author: cdf + * @CreateTime: 2025-09-12 + * @Description: + */ +@Slf4j +@RestController +@RequestMapping("harmonicUp") +@Api(tags = "谐波放大") +@RequiredArgsConstructor +public class HarmonicUpController extends BaseController { + + private final HarmonicUpService harmonicUpService; + + @GetMapping("analyzePreData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("谐波放大算法预处理") + public HttpResult analyzePreData(@RequestParam("date")String date) { + String methodDescribe = getMethodDescribe("analyzePreData"); + harmonicUpService.analyzePreData(date); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + @PostMapping("getDetail") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("获取监测点谐波放大详情") + public HttpResult> getDetail(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("getDetail"); + checkParam(param); + Page result = harmonicUpService.getDetail(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @PostMapping("getInfoList") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("谐波放大实时数据列表") + public HttpResult> getInfoList(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("getInfoList"); + Page result = harmonicUpService.getInfoList(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @PostMapping("tableInfo") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("谐波放大热力图") + public HttpResult tableInfo(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("tableInfo"); + UpTableInfo result = harmonicUpService.tableInfo(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + + private void checkParam(LargeScreenCountParam param){ + if(StrUtil.isBlank(param.getSearchBeginTime())){ + throw new BusinessException(CommonResponseEnum.FAIL,"时间不可为空!"); + } + if(StrUtil.isBlank(param.getLineId())){ + throw new BusinessException(CommonResponseEnum.FAIL,"监测点id不可为空!"); + } + /* if(StrUtil.isBlank(param.getDeptId())){ + throw new BusinessException(CommonResponseEnum.FAIL,"部门id不可为空!"); + }*/ + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataIUpToMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataIUpToMapper.java new file mode 100644 index 0000000..91b6969 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataIUpToMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.advance.harmonicUp.imapper; + +import com.njcn.influx.base.InfluxDbBaseMapper; +import com.njcn.product.advance.harmonicUp.pojo.po.DataIUp; + + +/** + * @author hongawen + * @version 1.0 + * @data 2024/11/7 18:49 + */ +public interface DataIUpToMapper extends InfluxDbBaseMapper { + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataVUpToMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataVUpToMapper.java new file mode 100644 index 0000000..2d4b616 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/imapper/DataVUpToMapper.java @@ -0,0 +1,18 @@ +package com.njcn.product.advance.harmonicUp.imapper; + + +import com.njcn.influx.base.InfluxDbBaseMapper; +import com.njcn.product.advance.harmonicUp.pojo.po.DataVUp; + +/** + * @author hongawen + * @version 1.0 + * @data 2024/11/7 18:49 + */ +public interface DataVUpToMapper extends InfluxDbBaseMapper { + + + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/mapper/UpHarmonicDetailMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/mapper/UpHarmonicDetailMapper.java new file mode 100644 index 0000000..d8c7a24 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/mapper/UpHarmonicDetailMapper.java @@ -0,0 +1,22 @@ +package com.njcn.product.advance.harmonicUp.mapper; + +/** + * @Author: cdf + * @CreateTime: 2025-09-12 + * @Description: + */ + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail; + +/** + *

+ * 谐波放大详情表 Mapper 接口 + *

+ * + * @author + * @since 2025-09-12 + */ +public interface UpHarmonicDetailMapper extends BaseMapper { + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/param/HistoryParam.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/param/HistoryParam.java new file mode 100644 index 0000000..370e611 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/param/HistoryParam.java @@ -0,0 +1,45 @@ +package com.njcn.product.advance.harmonicUp.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.advance.eventSource.pojo.constant.HarmonicValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +/** + * @author denghuajun + * @date 2022/3/11 + * + */ +@Data +public class HistoryParam { + @ApiModelProperty("开始时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + private String searchEndTime; + + @ApiModelProperty("监测点id集合") + private String[] lineId; + + @ApiModelProperty("指标集合") + private String[] condition; + + @ApiModelProperty("谐波次数") + private Integer harmonic; + + @ApiModelProperty("间谐波次数") + private Integer inHarmonic; + + @ApiModelProperty("类型(1-平均值;2-最小值;3-最大值;4-CP95值)") + private Integer valueType; + + @ApiModelProperty("接线方式") + @NotNull(message = "接线方式不可为空") + private Integer ptType; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataIUp.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataIUp.java new file mode 100644 index 0000000..46f421e --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataIUp.java @@ -0,0 +1,194 @@ +package com.njcn.product.advance.harmonicUp.pojo.po; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.njcn.influx.utils.InstantDateSerializer; +import lombok.Data; +import org.influxdb.annotation.Column; +import org.influxdb.annotation.Measurement; +import org.influxdb.annotation.TimeColumn; + +import java.time.Instant; + + +/** + * 类的介绍: + * + */ +@Data +@Measurement(name = "data_i_up") +public class DataIUp { + + @Column(name = "time",tag =true) + @JsonSerialize(using = InstantDateSerializer.class) + @TimeColumn + private Instant time; + + @Column(name = "line_id",tag = true) + private String lineId; + + @Column(name = "phasic_type",tag = true) + private String phasicType; + + @Column(name = "quality_flag",tag = true) + private String qualityFlag="0"; + + @Column(name = "value_type",tag = true) + private String valueType; + + //是否是异常指标数据,0否1是 + @Column(name = "abnormal_flag") + private Integer abnormalFlag; + + + @Column(name = "i_1") + private Double i1; + + @Column(name = "i_2") + private Double i2; + + @Column(name = "i_3") + private Double i3; + + @Column(name = "i_4") + private Double i4; + + @Column(name = "i_5") + private Double i5; + + @Column(name = "i_6") + private Double i6; + + @Column(name = "i_7") + private Double i7; + + @Column(name = "i_8") + private Double i8; + + @Column(name = "i_9") + private Double i9; + + @Column(name = "i_10") + private Double i10; + + @Column(name = "i_11") + private Double i11; + + @Column(name = "i_12") + private Double i12; + + @Column(name = "i_13") + private Double i13; + + @Column(name = "i_14") + private Double i14; + + @Column(name = "i_15") + private Double i15; + + @Column(name = "i_16") + private Double i16; + + @Column(name = "i_17") + private Double i17; + + @Column(name = "i_18") + private Double i18; + + @Column(name = "i_19") + private Double i19; + + @Column(name = "i_20") + private Double i20; + + @Column(name = "i_21") + private Double i21; + + @Column(name = "i_22") + private Double i22; + + @Column(name = "i_23") + private Double i23; + + @Column(name = "i_24") + private Double i24; + + @Column(name = "i_25") + private Double i25; + + @Column(name = "i_26") + private Double i26; + + @Column(name = "i_27") + private Double i27; + + @Column(name = "i_28") + private Double i28; + + @Column(name = "i_29") + private Double i29; + + @Column(name = "i_30") + private Double i30; + + @Column(name = "i_31") + private Double i31; + + @Column(name = "i_32") + private Double i32; + + @Column(name = "i_33") + private Double i33; + + @Column(name = "i_34") + private Double i34; + + @Column(name = "i_35") + private Double i35; + + @Column(name = "i_36") + private Double i36; + + @Column(name = "i_37") + private Double i37; + + @Column(name = "i_38") + private Double i38; + + @Column(name = "i_39") + private Double i39; + + @Column(name = "i_40") + private Double i40; + + @Column(name = "i_41") + private Double i41; + + @Column(name = "i_42") + private Double i42; + + @Column(name = "i_43") + private Double i43; + + @Column(name = "i_44") + private Double i44; + + @Column(name = "i_45") + private Double i45; + + @Column(name = "i_46") + private Double i46; + + @Column(name = "i_47") + private Double i47; + + @Column(name = "i_48") + private Double i48; + + @Column(name = "i_49") + private Double i49; + + @Column(name = "i_50") + private Double i50; + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataVUp.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataVUp.java new file mode 100644 index 0000000..50530c1 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/DataVUp.java @@ -0,0 +1,200 @@ +package com.njcn.product.advance.harmonicUp.pojo.po; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.njcn.influx.utils.InstantDateSerializer; +import lombok.Data; +import org.influxdb.annotation.Column; +import org.influxdb.annotation.Measurement; +import org.influxdb.annotation.TimeColumn; +import org.springframework.beans.BeanUtils; + +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 类的介绍: + * + */ +@Data +@Measurement(name = "data_v_up") +public class DataVUp { + + @TimeColumn + @Column(name = "time", tag = true) + @JsonSerialize(using = InstantDateSerializer.class) + private Instant time; + + @Column(name = "line_id", tag = true) + private String lineId; + + @Column(name = "phasic_type", tag = true) + private String phasicType; + + @Column(name = "value_type", tag = true) + private String valueType; + + @Column(name = "quality_flag", tag = true) + private String qualityFlag="0"; + + //是否是异常指标数据,0否1是 + @Column(name = "abnormal_flag") + private Integer abnormalFlag; + + @Column(name = "v_1") + private Double v1; + + @Column(name = "v_2") + private Double v2; + + @Column(name = "v_3") + private Double v3; + + @Column(name = "v_4") + private Double v4; + + @Column(name = "v_5") + private Double v5; + + @Column(name = "v_6") + private Double v6; + + @Column(name = "v_7") + private Double v7; + + @Column(name = "v_8") + private Double v8; + + @Column(name = "v_9") + private Double v9; + + @Column(name = "v_10") + private Double v10; + + @Column(name = "v_11") + private Double v11; + + @Column(name = "v_12") + private Double v12; + + @Column(name = "v_13") + private Double v13; + + @Column(name = "v_14") + private Double v14; + + @Column(name = "v_15") + private Double v15; + + @Column(name = "v_16") + private Double v16; + + @Column(name = "v_17") + private Double v17; + + @Column(name = "v_18") + private Double v18; + + @Column(name = "v_19") + private Double v19; + + @Column(name = "v_20") + private Double v20; + + @Column(name = "v_21") + private Double v21; + + @Column(name = "v_22") + private Double v22; + + @Column(name = "v_23") + private Double v23; + + @Column(name = "v_24") + private Double v24; + + @Column(name = "v_25") + private Double v25; + + @Column(name = "v_26") + private Double v26; + + @Column(name = "v_27") + private Double v27; + + @Column(name = "v_28") + private Double v28; + + @Column(name = "v_29") + private Double v29; + + @Column(name = "v_30") + private Double v30; + + @Column(name = "v_31") + private Double v31; + + @Column(name = "v_32") + private Double v32; + + @Column(name = "v_33") + private Double v33; + + @Column(name = "v_34") + private Double v34; + + @Column(name = "v_35") + private Double v35; + + @Column(name = "v_36") + private Double v36; + + @Column(name = "v_37") + private Double v37; + + @Column(name = "v_38") + private Double v38; + + @Column(name = "v_39") + private Double v39; + + @Column(name = "v_40") + private Double v40; + + @Column(name = "v_41") + private Double v41; + + @Column(name = "v_42") + private Double v42; + + @Column(name = "v_43") + private Double v43; + + @Column(name = "v_44") + private Double v44; + + @Column(name = "v_45") + private Double v45; + + @Column(name = "v_46") + private Double v46; + + @Column(name = "v_47") + private Double v47; + + @Column(name = "v_48") + private Double v48; + + @Column(name = "v_49") + private Double v49; + + @Column(name = "v_50") + private Double v50; + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/UpHarmonicDetail.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/UpHarmonicDetail.java new file mode 100644 index 0000000..c540e1b --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/po/UpHarmonicDetail.java @@ -0,0 +1,110 @@ +package com.njcn.product.advance.harmonicUp.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-09-12 + * @Description: + */ + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * 谐波放大详情表 + *

+ * + * @author + * @since 2025-09-12 + */ +@Data +@TableName("up_harmonic_detail") +public class UpHarmonicDetail implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 事件id + */ + @TableField(value = "id") + private String id; + + /** + * 监测点id + */ + @TableField("monitor_id") + private String monitorId; + + /** + * 开始时间 + */ + @TableField("start_time") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime startTime; + + /** + * 结束时间 + */ + @TableField("end_time") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime endTime; + + /** + * 谐波放大持续时间s + */ + @TableField("duration") + private Double duration; + + /** + * 谐波次数 + */ + @TableField("harmonic_count") + private Integer harmonicCount; + + /** + * 相别 + */ + @TableField("phase") + private String phase; + + /** + * 电压标准值 + */ + @TableField("v_Avg_Value") + private Double vAvgValue; + + /** + * 电流标准值 + */ + + @TableField("i_Avg_Value") + private Double iAvgValue; + + @TableField("up_scheme") + private String upScheme; + + /** + * 创建时间 + */ + @TableField("create_time") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createTime; + + + @TableField(exist = false) + private String stationName; + @TableField(exist = false) + private String monitorName; + @TableField(exist = false) + private String objName; + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/HistoryDataResultVO.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/HistoryDataResultVO.java new file mode 100644 index 0000000..1509bf9 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/HistoryDataResultVO.java @@ -0,0 +1,55 @@ +package com.njcn.product.advance.harmonicUp.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * @author denghuajun + * @date 2022/3/11 + * + */ +@Data +public class HistoryDataResultVO implements Serializable { + + @ApiModelProperty("监测点名称") + private String lineName; + + @ApiModelProperty("指标名称") + private String targetName; + + @ApiModelProperty("相别") + private List phaiscType; + + @ApiModelProperty("单位") + private List unit; + + @ApiModelProperty("谐波次数") + private Integer harmNum; + + @ApiModelProperty("数值") + private List> value; + + @ApiModelProperty("最小值") + private Float minValue; + + + @ApiModelProperty("最大值") + private Float maxValue; + + @ApiModelProperty("上限") + private Float topLimit; + + @ApiModelProperty("下限") + private Float lowerLimit; + + @ApiModelProperty("接线方式 0.星型 1.星三角 2.三角") + private String wiringMethod; + + /* @ApiModelProperty("暂降事件详情") + private List eventDetail;*/ + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/QueryResultLimitVO.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/QueryResultLimitVO.java new file mode 100644 index 0000000..ddd3528 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/QueryResultLimitVO.java @@ -0,0 +1,30 @@ +package com.njcn.product.advance.harmonicUp.pojo.vo; + +import com.njcn.influx.pojo.bo.HarmonicHistoryData; +import lombok.Data; +import org.influxdb.dto.QueryResult; + +import java.io.Serializable; +import java.util.List; + +/** + * @author denghuajun + * @date 2022/3/15 + * 存值 + */ +@Data +public class QueryResultLimitVO implements Serializable { + private QueryResult queryResult; + private List harmonicHistoryDataList; + private Float topLimit; + private Float lowerLimit; + private String lineName; + private String targetName; + private List phaiscType; + private List unit; + private Integer harmNum; + /** + * 接线方式 0.星型 1.星三角 2.三角 + */ + private String wiringMethod; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/UpTableInfo.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/UpTableInfo.java new file mode 100644 index 0000000..31c19cb --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/pojo/vo/UpTableInfo.java @@ -0,0 +1,32 @@ +package com.njcn.product.advance.harmonicUp.pojo.vo; + +import lombok.Data; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-15 + * @Description: + */ +@Data +public class UpTableInfo { + + private List date; + + private List monitorList; + + private List inner; + + + @Data + public static class Inner{ + private String date; + + private String lineId; + + private String monitorName; + + private Integer count = 0; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HarmonicUpService.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HarmonicUpService.java new file mode 100644 index 0000000..cbeb32f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HarmonicUpService.java @@ -0,0 +1,28 @@ +package com.njcn.product.advance.harmonicUp.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail; +import com.njcn.product.advance.harmonicUp.pojo.vo.UpTableInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-11 + * @Description: 谐波放大 + */ +public interface HarmonicUpService extends IService { + + void analyzePreData(String date); + + Page getDetail(LargeScreenCountParam param); + + Page getInfoList(LargeScreenCountParam param); + + + UpTableInfo tableInfo(LargeScreenCountParam param); + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HistoryResultService.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HistoryResultService.java new file mode 100644 index 0000000..5205435 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/HistoryResultService.java @@ -0,0 +1,27 @@ +package com.njcn.product.advance.harmonicUp.service; + +import com.njcn.common.pojo.param.StatisticsBizBaseParam; + +import com.njcn.influx.pojo.dto.HarmHistoryDataDTO; +import com.njcn.product.advance.harmonicUp.pojo.param.HistoryParam; +import com.njcn.product.advance.harmonicUp.pojo.vo.HistoryDataResultVO; + +import java.util.List; + +/** + * 稳态数据 + * @author denghuajun + * @date 2022/3/14 + * + */ +public interface HistoryResultService { + + /** + * 稳态数据分析 + * @param historyParam 参数 + * @return 结果 + */ + List getHistoryResult(HistoryParam historyParam); + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HarmonicUpServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HarmonicUpServiceImpl.java new file mode 100644 index 0000000..64222c0 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HarmonicUpServiceImpl.java @@ -0,0 +1,719 @@ +package com.njcn.product.advance.harmonicUp.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.*; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.IdWorker; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.influx.imapper.DataIMapper; +import com.njcn.influx.imapper.DataVMapper; +import com.njcn.influx.pojo.constant.InfluxDBTableConstant; +import com.njcn.influx.pojo.po.DataI; +import com.njcn.influx.pojo.po.DataV; +import com.njcn.influx.query.InfluxQueryWrapper; +import com.njcn.product.advance.harmonicUp.imapper.DataIUpToMapper; +import com.njcn.product.advance.harmonicUp.imapper.DataVUpToMapper; +import com.njcn.product.advance.harmonicUp.mapper.UpHarmonicDetailMapper; +import com.njcn.product.advance.harmonicUp.pojo.po.DataIUp; +import com.njcn.product.advance.harmonicUp.pojo.po.DataVUp; +import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail; +import com.njcn.product.advance.harmonicUp.pojo.vo.UpTableInfo; +import com.njcn.product.advance.harmonicUp.service.HarmonicUpService; +import com.njcn.product.terminal.mysqlTerminal.mapper.LedgerScaleMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.product.terminal.mysqlTerminal.service.CommGeneralService; +import com.njcn.web.factory.PageFactory; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @Author: cdf + * @CreateTime: 2025-09-11 + * @Description: + */ +/** + * @Author: cdf + * @CreateTime: 2025-09-11 + * @Description: 谐波分析服务实现类,仅使用up_harmonic_detail表存储事件信息 + */ +@Service +@EnableScheduling +@RequiredArgsConstructor +@Slf4j +public class HarmonicUpServiceImpl extends ServiceImpl implements HarmonicUpService { + + private final DataVMapper dataVMapper; + private final DataIMapper dataIMapper; + private final DataVUpToMapper dataVUpToMapper; + private final DataIUpToMapper dataIUpToMapper; + private final CommGeneralService commGeneralService; + private final LedgerScaleMapper ledgerScaleMapper; + + // 常量定义 + final String DAY_FORMAT = DatePattern.NORM_DATE_PATTERN; + final String MONTH_FORMAT = DatePattern.NORM_MONTH_PATTERN; + + // 配置参数 + @Value("${harmonic.voltage.change.rate.threshold:0.20}") + private Double voltageChangeRateThreshold; + + //电流 + @Value("${harmonic.current.change.rate.threshold:0.10}") + private Double currentChangeRateThreshold; + + @Value("${harmonic.continuous.anomaly.count:10}") + private Integer continuousAnomalyCount; + + // 需要分析的特定谐波次数,可根据需求扩展 + private List specificHarmonicOrders = Arrays.asList(3, 5, 7, 11, 13); + + /** + * 每日凌晨2点执行谐波分析(分析前一天的数据) + */ + @Scheduled(cron = "0 0 2 * * ?") + public void dailyHarmonicAnalysis() { + analyzePreData(""); + } + + @Override + public void analyzePreData(String date) { + log.info("开始执行谐波分析,日期: {}", date); + + Map> avgVMap = new HashMap<>(); + Map> avgIMap = new HashMap<>(); + + // 计算并保存电压和电流变化率数据 + List dataVUpList = calculateAndSaveDataVUp(date,avgVMap); + List dataIUpList = calculateAndSaveDataIUp(date,avgIMap); + + // 分析谐波放大事件并直接保存到up_harmonic_detail表 + analyzeAndSaveHarmonicEvents(dataVUpList, dataIUpList,avgVMap,avgIMap); + + log.info("谐波分析执行完成,日期: {}", date); + } + + @Override + public Page getDetail(LargeScreenCountParam param) { + Page resultPage = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)); + DateTime date; + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + + try { + date = DateUtil.parse(param.getSearchBeginTime(),DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)); + lambdaQueryWrapper.between(UpHarmonicDetail::getStartTime,DateUtil.beginOfDay(date),DateUtil.endOfDay(date)); + + }catch (Exception e){ + date = DateUtil.parse(param.getSearchBeginTime(),DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN)); + lambdaQueryWrapper.between(UpHarmonicDetail::getStartTime,DateUtil.beginOfMonth(date),DateUtil.endOfMonth(date)); + } + lambdaQueryWrapper.eq(UpHarmonicDetail::getMonitorId,param.getLineId()).orderByAsc(UpHarmonicDetail::getHarmonicCount,UpHarmonicDetail::getPhase,UpHarmonicDetail::getStartTime); + Page result = this.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),lambdaQueryWrapper); + if(CollUtil.isEmpty(result.getRecords())){ + return resultPage; + } + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(Stream.of(param.getLineId()).collect(Collectors.toList())); + if(CollUtil.isEmpty(ledgerBaseInfoList)){ + throw new BusinessException(CommonResponseEnum.FAIL,"查询台账为空"); + } + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoList.get(0); + result.getRecords().forEach(it->{ + it.setMonitorName(ledgerBaseInfo.getLineName()); + it.setStationName(ledgerBaseInfo.getStationName()); + it.setObjName(ledgerBaseInfo.getObjName()); + it.setVAvgValue(BigDecimal.valueOf(it.getVAvgValue()*1000).setScale(2,RoundingMode.HALF_UP).doubleValue()); + + }); + return result; + } + + @Override + public Page getInfoList(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)); + + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + List lineIds = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if(CollUtil.isEmpty(lineIds)){ + return result; + } + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.between(UpHarmonicDetail::getStartTime,start,end) + .in(UpHarmonicDetail::getMonitorId,lineIds).orderByDesc(UpHarmonicDetail::getStartTime); + result = this.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),lambdaQueryWrapper); + if(CollUtil.isEmpty(result.getRecords())){ + return result; + } + List ids = result.getRecords().stream().map(UpHarmonicDetail::getMonitorId).distinct().collect(Collectors.toList()); + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(ids); + if(CollUtil.isEmpty(ledgerBaseInfoList)){ + throw new BusinessException(CommonResponseEnum.FAIL,"查询台账为空"); + } + Map ledgerBaseInfoMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId,line->line)); + result.getRecords().forEach(it->{ + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(it.getMonitorId()); + it.setMonitorName(ledgerBaseInfo.getLineName()); + it.setStationName(ledgerBaseInfo.getStationName()); + it.setObjName(ledgerBaseInfo.getObjName()); + it.setVAvgValue(BigDecimal.valueOf(it.getVAvgValue()*1000).setScale(2,RoundingMode.HALF_UP).doubleValue()); + }); + return result; + } + + @Override + public UpTableInfo tableInfo(LargeScreenCountParam param) { + // 初始化结果对象 + UpTableInfo result = new UpTableInfo(); + List dateList = new ArrayList<>(); + List innerList = new ArrayList<>(); + + // 1. 获取线路ID和台账基础信息 + List lineIds = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(lineIds); + + if (CollUtil.isEmpty(ledgerBaseInfoList)) { + throw new BusinessException(CommonResponseEnum.FAIL, "查询台账为空"); + } + + // 2. 构建线路ID到名称的映射 & 提取线路名称列表 + Map ledgerBaseInfoMap = ledgerBaseInfoList.stream() + .collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity())); + List ledgerList = ledgerBaseInfoList.stream().map(it-> { + if(StrUtil.isBlank(it.getObjName())){ + return it.getLineName(); + } + return strTranslate(it.getObjName()); + + }).collect(Collectors.toList()); + + // 3. 处理日期范围 + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + long dayDiff = DateUtil.betweenDay(start, end, false); + + // 确定日期范围和格式 + DateRange dateRange; + String dateFormat; + if (dayDiff <= 31) { + dateRange = DateUtil.range(start, end, DateField.DAY_OF_MONTH); + dateFormat = DAY_FORMAT; + } else { + dateRange = DateUtil.range(start, end, DateField.MONTH); + dateFormat = MONTH_FORMAT; + } + + // 4. 查询数据 + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.between(UpHarmonicDetail::getStartTime, start, end) + .in(UpHarmonicDetail::getMonitorId, lineIds) + .orderByDesc(UpHarmonicDetail::getStartTime); + List data = this.list(queryWrapper); + + // 5. 处理数据(分空数据和非空数据情况) + if (CollUtil.isEmpty(data)) { + // 无数据时填充默认值 + fillDefaultData(dateRange, dateFormat, ledgerBaseInfoList, dateList, innerList); + } else { + // 有数据时按日期和线路分组统计 + processExistingData(dateRange, dateFormat, ledgerBaseInfoMap, data, dateList, innerList); + } + + // 6. 设置结果 + result.setDate(dateList); + result.setMonitorList(ledgerList); + result.setInner(innerList); + return result; + } + + /** + * 填充默认数据(当查询结果为空时) + */ + private void fillDefaultData(DateRange dateRange, String dateFormat, + List ledgerList, List dateList, + List innerList) { + for (DateTime range : dateRange) { + String time = DateUtil.format(range, dateFormat); + dateList.add(time); + + ledgerList.forEach(line -> { + UpTableInfo.Inner inner = new UpTableInfo.Inner(); + inner.setDate(time); + inner.setMonitorName(StrUtil.isNotBlank(line.getObjName())?strTranslate(line.getObjName()):line.getLineName()); + inner.setLineId(line.getLineId()); + inner.setCount(0); + innerList.add(inner); + }); + } + } + + /** + * 处理查询到的数据 + */ + private void processExistingData(DateRange dateRange, String dateFormat, + Map ledgerBaseInfoMap, + List data, + List dateList, + List innerList) { + // 按监控ID分组 + Map> upMonitorMap = data.stream() + .collect(Collectors.groupingBy(UpHarmonicDetail::getMonitorId)); + + Map temMap = ObjectUtil.cloneByStream(ledgerBaseInfoMap); + + for (DateTime range : dateRange) { + String time = DateUtil.format(range, dateFormat); + dateList.add(time); + + upMonitorMap.forEach((lineKey, details) -> { + temMap.remove(lineKey); + UpTableInfo.Inner inner = new UpTableInfo.Inner(); + inner.setDate(time); + if(ledgerBaseInfoMap.containsKey(lineKey)){ + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(lineKey); + inner.setMonitorName(StrUtil.isNotBlank(ledgerBaseInfo.getObjName())?strTranslate(ledgerBaseInfo.getObjName()):ledgerBaseInfo.getLineName()); + inner.setLineId(ledgerBaseInfo.getLineId()); + } + // 统计当前日期下的记录数 + long count = details.stream() + .filter(detail -> DateUtil.format(detail.getStartTime(),dateFormat).equals(time)) + .count(); + inner.setCount((int) count); + innerList.add(inner); + }); + + //针对未发生谐波放大的测点 + temMap.forEach((k,v)->{ + UpTableInfo.Inner inner = new UpTableInfo.Inner(); + inner.setDate(time); + inner.setMonitorName(StrUtil.isNotBlank(v.getObjName())?strTranslate(v.getObjName()):v.getLineName()); + inner.setLineId(v.getLineId()); + inner.setCount(0); + innerList.add(inner); + }); + } + } + + + private String strTranslate(String str){ + return str.replace("无锡市", "").replace("无锡", ""); + } + + + /** + * 计算并保存电压变化率数据 + */ + private List calculateAndSaveDataVUp(String date,Map> avgVMap) { + InfluxQueryWrapper influxQueryWrapperV = new InfluxQueryWrapper(DataV.class); + influxQueryWrapperV.between(DataV::getTime, date.concat(InfluxDBTableConstant.START_TIME), date.concat(InfluxDBTableConstant.END_TIME)) + .eq(DataV::getValueType, InfluxDBTableConstant.CP95) + .ne(DataV::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T); + + List dataVList = dataVMapper.selectByQueryWrapper(influxQueryWrapperV); + if(CollUtil.isEmpty(dataVList)){ + log.error("data_v谐波放大算法查询原始数据为空!"); + } + Map> lineVMap = dataVList.stream() + .collect(Collectors.groupingBy(DataV::getLineId)); + + List dataVUpList = new ArrayList<>(); + lineVMap.forEach((lineId, list) -> { + // 计算所有字段的平均值(V1-V50) + Map avgMap = calculateFieldAveragesV(list, 50); + avgVMap.put(lineId,avgMap); + // 按相别分组处理 + Map> phaseList = list.stream() + .collect(Collectors.groupingBy(DataV::getPhaseType)); + + phaseList.forEach((phase, pList) -> { + pList.forEach(dataV -> { + DataVUp dataVUp = new DataVUp(); + dataVUp.setPhasicType(phase); + dataVUp.setTime(dataV.getTime()); + dataVUp.setLineId(dataV.getLineId()); + dataVUp.setValueType(dataV.getValueType()); + + // 动态设置 V1-V50 的相对变化率 + avgMap.forEach((field, avg) -> { + try { + // 获取 DataV 的当前字段值 + Method getter = DataV.class.getMethod("get" + field); + double value = (double) getter.invoke(dataV); + + // 计算相对变化率 + double relativeChange = (avg == 0) ? 0 : + BigDecimal.valueOf((value - avg) / avg) + .setScale(6, RoundingMode.HALF_UP) + .doubleValue(); + + // 设置到 DataVUp + Method setter = DataVUp.class.getMethod("set" + field, Double.class); + setter.invoke(dataVUp, relativeChange); + + // 判断是否为异常值 + if (specificHarmonicOrders.contains(getHarmonicOrderFromField(field)) + && relativeChange > voltageChangeRateThreshold) { + dataVUp.setAbnormalFlag(1); + } else if (dataVUp.getAbnormalFlag() == null) { + dataVUp.setAbnormalFlag(0); + } + } catch (NoSuchMethodException e) { + log.error("字段 {} 的 getter/setter 方法不存在", field, e); + } catch (Exception e) { + log.error("反射调用字段 {} 失败: {}", field, e.getMessage(), e); + } + }); + dataVUpList.add(dataVUp); + }); + }); + }); + + if(CollUtil.isNotEmpty(dataVUpList)) { + List result = dataVUpList.stream() + .sorted(Comparator.comparing(DataVUp::getTime).thenComparing(DataVUp::getPhasicType)) + .collect(Collectors.toList()); + dataVUpToMapper.insertBatch(result); + } + + return dataVUpList; + } + + /** + * 计算并保存电流变化率数据 + */ + private List calculateAndSaveDataIUp(String date,Map> avgIMap) { + InfluxQueryWrapper influxQueryWrapperI = new InfluxQueryWrapper(DataI.class); + influxQueryWrapperI.between(DataI::getTime, date.concat(InfluxDBTableConstant.START_TIME), date.concat(InfluxDBTableConstant.END_TIME)) + .eq(DataI::getValueType, InfluxDBTableConstant.CP95) + .ne(DataI::getPhaseType, InfluxDBTableConstant.PHASE_TYPE_T); + + List dataIList = dataIMapper.selectByQueryWrapper(influxQueryWrapperI); + if(CollUtil.isEmpty(dataIList)){ + log.error("data_i谐波放大算法查询原始数据为空!"); + } + Map> lineIMap = dataIList.stream() + .collect(Collectors.groupingBy(DataI::getLineId)); + + List dataIUpList = new ArrayList<>(); + lineIMap.forEach((lineId, list) -> { + // 计算所有字段的平均值(I1-I50) + Map avgMap = calculateFieldAveragesI(list, 50); + avgIMap.put(lineId,avgMap); + + // 按相别分组处理 + Map> phaseList = list.stream() + .collect(Collectors.groupingBy(DataI::getPhaseType)); + + phaseList.forEach((phase, pList) -> { + pList.forEach(dataI -> { + DataIUp dataIUp = new DataIUp(); + dataIUp.setPhasicType(phase); + dataIUp.setTime(dataI.getTime()); + dataIUp.setLineId(dataI.getLineId()); + dataIUp.setValueType(dataI.getValueType()); + + // 动态设置 I1-I50 的相对变化率 + avgMap.forEach((field, avg) -> { + try { + // 获取 DataI 的当前字段值 + Method getter = DataI.class.getMethod("get" + field); + double value = (double) getter.invoke(dataI); + double relativeChange = 3.1415926; + if(value>0.01){ + // 计算相对变化率 + relativeChange = (avg == 0) ? 0 : + BigDecimal.valueOf(Math.abs(value - avg) / avg) + .setScale(6, RoundingMode.HALF_UP) + .doubleValue(); + } + + + + // 设置到 DataIUp + Method setter = DataIUp.class.getMethod("set" + field, Double.class); + setter.invoke(dataIUp, relativeChange); + } catch (NoSuchMethodException e) { + log.error("字段 {} 的 getter/setter 方法不存在", field, e); + } catch (Exception e) { + log.error("反射调用字段 {} 失败: {}", field, e.getMessage(), e); + } + + }); + dataIUpList.add(dataIUp); + + }); + }); + }); + + if(CollUtil.isNotEmpty(dataIUpList)) { + List result = dataIUpList.stream() + .sorted(Comparator.comparing(DataIUp::getTime).thenComparing(DataIUp::getPhasicType)) + .collect(Collectors.toList()); + dataIUpToMapper.insertBatch(result); + } + + return dataIUpList; + } + + /** + * 分析谐波放大事件并保存到up_harmonic_detail表 + */ + private void analyzeAndSaveHarmonicEvents(List dataVUpList, List dataIUpList,Map> avgVMap,Map> avgIMap) { + // 按线路、时间、相别分组电流数据,便于查询 + Map iUpMap = dataIUpList.stream() + .collect(Collectors.toMap( + item -> item.getLineId() + StrUtil.C_UNDERLINE + item.getTime() + StrUtil.C_UNDERLINE + item.getPhasicType(), + item -> item + )); + + // 存储所有异常点信息 + Map> anomalyMap = new HashMap<>(); + + // 遍历电压数据,检查异常点 + Set lineSet = new HashSet<>(); + for (DataVUp vUp : dataVUpList) { + lineSet.add(vUp.getLineId()); + String key = vUp.getLineId() + StrUtil.C_UNDERLINE + vUp.getTime() + StrUtil.C_UNDERLINE + vUp.getPhasicType(); + + // 检查是否有对应的电流数据 + if (!iUpMap.containsKey(key)) { + continue; + } + + DataIUp iUp = iUpMap.get(key); + // 检查每个特定谐波次数 + for (int order : specificHarmonicOrders) { + try { + // 获取电压变化率 + String vField = "v" + order; + Method vGetter = DataVUp.class.getMethod("get" + Character.toUpperCase(vField.charAt(0)) + vField.substring(1)); + double vChangeRate = (double) vGetter.invoke(vUp); + + // 获取电流变化率 + String iField = "i" + order; + Method iGetter = DataIUp.class.getMethod("get" + Character.toUpperCase(iField.charAt(0)) + iField.substring(1)); + double iChangeRate = (double) iGetter.invoke(iUp); + + // 检查是否满足异常条件 + if (vChangeRate > voltageChangeRateThreshold && iChangeRate < currentChangeRateThreshold && iChangeRate!=3.1415926) { + String anomalyKey = vUp.getLineId() + StrUtil.C_UNDERLINE + vUp.getPhasicType() + StrUtil.C_UNDERLINE + order; + + AnomalyInfo info = new AnomalyInfo(); + info.setLineId(vUp.getLineId()); + info.setPhase(vUp.getPhasicType()); + info.setHarmonicOrder(order); + info.setTime(vUp.getTime()); + info.setVoltageChangeRate(vChangeRate); + info.setCurrentChangeRate(iChangeRate); + + if (!anomalyMap.containsKey(anomalyKey)) { + anomalyMap.put(anomalyKey, new ArrayList<>()); + } + anomalyMap.get(anomalyKey).add(info); + } + } catch (Exception e) { + log.error("分析谐波次数 {} 时发生错误", order, e); + } + } + } + + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(new ArrayList<>(lineSet)); + Map ledgerBaseInfoMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId,Function.identity())); + + // 处理异常点,生成谐波放大事件 + List harmonicDetails = new ArrayList<>(); + + for (List anomalies : anomalyMap.values()) { + if (anomalies.size() < continuousAnomalyCount) { + continue; // 连续异常点数量不足,不生成事件 + } + + // 按时间排序 + List sortedAnomalies = anomalies.stream() + .sorted(Comparator.comparing(AnomalyInfo::getTime)) + .collect(Collectors.toList()); + + if(sortedAnomalies.get(0).getLineId().equals("9686e66738bab8516ff2c2e9fedc0518")){ + System.out.println(555); + } + + // 检查是否连续 + List> infoList =findAllContinuousAnomalies(sortedAnomalies,ledgerBaseInfoMap); + + if (!infoList.isEmpty()) { + for (List temList : infoList) { + AnomalyInfo first = temList.get(0); + AnomalyInfo last = temList.get(temList.size() - 1); + + // 创建谐波放大事件记录 + UpHarmonicDetail detail = new UpHarmonicDetail(); + detail.setId(IdWorker.get32UUID()); + detail.setMonitorId(first.getLineId()); + detail.setPhase(first.getPhase()); + detail.setHarmonicCount(first.getHarmonicOrder()); + + // 转换时间格式 + detail.setStartTime(LocalDateTime.ofInstant(first.getTime(), ZoneId.systemDefault())); + detail.setEndTime(LocalDateTime.ofInstant(last.getTime(), ZoneId.systemDefault())); + + // 计算持续时间(秒) + long duration = ChronoUnit.SECONDS.between( + detail.getStartTime(), + detail.getEndTime() + ); + detail.setDuration((double) duration); + detail.setVAvgValue(avgVMap.get(first.lineId).get("V"+first.getHarmonicOrder())); + detail.setIAvgValue(avgIMap.get(first.lineId).get("I"+first.getHarmonicOrder())); + + detail.setCreateTime(LocalDateTime.now()); + if(first.getHarmonicOrder()>5){ + detail.setUpScheme("选取5% - 6%电抗率"); + }else { + detail.setUpScheme("选取12%的电抗率(或选取5% - 6%与12%两种电抗率混装方式)"); + } + + harmonicDetails.add(detail); + + log.info("发现谐波放大事件: 监测点={}, 谐波次数={}, 持续时间={}秒, 开始时间={}", + first.getLineId(), first.getHarmonicOrder(), duration, detail.getStartTime()); + } + } + } + + // 批量保存事件 + if (CollUtil.isNotEmpty(harmonicDetails)) { + this.saveBatch(harmonicDetails); + } + } + + /** + * 检查数据是否连续(每分钟一条记录) + */ + /** + * 查找所有连续10条记录(每条间隔50~70秒)的事件 + */ + private List> findAllContinuousAnomalies(List anomalies,Map ledgerBaseInfoMap) { + List> groups = new ArrayList<>(); + List currentGroup = new ArrayList<>(); + + int timeInterval = ledgerBaseInfoMap.get(anomalies.get(0).getLineId()).getTimeInterval(); + + for (AnomalyInfo current : anomalies) { + if (currentGroup.isEmpty()) { + currentGroup.add(current); + } else { + AnomalyInfo lastInGroup = currentGroup.get(currentGroup.size() - 1); + long minutesDiff = ChronoUnit.MINUTES.between(lastInGroup.getTime(), current.getTime()); + + if (minutesDiff == timeInterval) { + currentGroup.add(current); + } else { + // 不连续,检查当前组是否满足 >=10 + if (currentGroup.size() >= continuousAnomalyCount) { + groups.add(new ArrayList<>(currentGroup)); + } + // 重置当前组 + currentGroup.clear(); + currentGroup.add(current); + } + } + } + return groups; + } + + /** + * 从字段名中提取谐波次数 + */ + private int getHarmonicOrderFromField(String field) { + try { + return Integer.parseInt(field.substring(1)); + } catch (Exception e) { + return -1; + } + } + + /** + * 计算 DataV 对象中 V1-Vmax 的平均值 + */ + private Map calculateFieldAveragesV(List list, Integer maxField) { + Map avgMap = new HashMap<>(); + for (int i = 1; i <= maxField; i++) { + String field = "V" + i; + double avg = list.stream() + .mapToDouble(dataV -> { + try { + Method getter = DataV.class.getMethod("get" + field); + return (double) getter.invoke(dataV); + } catch (Exception e) { + return 0d; + } + }) + .average() + .orElse(0); + avgMap.put(field, avg); + } + return avgMap; + } + + /** + * 计算 DataI 对象中 I1-Imax 的平均值 + */ + private Map calculateFieldAveragesI(List list, Integer maxField) { + Map avgMap = new HashMap<>(); + for (int i = 1; i <= maxField; i++) { + String field = "I" + i; + double avg = list.stream() + .mapToDouble(dataI -> { + try { + Method getter = DataI.class.getMethod("get" + field); + return (double) getter.invoke(dataI); + } catch (Exception e) { + return 0d; + } + }) + .average() + .orElse(0); + avgMap.put(field, avg); + } + return avgMap; + } + + /** + * 内部类:用于临时存储异常点信息 + */ + @Data + private static class AnomalyInfo { + private String lineId; + private String phase; + private int harmonicOrder; + private Instant time; + private double voltageChangeRate; + private double currentChangeRate; + + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HistoryResultServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HistoryResultServiceImpl.java new file mode 100644 index 0000000..634fe21 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/harmonicUp/service/impl/HistoryResultServiceImpl.java @@ -0,0 +1,777 @@ +package com.njcn.product.advance.harmonicUp.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.date.DateUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.njcn.common.pojo.constant.BizParamConstant; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.param.StatisticsBizBaseParam; +import com.njcn.common.utils.PubUtils; + +import com.njcn.influx.imapper.CommonMapper; +import com.njcn.influx.imapper.DataHarmRateVMapper; +import com.njcn.influx.imapper.DataIMapper; +import com.njcn.influx.pojo.bo.HarmonicHistoryData; +import com.njcn.influx.pojo.constant.InfluxDBTableConstant; +import com.njcn.product.advance.harmonicUp.pojo.param.HistoryParam; +import com.njcn.product.advance.harmonicUp.pojo.vo.HistoryDataResultVO; +import com.njcn.product.advance.harmonicUp.pojo.vo.QueryResultLimitVO; +import com.njcn.product.advance.harmonicUp.service.HistoryResultService; +import com.njcn.product.system.dict.mapper.DictDataMapper; + +import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.OverlimitMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Overlimit; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.PqsDeviceUnit; +import lombok.AllArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author denghuajun + * @date 2022/3/14 + */ +@Slf4j +@Service +@AllArgsConstructor +public class HistoryResultServiceImpl implements HistoryResultService { + + + private final CommonMapper commonMapper; + + private final DataIMapper dataIMapper; + + private final DataHarmRateVMapper dataHarmRateVMapper; + + private final LineMapper lineMapper; + private final OverlimitMapper overlimitMapper; + private final DictDataMapper dictDataMapper; + + + @Override + public List getHistoryResult(HistoryParam historyParam) { + List historyDataResultVOList = new ArrayList<>(); + //获取监测点 + String[] points = historyParam.getLineId(); + Integer number = 0; + for (int i = 0; i < points.length; i++) { + HistoryDataResultVO historyDataResultVO; + + //获取指标 + String[] contions = historyParam.getCondition(); + for (int j = 0; j < contions.length; j++) { + if ("40".equals(contions[j]) || "41".equals(contions[j]) || "42".equals(contions[j]) || "43".equals(contions[j]) + || "44".equals(contions[j]) || "45".equals(contions[j]) || "50".equals(contions[j]) || "51".equals(contions[j]) + || "52".equals(contions[j])) { + number = historyParam.getHarmonic(); + } + if ("46".equals(contions[j]) || "47".equals(contions[j]) || "48".equals(contions[j]) || "49".equals(contions[j])) { + number = historyParam.getInHarmonic(); + } + historyDataResultVO = getCondition(historyParam.getSearchBeginTime(), historyParam.getSearchEndTime(), points[i], contions[j], number, historyParam.getValueType(), historyParam.getPtType()); + + historyDataResultVOList.add(historyDataResultVO); + + } + } + return historyDataResultVOList; + } + + + + /** + * influxDB相关操作 + * 查询稳态数据分析 + */ + @SneakyThrows + private HistoryDataResultVO getCondition(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType) { + HistoryDataResultVO historyDataResultVO = new HistoryDataResultVO(); + QueryResultLimitVO queryResultLimitVO = getQueryResult(startTime, endTime, lineId, contion, number, valueType, ptType); + List harmonicHistoryDataList = queryResultLimitVO.getHarmonicHistoryDataList(); + BeanUtil.copyProperties(queryResultLimitVO, historyDataResultVO); + //时间轴 + List time = new ArrayList<>(); + //A相值 + List aValue; + //B相值 + List bValue = new ArrayList<>(); + //C相值 + List cValue = new ArrayList<>(); + //针对统计相别为T时存放的数据 + List fValue = new ArrayList<>(); + List> objectListData = new ArrayList<>(); + if (CollectionUtil.isNotEmpty(harmonicHistoryDataList)) { + //相别统计为T时,业务数据处理 + if (StrUtil.isBlank(harmonicHistoryDataList.get(0).getPhasicType()) || harmonicHistoryDataList.get(0).getPhasicType().equalsIgnoreCase("t")) { + for (HarmonicHistoryData harmonicHistoryData : harmonicHistoryDataList) { + time.add(PubUtils.instantToDate(harmonicHistoryData.getTime())); + fValue.add(BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP).floatValue()); + //返回结果有多个值,需要额外处理下 + if (Integer.parseInt(contion) == 14) { + bValue.add(BigDecimal.valueOf(harmonicHistoryData.getBValue()).setScale(4, RoundingMode.HALF_UP).floatValue()); + cValue.add(BigDecimal.valueOf(harmonicHistoryData.getCValue()).setScale(4, RoundingMode.HALF_UP).floatValue()); + } + } + //组装二维数组 + for (int i = 0; i < time.size(); i++) { + List objects = new ArrayList<>(); + objects.add(time.get(i)); + objects.add(fValue.get(i)); + if (Integer.parseInt(contion) == 14) { + objects.add(bValue.get(i)); + objects.add(cValue.get(i)); + } + objectListData.add(objects); + } + historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit()); + historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit()); + historyDataResultVO.setMinValue(Collections.min(fValue)); + historyDataResultVO.setMaxValue(Collections.max(fValue)); + historyDataResultVO.setValue(objectListData); + } else { + //按时间分组 + Map> map = harmonicHistoryDataList.stream().collect(Collectors.groupingBy(HarmonicHistoryData::getTime, TreeMap::new, Collectors.toList())); + + Float maxI = null; + Float minI = null; + for (Map.Entry> entry : map.entrySet()) { + List val = entry.getValue(); + Object[] objects = {PubUtils.instantToDate(entry.getKey()), 0, 0, 0}; + //需要保证val的长度为3 + if (val.size() != 3) { + for (int i = 0; i < 3 - val.size(); i++) { + HarmonicHistoryData tem = new HarmonicHistoryData(); + tem.setAValue(0f); + val.add(tem); + } + } + + for (HarmonicHistoryData harmonicHistoryData : val) { + if (InfluxDBTableConstant.PHASE_TYPE_A.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) { + + BigDecimal a = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP); + objects[1] = a; + maxI = max(maxI, a.floatValue()); + minI = min(minI, a.floatValue()); + + } else if (InfluxDBTableConstant.PHASE_TYPE_B.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) { + BigDecimal b = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP); + objects[2] = b; + maxI = max(maxI, b.floatValue()); + minI = min(minI, b.floatValue()); + + } else if (InfluxDBTableConstant.PHASE_TYPE_C.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) { + BigDecimal c = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP); + objects[3] = c; + maxI = max(maxI, c.floatValue()); + minI = min(minI, c.floatValue()); + + } + } + List list = new ArrayList<>(Arrays.asList(objects)); + + objectListData.add(list); + + } + + historyDataResultVO.setMaxValue(maxI); + historyDataResultVO.setMinValue(minI); + historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit()); + historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit()); + historyDataResultVO.setValue(objectListData); + } + + } else { + return historyDataResultVO; + } + return historyDataResultVO; + } + + + private Float max(Float ding, Float a) { + if (Objects.isNull(ding)) { + ding = a; + } + if (a > ding) { + ding = a; + } + return ding; + } + + private Float min(Float ding, Float a) { + if (Objects.isNull(ding)) { + ding = a; + } + if (a < ding) { + ding = a; + } + return ding; + } + + private QueryResultLimitVO getQueryResult(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType) { + PqsDeviceUnit pqsDeviceUnit = new PqsDeviceUnit(); + QueryResultLimitVO queryResultLimitVO = new QueryResultLimitVO(); + if (!lineId.isEmpty()) { + Float topLimit = 0f; + Float lowerLimit = 0f; + + + //获取监测点信息 + LineDevGetDTO lineDetailData = lineMapper.getMonitorDetail(lineId); + //获取限值 + Overlimit overlimit = overlimitMapper.selectById(lineId); + + //组装sql语句 + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(InfluxDBTableConstant.TIME + " >= '").append(startTime).append("' and ").append(InfluxDBTableConstant.TIME).append(" <= '").append(endTime).append("' and ("); + //sql语句 + stringBuilder.append(InfluxDBTableConstant.LINE_ID + "='").append(lineId).append("')"); + String valueTypeName = ""; + switch (valueType) { + case 1: + valueTypeName = "AVG"; + break; + case 2: + valueTypeName = "MIN"; + break; + case 3: + valueTypeName = "MAX"; + break; + case 4: + valueTypeName = "CP95"; + break; + default: + break; + } + if (!Integer.valueOf(contion).equals(60) && !Integer.valueOf(contion).equals(61) && !Integer.valueOf(contion).equals(62)) { + stringBuilder.append(" and ").append(InfluxDBTableConstant.VALUE_TYPE + "='").append(valueTypeName).append("'"); + } + String sql = ""; + List phasicType = new ArrayList<>(); + List unit = new ArrayList<>(); + String targetName = ""; + switch (Integer.parseInt(contion)) { + case 10: + //相电压有效值 + sql = "SELECT time as time, rms as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add(pqsDeviceUnit.getPhaseVoltage()); + targetName = "相电压有效值"; + break; + case 11: + //线电压有效值 + sql = "SELECT time as time, rms_lvr as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C')order by time asc tz('Asia/Shanghai');"; + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + unit.add(pqsDeviceUnit.getLineVoltage()); + targetName = "线电压有效值"; + break; + case 12: + //电压偏差 + sql = "SELECT time as time, vu_dev as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + topLimit = overlimit.getVoltageDev(); + lowerLimit = overlimit.getUvoltageDev(); + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + unit.add("%"); + targetName = "电压偏差"; + break; + case 13: + //三相电压不平衡度 + sql = "SELECT time as time, v_unbalance as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + topLimit = overlimit.getUbalance(); + phasicType.add("三相电压不平衡度"); + unit.add("%"); + targetName = "三相电压不平衡度"; + break; + case 14: + //电压不平衡 + sql = "SELECT time as time, v_zero as aValue, v_pos as bValue, v_neg as cValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='T') order by time asc tz('Asia/Shanghai');"; + phasicType.add("零序电压"); + phasicType.add("正序电压"); + phasicType.add("负序电压"); + unit.add(pqsDeviceUnit.getNoPositiveV()); + unit.add(pqsDeviceUnit.getPositiveV()); + unit.add(pqsDeviceUnit.getNoPositiveV()); + targetName = "电压不平衡"; + break; + case 15: + //电压总谐波畸变率 + sql = "SELECT time as time, v_thd as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + topLimit = overlimit.getUaberrance(); + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + unit.add("%"); + targetName = "电压总谐波畸变率"; + break; + case 20: + //电流有效值 + sql = "SELECT time as time, rms as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("A"); + targetName = "电流有效值"; + break; + case 21: + //电流总畸变率 + sql = "SELECT time as time, i_thd as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("%"); + targetName = "电流总谐波畸变率"; + break; + case 22: + //负序电流 + sql = "SELECT time as time, i_neg as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + topLimit = overlimit.getINeg(); + phasicType.add("负序电流"); + unit.add("A"); + targetName = "负序电流"; + break; + case 30: + //频率 V9暂时代表Freq + sql = "SELECT time as time, freq as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + topLimit = 50 + overlimit.getFreqDev(); + lowerLimit = 50 - overlimit.getFreqDev(); + phasicType.add("频率"); + unit.add("Hz"); + targetName = "频率"; + break; + case 40: + //谐波电压含有率 + if (number == 1) { + targetName = "基波电压幅值"; + //修改幅值表 + sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + unit.add(pqsDeviceUnit.getPhaseVoltage()); + } else { + targetName = "谐波电压含有率"; + sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + if (number < 26) { + topLimit = PubUtils.getValueByMethod(overlimit, "getUharm", number); + } + unit.add("%"); + } + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + + + break; + case 41: + //谐波电流含有率 + if (number == 1) { + targetName = "谐波电流幅值"; + sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + + unit.add("A"); + } else { + targetName = "谐波电流含有率"; + sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + unit.add("%"); + } + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + + + break; + case 42: + //谐波电压幅值 + if (number == 1) { + sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + } else { + sql = "SELECT time as time, v_" + number + "*1000 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + } + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + if (number == 1) { + unit.add(pqsDeviceUnit.getVfundEffective()); + targetName = "基波电压幅值"; + + } else { + unit.add("V"); + targetName = "谐波电压幅值"; + + } + break; + case 43: + //谐波电流幅值 + if (number == 1) { + sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + targetName = "基波电流幅值"; + + } else { + sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + if (number < 26) { + topLimit = PubUtils.getValueByMethod(overlimit, "getIharm", number); + } + targetName = "谐波电流幅值"; + + } + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("A"); + break; + case 44: + //谐波电压相角 + if (number == 1) { + targetName = "基波电压相角"; + + sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + } else { + targetName = "谐波电压相角"; + sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + } + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + unit.add("°"); + break; + case 45: + //谐波电流相角 + if (number == 1) { + sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + targetName = "基波电流相角"; + + } else { + sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + targetName = "谐波电流相角"; + + } + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("°"); + break; + case 46: + //间谐波电压含有率 + sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + if(number<17){ + topLimit = PubUtils.getValueByMethod(overlimit, "getInuharm", number); + }else { + topLimit = 0.0f; + } + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + unit.add("%"); + targetName = "间谐波电压含有率"; + break; + case 47: + //间谐波电流含有率 + sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("%"); + targetName = "间谐波电流含有率"; + break; + case 48: + //间谐波电压幅值 + sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_v WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + targetName = "间谐波电压幅值"; + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + unit.add(pqsDeviceUnit.getPhaseVoltage()); + break; + case 49: + //间谐波电流幅值 + sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_i WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add("A"); + targetName = "间谐波电流幅值"; + break; + case 50: + //谐波有功功率 + sql = "SELECT time as time, p_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + if (number == 1) { + unit.add(pqsDeviceUnit.getFundActiveP()); + } else { + unit.add("W"); + } + targetName = "谐波有功功率"; + break; + case 51: + //谐波无功功率 + sql = "SELECT time as time, q_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + if (number == 1) { + unit.add(pqsDeviceUnit.getTotalNoP()); + } else { + unit.add("Var"); + } + targetName = "谐波无功功率"; + break; + case 52: + //谐波视在功率 + sql = "SELECT time as time, s_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + if (number == 1) { + unit.add(pqsDeviceUnit.getTotalViewP()); + } else { + unit.add("VA"); + } + targetName = "谐波视在功率"; + break; + case 53: + //三相有功功率 + sql = "SELECT time as time, p as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add(pqsDeviceUnit.getTotalActiveP()); + targetName = "三相有功功率"; + break; + case 54: + //三相无功功率 + sql = "SELECT time as time, q as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add(pqsDeviceUnit.getTotalNoP()); + targetName = "三相无功功率"; + break; + case 55: + //三相视在功率 + sql = "SELECT time as time, s as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + unit.add(pqsDeviceUnit.getTotalViewP()); + targetName = "三相视在功率"; + break; + case 56: + //三相总有功功率 + sql = "SELECT time as time, p as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + phasicType.add("三相总有功功率"); + unit.add(pqsDeviceUnit.getTotalActiveP()); + targetName = "三相总有功功率"; + break; + case 57: + //三相总无功功率 + sql = "SELECT time as time, q as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + phasicType.add("三相总无功功率"); + unit.add(pqsDeviceUnit.getTotalNoP()); + targetName = "三相总无功功率"; + break; + case 58: + //三相总视在功率 + sql = "SELECT time as time, s as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + phasicType.add("三相总视在功率"); + unit.add(pqsDeviceUnit.getTotalViewP()); + targetName = "三相总视在功率"; + break; + case 59: + //视在功率因数 + sql = "SELECT time as time, pf as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') group by phasic_type order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + targetName = "视在功率因数"; + break; + case 591: + //位移功率因数 + sql = "SELECT time as time, df as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + targetName = "位移功率因数"; + break; + case 592: + //总视在功率因数 + sql = "SELECT time as time, pf as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + phasicType.add("总视在功率因数"); + targetName = "总视在功率因数"; + break; + case 593: + //总位移功率因数 + sql = "SELECT time as time, df as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder + + " and phasic_type ='T' order by time asc tz('Asia/Shanghai');"; + phasicType.add("总位移功率因数"); + targetName = "总位移功率因数"; + break; + case 61: + //长时闪变 + sql = "SELECT time as time, plt as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_plt WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + topLimit = overlimit.getFlicker(); + targetName = "长时闪变"; + break; + case 60: + //短时闪变 + sql = "SELECT time as time, pst as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_flicker WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + topLimit = overlimit.getFlicker(); + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + targetName = "短时闪变"; + break; + case 62: + //电压波动 + sql = "SELECT time as time, fluc as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_fluc WHERE " + stringBuilder + + " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');"; + if (ptType == 0) { + phasicType.add("A相"); + phasicType.add("B相"); + phasicType.add("C相"); + } else { + phasicType.add("AB相"); + phasicType.add("BC相"); + phasicType.add("CA相"); + } + targetName = "电压波动"; + unit.add("%"); + break; + default: + break; + } + //大致有3种类型 + //1、一次查询返回3条记录,分别为A/B/C三相的结果 + //2、一次查询返回一条记录,以T相为条件,返回某3个指标值 + //3、一次查询返回一条记录,以T相为条件,返回某1个指标值 + List harmonicHistoryData = commonMapper.getHistoryResult(sql); + queryResultLimitVO.setHarmonicHistoryDataList(harmonicHistoryData); + queryResultLimitVO.setTopLimit(topLimit); + queryResultLimitVO.setLowerLimit(lowerLimit); + queryResultLimitVO.setPhaiscType(phasicType); + queryResultLimitVO.setUnit(unit); + queryResultLimitVO.setLineName(lineDetailData.getPointName()); + queryResultLimitVO.setHarmNum(number); + queryResultLimitVO.setTargetName(targetName); + queryResultLimitVO.setWiringMethod(lineDetailData.getWiringMethod()); + } else { + return queryResultLimitVO; + } + return queryResultLimitVO; + } + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/analysis/CanonicalCorrelationAnalysis.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/analysis/CanonicalCorrelationAnalysis.java new file mode 100644 index 0000000..65bd810 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/analysis/CanonicalCorrelationAnalysis.java @@ -0,0 +1,382 @@ +package com.njcn.product.advance.responsility.analysis; + + +import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants; +import com.njcn.product.advance.responsility.utils.MathUtils; +import org.apache.commons.math3.linear.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 典则相关分析类 + * 实现典则相关系数的计算 + * + * @author hongawen + * @version 1.0 + */ +public class CanonicalCorrelationAnalysis { + + private static final Logger logger = LoggerFactory.getLogger(CanonicalCorrelationAnalysis.class); + + /** + * 计算典则相关系数 + * 对应C代码中的TransCancor函数 + * + * @param powerData 功率数据矩阵 [时间][节点] + * @param harmonicData 谐波数据向量 + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @return 典则相关系数 + */ + public static float computeCanonicalCorrelation(float[][] powerData, float[] harmonicData, + int windowSize, int nodeCount) { + logger.info("===== 开始典型相关分析 ====="); + logger.info("输入参数: windowSize={}, nodeCount={}", windowSize, nodeCount); + + try { + // 提取窗口数据 + double[][] x = new double[windowSize][nodeCount]; + double[] y = new double[windowSize]; + + // ===== 数据质量统计(只统计,不影响计算) ===== + int nanCountPower = 0, infiniteCountPower = 0, zeroCountPower = 0; + int nanCountHarmonic = 0, infiniteCountHarmonic = 0, zeroCountHarmonic = 0; + double powerSum = 0, harmonicSum = 0; + double powerMin = Double.MAX_VALUE, powerMax = -Double.MAX_VALUE; + double harmonicMin = Double.MAX_VALUE, harmonicMax = -Double.MAX_VALUE; + + for (int i = 0; i < windowSize; i++) { + for (int j = 0; j < nodeCount; j++) { + float val = powerData[i][j]; + x[i][j] = val; + + // 仅统计,不改变原逻辑 + if (Float.isNaN(val)) { + nanCountPower++; + } else if (Float.isInfinite(val)) { + infiniteCountPower++; + } else if (val == 0.0f) { + zeroCountPower++; + } else { + powerSum += val; + powerMin = Math.min(powerMin, val); + powerMax = Math.max(powerMax, val); + } + } + + float harmonicVal = harmonicData[i]; + y[i] = harmonicVal; + + // 仅统计,不改变原逻辑 + if (Float.isNaN(harmonicVal)) { + nanCountHarmonic++; + } else if (Float.isInfinite(harmonicVal)) { + infiniteCountHarmonic++; + } else if (harmonicVal == 0.0f) { + zeroCountHarmonic++; + } else { + harmonicSum += harmonicVal; + harmonicMin = Math.min(harmonicMin, harmonicVal); + harmonicMax = Math.max(harmonicMax, harmonicVal); + } + } + + // ===== 数据质量报告(只记录日志) ===== + int totalPowerCount = windowSize * nodeCount; + int totalHarmonicCount = windowSize; + + logger.info("功率数据质量分析:"); + logger.info(" 总数据点: {}", totalPowerCount); + logger.info(" NaN数量: {} ({:.2f}%)", nanCountPower, nanCountPower * 100.0 / totalPowerCount); + logger.info(" 无穷大数量: {} ({:.2f}%)", infiniteCountPower, infiniteCountPower * 100.0 / totalPowerCount); + logger.info(" 零值数量: {} ({:.2f}%)", zeroCountPower, zeroCountPower * 100.0 / totalPowerCount); + logger.info(" 有效数据范围: [{}, {}]", powerMin == Double.MAX_VALUE ? "N/A" : powerMin, + powerMax == -Double.MAX_VALUE ? "N/A" : powerMax); + + logger.info("谐波数据质量分析:"); + logger.info(" 总数据点: {}", totalHarmonicCount); + logger.info(" NaN数量: {} ({:.2f}%)", nanCountHarmonic, nanCountHarmonic * 100.0 / totalHarmonicCount); + logger.info(" 无穷大数量: {} ({:.2f}%)", infiniteCountHarmonic, infiniteCountHarmonic * 100.0 / totalHarmonicCount); + logger.info(" 零值数量: {} ({:.2f}%)", zeroCountHarmonic, zeroCountHarmonic * 100.0 / totalHarmonicCount); + logger.info(" 有效数据范围: [{}, {}]", harmonicMin == Double.MAX_VALUE ? "N/A" : harmonicMin, + harmonicMax == -Double.MAX_VALUE ? "N/A" : harmonicMax); + + // 只记录警告,不停止计算 + if (nanCountPower > 0 || infiniteCountPower > 0) { + logger.warn("功率数据包含异常值!NaN: {}, Infinite: {}", nanCountPower, infiniteCountPower); + } + if (nanCountHarmonic > 0 || infiniteCountHarmonic > 0) { + logger.warn("谐波数据包含异常值!NaN: {}, Infinite: {}", nanCountHarmonic, infiniteCountHarmonic); + } + + // 计算协方差矩阵 SXX + logger.info("===== 开始协方差计算 ====="); + double[][] sxxMatrix = MathUtils.covarianceMatrix(x, windowSize, nodeCount); + + // ===== SXX矩阵诊断(只记录日志)===== + double sxxTrace = 0; + double sxxFrobeniusNorm = 0; + boolean sxxHasNaN = false, sxxHasInfinite = false; + + for (int i = 0; i < nodeCount; i++) { + sxxTrace += sxxMatrix[i][i]; + for (int j = 0; j < nodeCount; j++) { + double val = sxxMatrix[i][j]; + if (Double.isNaN(val)) { + sxxHasNaN = true; + } + if (Double.isInfinite(val)) { + sxxHasInfinite = true; + } + sxxFrobeniusNorm += val * val; + } + } + sxxFrobeniusNorm = Math.sqrt(sxxFrobeniusNorm); + + logger.info("SXX矩阵诊断:"); + logger.info(" 维度: {}x{}", nodeCount, nodeCount); + logger.info(" 迹(trace): {}", sxxTrace); + logger.info(" Frobenius范数: {}", sxxFrobeniusNorm); + logger.info(" 包含NaN: {}", sxxHasNaN); + logger.info(" 包含无穷大: {}", sxxHasInfinite); + logger.info(" 对角线元素: {}", java.util.Arrays.toString( + java.util.stream.IntStream.range(0, nodeCount) + .mapToDouble(i -> sxxMatrix[i][i]) + .toArray())); + + // 计算协方差 SYY + double syyMatrix = MathUtils.covariance(y, y, windowSize); + logger.info("SYY协方差: {}", syyMatrix); + + if (Math.abs(syyMatrix) < HarmonicConstants.MIN_COVARIANCE) { + logger.warn("SYY过小 ({}), 调整为最小值: {}", syyMatrix, HarmonicConstants.MIN_COVARIANCE); + syyMatrix = HarmonicConstants.MIN_COVARIANCE; + } + + // 计算协方差向量 SXY + double[] sxyVector = MathUtils.covarianceVector(x, y, windowSize, nodeCount); + + // ===== SXY向量诊断(只记录日志)===== + double sxyNorm = 0; + boolean sxyHasNaN = false, sxyHasInfinite = false; + for (double val : sxyVector) { + if (Double.isNaN(val)) { + sxyHasNaN = true; + } + if (Double.isInfinite(val)) { + sxyHasInfinite = true; + } + sxyNorm += val * val; + } + sxyNorm = Math.sqrt(sxyNorm); + + logger.info("SXY向量诊断:"); + logger.info(" 长度: {}", sxyVector.length); + logger.info(" L2范数: {}", sxyNorm); + logger.info(" 包含NaN: {}", sxyHasNaN); + logger.info(" 包含无穷大: {}", sxyHasInfinite); + logger.info(" 向量值: {}", java.util.Arrays.toString(sxyVector)); + + // 使用Apache Commons Math进行矩阵运算 + logger.info("===== 开始矩阵分解 ====="); + RealMatrix sxx = new Array2DRowRealMatrix(sxxMatrix); + RealVector sxy = new ArrayRealVector(sxyVector); + + // 计算 SXX^(-1) + logger.info("准备计算SXX逆矩阵..."); + DecompositionSolver solver = new LUDecomposition(sxx).getSolver(); + RealMatrix invSxx; + + // 检查矩阵奇异性 + double sxxDet = new LUDecomposition(sxx).getDeterminant(); + logger.info("SXX矩阵行列式: {}", sxxDet); + + if (Math.abs(sxxDet) < 1e-15) { + logger.warn("SXX矩阵几乎奇异 (det={})", sxxDet); + } + + if (!solver.isNonSingular()) { + // 如果矩阵奇异,使用伪逆 + logger.warn("SXX matrix is singular, using pseudo-inverse"); + try { + SingularValueDecomposition svd = new SingularValueDecomposition(sxx); + invSxx = svd.getSolver().getInverse(); + } catch (Exception svdException) { + logger.error("SVD pseudo-inverse failed, using regularized inverse", svdException); + // 添加正则化项 + RealMatrix identity = MatrixUtils.createRealIdentityMatrix(sxx.getRowDimension()); + RealMatrix regularized = sxx.add(identity.scalarMultiply(1e-10)); + invSxx = new LUDecomposition(regularized).getSolver().getInverse(); + } + } else { + invSxx = solver.getInverse(); + } + + // 计算 U = SXX^(-1) * SXY * (1/SYY) * SXY' + RealVector temp = invSxx.operate(sxy); + double scale = 1.0 / syyMatrix; + RealMatrix uMatrix = temp.outerProduct(sxy).scalarMultiply(scale); + + // 计算特征值 - 添加数值稳定性处理 + double maxEigenvalue = 0.0; + + try { + // 首先检查矩阵是否有效 + double[][] uMatrixData = uMatrix.getData(); + boolean hasNaN = false; + boolean hasInfinite = false; + + for (int i = 0; i < uMatrixData.length; i++) { + for (int j = 0; j < uMatrixData[i].length; j++) { + if (Double.isNaN(uMatrixData[i][j])) { + hasNaN = true; + } + if (Double.isInfinite(uMatrixData[i][j])) { + hasInfinite = true; + } + } + } + + if (hasNaN || hasInfinite) { + logger.warn("U matrix contains NaN or Infinite values, returning 0"); + return 0.0f; + } + + // 检查矩阵条件数 + SingularValueDecomposition svdCheck = new SingularValueDecomposition(uMatrix); + double conditionNumber = svdCheck.getConditionNumber(); + + if (conditionNumber > 1e12) { + logger.warn("U matrix is ill-conditioned (condition number: {}), using SVD approach", conditionNumber); + + // 使用SVD方法获取最大奇异值的平方作为最大特征值 + double[] singularValues = svdCheck.getSingularValues(); + if (singularValues.length > 0) { + maxEigenvalue = singularValues[0] * singularValues[0]; + } + } else { + // 正常的特征值分解 + EigenDecomposition eigenDecomposition = new EigenDecomposition(uMatrix); + double[] eigenvalues = eigenDecomposition.getRealEigenvalues(); + + // 找最大特征值 + for (double eigenvalue : eigenvalues) { + maxEigenvalue = Math.max(maxEigenvalue, Math.abs(eigenvalue)); + } + } + + } catch (Exception eigenException) { + logger.warn("EigenDecomposition failed, trying alternative approach: {}", eigenException.getMessage()); + + // 备用方案:使用SVD方法 + try { + SingularValueDecomposition svd = new SingularValueDecomposition(uMatrix); + double[] singularValues = svd.getSingularValues(); + if (singularValues.length > 0) { + maxEigenvalue = singularValues[0] * singularValues[0]; + } + } catch (Exception svdException) { + logger.error("Both EigenDecomposition and SVD failed, returning 0", svdException); + return 0.0f; + } + } + + // 典则相关系数是最大特征值的平方根 + double canonicalCorr = Math.sqrt(Math.abs(maxEigenvalue)); + + // 限制在[0,1]范围内 + if (canonicalCorr > 1.0) { + canonicalCorr = 1.0; + } + + logger.info("===== 典型相关分析计算完成 ====="); + logger.info("最大特征值: {}", maxEigenvalue); + logger.info("典型相关系数: {}", canonicalCorr); + logger.info("是否被截断到1.0: {}", canonicalCorr >= 1.0); + + return (float) canonicalCorr; + + } catch (Exception e) { + logger.error("Error computing canonical correlation", e); + logger.error("异常详情: {}", e.getMessage()); + logger.error("异常类型: {}", e.getClass().getSimpleName()); + return 0.0f; + } + } + + /** + * 滑动窗口计算典则相关系数序列 + * 对应C代码中的SlideCanCor函数 + * + * @param powerData 功率数据矩阵 [时间][节点] + * @param harmonicData 谐波数据向量 + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @param dataLength 数据总长度 + * @return 典则相关系数序列 + */ + public static float[] slidingCanonicalCorrelation(float[][] powerData, float[] harmonicData, + int windowSize, int nodeCount, int dataLength) { + int slideLength = dataLength - windowSize; + if (slideLength <= 0) { + throw new IllegalArgumentException("Data length must be greater than window size"); + } + + float[] slideCanCor = new float[slideLength]; + + logger.info("Starting sliding canonical correlation analysis, slide length: {}", slideLength); + + for (int i = 0; i < slideLength; i++) { + // 提取窗口数据 + float[][] windowPower = new float[windowSize][nodeCount]; + float[] windowHarmonic = new float[windowSize]; + + for (int j = 0; j < windowSize; j++) { + System.arraycopy(powerData[i + j], 0, windowPower[j], 0, nodeCount); + windowHarmonic[j] = harmonicData[i + j]; + } + + // 计算当前窗口的典则相关系数 + slideCanCor[i] = computeCanonicalCorrelation(windowPower, windowHarmonic, + windowSize, nodeCount); + + if (i % 10 == 0) { + logger.debug("Processed window {}/{}", i, slideLength); + } + } + + logger.info("Sliding canonical correlation analysis completed"); + + return slideCanCor; + } + + /** + * 计算包含/不包含背景的动态相关系数 + * 对应C代码中的SlideCor函数 + * + * @param powerData 功率数据(单个节点) + * @param harmonicData 谐波数据 + * @param slideCanCor 滑动典则相关系数 + * @param windowSize 窗口大小 + * @return 动态相关系数序列 + */ + public static float[] slidingCorrelation(float[] powerData, float[] harmonicData, + float[] slideCanCor, int windowSize) { + int slideLength = slideCanCor.length; + float[] slideCor = new float[slideLength]; + + for (int i = 0; i < slideLength; i++) { + float[] tempPower = new float[windowSize]; + float[] tempHarmonic = new float[windowSize]; + + for (int j = 0; j < windowSize; j++) { + tempPower[j] = powerData[i + j]; + tempHarmonic[j] = harmonicData[i + j] * slideCanCor[i]; + } + + slideCor[i] = MathUtils.pearsonCorrelation(tempHarmonic, tempPower, windowSize); + } + + return slideCor; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/HarmonicCalculationEngine.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/HarmonicCalculationEngine.java new file mode 100644 index 0000000..becb25d --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/HarmonicCalculationEngine.java @@ -0,0 +1,425 @@ +package com.njcn.product.advance.responsility.calculator; + + +import com.njcn.product.advance.responsility.analysis.CanonicalCorrelationAnalysis; +import com.njcn.product.advance.responsility.model.HarmonicData; +import com.njcn.product.advance.responsility.pojo.constant.CalculationMode; +import com.njcn.product.advance.responsility.pojo.constant.CalculationStatus; +import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 谐波责任计算主引擎 + * 严格对应C代码中的harm_res系列函数 + * + * @author hongawen + * @version 2.0 - 修复版本,严格对照C代码实现 + */ +public class HarmonicCalculationEngine { + + private static final Logger logger = LoggerFactory.getLogger(HarmonicCalculationEngine.class); + + // 对应C代码中的全局变量 + private int P; // 节点数 p_node + private int TL; // 功率数据长度 p_num + private int LL; // 谐波数据长度 harm_num + private int JIANGE; // 数据间隔比例 + private int width; // 窗口大小 + private float XIANE; // 谐波门槛 + + /** + * 主计算入口 + * 对应C代码中的harm_res函数 + * + * @param data 谐波数据对象 + * @return 计算是否成功 + */ + public boolean calculate(HarmonicData data) { + logger.info("Starting harmonic calculation, mode: {}", data.getCalculationMode()); + + try { + if (data.getCalculationMode() == CalculationMode.FULL_CALCULATION) { + return fullCalculation(data); + } else { + return partialCalculation(data); + } + } catch (Exception e) { + logger.error("Calculation failed with exception: " + e.getMessage(), e); + e.printStackTrace(); + data.setCalculationStatus(CalculationStatus.FAILED); + return false; + } + } + + /** + * 完整计算模式 + * 严格对应C代码中的harm_res_all函数 + * + * @param data 谐波数据对象 + * @return 计算是否成功 + */ + private boolean fullCalculation(HarmonicData data) { + logger.info("Executing full calculation mode"); + + // 1. 数据初始化 - 对应 data_init_all() + if (!initializeFullCalculationData(data)) { + logger.error("Data initialization failed"); + data.setCalculationStatus(CalculationStatus.FAILED); + return false; + } + + // 2. 创建工作数组 - 对应C代码行536-540 + float[][] a = new float[TL][P]; // 功率数据副本 + float[] b = new float[LL]; // 谐波数据副本 + float[] u = new float[TL]; // 对齐后的谐波数据 + + // 3. 复制数据 - 对应C代码行542-552 + for (int i = 0; i < TL; i++) { + for (int j = 0; j < P; j++) { + a[i][j] = data.getPowerData()[i][j]; + } + } + for (int i = 0; i < LL; i++) { + b[i] = data.getHarmonicData()[i]; + } + + // 4. 数据对齐处理 - 严格对应C代码行554-562 + // 注意:C代码是原地修改数组b + for (int i = 0; i < LL; i += JIANGE) { + float tempt = 0.0f; + for (int j = 0; j < JIANGE; j++) { + tempt += b[i + j]; + } + b[i] = tempt / JIANGE; // 覆盖原位置 + } + + // 5. 构建Udata - 严格对应C代码行570-580 + // 注意:使用 i*JIANGE 索引 + for (int i = 0; i < TL; i++) { + u[i] = b[i * JIANGE]; // 关键:使用 i*JIANGE 索引 + } + + int slcorlength = TL - width; + + // 6. 计算滑动典则相关系数 - 对应C代码行584 + logger.info("Computing sliding canonical correlation"); + float[] cancorrelation = CanonicalCorrelationAnalysis.slidingCanonicalCorrelation( + a, u, width, P, TL + ); + + // 7. 保存典则相关系数 - 对应C代码行592-601 + float[] Core = new float[slcorlength]; + float[] BjCore = new float[slcorlength]; + for (int i = 0; i < slcorlength; i++) { + Core[i] = cancorrelation[i]; + BjCore[i] = 1 - cancorrelation[i]; + } + data.setCanonicalCorrelation(Core); + data.setBackgroundCanonicalCorr(BjCore); + + // 8. 计算动态相关系数矩阵 - 对应C代码行605-635 + logger.info("Computing correlation matrix"); + float[][] simCor = new float[slcorlength][P]; + + // 对应C代码行618-632:对每个节点计算动态相关系数 + for (int i = 0; i < P; i++) { + // 提取第i个节点的功率数据 + float[] xe = new float[TL]; + for (int m = 0; m < TL; m++) { + xe[m] = a[m][i]; // 对应 Pdata.block(0, i, TL, 1) + } + + // 计算该节点的滑动相关系数 + float[] slidecor = CanonicalCorrelationAnalysis.slidingCorrelation( + xe, u, cancorrelation, width + ); + + // 存储结果 + for (int j = 0; j < slcorlength; j++) { + simCor[j][i] = slidecor[j]; + } + } + data.setCorrelationData(simCor); + + // 9. 计算EK值 - 对应C代码行642-654 + logger.info("Computing EK values"); + float[][] EKdata = ResponsibilityCalculator.computeEK( + simCor, a, width, P, TL + ); + + // 10. 计算FK值 - 对应C代码行660-673 + logger.info("Computing FK values"); + float[][] FKdata = ResponsibilityCalculator.computeFK( + EKdata, width, P, TL + ); + data.setFkData(FKdata); + + // 11. 计算HK值 - 对应C代码行678-691 + logger.info("Computing HK values"); + float[][] HKdata = ResponsibilityCalculator.computeHK( + BjCore, EKdata, width, P, TL + ); + data.setHkData(HKdata); + + // 12. 设置结果数量 - 对应C代码行693 + data.setResponsibilityDataCount(slcorlength); + + // 13. 统计超限时段的责任 - 对应C代码行696-724 + logger.info("Computing responsibility sums"); + + // 重要修正:C代码的SumHK函数中,虽然Udata长度是TL,但是循环只遍历前slg(=TL-width)个元素 + // 所以我们需要传入完整的u数组(长度TL),让sumResponsibility内部处理 + // 对应C代码:VectorXd Udata(TL); 以及 SumHK函数调用 + + // 统计HK责任(包含背景)- 对应C代码行698-710 + // 注意:传入完整的u数组(TL长度),而不是截取的数组 + float[] sumHK = ResponsibilityCalculator.sumResponsibility( + HKdata, u, XIANE, width, P + 1, TL + ); + data.setSumHKData(sumHK); + + // 统计FK责任(不包含背景)- 对应C代码行712-724 + // 同样传入完整的u数组和TL参数 + float[] sumFK = ResponsibilityCalculator.sumResponsibility( + FKdata, u, XIANE, width, P, TL + ); + data.setSumFKData(sumFK); + + // 14. 标记计算成功 - 对应C代码行739 + data.setCalculationStatus(CalculationStatus.CALCULATED); + logger.info("Full calculation completed successfully"); + + return true; + } + + /** + * 初始化完整计算数据 + * 对应C代码中的data_init_all函数 + */ + private boolean initializeFullCalculationData(HarmonicData data) { + // 设置全局变量 - 对应C代码行478-483 + P = data.getPowerNodeCount(); + TL = data.getPowerCount(); + LL = data.getHarmonicCount(); + // 对应C代码第481行:JIANGE = pq_buf.harm_num/pq_buf.p_num; + // 重要修正:JIANGE应该是 谐波数量/功率点数,不是谐波数量/节点数 + JIANGE = LL / TL; // 这个是正确的:harm_num / p_num (其中p_num是功率点数) + width = data.getWindowSize(); + XIANE = data.getHarmonicThreshold(); + + // 验证数据 - 对应C代码行485-504 + if (JIANGE * TL != LL || JIANGE < 1) { + logger.error("Data length mismatch: JIANGE({}) * TL({}) != LL({})", + JIANGE, TL, LL); + return false; + } + + if (width < HarmonicConstants.MIN_WIN_LEN || width > HarmonicConstants.MAX_WIN_LEN) { + logger.error("Invalid window size: {}", width); + return false; + } + + if (TL < 2 * width) { + logger.error("Power data length {} is too short for window size {}", TL, width); + return false; + } + + if (P > HarmonicConstants.MAX_P_NODE || TL > HarmonicConstants.MAX_P_NUM || + LL > HarmonicConstants.MAX_HARM_NUM) { + logger.error("Data size exceeds limits"); + return false; + } + + return true; + } + + /** + * 部分重算模式 + * 对应C代码中的harm_res_part函数 + * + * @param data 谐波数据对象 + * @return 计算是否成功 + */ + private boolean partialCalculation(HarmonicData data) { + logger.info("Executing partial calculation mode"); + + // 1. 数据初始化 - 对应 data_init_part() + if (!initializePartialCalculationData(data)) { + logger.error("Data initialization failed for partial calculation"); + data.setCalculationStatus(CalculationStatus.FAILED); + return false; + } + + // 2. 准备Udata - 对应C代码行816-818 + // C代码:VectorXd Udata(TL); 并从pq_buf.harm_data复制TL个元素 + int res_num = data.getResponsibilityDataCount(); + + // 验证责任数据行数 + if (res_num != TL - width) { + logger.warn("责任数据行数({})与期望值(TL-width={})不匹配", res_num, TL - width); + res_num = TL - width; // 使用正确的值 + } + + // 重要修正:与C代码保持一致,Udata长度应该是TL,而不是res_num + // C代码:VectorXd Udata(TL); + float[] Udata = new float[TL]; + + // 从harm_data复制TL个元素到Udata + // C代码:for (int j = 0; j < TL; j++) Udata[j] = pq_buf.harm_data[j]; + if (data.getHarmonicData().length < TL) { + logger.warn("谐波数据长度({})小于TL({}), 将补零", + data.getHarmonicData().length, TL); + System.arraycopy(data.getHarmonicData(), 0, Udata, 0, data.getHarmonicData().length); + // 剩余部分自动补零 + } else { + System.arraycopy(data.getHarmonicData(), 0, Udata, 0, TL); + } + + logger.debug("准备Udata完成: 长度={} (对应C代码TL), 责任数据行数={}", Udata.length, res_num); + + // 3. 统计HK责任 - 对应C代码行806-830 + logger.info("Recalculating HK responsibility sums"); + + // 对应C代码第808-814行:创建新的HKdata矩阵,只包含RES_NUM行 + // C代码:MatrixXd HKdata(RES_NUM, (P + 1)); + + // 添加数据验证 + if (data.getHkData() == null || data.getHkData().length == 0) { + logger.error("HK数据为空或长度为0"); + data.setCalculationStatus(CalculationStatus.FAILED); + return false; + } + + // 重要:C代码创建了新的RES_NUM行的HKdata,从原始数据复制前RES_NUM行 + // 对应C代码第808-814行 + float[][] HKdataForCalc = new float[res_num][P + 1]; + int copyRows = Math.min(res_num, data.getHkData().length); + + logger.debug("创建用于计算的HK数据矩阵: {}x{}, 从原始数据复制{}行", + res_num, P + 1, copyRows); + + for (int i = 0; i < copyRows; i++) { + for (int j = 0; j < P + 1; j++) { + if (j < data.getHkData()[i].length) { + HKdataForCalc[i][j] = data.getHkData()[i][j]; + } + } + } + + + logger.debug("调用HK sumResponsibility参数: HKdata[{}x{}], Udata[{}], TL={}, width={}", + HKdataForCalc.length, HKdataForCalc.length > 0 ? HKdataForCalc[0].length : 0, + Udata.length, TL, width); + + try { + // 对应C代码第819行:arrHKsum = SumHK(HKdata, Udata, wdith, colK, TL); + float[] sumHK = ResponsibilityCalculator.sumResponsibility( + HKdataForCalc, // 使用新创建的RES_NUM行的HK数据 + Udata, // 长度为TL的数组 + XIANE, + width, + P + 1, + TL // 传入TL参数 + ); + data.setSumHKData(sumHK); + logger.debug("HK责任计算完成,结果长度: {}", sumHK != null ? sumHK.length : "null"); + } catch (Exception e) { + logger.error("HK责任计算失败: " + e.getMessage(), e); + throw e; + } + + // 4. 统计FK责任 - 对应C代码行839-851 + logger.info("Recalculating FK responsibility sums"); + + // 对应C代码:虽然没有显式创建新的FKdata,但逻辑相同 + + // 添加数据验证 + if (data.getFkData() == null || data.getFkData().length == 0) { + logger.error("FK数据为空或长度为0"); + data.setCalculationStatus(CalculationStatus.FAILED); + return false; + } + + // 创建用于计算的FK数据矩阵(RES_NUM行) + float[][] FKdataForCalc = new float[res_num][P]; + int copyRowsFK = Math.min(res_num, data.getFkData().length); + + logger.debug("创建用于计算的FK数据矩阵: {}x{}, 从原始数据复制{}行", + res_num, P, copyRowsFK); + + for (int i = 0; i < copyRowsFK; i++) { + for (int j = 0; j < P; j++) { + if (j < data.getFkData()[i].length) { + FKdataForCalc[i][j] = data.getFkData()[i][j]; + } + } + } + + + logger.debug("调用FK sumResponsibility参数: FKdata[{}x{}], Udata[{}], TL={}, width={}", + FKdataForCalc.length, FKdataForCalc.length > 0 ? FKdataForCalc[0].length : 0, + Udata.length, TL, width); + + try { + // 对应C代码第840行:arrHKsum = SumHK(FKdata, Udata, wdith, colK, TL); + float[] sumFK = ResponsibilityCalculator.sumResponsibility( + FKdataForCalc, // 使用新创建的RES_NUM行的FK数据 + Udata, // 使用相同的Udata(长度TL) + XIANE, + width, + P, + TL // 传入TL参数 + ); + data.setSumFKData(sumFK); + logger.debug("FK责任计算完成,结果长度: {}", sumFK != null ? sumFK.length : "null"); + } catch (Exception e) { + logger.error("FK责任计算失败: " + e.getMessage(), e); + throw e; + } + + // 5. 标记计算成功 - 对应C代码行858 + data.setCalculationStatus(CalculationStatus.CALCULATED); + logger.info("Partial calculation completed successfully"); + + return true; + } + + /** + * 初始化部分计算数据 + * 对应C代码中的data_init_part函数 + */ + private boolean initializePartialCalculationData(HarmonicData data) { + // 设置变量 - 对应C代码行762-766 + int RES_NUM = data.getResponsibilityDataCount(); + P = data.getPowerNodeCount(); + TL = data.getWindowSize() + RES_NUM; + width = data.getWindowSize(); + XIANE = data.getHarmonicThreshold(); + + // 验证数据 - 对应C代码行756-778 + if ((RES_NUM + width) != data.getHarmonicCount()) { + logger.error("Data length mismatch: res_num({}) + win({}) != harm_num({})", + RES_NUM, width, data.getHarmonicCount()); + return false; + } + + if (width < HarmonicConstants.MIN_WIN_LEN || width > HarmonicConstants.MAX_WIN_LEN) { + logger.error("Invalid window size: {}", width); + return false; + } + + if (P > HarmonicConstants.MAX_P_NODE || TL > HarmonicConstants.MAX_P_NUM) { + logger.error("Data size exceeds limits"); + return false; + } + + // 验证FK和HK数据存在 + if (data.getFkData() == null || data.getHkData() == null) { + logger.error("FK or HK data is null"); + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/ResponsibilityCalculator.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/ResponsibilityCalculator.java new file mode 100644 index 0000000..027b8de --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/calculator/ResponsibilityCalculator.java @@ -0,0 +1,429 @@ +package com.njcn.product.advance.responsility.calculator; + +import com.njcn.product.advance.responsility.analysis.CanonicalCorrelationAnalysis; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 责任指标计算类 + * 计算谐波责任的各项指标 + * 严格对应C代码实现 + * + * @author hongawen + * @version 2.0 - 修复版本,严格对照C代码实现 + */ +public class ResponsibilityCalculator { + + private static final Logger logger = LoggerFactory.getLogger(ResponsibilityCalculator.class); + + /** + * 计算EK值(动态责任指标) + * 严格对应C代码中的DyEKCom函数(行300-357) + * + * @param correlationData 动态相关系数矩阵 [时间][节点] + * @param powerData 功率数据矩阵 [时间][节点] + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @param dataLength 数据长度 + * @return EK值矩阵 + */ + public static float[][] computeEK(float[][] correlationData, float[][] powerData, + int windowSize, int nodeCount, int dataLength) { + int slideLength = dataLength - windowSize; + float[][] ekData = new float[slideLength][nodeCount]; + float[][] akData = new float[slideLength][nodeCount]; + + logger.info("Computing EK values, slide length: {}", slideLength); + + // 计算AK值 - 对应C代码行307-319 + for (int i = 0; i < slideLength; i++) { + float sumPower = 0; + + // 计算功率总和 - 对应C代码行309-313 + for (int j = 0; j < nodeCount; j++) { + sumPower += powerData[i][j]; // 注意:这里用的是powerData[i][j] + } + + // 计算AK值 - 对应C代码行314-318 + for (int j = 0; j < nodeCount; j++) { + if (sumPower > 0) { + akData[i][j] = correlationData[i][j] * (powerData[i][j] / sumPower); + } else { + akData[i][j] = 0; + } + } + } + + // 归一化处理得到EK值 - 对应C代码行320-342 + for (int i = 0; i < slideLength; i++) { + // 重要:C代码初始化为0,而不是Float.MIN_VALUE/MAX_VALUE + // 对应C代码行322-323 + float maxValue = 0; + float minValue = 0; + + // 找最大最小值 - 对应C代码行322-334 + for (int j = 0; j < nodeCount; j++) { + if (akData[i][j] > maxValue) { + maxValue = akData[i][j]; + } + if (akData[i][j] < minValue) { + minValue = akData[i][j]; + } + } + + float range = maxValue - minValue; + + // 归一化 - 对应C代码行338-341 + for (int j = 0; j < nodeCount; j++) { + if (Math.abs(range) > 1e-10) { + ekData[i][j] = (akData[i][j] - minValue) / range; + } else { + ekData[i][j] = 0; + } + } + } + + logger.info("EK computation completed"); + + return ekData; + } + + /** + * 计算FK值(不包含背景的责任指标) + * 严格对应C代码中的DyFKCom函数(行358-389) + * + * @param ekData EK值矩阵 + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @param dataLength 数据长度 + * @return FK值矩阵 + */ + public static float[][] computeFK(float[][] ekData, int windowSize, + int nodeCount, int dataLength) { + int slideLength = dataLength - windowSize; + float[][] fkData = new float[slideLength][nodeCount]; + + logger.info("Computing FK values"); + + // 对应C代码行364-376 + for (int i = 0; i < slideLength; i++) { + float sumEK = 0; + + // 计算EK总和 - 对应C代码行366-370 + for (int j = 0; j < nodeCount; j++) { + sumEK += ekData[i][j]; + } + + // 计算FK值(归一化)- 对应C代码行372-375 + for (int j = 0; j < nodeCount; j++) { + if (sumEK > 0) { + fkData[i][j] = ekData[i][j] / sumEK; + } else { + fkData[i][j] = 0; + } + } + } + + logger.info("FK computation completed"); + + return fkData; + } + + /** + * 计算HK值(包含背景的责任指标) + * 严格对应C代码中的DyHKCom函数(行390-429) + * + * @param backgroundCanCor 背景典则相关系数(1-典则相关系数) + * @param ekData EK值矩阵 + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @param dataLength 数据长度 + * @return HK值矩阵 + */ + public static float[][] computeHK(float[] backgroundCanCor, float[][] ekData, + int windowSize, int nodeCount, int dataLength) { + int slideLength = dataLength - windowSize; + float[][] hkData = new float[slideLength][nodeCount + 1]; + float[][] newEK = new float[slideLength][nodeCount + 1]; + + logger.info("Computing HK values"); + + // 构建包含背景的EK矩阵 - 对应C代码行396-403 + for (int i = 0; i < slideLength; i++) { + // 复制原有EK值 + for (int j = 0; j < nodeCount; j++) { + newEK[i][j] = ekData[i][j]; + } + // 添加背景值 + newEK[i][nodeCount] = backgroundCanCor[i]; + } + + // 计算HK值 - 对应C代码行405-416 + for (int i = 0; i < slideLength; i++) { + float sumEK = 0; + + // 计算总和 - 对应C代码行407-411 + for (int j = 0; j < nodeCount + 1; j++) { + sumEK += newEK[i][j]; + } + + // 归一化得到HK值 - 对应C代码行412-415 + for (int j = 0; j < nodeCount + 1; j++) { + if (sumEK > 0) { + hkData[i][j] = newEK[i][j] / sumEK; + } else { + hkData[i][j] = 0; + } + } + } + + logger.info("HK computation completed"); + + return hkData; + } + + /** + * 计算超限时段的责任总和 + * 严格对应C代码中的SumHK函数(行431-461) + * + * @param responsibilityData 责任数据矩阵(FK或HK)[时间][节点] + * @param harmonicData 谐波数据(Udata) - 长度为TL + * @param threshold 谐波门槛(XIANE) + * @param windowSize 窗口大小 + * @param columnCount 列数(节点数或节点数+1) + * @param tl_num 对应C代码的TL参数(总数据点数) + * @return 各节点的责任总和百分比 + */ + public static float[] sumResponsibility(float[][] responsibilityData, float[] harmonicData, + float threshold, int windowSize, int columnCount, int tl_num) { + // 对应C代码:int slg = tl_num - width; + int slideLength = tl_num - windowSize; // 使用传入的tl_num计算,而不是从responsibilityData.length推断 + float[] sumData = new float[columnCount]; // 对应C代码中的 arrHKsum + double[] HKSum = new double[columnCount]; // 对应C代码中的 VectorXd HKSum - 使用double精度 + int exceedCount = 0; // 对应C代码中的 coutt + + // ===== 添加详细调试日志 ===== + logger.info("======= 开始 sumResponsibility 计算 ======="); + logger.info("输入参数:"); + logger.info(" threshold(阈值): {}", threshold); + logger.info(" windowSize(窗口大小): {}", windowSize); + logger.info(" columnCount(列数): {}", columnCount); + logger.info(" tl_num(总数据长度): {}", tl_num); + logger.info(" slideLength(滑动长度): {}", slideLength); + logger.info(" responsibilityData维度: {}x{}", + responsibilityData != null ? responsibilityData.length : "null", + responsibilityData != null && responsibilityData.length > 0 ? responsibilityData[0].length : "null"); + logger.info(" harmonicData长度: {}", harmonicData != null ? harmonicData.length : "null"); + + // 数据验证 + if (harmonicData == null) { + logger.error("错误: harmonicData为null!"); + throw new NullPointerException("harmonicData不能为null"); + } + + if (responsibilityData == null) { + logger.error("错误: responsibilityData为null!"); + throw new NullPointerException("responsibilityData不能为null"); + } + + + // 关键验证:检查数组长度是否充足 + // C代码中Udata长度是TL,循环遍历slg=TL-width个元素 + logger.info("数据验证: slideLength={}, harmonicData.length={}, responsibilityData.length={}", + slideLength, harmonicData.length, responsibilityData.length); + + if (harmonicData.length < slideLength) { + logger.error("!!!谐波数据长度不足!!!"); + logger.error("需要访问harmonicData[0]到harmonicData[{}], 但数组长度只有{}", + slideLength - 1, harmonicData.length); + throw new IllegalArgumentException( + String.format("谐波数据长度不足: 需要%d, 实际%d", slideLength, harmonicData.length)); + } + + if (responsibilityData.length < slideLength) { + logger.error("!!!责任数据行数不足!!!"); + logger.error("需要访问responsibilityData[0]到responsibilityData[{}], 但数组长度只有{}", + slideLength - 1, responsibilityData.length); + throw new IllegalArgumentException( + String.format("责任数据行数不足: 需要%d, 实际%d", slideLength, responsibilityData.length)); + } + + // ===== 添加数据分布统计 ===== + logger.info("谐波数据分析:"); + float harmonicMin = Float.MAX_VALUE, harmonicMax = Float.MIN_VALUE; + double harmonicSum = 0; + int preliminaryExceedCount = 0; + for (int i = 0; i < Math.min(slideLength, harmonicData.length); i++) { + float val = harmonicData[i]; + harmonicMin = Math.min(harmonicMin, val); + harmonicMax = Math.max(harmonicMax, val); + harmonicSum += val; + if (val > threshold) { + preliminaryExceedCount++; + } + } + double harmonicAvg = harmonicSum / Math.min(slideLength, harmonicData.length); + logger.info(" 谐波数据范围: [{}, {}]", harmonicMin, harmonicMax); + logger.info(" 谐波数据平均值: {}", harmonicAvg); + logger.info(" 设定阈值: {}", threshold); + logger.info(" 初步统计超限个数: {}/{} ({:.2f}%)", + preliminaryExceedCount, Math.min(slideLength, harmonicData.length), + preliminaryExceedCount * 100.0 / Math.min(slideLength, harmonicData.length)); + + // ===== 责任数据分析 ===== + logger.info("责任数据分析(检查前5行的归一化情况):"); + for (int i = 0; i < Math.min(5, responsibilityData.length); i++) { + float rowSum = 0; + for (int j = 0; j < responsibilityData[i].length; j++) { + rowSum += responsibilityData[i][j]; + } + logger.info(" 第{}行和: {} (期望值: 1.0, 偏差: {})", i, rowSum, Math.abs(rowSum - 1.0f)); + } + + // 统计超限时段的责任 - 对应C代码行437-449 + // 重要:C代码中有一个设计缺陷:coutt在每个j循环中被重置, + // 但最后计算百分比时使用的是最后一次j循环的coutt值 + // 为了严格保持一致,我们也要复现这个逻辑 + logger.info("===== 开始循环计算每列的累加值 ====="); + int[] exceedCountPerColumn = new int[columnCount]; // 记录每列的超限次数,用于调试 + + for (int j = 0; j < columnCount; j++) { + HKSum[j] = 0; + exceedCount = 0; // 对应C代码行440: coutt = 0; + logger.info("开始计算第{}列 (共{}列)", j, columnCount); + + double columnSum = 0; // 用于调试 + int columnExceedCount = 0; // 用于调试 + + for (int i = 0; i < slideLength; i++) { + // 添加越界检查 + if (i >= harmonicData.length) { + logger.error("!!!数组越界!!! 尝试访问harmonicData[{}], 但数组长度只有{}", + i, harmonicData.length); + logger.error("发生在: j={}, i={}", j, i); + throw new ArrayIndexOutOfBoundsException( + String.format("访问harmonicData[%d]越界, 数组长度=%d", i, harmonicData.length)); + } + + // 对应C代码行443-447 + if (harmonicData[i] > threshold) { + double currentResponsibility = responsibilityData[i][j]; + HKSum[j] += currentResponsibility; // 对应C代码行445 + exceedCount++; // 对应C代码行446 + columnSum += currentResponsibility; + columnExceedCount++; + + // 只打印前几个超限情况的详细信息 + if (columnExceedCount <= 3) { + logger.info(" 时刻i={}: 谐波值={} > 阈值={}, 责任值={}, 累加到{}", + i, harmonicData[i], threshold, currentResponsibility, HKSum[j]); + } + } + } + + exceedCountPerColumn[j] = columnExceedCount; + logger.info("第{}列计算完成: 累加值={}, 超限次数={}", j, HKSum[j], columnExceedCount); + } + // 注意:这里exceedCount保留的是最后一列(j=columnCount-1)的超限次数 + // 这与C代码的行为一致 + + logger.info("===== 循环计算完成 ====="); + logger.info("最终exceedCount={} (来自最后一列的计算)", exceedCount); + logger.info("各列超限次数对比: {}", java.util.Arrays.toString(exceedCountPerColumn)); + logger.info("各列累加值: {}", java.util.Arrays.toString(HKSum)); + + // 计算平均责任百分比 - 对应C代码行453-459 + logger.info("===== 开始计算最终百分比 ====="); + for (int i = 0; i < columnCount; i++) { + sumData[i] = 0; // 对应C代码行454 + } + + double totalPercentage = 0; // 用于统计总和 + for (int i = 0; i < columnCount; i++) { + if (exceedCount > 0) { + // 对应C代码行458: arrHKsum[i] = 100 * (HKSum(i)/coutt); + // 使用double进行计算,然后转换为float + double percentage = 100.0 * (HKSum[i] / (double)exceedCount); + sumData[i] = (float)percentage; + totalPercentage += percentage; + + logger.info("节点{}: 累加值={}, 除以超限次数={}, 百分比={}%", + i, HKSum[i], exceedCount, percentage); + } else { + logger.warn("节点{}: 超限次数为0,百分比设为0", i); + } + } + + logger.info("===== 计算结果汇总 ====="); + logger.info("使用的超限次数(分母): {}", exceedCount); + logger.info("各节点百分比: {}", java.util.Arrays.toString(sumData)); + logger.info("百分比总和: {}% (期望100%)", totalPercentage); + logger.info("偏差: {}%", Math.abs(totalPercentage - 100.0)); + + if (Math.abs(totalPercentage - 100.0) > 1.0) { + logger.warn("!!!注意!!! 百分比总和偏离100%超过1%,可能存在问题"); + } + + logger.info("======= sumResponsibility 计算完成 ======="); + return sumData; + } + + /** + * 计算超限时段的责任总和(兼容版本) + * 为了向后兼容,保留不带tl_num参数的版本 + * + * @param responsibilityData 责任数据矩阵(FK或HK)[时间][节点] + * @param harmonicData 谐波数据(Udata) + * @param threshold 谐波门槛(XIANE) + * @param windowSize 窗口大小 + * @param columnCount 列数(节点数或节点数+1) + * @return 各节点的责任总和百分比 + */ + public static float[] sumResponsibility(float[][] responsibilityData, float[] harmonicData, + float threshold, int windowSize, int columnCount) { + // 如果没有提供tl_num,从数据推断 + int tl_num = responsibilityData.length + windowSize; + return sumResponsibility(responsibilityData, harmonicData, threshold, windowSize, columnCount, tl_num); + } + + /** + * 计算所有节点的动态相关系数矩阵 + * 这个函数在主引擎中已经内联实现,这里保留作为辅助方法 + * + * @param powerData 功率数据矩阵 + * @param harmonicData 谐波数据 + * @param canonicalCorr 典则相关系数序列 + * @param windowSize 窗口大小 + * @param nodeCount 节点数量 + * @return 动态相关系数矩阵 + */ + public static float[][] computeCorrelationMatrix(float[][] powerData, float[] harmonicData, + float[] canonicalCorr, int windowSize, + int nodeCount) { + int slideLength = canonicalCorr.length; + float[][] correlationMatrix = new float[slideLength][nodeCount]; + + logger.info("Computing correlation matrix for all nodes"); + + for (int nodeIdx = 0; nodeIdx < nodeCount; nodeIdx++) { + // 提取单个节点的功率数据 + float[] nodePower = new float[powerData.length]; + for (int i = 0; i < powerData.length; i++) { + nodePower[i] = powerData[i][nodeIdx]; + } + + // 计算该节点的动态相关系数 + float[] nodeCorr = CanonicalCorrelationAnalysis + .slidingCorrelation(nodePower, harmonicData, canonicalCorr, windowSize); + + // 存储结果 + for (int i = 0; i < slideLength; i++) { + correlationMatrix[i][nodeIdx] = nodeCorr[i]; + } + } + + logger.info("Correlation matrix computation completed"); + + return correlationMatrix; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/HistoryHarmonicController.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/HistoryHarmonicController.java new file mode 100644 index 0000000..0a0f00d --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/HistoryHarmonicController.java @@ -0,0 +1,68 @@ +package com.njcn.product.advance.responsility.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.influx.pojo.dto.HarmHistoryDataDTO; +import com.njcn.product.advance.harmonicUp.pojo.param.HistoryParam; +import com.njcn.product.advance.harmonicUp.pojo.vo.HistoryDataResultVO; +import com.njcn.product.advance.harmonicUp.service.HistoryResultService; +import com.njcn.product.advance.responsility.pojo.param.HistoryHarmParam; +import com.njcn.product.advance.eventSource.service.HistoryHarmonicService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-08 + * @Description: + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/harmonic") +@Api(tags = "稳态数据分析") +@RequiredArgsConstructor +public class HistoryHarmonicController extends BaseController { + + private final HistoryHarmonicService historyHarmonicService; + + private final HistoryResultService historyResultService; + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getHistoryHarmData") + @ApiOperation("获取谐波历史数据") + @ApiImplicitParam(name = "historyHarmParam", value = "谐波历史数据请求参数", required = true) + public HttpResult getHistoryHarmData(@RequestBody @Validated HistoryHarmParam historyHarmParam) { + String methodDescribe = getMethodDescribe("getHistoryHarmData"); + HarmHistoryDataDTO harmHistoryDataDTO = historyHarmonicService.getHistoryHarmData(historyHarmParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, harmHistoryDataDTO, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getHistoryResult") + @ApiOperation("稳态数据分析") + @ApiImplicitParam(name = "historyParam", value = "稳态数据分析参数", required = true) + public HttpResult> getHistoryResult(@RequestBody @Validated HistoryParam historyParam) { + String methodDescribe = getMethodDescribe("getHistoryResult"); + List list = historyResultService.getHistoryResult(historyParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/ResponsibilityController.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/ResponsibilityController.java new file mode 100644 index 0000000..a8dbb8a --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/ResponsibilityController.java @@ -0,0 +1,114 @@ +package com.njcn.product.advance.responsility.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; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.product.advance.responsility.pojo.dto.RespDataDTO; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.param.RespBaseParam; +import com.njcn.product.advance.responsility.pojo.param.ResponsibilityCalculateParam; +import com.njcn.product.advance.responsility.pojo.param.ResponsibilitySecondCalParam; +import com.njcn.product.advance.responsility.service.IRespDataResultService; +import com.njcn.product.advance.responsility.service.IRespDataService; +import com.njcn.web.controller.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:06 + */ +@RestController +@RequestMapping("responsibility") +@Api(tags = "谐波责任划分-谐波责任数据处理") +@RequiredArgsConstructor +public class ResponsibilityController extends BaseController { + + private final IRespDataService respDataService; + + private final IRespDataResultService respDataResultService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/responsibilityList") + @ApiOperation("查询责任划分列表分页") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> responsibilityList(@RequestBody @Validated RespBaseParam queryParam) { + String methodDescribe = getMethodDescribe("responsibilityList"); + Page list = respDataService.responsibilityList(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/deleteByIds") + @ApiOperation("删除责任划分数据") + @ApiImplicitParam(name = "ids", value = "待删除的责任id集合", required = true) + public HttpResult> deleteByIds(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("deleteByIds"); + respDataService.deleteByIds(ids); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + + @PostMapping("getDynamicData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("动态谐波责任划分") + @ApiImplicitParam(name = "responsibilityCalculateParam", value = "谐波责任动态划分参数", required = true) + public HttpResult getDynamicData(@RequestBody @Validated ResponsibilityCalculateParam responsibilityCalculateParam) { + String methodDescribe = getMethodDescribe("getDynamicData"); + ResponsibilityResult datas = respDataService.getDynamicData(responsibilityCalculateParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, datas, methodDescribe); + } + + @PostMapping("getResponsibilityData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("二次计算责任划分") + @ApiImplicitParam(name = "responsibilitySecondCalParam", value = "二次计算责任划分参数", required = true) + public HttpResult getResponsibilityData(@RequestBody @Validated ResponsibilitySecondCalParam responsibilitySecondCalParam) { + String methodDescribe = getMethodDescribe("getResponsibilityData"); + ResponsibilityResult datas = respDataService.getResponsibilityData(responsibilitySecondCalParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, datas, methodDescribe); + } + + + @GetMapping("displayHistoryData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("回显历史责任划分结果") + @ApiImplicitParam(name = "id", value = "责任数据id", required = true) + public HttpResult> displayHistoryData(String id,Integer time) { + String methodDescribe = getMethodDescribe("displayHistoryData"); + List datas = respDataResultService.displayHistoryData(id,time); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, datas, methodDescribe); + } + + + + @PostMapping("systemDynamicData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("动态谐波责任划分") + @ApiImplicitParam(name = "responsibilityCalculateParam", value = "谐波责任动态划分参数", required = true) + public HttpResult systemDynamicData(@RequestBody @Validated ResponsibilityCalculateParam responsibilityCalculateParam) { + String methodDescribe = getMethodDescribe("getDynamicData"); + ResponsibilityResult datas = respDataService.getDynamicData(responsibilityCalculateParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, datas, methodDescribe); + } + + + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/UserDataController.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/UserDataController.java new file mode 100644 index 0000000..fd9acc4 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/controller/UserDataController.java @@ -0,0 +1,114 @@ +package com.njcn.product.advance.responsility.controller; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.dto.SelectOption; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.product.advance.responsility.pojo.dto.RespDataDTO; +import com.njcn.product.advance.responsility.pojo.param.UserDataIntegrityParam; +import com.njcn.product.advance.responsility.pojo.po.RespUserData; +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; +import com.njcn.product.advance.responsility.service.IRespUserDataIntegrityService; +import com.njcn.product.advance.responsility.service.IRespUserDataService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月13日 14:11 + */ +@RestController +@RequestMapping("responsibility") +@Api(tags = "谐波责任划分-用采数据处理") +@RequiredArgsConstructor +public class UserDataController extends BaseController { + + + private final IRespUserDataService respUserDataService; + + private final IRespUserDataIntegrityService respUserDataIntegrityService; + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/userDataList") + @ApiOperation("查询用户列表分页") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> userDataList(@RequestBody @Validated BaseParam queryParam) { + String methodDescribe = getMethodDescribe("userDataList"); + Page list = respUserDataService.userDataList(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/userDataIntegrityList") + @ApiOperation("用采完整性不足列表") + @ApiImplicitParam(name = "userDataIntegrityParam", value = "查询参数", required = true) + public HttpResult> userDataIntegrityList(@RequestBody @Validated UserDataIntegrityParam userDataIntegrityParam) { + String methodDescribe = getMethodDescribe("userDataIntegrityList"); + Page list = respUserDataIntegrityService.userDataIntegrityList(userDataIntegrityParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/deleteUserDataByIds") + @ApiOperation("删除用采数据") + @ApiImplicitParam(name = "ids", value = "待删除用采数据id集合", required = true) + public HttpResult> deleteUserDataByIds(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("deleteUserDataByIds"); + respUserDataService.deleteUserDataByIds(ids); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @GetMapping("/userDataSelect") + @ApiOperation("用采数据下拉") + public HttpResult> userDataSelect() { + String methodDescribe = getMethodDescribe("userDataSelect"); + List listOption = respUserDataService.userDataSelect(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, listOption, methodDescribe); + } + + /** + * 上传用采数据,并对用采数据进行数据分析并缓存 + * + * @param file 上传的表格 + */ + @PostMapping("uploadUserData") + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("上传用采数据") + public HttpResult uploadUserData(@ApiParam(value = "文件", required = true) @RequestPart("file") MultipartFile file, HttpServletResponse response) { + String methodDescribe = getMethodDescribe("uploadUserData"); + String fileName = file.getOriginalFilename(); + long fileSize = file.getSize() / 1024; + //判断文件大小 + if (fileSize > 3072) { + throw new BusinessException(CommonResponseEnum.FILE_SIZE_ERROR); + } + assert fileName != null; + if (!fileName.matches("^.+\\.(?i)(xlsx)$") && !fileName.matches("^.+\\.(?i)(xls)$")) { + throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR); + } + respUserDataService.uploadUserData(file, response); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/imapper/DataHarmP.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/imapper/DataHarmP.java new file mode 100644 index 0000000..283b719 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/imapper/DataHarmP.java @@ -0,0 +1,30 @@ +package com.njcn.product.advance.responsility.imapper; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.njcn.influx.ano.IgnoreData; +import com.njcn.influx.utils.InstantDateDeserializer; +import com.njcn.influx.utils.InstantDateSerializer; +import lombok.Data; +import org.influxdb.annotation.Column; + +import java.time.Instant; + +/** + * @Author: cdf + * @CreateTime: 2025-09-18 + * @Description: + */ +@Data +public class DataHarmP { + @Column(name = "time") + @JsonSerialize(using = InstantDateSerializer.class) + @JsonDeserialize(using = InstantDateDeserializer.class) + private Instant time; + + @Column(name = "line_id") + private String lineId; + + @IgnoreData(true) + private Float value; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataMapper.java new file mode 100644 index 0000000..0b36de1 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataMapper.java @@ -0,0 +1,26 @@ +package com.njcn.product.advance.responsility.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.advance.responsility.pojo.dto.RespDataDTO; +import com.njcn.product.advance.responsility.pojo.po.RespData; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2023-07-21 + */ +public interface RespDataMapper extends BaseMapper { + + Page page(@Param("page") Page objectPage, @Param("ew")QueryWrapper queryWrapper); + + void deleteByIds(@Param("ids") List ids); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataResultMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataResultMapper.java new file mode 100644 index 0000000..69ceb23 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespDataResultMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.advance.responsility.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.advance.responsility.pojo.po.RespDataResult; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2023-07-24 + */ +public interface RespDataResultMapper extends BaseMapper { + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataIntegrityMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataIntegrityMapper.java new file mode 100644 index 0000000..45d739f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataIntegrityMapper.java @@ -0,0 +1,20 @@ +package com.njcn.product.advance.responsility.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; +import org.apache.ibatis.annotations.Param; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +public interface RespUserDataIntegrityMapper extends BaseMapper { + + Page page(@Param("page") Page objectPage, @Param("ew") QueryWrapper lambdaQueryWrapper); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataMapper.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataMapper.java new file mode 100644 index 0000000..8aaf7ab --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/RespUserDataMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.advance.responsility.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.advance.responsility.pojo.po.RespUserData; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +public interface RespUserDataMapper extends BaseMapper { + + Page page(@Param("page")Page objectPage, @Param("ew")QueryWrapper respUserDataQueryWrapper); + + void deleteUserDataByIds(@Param("ids") List ids); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataMapper.xml new file mode 100644 index 0000000..17ffb84 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataMapper.xml @@ -0,0 +1,26 @@ + + + + + + + + update + pqs_resp_data + set state = 0 + where + id + in + + #{item} + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataResultMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataResultMapper.xml new file mode 100644 index 0000000..7d2127c --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespDataResultMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataIntegrityMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataIntegrityMapper.xml new file mode 100644 index 0000000..ed8eb5f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataIntegrityMapper.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataMapper.xml b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataMapper.xml new file mode 100644 index 0000000..306c59e --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/mapper/mapping/RespUserDataMapper.xml @@ -0,0 +1,24 @@ + + + + + + + + update + pqs_resp_user_data + set state = 0 + where + id + in + + #{item} + + + + + diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/CacheQvvrData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/CacheQvvrData.java new file mode 100644 index 0000000..246e38e --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/CacheQvvrData.java @@ -0,0 +1,47 @@ +package com.njcn.product.advance.responsility.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.List; + +/** + * 当根据动态责任数据获取用户责任量化结果时,将需要的一些参数进行缓存 + * 比如 harmNum,pNode,HKData,FKData,HarmData,监测点的测量间隔,win窗口,最小公倍数 + * 以及FKData每个时间点的p对应的用户List + * + * @author hongawen + * @Date: 2019/4/29 16:06 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CacheQvvrData implements Serializable { + + private int pNode; + + private int harmNum; + + private float[] harmData; + + private float[][] fKData; + + private float[][] hKData; + + private List names; + + private int lineInterval; + + private int win; + + //最小公倍数 + private int minMultiple; + + //横轴时间 + private List times; + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HIKSDKStructure.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HIKSDKStructure.java new file mode 100644 index 0000000..fc82168 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HIKSDKStructure.java @@ -0,0 +1,33 @@ +package com.njcn.product.advance.responsility.model; + + +import com.sun.jna.Structure; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * @author: tw + * @date: 2022/1/12 10:57 + */ +public class HIKSDKStructure extends Structure { + protected List getFieldOrder(){ + List fieldOrderList = new ArrayList(); + for (Class cls = getClass(); + !cls.equals(HIKSDKStructure.class); + cls = cls.getSuperclass()) { + Field[] fields = cls.getDeclaredFields(); + int modifiers; + for (Field field : fields) { + modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) { + continue; + } + fieldOrderList.add(field.getName()); + } + } + return fieldOrderList; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HKDataStruct.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HKDataStruct.java new file mode 100644 index 0000000..00bb3a1 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HKDataStruct.java @@ -0,0 +1,37 @@ +package com.njcn.product.advance.responsility.model; + +import com.sun.jna.Structure; + +import java.io.Serializable; +import java.util.Collections; +import java.util.List; + +public class HKDataStruct extends Structure implements Serializable { + public float hk[] = new float[QvvrStruct.MAX_P_NODE + 1]; + + public HKDataStruct() { + } + + @Override + protected List getFieldOrder() { + return Collections.singletonList("hk"); + } + + public HKDataStruct(double[] hk) { + for (int i = 0; i < hk.length; i++) { + this.hk[i] = (float) hk[i]; + } + } + + public static class ByReference extends HKDataStruct implements Structure.ByReference { + public ByReference(double[] p) { + super(p); + } + } + + public static class ByValue extends HKDataStruct implements Structure.ByValue { + public ByValue(double[] p) { + super(p); + } + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HarmonicData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HarmonicData.java new file mode 100644 index 0000000..9df294b --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/HarmonicData.java @@ -0,0 +1,287 @@ +package com.njcn.product.advance.responsility.model; + + +import com.njcn.product.advance.responsility.pojo.constant.CalculationMode; +import com.njcn.product.advance.responsility.pojo.constant.CalculationStatus; +import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants; + +/** + * 谐波数据结构类 + * 对应C语言中的harm_data_struct结构体 + * + * @author hongawen + * @version 1.0 + */ +public class HarmonicData { + + // 输入参数 + private CalculationMode calculationMode; // 计算标志 + private int harmonicCount; // 谐波数据个数 + private int powerCount; // 功率数据个数 + private int powerNodeCount; // 功率负荷节点数 + private int windowSize; // 数据窗大小 + private int responsibilityDataCount; // 代入的责任数据个数 + private float harmonicThreshold; // 谐波电压门槛 + + // 数据数组 + private float[] harmonicData; // 谐波数据序列 + private float[][] powerData; // 功率数据序列 + + // 输入输出数据 + private float[][] correlationData; // 动态相关系数数据序列 + private float[][] fkData; // 不包含背景动态谐波责任数据序列 + private float[][] hkData; // 包含背景动态谐波责任数据序列 + private float[] canonicalCorrelation; // 典则相关系数 + private float[] backgroundCanonicalCorr; // 包含背景典则相关系数 + + // 输出结果 + private CalculationStatus calculationStatus; // 计算状态 + private float[] sumFKData; // 不包含背景谐波责任 + private float[] sumHKData; // 包含背景谐波责任 + + /** + * 默认构造函数 + */ + public HarmonicData() { + this.calculationMode = CalculationMode.FULL_CALCULATION; + this.calculationStatus = CalculationStatus.NOT_CALCULATED; + this.windowSize = HarmonicConstants.DEFAULT_WINDOW_SIZE; + } + + /** + * Builder模式构造器 + */ + public static class Builder { + private HarmonicData data = new HarmonicData(); + + public Builder calculationMode(CalculationMode mode) { + data.calculationMode = mode; + return this; + } + + public Builder harmonicCount(int count) { + data.harmonicCount = count; + return this; + } + + public Builder powerCount(int count) { + data.powerCount = count; + return this; + } + + public Builder powerNodeCount(int count) { + data.powerNodeCount = count; + return this; + } + + public Builder windowSize(int size) { + data.windowSize = size; + return this; + } + + public Builder harmonicThreshold(float threshold) { + data.harmonicThreshold = threshold; + return this; + } + + public Builder harmonicData(float[] data) { + this.data.harmonicData = data; + return this; + } + + public Builder powerData(float[][] data) { + this.data.powerData = data; + return this; + } + + public HarmonicData build() { + // 验证数据 + validateData(); + // 初始化数组 + initializeArrays(); + return data; + } + + private void validateData() { + if (data.harmonicCount <= 0 || data.harmonicCount > HarmonicConstants.MAX_HARM_NUM) { + throw new IllegalArgumentException("Invalid harmonic count: " + data.harmonicCount); + } + if (data.powerCount <= 0 || data.powerCount > HarmonicConstants.MAX_P_NUM) { + throw new IllegalArgumentException("Invalid power count: " + data.powerCount); + } + if (data.powerNodeCount <= 0 || data.powerNodeCount > HarmonicConstants.MAX_P_NODE) { + throw new IllegalArgumentException("Invalid power node count: " + data.powerNodeCount); + } + if (data.windowSize < HarmonicConstants.MIN_WIN_LEN || + data.windowSize > HarmonicConstants.MAX_WIN_LEN) { + throw new IllegalArgumentException("Invalid window size: " + data.windowSize); + } + + // 验证数据对齐 + if (data.calculationMode == CalculationMode.FULL_CALCULATION) { + int ratio = data.harmonicCount / data.powerCount; + if (ratio * data.powerCount != data.harmonicCount || ratio < 1) { + throw new IllegalArgumentException("Harmonic data count must be integer multiple of power data count"); + } + } + } + + private void initializeArrays() { + if (data.harmonicData == null) { + data.harmonicData = new float[data.harmonicCount]; + } + if (data.powerData == null) { + data.powerData = new float[data.powerCount][data.powerNodeCount]; + } + + int resultCount = data.powerCount - data.windowSize; + if (resultCount > 0) { + data.correlationData = new float[resultCount][data.powerNodeCount]; + data.fkData = new float[resultCount][data.powerNodeCount]; + data.hkData = new float[resultCount][data.powerNodeCount + 1]; + data.canonicalCorrelation = new float[resultCount]; + data.backgroundCanonicalCorr = new float[resultCount]; + } + + data.sumFKData = new float[data.powerNodeCount]; + data.sumHKData = new float[data.powerNodeCount + 1]; + } + } + + // Getters and Setters + public CalculationMode getCalculationMode() { + return calculationMode; + } + + public void setCalculationMode(CalculationMode calculationMode) { + this.calculationMode = calculationMode; + } + + public int getHarmonicCount() { + return harmonicCount; + } + + public void setHarmonicCount(int harmonicCount) { + this.harmonicCount = harmonicCount; + } + + public int getPowerCount() { + return powerCount; + } + + public void setPowerCount(int powerCount) { + this.powerCount = powerCount; + } + + public int getPowerNodeCount() { + return powerNodeCount; + } + + public void setPowerNodeCount(int powerNodeCount) { + this.powerNodeCount = powerNodeCount; + } + + public int getWindowSize() { + return windowSize; + } + + public void setWindowSize(int windowSize) { + this.windowSize = windowSize; + } + + public int getResponsibilityDataCount() { + return responsibilityDataCount; + } + + public void setResponsibilityDataCount(int responsibilityDataCount) { + this.responsibilityDataCount = responsibilityDataCount; + } + + public float getHarmonicThreshold() { + return harmonicThreshold; + } + + public void setHarmonicThreshold(float harmonicThreshold) { + this.harmonicThreshold = harmonicThreshold; + } + + public float[] getHarmonicData() { + return harmonicData; + } + + public void setHarmonicData(float[] harmonicData) { + this.harmonicData = harmonicData; + } + + public float[][] getPowerData() { + return powerData; + } + + public void setPowerData(float[][] powerData) { + this.powerData = powerData; + } + + public float[][] getCorrelationData() { + return correlationData; + } + + public void setCorrelationData(float[][] correlationData) { + this.correlationData = correlationData; + } + + public float[][] getFkData() { + return fkData; + } + + public void setFkData(float[][] fkData) { + this.fkData = fkData; + } + + public float[][] getHkData() { + return hkData; + } + + public void setHkData(float[][] hkData) { + this.hkData = hkData; + } + + public float[] getCanonicalCorrelation() { + return canonicalCorrelation; + } + + public void setCanonicalCorrelation(float[] canonicalCorrelation) { + this.canonicalCorrelation = canonicalCorrelation; + } + + public float[] getBackgroundCanonicalCorr() { + return backgroundCanonicalCorr; + } + + public void setBackgroundCanonicalCorr(float[] backgroundCanonicalCorr) { + this.backgroundCanonicalCorr = backgroundCanonicalCorr; + } + + public CalculationStatus getCalculationStatus() { + return calculationStatus; + } + + public void setCalculationStatus(CalculationStatus calculationStatus) { + this.calculationStatus = calculationStatus; + } + + public float[] getSumFKData() { + return sumFKData; + } + + public void setSumFKData(float[] sumFKData) { + this.sumFKData = sumFKData; + } + + public float[] getSumHKData() { + return sumHKData; + } + + public void setSumHKData(float[] sumHKData) { + this.sumHKData = sumHKData; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/PDataStruct.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/PDataStruct.java new file mode 100644 index 0000000..d9c9555 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/PDataStruct.java @@ -0,0 +1,55 @@ +package com.njcn.product.advance.responsility.model; + +import com.sun.jna.Structure; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + + +public class PDataStruct extends Structure implements Serializable { + public float p[] = new float[QvvrStruct.MAX_P_NODE]; + + public PDataStruct() { + } + + @Override + protected List getFieldOrder() { +// return null; + return Collections.singletonList("p"); + } + + public PDataStruct(double[] p) { + for (int i = 0; i < p.length; i++) { + this.p[i] = (float) p[i]; + } + } + + public static class ByReference extends PDataStruct implements Structure.ByReference { + public ByReference(double[] p) { + super(p); + } + } + + public static class ByValue extends PDataStruct implements Structure.ByValue { + public ByValue(double[] p) { + super(p); + } + } + + public float[] getP() { + return p; + } + + public void setP(float[] p) { + this.p = p; + } + + @Override + public String toString() { + return "PDataStruct{" + + "p=" + Arrays.toString(p) + + '}'; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrDataEntity.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrDataEntity.java new file mode 100644 index 0000000..ce1ba8d --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrDataEntity.java @@ -0,0 +1,54 @@ +package com.njcn.product.advance.responsility.model; + + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class QvvrDataEntity implements Serializable { + + public static final int MAX_P_NODE= 200; //功率节点个数限制,按200个限制 + public static final int MAX_P_NUM= 96 * 100; //功率数据按15分钟间隔,100天处理 + public static final int MAX_HARM_NUM= 1440 * 100; //谐波数据按一分钟间隔,100天处理 + public static final int MAX_WIN_LEN=96 * 10; //按15分钟算10天 + public static final int MIN_WIN_LEN = 4; //按15分钟算1小时 + + + //输入参数 + public int calFlag; //计算标志,0默认用电压和功率数据计算相关系数和责任,1用代入的动态相关系数计算责任 + public int harmNum; //谐波数据个数 + public int pNum; //功率数据个数 + public int pNode; //功率负荷节点数 + public int win; //数据窗大小 + public int resNum; //代入的责任数据个数 + public float harmMk; //谐波电压门槛 + public float harmData[]; //谐波数据序列 + public float [][] pData; //功率数据序列 + public float [][] simData; //动态相关系数数据序列,可作为输入或者输出 + public float [][] fKData; //不包含背景动态谐波责任数据序列,可作为输入或者输出 + public float [][] hKData; //包含背景动态谐波责任数据序列,可作为输入或者输出 + public float [] core; //典则相关系数 + public float [] bjCore; //包含背景典则相关系数 + + //输出结果 + public int calOk; //是否计算正确标志,置位0表示未计算,置位1表示计算完成 + public float [] sumFKdata;//不包含背景谐波责任 + public float [] sumHKdata;//包含背景谐波责任 + + public QvvrDataEntity() { + calFlag = 0; + harmData = new float[MAX_HARM_NUM]; + pData = new float[MAX_P_NUM][MAX_P_NODE]; + simData = new float[MAX_P_NUM][MAX_P_NODE]; + fKData = new float[MAX_P_NUM][MAX_P_NODE]; + hKData = new float[MAX_P_NUM][MAX_P_NODE+1]; + core = new float[MAX_P_NUM]; + bjCore = new float[MAX_P_NUM]; + sumFKdata = new float[MAX_P_NODE]; + sumHKdata = new float[MAX_P_NODE + 1]; + } + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrStruct.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrStruct.java new file mode 100644 index 0000000..7426426 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/model/QvvrStruct.java @@ -0,0 +1,205 @@ +package com.njcn.product.advance.responsility.model; + +import com.sun.jna.Structure; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; + +public class QvvrStruct extends HIKSDKStructure implements Serializable { + public static final int MAX_P_NODE = 200; //功率节点个数限制,按200个限制 + public static final int MAX_P_NUM = 96 * 100; //功率数据按15分钟间隔,100天处理 + public static final int MAX_HARM_NUM = 1440 * 100; //谐波数据按一分钟间隔,100天处理 + public static final int MAX_WIN_LEN = 96 * 10; //按15分钟算10天 + public static final int MIN_WIN_LEN = 4; //按15分钟算1小时 + + + //输入参数 + public int cal_flag; //计算标志,0默认用电压和功率数据计算相关系数和责任,1用代入的动态相关系数计算责任 + public int harm_num; //谐波数据个数 + public int p_num; //功率数据个数 + public int p_node; //功率负荷节点数 + public int win; //数据窗大小 + public int res_num; //代入的责任数据个数 + public float harm_mk; //谐波电压门槛 + public float harm_data[]; //谐波数据序列 + public PDataStruct p_data[]; //功率数据序列 + public PDataStruct sim_data[]; //动态相关系数数据序列,可作为输入或者输出 + public PDataStruct FKdata[]; //不包含背景动态谐波责任数据序列,可作为输入或者输出 + public HKDataStruct HKdata[]; //包含背景动态谐波责任数据序列,可作为输入或者输出 + public float Core[]; //典则相关系数 + public float BjCore[]; //包含背景典则相关系数 + + //输出结果 + public int cal_ok; //是否计算正确标志,置位0表示未计算,置位1表示计算完成 + public float sumFKdata[];//不包含背景谐波责任 + public float sumHKdata[];//包含背景谐波责任 + + public QvvrStruct() { + cal_flag = 0; + harm_data = new float[MAX_HARM_NUM]; + p_data = new PDataStruct[MAX_P_NUM]; + sim_data = new PDataStruct[MAX_P_NUM]; + FKdata = new PDataStruct[MAX_P_NUM]; + HKdata = new HKDataStruct[MAX_P_NUM]; + Core = new float[MAX_P_NUM]; + BjCore = new float[MAX_P_NUM]; + sumFKdata = new float[MAX_P_NODE]; + sumHKdata = new float[MAX_P_NODE + 1]; + } + + public static class ByReference extends QvvrStruct implements Structure.ByReference { + + } + + public static class ByValue extends QvvrStruct implements Structure.ByValue { + + } + + + public PDataStruct[] getFKdata() { + return FKdata; + } + + public void setFKdata(PDataStruct[] FKdata) { + this.FKdata = FKdata; + } + + public HKDataStruct[] getHKdata() { + return HKdata; + } + + public void setHKdata(HKDataStruct[] HKdata) { + this.HKdata = HKdata; + } + + public float[] getSumFKdata() { + return sumFKdata; + } + + public void setSumFKdata(float[] sumFKdata) { + this.sumFKdata = sumFKdata; + } + + public float[] getSumHKdata() { + return sumHKdata; + } + + public void setSumHKdata(float[] sumHKdata) { + this.sumHKdata = sumHKdata; + } + + public int getCal_flag() { + return cal_flag; + } + + public void setCal_flag(int cal_flag) { + this.cal_flag = cal_flag; + } + + public int getHarm_num() { + return harm_num; + } + + public void setHarm_num(int harm_num) { + this.harm_num = harm_num; + } + + public float getHarm_mk() { + return harm_mk; + } + + public void setHarm_mk(float harm_mk) { + this.harm_mk = harm_mk; + } + + public float[] getHarm_data() { + return harm_data; + } + + public void setHarm_data(float[] harm_data) { + this.harm_data = harm_data; + } + + public float[] getCore() { + return Core; + } + + public void setCore(float[] core) { + Core = core; + } + + public float[] getBjCore() { + return BjCore; + } + + public void setBjCore(float[] bjCore) { + BjCore = bjCore; + } + + public int getCal_ok() { + return cal_ok; + } + + public void setCal_ok(int cal_ok) { + this.cal_ok = cal_ok; + } + + public int getP_num() { + return p_num; + } + + public void setP_num(int p_num) { + this.p_num = p_num; + } + + public int getP_node() { + return p_node; + } + + public void setP_node(int p_node) { + this.p_node = p_node; + } + + public int getWin() { + return win; + } + + public void setWin(int win) { + this.win = win; + } + + public int getRes_num() { + return res_num; + } + + public void setRes_num(int res_num) { + this.res_num = res_num; + } + + public PDataStruct[] getP_data() { + return p_data; + } + + public void setP_data(PDataStruct[] p_data) { + this.p_data = p_data; + } + + public PDataStruct[] getSim_data() { + return sim_data; + } + + public void setSim_data(PDataStruct[] sim_data) { + this.sim_data = sim_data; + } + + @Override + protected List getFieldOrder() { + return Arrays.asList( + "cal_flag", "harm_num", "p_num", "p_node", "win", + "res_num", "harm_mk", "harm_data", "p_data", "sim_data", + "FKdata", "HKdata", "Core", "BjCore", "cal_ok", + "sumFKdata", + "sumHKdata"); + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealDataResult.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealDataResult.java new file mode 100644 index 0000000..dff5a23 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealDataResult.java @@ -0,0 +1,37 @@ +package com.njcn.product.advance.responsility.pojo.bo; + + +import lombok.Data; + +import java.io.Serializable; +import java.util.*; + +/** + * 处理用采原始数据得到的一个结果 + * + * @author hongawen + * @Date: 2019/4/26 15:57 + */ +@Data +public class DealDataResult implements Serializable { + + /*** + * String 户号@监测点号@户名 + * String yyyy-MM-dd + * Date 数据的详细日期 + * UserDataExcel 数据详细信息 + * 先以测量局号分组,再以该测量局号下每个日期分组 + */ + private Map>> totalData = new HashMap<>(); + + private List dates = new ArrayList<>(); + + /*** + * String 户号@监测点号@户名 + * String yyyy-MM-dd + * UserDataExcel 数据详细信息 + * 先以测量局号分组,再以该测量局号下每个日期分组 + */ + private Map>> totalListData = new HashMap<>(); + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealUserDataResult.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealUserDataResult.java new file mode 100644 index 0000000..2376341 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/DealUserDataResult.java @@ -0,0 +1,31 @@ +package com.njcn.product.advance.responsility.pojo.bo; + + +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 针对天处理用采数据的结果实体 + * @author hongawen + * @Date: 2019/4/19 14:38 + */ +@Data +public class DealUserDataResult implements Serializable { + + //处理好的数据 + private List completed = new ArrayList<>(); + + //因当日完整性不足90,没有处理直接返回 + private List lack = new ArrayList<>(); + + //完整性不足时,用户信息描述 + private String detail; + + //完整性不足的具体信息 + private RespUserDataIntegrity respUserDataIntegrity; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespCommon.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespCommon.java new file mode 100644 index 0000000..302de45 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespCommon.java @@ -0,0 +1,25 @@ +package com.njcn.product.advance.responsility.pojo.bo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月28日 11:32 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class RespCommon implements Serializable { + + private int pNum; + + private int userIntervalTime; + + private int lineInterval; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespHarmData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespHarmData.java new file mode 100644 index 0000000..ae00208 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/RespHarmData.java @@ -0,0 +1,25 @@ +package com.njcn.product.advance.responsility.pojo.bo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月28日 11:38 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class RespHarmData implements Serializable { + + private float[] harmData; + + private List harmTime; + + private float overLimit; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/UserDataExcel.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/UserDataExcel.java new file mode 100644 index 0000000..2720573 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/bo/UserDataExcel.java @@ -0,0 +1,46 @@ +package com.njcn.product.advance.responsility.pojo.bo; + +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 提取用采数据或者将用采数据写进excel的实体类 + * + * @author hongawen + * @date 2019/4/11 10:43 + */ +@Data +public class UserDataExcel implements Serializable, Comparable { + + @Excel(name = "时间") + private String time; + + @Excel(name = "瞬时功率") + private BigDecimal work; + + @Excel(name = "户号") + private String userId; + + @Excel(name = "测量点局号") + private String line; + + @Excel(name = "户名") + private String userName; + + + @Override + public int compareTo(UserDataExcel o) { + + if (DateUtil.parse(this.time, DatePattern.NORM_DATETIME_PATTERN).getTime() > DateUtil.parse(o.getTime(), DatePattern.NORM_DATETIME_PATTERN).getTime()) { + return 1; + } else if (DateUtil.parse(this.time, DatePattern.NORM_DATETIME_PATTERN).getTime() == DateUtil.parse(o.getTime(), DatePattern.NORM_DATETIME_PATTERN).getTime()) { + return 0; + } + return -1; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationMode.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationMode.java new file mode 100644 index 0000000..6cf45f8 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationMode.java @@ -0,0 +1,46 @@ +package com.njcn.product.advance.responsility.pojo.constant; + +/** + * 计算模式枚举 + * + * @author hongawen + * @version 1.0 + */ +public enum CalculationMode { + /** + * 完整计算模式 + * 使用电压和功率数据计算相关系数和责任 + */ + FULL_CALCULATION(0, "完整计算模式"), + + /** + * 部分重算模式 + * 使用已有的动态相关系数计算责任 + */ + PARTIAL_RECALCULATION(1, "部分重算模式"); + + private final int code; + private final String description; + + CalculationMode(int code, String description) { + this.code = code; + this.description = description; + } + + public int getCode() { + return code; + } + + public String getDescription() { + return description; + } + + public static CalculationMode fromCode(int code) { + for (CalculationMode mode : values()) { + if (mode.code == code) { + return mode; + } + } + throw new IllegalArgumentException("Invalid calculation mode code: " + code); + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationStatus.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationStatus.java new file mode 100644 index 0000000..359f757 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/CalculationStatus.java @@ -0,0 +1,49 @@ +package com.njcn.product.advance.responsility.pojo.constant; + +/** + * 计算状态枚举 + * + * @author hongawen + * @version 1.0 + */ +public enum CalculationStatus { + /** + * 未计算 + */ + NOT_CALCULATED(0, "未计算"), + + /** + * 计算完成 + */ + CALCULATED(1, "计算完成"), + + /** + * 计算失败 + */ + FAILED(-1, "计算失败"); + + private final int code; + private final String description; + + CalculationStatus(int code, String description) { + this.code = code; + this.description = description; + } + + public int getCode() { + return code; + } + + public String getDescription() { + return description; + } + + public static CalculationStatus fromCode(int code) { + for (CalculationStatus status : values()) { + if (status.code == code) { + return status; + } + } + return NOT_CALCULATED; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/HarmonicConstants.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/HarmonicConstants.java new file mode 100644 index 0000000..75e439a --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/constant/HarmonicConstants.java @@ -0,0 +1,60 @@ +package com.njcn.product.advance.responsility.pojo.constant; + +/** + * 谐波责任量化系统常量定义 + * + * @author hongawen + * @version 1.0 + */ +public final class HarmonicConstants { + + private HarmonicConstants() { + // 防止实例化 + } + + /** + * 最大谐波数据个数 (1440*100) + * 按一分钟间隔,100天处理 + */ + public static final int MAX_HARM_NUM = 144000; + + /** + * 最大功率数据个数 (96*100) + * 按15分钟间隔,100天处理 + */ + public static final int MAX_P_NUM = 9600; + + /** + * 最大功率节点个数 + * 按200个限制 + */ + public static final int MAX_P_NODE = 200; + + /** + * 最大数据窗长度 (96*10) + * 按15分钟算10天 + */ + public static final int MAX_WIN_LEN = 960; + + /** + * 最小数据窗长度 + * 按15分钟算一小时 + */ + public static final int MIN_WIN_LEN = 4; + + /** + * 默认数据窗大小 + * 一天的数据量(15分钟间隔) + */ + public static final int DEFAULT_WINDOW_SIZE = 96; + + /** + * 数值计算精度阈值 + */ + public static final double EPSILON = 1e-10; + + /** + * 协方差计算最小值(避免除零) + */ + public static final double MIN_COVARIANCE = 1e-5; +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerData.java new file mode 100644 index 0000000..c615675 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerData.java @@ -0,0 +1,27 @@ +package com.njcn.product.advance.responsility.pojo.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @author hongawen + * @Date: 2019/4/3 13:34 + */ +@Data +public class CustomerData implements Serializable { + + /*** + * 用户名称 + */ + private String customerName; + + + /*** + * 每时刻的数据 + */ + private List valueDatas=new ArrayList<>(); + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerResponsibility.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerResponsibility.java new file mode 100644 index 0000000..ac8f2a2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/CustomerResponsibility.java @@ -0,0 +1,34 @@ +package com.njcn.product.advance.responsility.pojo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author hongawen + * @Date: 2019/4/3 13:35 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CustomerResponsibility implements Serializable { + + /*** + * 用户名 + */ + private String customerName; + + /*** + * 责任值 + */ + private float responsibilityData; + + + /*** + * 监测点id + */ + private String monitorId; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/RespDataDTO.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/RespDataDTO.java new file mode 100644 index 0000000..ec223b1 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/RespDataDTO.java @@ -0,0 +1,29 @@ +package com.njcn.product.advance.responsility.pojo.dto; + +import com.njcn.product.advance.responsility.pojo.po.RespData; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月24日 17:49 + */ +@Data +public class RespDataDTO extends RespData implements Serializable { + + private String userDataName; + + private String gdName; + + private String subName; + + private String devName; + + private String ip; + + private String lineName; + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/ResponsibilityResult.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/ResponsibilityResult.java new file mode 100644 index 0000000..e6d37e4 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/dto/ResponsibilityResult.java @@ -0,0 +1,53 @@ +package com.njcn.product.advance.responsility.pojo.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 谐波责任量化最终结果,包括动态数据和责任量化结果 + * + * @author hongawen + * @Date: 2019/4/3 15:00 + */ +@Data +public class ResponsibilityResult implements Serializable { + + /*** + * 限值 + */ + private String limitValue; + + /*** + * 指定起始时间 + */ + private String limitSTime; + + /*** + * 指定结束时间 + */ + private String limitETime; + + /*** + * 责任划分结果存库数据 + */ + private String responsibilityDataIndex; + + /*** + * 每个用户的详细时刻的责任数据 + */ + private List datas; + + /*** + * 时间轴 + */ + private List timeDatas=new ArrayList<>(); + + /*** + * 用户责任的表格数据 + */ + private List responsibilities; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/HistoryHarmParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/HistoryHarmParam.java new file mode 100644 index 0000000..68bb27f --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/HistoryHarmParam.java @@ -0,0 +1,56 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.advance.eventSource.pojo.constant.HarmonicValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月19日 09:23 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class HistoryHarmParam implements Serializable { + + + @ApiModelProperty("开始时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchEndTime; + + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @ApiModelProperty("监测点索引") + private String lineId; + + + + @Max(1) + @Min(0) + @ApiModelProperty("0-电流 1-电压") + private int type; + + @Max(50) + @Min(2) + @ApiModelProperty("谐波次数") + private Integer time; + + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/PHistoryHarmParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/PHistoryHarmParam.java new file mode 100644 index 0000000..7e215e2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/PHistoryHarmParam.java @@ -0,0 +1,34 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.advance.eventSource.pojo.constant.HarmonicValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-18 + * @Description: + */ +@Data +public class PHistoryHarmParam { + + + @ApiModelProperty("开始时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchEndTime; + + @NotBlank(message = HarmonicValidMessage.DATA_NOT_BLANK) + @ApiModelProperty("监测点索引") + private List lineIds; +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/RespBaseParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/RespBaseParam.java new file mode 100644 index 0000000..032aaf6 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/RespBaseParam.java @@ -0,0 +1,18 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import com.njcn.web.pojo.param.BaseParam; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @Author: cdf + * @CreateTime: 2025-09-09 + * @Description: + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class RespBaseParam extends BaseParam { + + private String deptId; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilityCalculateParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilityCalculateParam.java new file mode 100644 index 0000000..00aa456 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilityCalculateParam.java @@ -0,0 +1,57 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.io.Serializable; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月21日 10:20 + */ +@Data +public class ResponsibilityCalculateParam implements Serializable { + + + @ApiModelProperty("开始时间") + @NotBlank(message = "参数不能为空") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @NotBlank(message = "参数不能为空") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchEndTime; + + @NotBlank(message = "参数不能为空") + @ApiModelProperty("监测点索引") + private String lineId; + + @NotBlank(message = "参数不能为空") + @ApiModelProperty("用采数据索引") + private String userDataId; + + @Min(0) + @Max(1) + @ApiModelProperty("0-电流 1-电压") + private int type; + + @Min(2) + @Max(50) + @ApiModelProperty("谐波次数") + private Integer time; + + @ApiModelProperty("背景用户的下级") + private List userList; + + @ApiModelProperty("0或者null:配网环境,1.系统环境") + private Integer systemType; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilitySecondCalParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilitySecondCalParam.java new file mode 100644 index 0000000..dad8cbb --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/ResponsibilitySecondCalParam.java @@ -0,0 +1,44 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月24日 15:47 + */ +@Data +public class ResponsibilitySecondCalParam implements Serializable { + + @NotBlank(message = "参数不能为空") + @ApiModelProperty("责任数据索引") + private String resDataId; + + @Min(2) + @Max(50) + @ApiModelProperty("谐波次数") + private Integer time; + + @Min(0) + @Max(1) + @ApiModelProperty("0-电流 1-电压") + private int type; + + @ApiModelProperty("限值") + private float limitValue; + + @ApiModelProperty("开始时间(yyyy-MM-dd HH:mm:ss)") + @NotBlank(message = "参数不能为空") + private String limitStartTime; + + @ApiModelProperty("结束时间(yyyy-MM-dd HH:mm:ss)") + @NotBlank(message = "参数不能为空") + private String limitEndTime; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/UserDataIntegrityParam.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/UserDataIntegrityParam.java new file mode 100644 index 0000000..0b86cbf --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/param/UserDataIntegrityParam.java @@ -0,0 +1,19 @@ +package com.njcn.product.advance.responsility.pojo.param; + +import com.njcn.web.pojo.param.BaseParam; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2023年07月25日 14:14 + */ +@Data +public class UserDataIntegrityParam extends BaseParam implements Serializable { + + + private String userDataId; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespData.java new file mode 100644 index 0000000..0a567b2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespData.java @@ -0,0 +1,55 @@ +package com.njcn.product.advance.responsility.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +/** + * + * @author hongawen + * @since 2023-07-21 + */ +@Getter +@Setter +@TableName("pqs_resp_data") +public class RespData extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 责任量化数据结果 + */ + private String id; + + /** + * 监测点索引 + */ + private String lineId; + + /** + * 用采数据索引 + */ + private String userDataId; + + /** + * 谐波类型(谐波电压、谐波电流) + */ + private String dataType; + + /** + * 谐波次数 + */ + private String dataTimes; + + /** + * 计算的时间窗口 + */ + private String timeWindow; + + /** + * 状态(0 删除 1正常) + */ + private Integer state; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespDataResult.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespDataResult.java new file mode 100644 index 0000000..6950d6b --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespDataResult.java @@ -0,0 +1,80 @@ +package com.njcn.product.advance.responsility.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + *

+ * + *

+ * + * @author hongawen + * @since 2023-07-24 + */ +@Getter +@Setter +@TableName("pqs_resp_data_result") +public class RespDataResult extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 责任划分结果数据文件保存记录表 + */ + private String id; + + /** + * 责任划分结果表id + */ + private String resDataId; + + /** + * 限值 + */ + private Float limitValue; + + /*** + * 起始时间 + */ + private Date startTime; + + /*** + * 结束时间 + */ + private Date endTime; + + /** + * 谐波次数 + */ + private Integer time; + + /** + * 用户责任数据地址 + */ + private String userDetailData; + + /** + * 用户责任时间数据地址 + */ + private String timeData; + + /** + * 前10用户的每刻对应的责任数据地址 + */ + private String userResponsibility; + + /** + * 调用高级算法后的数据结果地址,提供二次计算 + */ + private String qvvrData; + + /** + * 状态(0 删除 1正常) + */ + private Integer state; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserData.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserData.java new file mode 100644 index 0000000..e45180a --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserData.java @@ -0,0 +1,57 @@ +package com.njcn.product.advance.responsility.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDate; + +/** + * + * @author hongawen + * @since 2023-07-13 + */ +@Getter +@Setter +@TableName("pqs_resp_user_data") +public class RespUserData extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 用采数据表id + */ + private String id; + + /** + * 用采数据名称 + */ + private String name; + + /** + * 起始日期 + */ + private LocalDate startTime; + + /** + * 截止日期 + */ + private LocalDate endTime; + + /** + * 0 存在数据不完整的;1 存在数据完整 + */ + private Integer integrity = 1; + + /** + * 用采数据存放地址 + */ + private String dataPath; + + /** + * 状态(0 删除 1正常) + */ + private Integer state; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserDataIntegrity.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserDataIntegrity.java new file mode 100644 index 0000000..cf69d08 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/pojo/po/RespUserDataIntegrity.java @@ -0,0 +1,63 @@ +package com.njcn.product.advance.responsility.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** + * + * @author hongawen + * @since 2023-07-13 + */ +@Getter +@Setter +@TableName("pqs_resp_user_data_integrity") +public class RespUserDataIntegrity extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 用采数据完整不足表Id + */ + private String id; + + /** + * 用采数据表id + */ + private String userDataId; + + /** + * 用户名称 + */ + private String userName; + + /** + * 用户户号 + */ + private String userNo; + + /** + * 测量点局号 + */ + private String lineNo; + + /** + * 数据不完整的日期 + */ + private LocalDate lackDate; + + /** + * 完整率(低于90%会记录) + */ + private BigDecimal integrity; + + /** + * 状态(0 删除 1正常) + */ + private Integer state; + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IHarmonicResponsibilityService.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IHarmonicResponsibilityService.java new file mode 100644 index 0000000..3230b20 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IHarmonicResponsibilityService.java @@ -0,0 +1,62 @@ +package com.njcn.product.advance.responsility.service; + + +import com.njcn.product.advance.responsility.model.HarmonicData; + +/** + * 谐波责任计算服务接口 + * + * @author hongawen + * @version 1.0 + */ +public interface IHarmonicResponsibilityService { + + /** + * 执行谐波责任计算 + * + * @param data 输入的谐波数据 + * @return 计算是否成功 + */ + boolean calculate(HarmonicData data); + + /** + * 执行完整计算 + * + * @param harmonicData 谐波数据数组 + * @param powerData 功率数据矩阵 + * @param harmonicCount 谐波数据个数 + * @param powerCount 功率数据个数 + * @param nodeCount 节点数量 + * @param windowSize 窗口大小 + * @param threshold 谐波门槛 + * @return 计算结果 + */ + HarmonicData fullCalculation(float[] harmonicData, float[][] powerData, + int harmonicCount, int powerCount, int nodeCount, + int windowSize, float threshold); + + /** + * 执行部分重算 + * + * @param harmonicData 谐波数据数组 + * @param fkData FK数据矩阵 + * @param hkData HK数据矩阵 + * @param harmonicCount 谐波数据个数 + * @param nodeCount 节点数量 + * @param windowSize 窗口大小 + * @param responsibilityCount 责任数据个数 + * @param threshold 谐波门槛 + * @return 计算结果 + */ + HarmonicData partialCalculation(float[] harmonicData, float[][] fkData, float[][] hkData, + int harmonicCount, int nodeCount, int windowSize, + int responsibilityCount, float threshold); + + /** + * 验证输入数据的有效性 + * + * @param data 待验证的数据 + * @return 验证结果消息,null表示验证通过 + */ + String validateData(HarmonicData data); +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataResultService.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataResultService.java new file mode 100644 index 0000000..463a4ac --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataResultService.java @@ -0,0 +1,20 @@ +package com.njcn.product.advance.responsility.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.po.RespDataResult; + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2023-07-24 + */ +public interface IRespDataResultService extends IService { + + List displayHistoryData(String id, Integer time); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataService.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataService.java new file mode 100644 index 0000000..a17db8c --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespDataService.java @@ -0,0 +1,38 @@ +package com.njcn.product.advance.responsility.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.product.advance.responsility.pojo.dto.RespDataDTO; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.param.RespBaseParam; +import com.njcn.product.advance.responsility.pojo.param.ResponsibilityCalculateParam; +import com.njcn.product.advance.responsility.pojo.param.ResponsibilitySecondCalParam; +import com.njcn.product.advance.responsility.pojo.po.RespData; +import com.njcn.web.pojo.param.BaseParam; + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2023-07-21 + */ +public interface IRespDataService extends IService { + + ResponsibilityResult getDynamicDataOld(ResponsibilityCalculateParam responsibilityCalculateParam); + + ResponsibilityResult getDynamicData(ResponsibilityCalculateParam responsibilityCalculateParam); + + ResponsibilityResult getResponsibilityDataOld(ResponsibilitySecondCalParam responsibilitySecondCalParam); + + ResponsibilityResult getResponsibilityData(ResponsibilitySecondCalParam responsibilitySecondCalParam); + + Page responsibilityList(RespBaseParam queryParam); + + void deleteByIds(List ids); + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataIntegrityService.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataIntegrityService.java new file mode 100644 index 0000000..938b87c --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataIntegrityService.java @@ -0,0 +1,20 @@ +package com.njcn.product.advance.responsility.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.advance.responsility.pojo.param.UserDataIntegrityParam; +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; + + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +public interface IRespUserDataIntegrityService extends IService { + + Page userDataIntegrityList(UserDataIntegrityParam userDataIntegrityParam); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataService.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataService.java new file mode 100644 index 0000000..9f718e6 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/IRespUserDataService.java @@ -0,0 +1,40 @@ +package com.njcn.product.advance.responsility.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.common.pojo.dto.SelectOption; +import com.njcn.product.advance.responsility.pojo.bo.UserDataExcel; +import com.njcn.product.advance.responsility.pojo.po.RespUserData; +import com.njcn.web.pojo.param.BaseParam; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +public interface IRespUserDataService extends IService { + + /** + * 解析用采数据并保存 + * @author hongawen + * @date 2023/7/13 19:48 + * @param file 用采数据 + */ + void uploadUserData(MultipartFile file, HttpServletResponse response); + + Page userDataList(BaseParam queryParam); + + List userDataSelect(); + + void deleteUserDataByIds(List ids); + + List getUserDataExcelList(String userDataId); +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/HarmonicResponsibilityServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/HarmonicResponsibilityServiceImpl.java new file mode 100644 index 0000000..96b4241 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/HarmonicResponsibilityServiceImpl.java @@ -0,0 +1,163 @@ +package com.njcn.product.advance.responsility.service.impl; + + +import com.njcn.product.advance.responsility.calculator.HarmonicCalculationEngine; +import com.njcn.product.advance.responsility.model.HarmonicData; +import com.njcn.product.advance.responsility.pojo.constant.CalculationMode; +import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants; +import com.njcn.product.advance.responsility.service.IHarmonicResponsibilityService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +/** + * 谐波责任计算服务实现类 + * + * @author hongawen + * @version 1.0 + */ +@Service +public class HarmonicResponsibilityServiceImpl implements IHarmonicResponsibilityService { + + private static final Logger logger = LoggerFactory.getLogger(HarmonicResponsibilityServiceImpl.class); + + private final HarmonicCalculationEngine engine; + + public HarmonicResponsibilityServiceImpl() { + this.engine = new HarmonicCalculationEngine(); + } + + @Override + public boolean calculate(HarmonicData data) { + if (data == null) { + logger.error("Input data is null"); + return false; + } + + String validationError = validateData(data); + if (validationError != null) { + logger.error("Data validation failed: {}", validationError); + return false; + } + + long startTime = System.currentTimeMillis(); + boolean result = engine.calculate(data); + long endTime = System.currentTimeMillis(); + + logger.info("Calculation completed in {} ms, result: {}", (endTime - startTime), result); + + return result; + } + + @Override + public HarmonicData fullCalculation(float[] harmonicData, float[][] powerData, + int harmonicCount, int powerCount, int nodeCount, + int windowSize, float threshold) { + logger.info("Starting full calculation with harmonicCount={}, powerCount={}, nodeCount={}, windowSize={}", + harmonicCount, powerCount, nodeCount, windowSize); + + HarmonicData data = new HarmonicData.Builder() + .calculationMode(CalculationMode.FULL_CALCULATION) + .harmonicCount(harmonicCount) + .powerCount(powerCount) + .powerNodeCount(nodeCount) + .windowSize(windowSize) + .harmonicThreshold(threshold) + .harmonicData(harmonicData) + .powerData(powerData) + .build(); + + calculate(data); + + return data; + } + + @Override + public HarmonicData partialCalculation(float[] harmonicData, float[][] fkData, float[][] hkData, + int harmonicCount, int nodeCount, int windowSize, + int responsibilityCount, float threshold) { + logger.info("Starting partial calculation with harmonicCount={}, nodeCount={}, windowSize={}, responsibilityCount={}", + harmonicCount, nodeCount, windowSize, responsibilityCount); + + HarmonicData data = new HarmonicData(); + data.setCalculationMode(CalculationMode.PARTIAL_RECALCULATION); + data.setHarmonicCount(harmonicCount); + data.setPowerNodeCount(nodeCount); + data.setWindowSize(windowSize); + data.setResponsibilityDataCount(responsibilityCount); + data.setHarmonicThreshold(threshold); + data.setHarmonicData(harmonicData); + data.setFkData(fkData); + data.setHkData(hkData); + + // 初始化输出数组 + data.setSumFKData(new float[nodeCount]); + data.setSumHKData(new float[nodeCount + 1]); + + calculate(data); + + return data; + } + + @Override + public String validateData(HarmonicData data) { + if (data == null) { + return "Data object is null"; + } + + // 验证基本参数 + if (data.getHarmonicCount() <= 0 || data.getHarmonicCount() > HarmonicConstants.MAX_HARM_NUM) { + return String.format("Invalid harmonic count: %d (should be 1-%d)", + data.getHarmonicCount(), HarmonicConstants.MAX_HARM_NUM); + } + + if (data.getCalculationMode() == CalculationMode.FULL_CALCULATION) { + // 完整计算模式验证 + if (data.getPowerCount() <= 0 || data.getPowerCount() > HarmonicConstants.MAX_P_NUM) { + return String.format("Invalid power count: %d (should be 1-%d)", + data.getPowerCount(), HarmonicConstants.MAX_P_NUM); + } + + if (data.getPowerNodeCount() <= 0 || data.getPowerNodeCount() > HarmonicConstants.MAX_P_NODE) { + return String.format("Invalid power node count: %d (should be 1-%d)", + data.getPowerNodeCount(), HarmonicConstants.MAX_P_NODE); + } + + // 验证数据对齐 + int ratio = data.getHarmonicCount() / data.getPowerCount(); + if (ratio * data.getPowerCount() != data.getHarmonicCount()) { + return String.format("Harmonic count %d is not aligned with power count %d", + data.getHarmonicCount(), data.getPowerCount()); + } + + // 验证数据数组 + if (data.getHarmonicData() == null || data.getHarmonicData().length < data.getHarmonicCount()) { + return "Harmonic data array is null or insufficient"; + } + + if (data.getPowerData() == null || data.getPowerData().length < data.getPowerCount()) { + return "Power data array is null or insufficient"; + } + + } else if (data.getCalculationMode() == CalculationMode.PARTIAL_RECALCULATION) { + // 部分计算模式验证 + if (data.getResponsibilityDataCount() + data.getWindowSize() != data.getHarmonicCount()) { + return String.format("Data length mismatch: resNum(%d) + winSize(%d) != harmCount(%d)", + data.getResponsibilityDataCount(), data.getWindowSize(), data.getHarmonicCount()); + } + + if (data.getFkData() == null || data.getHkData() == null) { + return "FK or HK data is null for partial calculation"; + } + } + + // 验证窗口大小 + if (data.getWindowSize() < HarmonicConstants.MIN_WIN_LEN || + data.getWindowSize() > HarmonicConstants.MAX_WIN_LEN) { + return String.format("Invalid window size: %d (should be %d-%d)", + data.getWindowSize(), HarmonicConstants.MIN_WIN_LEN, HarmonicConstants.MAX_WIN_LEN); + } + + return null; // 验证通过 + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataResultServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataResultServiceImpl.java new file mode 100644 index 0000000..a7ce6ba --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataResultServiceImpl.java @@ -0,0 +1,88 @@ +package com.njcn.product.advance.responsility.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.text.StrPool; +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.advance.responsility.mapper.RespDataResultMapper; +import com.njcn.product.advance.responsility.pojo.dto.CustomerData; +import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.po.RespData; +import com.njcn.product.advance.responsility.pojo.po.RespDataResult; +import com.njcn.product.advance.responsility.service.IRespDataResultService; +import com.njcn.product.advance.responsility.service.IRespDataService; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2023-07-24 + */ +@Service +public class RespDataResultServiceImpl extends ServiceImpl implements IRespDataResultService { + + @Resource + private FileStorageUtil fileStorageUtil; + + @Lazy + @Resource + private IRespDataService respDataService; + + @Override + public List displayHistoryData(String id, Integer time) { + List responsibilityResults = new ArrayList<>(); + if (Objects.isNull(time)) { + RespData respData = respDataService.getById(id); + String[] split = respData.getDataTimes().split(StrPool.COMMA); + time = Integer.parseInt(split[0]); + } + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, id) + .eq(RespDataResult::getTime, time); + List respDataResults = this.baseMapper.selectList(respDataResultLambdaQueryWrapper); + if (CollectionUtil.isNotEmpty(respDataResults)) { + ResponsibilityResult responsibilityResult; + for (RespDataResult respDataResult : respDataResults) { + responsibilityResult = new ResponsibilityResult(); + responsibilityResult.setLimitValue(String.valueOf(respDataResult.getLimitValue())); + responsibilityResult.setLimitSTime(DateUtil.format(respDataResult.getStartTime(), DatePattern.NORM_DATETIME_PATTERN)); + responsibilityResult.setLimitETime(DateUtil.format(respDataResult.getEndTime(), DatePattern.NORM_DATETIME_PATTERN)); + responsibilityResult.setResponsibilityDataIndex(respDataResult.getResDataId()); + //处理时间轴数据 + InputStream timeDataStream = fileStorageUtil.getFileStream(respDataResult.getTimeData()); + String timeDataStr = IoUtil.readUtf8(timeDataStream); + List timeData = JSONArray.parseArray(timeDataStr, Long.class); + responsibilityResult.setTimeDatas(timeData); + //处理用户详细数据 + InputStream userDetailStream = fileStorageUtil.getFileStream(respDataResult.getUserDetailData()); + String userDetailStr = IoUtil.readUtf8(userDetailStream); + List customerData = JSONArray.parseArray(userDetailStr, CustomerData.class); + responsibilityResult.setDatas(customerData); + //处理排名前10数据 + InputStream respStream = fileStorageUtil.getFileStream(respDataResult.getUserResponsibility()); + String respStr = IoUtil.readUtf8(respStream); + List respData = JSONArray.parseArray(respStr, CustomerResponsibility.class); + responsibilityResult.setResponsibilities(respData); + responsibilityResults.add(responsibilityResult); + } + } + return responsibilityResults; + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataServiceImpl.java new file mode 100644 index 0000000..32e6ae8 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespDataServiceImpl.java @@ -0,0 +1,1756 @@ +package com.njcn.product.advance.responsility.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.date.DateUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.text.StrPool; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.constant.ServerInfo; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.FileUtil; +import com.njcn.common.utils.PubUtils; + +import com.njcn.db.mybatisplus.constant.DbConstant; +import com.njcn.influx.pojo.constant.InfluxDBTableConstant; +import com.njcn.influx.pojo.dto.HarmData; +import com.njcn.influx.pojo.dto.HarmHistoryDataDTO; +import com.njcn.influx.pojo.po.DataHarmPowerP; +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.advance.eventSource.pojo.enums.AdvanceResponseEnum; +import com.njcn.product.advance.eventSource.service.HistoryHarmonicService; +import com.njcn.product.advance.responsility.imapper.DataHarmP; +import com.njcn.product.advance.responsility.mapper.RespDataMapper; +import com.njcn.product.advance.responsility.model.CacheQvvrData; +import com.njcn.product.advance.responsility.model.HarmonicData; +import com.njcn.product.advance.responsility.model.QvvrDataEntity; +import com.njcn.product.advance.responsility.pojo.bo.DealDataResult; +import com.njcn.product.advance.responsility.pojo.bo.RespCommon; +import com.njcn.product.advance.responsility.pojo.bo.RespHarmData; +import com.njcn.product.advance.responsility.pojo.bo.UserDataExcel; +import com.njcn.product.advance.responsility.pojo.constant.CalculationStatus; +import com.njcn.product.advance.responsility.pojo.dto.CustomerData; +import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility; +import com.njcn.product.advance.responsility.pojo.dto.RespDataDTO; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.param.*; +import com.njcn.product.advance.responsility.pojo.po.RespData; +import com.njcn.product.advance.responsility.pojo.po.RespDataResult; +import com.njcn.product.advance.responsility.service.IHarmonicResponsibilityService; +import com.njcn.product.advance.responsility.service.IRespDataResultService; +import com.njcn.product.advance.responsility.service.IRespDataService; +import com.njcn.product.advance.responsility.service.IRespUserDataService; +import com.njcn.product.advance.responsility.utils.ResponsibilityAlgorithm; +import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.OverlimitMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeptGetChildrenMoreDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeptGetLineParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Overlimit; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDetailDataVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDetailVO; +import com.njcn.product.terminal.mysqlTerminal.service.CommTerminalService; +import com.njcn.product.terminal.mysqlTerminal.service.LineService; +import com.njcn.product.terminal.mysqlTerminal.service.impl.CommTerminalServiceImpl; +import com.njcn.web.factory.PageFactory; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2023-07-21 + */ +@Service +@RequiredArgsConstructor +public class RespDataServiceImpl extends ServiceImpl implements IRespDataService { + + + private final FileStorageUtil fileStorageUtil; + + + private final IRespDataResultService respDataResultService; + + private final IRespUserDataService respUserDataService; + + private final CommTerminalService commTerminalService; + + private final OverlimitMapper overlimitMapper; + + private final LineService lineService; + + private final HistoryHarmonicService historyHarmonicService; + + private final LineMapper lineMapper; + + private final IHarmonicResponsibilityService harmonicResponsibilityService; + + private static DateTimeFormatter format = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN); + + public final static int SORT_10 = 10; + public final static int INTERVAL_TIME_1 = 1; + public final static int INTERVAL_TIME_3 = 3; + public final static int INTERVAL_TIME_5 = 5; + public final static int INTERVAL_TIME_15 = 15; + public final static int INTERVAL_TIME_30 = 30; + public final static int WINDOW_96 = 96; + public final static int WINDOW_48 = 48; + public final static int WINDOW_4 = 4; + + public final static int MINUS_2 = 2; + public final static int MINUS_3 = 3; + public final static int MINUS_4 = 4; + public final static int MINUS_5 = 5; + private final CommTerminalServiceImpl commTerminalServiceImpl; + + + @Override + public Page responsibilityList(RespBaseParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + //获取当前用户部门,根据部门获取监测点 + DeptGetLineParam deptGetLineParam = new DeptGetLineParam(); + deptGetLineParam.setDeptId(queryParam.getDeptId()); + deptGetLineParam.setServerName(ServerInfo.ADVANCE_BOOT); + List list = commTerminalService.deptGetLine(deptGetLineParam); + DeptGetChildrenMoreDTO dto = list.stream().collect(Collectors.toMap(DeptGetChildrenMoreDTO::getUnitId, Function.identity())).get(queryParam.getDeptId()); + if (CollUtil.isNotEmpty(dto.getLineBaseList())) { + List line = dto.getLineBaseList().stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList()); + queryWrapper.in("pqs_resp_data.line_id", line); + } + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //仅提供用采名称 + queryWrapper.and(param -> param.like("pqs_resp_user_data.name", queryParam.getSearchValue())); + } + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + //没有排序参数,默认根据sort字段排序,没有排序字段的,根据updateTime更新时间排序 + queryWrapper.orderBy(true, false, "pqs_resp_data.create_time"); + } + queryWrapper.between("pqs_resp_data.create_time", DateUtil.beginOfDay(DateUtil.parse(queryParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(queryParam.getSearchEndTime()))); + } + queryWrapper.eq("pqs_resp_data.state", DataStateEnum.ENABLE.getCode()); + Page page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + List records = page.getRecords(); + if (CollectionUtil.isNotEmpty(records)) { + //获取该监测点的详细信息 + for (RespDataDTO respDataDTO : records) { + LineDetailVO lineSubGdDetail = lineMapper.getLineSubGdDetail(respDataDTO.getLineId()); + BeanUtil.copyProperties(lineSubGdDetail, respDataDTO); + } + } + return page.setRecords(records); + } + + + /*** + * 批量逻辑删除责任划分数据 + * @author hongawen + * @date 2023/7/24 19:16 + */ + @Override + public void deleteByIds(List ids) { + this.baseMapper.deleteByIds(ids); + } + + + @Override + @Deprecated + public ResponsibilityResult getDynamicDataOld(ResponsibilityCalculateParam responsibilityCalculateParam) { + ResponsibilityResult result = new ResponsibilityResult(); + //调用c++依赖需要待初始化的参数 + int pNode, pNum, win, harmNum; + float harmMk; + List userDataExcels = respUserDataService.getUserDataExcelList(responsibilityCalculateParam.getUserDataId()); + //开始处理,根据接口参数需求,需要节点数(用户数,用户名+监测点号为一个用户),时间范围内功率数据 + DealDataResult dealDataResult = RespUserDataServiceImpl.getStanderData(userDataExcels, 1); + List dateStr = PubUtils.getTimes(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DateUtil.parse(responsibilityCalculateParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)); + Map>> finalData = getFinalUserData(dealDataResult, dateStr); + //至此,finalData便是我们最终获得的用于计算责任数据,第一个参数节点数值pNode获取到 + //第一个参数pNode + pNode = finalData.size(); + if (pNode < 1) { + //没有合理的用采数据直接返回 + throw new BusinessException(AdvanceResponseEnum.USER_DATA_P_NODE_PARAMETER_ERROR); + } + //第二个参数pNum,根据起始时间和截止时间以及监测点测量间隔计算数量 + RespCommon pNumAndInterval = getPNumAndInterval(finalData, responsibilityCalculateParam.getLineId(), dateStr); + pNum = pNumAndInterval.getPNum(); + int userIntervalTime = pNumAndInterval.getUserIntervalTime(); + int lineInterval = pNumAndInterval.getLineInterval(); + //第三个参数win,根据起始时间和截止时间的间隔 + if (dateStr.size() > 1) { + if (userIntervalTime == INTERVAL_TIME_15) { + win = WINDOW_96; + } else { + win = WINDOW_48; + } + } else { + win = WINDOW_4; + } + //第四个参数harmMk,默认为0f + harmMk = 0f; + //第五个参数harmNum,与功率数据保持一致 + harmNum = pNum; + //至此基础数据组装完毕,开始组装功率数据和谐波数据 + //先做谐波数据,理论上到这步的时候,谐波数据是满足完整性并已经补充完整性到100%,此处需要将谐波数据与功率数据长度匹配上 + RespHarmData respHarmData = getRespHarmData(responsibilityCalculateParam, lineInterval); + //harmData填充完毕后,开始组装功率数据 + //首先获取当前时间内的各个用户的数据 + Map> originalPData = new HashMap<>(16); + List names = new ArrayList<>(); + Set userNamesFinal = finalData.keySet(); + for (String userName : userNamesFinal) { + List tempData = new ArrayList<>(); + //根据日期将日期数据全部获取出来z + Map> tempResult = finalData.get(userName); + for (String date : dateStr) { + tempData.addAll(tempResult.get(date)); + } + //按日期排序 + Collections.sort(tempData); + originalPData.put(userName, tempData); + names.add(userName); + } + //然后开始组装数据 + float[][] pData = new float[QvvrDataEntity.MAX_P_NUM][QvvrDataEntity.MAX_P_NODE]; + for (int i = 0; i < names.size(); i++) { + //当前某用户测量节点的所有数据 + List userDataExcelBodies1 = originalPData.get(names.get(i)); + for (int k = 0; k < userDataExcelBodies1.size(); k++) { + float[] pDataStruct = pData[k]; + if (pDataStruct == null) { + pDataStruct = new float[QvvrDataEntity.MAX_P_NODE]; + } + float[] p = pDataStruct; + p[i] = userDataExcelBodies1.get(k).getWork().floatValue(); + pData[k] = pDataStruct; + } + } + //至此功率数据也组装完毕,调用友谊提供的接口 + QvvrDataEntity qvvrDataEntity = new QvvrDataEntity(); + qvvrDataEntity.calFlag = 0; + qvvrDataEntity.pNode = pNode; + qvvrDataEntity.pNum = pNum; + qvvrDataEntity.win = win; + qvvrDataEntity.harmNum = harmNum; + qvvrDataEntity.harmMk = harmMk; + qvvrDataEntity.pData = pData; + qvvrDataEntity.harmData = respHarmData.getHarmData(); + ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm(); + qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity); + //至此接口调用结束,开始组装动态责任数据和用户责任量化结果 + //首先判断cal_ok的标识位是否为1,为0表示程序没有计算出结果 + if (qvvrDataEntity.calOk == 0) { + throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR); + } + //没问题后,先玩动态责任数据 + CustomerData[] customerDatas = new CustomerData[qvvrDataEntity.pNode]; + float[][] fKdata/*无背景的动态责任数据*/ = qvvrDataEntity.getFKData(); + //第一个时间节点是起始时间+win窗口得到的时间 + Date sTime = DateUtil.parse(dateStr.get(0).concat(" 00:00:00"), DatePattern.NORM_DATETIME_PATTERN); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(sTime); + calendar.add(Calendar.MINUTE, (win - 1) * userIntervalTime); + List timeDatas = new ArrayList<>(); + for (int i = 0; i < qvvrDataEntity.pNum - qvvrDataEntity.win; i++) { + calendar.add(Calendar.MINUTE, userIntervalTime); + //一个时间点所有的用户数据 + float[] fKdatum = fKdata[i]; + for (int k = 0; k < qvvrDataEntity.pNode; k++) { + CustomerData customerData = customerDatas[k]; + if (null == customerData) { + customerData = new CustomerData(); + customerData.setCustomerName(names.get(k)); + } + List valueDatas = customerData.getValueDatas(); + Float valueTemp = fKdatum[k]; + if (valueTemp.isNaN()) { + valueTemp = 0.0f; + } + valueDatas.add(valueTemp); + customerData.setValueDatas(valueDatas); + customerDatas[k] = customerData; + } + timeDatas.add(calendar.getTimeInMillis()); + } + //OK拿到所有测量点的数据了,现在就是看如何将相同户号的动态数据进行算术和求值,之前的用户name为:户号@测量点号@用户名 + Map> customerDataTemp = new HashMap<>(16); + for (CustomerData data : customerDatas) { + String customerName = data.getCustomerName(); + String[] customerInfo = customerName.split("@"); + String name = customerInfo[2] + "(" + customerInfo[0] + ")"; + List customerData = customerDataTemp.get(name); + CustomerData temp = data; + temp.setCustomerName(name); + if (CollectionUtils.isEmpty(customerData)) { + customerData = new ArrayList<>(); + } + customerData.add(temp); + customerDataTemp.put(name, customerData); + } + //动态数据组装完成后,开始组装责任数据 + List customerResponsibilities = getCustomerResponsibilityData(names, qvvrDataEntity.sumFKdata, qvvrDataEntity.pNode); + //根据前十的用户数据,获取这些用户的动态责任数据 + List customerData = new ArrayList<>(); + for (CustomerResponsibility customerResponsibility : customerResponsibilities) { + String cusName = customerResponsibility.getCustomerName(); + List customerData1 = customerDataTemp.get(cusName); + if (CollectionUtils.isEmpty(customerData1)) { + continue; + } + if (customerData1.size() == 1) { + //表示用户唯一的 + customerData.add(customerData1.get(0)); + } else { + // 表示用户可能包含多个监测点号,需要进行数据累加 + CustomerData customerDataT = new CustomerData(); + customerDataT.setCustomerName(cusName); + //进行数值累加 + List valueDatas = new ArrayList<>(); + for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) { + float original = 0.0f; + for (CustomerData data : customerData1) { + original = original + data.getValueDatas().get(i); + } + valueDatas.add(original); + } + customerDataT.setValueDatas(valueDatas); + customerData.add(customerDataT); + } + } + result.setDatas(customerData); + result.setTimeDatas(timeDatas); + result.setResponsibilities(customerResponsibilities); + //此次的操作进行入库操作responsibilityData表数据 + //根据监测点名称+谐波框选的时间来查询,是否做过责任量化 + String timeWin = responsibilityCalculateParam.getSearchBeginTime().replaceAll(StrPool.DASHED, "").concat(StrPool.DASHED).concat(responsibilityCalculateParam.getSearchEndTime().replaceAll(StrPool.DASHED, "")); + String type = responsibilityCalculateParam.getType() == 0 ? "谐波电流" : "谐波电压"; + //为了避免有监测点名称重复的,最终还是选择使用监测点索引来判断唯一性 + LambdaQueryWrapper respDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataLambdaQueryWrapper.eq(RespData::getLineId, responsibilityCalculateParam.getLineId()) + .eq(RespData::getUserDataId, responsibilityCalculateParam.getUserDataId()) + .eq(RespData::getTimeWindow, timeWin) + .eq(RespData::getDataType, type) + .eq(RespData::getState, DataStateEnum.ENABLE.getCode()); + List responsibilityDataTemp = this.baseMapper.selectList(respDataLambdaQueryWrapper); + RespData responsibilityData; + if (CollectionUtils.isEmpty(responsibilityDataTemp)) { + responsibilityData = new RespData(); + //库中没有记录则可以新建数据进行插入 + responsibilityData.setLineId(responsibilityCalculateParam.getLineId()); + responsibilityData.setUserDataId(responsibilityCalculateParam.getUserDataId()); + responsibilityData.setDataType(type); + responsibilityData.setDataTimes(responsibilityCalculateParam.getTime().toString()); + responsibilityData.setTimeWindow(timeWin); + responsibilityData.setState(DataStateEnum.ENABLE.getCode()); + //进行插入操作 + this.baseMapper.insert(responsibilityData); + } else { + //库中存在记录只需要判断次数进行数据更新 + responsibilityData = responsibilityDataTemp.get(0); + String times = responsibilityData.getDataTimes(); + List timesList = Stream.of(times.split(StrPool.COMMA)).collect(Collectors.toList()); + Integer time = responsibilityCalculateParam.getTime(); + if (!timesList.contains(time.toString())) { + timesList.add(time.toString()); + timesList = timesList.stream().sorted().collect(Collectors.toList()); + responsibilityData.setDataTimes(String.join(StrPool.COMMA, timesList)); + } + //执行更新操作 + this.baseMapper.updateById(responsibilityData); + } + //入库完毕之后,需要将必要数据进行序列化存储,方便后期的重复利用 + /* + * 需要序列化三种数据结构 1 cal_flag置为1时需要的一些列参数的CacheQvvrData 2 cal_flag为0时的,动态结果。3 用户责任量化结果 + * 其中1/2都只需要一个文件即可 + * 3因为用户限值的变化调整,可能存在很多个文件,具体根据用户的选择而定 + * + * 路径的结构为,temPath+userData+excelName+type+timeWin+lineIndex+time+文件名 + * 用户责任量化结果,需要再细化到限值 + */ + //首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性 + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilityCalculateParam.getTime()) + .eq(RespDataResult::getStartTime, DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getEndTime, DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getLimitValue, respHarmData.getOverLimit()); + RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper); + if (Objects.isNull(respDataResult)) { + respDataResult = new RespDataResult(); + respDataResult.setResDataId(responsibilityData.getId()); + respDataResult.setTime(responsibilityCalculateParam.getTime()); + respDataResult.setStartTime(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setEndTime(DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setLimitValue(respHarmData.getOverLimit()); + //时间横轴数据 timeDatas + JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas)); + InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString()); + String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setTimeData(timeDataPath); + //用户每时刻对应的责任数据 + JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData)); + InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString()); + String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserDetailData(customerPath); + //调用qvvr生成的中间数据 + CacheQvvrData cacheQvvrData = new CacheQvvrData(qvvrDataEntity.getPNode(), qvvrDataEntity.getHarmNum(), qvvrDataEntity.getHarmData(), qvvrDataEntity.fKData, qvvrDataEntity.hKData, names, userIntervalTime, qvvrDataEntity.win, userIntervalTime, respHarmData.getHarmTime()); + String cacheJson = PubUtils.obj2json(cacheQvvrData); + InputStream cacheQvvrDataStream = IoUtil.toUtf8Stream(cacheJson); + String cacheQvvrDataPath = fileStorageUtil.uploadStream(cacheQvvrDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setQvvrData(cacheQvvrDataPath); + //用户前10数据存储 + JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities)); + InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString()); + String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserResponsibility(customerResPath); + respDataResultService.save(respDataResult); + } + //防止过程中创建了大量的对象,主动调用下GC处理 + System.gc(); + result.setResponsibilityDataIndex(responsibilityData.getId()); + return result; + } + + @Override + public ResponsibilityResult getDynamicData(ResponsibilityCalculateParam responsibilityCalculateParam) { + ResponsibilityResult result = new ResponsibilityResult(); + //调用c++依赖需要待初始化的参数 + int pNode, pNum, win, harmNum; + float harmMk; + List userDataExcels = new ArrayList<>(); + if(Objects.nonNull(responsibilityCalculateParam.getSystemType()) && responsibilityCalculateParam.getSystemType()==1){ + userDataExcels = test(responsibilityCalculateParam.getUserList(),responsibilityCalculateParam.getSearchBeginTime(),responsibilityCalculateParam.getSearchEndTime()); + }else { + userDataExcels = respUserDataService.getUserDataExcelList(responsibilityCalculateParam.getUserDataId()); + + } + //开始处理,根据接口参数需求,需要节点数(用户数,用户名+监测点号为一个用户),时间范围内功率数据 + DealDataResult dealDataResult = RespUserDataServiceImpl.getStanderData(userDataExcels, 1); + List dateStr = PubUtils.getTimes(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN), DateUtil.parse(responsibilityCalculateParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)); + Map>> finalData = getFinalUserData(dealDataResult, dateStr); + //至此,finalData便是我们最终获得的用于计算责任数据,第一个参数节点数值pNode获取到 + //第一个参数pNode + pNode = finalData.size(); + if (pNode < 1) { + //没有合理的用采数据直接返回 + throw new BusinessException(AdvanceResponseEnum.USER_DATA_P_NODE_PARAMETER_ERROR); + } + //第二个参数pNum,根据起始时间和截止时间以及监测点测量间隔计算数量 + RespCommon pNumAndInterval = getPNumAndInterval(finalData, responsibilityCalculateParam.getLineId(), dateStr); + pNum = pNumAndInterval.getPNum(); + int userIntervalTime = pNumAndInterval.getUserIntervalTime(); + int lineInterval = pNumAndInterval.getLineInterval(); + //第三个参数win,根据起始时间和截止时间的间隔 + if (dateStr.size() > 1) { + if (userIntervalTime == INTERVAL_TIME_15) { + win = WINDOW_96; + } else { + win = WINDOW_48; + } + } else { + win = WINDOW_4; + } + //第四个参数harmMk,默认为0f + harmMk = 0f; + //第五个参数harmNum,与功率数据保持一致 + harmNum = pNum; + //至此基础数据组装完毕,开始组装功率数据和谐波数据 + //先做谐波数据,理论上到这步的时候,谐波数据是满足完整性并已经补充完整性到100%,此处需要将谐波数据与功率数据长度匹配上 + RespHarmData respHarmData = getRespHarmData(responsibilityCalculateParam, lineInterval); + //harmData填充完毕后,开始组装功率数据 + //首先获取当前时间内的各个用户的数据 + Map> originalPData = new HashMap<>(16); + List names = new ArrayList<>(); + Set userNamesFinal = finalData.keySet(); + for (String userName : userNamesFinal) { + List tempData = new ArrayList<>(); + //根据日期将日期数据全部获取出来z + Map> tempResult = finalData.get(userName); + for (String date : dateStr) { + tempData.addAll(tempResult.get(date)); + } + //按日期排序 + Collections.sort(tempData); + originalPData.put(userName, tempData); + names.add(userName); + } + //然后开始组装数据 + float[][] pData = new float[QvvrDataEntity.MAX_P_NUM][QvvrDataEntity.MAX_P_NODE]; + for (int i = 0; i < names.size(); i++) { + //当前某用户测量节点的所有数据 + List userDataExcelBodies1 = originalPData.get(names.get(i)); + for (int k = 0; k < userDataExcelBodies1.size(); k++) { + float[] pDataStruct = pData[k]; + if (pDataStruct == null) { + pDataStruct = new float[QvvrDataEntity.MAX_P_NODE]; + } + float[] p = pDataStruct; + p[i] = userDataExcelBodies1.get(k).getWork().floatValue(); + pData[k] = pDataStruct; + } + } + //至此功率数据也组装完毕,调用友谊提供的接口 +// QvvrDataEntity qvvrDataEntity = new QvvrDataEntity(); +// qvvrDataEntity.calFlag = 0; +// qvvrDataEntity.pNode = pNode; +// qvvrDataEntity.pNum = pNum; +// qvvrDataEntity.win = win; +// qvvrDataEntity.harmNum = harmNum; +// qvvrDataEntity.harmMk = harmMk; +// qvvrDataEntity.pData = pData; +// qvvrDataEntity.harmData = respHarmData.getHarmData(); +// ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm(); +// qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity); + + HarmonicData harmonicData = harmonicResponsibilityService.fullCalculation(respHarmData.getHarmData(), pData, harmNum, pNum, pNode, win, harmMk); + //至此接口调用结束,开始组装动态责任数据和用户责任量化结果 + //首先判断cal_ok的标识位是否为1,为0表示程序没有计算出结果 + if (harmonicData.getCalculationStatus() == CalculationStatus.FAILED) { + throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR); + } + //没问题后,先玩动态责任数据 + CustomerData[] customerDatas = new CustomerData[harmonicData.getPowerNodeCount()]; + float[][] fKdata/*无背景的动态责任数据*/ = harmonicData.getFkData(); + //第一个时间节点是起始时间+win窗口得到的时间 + Date sTime = DateUtil.parse(dateStr.get(0).concat(" 00:00:00"), DatePattern.NORM_DATETIME_PATTERN); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(sTime); + calendar.add(Calendar.MINUTE, (win - 1) * userIntervalTime); + List timeDatas = new ArrayList<>(); + for (int i = 0; i < harmonicData.getPowerCount() - harmonicData.getWindowSize(); i++) { + calendar.add(Calendar.MINUTE, userIntervalTime); + //一个时间点所有的用户数据 + float[] fKdatum = fKdata[i]; + for (int k = 0; k < harmonicData.getPowerNodeCount(); k++) { + CustomerData customerData = customerDatas[k]; + if (null == customerData) { + customerData = new CustomerData(); + customerData.setCustomerName(names.get(k)); + } + List valueDatas = customerData.getValueDatas(); + Float valueTemp = fKdatum[k]; + if (valueTemp.isNaN()) { + valueTemp = 0.0f; + } + valueDatas.add(valueTemp); + customerData.setValueDatas(valueDatas); + customerDatas[k] = customerData; + } + timeDatas.add(calendar.getTimeInMillis()); + } + //OK拿到所有测量点的数据了,现在就是看如何将相同户号的动态数据进行算术和求值,之前的用户name为:户号@测量点号@用户名 + Map> customerDataTemp = new HashMap<>(16); + for (CustomerData data : customerDatas) { + String customerName = data.getCustomerName(); + String[] customerInfo = customerName.split("@"); + String name = customerInfo[2] + "(" + customerInfo[0] + ")"; + List customerData = customerDataTemp.get(name); + CustomerData temp = data; + temp.setCustomerName(name); + if (CollectionUtils.isEmpty(customerData)) { + customerData = new ArrayList<>(); + } + customerData.add(temp); + customerDataTemp.put(name, customerData); + } + //动态数据组装完成后,开始组装责任数据 + List customerResponsibilities = getCustomerResponsibilityData(names, harmonicData.getSumFKData(), harmonicData.getPowerNodeCount()); + //根据前十的用户数据,获取这些用户的动态责任数据 + List customerData = new ArrayList<>(); + for (CustomerResponsibility customerResponsibility : customerResponsibilities) { + String cusName = customerResponsibility.getCustomerName(); + List customerData1 = customerDataTemp.get(cusName); + if (CollectionUtils.isEmpty(customerData1)) { + continue; + } + if (customerData1.size() == 1) { + //表示用户唯一的 + customerData.add(customerData1.get(0)); + } else { + // 表示用户可能包含多个监测点号,需要进行数据累加 + CustomerData customerDataT = new CustomerData(); + customerDataT.setCustomerName(cusName); + //进行数值累加 + List valueDatas = new ArrayList<>(); + for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) { + float original = 0.0f; + for (CustomerData data : customerData1) { + original = original + data.getValueDatas().get(i); + } + valueDatas.add(original); + } + customerDataT.setValueDatas(valueDatas); + customerData.add(customerDataT); + } + } + result.setDatas(customerData); + result.setTimeDatas(timeDatas); + result.setResponsibilities(customerResponsibilities); + //此次的操作进行入库操作responsibilityData表数据 + //根据监测点名称+谐波框选的时间来查询,是否做过责任量化 + String timeWin = responsibilityCalculateParam.getSearchBeginTime().replaceAll(StrPool.DASHED, "").concat(StrPool.DASHED).concat(responsibilityCalculateParam.getSearchEndTime().replaceAll(StrPool.DASHED, "")); + String type = responsibilityCalculateParam.getType() == 0 ? "谐波电流" : "谐波电压"; + //为了避免有监测点名称重复的,最终还是选择使用监测点索引来判断唯一性 + LambdaQueryWrapper respDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataLambdaQueryWrapper.eq(RespData::getLineId, responsibilityCalculateParam.getLineId()) + .eq(RespData::getUserDataId, responsibilityCalculateParam.getUserDataId()) + .eq(RespData::getTimeWindow, timeWin) + .eq(RespData::getDataType, type) + .eq(RespData::getState, DataStateEnum.ENABLE.getCode()); + List responsibilityDataTemp = this.baseMapper.selectList(respDataLambdaQueryWrapper); + RespData responsibilityData; + if (CollectionUtils.isEmpty(responsibilityDataTemp)) { + responsibilityData = new RespData(); + //库中没有记录则可以新建数据进行插入 + responsibilityData.setLineId(responsibilityCalculateParam.getLineId()); + responsibilityData.setUserDataId(responsibilityCalculateParam.getUserDataId()); + responsibilityData.setDataType(type); + responsibilityData.setDataTimes(responsibilityCalculateParam.getTime().toString()); + responsibilityData.setTimeWindow(timeWin); + responsibilityData.setState(DataStateEnum.ENABLE.getCode()); + //进行插入操作 + this.baseMapper.insert(responsibilityData); + } else { + //库中存在记录只需要判断次数进行数据更新 + responsibilityData = responsibilityDataTemp.get(0); + String times = responsibilityData.getDataTimes(); + List timesList = Stream.of(times.split(StrPool.COMMA)).collect(Collectors.toList()); + Integer time = responsibilityCalculateParam.getTime(); + if (!timesList.contains(time.toString())) { + timesList.add(time.toString()); + timesList = timesList.stream().sorted().collect(Collectors.toList()); + responsibilityData.setDataTimes(String.join(StrPool.COMMA, timesList)); + } + //执行更新操作 + this.baseMapper.updateById(responsibilityData); + } + //入库完毕之后,需要将必要数据进行序列化存储,方便后期的重复利用 + /* + * 需要序列化三种数据结构 1 cal_flag置为1时需要的一些列参数的CacheQvvrData 2 cal_flag为0时的,动态结果。3 用户责任量化结果 + * 其中1/2都只需要一个文件即可 + * 3因为用户限值的变化调整,可能存在很多个文件,具体根据用户的选择而定 + * + * 路径的结构为,temPath+userData+excelName+type+timeWin+lineIndex+time+文件名 + * 用户责任量化结果,需要再细化到限值 + */ + //首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性 + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilityCalculateParam.getTime()) + .eq(RespDataResult::getStartTime, DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getEndTime, DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getLimitValue, respHarmData.getOverLimit()); + RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper); + if (Objects.isNull(respDataResult)) { + respDataResult = new RespDataResult(); + respDataResult.setResDataId(responsibilityData.getId()); + respDataResult.setTime(responsibilityCalculateParam.getTime()); + respDataResult.setStartTime(DateUtil.parse(responsibilityCalculateParam.getSearchBeginTime() + " 00:00:00", DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setEndTime(DateUtil.parse(responsibilityCalculateParam.getSearchEndTime() + " 23:59:59", DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setLimitValue(respHarmData.getOverLimit()); + //时间横轴数据 timeDatas + JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas)); + InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString()); + String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setTimeData(timeDataPath); + //用户每时刻对应的责任数据 + JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData)); + InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString()); + String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserDetailData(customerPath); + //调用qvvr生成的中间数据 + CacheQvvrData cacheQvvrData = new CacheQvvrData(harmonicData.getPowerNodeCount(), harmonicData.getHarmonicCount(), harmonicData.getHarmonicData(), harmonicData.getFkData(), harmonicData.getHkData(), names, userIntervalTime, harmonicData.getWindowSize(), userIntervalTime, respHarmData.getHarmTime()); + String cacheJson = PubUtils.obj2json(cacheQvvrData); + InputStream cacheQvvrDataStream = IoUtil.toUtf8Stream(cacheJson); + String cacheQvvrDataPath = fileStorageUtil.uploadStream(cacheQvvrDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setQvvrData(cacheQvvrDataPath); + //用户前10数据存储 + JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities)); + InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString()); + String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserResponsibility(customerResPath); + respDataResultService.save(respDataResult); + } + //防止过程中创建了大量的对象,主动调用下GC处理 + System.gc(); + result.setResponsibilityDataIndex(responsibilityData.getId()); + return result; + } + + @Override + @Deprecated + public ResponsibilityResult getResponsibilityDataOld(ResponsibilitySecondCalParam responsibilitySecondCalParam) { + ResponsibilityResult result = new ResponsibilityResult(); + //根据时间天数,获取理论上多少次用采数据 + RespData responsibilityData = this.baseMapper.selectById(responsibilitySecondCalParam.getResDataId()); + if (Objects.isNull(responsibilityData)) { + throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND); + } + Overlimit overlimit = overlimitMapper.selectById(responsibilityData.getLineId()); + //获取总数据 + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime()); + if (responsibilitySecondCalParam.getType() == 0) { + respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getIharm", responsibilitySecondCalParam.getTime())); + } else { + respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getUharm", responsibilitySecondCalParam.getTime())); + } + RespDataResult respDataResultTemp = respDataResultService.getOne(respDataResultLambdaQueryWrapper); + if (Objects.isNull(respDataResultTemp)) { + throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND); + } + CacheQvvrData cacheQvvrData; + try { + InputStream fileStream = fileStorageUtil.getFileStream(respDataResultTemp.getQvvrData()); + String qvvrDataStr = IoUtil.readUtf8(fileStream); + cacheQvvrData = PubUtils.json2obj(qvvrDataStr, CacheQvvrData.class); + + } catch (Exception exception) { + throw new BusinessException(AdvanceResponseEnum.RESP_RESULT_DATA_NOT_FOUND); + } + //获取成功后,延长该缓存的生命周期为初始生命时长 + int win = cacheQvvrData.getWin(); + //不管窗口为4或者96,都需要考虑最小公倍数 + //最小公倍数根据监测点测量间隔来获取,可以考虑也由第一步操作缓存起来 + int minMultiple = cacheQvvrData.getMinMultiple(); + //谐波横轴所有的时间 + List times = cacheQvvrData.getTimes(); + //首先根据窗口判断限值时间范围是否满足最小窗口 + Long limitSL = DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN).getTime(); + Long limitEL = DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN).getTime(); + List temp = getTimes(times, limitSL, limitEL); + //在动态责任数据中,时间的起始索引位置和截止索引位置 + Integer timeStartIndex = temp.get(0); + Integer timeEndIndex = temp.get(1); + //间隔中的时间长度 + int minus = timeEndIndex - timeStartIndex + 1; + //组装参数 + QvvrDataEntity qvvrDataEntity = new QvvrDataEntity(); + qvvrDataEntity.calFlag = 1; + qvvrDataEntity.pNode = cacheQvvrData.getPNode(); + qvvrDataEntity.harmMk = responsibilitySecondCalParam.getLimitValue(); + qvvrDataEntity.win = win; + int resNum; + float[][] FKdata = new float[9600][QvvrDataEntity.MAX_P_NODE]; + float[][] HKdata = new float[9600][QvvrDataEntity.MAX_P_NODE + 1]; + float[] harmData = new float[1440 * 100]; + float[][] fKdataOriginal = cacheQvvrData.getFKData(); + float[][] hKdataOriginal = cacheQvvrData.getHKData(); + float[] harmDataOriginal = cacheQvvrData.getHarmData(); + //如果起始索引与截止索引的差值等于时间轴的长度,则说明用户没有选择限值时间,直接带入全部的原始数据,参与计算即可 + if (minus == times.size()) { + qvvrDataEntity.harmNum = cacheQvvrData.getHarmNum(); + qvvrDataEntity.resNum = cacheQvvrData.getHarmNum() - cacheQvvrData.getWin(); + qvvrDataEntity.setFKData(cacheQvvrData.getFKData()); + qvvrDataEntity.setHKData(cacheQvvrData.getHKData()); + qvvrDataEntity.harmData = cacheQvvrData.getHarmData(); + } else { + if (win == WINDOW_4) { + //当窗口为4时,两个时间限制范围在最小公倍数为15时,最起码有5个有效时间点,在最小公倍数为30时,最起码有3个有效时间点 + if (minMultiple == INTERVAL_TIME_15) { + if (minus < MINUS_5) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - MINUS_4; + + } else if (minMultiple == INTERVAL_TIME_30) { + if (minus < MINUS_3) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - MINUS_2; + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + } else if (win == WINDOW_96) { + //当窗口为96时,两个时间限值范围在最小公倍数为15时,最起码有97个有效时间点,在最小公倍数为30时,最起码有49个有效时间点 + if (minMultiple == INTERVAL_TIME_15) { + if (minus <= WINDOW_96) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - WINDOW_96; + } else if (minMultiple == INTERVAL_TIME_30) { + if (minus <= WINDOW_48) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - WINDOW_48; + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + qvvrDataEntity.resNum = resNum; + qvvrDataEntity.harmNum = minus; + //因为限值时间实际是含头含尾的,所以harmNum需要索引差值+1 + for (int i = timeStartIndex; i <= timeEndIndex; i++) { + harmData[i - timeStartIndex] = harmDataOriginal[i]; + } + qvvrDataEntity.harmData = harmData; + //FKData与HKData的值则等于resNum + for (int i = timeStartIndex; i < timeStartIndex + resNum; i++) { + FKdata[i - timeStartIndex] = fKdataOriginal[i]; + HKdata[i - timeStartIndex] = hKdataOriginal[i]; + } + + qvvrDataEntity.setFKData(FKdata); + qvvrDataEntity.setHKData(HKdata); + } + ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm(); + qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity); + if (qvvrDataEntity.calOk == 0) { + throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR); + } + + //没问题后,先玩动态责任数据 + List names = cacheQvvrData.getNames(); + CustomerData[] customerDatas = new CustomerData[qvvrDataEntity.pNode]; + float[][] fKdata/*无背景的动态责任数据*/ = qvvrDataEntity.getFKData(); + //第一个时间节点是起始时间+win窗口得到的时间 + Date sTime = new Date(); + sTime.setTime(times.get(timeStartIndex)); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(sTime); + calendar.add(Calendar.MINUTE, (win - 1) * minMultiple); + List timeDatas = new ArrayList<>(); + for (int i = 0; i < qvvrDataEntity.harmNum - qvvrDataEntity.win; i++) { + calendar.add(Calendar.MINUTE, minMultiple); + //一个时间点所有的用户数据 + float[] fKdatum = fKdata[i]; + for (int k = 0; k < qvvrDataEntity.pNode; k++) { + CustomerData customerData = customerDatas[k]; + if (null == customerData) { + customerData = new CustomerData(); + customerData.setCustomerName(names.get(k)); + } + List valueDatas = customerData.getValueDatas(); + Float valueTemp = fKdatum[k]; + if (valueTemp.isNaN()) { + valueTemp = 0.0f; + } + valueDatas.add(valueTemp); + customerData.setValueDatas(valueDatas); + customerDatas[k] = customerData; + } + timeDatas.add(calendar.getTimeInMillis()); + } + //OK拿到所有测量点的数据了,现在就是看如何将相同户号的动态数据进行算术和求值,之前的用户name为:户号@测量点号@用户名 + Map> customerDataTemp = new HashMap<>(32); + for (CustomerData data : customerDatas) { + String customerName = data.getCustomerName(); + String[] customerInfo = customerName.split("@"); + String name = customerInfo[2] + "(" + customerInfo[0] + ")"; + List customerData = customerDataTemp.get(name); + CustomerData customerTemp = data; + customerTemp.setCustomerName(name); + if (CollectionUtils.isEmpty(customerData)) { + customerData = new ArrayList<>(); + } + customerData.add(customerTemp); + customerDataTemp.put(name, customerData); + } + //调用程序接口后,首先组装责任量化结果 + float[] sumFKdata = qvvrDataEntity.sumFKdata; + List customerResponsibilities = getCustomerResponsibilityData(names, sumFKdata, qvvrDataEntity.pNode); + //根据前十的用户数据,获取这些用户的动态责任数据 + List customerData = new ArrayList<>(); + + for (CustomerResponsibility customerResponsibility : customerResponsibilities) { + String cusName = customerResponsibility.getCustomerName(); + List customerData1 = customerDataTemp.get(cusName); + if (CollectionUtils.isEmpty(customerData1)) { + continue; + } + if (customerData1.size() == 1) { + //表示用户唯一的 + customerData.add(customerData1.get(0)); + } else { + // 表示用户可能包含多个监测点号,需要进行数据累加 + CustomerData customerDataT = new CustomerData(); + customerDataT.setCustomerName(cusName); + //进行数值累加 + List valueDatas = new ArrayList<>(); + for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) { + float original = 0.0f; + for (CustomerData data : customerData1) { + original = original + data.getValueDatas().get(i); + } + valueDatas.add(original); + } + customerDataT.setValueDatas(valueDatas); + customerData.add(customerDataT); + } + } + //接着组装动态数据结果 + result.setResponsibilities(customerResponsibilities); + result.setDatas(customerData); + result.setTimeDatas(timeDatas); + + //首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性 + LambdaQueryWrapper respDataResultLambdaQueryWrapper1 = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper1.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime()) + .eq(RespDataResult::getStartTime, DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getEndTime, DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getLimitValue, responsibilitySecondCalParam.getLimitValue()); + RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper1); + if (Objects.isNull(respDataResult)) { + respDataResult = new RespDataResult(); + respDataResult.setResDataId(responsibilityData.getId()); + respDataResult.setTime(responsibilitySecondCalParam.getTime()); + respDataResult.setStartTime(DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setEndTime(DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setLimitValue(responsibilitySecondCalParam.getLimitValue()); + //时间横轴数据 timeDatas + JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas)); + InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString()); + String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setTimeData(timeDataPath); + //用户每时刻对应的责任数据 + JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData)); + InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString()); + String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserDetailData(customerPath); + //用户前10数据存储 + JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities)); + InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString()); + String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserResponsibility(customerResPath); + respDataResultService.save(respDataResult); + } + //防止过程中创建了大量的对象,主动调用下GC处理 + System.gc(); + result.setResponsibilityDataIndex(responsibilityData.getId()); + return result; + } + + @Override + public ResponsibilityResult getResponsibilityData(ResponsibilitySecondCalParam responsibilitySecondCalParam) { + ResponsibilityResult result = new ResponsibilityResult(); + //根据时间天数,获取理论上多少次用采数据 + RespData responsibilityData = this.baseMapper.selectById(responsibilitySecondCalParam.getResDataId()); + if (Objects.isNull(responsibilityData)) { + throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND); + } + Overlimit overlimit = overlimitMapper.selectById(responsibilityData.getLineId()); + //获取总数据 + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime()); + if (responsibilitySecondCalParam.getType() == 0) { + respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getIharm", responsibilitySecondCalParam.getTime())); + } else { + respDataResultLambdaQueryWrapper.eq(RespDataResult::getLimitValue, PubUtils.getValueByMethod(overlimit, "getUharm", responsibilitySecondCalParam.getTime())); + } + RespDataResult respDataResultTemp = respDataResultService.getOne(respDataResultLambdaQueryWrapper); + if (Objects.isNull(respDataResultTemp)) { + throw new BusinessException(AdvanceResponseEnum.RESP_DATA_NOT_FOUND); + } + CacheQvvrData cacheQvvrData; + try { + InputStream fileStream = fileStorageUtil.getFileStream(respDataResultTemp.getQvvrData()); + String qvvrDataStr = IoUtil.readUtf8(fileStream); + cacheQvvrData = PubUtils.json2obj(qvvrDataStr, CacheQvvrData.class); + + } catch (Exception exception) { + throw new BusinessException(AdvanceResponseEnum.RESP_RESULT_DATA_NOT_FOUND); + } + //获取成功后,延长该缓存的生命周期为初始生命时长 + int win = cacheQvvrData.getWin(); + //不管窗口为4或者96,都需要考虑最小公倍数 + //最小公倍数根据监测点测量间隔来获取,可以考虑也由第一步操作缓存起来 + int minMultiple = cacheQvvrData.getMinMultiple(); + //谐波横轴所有的时间 + List times = cacheQvvrData.getTimes(); + //首先根据窗口判断限值时间范围是否满足最小窗口 + Long limitSL = DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN).getTime(); + Long limitEL = DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN).getTime(); + List temp = getTimes(times, limitSL, limitEL); + //在动态责任数据中,时间的起始索引位置和截止索引位置 + Integer timeStartIndex = temp.get(0); + Integer timeEndIndex = temp.get(1); + //间隔中的时间长度 + int minus = timeEndIndex - timeStartIndex + 1; + //组装参数 + QvvrDataEntity qvvrDataEntity = new QvvrDataEntity(); + qvvrDataEntity.calFlag = 1; + qvvrDataEntity.pNode = cacheQvvrData.getPNode(); + qvvrDataEntity.harmMk = responsibilitySecondCalParam.getLimitValue(); + qvvrDataEntity.win = win; + int resNum; + float[][] FKdata = new float[9600][QvvrDataEntity.MAX_P_NODE]; + float[][] HKdata = new float[9600][QvvrDataEntity.MAX_P_NODE + 1]; + float[] harmData = new float[1440 * 100]; + float[][] fKdataOriginal = cacheQvvrData.getFKData(); + float[][] hKdataOriginal = cacheQvvrData.getHKData(); + float[] harmDataOriginal = cacheQvvrData.getHarmData(); + //如果起始索引与截止索引的差值等于时间轴的长度,则说明用户没有选择限值时间,直接带入全部的原始数据,参与计算即可 + if (minus == times.size()) { + qvvrDataEntity.harmNum = cacheQvvrData.getHarmNum(); + qvvrDataEntity.resNum = cacheQvvrData.getHarmNum() - cacheQvvrData.getWin(); + qvvrDataEntity.setFKData(cacheQvvrData.getFKData()); + qvvrDataEntity.setHKData(cacheQvvrData.getHKData()); + qvvrDataEntity.harmData = cacheQvvrData.getHarmData(); + } else { + if (win == WINDOW_4) { + //当窗口为4时,两个时间限制范围在最小公倍数为15时,最起码有5个有效时间点,在最小公倍数为30时,最起码有3个有效时间点 + if (minMultiple == INTERVAL_TIME_15) { + if (minus < MINUS_5) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - MINUS_4; + + } else if (minMultiple == INTERVAL_TIME_30) { + if (minus < MINUS_3) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - MINUS_2; + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + } else if (win == WINDOW_96) { + //当窗口为96时,两个时间限值范围在最小公倍数为15时,最起码有97个有效时间点,在最小公倍数为30时,最起码有49个有效时间点 + if (minMultiple == INTERVAL_TIME_15) { + if (minus <= WINDOW_96) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - WINDOW_96; + } else if (minMultiple == INTERVAL_TIME_30) { + if (minus <= WINDOW_48) { + throw new BusinessException(AdvanceResponseEnum.WIN_TIME_ERROR); + } + resNum = minus - WINDOW_48; + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + } else { + throw new BusinessException(AdvanceResponseEnum.CALCULATE_INTERVAL_ERROR); + } + qvvrDataEntity.resNum = resNum; + qvvrDataEntity.harmNum = minus; + //因为限值时间实际是含头含尾的,所以harmNum需要索引差值+1 + for (int i = timeStartIndex; i <= timeEndIndex; i++) { + harmData[i - timeStartIndex] = harmDataOriginal[i]; + } + qvvrDataEntity.harmData = harmData; + //FKData与HKData的值则等于resNum + for (int i = timeStartIndex; i < timeStartIndex + resNum; i++) { + FKdata[i - timeStartIndex] = fKdataOriginal[i]; + HKdata[i - timeStartIndex] = hKdataOriginal[i]; + } + + qvvrDataEntity.setFKData(FKdata); + qvvrDataEntity.setHKData(HKdata); + } +// ResponsibilityAlgorithm responsibilityAlgorithm = new ResponsibilityAlgorithm(); +// qvvrDataEntity = responsibilityAlgorithm.getResponsibilityResult(qvvrDataEntity); +// +// if (qvvrDataEntity.calOk == 0) { +// throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR); +// } + HarmonicData harmonicData = harmonicResponsibilityService.partialCalculation( + qvvrDataEntity.getHarmData(), qvvrDataEntity.getFKData(), qvvrDataEntity.getHKData(), qvvrDataEntity.getHarmNum(), qvvrDataEntity.getPNode(), qvvrDataEntity.getWin(), qvvrDataEntity.getResNum(), qvvrDataEntity.getHarmMk()); + if (harmonicData.getCalculationStatus() == CalculationStatus.FAILED) { + throw new BusinessException(AdvanceResponseEnum.RESPONSIBILITY_PARAMETER_ERROR); + } + + //没问题后,先玩动态责任数据 + List names = cacheQvvrData.getNames(); + CustomerData[] customerDatas = new CustomerData[harmonicData.getPowerNodeCount()]; + float[][] fKdata/*无背景的动态责任数据*/ = harmonicData.getFkData(); + //第一个时间节点是起始时间+win窗口得到的时间 + Date sTime = new Date(); + sTime.setTime(times.get(timeStartIndex)); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(sTime); + calendar.add(Calendar.MINUTE, (win - 1) * minMultiple); + List timeDatas = new ArrayList<>(); + for (int i = 0; i < harmonicData.getHarmonicCount() - harmonicData.getWindowSize(); i++) { + calendar.add(Calendar.MINUTE, minMultiple); + //一个时间点所有的用户数据 + float[] fKdatum = fKdata[i]; + for (int k = 0; k < harmonicData.getPowerNodeCount(); k++) { + CustomerData customerData = customerDatas[k]; + if (null == customerData) { + customerData = new CustomerData(); + customerData.setCustomerName(names.get(k)); + } + List valueDatas = customerData.getValueDatas(); + Float valueTemp = fKdatum[k]; + if (valueTemp.isNaN()) { + valueTemp = 0.0f; + } + valueDatas.add(valueTemp); + customerData.setValueDatas(valueDatas); + customerDatas[k] = customerData; + } + timeDatas.add(calendar.getTimeInMillis()); + } + //OK拿到所有测量点的数据了,现在就是看如何将相同户号的动态数据进行算术和求值,之前的用户name为:户号@测量点号@用户名 + Map> customerDataTemp = new HashMap<>(32); + for (CustomerData data : customerDatas) { + String customerName = data.getCustomerName(); + String[] customerInfo = customerName.split("@"); + String name = customerInfo[2] + "(" + customerInfo[0] + ")"; + List customerData = customerDataTemp.get(name); + CustomerData customerTemp = data; + customerTemp.setCustomerName(name); + if (CollectionUtils.isEmpty(customerData)) { + customerData = new ArrayList<>(); + } + customerData.add(customerTemp); + customerDataTemp.put(name, customerData); + } + //调用程序接口后,首先组装责任量化结果 + float[] sumFKdata = harmonicData.getSumFKData(); + List customerResponsibilities = getCustomerResponsibilityData(names, sumFKdata, harmonicData.getPowerNodeCount()); + //根据前十的用户数据,获取这些用户的动态责任数据 + List customerData = new ArrayList<>(); + + for (CustomerResponsibility customerResponsibility : customerResponsibilities) { + String cusName = customerResponsibility.getCustomerName(); + List customerData1 = customerDataTemp.get(cusName); + if (CollectionUtils.isEmpty(customerData1)) { + continue; + } + if (customerData1.size() == 1) { + //表示用户唯一的 + customerData.add(customerData1.get(0)); + } else { + // 表示用户可能包含多个监测点号,需要进行数据累加 + CustomerData customerDataT = new CustomerData(); + customerDataT.setCustomerName(cusName); + //进行数值累加 + List valueDatas = new ArrayList<>(); + for (int i = 0; i < customerData1.get(0).getValueDatas().size(); i++) { + float original = 0.0f; + for (CustomerData data : customerData1) { + original = original + data.getValueDatas().get(i); + } + valueDatas.add(original); + } + customerDataT.setValueDatas(valueDatas); + customerData.add(customerDataT); + } + } + //接着组装动态数据结果 + result.setResponsibilities(customerResponsibilities); + result.setDatas(customerData); + result.setTimeDatas(timeDatas); + + //首先判断有没有存储记录,没有则存储,有就略过 指定测点、时间窗口、谐波类型、谐波次数判断唯一性 + LambdaQueryWrapper respDataResultLambdaQueryWrapper1 = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper1.eq(RespDataResult::getResDataId, responsibilityData.getId()) + .eq(RespDataResult::getTime, responsibilitySecondCalParam.getTime()) + .eq(RespDataResult::getStartTime, DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getEndTime, DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN)) + .eq(RespDataResult::getLimitValue, responsibilitySecondCalParam.getLimitValue()); + RespDataResult respDataResult = respDataResultService.getOne(respDataResultLambdaQueryWrapper1); + if (Objects.isNull(respDataResult)) { + respDataResult = new RespDataResult(); + respDataResult.setResDataId(responsibilityData.getId()); + respDataResult.setTime(responsibilitySecondCalParam.getTime()); + respDataResult.setStartTime(DateUtil.parse(responsibilitySecondCalParam.getLimitStartTime(), DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setEndTime(DateUtil.parse(responsibilitySecondCalParam.getLimitEndTime(), DatePattern.NORM_DATETIME_PATTERN)); + respDataResult.setLimitValue(responsibilitySecondCalParam.getLimitValue()); + //时间横轴数据 timeDatas + JSONArray timeDataJson = JSONArray.parseArray(JSON.toJSONString(timeDatas)); + InputStream timeDataStream = IoUtil.toUtf8Stream(timeDataJson.toString()); + String timeDataPath = fileStorageUtil.uploadStream(timeDataStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setTimeData(timeDataPath); + //用户每时刻对应的责任数据 + JSONArray customerDataJson = JSONArray.parseArray(JSON.toJSONString(customerData)); + InputStream customerStream = IoUtil.toUtf8Stream(customerDataJson.toString()); + String customerPath = fileStorageUtil.uploadStream(customerStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserDetailData(customerPath); + //用户前10数据存储 + JSONArray customerResJson = JSONArray.parseArray(JSON.toJSONString(customerResponsibilities)); + InputStream customerResStream = IoUtil.toUtf8Stream(customerResJson.toString()); + String customerResPath = fileStorageUtil.uploadStream(customerResStream, OssPath.RESPONSIBILITY_USER_RESULT_DATA, FileUtil.generateFileName("json")); + respDataResult.setUserResponsibility(customerResPath); + respDataResultService.save(respDataResult); + } + //防止过程中创建了大量的对象,主动调用下GC处理 + System.gc(); + result.setResponsibilityDataIndex(responsibilityData.getId()); + return result; + } + + + /** + * 监测点测量间隔获取最后用于计算的功率数据 + * + * @param finalData 参数计算的功率数据 + */ + private Map>> dealFinalDataByLineInterval(Map>> finalData) { + DecimalFormat decimalFormat = new DecimalFormat("0.0000"); + Map>> result; + //当监测点测量间隔为10分钟时,功率数据需要调整为30分钟数据 + result = new HashMap<>(32); + Set userNames = finalData.keySet(); + for (String userName : userNames) { + Map> temp = new HashMap<>(32); + Map> original = finalData.get(userName); + Set dates = original.keySet(); + for (String date : dates) { + //某当天的数据 + List single = original.get(date); + //先根据事时间排序 + Collections.sort(single); + //此时根据当天所有的数据,重新计算出所有时间点的数据,担心这个过程会消耗过长时间 + List tempDatas = new ArrayList<>(); + for (int i = 0; i < WINDOW_96; i = i + 2) { + //30分钟内的2个15分钟功率数据相加作平均计算30分钟内的功率数据,最终的数据序列时间间隔30分钟。by 友谊文档 + UserDataExcel tempData = new UserDataExcel(); + tempData.setUserName(single.get(i).getUserName()); + tempData.setUserId(single.get(i).getUserId()); + tempData.setLine(single.get(i).getLine()); + tempData.setTime(single.get(i).getTime()); + //功率为 2个15分钟功率数据相加作平均 + double work = single.get(i).getWork().doubleValue() + single.get(i + 1).getWork().doubleValue(); + tempData.setWork(new BigDecimal(decimalFormat.format(work / 2.0))); + tempDatas.add(tempData); + } + temp.put(date, tempDatas); + } + result.put(userName, temp); + } + return result; + } + + /** + * 通过监测点测量间隔计算对齐后的谐波数据 + * 暂且认为最小公倍数就15、30两种可能 + * + * @param historyData 原始的谐波数据 + * @param lineInterval 测量间隔 + */ + private List getDataWithLineInterval(List historyData, int lineInterval) { + List result; + switch (lineInterval) { + case 1: + result = getHarmResultByTimes(historyData, 15); + break; + case 3: + result = getHarmResultByTimes(historyData, 5); + break; + // 间隔为5、10时,直接返回即可 + default: + result = getHarmResultByTimes(historyData, 3); + break; + } + return result.stream().sorted(Comparator.comparing(HarmData::getTime)).collect(Collectors.toList()); + } + + /** + * 通过监测点测量间隔计算对齐后的谐波数据 + * + * @param historyData 原始的谐波数据 + */ + private List getHarmResultByTimes(List historyData, int times) { + List result = new ArrayList<>(); + DecimalFormat decimalFormat = new DecimalFormat("0.0000"); + for (int i = 0; i < historyData.size(); i = i + times) { + float temp = 0.0f; + for (int j = 0; j < times; j++) { + int index = i + j; + temp = temp + historyData.get(index).getValue(); + } + //求平均值 + temp = Float.parseFloat(decimalFormat.format(temp / (float) times)); + HarmData resTemp = new HarmData(); + resTemp.setTime(historyData.get(i).getTime()); + resTemp.setValue(temp); + result.add(resTemp); + } + return result; + } + + /** + * 根据接口返回值组装需要显示的责任量化数据 + */ + private List getCustomerResponsibilityData(List names, float[] sumFKdata, int pNode) { + Map customerResponsibilityMap = new HashMap<>(16); + for (int i = 0; i < pNode; i++) { + /*用户ID 测量点ID 用户名*/ + String[] customerInfo = names.get(i).split("@"); + String name = customerInfo[2] + "(" + customerInfo[0] + ")"; + CustomerResponsibility customerResponsibility; + if (customerResponsibilityMap.containsKey(name)) { + customerResponsibility = customerResponsibilityMap.get(name); + customerResponsibility.setResponsibilityData(customerResponsibility.getResponsibilityData() + sumFKdata[i]); + } else { + customerResponsibility = new CustomerResponsibility(); + customerResponsibility.setCustomerName(name); + customerResponsibility.setResponsibilityData(sumFKdata[i]); + } + customerResponsibilityMap.put(name, customerResponsibility); + } + //map转为list + List customerResponsibilities = new ArrayList<>(); + Set cusNames = customerResponsibilityMap.keySet(); + for (String cusName : cusNames) { + customerResponsibilities.add(customerResponsibilityMap.get(cusName)); + } + //取出前十的用户责任数据 + customerResponsibilities = customerResponsibilities.stream().sorted(Comparator.comparing(CustomerResponsibility::getResponsibilityData).reversed()).collect(Collectors.toList()); + if (customerResponsibilities.size() > SORT_10) { + //当用户超出10,将前十用户保留,然后剩余归类为其他用户 + float tenTotal = 0.0f; + for (int i = 0; i < SORT_10; i++) { + float temp = PubUtils.floatRound(3, customerResponsibilities.get(i).getResponsibilityData()); + tenTotal = tenTotal + temp; + } + int size = customerResponsibilities.size() - 10; + customerResponsibilities = customerResponsibilities.subList(0, 10); + CustomerResponsibility others = new CustomerResponsibility(); + others.setCustomerName("其他用户(" + size + ")"); + others.setResponsibilityData(PubUtils.floatRound(3, 100.0f - tenTotal)); + customerResponsibilities.add(others); + } + return customerResponsibilities; + } + + /** + * 根据起始时间获取在集合中最接近的起始和截止值 + * + * @param times 时间集合 + * @param limitSL 起始值 + * @param limitEL 截止值 + */ + private List getTimes(List times, Long limitSL, Long limitEL) { + List result = new ArrayList<>(); + Integer temps = null; + Integer tempe = null; + //因为可以知道times是为4的倍数,所以长度肯定是偶数,不会出现索引越界的异常 + if (limitSL < times.get(0)) { + temps = 0; + } + if (limitEL > times.get(times.size() - 1)) { + tempe = times.size() - 1; + } + for (int i = 0; i < times.size() - 1; i++) { + if (temps != null & tempe != null) { + //判断都已经赋值后,跳出循环 + break; + } + //锁定前值 + if (times.get(i).equals(limitSL)) { + //相等则给起始时间赋值 + temps = i; + } else if (times.get(i + 1).equals(limitSL)) { + temps = i + 1; + } else if (times.get(i) < limitSL & times.get(i + 1) > limitSL) { + //当起始时间处于中间时,将后值赋值给temps + temps = i + 1; + } + //锁定后值 + if (times.get(i).equals(limitEL)) { + //相等则给起始时间赋值 + tempe = i; + } else if (times.get(i + 1).equals(limitEL)) { + tempe = i + 1; + } else if (times.get(i) < limitEL & times.get(i + 1) > limitEL) { + //当起始时间处于中间时,将前值赋值给temps + tempe = i; + } + } + if (temps == null) { + temps = 0; + } + if (tempe == null) { + tempe = times.size() - 1; + } + result.add(temps); + result.add(tempe); + return result; + } + + + /*** + * 用采数据,根据用户选择的时间窗口过滤出稍后用于计算的用采数据 + */ + private Map>> getFinalUserData(DealDataResult dealDataResult, List dateStr) { + Map>> totalData = dealDataResult.getTotalListData(); + Map>> finalData = new HashMap<>(16); + /*第一个参数pNode 如果时间范围内完整性不足90%的节点,不参与责任量化统计,因为之前处理过用采数据,此时只需要判断是否满足100%就可以判断*/ + int dueCounts = dateStr.size() * 96; + Set userNames = totalData.keySet(); + for (String userName : userNames) { + int realCounts = 0; + Map> temp = totalData.get(userName); + for (String date : dateStr) { + if (CollectionUtil.isNotEmpty(temp.get(date))) { + realCounts = realCounts + temp.get(date).size(); + } + } + if (realCounts == dueCounts) { + //只有期望和实际数量一致的时候才作为计算用户 + finalData.put(userName, temp); + } + } + return finalData; + } + + /*** + * 处理获取pNum参数 + */ + private RespCommon getPNumAndInterval(Map>> finalData, String lineId, List dateStr) { + int pNum; + LineDetailDataVO lineDetailData = lineService.getLineDetailData(lineId); + int lineInterval = lineDetailData.getTimeInterval(); + int userIntervalTime; + if (lineInterval == INTERVAL_TIME_1 || lineInterval == INTERVAL_TIME_3 || lineInterval == INTERVAL_TIME_5) { + userIntervalTime = INTERVAL_TIME_15; + pNum = dateStr.size() * WINDOW_96; + } else { + userIntervalTime = INTERVAL_TIME_30; + pNum = dateStr.size() * WINDOW_48; + finalData = dealFinalDataByLineInterval(finalData); + } + return new RespCommon(pNum, userIntervalTime, lineInterval); + } + + + /*** + * 获取责任需要的谐波数据 + */ + private RespHarmData getRespHarmData(ResponsibilityCalculateParam responsibilityCalculateParam, int lineInterval) { + HarmHistoryDataDTO data = historyHarmonicService.getHistoryHarmData(new HistoryHarmParam(responsibilityCalculateParam.getSearchBeginTime(), responsibilityCalculateParam.getSearchEndTime(), responsibilityCalculateParam.getLineId(), responsibilityCalculateParam.getType(), responsibilityCalculateParam.getTime())); + List historyData = data.getHistoryData(); + historyData = getDataWithLineInterval(historyData, lineInterval); + //理论上此处的historyData的长度等于pNum,开始填充harm_data + float[] harmData = new float[144000]; + //谐波波形的横轴时间集合 + List harmTime = new ArrayList<>(); + for (int i = 0; i < historyData.size(); i++) { + Float value = historyData.get(i).getValue(); +// if (value != null) { +// value = value * 1000; +// } + harmData[i] = value; + harmTime.add(PubUtils.instantToDate(historyData.get(i).getTime()).getTime()); + } + return new RespHarmData(harmData, harmTime, data.getOverLimit()); + } + + + /** + * 获取背景用户的下级用户及其数据 + */ + + public List test(List userList, String startTime, String endTime){ + List userDataExcelList = new ArrayList<>(); + PHistoryHarmParam param = new PHistoryHarmParam(); + param.setSearchBeginTime(startTime); + param.setSearchEndTime(endTime); + param.setLineIds(userList); + List dataHarmPList = historyHarmonicService.getHarmonicPData(param); + Map> collect = dataHarmPList.stream().collect(Collectors.groupingBy(DataHarmPowerP::getLineId)); + List result = new ArrayList<>(); + collect.forEach((k,v)->{ + LineDetailDataVO lineDetailData = lineService.getLineDetailData(k); + + //数据补全 + List dataHarmPowerPList = linearInterpolate(startTime.concat(InfluxDBTableConstant.START_TIME), endTime.concat(InfluxDBTableConstant.END_TIME), lineDetailData.getTimeInterval()*60, v); + //数据间隔转换成15分钟 + dataHarmPowerPList =convertTo15MinuteInterval(dataHarmPowerPList,lineDetailData.getTimeInterval()); + List userDataExcels = dataHarmPowerPList.stream().map(temp -> { + UserDataExcel userDataExcel = new UserDataExcel(); + userDataExcel.setTime(format.format(temp.getTime().atZone(ZoneId.systemDefault()))); + userDataExcel.setWork(BigDecimal.valueOf(temp.getP())); + userDataExcel.setUserId(k); + userDataExcel.setUserName(lineDetailData.getObjName()); + + return userDataExcel; + }).collect(Collectors.toList()); + + userDataExcelList.addAll(userDataExcels); + }); + + System.out.println(result.size()); + + return userDataExcelList; + } + + private static List convertTo15MinuteInterval(List dataHarmPowerPList, int interval) { + List result = new ArrayList<>(); + Instant startTime = dataHarmPowerPList.get(0).getTime(); + Instant endTime = dataHarmPowerPList.get(dataHarmPowerPList.size()-1).getTime(); + //向内寻找15分钟的约数 + while (startTime.atZone(ZoneId.systemDefault()).getMinute()%15!=0 ){ + startTime = startTime.plusSeconds(60); + } + while (endTime.atZone(ZoneId.systemDefault()).getMinute()%15!=0 ){ + endTime = endTime.minusSeconds(60); + } + + Instant currentTime = startTime; + List timePoints15Min = new ArrayList<>(); + + while (!currentTime.isAfter(endTime)) { + timePoints15Min.add(currentTime); + currentTime = currentTime.plusSeconds(15*60); + } + + if(interval==1||interval==3||interval==5){ + result = dataHarmPowerPList.stream().filter(temp->timePoints15Min.contains(temp.getTime())).collect(Collectors.toList()); + } + else if(interval==10){ + // 对每个15分钟时间点处理数据 + for (Instant targetTime : timePoints15Min) { + // 查找目标时间点前后最近的两个10分钟数据点 + DataHarmPowerP before = null; + DataHarmPowerP after = null; + + for (DataHarmPowerP data : dataHarmPowerPList) { + if (!data.getTime().isAfter(targetTime)) { + before = data; + } else { + after = data; + break; + } + } + + Double value; + + // 如果正好有10分钟数据点在这个15分钟时间点上 + if (before != null && before.getTime().equals(targetTime)) { + value = before.getP(); + } + // 如果目标时间点正好在两个10分钟数据点中间 + else if (before != null && after != null) { + // 计算平均值 + value = (before.getP() + after.getP()) / 2.0; + } + // 如果只有前一个点(边界情况) + else if (before != null) { + value = before.getP(); + } + // 如果只有后一个点(边界情况) + else if (after != null) { + value = after.getP(); + } + // 理论上不会发生 + else { + continue; + } + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + dataHarmPowerP.setP(value); + dataHarmPowerP.setTime(targetTime); + dataHarmPowerP.setLineId(dataHarmPowerPList.get(0).getLineId()); + result.add(dataHarmPowerP); + } + }else { + throw new BusinessException(AdvanceResponseEnum.INTERVAL_ERROR); + } + return result; + } + + + /** + * 将字符串时间转换为Instant + * @param timeStr 时间字符串,格式为"yyyy-MM-dd HH:mm:ss" + * @return Instant对象 + */ + private static Instant parseTime(String timeStr) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime localDateTime = LocalDateTime.parse(timeStr, formatter); + return localDateTime.atZone(ZoneId.systemDefault()).toInstant(); + } + + /** + * 线性补全时间序列数据 + * @param startTimeStr 开始时间字符串 + * @param endTimeStr 结束时间字符串 + * @param interval 数据时间间隔(秒) + * @param originalData 原始数据列表 + * @return 补全后的数据列表 + */ + public static List linearInterpolate(String startTimeStr, String endTimeStr, int interval, List originalData) { + List result = new ArrayList<>(); + + // 如果原始数据为空,直接返回空列表 + if (originalData == null || originalData.isEmpty()) { + return result; + } + + // 解析时间字符串 + Instant startTime = parseTime(startTimeStr); + Instant endTime = parseTime(endTimeStr); + + + + + // 按时间排序 + originalData.sort(Comparator.comparing(DataHarmPowerP::getTime)); + + // 创建时间点列表 + List timePoints = new ArrayList<>(); + Instant currentTime = startTime; + while (!currentTime.isAfter(endTime)) { + timePoints.add(currentTime); + currentTime = currentTime.plusSeconds(interval); + } + + // 使用双指针进行线性插值 + int dataIndex = 0; + for (Instant currentPoint : timePoints) { + + // 如果当前时间点早于所有数据点,使用第一个数据点的值 + if (currentPoint.isBefore(originalData.get(0).getTime())) { + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + + dataHarmPowerP.setP(originalData.get(0).getP()); + dataHarmPowerP.setTime(currentPoint); + dataHarmPowerP.setLineId(originalData.get(0).getLineId()); + result.add(dataHarmPowerP); + continue; + } + + // 如果当前时间点晚于所有数据点,使用最后一个数据点的值 + if (currentPoint.isAfter(originalData.get(originalData.size() - 1).getTime())) { + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + + dataHarmPowerP.setP(originalData.get(originalData.size() - 1).getP()); + dataHarmPowerP.setTime(currentPoint); + dataHarmPowerP.setLineId(originalData.get(0).getLineId()); + result.add(dataHarmPowerP); + + continue; + } + + // 找到当前时间点所在的数据区间 + while (dataIndex < originalData.size() - 1 && + originalData.get(dataIndex + 1).getTime().isBefore(currentPoint)) { + dataIndex++; + } + + // 如果正好有数据点在这个时间点上 + if (originalData.get(dataIndex).getTime().equals(currentPoint)) { + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + + dataHarmPowerP.setP( originalData.get(dataIndex).getP()); + dataHarmPowerP.setTime(currentPoint); + dataHarmPowerP.setLineId(originalData.get(0).getLineId()); + result.add(dataHarmPowerP); + + continue; + } + + // 如果当前时间点在前一个数据点和后一个数据点之间,进行线性插值 + DataHarmPowerP prev = originalData.get(dataIndex); + DataHarmPowerP next = originalData.get(dataIndex + 1); + + long timeDiff = next.getTime().getEpochSecond() - prev.getTime().getEpochSecond(); + long currentDiff = currentPoint.getEpochSecond() - prev.getTime().getEpochSecond(); + + double slope = (next.getP() - prev.getP()) / timeDiff; + double interpolatedValue = prev.getP() + slope * currentDiff; + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + + dataHarmPowerP.setP( interpolatedValue); + dataHarmPowerP.setTime(currentPoint); + dataHarmPowerP.setLineId(originalData.get(0).getLineId()); + result.add(dataHarmPowerP); + } + + + return result; + } + + public static void main(String[] args) { + // 创建测试数据 - 10分钟间隔 + List testData = new ArrayList<>(); + Instant baseTime = Instant.parse("2025-01-01T00:10:00Z"); + + + // 创建10分钟间隔的数据点 (0, 10, 20, 30, 40, 50分钟) + for (int i = 0; i < 13; i++) { + DataHarmPowerP dataHarmPowerP = new DataHarmPowerP(); + dataHarmPowerP.setP(10.0 + i * 2.0); + + dataHarmPowerP.setTime(baseTime.plusSeconds(i * 600)); + dataHarmPowerP.setLineId("123"); + testData.add(dataHarmPowerP); + } + + + + System.out.println("原始数据 (10分钟间隔):"); + for (DataHarmPowerP data : testData) { + ZonedDateTime zdt = data.getTime().atZone(ZoneId.systemDefault()); + System.out.println(data.getLineId() + " - " + + zdt.getHour() + ":" + + String.format("%02d", zdt.getMinute()) + + " - " + data.getP()); + } + + // 转换为15分钟间隔 + List convertedData = convertTo15MinuteInterval(testData,10); + + System.out.println("\n转换后的数据 (15分钟间隔):"); + for (DataHarmPowerP data : convertedData) { + ZonedDateTime zdt = data.getTime().atZone(ZoneId.systemDefault()); + System.out.println(data.getLineId() + " - " + + zdt.getHour() + ":" + + String.format("%02d", zdt.getMinute()) + + " - " + data.getP()); + } + + // 按lineId分组显示结果 + Map> groupedResults = new HashMap<>(); + for (DataHarmPowerP data : convertedData) { + groupedResults.putIfAbsent(data.getLineId(), new ArrayList<>()); + groupedResults.get(data.getLineId()).add(data); + } + + System.out.println("\n按lineId分组的结果:"); + for (String lineId : groupedResults.keySet()) { + System.out.println("Line: " + lineId); + for (DataHarmPowerP data : groupedResults.get(lineId)) { + ZonedDateTime zdt = data.getTime().atZone(ZoneId.systemDefault()); + System.out.println(" " + zdt.getHour() + ":" + + String.format("%02d", zdt.getMinute()) + + ": " + data.getP()); + } + } + } + + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataIntegrityServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataIntegrityServiceImpl.java new file mode 100644 index 0000000..cc128a2 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataIntegrityServiceImpl.java @@ -0,0 +1,33 @@ +package com.njcn.product.advance.responsility.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.product.advance.responsility.mapper.RespUserDataIntegrityMapper; +import com.njcn.product.advance.responsility.pojo.param.UserDataIntegrityParam; +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; +import com.njcn.product.advance.responsility.service.IRespUserDataIntegrityService; +import com.njcn.web.factory.PageFactory; +import org.springframework.stereotype.Service; + + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +@Service +public class RespUserDataIntegrityServiceImpl extends ServiceImpl implements IRespUserDataIntegrityService { + + @Override + public Page userDataIntegrityList(UserDataIntegrityParam userDataIntegrityParam) { + QueryWrapper lambdaQueryWrapper = new QueryWrapper<>(); + lambdaQueryWrapper.eq("pqs_resp_user_data_integrity.user_data_id", userDataIntegrityParam.getUserDataId()) + .orderByDesc("pqs_resp_user_data_integrity.create_time").like("pqs_resp_user_data_integrity.user_name",userDataIntegrityParam.getSearchValue()); + return this.baseMapper.page(new Page<>(PageFactory.getPageNum(userDataIntegrityParam), PageFactory.getPageSize(userDataIntegrityParam)), lambdaQueryWrapper); + } +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataServiceImpl.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataServiceImpl.java new file mode 100644 index 0000000..13b5850 --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/service/impl/RespUserDataServiceImpl.java @@ -0,0 +1,486 @@ +package com.njcn.product.advance.responsility.service.impl; + +import cn.afterturn.easypoi.excel.ExcelImportUtil; +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.handler.inter.IReadHandler; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.date.LocalDateTimeUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.text.StrPool; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.common.pojo.dto.SelectOption; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.FileUtil; +import com.njcn.common.utils.PubUtils; +import com.njcn.db.mybatisplus.constant.DbConstant; +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.advance.responsility.mapper.RespUserDataMapper; +import com.njcn.product.advance.responsility.pojo.bo.DealDataResult; +import com.njcn.product.advance.responsility.pojo.bo.DealUserDataResult; +import com.njcn.product.advance.responsility.pojo.bo.UserDataExcel; +import com.njcn.product.advance.eventSource.pojo.enums.AdvanceResponseEnum; +import com.njcn.product.advance.responsility.pojo.po.RespUserData; +import com.njcn.product.advance.responsility.pojo.po.RespUserDataIntegrity; +import com.njcn.product.advance.responsility.service.IRespUserDataIntegrityService; +import com.njcn.product.advance.responsility.service.IRespUserDataService; +import com.njcn.web.factory.PageFactory; +import com.njcn.web.pojo.param.BaseParam; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2023-07-13 + */ +@Service +@RequiredArgsConstructor +public class RespUserDataServiceImpl extends ServiceImpl implements IRespUserDataService { + + private final FileStorageUtil fileStorageUtil; + + private final IRespUserDataIntegrityService respUserDataIntegrityService; + + @Override + public void uploadUserData(MultipartFile file, HttpServletResponse response) { + ImportParams params = new ImportParams(); + List userDataExcels = new ArrayList<>(); + try { + // 显式设置SAX解析器(如果添加依赖后仍有问题) + System.setProperty("org.xml.sax.driver", "org.apache.xerces.parsers.SAXParser"); + + ExcelImportUtil.importExcelBySax(file.getInputStream(), UserDataExcel.class, params, new IReadHandler() { + @Override + public void handler(UserDataExcel o) { + userDataExcels.add(o); + } + + @Override + public void doAfterAll() { + + } + }); + //处理用户上传的用采数据内容 + analysisUserData(userDataExcels, file.getOriginalFilename()); + } catch (Exception e) { + throw new BusinessException(AdvanceResponseEnum.ANALYSIS_USER_DATA_ERROR); + } + } + + @Override + public Page userDataList(BaseParam queryParam) { + QueryWrapper respUserDataQueryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + //查询参数不为空,进行条件填充 + if (StrUtil.isNotBlank(queryParam.getSearchValue())) { + //仅提供用采名称 + respUserDataQueryWrapper.and(param -> param.like("pqs_resp_user_data.name", queryParam.getSearchValue())); + } + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + respUserDataQueryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + //没有排序参数,默认根据sort字段排序,没有排序字段的,根据updateTime更新时间排序 + respUserDataQueryWrapper.orderBy(true, false, "pqs_resp_user_data.update_time"); + } + } else { + respUserDataQueryWrapper.orderBy(true, false, "pqs_resp_user_data.update_time"); + } + respUserDataQueryWrapper.eq("pqs_resp_user_data.state", DataStateEnum.ENABLE.getCode()); + return this.baseMapper.page(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), respUserDataQueryWrapper); + } + + @Override + public List userDataSelect() { + List selectOptions = new ArrayList<>(); + LambdaQueryWrapper respUserDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respUserDataLambdaQueryWrapper.eq(RespUserData::getState, DataStateEnum.ENABLE.getCode()) + .orderByDesc(RespUserData::getUpdateTime); + List respUserData = this.baseMapper.selectList(respUserDataLambdaQueryWrapper); + if (CollectionUtil.isNotEmpty(respUserData)) { + selectOptions = respUserData.stream().map(temp -> new SelectOption(temp.getName(), temp.getId())).collect(Collectors.toList()); + } + return selectOptions; + } + + @Override + public void deleteUserDataByIds(List ids) { + this.baseMapper.deleteUserDataByIds(ids); + } + + @Override + public List getUserDataExcelList(String userDataId) { + LambdaQueryWrapper userDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + userDataLambdaQueryWrapper.eq(RespUserData::getId, userDataId).eq(RespUserData::getState, DataStateEnum.ENABLE.getCode()); + RespUserData respUserData = this.getOne(userDataLambdaQueryWrapper); + if (Objects.isNull(respUserData)) { + throw new BusinessException(AdvanceResponseEnum.USER_DATA_NOT_FOUND); + } + InputStream fileStream = fileStorageUtil.getFileStream(respUserData.getDataPath()); + String excelDataStr = IoUtil.read(fileStream, CharsetUtil.UTF_8); + //将文件流转为list集合 + List userDataExcels = JSONArray.parseArray(excelDataStr, UserDataExcel.class); + if (CollectionUtils.isEmpty(userDataExcels)) { + throw new BusinessException(AdvanceResponseEnum.USER_DATA_NOT_FOUND); + } + return userDataExcels; + } + + + /** + * 根据流获取出用采有功功率数据 + */ + private void analysisUserData(List userDataExcelList, String fileName) { + List exportExcelList = new ArrayList<>(); + RespUserData respUserData; + //判断数据提取情况 + if (CollectionUtils.isEmpty(userDataExcelList)) { + throw new BusinessException(AdvanceResponseEnum.USER_DATA_EMPTY); + } + DealDataResult dealDataResult = getStanderData(userDataExcelList, 0); + Map>> totalData = dealDataResult.getTotalData(); + //收集所有的日期,以便获取起始日期和截止日期 + List dates = dealDataResult.getDates(); + //将前面获取出来的日期进行排序,提供入库 + List resultDates = getSortDate(dates); + LocalDate endTime = resultDates.get(resultDates.size() - 1); + LocalDate startTime = resultDates.get(0); + //针对每个用户的数据进行完整度的判断 todo 暂且认为所有用户的时间跨度是一样的,比如都是15天或者都是30天,不存在有的用户5天数据,有的用户10天数据 + Map> tempResult = new HashMap<>(); + List respUserDataIntegrities = new ArrayList<>(); + Set userNames = totalData.keySet(); + for (String name : userNames) { + Map> userDataTemp = totalData.get(name); + //现在数据拿到了,但是因为是hashkey,所以日期顺序是乱的-->怎么变成有序的呢 + Set times = userDataTemp.keySet(); + //循环日期处理数据 + for (String time : times) { + DealUserDataResult dealtData = dealUserData(name, userDataTemp.get(time), time, 15); + List UserDataExcelTemp = dealtData.getCompleted(); + List UserDataExcel; + if (CollectionUtils.isEmpty(UserDataExcelTemp) && Objects.nonNull(dealtData.getRespUserDataIntegrity())) { + //为空,说明补齐操作没有进行,选择填充缺失数据即可 + respUserDataIntegrities.add(dealtData.getRespUserDataIntegrity()); + UserDataExcel = dealtData.getLack(); + } else { + //填充补齐完整性后的数据 + UserDataExcel = UserDataExcelTemp; + } + List userDatas = tempResult.get(name); + if (CollectionUtil.isNotEmpty(UserDataExcel)) { + if (CollectionUtils.isEmpty(userDatas)) { + userDatas = new ArrayList<>(UserDataExcel); + } else { + userDatas.addAll(UserDataExcel); + } + } + tempResult.put(name, userDatas); + } + } + //完成后,开始将数据按公司排序,然后输出到指定表格中,方便下次使用 + for (String name : userNames) { + List tempUserData = tempResult.get(name); + //按时间排序 + Collections.sort(tempUserData); + exportExcelList.addAll(tempUserData); + } + //输出到报表中 + String fileNameWithOutSuffix = fileName.substring(0, fileName.indexOf('.')); + fileNameWithOutSuffix = fileNameWithOutSuffix.concat(LocalDateTimeUtil.format(startTime, DatePattern.PURE_DATE_PATTERN)).concat(StrPool.DASHED).concat(LocalDateTimeUtil.format(endTime, DatePattern.PURE_DATE_PATTERN)); + //处理完后的用采数据,生成json文件流到oss服务器 + JSONArray finalUserData = JSONArray.parseArray(JSON.toJSONString(exportExcelList)); + InputStream reportStream = IoUtil.toStream(finalUserData.toString(), CharsetUtil.UTF_8); + String ossPath = fileStorageUtil.uploadStream(reportStream, OssPath.RESPONSIBILITY_USER_DATA, FileUtil.generateFileName("json")); + //入库前进行查询操作,存在则更新,不存在则插入 + LambdaQueryWrapper respUserDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respUserDataLambdaQueryWrapper.eq(RespUserData::getName, fileNameWithOutSuffix) + .eq(RespUserData::getStartTime, startTime) + .eq(RespUserData::getEndTime, endTime) + .eq(RespUserData::getState, DataStateEnum.ENABLE.getCode()); + respUserData = this.baseMapper.selectOne(respUserDataLambdaQueryWrapper); + //不存在则插入 + if (Objects.isNull(respUserData)) { + respUserData = new RespUserData(); + respUserData.setEndTime(endTime); + respUserData.setStartTime(startTime); + respUserData.setName(fileNameWithOutSuffix); + respUserData.setDataPath(ossPath); + respUserData.setState(DataStateEnum.ENABLE.getCode()); + this.baseMapper.insert(respUserData); + if (CollectionUtil.isNotEmpty(respUserDataIntegrities)) { + //关联插入数据 户号,监测点号,户名,时间,完整性 + for (RespUserDataIntegrity respUserDataIntegrity : respUserDataIntegrities) { + respUserDataIntegrity.setUserDataId(respUserData.getId()); + } + //插入操作 + respUserDataIntegrityService.saveBatch(respUserDataIntegrities); + respUserData.setIntegrity(1); + } else { + respUserData.setIntegrity(0); + } + this.baseMapper.updateById(respUserData); + } else { + //存在则更新,需要删除之前的oss文件 + fileStorageUtil.deleteFile(respUserData.getDataPath()); + if (CollectionUtil.isNotEmpty(respUserDataIntegrities)) { + LambdaQueryWrapper respUserDataIntegrityLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respUserDataIntegrityLambdaQueryWrapper.eq(RespUserDataIntegrity::getUserDataId, respUserData.getId()); + respUserDataIntegrityService.remove(respUserDataIntegrityLambdaQueryWrapper); + for (RespUserDataIntegrity respUserDataIntegrity : respUserDataIntegrities) { + respUserDataIntegrity.setUserDataId(respUserData.getId()); + } + //插入操作 + respUserDataIntegrityService.saveBatch(respUserDataIntegrities); + respUserData.setIntegrity(1); + } else { + respUserData.setIntegrity(0); + } + respUserData.setDataPath(ossPath); + this.baseMapper.updateById(respUserData); + } + + } + + /** + * 解析用采数据为一个标准格式 + */ + public static DealDataResult getStanderData(List userDataExcelBodies, int flag) { + DealDataResult result = new DealDataResult(); + //收集所有的日期,以便获取起始日期和截止日期 + List dates = new ArrayList<>(); + Map>> totalData = new HashMap<>(); + Map>> totalListData = new HashMap<>(); + for (UserDataExcel UserDataExcel : userDataExcelBodies) { + //第一个key + String key = UserDataExcel.getUserId() + "@" + UserDataExcel.getLine() + "@" + UserDataExcel.getUserName(); + String time = UserDataExcel.getTime().substring(0, 10); + if (!dates.contains(time)) { + dates.add(time); + } + if (!totalData.containsKey(key)) { + if (flag == 0) { + //Map形式,避免后面补齐数据嵌套循环 + Map userDatas = new HashMap<>(); + userDatas.put(PubUtils.getSecondsAsZero(DateUtil.parse(UserDataExcel.getTime(), DatePattern.NORM_DATETIME_PATTERN)), UserDataExcel); + Map> dataToUserDatas = new HashMap<>(); + dataToUserDatas.put(time, userDatas); + totalData.put(key, dataToUserDatas); + } else if (flag == 1) { + //List形式,避免后面责任数据提取嵌套循环 + List userListDatas = new ArrayList<>(); + userListDatas.add(UserDataExcel); + Map> dataToUserListDatas = new HashMap<>(); + dataToUserListDatas.put(time, userListDatas); + totalData.put(key, new HashMap<>()); + totalListData.put(key, dataToUserListDatas); + } + } else { + if (flag == 0) { + //Map形式,避免后面补齐数据嵌套循环 + Map> dataToUserDatas = totalData.get(key); + Map userDatas = dataToUserDatas.get(time); + //某日凌晨,还没存放该日的数据 + if (CollectionUtils.isEmpty(userDatas)) { + userDatas = new HashMap<>(); + userDatas.put(PubUtils.getSecondsAsZero(DateUtil.parse(UserDataExcel.getTime(), DatePattern.NORM_DATETIME_PATTERN)), UserDataExcel); + dataToUserDatas.put(time, userDatas); + } else { + //累加该日的数据 + userDatas.put(PubUtils.getSecondsAsZero(DateUtil.parse(UserDataExcel.getTime(), DatePattern.NORM_DATETIME_PATTERN)), UserDataExcel); + dataToUserDatas.put(time, userDatas); + } + totalData.put(key, dataToUserDatas); + } else if (flag == 1) { + //List形式,避免后面责任数据提取嵌套循环 + Map> dataToUserListDatas = totalListData.get(key); + List userListDatas = dataToUserListDatas.get(time); + if (CollectionUtils.isEmpty(userListDatas)) { + userListDatas = new ArrayList<>(); + userListDatas.add(UserDataExcel); + dataToUserListDatas.put(time, userListDatas); + } else { + userListDatas.add(UserDataExcel); + dataToUserListDatas.put(time, userListDatas); + } + totalListData.put(key, dataToUserListDatas); + } + } + + } + result.setDates(dates); + result.setTotalData(totalData); + result.setTotalListData(totalListData); + return result; + } + + /** + * 将日期排序后返回 + */ + private List getSortDate(List dates) { + List result = new ArrayList<>(); + for (String date : dates) { + LocalDate temp = LocalDateTimeUtil.parseDate(date, DatePattern.NORM_DATE_PATTERN); + result.add(temp); + } + if (!CollectionUtils.isEmpty(result)) { + Collections.sort(result); + } + return result; + } + + + /** + * 处理用户每日数据 + * + * @param name 用户名 + * @param beforeDeal 处理前的用户数据 + */ + private DealUserDataResult dealUserData(String name, Map beforeDeal, String time, int step) { + DealUserDataResult result = new DealUserDataResult(); + String[] userFlag = name.split("@"); + //每天的最开是的数据是从00:00:00开始的,所以起始时间为time + 00:00:00 + List completed = new ArrayList<>(); + List lack = new ArrayList<>(); + if (CollectionUtils.isEmpty(beforeDeal)) { + return result; + } else { + String timeTemp = time + " 00:00:00"; + Date date = DateUtil.parse(timeTemp, DatePattern.NORM_DATETIME_PATTERN); + int count = 24 * 60 / 15; + if ((float) beforeDeal.size() / (float) count < 0.9) { + Set dates = beforeDeal.keySet(); + for (Date tempDate : dates) { + UserDataExcel UserDataExcel = beforeDeal.get(tempDate); + if (UserDataExcel.getWork() != null) { + lack.add(UserDataExcel); + } + } + RespUserDataIntegrity respUserDataIntegrity = new RespUserDataIntegrity(); + respUserDataIntegrity.setIntegrity(BigDecimal.valueOf((double) lack.size() / 96.0)); + respUserDataIntegrity.setLackDate(LocalDateTimeUtil.parseDate(time, DatePattern.NORM_DATE_PATTERN)); + respUserDataIntegrity.setUserName(userFlag[2]); + respUserDataIntegrity.setLineNo(userFlag[1]); + respUserDataIntegrity.setUserNo(userFlag[0]); + result.setLack(lack); + result.setRespUserDataIntegrity(respUserDataIntegrity); + return result; + } else { + for (int i = 0; i < count; i++) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MINUTE, step * i); + UserDataExcel UserDataExcel = beforeDeal.get(calendar.getTime()); + if (UserDataExcel != null && UserDataExcel.getWork() != null) { + completed.add(UserDataExcel); + } else { + //找到前一个时间点值 + Float perValue = getPreValue(date, calendar.getTime(), beforeDeal); + //找到后一个时间点值 + Float appendValue = getAppendValue(date, count, step, calendar.getTime(), beforeDeal); + UserDataExcel temp = new UserDataExcel(); + SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN); + temp.setTime(sdf.format(calendar.getTime())); + temp.setUserId(userFlag[0]); + temp.setLine(userFlag[1]); + temp.setUserName(userFlag[2]); + //还需要判断前值和后值为空的情况 + if (null == perValue && null == appendValue) { + temp.setWork(new BigDecimal("0.0")); + } else if (null == perValue) { + temp.setWork(new BigDecimal(appendValue)); + } else if (null == appendValue) { + temp.setWork(new BigDecimal(perValue)); + } else { + temp.setWork(BigDecimal.valueOf((perValue + appendValue) / 2)); + } + completed.add(temp); + } + } + } + } + result.setCompleted(completed); + return result; + } + + /** + * 递归找前值 + * + * @param date 起始时间 + * @param time 当前时间 + * @param beforeDeal 处理前的数据 + */ + private Float getPreValue(Date date, Date time, Map beforeDeal) { + Float result; + if (date.equals(time)) { + return null; + } else { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(time); + calendar.add(Calendar.MINUTE, -15); + UserDataExcel temp = beforeDeal.get(calendar.getTime()); + if (temp == null || temp.getWork() == null) { + result = getPreValue(date, calendar.getTime(), beforeDeal); + } else { + result = temp.getWork().floatValue(); + } + } + return result; + } + + /** + * 递归找后置 + * + * @param date 起始时间 + * @param count 一天时间的总计数 + * @param step 间隔分钟 + * @param time 截止时间 + */ + private Float getAppendValue(Date date, int count, int step, Date time, Map beforeDeal) { + Float result; + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.MINUTE, (count - 1) * step); + if (time.equals(calendar.getTime())) { + return null; + } else { + Calendar calendar1 = Calendar.getInstance(); + calendar1.setTime(time); + calendar1.add(Calendar.MINUTE, 15); + UserDataExcel temp = beforeDeal.get(calendar1.getTime()); + if (temp == null || temp.getWork() == null) { + result = getAppendValue(date, count, step, calendar1.getTime(), beforeDeal); + } else { + result = temp.getWork().floatValue(); + } + } + return result; + } + +} diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/MathUtils.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/MathUtils.java new file mode 100644 index 0000000..9fce3cb --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/MathUtils.java @@ -0,0 +1,314 @@ +package com.njcn.product.advance.responsility.utils; + +import com.njcn.product.advance.responsility.pojo.constant.HarmonicConstants; +import org.apache.commons.math3.linear.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 数学工具类 + * 提供基础数学计算功能 + * + * @author hongawen + * @version 1.0 + */ +public class MathUtils { + + private static final Logger logger = LoggerFactory.getLogger(MathUtils.class); + + /** + * 计算协方差 + * + * @param x 数据序列1 + * @param y 数据序列2 + * @param width 数据窗宽度 + * @return 协方差值 + */ + public static double covariance(double[] x, double[] y, int width) { + if (x == null || y == null || width <= 0) { + throw new IllegalArgumentException("Invalid input parameters for covariance calculation"); + } + + if (x.length < width || y.length < width) { + throw new IllegalArgumentException("Data length is less than window width"); + } + + double meanX = 0.0; + double meanY = 0.0; + + // 计算均值 + for (int i = 0; i < width; i++) { + meanX += x[i]; + meanY += y[i]; + } + meanX /= width; + meanY /= width; + + // 计算协方差 + double cov = 0.0; + for (int i = 0; i < width; i++) { + cov += (x[i] - meanX) * (y[i] - meanY); + } + + return cov / (width - 1); + } + + /** + * 计算协方差(float版本) + */ + public static float covariance(float[] x, float[] y, int width) { + double[] dx = new double[x.length]; + double[] dy = new double[y.length]; + for (int i = 0; i < x.length; i++) dx[i] = x[i]; + for (int i = 0; i < y.length; i++) dy[i] = y[i]; + return (float) covariance(dx, dy, width); + } + + /** + * 计算Pearson相关系数 + * + * @param x 数据序列1 + * @param y 数据序列2 + * @param count 数据长度 + * @return Pearson相关系数 + */ + public static double pearsonCorrelation(double[] x, double[] y, int count) { + if (x == null || y == null || count <= 0) { + throw new IllegalArgumentException("Invalid input parameters for Pearson correlation"); + } + + double meanX = 0.0; + double meanY = 0.0; + + // 计算均值 + for (int i = 0; i < count; i++) { + meanX += x[i]; + meanY += y[i]; + } + meanX /= count; + meanY /= count; + + // 计算相关系数的各个部分 + double numerator = 0.0; + double denomX = 0.0; + double denomY = 0.0; + + for (int i = 0; i < count; i++) { + double dx = x[i] - meanX; + double dy = y[i] - meanY; + numerator += dx * dy; + denomX += dx * dx; + denomY += dy * dy; + } + + double denominator = Math.sqrt(denomX * denomY); + + if (Math.abs(denominator) < HarmonicConstants.EPSILON) { + logger.warn("Denominator is too small in Pearson correlation calculation"); + return 0.0; + } + + return numerator / denominator; + } + + /** + * 计算Pearson相关系数(float版本) + */ + public static float pearsonCorrelation(float[] x, float[] y, int count) { + double[] dx = new double[count]; + double[] dy = new double[count]; + for (int i = 0; i < count; i++) { + dx[i] = x[i]; + dy[i] = y[i]; + } + return (float) pearsonCorrelation(dx, dy, count); + } + + /** + * 计算协方差矩阵(SXX) + * + * @param data 数据矩阵 [时间][节点] + * @param width 窗口宽度 + * @param nodeCount 节点数 + * @return 协方差矩阵 + */ + public static double[][] covarianceMatrix(double[][] data, int width, int nodeCount) { + double[][] covMatrix = new double[nodeCount][nodeCount]; + + for (int i = 0; i < nodeCount; i++) { + for (int j = 0; j < nodeCount; j++) { + double[] col1 = new double[width]; + double[] col2 = new double[width]; + + for (int k = 0; k < width; k++) { + col1[k] = data[k][i]; + col2[k] = data[k][j]; + } + + covMatrix[i][j] = covariance(col1, col2, width); + } + } + + return covMatrix; + } + + /** + * 计算协方差矩阵(float版本) + */ + public static float[][] covarianceMatrix(float[][] data, int width, int nodeCount) { + float[][] covMatrix = new float[nodeCount][nodeCount]; + + for (int i = 0; i < nodeCount; i++) { + for (int j = 0; j < nodeCount; j++) { + float[] col1 = new float[width]; + float[] col2 = new float[width]; + + for (int k = 0; k < width; k++) { + col1[k] = data[k][i]; + col2[k] = data[k][j]; + } + + covMatrix[i][j] = covariance(col1, col2, width); + } + } + + return covMatrix; + } + + /** + * 计算协方差向量(SXY) + * + * @param data 数据矩阵 [时间][节点] + * @param y 目标向量 + * @param width 窗口宽度 + * @param nodeCount 节点数 + * @return 协方差向量 + */ + public static double[] covarianceVector(double[][] data, double[] y, int width, int nodeCount) { + double[] covVector = new double[nodeCount]; + + for (int i = 0; i < nodeCount; i++) { + double[] col = new double[width]; + for (int k = 0; k < width; k++) { + col[k] = data[k][i]; + } + covVector[i] = covariance(col, y, width); + } + + return covVector; + } + + /** + * 计算协方差向量(float版本) + */ + public static float[] covarianceVector(float[][] data, float[] y, int width, int nodeCount) { + float[] covVector = new float[nodeCount]; + + for (int i = 0; i < nodeCount; i++) { + float[] col = new float[width]; + for (int k = 0; k < width; k++) { + col[k] = data[k][i]; + } + covVector[i] = covariance(col, y, width); + } + + return covVector; + } + + /** + * 矩阵求逆 + * 使用Apache Commons Math库 + * + * @param matrix 输入矩阵 + * @return 逆矩阵 + */ + public static double[][] matrixInverse(double[][] matrix) { + RealMatrix realMatrix = new Array2DRowRealMatrix(matrix); + + try { + // 使用LU分解求逆 + DecompositionSolver solver = new LUDecomposition(realMatrix).getSolver(); + RealMatrix inverseMatrix = solver.getInverse(); + return inverseMatrix.getData(); + } catch (SingularMatrixException e) { + logger.error("Matrix is singular, cannot compute inverse", e); + throw new RuntimeException("Matrix inversion failed: singular matrix"); + } + } + + /** + * 计算矩阵的特征值 + * + * @param matrix 输入矩阵 + * @return 特征值数组 + */ + public static double[] eigenvalues(double[][] matrix) { + RealMatrix realMatrix = new Array2DRowRealMatrix(matrix); + EigenDecomposition eigenDecomposition = new EigenDecomposition(realMatrix); + return eigenDecomposition.getRealEigenvalues(); + } + + /** + * 归一化处理 + * 将数据归一化到[0,1]区间 + * + * @param data 输入数据 + * @return 归一化后的数据 + */ + public static double[] normalize(double[] data) { + if (data == null || data.length == 0) { + return data; + } + + double min = Double.MAX_VALUE; + double max = Double.MIN_VALUE; + + // 找最大最小值 + for (double value : data) { + min = Math.min(min, value); + max = Math.max(max, value); + } + + double range = max - min; + if (Math.abs(range) < HarmonicConstants.EPSILON) { + return new double[data.length]; // 返回全0数组 + } + + double[] normalized = new double[data.length]; + for (int i = 0; i < data.length; i++) { + normalized[i] = (data[i] - min) / range; + } + + return normalized; + } + + /** + * 数据对齐处理 + * 将不同采样间隔的数据对齐到相同的时间间隔 + * + * @param data 原始数据 + * @param originalInterval 原始采样间隔 + * @param targetInterval 目标采样间隔 + * @return 对齐后的数据 + */ + public static float[] alignData(float[] data, int originalInterval, int targetInterval) { + if (targetInterval % originalInterval != 0) { + throw new IllegalArgumentException( + "Target interval must be multiple of original interval"); + } + + int ratio = targetInterval / originalInterval; + int newLength = data.length / ratio; + float[] alignedData = new float[newLength]; + + for (int i = 0; i < newLength; i++) { + float sum = 0; + for (int j = 0; j < ratio; j++) { + sum += data[i * ratio + j]; + } + alignedData[i] = sum / ratio; + } + + return alignedData; + } +} \ No newline at end of file diff --git a/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/ResponsibilityAlgorithm.java b/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/ResponsibilityAlgorithm.java new file mode 100644 index 0000000..395d16e --- /dev/null +++ b/cn-advance/src/main/java/com/njcn/product/advance/responsility/utils/ResponsibilityAlgorithm.java @@ -0,0 +1,766 @@ +package com.njcn.product.advance.responsility.utils; + +import cn.hutool.core.bean.BeanUtil; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.advance.eventSource.pojo.enums.AdvanceResponseEnum; +import com.njcn.product.advance.responsility.model.QvvrDataEntity; +import org.apache.commons.math3.linear.*; +import org.ejml.data.DMatrixRMaj; +import org.ejml.dense.row.CommonOps_DDRM; +import org.ejml.dense.row.factory.DecompositionFactory_DDRM; +import org.ejml.interfaces.decomposition.EigenDecomposition_F64; +import org.ejml.simple.SimpleMatrix; + +import java.util.Arrays; + +/** + * 责任量化的算法细节: + * 此代码用以计算刻度不等两序列之间的动态相关系数与动态谐波责任指标; + * 随机数生成器生成原始谐波U数据,一维数组长度为LL;生成原始负荷PE数据,二维数组,(行)长度为TL,(列)宽度为P(表示P个负荷公司); + * 只能识别 U数据长度 为PE数据长度的 JIANGE倍,也即无法自动判别时间间隔,需人为定义; + * Width用以控制动态相关系数的计算窗宽; + * 使用库中函数进行矩阵构造与计算; + * 最终的到结果为:向量Core为动态典则相关系数 + * 矩阵simCor为剥离背景后的动态相关系数,其中每列为每一用户负荷 + * 矩阵HKdata为使用simCor计算的动态谐波责任指标,其中每列为每一用户负荷 + * 向量sumHKdata为超限额的谐波时,不同用户的长时谐波责任指标; + * 函数说明:cov(a,b)计算协方差; + * SXX(a,width)计算(行)长度为width序列的方差矩阵; + * SXY(a,b,width)计算长度为width两序列的协方差矩阵; + * TransCancor(Ma,Vb,width)计算长度为width的矩阵a与向量b的典则相关系数; + * SlideCanCor(a,b,width)计算a与b的在 窗宽 width下 的动态典则相关系数; + * SlideCor(a,b,slidecancor,width)计算a,b,在窗宽 width 下 典则相关剥离背景后的动态相关系数。 + * + * 算法很多代码没有注释,这些代码翻译的友谊的C代码,不清楚实际逻辑 + */ +public class ResponsibilityAlgorithm { + + static int P = 21; + static int TL = 671; + static int LL = 3355; + static int JIANGE = 5; + static int wdith = 96; + static float XIANE = 0; + static int RES_NUM = 0; + + static QvvrDataEntity qvvrResult; + + + public QvvrDataEntity getResponsibilityResult(QvvrDataEntity qvvrParam) { + int i, j; + if (qvvrParam != null) { + // 计算责任 + harm_res(qvvrParam.calFlag, qvvrParam); + // 输出结果 + qvvrParam.calOk = qvvrResult.calOk; + if (qvvrParam.calOk == 1) { + // 长时越限谐波责任 + for (i = 0; i < qvvrParam.pNode; i++) + qvvrParam.sumFKdata[i] = qvvrResult.sumFKdata[i]; + for (i = 0; i < (qvvrParam.pNode + 1); i++) + qvvrParam.sumHKdata[i] = qvvrResult.sumHKdata[i]; + // 如果是原始功率数据和谐波数据代入计算,将动态相关系数和动态谐波责任输出 + if (qvvrParam.calFlag == 0) { + qvvrParam.resNum = qvvrResult.resNum; + for (i = 0; i < qvvrResult.resNum; i++) { + qvvrParam.core[i] = qvvrResult.core[i]; + qvvrParam.bjCore[i] = qvvrResult.bjCore[i]; + for (j = 0; j < qvvrParam.pNode; j++) { + qvvrParam.fKData[i][j] = qvvrResult.fKData[i][j]; + qvvrParam.simData[i][j] = qvvrResult.simData[i][j]; + } + for (j = 0; j < (qvvrParam.pNode + 1); j++) + qvvrParam.hKData[i][j] = qvvrResult.hKData[i][j]; + } + } + } + } + return qvvrParam; + } + + + public static int harm_res(int calFlag, QvvrDataEntity qvvrParam) { + if (calFlag == 0) { + harm_res_all(qvvrParam); + } else if (calFlag == 1) { + harm_res_part(qvvrParam); + } + return 0; + } + + static int harm_res_part(QvvrDataEntity qvvrParam) { + int ret = 0; + //缓冲大小初始化 + ret = data_init_part(qvvrParam); + if (ret != 0) { + qvvrResult.calOk = 0; +// System.out.printf("data init err,exit\r\n"); + throw new BusinessException(AdvanceResponseEnum.DATA_ERROR); + } + int colK = P + 1; + RealMatrix HKdata = MatrixUtils.createRealMatrix(RES_NUM, colK); + for (int i = 0; i < P + 1; i++) { + for (int j = 0; j < RES_NUM; j++) { + HKdata.setEntry(j, i, qvvrResult.hKData[j][i]); + } + } + + RealVector Udata = new ArrayRealVector(TL); + for (int j = 0; j < TL; j++) { + Udata.setEntry(j, qvvrResult.harmData[j]); + } + + float[] arrHKsum = SumHK(HKdata, Udata, wdith, colK, TL); + RealVector sumHKdata = new ArrayRealVector(colK); + for (int i = 0; i < colK; i++) { + sumHKdata.setEntry(i, 0); + } + + float sum_hk = 0; + for (int i = 0; i < colK; i++) { + sumHKdata.setEntry(i, arrHKsum[i]); + sum_hk += sumHKdata.getEntry(i); + qvvrResult.sumHKdata[i] = (float) sumHKdata.getEntry(i); + } + + RealMatrix FKdata = MatrixUtils.createRealMatrix(RES_NUM, P); + for (int i = 0; i < P; i++) { + for (int j = 0; j < RES_NUM; j++) { + FKdata.setEntry(j, i, qvvrResult.fKData[j][i]); + } + } + + colK = P; + arrHKsum = SumHK(FKdata, Udata, wdith, colK, TL); + RealVector sumFKdata = new ArrayRealVector(colK); + for (int i = 0; i < colK; i++) { + sumFKdata.setEntry(i, 0); + } + + float sum_fk = 0; + for (int i = 0; i < colK; i++) { + sumFKdata.setEntry(i, arrHKsum[i]); + sum_fk += sumFKdata.getEntry(i); + qvvrResult.sumFKdata[i] = (float) sumFKdata.getEntry(i); + } + + qvvrResult.calOk = 1; + return 0; + } + + static int data_init_part(QvvrDataEntity qvvrParam) { + qvvrResult = new QvvrDataEntity(); + //输入数据处理 + BeanUtil.copyProperties(qvvrParam, qvvrResult); +// if ((qvvrResult.resNum + qvvrResult.win) != qvvrResult.harmNum) { +// System.out.printf("数据未对齐...\r\n"); +// return -1; +// } + RES_NUM = qvvrResult.resNum; + P = qvvrResult.pNode; + TL = qvvrResult.win + qvvrResult.resNum; + wdith = qvvrResult.win; + XIANE = qvvrResult.harmMk; + + if ((wdith < QvvrDataEntity.MIN_WIN_LEN) || (wdith > QvvrDataEntity.MAX_WIN_LEN)) { + System.out.printf("窗宽超限...\r\n"); + throw new BusinessException(AdvanceResponseEnum.WIN_DATA_ERROR); + } + + if ((P > QvvrDataEntity.MAX_P_NODE) || (TL > QvvrDataEntity.MAX_P_NUM)) { + System.out.printf("数据长度超限...\r\n"); + throw new BusinessException(AdvanceResponseEnum.DATA_ERROR); + } + for (int i = 0; i < RES_NUM; i++) { + for (int j = 0; j < P; j++) { + qvvrResult.fKData[i][j] = qvvrParam.fKData[i][j]; + } + for (int j = 0; j < P + 1; j++) { + qvvrResult.hKData[i][j] = qvvrParam.hKData[i][j]; + } + } + + // 复制 qvvrParam + for (int i = 0; i < TL; i++) { + qvvrResult.harmData[i] = qvvrParam.harmData[i]; + } + return 0; + } + + static int harm_res_all(QvvrDataEntity qvvrParam) { + int ret = 0; + //缓冲大小初始化 + ret = data_init_all(qvvrParam); + if (ret != 0) { + qvvrResult.calOk = 0; + System.out.printf("data init err,exit\r\n"); + throw new BusinessException(AdvanceResponseEnum.INIT_DATA_ERROR); + } + //测试数据申请空间 + float[][] a = new float[TL][]; + for (int i = 0; i < TL; i++) { + a[i] = new float[P]; + } + + float[] b = new float[LL]; + float[] u = new float[TL]; + + for (int i = 0; i < TL; i++) { + for (int j = 0; j < P; j++) { + a[i][j] = qvvrResult.pData[i][j]; + } + } + for (int i = 0; i < LL; i++) { + b[i] = qvvrResult.harmData[i]; + } + + for (int i = 0; i < LL; i += JIANGE) { + float tempt = 0.0f; + for (int j = 0; j < JIANGE; j++) { + tempt += b[i + j]; + } + b[i] = tempt / JIANGE; + } + int width = wdith; + int slcorlength = TL - width; + + //剥离背景谐波后的动态相关系数计算 + //数据格式转换 + // 创建矩阵Pdata并复制数据 + double[][] PdataArray = new double[TL][P]; + for (int i = 0; i < TL; i++) { + for (int j = 0; j < P; j++) { + PdataArray[i][j] = a[i][j]; + } + } + RealMatrix Pdata = new Array2DRowRealMatrix(PdataArray); + // 创建向量Udata并复制数据 + double[] UdataArray = new double[TL]; + for (int i = 0; i < TL; i++) { + UdataArray[i] = b[i * JIANGE]; + } + RealVector Udata = new ArrayRealVector(UdataArray); + for (int i = 0; i < TL; i++) { + u[i] = (float) UdataArray[i]; + } + + //动态典则相关系数数组获得 并转化为向量 + + float[] cancorrelation = SlideCanCor(a, u, width, P, TL); + + RealVector Core = new ArrayRealVector(slcorlength); + RealVector bjCore = new ArrayRealVector(slcorlength); + for (int i = 0; i < slcorlength; i++) { + Core.setEntry(i, cancorrelation[i]); + qvvrResult.core[i] = (float) Core.getEntry(i); + } + for (int i = 0; i < slcorlength; i++) { + bjCore.setEntry(i, 1 - cancorrelation[i]); + qvvrResult.bjCore[i] = (float) bjCore.getEntry(i); + } + + float[] y = new float[TL]; + float[] xe = new float[TL]; + float[] slidecor; + RealVector temptPe = new ArrayRealVector(TL); + RealVector temptU = new ArrayRealVector(TL); + RealMatrix simCor = new Array2DRowRealMatrix(slcorlength, P); + + // 格式转换 + temptU = Udata.getSubVector(0, TL); + for (int m = 0; m < TL; m++) { + y[m] = (float) temptU.getEntry(m); + } + // 格式转换、计算系数、格式转换 + for (int i = 0; i < P; i++) { + temptPe = Pdata.getColumnVector(i); + for (int m = 0; m < TL; m++) { + xe[m] = (float) temptPe.getEntry(m); + } + slidecor = slideCor(xe, y, cancorrelation, width, TL); // 计算每个用户负荷与用户谐波的动态相关系数 + + for (int j = 0; j < slcorlength; j++) { + simCor.setEntry(j, i, slidecor[j]); + qvvrResult.simData[j][i] = (float) simCor.getEntry(j, i); + } + } + + //动态谐波责任指标计算 + //EK计算,用于后续计算FK(不含背景的用户责任指标)、HK(包含背景的用户责任指标) + //float **EKarr = (float **)malloc(TL * sizeof(float *));//先申请P个指针型字节的空间 + //for (int i = 0; i < TL; i++) + //EKarr[i] = (float *)malloc(TL * Float.SIZE / Byte.SIZE); + + float[][] EKarr; + EKarr = dyEKCom(simCor, Pdata, width, P, TL); + RealMatrix EKdata = MatrixUtils.createRealMatrix(slcorlength, P); + for (int i = 0; i < slcorlength; i++) { + for (int j = 0; j < P; j++) { + EKdata.setEntry(i, j, EKarr[i][j]); + } + } + + //不含背景的用户谐波责任指标 + //float **FKarr = (float **)malloc(TL * sizeof(float *));//先申请P个指针型字节的空间 + //for (int i = 0; i < TL; i++) + //FKarr[i] = (float *)malloc(TL * Float.SIZE / Byte.SIZE); + float[][] FKarr; + FKarr = DyFKCom(EKdata, width, P, TL); + RealMatrix FKdata = MatrixUtils.createRealMatrix(slcorlength, P); + for (int i = 0; i < slcorlength; i++) { + for (int j = 0; j < P; j++) { + FKdata.setEntry(i, j, FKarr[i][j]); + } + } + qvvrResult.fKData=FKarr; + //包含背景的谐波责任指标 + //float **HKarr = (float **)malloc(TL * sizeof(float *));//先申请P个指针型字节的空间 + //for (int i = 0; i < TL; i++) + //HKarr[i] = (float *)malloc(TL * Float.SIZE / Byte.SIZE); + float[][] HKarr; + HKarr = DyHKCom(bjCore, EKdata, width, P, TL); + RealMatrix HKdata = MatrixUtils.createRealMatrix(slcorlength, (P + 1)); + for (int i = 0; i < slcorlength; i++) { + for (int j = 0; j < (P + 1); j++) { + HKdata.setEntry(i, j, HKarr[i][j]); + qvvrResult.hKData[i][j] = (float) HKdata.getEntry(i, j); + } + } + qvvrResult.resNum = slcorlength; + + + //超限额长时谐波责任指标计算 + float[] arrHKsum = new float[TL]; + int colK = P + 1;//FKdata时为P + arrHKsum = SumHK(HKdata, Udata, width, colK, TL);//可更改FKdata,表示为不包含背景时的长时责任划分 + RealVector sumHKdata = new ArrayRealVector(colK); + for (int i = 0; i < colK; i++) { + sumHKdata.setEntry(i, 0); + } + + float sum_hk = 0; + for (int i = 0; i < colK; i++) { + sumHKdata.setEntry(i, arrHKsum[i]); + sum_hk += sumHKdata.getEntry(i); + qvvrResult.sumHKdata[i] = (float) sumHKdata.getEntry(i); + } + + colK = P;//FKdata时为P + arrHKsum = SumHK(FKdata, Udata, width, colK, TL);//可更改FKdata,表示为不包含背景时的长时责任划分 + RealVector sumFKdata = new ArrayRealVector(colK); + + for (int i = 0; i < colK; i++) { + sumFKdata.setEntry(i, 0); + } + float sum_fk = 0; + for (int i = 0; i < colK; i++) { + sumFKdata.setEntry(i, arrHKsum[i]); + sum_fk += sumFKdata.getEntry(i); + qvvrResult.sumFKdata[i] = (float) sumHKdata.getEntry(i); + } + //结果输出 + qvvrResult.calOk = 1; + return 0; + } + + + + static int data_init_all(QvvrDataEntity qvvrParam) { + qvvrResult = new QvvrDataEntity(); + //输入数据处理 + BeanUtil.copyProperties(qvvrParam, qvvrResult); + P = qvvrResult.pNode; + TL = qvvrResult.pNum; + LL = qvvrResult.harmNum; + JIANGE = qvvrResult.harmNum / qvvrResult.pNum; + wdith = qvvrResult.win; + XIANE = qvvrResult.harmMk; + + if ((JIANGE * TL != LL) || (JIANGE < 1)) { + return -1; + } + if ((wdith < QvvrDataEntity.MIN_WIN_LEN) || (wdith > QvvrDataEntity.MAX_WIN_LEN)) { +// System.out.printf("窗宽超限...\r\n"); + throw new BusinessException(AdvanceResponseEnum.EVENT_DATA_MISS); + } + + if (TL < (2 * wdith)) { + System.out.printf("窗宽和数据长度不匹配...\r\n"); + return -1; + } + + if ((P > QvvrDataEntity.MAX_P_NODE) || (TL > QvvrDataEntity.MAX_P_NUM) || (LL > QvvrDataEntity.MAX_HARM_NUM)) { + System.out.printf("数据长度超限...\r\n"); + throw new BusinessException(AdvanceResponseEnum.EVENT_DATA_MISS); + } + + + float[][] clone = new float[qvvrParam.getPData().length][]; + for (int i = 0; i < qvvrParam.getPData().length; i++) { + clone[i] = Arrays.copyOf(qvvrParam.getPData()[i], qvvrParam.getPData()[i].length); + } + qvvrResult.setPData(clone); + + + for (int i = 0; i < LL; i++) { + qvvrResult.getHarmData()[i] = qvvrParam.getHarmData()[i]; + } + //System.out.printf("win = %d\r\n",wdith); + return 0; + } + + + public static float[] SlideCanCor(float[][] x, float[] y, int width, int p_num, int tl_num) { + int slcorlength = tl_num - width; + float[][] a = new float[width][p_num]; + for (int i = 0; i < width; i++) { + a[i] = new float[p_num]; + } + float[] b = new float[width]; + + float[][] sxxmatrix = new float[p_num][p_num]; + for (int i = 0; i < p_num; i++) { + sxxmatrix[i] = new float[p_num]; + } + float[] sxymatrix = new float[tl_num]; + float[] x1 = new float[tl_num]; + float[] x2 = new float[tl_num]; + float[] x3 = new float[tl_num]; + float[][] xx = new float[width][p_num]; + for (int i = 0; i < width; i++) { + xx[i] = new float[p_num]; + } + float[] yy = new float[width]; + + RealMatrix Pdata = new Array2DRowRealMatrix(tl_num, p_num); + RealVector Udata = new ArrayRealVector(tl_num); + for (int i = 0; i < tl_num; i++) { + for (int j = 0; j < p_num; j++) { + Pdata.setEntry(i, j, x[i][j]); + } + Udata.setEntry(i, y[i]); + } + + RealMatrix temptP = new Array2DRowRealMatrix(width, p_num); + RealVector temptU = new ArrayRealVector(width); + float[] slideCancor = new float[tl_num]; + for (int i = 0; i < slcorlength; i++) { + temptU = Udata.getSubVector(i, width); + temptP = Pdata.getSubMatrix(i, i + width - 1, 0, p_num - 1); + slideCancor[i] = TransCancor(temptP, temptU, width, p_num, tl_num, sxxmatrix, sxymatrix, x1, x2, x3, xx, yy); + } + + return slideCancor; + } + + + public static float TransCancor(RealMatrix a, RealVector b, int width, int p_num, int tl_num, + float[][] sxxMatrix, float[] sxyMatrix, float[] x1, float[] x2, + float[] x3, float[][] x, float[] y) { + float syymatrix; + for (int i = 0; i < width; i++) { + for (int j = 0; j < p_num; j++) { + x[i][j] = (float) a.getEntry(i, j); + } + y[i] = (float) b.getEntry(i); + } + // 假设的SXX函数,需要根据实际实现来调整 + sxxMatrix = SXX(x, width, p_num, tl_num, sxxMatrix, x1, x2); + syymatrix = cov(y, y, width); // 假设的COV函数,需要根据实际实现来调整 + if (syymatrix == 0) { + syymatrix = 0.00001F; + } + // 假设的SXY函数,需要根据实际实现来调整 + sxyMatrix = SXY(x, y, width, p_num, tl_num, sxyMatrix, x3); + +// +// RealMatrix A = MatrixUtils.createRealMatrix(p_num, p_num); +// RealMatrix invSXX = MatrixUtils.createRealMatrix(p_num, p_num); +// RealMatrix I = MatrixUtils.createRealIdentityMatrix(p_num); // I is an identity matrix +// +// // 二维数组转为矩阵 +// for (int i = 0; i < p_num; i++) { +// for (int j = 0; j < p_num; j++) { +// A.setEntry(i, j, sxxMatrix[i][j]); +// } +// } +// +// // 使用 LU 分解方法计算矩阵 invSXX +// invSXX = new LUDecomposition(A).getSolver().solve(I); + + // 创建 p_num × p_num 的矩阵 A + SimpleMatrix A = new SimpleMatrix(p_num, p_num); + + // 创建 p_num × p_num 的逆矩阵 invSXX + SimpleMatrix invSXX = new SimpleMatrix(p_num, p_num); + + // 创建 p_num × p_num 的单位矩阵 I + SimpleMatrix I = SimpleMatrix.identity(p_num); + + // 二维数组转为矩阵 A + for (int i = 0; i < p_num; i++) { + for (int j = 0; j < p_num; j++) { + A.set(i, j, sxxMatrix[i][j]); + } + } + + // 使用 LU 分解方法计算矩阵 invSXX + //invSXX = A.invert().mult(I); + + // 创建长度为 p_num 的向量 sXYMa_Eigen + DMatrixRMaj sXYMa_Eigen = new DMatrixRMaj(p_num, 1); + for (int i = 0; i < p_num; i++) { + sXYMa_Eigen.set(i, 0, sxyMatrix[i]); + } + + // 计算 Umatrix + DMatrixRMaj Umatrix = new DMatrixRMaj(p_num, p_num); + CommonOps_DDRM.multOuter(sXYMa_Eigen, Umatrix); // 外积 + CommonOps_DDRM.divide(Umatrix, syymatrix); // 矩阵按标量除法 + CommonOps_DDRM.divide(Umatrix, syymatrix); // 再次按标量除法 + + // 计算特征值 + EigenDecomposition_F64 eigenDecomposition = DecompositionFactory_DDRM.eig(p_num, false); + eigenDecomposition.decompose(Umatrix); + + float corrMax = 0; + for (int i = 0; i < p_num; i++) { + float absCorr = (float) Math.abs(eigenDecomposition.getEigenvalue(i).getReal()); + if (absCorr > corrMax) { + corrMax = absCorr; + } + } + + float cancor = (float) Math.sqrt(corrMax); + if (cancor >= 1) { + cancor = 1; + } + + return cancor; + } + + + public static float[][] SXX(float[][] x, int width, int p_num, int tl_num, float[][] sxxmatrix, float[] x1, float[] x2) { + int i, j, m; + for (i = 0; i < p_num; i++) { + for (j = 0; j < p_num; j++) { + for (m = 0; m < width; m++) { + x1[m] = x[m][i]; + x2[m] = x[m][j]; + } + sxxmatrix[i][j] = cov(x1, x2, width); + } + } + return sxxmatrix; + } + + public static float[] SXY(float[][] x, float[] y, int width, int p_num, int tl_num, float[] sxymatrix, float[] x1) { + int i, m; + for (i = 0; i < p_num; i++) { + for (m = 0; m < width; m++) { + x1[m] = x[m][i]; + } + sxymatrix[i] = cov(x1, y, width); + } + return sxymatrix; + } + + public static float cov(float[] x, float[] y, int width) { + float d1, d2, d3, d4; + float mx, my; + float cov; + int i; + int xlength = width; + int ylength = width; + d1 = d2 = d3 = d4 = mx = my = 0.0f; + for (i = 0; i < xlength; i++) { + mx += x[i]; + my += y[i]; + } + mx = mx / xlength; + my = my / ylength; + for (i = 0; i < xlength; i++) { + d1 += (x[i] - mx) * (y[i] - my); + } + cov = d1 / (xlength - 1); + return cov; + } + + public static float[] slideCor(float[] x, float[] y, float[] slidecor, int width, int tlNum) { + int slcorLength = tlNum - width; + float[] slcor = new float[tlNum]; // 注意调整数组大小根据实际需要 + + // 动态相关系数 + for (int i = 0; i < slcorLength; i++) { + float[] temptp = new float[width]; + float[] temptq = new float[width]; + for (int j = 0; j < width; j++) { + temptp[j] = x[i + j]; + temptq[j] = y[i + j] * slidecor[i]; + } + slcor[i] = pearCor(temptq, temptp, width); + } + + return slcor; + } + + public static float pearCor(float[] x, float[] y, int count) { + float d1 = 0, d2 = 0, d3 = 0, d4 = 0; + float mx = 0, my = 0; + float result = 0; + + // 计算x和y的平均值 + for (int i = 0; i < count; i++) { + mx += x[i]; + my += y[i]; + } + mx /= count; + my /= count; + + // 计算相关系数的数据组成部分 + for (int i = 0; i < count; i++) { + d1 += (x[i] - mx) * (y[i] - my); + d2 += (x[i] - mx) * (x[i] - mx); + d3 += (y[i] - my) * (y[i] - my); + } + d4 = (float) Math.sqrt(d2 * d3); + + if (d4 == 0) { + // 除数为0时,相关系数为0 + result = 0; + } else { + result = d1 / d4; + } + + return result; + } + + private static float[][] dyEKCom(RealMatrix Dydata, RealMatrix Pdata, int width, int p_num, int tl_num) { + int slg = tl_num - width; + RealMatrix AKdata = MatrixUtils.createRealMatrix(slg, p_num); + RealMatrix SumP = MatrixUtils.createRealMatrix(slg, 1); + RealMatrix EKdata = MatrixUtils.createRealMatrix(slg, p_num); + + for (int i = 0; i < slg; i++) { + SumP.setEntry(i, 0, 0); + for (int j = 0; j < p_num; j++) { + float sumPValue = (float) (SumP.getEntry(i, 0) + Pdata.getEntry(i, j)); + SumP.setEntry(i, 0, sumPValue); + } + for (int j = 0; j < p_num; j++) { + float AKdataValue = (float) (Dydata.getEntry(i, j) * (Pdata.getEntry(i, j) / SumP.getEntry(i, 0))); + AKdata.setEntry(i, j, AKdataValue); + } + } + for (int i = 0; i < slg; i++) { + float maxdata = Float.MIN_VALUE; + float mindata = Float.MAX_VALUE; + for (int j = 0; j < p_num; j++) { + maxdata = Math.max(maxdata, (float) AKdata.getEntry(i, j)); + mindata = Math.min(mindata, (float) AKdata.getEntry(i, j)); + } + for (int j = 0; j < p_num; j++) { + EKdata.setEntry(i, j, (AKdata.getEntry(i, j) - mindata) / (maxdata - mindata)); + } + } + + float[][] arrEK = new float[slg][p_num]; + for (int i = 0; i < slg; i++) { + for (int j = 0; j < p_num; j++) { + arrEK[i][j] = (float) EKdata.getEntry(i, j); + } + } + return arrEK; + } + + private static float[][] DyFKCom(RealMatrix EKdata, int width, int p_num, int tl_num) { + int slg = tl_num - width; + RealMatrix FKdata = MatrixUtils.createRealMatrix(slg, p_num); + ArrayRealVector SumEK = new ArrayRealVector(slg); + + for (int i = 0; i < slg; i++) { + SumEK.setEntry(i, 0); + for (int j = 0; j < p_num; j++) { + float sumEKValue = (float) (SumEK.getEntry(i) + EKdata.getEntry(i, j)); + SumEK.setEntry(i, sumEKValue); + } + for (int j = 0; j < p_num; j++) { + float FKdataValue = (float) (EKdata.getEntry(i, j) / SumEK.getEntry(i)); + FKdata.setEntry(i, j, FKdataValue); + } + } + + float[][] arrFK = new float[tl_num][p_num]; + for (int i = 0; i < slg; i++) { + for (int j = 0; j < p_num; j++) { + arrFK[i][j] = (float) FKdata.getEntry(i, j); + } + } + return arrFK; + } + + private static float[][] DyHKCom(RealVector cancordata, RealMatrix EKdata, int width, int p_num, int tl_num) { + int slg = tl_num - width; + RealMatrix HKdata = MatrixUtils.createRealMatrix(slg, p_num + 1); + RealMatrix newEK = MatrixUtils.createRealMatrix(slg, p_num + 1); + ArrayRealVector SumEK = new ArrayRealVector(slg); + + for (int i = 0; i < slg; i++) { + for (int j = 0; j < p_num; j++) { + newEK.setEntry(i, j, EKdata.getEntry(i, j)); + } + newEK.setEntry(i, p_num, cancordata.getEntry(i)); + } + + for (int i = 0; i < slg; i++) { + SumEK.setEntry(i, 0); + for (int j = 0; j < p_num + 1; j++) { + float sumEKValue = (float) (SumEK.getEntry(i) + newEK.getEntry(i, j)); + SumEK.setEntry(i, sumEKValue); + } + for (int j = 0; j < p_num + 1; j++) { + float HKdataValue = (float) (newEK.getEntry(i, j) / SumEK.getEntry(i)); + HKdata.setEntry(i, j, HKdataValue); + } + } + + float[][] arrHK = new float[tl_num][p_num + 1]; + for (int i = 0; i < slg; i++) { + for (int j = 0; j < p_num + 1; j++) { + arrHK[i][j] = (float) HKdata.getEntry(i, j); + } + } + return arrHK; + } + + private static float[] SumHK(RealMatrix HKdata, RealVector Udata, int width, int colK, int tl_num) { + int P1 = colK; + RealVector HKSum = new ArrayRealVector(P1); + int slg = tl_num - width; + int coutt = 0; + + for (int j = 0; j < P1; j++) { + HKSum.setEntry(j, 0); + coutt = 0; + for (int i = 0; i < slg; i++) { + if (Udata.getEntry(i) > XIANE) { + float HKdataEntry = (float) HKdata.getEntry(i, j); + HKSum.setEntry(j, HKSum.getEntry(j) + HKdataEntry); + coutt++; + } + } + } + + float[] arrHKsum = new float[P1]; + for (int i = 0; i < P1; i++) { + arrHKsum[i] = 0; + } + for (int i = 0; i < P1; i++) { + if (coutt > 0) { + arrHKsum[i] = (float) (100 * (HKSum.getEntry(i) / coutt)); + } + } + return arrHKsum; + } + +} diff --git a/cn-advance/src/test/java/com/njcn/product/advance/CnAdvanceApplicationTests.java b/cn-advance/src/test/java/com/njcn/product/advance/CnAdvanceApplicationTests.java new file mode 100644 index 0000000..39f8920 --- /dev/null +++ b/cn-advance/src/test/java/com/njcn/product/advance/CnAdvanceApplicationTests.java @@ -0,0 +1,13 @@ +package com.njcn.product.advance; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CnAdvanceApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/cn-begin/.gitignore b/cn-begin/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-begin/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-begin/pom.xml b/cn-begin/pom.xml new file mode 100644 index 0000000..fadcccb --- /dev/null +++ b/cn-begin/pom.xml @@ -0,0 +1,84 @@ + + + 4.0.0 + + + com.njcn.product + CN_Product + 1.0.0 + + + cn-begin + 0.0.1-SNAPSHOT + cn-begin + cn-begin + + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + com.njcn.product + cn-diagram + 1.0.0 + + + + + + + + + cn-begin + + + org.springframework.boot + spring-boot-maven-plugin + + + package + + repackage + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + + src/main/resources + + **/* + + + + + + diff --git a/cn-begin/src/main/java/com/njcn/product/begin/CnBeginApplication.java b/cn-begin/src/main/java/com/njcn/product/begin/CnBeginApplication.java new file mode 100644 index 0000000..a67b188 --- /dev/null +++ b/cn-begin/src/main/java/com/njcn/product/begin/CnBeginApplication.java @@ -0,0 +1,20 @@ +package com.njcn.product.begin; + +import lombok.extern.slf4j.Slf4j; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.DependsOn; + + +@Slf4j +@MapperScan("com.njcn.**.mapper") +@SpringBootApplication(scanBasePackages = "com.njcn") +@DependsOn("proxyMapperRegister") +public class CnBeginApplication { + + public static void main(String[] args) { + SpringApplication.run(CnBeginApplication.class, args); + } + +} diff --git a/cn-begin/src/main/resources/application-wuxi_dev.yml b/cn-begin/src/main/resources/application-wuxi_dev.yml new file mode 100644 index 0000000..53d7c92 --- /dev/null +++ b/cn-begin/src/main/resources/application-wuxi_dev.yml @@ -0,0 +1,99 @@ +#当前服务的基本信息 +spring: + datasource: + dynamic: + primary: master + strict: false # 是否严格匹配数据源,默认false + druid: # 如果使用Druid连接池 + validation-query: SELECT 1 FROM DUAL # 达梦专用校验SQL + initial-size: 10 + # 初始化大小,最小,最大 + min-idle: 20 + maxActive: 500 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + testWhileIdle: true + testOnBorrow: true + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + datasource: + master: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://192.168.1.24:13306/pqsinfo_wuxi?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai + username: root + password: njcnpqs + salve: + url: jdbc:oracle:thin:@192.168.1.51:1521:pqsbase + username: pqsadmin_bj + password: pqsadmin + driver-class-name: oracle.jdbc.OracleDriver + + + servlet: + multipart: + max-file-size: 100MB + max-request-size: 100MB + #influxDB内容配置 + influx: + url: http://192.168.1.103:18086 + user: admin + password: 123456 + database: pqsbase_wx + mapper-location: com.njcn.**.imapper +#mybatis配置信息 +mybatis-plus: + mapper-locations: classpath*:com/njcn/**/mapping/*.xml + #别名扫描 + type-aliases-package: com.njcn.product.**.pojo + configuration: + #驼峰命名 + map-underscore-to-camel-case: true + #配置sql日志输出 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + # #关闭日志输出 + # log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl + global-config: + db-config: + #指定主键生成策略 + id-type: assign_uuid +db: + type: mysql +#文件位置配置 +business: + #处理波形数据位置 + wavePath: D://comtrade + #wavePath: /usr/local/comtrade + #处理临时数据 + #tempPath: D://file + tempPath: /usr/local/file + #文件存储的方式 1.本地 + file: + storage: 1 + #localStoragePath: /usr/local/localStoragePath + localStoragePath: f://localStoragePath +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.22:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 + + + + diff --git a/cn-begin/src/main/resources/application-wuxi_prod.yml b/cn-begin/src/main/resources/application-wuxi_prod.yml new file mode 100644 index 0000000..dd52cdf --- /dev/null +++ b/cn-begin/src/main/resources/application-wuxi_prod.yml @@ -0,0 +1,73 @@ +spring: + datasource: + dynamic: + primary: master + strict: false # 是否严格匹配数据源,默认false + druid: # 如果使用Druid连接池 + validation-query: SELECT 1 FROM DUAL # 达梦专用校验SQL + initial-size: 10 + # 初始化大小,最小,最大 + min-idle: 20 + maxActive: 500 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + testWhileIdle: true + testOnBorrow: true + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + datasource: + master: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://192.168.1.103:13306/pqsinfo_wuxi?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai + username: root + password: njcnpqs + + + #influxDB内容配置 + influx: + url: http://192.168.1.103:18086 + user: admin + password: 123456 + database: pqsbase_wx + mapper-location: com.njcn.**.imapper + +db: + type: mysql +#文件位置配置 +business: + #处理波形数据位置 + #wavePath: D://comtrade + wavePath: /usr/local/comtrade + #处理临时数据 + #tempPath: D://file + tempPath: /usr/local/file + #文件存储的方式 1.本地 + file: + storage: 1 + localStoragePath: /usr/local/localStoragePath + #localStoragePath: f://localStoragePath +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.22:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 + + + diff --git a/cn-begin/src/main/resources/application.yml b/cn-begin/src/main/resources/application.yml new file mode 100644 index 0000000..1a6d172 --- /dev/null +++ b/cn-begin/src/main/resources/application.yml @@ -0,0 +1,84 @@ +#当前服务的基本信息 +microservice: + ename: cn-begin + name: cn-begin +server: + port: 19001 +spring: + application: + name: cn-begin + + profiles: + active: wuxi_dev + + + jackson: + time-zone: GMT+8 + date-format: yyyy-MM-dd HH:mm:ss + locale: zh_CN + serialization: + # 格式化输出 + indent_output: false + servlet: + multipart: + max-file-size: 100MB + max-request-size: 100MB + +#mybatis配置信息 +mybatis-plus: + mapper-locations: classpath*:com/njcn/**/mapping/*.xml + #别名扫描 + type-aliases-package: com.njcn.product.**.pojo + configuration: + #驼峰命名 + map-underscore-to-camel-case: true + #配置sql日志输出 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + # #关闭日志输出 + # log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl + global-config: + db-config: + #指定主键生成策略 + id-type: assign_uuid +db: + type: mysql +#文件位置配置 +business: + #处理波形数据位置 + wavePath: D://comtrade + #wavePath: /usr/local/comtrade + #处理临时数据 + #tempPath: D://file + tempPath: /usr/local/file + #文件存储的方式 1.本地 + file: + storage: 1 + #localStoragePath: /usr/local/localStoragePath + localStoragePath: f://localStoragePath +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.22:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 + +#线程池配置信息 +threadPool: + corePoolSize: 10 + maxPoolSize: 20 + queueCapacity: 500 + keepAliveSeconds: 60 +file: + upload-dir: D:/carry + + diff --git a/cn-begin/src/main/resources/logback.xml b/cn-begin/src/main/resources/logback.xml new file mode 100644 index 0000000..7864c7b --- /dev/null +++ b/cn-begin/src/main/resources/logback.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %logger{36} - %msg%n + UTF-8 + + + + + + + + ${logHomeDir}/${log.projectName}/debug/debug.log + + + + + DEBUG + + ACCEPT + + DENY + + + + + + ${logHomeDir}/${log.projectName}/debug/debug.log.%d{yyyy-MM-dd}.%i.log + + 10MB + + ${log.maxHistory:-30} + + + + + + + + + + ${log.pattern} + + UTF-8 + + + + + + + INFO + ACCEPT + DENY + + + ${logHomeDir}/${log.projectName}/info/info.log + + + + ${logHomeDir}/${log.projectName}/info/info.log.%d{yyyy-MM-dd}.%i.log + + 10MB + ${log.maxHistory:-30} + + + + ${log.pattern} + + UTF-8 + + + + + + + + ${logHomeDir}/${log.projectName}/error/error.log + + + ERROR + ACCEPT + DENY + + + + ${logHomeDir}/${log.projectName}/error/error.log.%d{yyyy-MM-dd}.%i.log + + 10MB + ${log.maxHistory:-30} + + + + ${log.pattern} + + UTF-8 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cn-begin/src/test/java/com/njcn/product/begin/CnBeginApplicationTests.java b/cn-begin/src/test/java/com/njcn/product/begin/CnBeginApplicationTests.java new file mode 100644 index 0000000..768d156 --- /dev/null +++ b/cn-begin/src/test/java/com/njcn/product/begin/CnBeginApplicationTests.java @@ -0,0 +1,13 @@ +package com.njcn.product.begin; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CnBeginApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/cn-diagram/.gitignore b/cn-diagram/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-diagram/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-diagram/pom.xml b/cn-diagram/pom.xml new file mode 100644 index 0000000..e8983f8 --- /dev/null +++ b/cn-diagram/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + cn-diagram + 1.0.0 + cn-diagram + cn-diagram + + + + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + com.njcn.product + cn-user + 1.0.0 + + + + + com.njcn.product + cn-auth + 1.0.0 + + + + com.njcn.product + cn-system + 1.0.0 + + + + com.njcn.product + cn-zutai + 1.0.0 + + + + com.njcn.product + cn-terminal + 1.0.0 + + + + org.springframework.boot + spring-boot-starter-websocket + ${websocket.version} + + + + com.njcn + common-oss + 1.0.0 + + + com.njcn + common-web + + + + + + + + + com.baomidou + dynamic-datasource-spring-boot-starter + 3.5.1 + + + + + com.njcn.product + cn-advance + 1.0.0 + + + + + + diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/controller/LedgerScaleController.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/controller/LedgerScaleController.java new file mode 100644 index 0000000..9058003 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/controller/LedgerScaleController.java @@ -0,0 +1,171 @@ +package com.njcn.product.diagram.LedgerScale.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; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility; +import com.njcn.product.diagram.LedgerScale.pojo.dto.EventSourceDTO; +import com.njcn.product.diagram.LedgerScale.pojo.dto.LedgerScaleDTO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventDetailVO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventLedgerVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalShowVO; +import com.njcn.product.diagram.LedgerScale.service.LedgerScaleService; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: 台账规模 + */ +@Slf4j +@RestController +@Api(tags = "大屏") +@RequestMapping("/scale") +@RequiredArgsConstructor +public class LedgerScaleController extends BaseController { + + private final LedgerScaleService ledgerScaleService; + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/ledgerScale") + @ApiOperation("台账规模") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult ledgerScale(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("ledgerScale"); + LedgerScaleDTO ledgerScaleDTO = ledgerScaleService.ledgerScaleStatistic(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, ledgerScaleDTO, methodDescribe); + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/eventSource") + @ApiOperation("暂降溯源统计") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult eventSource(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("eventSource"); + EventSourceDTO eventSourceDTO = ledgerScaleService.eventSource(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, eventSourceDTO, methodDescribe); + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/eventAggregation") + @ApiOperation("暂降聚合分析") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult eventAggregation(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("eventAggregation"); + EventSourceDTO eventSourceDTO = ledgerScaleService.eventAggregation(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, eventSourceDTO, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/hasEventList") + @ApiOperation("一次接线图发生暂降事件的监测点闪烁") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> hasEventList(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("hasEventList"); + List result = ledgerScaleService.hasEventList(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/hasUpEventList") + @ApiOperation("一次接线图发生谐波放大的监测点闪烁") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> hasUpEventList(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("hasUpEventList"); + List result = ledgerScaleService.hasUpEventList(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/clickImage") + @ApiOperation("一次接线图点击事件") + @ApiImplicitParam(name = "lineId", value = "查询参数", required = true) + public HttpResult clickImage(@RequestParam("lineId")String lineId) { + String methodDescribe = getMethodDescribe("clickImage"); + EventLedgerVO result = ledgerScaleService.clickImage(lineId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/eventList") + @ApiOperation("暂降实时数据") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> eventList(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("eventList"); + Page result = ledgerScaleService.eventList(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/eventListByLineId") + @ApiOperation("暂降实时数据") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> eventListByLineId(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("eventListByLineId"); + Page result = ledgerScaleService.eventListByLineId(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/stationPage") + @ApiOperation("电站详情") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> stationPage(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("stationPage"); + Page result = ledgerScaleService.stationPage(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/devPage") + @ApiOperation("终端详情") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> devPage(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("devPage"); + Page result = ledgerScaleService.devPage(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/linePage") + @ApiOperation("监测点详情") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> linePage(@RequestBody LargeScreenCountParam param) { + String methodDescribe = getMethodDescribe("linePage"); + Page result = ledgerScaleService.linePage(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/harmOneImage") + @ApiOperation("谐波溯源事件点击关联一次接线图") + @ApiImplicitParam(name = "param", value = "查询参数", required = true) + public HttpResult> harmOneImage(@RequestParam("id")String id, @RequestParam("time")Integer time) { + String methodDescribe = getMethodDescribe("harmOneImage"); + List result = ledgerScaleService.harmOneImage(id,time); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/EventSourceDTO.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/EventSourceDTO.java new file mode 100644 index 0000000..f7c6738 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/EventSourceDTO.java @@ -0,0 +1,32 @@ +package com.njcn.product.diagram.LedgerScale.pojo.dto; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: + */ +@Data +public class EventSourceDTO { + + private Integer eventCount = 0; + + private List innerList = new ArrayList<>(); + + + + @Data + public static class Inner{ + + private String id; + + private String name; + + private Integer count; + + } +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/LedgerScaleDTO.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/LedgerScaleDTO.java new file mode 100644 index 0000000..fb61b05 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/dto/LedgerScaleDTO.java @@ -0,0 +1,25 @@ +package com.njcn.product.diagram.LedgerScale.pojo.dto; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: 台账规模 + */ +@Data +public class LedgerScaleDTO { + + private Integer stationAll; + + private Integer stationRun; + + private Integer devAll; + + private Integer devRun; + + private Integer lineAll; + + private Integer lineRun; + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventDetailVO.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventDetailVO.java new file mode 100644 index 0000000..cde637b --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventDetailVO.java @@ -0,0 +1,82 @@ +package com.njcn.product.diagram.LedgerScale.pojo.vo; + +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @Author: cdf + * @CreateTime: 2025-09-03 + * @Description: + */ +@EqualsAndHashCode(callSuper = true) +@Data +public class EventDetailVO extends RmpEventDetailPO { + + + /** + * 监测点id + */ + private String lineId; + + /** + * 监测点名称 + */ + private String lineName; + + /** + * 装置通道 + */ + private Integer num; + + /** + * 监测点电压等级 + */ + private String voltageLevel; + + /** + * 监测点用户 + */ + private String objName; + + /** + * 0:通讯中断;1:通讯正常 + */ + private Integer comFlag; + + /** + * 0:投运;1:热备用;2:停运 + */ + private Integer runFlag; + + /** + * 设备id + */ + private String devId; + + /** + * 设备名称 + */ + private String devName; + + /** + * 电站id + */ + private String stationId; + + /** + * 电站名称 + */ + private String stationName; + + /** + * 供电id + */ + private String gdId; + + /** + * 供电公司 + */ + private String gdName; + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventLedgerVO.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventLedgerVO.java new file mode 100644 index 0000000..4d52aac --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/pojo/vo/EventLedgerVO.java @@ -0,0 +1,27 @@ +package com.njcn.product.diagram.LedgerScale.pojo.vo; + +import com.njcn.product.diagram.LedgerScale.pojo.dto.LedgerScaleDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-03 + * @Description: + */ +@EqualsAndHashCode(callSuper = true) +@Data +public class EventLedgerVO extends LedgerBaseInfo { + + private List eventIds; + + private List eventList; + + private Integer isImport; + + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/LedgerScaleService.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/LedgerScaleService.java new file mode 100644 index 0000000..eb3e5d4 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/LedgerScaleService.java @@ -0,0 +1,47 @@ +package com.njcn.product.diagram.LedgerScale.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility; +import com.njcn.product.diagram.LedgerScale.pojo.dto.EventSourceDTO; +import com.njcn.product.diagram.LedgerScale.pojo.dto.LedgerScaleDTO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventDetailVO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventLedgerVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalShowVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: + */ +public interface LedgerScaleService { + + LedgerScaleDTO ledgerScaleStatistic(LargeScreenCountParam param); + + EventSourceDTO eventSource(LargeScreenCountParam param); + + EventSourceDTO eventAggregation(LargeScreenCountParam param); + + List hasEventList(LargeScreenCountParam param); + + List hasUpEventList(LargeScreenCountParam param); + + + EventLedgerVO clickImage(String lineId); + + Page eventList(LargeScreenCountParam param); + + Page eventListByLineId(LargeScreenCountParam param); + + Page stationPage(LargeScreenCountParam param); + + Page devPage(LargeScreenCountParam param); + + Page linePage(LargeScreenCountParam param); + + + List harmOneImage(String id, Integer time); +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/impl/LedgerScaleServiceImpl.java b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/impl/LedgerScaleServiceImpl.java new file mode 100644 index 0000000..fc8ce45 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/LedgerScale/service/impl/LedgerScaleServiceImpl.java @@ -0,0 +1,500 @@ +package com.njcn.product.diagram.LedgerScale.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.date.DateTime; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.advance.eventSource.mapper.RmpEventDetailAssMapper; +import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO; +import com.njcn.product.advance.harmonicUp.mapper.UpHarmonicDetailMapper; +import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail; +import com.njcn.product.advance.responsility.mapper.RespDataResultMapper; +import com.njcn.product.advance.responsility.pojo.dto.CustomerData; +import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility; +import com.njcn.product.advance.responsility.pojo.dto.ResponsibilityResult; +import com.njcn.product.advance.responsility.pojo.po.RespDataResult; +import com.njcn.product.diagram.LedgerScale.pojo.dto.EventSourceDTO; +import com.njcn.product.diagram.LedgerScale.pojo.dto.LedgerScaleDTO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventDetailVO; +import com.njcn.product.diagram.LedgerScale.pojo.vo.EventLedgerVO; +import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.UserReportPOMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportPO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalShowVO; +import com.njcn.product.diagram.LedgerScale.service.LedgerScaleService; +import com.njcn.product.system.dict.mapper.DictDataMapper; +import com.njcn.product.system.dict.pojo.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.terminal.mysqlTerminal.mapper.LedgerScaleMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.RmpEventDetailMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.RunFlagEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import com.njcn.product.terminal.mysqlTerminal.service.CommGeneralService; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.io.InputStream; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: 台账规模 + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class LedgerScaleServiceImpl implements LedgerScaleService { + + private final CommGeneralService commGeneralService; + + private final LedgerScaleMapper ledgerScaleMapper; + + private final RmpEventDetailMapper rmpEventDetailMapper; + + private final RmpEventDetailAssMapper rmpEventDetailAssMapper; + private final DictDataMapper dictDataMapper; + private final LineMapper lineMapper; + + private final RespDataResultMapper respDataResultMapper; + + private final FileStorageUtil fileStorageUtil; + private final UserReportPOMapper userReportPOMapper; + private final UpHarmonicDetailMapper upHarmonicDetailMapper; + + + @Override + public LedgerScaleDTO ledgerScaleStatistic(LargeScreenCountParam param) { + LedgerScaleDTO ledgerScaleDTO = new LedgerScaleDTO(); + + List deptIds = commGeneralService.getAllLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(deptIds)) { + throw new BusinessException(CommonResponseEnum.FAIL, "用户部门没有绑定监测点"); + } + + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(deptIds); + + List runList = ledgerBaseInfoList.stream().filter(it -> Objects.equals(it.getRunFlag(), RunFlagEnum.RUNNING.getStatus())).collect(Collectors.toList()); + + + List onlineList = runList.stream().filter(it -> it.getComFlag() == 1).collect(Collectors.toList()); + + ledgerScaleDTO.setLineAll(runList.size()); + ledgerScaleDTO.setLineRun(onlineList.size()); + + long devAll = ledgerBaseInfoList.stream().map(LedgerBaseInfo::getDevId).distinct().count(); + long devRun = runList.stream().map(LedgerBaseInfo::getDevId).distinct().count(); + ledgerScaleDTO.setDevAll((int) devAll); + ledgerScaleDTO.setDevRun((int) devRun); + + long stationAll = ledgerBaseInfoList.stream().map(LedgerBaseInfo::getStationId).distinct().count(); + long stationRun = runList.stream().map(LedgerBaseInfo::getStationId).distinct().count(); + ledgerScaleDTO.setStationAll((int) stationAll); + ledgerScaleDTO.setStationRun((int) stationRun); + return ledgerScaleDTO; + } + + @Override + public EventSourceDTO eventSource(LargeScreenCountParam param) { + EventSourceDTO eventSourceDTO = new EventSourceDTO(); + List deptIds = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(deptIds)) { + return eventSourceDTO; + } + + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.between(RmpEventDetailPO::getStartTime, start, end).in(RmpEventDetailPO::getLineId, deptIds); + List eventList = rmpEventDetailMapper.selectList(lambdaQueryWrapper); + if (CollUtil.isEmpty(eventList)) { + return eventSourceDTO; + } + + List ids = eventList.stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList()); + List ledgerBaseInfoList = ledgerScaleMapper.getBaseInfo(ids); + Map objMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity())); + + Map> map = eventList.stream().collect(Collectors.groupingBy(RmpEventDetailPO::getLineId)); + + List innerList = new ArrayList<>(); + map.forEach((k, val) -> { + EventSourceDTO.Inner inner = new EventSourceDTO.Inner(); + LedgerBaseInfo ledgerBaseInfo = objMap.get(k); + inner.setName(StrUtil.isNotBlank(ledgerBaseInfo.getObjName()) ? ledgerBaseInfo.getObjName() : ledgerBaseInfo.getLineName()); + inner.setCount(val.size()); + inner.setId(ledgerBaseInfo.getLineId()); + innerList.add(inner); + }); + eventSourceDTO.setEventCount(eventList.size()); + eventSourceDTO.setInnerList(innerList); + + return eventSourceDTO; + } + + @Override + public EventSourceDTO eventAggregation(LargeScreenCountParam param) { + EventSourceDTO eventSourceDTO = new EventSourceDTO(); + + + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.orderByDesc(RmpEventDetailAssPO::getTimeId).between(RmpEventDetailAssPO::getTimeId, start, end); + List assPOList = rmpEventDetailAssMapper.selectList(lambdaQueryWrapper); + if (CollUtil.isEmpty(assPOList)) { + return eventSourceDTO; + } + /* Map assObjMap = assPOList.stream().collect(Collectors.toMap(RmpEventDetailAssPO::getEventAssId, Function.identity())); + + List assIds = assPOList.stream().map(RmpEventDetailAssPO::getEventAssId).collect(Collectors.toList()); + List rmpEventDetailPOList = rmpEventDetailMapper.selectList(new LambdaQueryWrapper().in(RmpEventDetailPO::getEventassIndex, assIds)); + + + Map assMap = assPOList.stream().collect(Collectors.toMap(RmpEventDetailAssPO::getEventAssId, RmpEventDetailAssPO::getTimeId)); + rmpEventDetailPOList = rmpEventDetailPOList.stream().filter(it -> { + if (!assMap.containsKey(it.getEventassIndex())) { + return false; + } + LocalDateTime localDateTime = assMap.get(it.getEventassIndex()); + if (it.getStartTime().equals(localDateTime)) { + return true; + } else { + return false; + } + }).collect(Collectors.toList());*/ + + eventSourceDTO.setEventCount(assPOList.size()); + + List innerList = new ArrayList<>(); + for (RmpEventDetailAssPO it : assPOList) { + EventSourceDTO.Inner inner = new EventSourceDTO.Inner(); + inner.setId(it.getEventAssId()); + inner.setName(it.getContentDes()); + innerList.add(inner); + } + eventSourceDTO.setInnerList(innerList); + return eventSourceDTO; + } + + @Override + public List hasEventList(LargeScreenCountParam param) { + List result = new ArrayList<>(); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + if (StrUtil.isBlank(param.getEventAssId())) { + List ids = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(ids)) { + return result; + } + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + lambdaQueryWrapper.in(RmpEventDetailPO::getLineId, ids).between(RmpEventDetailPO::getStartTime, start, end); + } else { + lambdaQueryWrapper.eq(RmpEventDetailPO::getEventassIndex, param.getEventAssId()); + } + + + List rmpEventDetailPOList = rmpEventDetailMapper.selectList(lambdaQueryWrapper); + List lineIds = rmpEventDetailPOList.stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList()); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + Map ledgerBaseInfoMap = ledgerScaleMapper.getLedgerBaseInfo(lineIds).stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity())); + Map> map = rmpEventDetailPOList.stream().collect(Collectors.groupingBy(RmpEventDetailPO::getLineId)); + + RmpEventDetailPO minPo = rmpEventDetailPOList.stream().min(Comparator.comparingDouble(RmpEventDetailPO::getFeatureAmplitude)).get(); + map.forEach((lineId, list) -> { + + + + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(lineId); + EventLedgerVO eventLedgerVO = new EventLedgerVO(); + BeanUtil.copyProperties(ledgerBaseInfo, eventLedgerVO); + eventLedgerVO.setEventIds(list.stream().map(RmpEventDetailPO::getEventId).collect(Collectors.toList())); + if (StrUtil.isBlank(param.getEventAssId())) { + eventLedgerVO.setIsImport(DataStateEnum.DELETED.getCode()); + }else { + if(minPo.getLineId().equals(lineId)){ + eventLedgerVO.setIsImport(DataStateEnum.ENABLE.getCode()); + }else { + eventLedgerVO.setIsImport(DataStateEnum.DELETED.getCode()); + } + } + result.add(eventLedgerVO); + }); + return result; + } + + @Override + public List hasUpEventList(LargeScreenCountParam param) { + List result = new ArrayList<>(); + List ids = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(ids)) { + return result; + } + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + lambdaQueryWrapper.in(UpHarmonicDetail::getMonitorId, ids).between(UpHarmonicDetail::getStartTime, start, end); + List upHarmonicDetailList = upHarmonicDetailMapper.selectList(lambdaQueryWrapper); + if(CollUtil.isEmpty(upHarmonicDetailList)){ + return result; + } + + List monitorIds = upHarmonicDetailList.stream().map(UpHarmonicDetail::getMonitorId).distinct().collect(Collectors.toList()); + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(monitorIds); + Map ledgerBaseInfoMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId,Function.identity())); + + Map> map = upHarmonicDetailList.stream().collect(Collectors.groupingBy(UpHarmonicDetail::getMonitorId)); + map.forEach((lineId,list)->{ + EventLedgerVO eventLedgerVO = new EventLedgerVO(); + BeanUtil.copyProperties(ledgerBaseInfoMap.get(lineId),eventLedgerVO); + eventLedgerVO.setEventIds(list.stream().map(UpHarmonicDetail::getId).collect(Collectors.toList())); + result.add(eventLedgerVO); + }); + return result; + } + + @Override + public EventLedgerVO clickImage(String lineId) { + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(Stream.of(lineId).collect(Collectors.toList())); + if (CollUtil.isEmpty(ledgerBaseInfoList)) { + throw new BusinessException(CommonResponseEnum.FAIL, "当前节点未查询到测点信息"); + } + + EventLedgerVO eventLedgerVO = new EventLedgerVO(); + BeanUtil.copyProperties(ledgerBaseInfoList.get(0), eventLedgerVO); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(RmpEventDetailPO::getLineId, lineId); + List rmpEventDetailPOList = rmpEventDetailMapper.selectList(lambdaQueryWrapper); + + List dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()); + Map dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + rmpEventDetailPOList.forEach(item-> item.setEventType(dictDataMap.get(item.getEventType()).getName())); + eventLedgerVO.setEventList(rmpEventDetailPOList); + return eventLedgerVO; + } + + + @Override + public Page eventList(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + if (StrUtil.isBlank(param.getEventAssId())) { + List ids = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(ids)) { + return result; + } + + if(StrUtil.isNotBlank(param.getSearchValue())){ + ids = ledgerScaleMapper.getQueryLedger(ids,param.getSearchValue()); + if (CollUtil.isEmpty(ids)) { + return result; + } + } + + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + lambdaQueryWrapper.in(RmpEventDetailPO::getLineId, ids).between(RmpEventDetailPO::getStartTime, start, end).orderByDesc(RmpEventDetailPO::getStartTime); + + if(StrUtil.isNotBlank(param.getEventType())){ + lambdaQueryWrapper.eq(RmpEventDetailPO::getEventType,param.getEventType()); + } + + if(Objects.nonNull(param.getEventDurationMin()) ||Objects.nonNull(param.getEventDurationMax())){ + lambdaQueryWrapper.gt(Objects.nonNull(param.getEventDurationMin()),RmpEventDetailPO::getDuration,param.getEventDurationMin()); + lambdaQueryWrapper.lt(Objects.nonNull(param.getEventDurationMax()),RmpEventDetailPO::getDuration,param.getEventDurationMax()); + } + + if(Objects.nonNull(param.getEventValueMin()) ||Objects.nonNull(param.getEventValueMax())){ + lambdaQueryWrapper.gt(Objects.nonNull(param.getEventValueMin()),RmpEventDetailPO::getFeatureAmplitude,param.getEventValueMin()); + lambdaQueryWrapper.lt(Objects.nonNull(param.getEventValueMax()),RmpEventDetailPO::getFeatureAmplitude,param.getEventValueMax()); + } + + } else { + lambdaQueryWrapper.eq(RmpEventDetailPO::getEventassIndex, param.getEventAssId()); + } + + Page page = rmpEventDetailMapper.selectPage(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lambdaQueryWrapper); + if (CollUtil.isEmpty(page.getRecords())) { + return result; + } + + List lineIds = page.getRecords().stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList()); + Map ledgerBaseInfoMap = ledgerScaleMapper.getLedgerBaseInfo(lineIds).stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity())); + + List dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()); + Map dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + + List temList = new ArrayList<>(); + page.getRecords().forEach(item -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + BeanUtil.copyProperties(item, eventDetailVO); + + eventDetailVO.setFeatureAmplitude(BigDecimal.valueOf(item.getFeatureAmplitude()).setScale(5, RoundingMode.HALF_UP).doubleValue()); + eventDetailVO.setEventType(dictDataMap.get(eventDetailVO.getEventType()).getName()); + + if (ledgerBaseInfoMap.containsKey(item.getLineId())) { + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(item.getLineId()); + BeanUtil.copyProperties(ledgerBaseInfo, eventDetailVO); + } + temList.add(eventDetailVO); + }); + result.setRecords(temList); + result.setTotal(page.getTotal()); + return result; + } + + + @Override + public Page eventListByLineId(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())); + lambdaQueryWrapper.eq(RmpEventDetailPO::getLineId, param.getLineId()).between(RmpEventDetailPO::getStartTime, start, end).orderByDesc(RmpEventDetailPO::getStartTime); + + Page page = rmpEventDetailMapper.selectPage(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lambdaQueryWrapper); + if (CollUtil.isEmpty(page.getRecords())) { + return result; + } + + List ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(Collections.singletonList(param.getLineId())); + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoList.get(0); + + List dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()); + Map dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + + List temList = new ArrayList<>(); + page.getRecords().forEach(item -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + BeanUtil.copyProperties(item, eventDetailVO); + + eventDetailVO.setFeatureAmplitude(BigDecimal.valueOf(item.getFeatureAmplitude()).setScale(5, RoundingMode.HALF_UP).doubleValue()); + eventDetailVO.setEventType(dictDataMap.get(eventDetailVO.getEventType()).getName()); + BeanUtil.copyProperties(ledgerBaseInfo, eventDetailVO); + temList.add(eventDetailVO); + }); + result.setRecords(temList); + result.setTotal(page.getTotal()); + return result; + } + + + @Override + public Page stationPage(LargeScreenCountParam param) { + List lineIds = commGeneralService.getAllLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(lineIds)) { + return new Page<>(); + } + Page page = lineMapper.getStationList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getRunFlag(), param.getSearchValue()); + if (CollUtil.isNotEmpty(page.getRecords())) { + List dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()); + Map map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + page.getRecords().forEach(it -> { + if (map.containsKey(it.getStationVoltageLevel())) { + it.setStationVoltageLevel(map.get(it.getStationVoltageLevel()).getName()); + } + }); + } + + return page; + } + + + @Override + public Page devPage(LargeScreenCountParam param) { + List lineIds = commGeneralService.getAllLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(lineIds)) { + return new Page<>(); + } + Page page = lineMapper.getDevList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getRunFlag(), param.getSearchValue()); + if (CollUtil.isNotEmpty(page.getRecords())) { + List dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_MANUFACTURER.getCode()); + Map map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + page.getRecords().forEach(it -> { + if (map.containsKey(it.getManufacturer())) { + it.setManufacturer(map.get(it.getManufacturer()).getName()); + } + }); + } + return page; + } + + @Override + public Page linePage(LargeScreenCountParam param) { + List lineIds = commGeneralService.getRunLineIdsByDept(param.getDeptId()); + if (CollUtil.isEmpty(lineIds)) { + return new Page<>(); + } + Page page = lineMapper.getLineList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getComFlag(), param.getSearchValue()); + if (CollUtil.isNotEmpty(page.getRecords())) { + List dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()); + Map map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity())); + page.getRecords().forEach(it -> { + if (map.containsKey(it.getVoltageLevel())) { + it.setVoltageLevel(map.get(it.getVoltageLevel()).getName()); + } + }); + } + return page; + } + + @Override + public List harmOneImage(String id, Integer time) { + LambdaQueryWrapper respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>(); + respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, id) + .eq(RespDataResult::getTime, time).orderByDesc(RespDataResult::getCreateTime); + List respDataResults = respDataResultMapper.selectList(respDataResultLambdaQueryWrapper); + if (CollectionUtil.isNotEmpty(respDataResults)) { + + RespDataResult respDataResult = respDataResults.get(0); + //处理排名前10数据 + InputStream respStream = fileStorageUtil.getFileStream(respDataResult.getUserResponsibility()); + String respStr = IoUtil.readUtf8(respStream); + List respData = JSONArray.parseArray(respStr, CustomerResponsibility.class); + List userNos = respData.stream().map(it -> it.getCustomerName().substring(it.getCustomerName().indexOf("(") + 1, it.getCustomerName().indexOf(")"))).collect(Collectors.toList()); + + List ledgerBaseInfoList = lineMapper.queryMonitorByUser(userNos); + Map ledgerBaseInfoMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getUserNo, Function.identity())); + respData.forEach(it -> { + String tem = it.getCustomerName().substring(it.getCustomerName().indexOf("(") + 1, it.getCustomerName().indexOf(")")); + if (ledgerBaseInfoMap.containsKey(tem)) { + LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(tem); + it.setMonitorId(ledgerBaseInfo.getLineId()); + } + }); + return respData; + } + return new ArrayList<>(); + } + + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/job/CustomJob.java b/cn-diagram/src/main/java/com/njcn/product/diagram/job/CustomJob.java new file mode 100644 index 0000000..af0d9f4 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/job/CustomJob.java @@ -0,0 +1,39 @@ +package com.njcn.product.diagram.job; + +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateTime; +import com.njcn.product.advance.harmonicUp.service.HarmonicUpService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +/** + * @Author: cdf + * @CreateTime: 2025-09-19 + * @Description: 定时任务 + */ +@Component +@EnableScheduling +@RequiredArgsConstructor +@Slf4j +public class CustomJob { + + private final HarmonicUpService harmonicUpService; + + // 每天凌晨4:30执行 + @Scheduled(cron = "0 30 4 * * ?") + public void UpHarmonicJob(){ + log.info("开始执行谐波放大调度任务--------------------------------"); + String date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)); + harmonicUpService.analyzePreData(date); + log.info("执行谐波放大调度任务结束--------------------------------"); + } + + + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketConfig.java b/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketConfig.java new file mode 100644 index 0000000..21eeaf5 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketConfig.java @@ -0,0 +1,41 @@ +package com.njcn.product.diagram.websocket; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; +import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; + +/** + * Description: + * Date: 2024/12/13 15:09【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Configuration +public class WebSocketConfig { + + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } + + /** + * 通信文本消息和二进制缓存区大小 + * 避免对接 第三方 报文过大时,Websocket 1009 错误 + * + * @return + */ + + @Bean + public ServletServerContainerFactoryBean createWebSocketContainer() { + ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); + // 在此处设置bufferSize + container.setMaxTextMessageBufferSize(10240000); + container.setMaxBinaryMessageBufferSize(10240000); + container.setMaxSessionIdleTimeout(15 * 60000L); + return container; + } + + +} diff --git a/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketServer.java b/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketServer.java new file mode 100644 index 0000000..a011594 --- /dev/null +++ b/cn-diagram/src/main/java/com/njcn/product/diagram/websocket/WebSocketServer.java @@ -0,0 +1,176 @@ +package com.njcn.product.diagram.websocket; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSONObject; +import com.njcn.product.cnzutai.zutai.pojo.dto.AskRealTimeDataDTO; +import com.njcn.product.cnzutai.zutai.pojo.dto.RealTimeDataDTO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsRtDataVO; +import com.njcn.product.cnzutai.zutai.service.ILineTargetService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + + +@Slf4j +@Component +@ServerEndpoint(value = "/ws/{userId}") +public class WebSocketServer { + + private static final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap lastHeartbeatTime = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap heartbeatExecutors = new ConcurrentHashMap<>(); + // 60秒超时 + private static final long HEARTBEAT_TIMEOUT = 60; + + @Autowired + private static ILineTargetService lineTargetService; + + @Autowired + public void setDataVQuery( ILineTargetService lineTargetService) { + WebSocketServer.lineTargetService = lineTargetService; + } + + + @OnOpen + public void onOpen(Session session, @PathParam("userId") String userId) { + if (StrUtil.isNotBlank(userId)) { + sessions.put(userId, session); + lastHeartbeatTime.put(userId, System.currentTimeMillis()); + sendMessage(session, "连接成功"); + System.out.println("用户 " + userId + " 已连接"); + + // 启动心跳检测 + startHeartbeat(session, userId); + } else { + try { + session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "用户ID不能为空")); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @OnMessage + public void onMessage(String message, Session session, @PathParam("userId") String userId) { + if ("alive".equalsIgnoreCase(message)) { + // 更新最后心跳时间 + lastHeartbeatTime.put(userId, System.currentTimeMillis()); + sendMessage(session, "over"); + } else { + System.out.println("收到用户 " + userId + " 的消息: " + message); + // TODO: 处理业务逻辑 + + AskRealTimeDataDTO param = JSONUtil.toBean(message,AskRealTimeDataDTO.class,true); + if(Objects.isNull(message)){ + RealTimeDataDTO recallReplyDTO = new RealTimeDataDTO(500,"参数有误",1); + sendMessage(session, JSONObject.toJSONString(recallReplyDTO)); + }else { + List lineData = lineTargetService.getLineData(param.getPageId()); + List collect = lineData.stream().filter(temp -> (!CollectionUtils.isEmpty(param.getLineIdList())) && param.getLineIdList().contains(temp.getLineId())).collect(Collectors.toList()); + RealTimeDataDTO recallReplyDTO = new RealTimeDataDTO(); + recallReplyDTO.setCode(200); + recallReplyDTO.setMessage(JSONObject.toJSONString(collect)); + + sendMessage(session,JSONObject.toJSONString(recallReplyDTO)); + + } + } + } + + @OnClose + public void onClose(Session session, CloseReason closeReason, @PathParam("userId") String userId) { + // 移除用户并取消心跳检测 + sessions.remove(userId); + lastHeartbeatTime.remove(userId); + ScheduledExecutorService executor = heartbeatExecutors.remove(userId); + if (executor != null) { + executor.shutdownNow(); + } + System.out.println("用户 " + userId + " 已断开连接,状态码: " + closeReason.getCloseCode()); + } + + @OnError + public void onError(Session session, Throwable throwable, @PathParam("userId") String userId) { + System.out.println("用户 " + userId + " 发生错误: " + throwable.getMessage()); + try { + session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "发生错误")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void sendMessageToUser(String userId, String message) { + Session session = sessions.get(userId); + if (session != null && session.isOpen()) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage()); + } + } else { + System.out.println("webSocket用户 " + userId + " 不在线或会话已关闭"); + } + } + + private final Object lock = new Object(); + + public void sendMessageToAll(String message) { + sessions.forEach((userId, session) -> { + System.out.println("给用户推送消息" + userId); + if (session.isOpen()) { + synchronized (lock) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage()); + } + } + } + }); + } + + private void sendMessage(Session session, String message) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息失败: " + e.getMessage()); + } + } + + private void startHeartbeat(Session session, String userId) { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + heartbeatExecutors.put(userId, executor); + + // 定期检查心跳 + executor.scheduleAtFixedRate(() -> { + long lastTime = lastHeartbeatTime.getOrDefault(userId, 0L); + long currentTime = System.currentTimeMillis(); + + // 如果超过30秒没有收到心跳 + if (currentTime - lastTime > HEARTBEAT_TIMEOUT * 1000) { + try { + System.out.println("用户 " + userId + " 心跳超时,关闭连接"); + session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "心跳超时")); + } catch (IOException e) { + System.out.println("关闭用户 " + userId + " 连接时出错: " + e.getMessage()); + } + executor.shutdown(); + heartbeatExecutors.remove(userId); + } + }, 0, 5, TimeUnit.SECONDS); // 每5秒检查一次 + } +} \ No newline at end of file diff --git a/cn-terminal/.gitignore b/cn-terminal/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-terminal/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-terminal/pom.xml b/cn-terminal/pom.xml new file mode 100644 index 0000000..f14a981 --- /dev/null +++ b/cn-terminal/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + cn-terminal + 1.0.0 + cn-terminal + cn-terminal + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + + com.oracle.database.jdbc + ojdbc8 + 21.6.0.0 + + + com.oracle.database.nls + orai18n + 21.1.0.0 + + + + + + com.baomidou + dynamic-datasource-spring-boot-starter + 3.5.1 + + + + com.njcn + common-event + 1.0.0 + + + common-microservice + com.njcn + + + common-web + com.njcn + + + + + + com.njcn.product + cn-user + 1.0.0 + + + + com.njcn.product + cn-system + 1.0.0 + + + + com.alibaba + fastjson + 1.2.83 + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceDetailMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceDetailMapper.java new file mode 100644 index 0000000..2b9e285 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceDetailMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.device.pojo.po.PqDeviceDetail; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/12 + */ +public interface PqDeviceDetailMapper extends BaseMapper { +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceMapper.java new file mode 100644 index 0000000..efdda14 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqDeviceMapper.java @@ -0,0 +1,30 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.terminal.device.pojo.dto.DeviceDTO; +import com.njcn.product.terminal.device.pojo.dto.DeviceDeptDTO; +import com.njcn.product.terminal.device.pojo.po.PqDevice; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDeviceMapper extends BaseMapper { + List queryListByIds(@Param("ids") List ids); + + Page selectDeviceDTOPage(Page pqsEventdetailPage, @Param("searchValue") String searchValue,@Param("devIndexs") List devIndexs); + + Page queryListByLineIds(Page pqsEventdetailPage, @Param("searchValue") String searchValue,@Param("lineIds") List lineIds); + + + List selectDeviceDept(); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqGdCompanyMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqGdCompanyMapper.java new file mode 100644 index 0000000..acc2ff6 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqGdCompanyMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.device.pojo.po.PqGdCompany; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqGdCompanyMapper extends BaseMapper { + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLineMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLineMapper.java new file mode 100644 index 0000000..68b3c91 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLineMapper.java @@ -0,0 +1,28 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.device.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.terminal.device.pojo.po.PqLine; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqLineMapper extends BaseMapper { + + List getBaseLineInfo(@Param("ids")List ids); + + + List getBaseLedger(@Param("ids")List ids,@Param("searchValue")String searchValue); + + + List getRunMonitorIds(@Param("ids")List ids); + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLinedetailMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLinedetailMapper.java new file mode 100644 index 0000000..f84d33e --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqLinedetailMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.device.pojo.po.PqLinedetail; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface PqLinedetailMapper extends BaseMapper { +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqSubstationMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqSubstationMapper.java new file mode 100644 index 0000000..89c2085 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqSubstationMapper.java @@ -0,0 +1,21 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.terminal.device.pojo.dto.SubstationDTO; +import com.njcn.product.terminal.device.pojo.po.PqSubstation; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqSubstationMapper extends BaseMapper { + List queryListByIds(@Param("ids")List ids); +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsDeptslineMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsDeptslineMapper.java new file mode 100644 index 0000000..3f032c7 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsDeptslineMapper.java @@ -0,0 +1,17 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.device.pojo.po.PqsDeptsline; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptslineMapper extends BaseMapper { + + // List getPhoneUser(@Param("lineId")String lineId); +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsStationMapMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsStationMapMapper.java new file mode 100644 index 0000000..bbf6f15 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/PqsStationMapMapper.java @@ -0,0 +1,18 @@ +package com.njcn.product.terminal.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.terminal.device.pojo.po.PqsStationMap; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsStationMapMapper extends BaseMapper { + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqDeviceMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqDeviceMapper.xml new file mode 100644 index 0000000..e5a326d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqDeviceMapper.xml @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + DEV_INDEX, GD_INDEX, SUB_INDEX, "NAME", "STATUS", DEVTYPE, LOGONTIME, UPDATETIME, + NODE_INDEX, PORTID, DEVFLAG, DEV_SERIES, DEV_KEY, IP, DEVMODEL, CALLFLAG, DATATYPE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqLineMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqLineMapper.xml new file mode 100644 index 0000000..db278fc --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqLineMapper.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + LINE_INDEX, GD_INDEX, SUB_INDEX, SUBV_INDEX, DEV_INDEX, "NAME", PT1, PT2, CT1, CT2, + DEVCMP, DLCMP, JZCMP, XYCMP, SUBV_NO, "SCALE", SUBV_NAME + + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqSubstationMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqSubstationMapper.xml new file mode 100644 index 0000000..01c1e6a --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/mapper/mapping/PqSubstationMapper.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + SUB_INDEX, GD_INDEX, "NAME", "SCALE" + + + + \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDTO.java new file mode 100644 index 0000000..1445451 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDTO.java @@ -0,0 +1,45 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * Description: + * Date: 2025/06/27 下午 3:25【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class DeviceDTO { + private Integer devId; + private String devName; + private Integer stationId; + private String stationName; + private String gdName; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updateTime; + private String devFlag; + private String ip; + private String manufacturerName; + + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate thisTimeCheck; + + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate nextTimeCheck; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime logonTime; + + private String deptName; + //通讯状态 + private Integer runFlag=0; + //装置通讯状态(0:中断;1:正常) + private Integer status; + private double onLineRate=0.00; + private double integrityRate = 0.00; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDeptDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDeptDTO.java new file mode 100644 index 0000000..f084dd6 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/DeviceDeptDTO.java @@ -0,0 +1,18 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import lombok.Data; + +/** + * Description: + * Date: 2025/06/27 下午 3:25【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class DeviceDeptDTO { + private Integer devId; + private String deptId; + private String deptName; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/LedgerBaseInfoDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/LedgerBaseInfoDTO.java new file mode 100644 index 0000000..b0ff2b8 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/LedgerBaseInfoDTO.java @@ -0,0 +1,39 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ +@Data +public class LedgerBaseInfoDTO { + private String gdName; + private String gdIndex; + + private Integer lineId; + + private String lineName; + + private Integer busBarId; + + private String busBarName; + + private Integer devId; + + private String devName; + + private String objName; + + private Integer stationId; + + private String stationName; + //通讯状态 + private Integer runFlag=0; + + private Integer eventCount; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/OracleLedgerTreeDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/OracleLedgerTreeDTO.java new file mode 100644 index 0000000..755a086 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/OracleLedgerTreeDTO.java @@ -0,0 +1,25 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-28 + * @Description: + */ +@Data +public class OracleLedgerTreeDTO { + + private String name; + + private Integer id; + + private Integer pid; + + private Integer level; + + private List children = new ArrayList<>(); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/PqsDeptDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/PqsDeptDTO.java new file mode 100644 index 0000000..8c74107 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/PqsDeptDTO.java @@ -0,0 +1,70 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * Description: + * Date: 2025/07/29 下午 3:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class PqsDeptDTO { + /** + * 部门表Guid + */ + private String deptsIndex; + + /** + * 部门名称 + */ + + private String deptsname; + + /** + * 排序 + */ + + private Integer deptsDesc; + + /** + * (关联表PQS_User)用户表Guid + */ + + private String userIndex; + + /** + * 更新时间 + */ + + private LocalDateTime updatetime; + + /** + * 部门描述 + */ + + private String deptsDescription; + + /** + * 角色状态0:删除;1:正常; + */ + + private Integer state; + + /** + * 行政区域 + */ + + private String area; + + private String areaName; + + + private Integer customDept; + + + private String parentnodeid; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/SubstationDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/SubstationDTO.java new file mode 100644 index 0000000..7a8405d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/dto/SubstationDTO.java @@ -0,0 +1,22 @@ +package com.njcn.product.terminal.device.pojo.dto; + +import lombok.Data; + +/** + * Description: + * Date: 2025/06/27 下午 3:37【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class SubstationDTO { + + private Integer stationId; + private String stationName; + private String gdName; + private double longitude; + private double latitude; + private Integer runFlag=0;; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDevice.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDevice.java new file mode 100644 index 0000000..dab495f --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDevice.java @@ -0,0 +1,127 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.time.LocalDateTime; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠? + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_DEVICE") +public class PqDevice { + /** + * 靠靠 + */ + @TableId(value = "DEV_INDEX", type = IdType.INPUT) + private Integer devIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "SUB_INDEX") + private Integer subIndex; + + /** + * 靠靠 + */ + @TableField(value = "\"NAME\"") + private String name; + + /** + * 靠靠靠(0:靠;1:靠) + */ + @TableField(value = "\"STATUS\"") + private Integer status; + + /** + * (靠縋QS_Dicdata)靠靠Guid + */ + @TableField(value = "DEVTYPE") + private String devtype; + + /** + * 靠靠 + */ + @TableField(value = "LOGONTIME") + private LocalDateTime logontime; + + /** + * 靠靠靠 + */ + @TableField(value = "UPDATETIME") + private LocalDateTime updatetime; + + /** + * 靠縉odeInformation)靠靠靠,靠靠靠靠靠靠靠? + */ + @TableField(value = "NODE_INDEX") + private Integer nodeIndex; + + /** + * 靠ID,靠靠靠 + */ + @TableField(value = "PORTID") + private Long portid; + + /** + * 靠靠(0:投运;1:靠;2:靠) + */ + @TableField(value = "DEVFLAG") + private Integer devflag; + + /** + * 靠靠?靠3ds靠 + */ + @TableField(value = "DEV_SERIES") + private String devSeries; + + /** + * 靠靠,靠3ds靠 + */ + @TableField(value = "DEV_KEY") + private String devKey; + + /** + * IP靠 + */ + @TableField(value = "IP") + private String ip; + + /** + * 靠靠(0:靠靠;1:靠靠) + */ + @TableField(value = "DEVMODEL") + private Integer devmodel; + + /** + * 靠靠? + */ + @TableField(value = "CALLFLAG") + private Integer callflag; + + /** + * 靠靠(0:靠靠;1:靠靠;2:靠靠) + */ + @TableField(value = "DATATYPE") + private Integer datatype; +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDeviceDetail.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDeviceDetail.java new file mode 100644 index 0000000..36df722 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqDeviceDetail.java @@ -0,0 +1,69 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/12 + */ +@TableName(value = "PQ_DEVICEDETAIL") +@Data +public class PqDeviceDetail { + + + @TableId(value = "DEV_INDEX") + private Long devIndex; + + @TableField(value = "Manufacturer") + private String manufacturer; + + @TableField(value = "CheckFlag") + private Long checkFlag; + + @TableField(value="ThisTimeCheck") + private LocalDate ThisTimeCheck; + + @TableField(value="NextTimeCheck") + private LocalDate NextTimeCheck; + + @TableField(value="DATAPLAN") + private Long dataplan; + + @TableField(value="NEWTRAFFIC") + private Long newtraffic; + + + @TableField(value = "electroplate") + private Integer electroplate = 0; + + @TableField(value = "ONTIME") + private Integer ontime; + @TableField(value = "contract") + private String contract; + + @TableField(value = "DEV_CATENA") + private String devCatnea; + + @TableField(value = "SIM") + private String sim; + + @TableField(value = "DEV_NO") + private String devNo; + + @TableField(value = "DEV_LOCATION") + private String devLocation; + + @TableField(value = "IS_ALARM") + private Integer isAlarm; + + + + + } diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqGdCompany.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqGdCompany.java new file mode 100644 index 0000000..6b8524e --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqGdCompany.java @@ -0,0 +1,26 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/9 + */ +@Data +@TableName(value = "PQ_GDINFORMATION") +public class PqGdCompany { + + @TableId(value = "GD_INDEX") + private Long gdIndex; + + @TableField(value="NAME") + private String name; + + @TableField(value="PROVINCE_INDEX") + private Long provinceIndex; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLine.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLine.java new file mode 100644 index 0000000..c701829 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLine.java @@ -0,0 +1,132 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠? + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_LINE") +public class PqLine { + /** + * 靠靠 + */ + @TableId(value = "LINE_INDEX", type = IdType.INPUT) + private Integer lineIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "SUB_INDEX") + private Integer subIndex; + + /** + * 靠靠 + */ + @TableField(value = "SUBV_INDEX") + private Integer subvIndex; + + /** + * 靠靠 + */ + @TableField(value = "DEV_INDEX") + private Integer devIndex; + + /** + * 靠靠 + */ + @TableField(value = "\"NAME\"") + private String name; + + /** + * PT靠靠 + */ + @TableField(value = "PT1") + private Double pt1; + + /** + * PT靠靠 + */ + @TableField(value = "PT2") + private Double pt2; + + /** + * CT靠靠 + */ + @TableField(value = "CT1") + private Double ct1; + + /** + * CT靠靠 + */ + @TableField(value = "CT2") + private Double ct2; + + /** + * 靠靠 + */ + @TableField(value = "DEVCMP") + private Double devcmp; + + /** + * 靠靠 + */ + @TableField(value = "DLCMP") + private Double dlcmp; + + /** + * 靠靠 + */ + @TableField(value = "JZCMP") + private Double jzcmp; + + /** + * 靠靠 + */ + @TableField(value = "XYCMP") + private Double xycmp; + + /** + * 靠?靠靠靠靠靠靠? + */ + @TableField(value = "SUBV_NO") + private Integer subvNo; + + /** + * (靠PQS_Dictionary?靠靠Guid + */ + @TableField(value = "\"SCALE\"") + private String scale; + + /** + * 靠靠 + */ + @TableField(value = "SUBV_NAME") + private String subvName; + + @TableField(exist = false) + private String subName; + + @TableField(exist = false) + private String deptName; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLinedetail.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLinedetail.java new file mode 100644 index 0000000..f35456c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqLinedetail.java @@ -0,0 +1,52 @@ +package com.njcn.product.terminal.device.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("PQ_LINEDETAIL") +public class PqLinedetail { + + @TableId(value = "LINE_INDEX", type = IdType.INPUT) + private Integer lineIndex; + + private Integer gdIndex; + + private Integer subIndex; + + private String lineName; + + private Integer pttype; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date lastTime; + + private Integer tinterval; + + private String loadtype; + + private String businesstype; + + private String remark; + + private String monitorId; + + private Integer powerid; + + private String objname; + + @TableField(fill = FieldFill.INSERT) + private Integer statflag; + + private String lineGrade; + + private String powerSubstationName; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqSubstation.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqSubstation.java new file mode 100644 index 0000000..119b880 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqSubstation.java @@ -0,0 +1,45 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠靠 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_SUBSTATION") +public class PqSubstation { + /** + * 靠靠? + */ + @TableId(value = "SUB_INDEX", type = IdType.INPUT) + private Integer subIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "\"NAME\"") + private String name; + + @TableField(value = "\"SCALE\"") + private String scale; +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsDeptsline.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsDeptsline.java new file mode 100644 index 0000000..24795d7 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsDeptsline.java @@ -0,0 +1,30 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@TableName(value = "PQS_DEPTSLINE") +public class PqsDeptsline { + /** + * 部门表Guid + */ + @TableField(value = "DEPTS_INDEX") + private String deptsIndex; + + @TableField(value = "LINE_INDEX") + private Integer lineIndex; + + @TableField(value = "SYSTYPE") + private String systype; +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsStationMap.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsStationMap.java new file mode 100644 index 0000000..81a0fd5 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/pojo/po/PqsStationMap.java @@ -0,0 +1,57 @@ +package com.njcn.product.terminal.device.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/11 + */ +@TableName(value="PQS_MAP") +@Data +public class PqsStationMap { + + + @TableId(value = "MAP_INDEX") + private String mapIndex; + + + @TableField(value = "SUB_INDEX") + private Long subIndex; + + + @TableField(value = "GD_INDEX") + private Long gdIndex; + + //经度 + + @TableField(value = "LONGITUDE") + private Float longItude; + + //纬度 + + @TableField(value = "LATITUDE") + private Float latItude; + + //数据状态 + + @TableField(value = "STATE") + private Long state; + + //用户ID + + @TableField(value = "USER_INDEX") + private String userIndex; + + //更新时间 + + @TableField(value = "UPDATETIME") + private Date updateTime; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/LedgerTreeService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/LedgerTreeService.java new file mode 100644 index 0000000..b360b48 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/LedgerTreeService.java @@ -0,0 +1,10 @@ +package com.njcn.product.terminal.device.service; + +import com.njcn.product.terminal.device.pojo.dto.OracleLedgerTreeDTO; + +import java.util.List; + +public interface LedgerTreeService { + + List getTree(); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqDeviceService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqDeviceService.java new file mode 100644 index 0000000..48011df --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqDeviceService.java @@ -0,0 +1,27 @@ +package com.njcn.product.terminal.device.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.terminal.device.pojo.dto.DeviceDTO; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.device.pojo.dto.DeviceDeptDTO; +import com.njcn.product.terminal.device.pojo.po.PqDevice; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDeviceService extends IService{ + + List queryListByIds(List lineIds); + + Page selectDeviceDTOPage(Page pqsEventdetailPage, String searchValue, List devIndexs); + + List selectDeviceDept(); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqLineService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqLineService.java new file mode 100644 index 0000000..11a49be --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqLineService.java @@ -0,0 +1,25 @@ +package com.njcn.product.terminal.device.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.device.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.terminal.device.pojo.po.PqLine; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqLineService extends IService{ + + + List getBaseLineInfo(List ids); + + List getBaseLedger(@Param("ids") List ids, @Param("searchValue") String searchValue); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqSubstationService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqSubstationService.java new file mode 100644 index 0000000..0722b88 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqSubstationService.java @@ -0,0 +1,21 @@ +package com.njcn.product.terminal.device.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.device.pojo.dto.SubstationDTO; +import com.njcn.product.terminal.device.pojo.po.PqSubstation; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqSubstationService extends IService{ + + List queryListByIds(List lineIds); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqsDeptslineService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqsDeptslineService.java new file mode 100644 index 0000000..8ca0593 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/PqsDeptslineService.java @@ -0,0 +1,17 @@ +package com.njcn.product.terminal.device.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.device.pojo.po.PqsDeptsline; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptslineService extends IService{ + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/LedgerTreeServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/LedgerTreeServiceImpl.java new file mode 100644 index 0000000..f5fe5d4 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/LedgerTreeServiceImpl.java @@ -0,0 +1,85 @@ +package com.njcn.product.terminal.device.service.impl; + + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.njcn.product.terminal.device.mapper.PqDeviceMapper; +import com.njcn.product.terminal.device.mapper.PqGdCompanyMapper; +import com.njcn.product.terminal.device.mapper.PqLineMapper; +import com.njcn.product.terminal.device.mapper.PqSubstationMapper; +import com.njcn.product.terminal.device.pojo.dto.OracleLedgerTreeDTO; +import com.njcn.product.terminal.device.pojo.po.PqDevice; +import com.njcn.product.terminal.device.pojo.po.PqGdCompany; +import com.njcn.product.terminal.device.pojo.po.PqLine; +import com.njcn.product.terminal.device.pojo.po.PqSubstation; +import com.njcn.product.terminal.device.service.LedgerTreeService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @Author: cdf + * @CreateTime: 2025-08-28 + * @Description: + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class LedgerTreeServiceImpl implements LedgerTreeService { + + private final PqLineMapper pqLineMapper; + + private final PqGdCompanyMapper pqGdCompanyMapper; + + private final PqDeviceMapper pqDeviceMapper; + + private final PqSubstationMapper substationMapper; + + + @Override + public List getTree() { + List pqLineList = pqLineMapper.selectList(null); + List lineDtoList = pqLineList.stream().map(it->{ + OracleLedgerTreeDTO oracleLedgerTreeDTO = new OracleLedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getLineIndex()); + oracleLedgerTreeDTO.setName(it.getSubvName()+"_"+it.getName()); + oracleLedgerTreeDTO.setPid(it.getDevIndex()); + oracleLedgerTreeDTO.setLevel(4); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + List deviceList = pqDeviceMapper.selectList(new LambdaQueryWrapper().eq(PqDevice::getDevflag,0).eq(PqDevice::getDevmodel,1)); + List devDtoList = deviceList.stream().map(it->{ + OracleLedgerTreeDTO oracleLedgerTreeDTO = new OracleLedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getDevIndex()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid(it.getSubIndex()); + oracleLedgerTreeDTO.setLevel(3); + oracleLedgerTreeDTO.setChildren(lineDtoList.stream().filter(line->Objects.equals(it.getDevIndex(),line.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + List substationList = substationMapper.selectList(null); + List stationDtoList = substationList.stream().map(it->{ + OracleLedgerTreeDTO oracleLedgerTreeDTO = new OracleLedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getSubIndex()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid(it.getGdIndex()); + oracleLedgerTreeDTO.setLevel(2); + oracleLedgerTreeDTO.setChildren(devDtoList.stream().filter(dev->Objects.equals(it.getSubIndex(),dev.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + List pqGdCompanyList = pqGdCompanyMapper.selectList(null); + List gdDtoList = pqGdCompanyList.stream().map(it->{ + OracleLedgerTreeDTO oracleLedgerTreeDTO = new OracleLedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getGdIndex().intValue()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid(0); + oracleLedgerTreeDTO.setLevel(1); + oracleLedgerTreeDTO.setChildren(stationDtoList.stream().filter(sub->Objects.equals(it.getGdIndex().intValue(),sub.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + return gdDtoList; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqDeviceServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqDeviceServiceImpl.java new file mode 100644 index 0000000..a7da9fa --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqDeviceServiceImpl.java @@ -0,0 +1,40 @@ +package com.njcn.product.terminal.device.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.terminal.device.mapper.PqDeviceMapper; +import com.njcn.product.terminal.device.pojo.dto.DeviceDTO; +import com.njcn.product.terminal.device.pojo.dto.DeviceDeptDTO; +import com.njcn.product.terminal.device.pojo.po.PqDevice; +import com.njcn.product.terminal.device.service.PqDeviceService; +import org.springframework.stereotype.Service; + +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqDeviceServiceImpl extends ServiceImpl implements PqDeviceService { + + @Override + public List queryListByIds(List lineIds) { + return this.baseMapper.queryListByIds(lineIds); + } + + @Override + public Page selectDeviceDTOPage(Page pqsEventdetailPage, String searchValue, List devIndexs) { + return this.baseMapper.selectDeviceDTOPage(pqsEventdetailPage,searchValue,devIndexs); + } + + @Override + public List selectDeviceDept() { + return this.baseMapper.selectDeviceDept(); + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqLineServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqLineServiceImpl.java new file mode 100644 index 0000000..0141bfb --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqLineServiceImpl.java @@ -0,0 +1,70 @@ +package com.njcn.product.terminal.device.service.impl; + +import cn.hutool.core.collection.CollUtil; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.terminal.device.mapper.PqLineMapper; +import com.njcn.product.terminal.device.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.terminal.device.pojo.po.PqLine; +import com.njcn.product.terminal.device.service.PqLineService; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.util.CollectionUtils; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqLineServiceImpl extends ServiceImpl implements PqLineService { + + + @Override + public List getBaseLineInfo(List ids){ + List ledgerBaseInfoDTOS = new ArrayList<>(); + + if(CollectionUtils.isEmpty(ids)){ + return ledgerBaseInfoDTOS; + } + if(ids.size()>1000){ + List> listIds = CollUtil.split(ids,1000); + for(List itemIds : listIds){ + List temp =this.baseMapper.getBaseLineInfo(itemIds); + ledgerBaseInfoDTOS.addAll(temp); + } + }else { + List temp =this.baseMapper.getBaseLineInfo(ids); + ledgerBaseInfoDTOS.addAll(temp); + } + return ledgerBaseInfoDTOS; + } + + @Override + public List getBaseLedger(List ids,String searchValue) { + List ledgerBaseInfoDTOS = new ArrayList<>(); + + if(CollectionUtils.isEmpty(ids)){ + return ledgerBaseInfoDTOS; + } + if(ids.size()>1000){ + List> listIds = CollUtil.split(ids,1000); + for(List itemIds : listIds){ + List temp =this.baseMapper.getBaseLedger(itemIds,searchValue); + ledgerBaseInfoDTOS.addAll(temp); + } + }else { + List temp =this.baseMapper.getBaseLedger(ids,searchValue); + ledgerBaseInfoDTOS.addAll(temp); + } + return ledgerBaseInfoDTOS; + }; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqSubstationServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqSubstationServiceImpl.java new file mode 100644 index 0000000..c87bb4d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqSubstationServiceImpl.java @@ -0,0 +1,26 @@ +package com.njcn.product.terminal.device.service.impl; + +import com.njcn.product.terminal.device.mapper.PqSubstationMapper; +import com.njcn.product.terminal.device.pojo.dto.SubstationDTO; +import com.njcn.product.terminal.device.pojo.po.PqSubstation; +import com.njcn.product.terminal.device.service.PqSubstationService; +import org.springframework.stereotype.Service; +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqSubstationServiceImpl extends ServiceImpl implements PqSubstationService { + + @Override + public List queryListByIds(List lineIds) { + return this.baseMapper.queryListByIds(lineIds); + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqsDeptslineServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqsDeptslineServiceImpl.java new file mode 100644 index 0000000..41a94b0 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/device/service/impl/PqsDeptslineServiceImpl.java @@ -0,0 +1,20 @@ +package com.njcn.product.terminal.device.service.impl; + +import com.njcn.product.terminal.device.mapper.PqsDeptslineMapper; +import com.njcn.product.terminal.device.pojo.po.PqsDeptsline; +import com.njcn.product.terminal.device.service.PqsDeptslineService; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsDeptslineServiceImpl extends ServiceImpl implements PqsDeptslineService { + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/event/controller/EventGateController.java b/cn-terminal/src/main/java/com/njcn/product/terminal/event/controller/EventGateController.java new file mode 100644 index 0000000..bd0bc1a --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/event/controller/EventGateController.java @@ -0,0 +1,45 @@ +package com.njcn.product.terminal.event.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.event.file.pojo.dto.WaveDataDTO; +import com.njcn.product.terminal.event.pojo.param.MonitorTerminalParam; +import com.njcn.product.terminal.event.service.EventGateService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @Author: cdf + * @CreateTime: 2025-09-03 + * @Description: + */ +@Api(tags = "暂降接收") +@RequestMapping("accept") +@RestController +@RequiredArgsConstructor +@Slf4j +public class EventGateController extends BaseController { + + private final EventGateService eventGateService; + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getTransientAnalyseWave") + @ApiOperation("暂态事件波形分析") + public HttpResult getTransientAnalyseWave(@RequestBody @Validated MonitorTerminalParam param) { + String methodDescribe = getMethodDescribe("getTransientAnalyseWave"); + WaveDataDTO wave = eventGateService.getTransientAnalyseWave(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, wave, methodDescribe); + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/event/pojo/param/MonitorTerminalParam.java b/cn-terminal/src/main/java/com/njcn/product/terminal/event/pojo/param/MonitorTerminalParam.java new file mode 100644 index 0000000..3afe8e1 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/event/pojo/param/MonitorTerminalParam.java @@ -0,0 +1,23 @@ +package com.njcn.product.terminal.event.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * <监测点波形入参> + * + * @author wr + * @createTime: 2023-03-23 + */ +@Data +public class MonitorTerminalParam { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id") + @NotBlank(message = "事件id不能为空") + private String id; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/EventGateService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/EventGateService.java new file mode 100644 index 0000000..da73be6 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/EventGateService.java @@ -0,0 +1,15 @@ +package com.njcn.product.terminal.event.service; + +import com.njcn.event.file.pojo.dto.WaveDataDTO; +import com.njcn.product.terminal.event.pojo.param.MonitorTerminalParam; + +public interface EventGateService { + + + /** + * 功能描述: 暂态事件波形分析 + * @param param + * @return + */ + WaveDataDTO getTransientAnalyseWave(MonitorTerminalParam param); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/impl/EventGateServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/impl/EventGateServiceImpl.java new file mode 100644 index 0000000..dbd9e88 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/event/service/impl/EventGateServiceImpl.java @@ -0,0 +1,80 @@ +package com.njcn.product.terminal.event.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.njcn.common.config.GeneralInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.event.file.component.WaveFileComponent; +import com.njcn.event.file.pojo.dto.WaveDataDTO; +import com.njcn.event.file.pojo.enums.WaveFileResponseEnum; + +import com.njcn.product.terminal.event.pojo.param.MonitorTerminalParam; +import com.njcn.product.terminal.event.service.EventGateService; +import com.njcn.product.terminal.mysqlTerminal.mapper.LedgerScaleMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.RmpEventDetailMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.io.InputStream; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @Author: cdf + * @CreateTime: 2025-06-30 + * @Description: + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class EventGateServiceImpl implements EventGateService { + + private final RmpEventDetailMapper rmpEventDetailMapper; + + private final WaveFileComponent waveFileComponent; + + private final LedgerScaleMapper ledgerScaleMapper; + + private final GeneralInfo generalInfo; + + @Override + public WaveDataDTO getTransientAnalyseWave(MonitorTerminalParam param) { + WaveDataDTO waveDataDTO; + //获取暂降事件 + RmpEventDetailPO eventDetail = rmpEventDetailMapper.selectById(param.getId()); + if(Objects.isNull(eventDetail)){ + throw new BusinessException(CommonResponseEnum.FAIL,"查询事件为空,请检查参数"); + } + String lineid = eventDetail.getLineId(); + LedgerBaseInfo pqLine = ledgerScaleMapper.getLedgerBaseInfo(Stream.of(lineid).collect(Collectors.toList())).get(0); + String waveName = eventDetail.getWavePath(); + String cfgPath, datPath; + if (StrUtil.isBlank(waveName)) { + throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); + } + cfgPath = generalInfo.getBusinessWavePath()+ File.separator+pqLine.getIp()+"/"+waveName+".CFG"; + datPath = generalInfo.getBusinessWavePath()+ File.separator+pqLine.getIp()+"/"+waveName+".DAT"; + log.info("本地磁盘波形文件路径----" + cfgPath); + InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath); + InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath); + if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) { + throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); + } + waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1); + + waveDataDTO = waveFileComponent.getValidData(waveDataDTO); + + waveDataDTO.setPtType(pqLine.getPtType()); + waveDataDTO.setPt(pqLine.getPt1()/ pqLine.getPt2()); + waveDataDTO.setCt(pqLine.getCt1()/ pqLine.getCt2()); + waveDataDTO.setMonitorName(pqLine.getLineName()); + return waveDataDTO; + + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LedgerTreeController.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LedgerTreeController.java new file mode 100644 index 0000000..f56b37f --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LedgerTreeController.java @@ -0,0 +1,72 @@ +package com.njcn.product.terminal.mysqlTerminal.controller; + +import com.baomidou.dynamic.datasource.annotation.DS; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.dto.SimpleDTO; +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.product.terminal.device.service.LedgerTreeService; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerTreeDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.StatisticsEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalTree; +import com.njcn.product.terminal.mysqlTerminal.service.LineService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-28 + * @Description: + */ +@RestController +@RequiredArgsConstructor +@Api(tags = "台账树") +@RequestMapping("/terminalTree") +public class LedgerTreeController extends BaseController { + + private final LineService lineService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("获取台账树") + @GetMapping(value = "/tree") + public HttpResult tree() { + String methodDescribe = getMethodDescribe("tree"); + List treeDTOList = lineService.getTree(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, treeDTOList, methodDescribe); + } + + + /** + * 获取终端台账设备树 + * @author cdf + * @date 2021/7/19 + */ + + @ApiOperation("获取5层终端树") + @OperateInfo(info = LogEnum.BUSINESS_MEDIUM) + @PostMapping("getTerminalTreeForFive") + @ApiImplicitParam(name = "deviceInfoParam", value = "台账查询参数", required = true) + public HttpResult> getTerminalTreeForFive(@RequestBody @Validated DeviceInfoParam deviceInfoParam){ + String methodDescribe = getMethodDescribe("getTerminalTreeForFive"); + SimpleDTO simpleDTO = new SimpleDTO(); + simpleDTO.setCode(StatisticsEnum.POWER_NETWORK.getCode()); + deviceInfoParam.setStatisticalType(simpleDTO); + List tree = lineService.getTerminalTreeForFive(deviceInfoParam); + + return com.njcn.common.utils.HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, tree, methodDescribe); + } + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LineController.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LineController.java new file mode 100644 index 0000000..31b5bbf --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/controller/LineController.java @@ -0,0 +1,46 @@ +package com.njcn.product.terminal.mysqlTerminal.controller; + + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.terminal.device.pojo.dto.OracleLedgerTreeDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerTreeDTO; +import com.njcn.product.terminal.mysqlTerminal.service.LineService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.*; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author denghuajun + * @date 2022/2/23 + * 监测点相关 + */ +@Slf4j +@Api(tags = "监测点管理") +@RestController +@RequestMapping("/line") +@RequiredArgsConstructor +public class LineController extends BaseController { + + private final LineService lineService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @ApiOperation("获取台账树") + @GetMapping(value = "/tree") + public HttpResult tree() { + String methodDescribe = getMethodDescribe("tree"); + List treeDTOList = lineService.getTree(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, treeDTOList, methodDescribe); + } + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeptLineMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeptLineMapper.java new file mode 100644 index 0000000..4fa8769 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeptLineMapper.java @@ -0,0 +1,28 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.DeptLine; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + + +/** + *

+ * Mapper 接口 + *

+ * + * @author denghuajun + * @since 2022-01-12 18:04 + */ +public interface DeptLineMapper extends BaseMapper { + + + List getLineIdByDeptIds(@Param("deptIds") List deptIds,@Param("runFlag")List runFlag); + + List lineDevGet(@Param("list")List devType, @Param("type")Integer type, @Param("lineRunFlag") Integer lineRunFlag); + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeviceMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeviceMapper.java new file mode 100644 index 0000000..410db6c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/DeviceMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Device; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface DeviceMapper extends BaseMapper { + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LedgerScaleMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LedgerScaleMapper.java new file mode 100644 index 0000000..2143bc0 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LedgerScaleMapper.java @@ -0,0 +1,19 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface LedgerScaleMapper { + + List getLedgerBaseInfo(@Param("lineIds") List lineIds); + + List getQueryLedger(@Param("lineIds") List lineIds,@Param("searchValue")String searchValue); + + + + List getBaseInfo(@Param("lineIds") List lineIds); + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineDetailMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineDetailMapper.java new file mode 100644 index 0000000..3fc1845 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineDetailMapper.java @@ -0,0 +1,86 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.terminal.mysqlTerminal.pojo.po.LineDetail; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface LineDetailMapper extends BaseMapper { + +/* + */ +/** + * 查询装置下监测点号号是否已被占用 + * @param devIndex 装置索引 + * @param num 线路号 + * @return 监测点信息 + *//* + + List getLineDetail(@Param("devIndex") String devIndex, @Param("num") List num); + + */ +/** + * 实际设备下的监测点&&稳态系统和两个系统的监测点&&投运终端下的监测点 + * 获取指定条件的监测点信息 + * @param list 监测点集合 + * @return 结果 + *//* + + List getSpecifyLineDetail(@Param("list") List list); + + + */ +/** + * 获取指定的监测点信息以及电压等级(需要其他字段可在基础上扩充) + * @param lineIds 监测点集合 + * @return 结果 + *//* + + List getLineDetailInfo(@Param("lineIds") List lineIds); + + + @Select ("select count(1) from pq_line a where a.Level=4 and SUBSTRING_INDEX(SUBSTRING_INDEX(a.Pids, ',', 4),',',-1)=#{subIndex}") + Integer getDeviceCountBySubstation(@Param("subIndex")String subIndex); + + @Select ("select count(1) from pq_line a where a.Level=6 and SUBSTRING_INDEX(SUBSTRING_INDEX(a.Pids, ',', 4),',',-1)=#{subIndex}") + Integer getLineCountBySubstation(@Param("subIndex")String subIndex); + + + LineDevGetDTO getMonitorDetail(@Param("monitorId")String monitorId); + + void updateLineRunFlag(@Param("id")String lineId, @Param("runFlag")Integer status); + + void updateLineRunFlagBatch(@Param("lineIds") List lineIds, @Param("runFlag") Integer status); + + */ +/** + * 根据监测点信息获取监测点详情(关联终端和母线) + * 获取指定条件的监测点信息 + * @param Ids 监测点集合 + * @return 结果 + *//* + + List getLineDetailByIds(@Param("ids") List Ids); + + */ +/** + * 判断该新能源场站信息是否绑定了测点ID + *//* + + Integer checkExistsLineByNewStationId(@Param("newStationId") String newStationId); +*/ + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineMapper.java new file mode 100644 index 0000000..70ccddf --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/LineMapper.java @@ -0,0 +1,114 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import cn.hutool.core.date.DateTime; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeviceType; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDataVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDetailVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalShowVO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface LineMapper extends BaseMapper { + + + Page getStationList(@Param("page")Page page,@Param("lineIds")List lineIds,@Param("runFlag")Integer runFlag,@Param("searchValue") String searchValue); + + Page getDevList(@Param("page")Page page,@Param("lineIds")List lineIds,@Param("runFlag")Integer runFlag,@Param("searchValue") String searchValue); + + Page getLineList(@Param("page")Page page,@Param("lineIds")List lineIds,@Param("comFlag")Integer comFlag,@Param("searchValue") String searchValue); + + + LineDevGetDTO getMonitorDetail(@Param("monitorId")String monitorId); + + /** + * 根据监测点id,获取所有监测点 + * + * @param ids 监测点id + * @param deviceInfoParam 监测点查询条件 + * @return 监测点数据 + */ + List getLineByCondition(@Param("ids") List ids, @Param("deviceInfoParam") DeviceInfoParam deviceInfoParam); + + /** + * 查询母线信息 + * + * @param voltageIds 母线索引 + * @param scale 电压等级 + */ + List getVoltageByCondition(@Param("voltageIds") List voltageIds, @Param("scale") List scale); + + /** + * 查询终端信息 + * + * @param devIds 终端索引 + * @param deviceType 终端筛选条件 + * @param manufacturer 终端厂家 + */ + List getDeviceByCondition(@Param("devIds") List devIds, @Param("deviceType") DeviceType deviceType, @Param("manufacturer") List manufacturer); + + + List getSubByCondition(@Param("subIds") List subIds, @Param("scale") List scale); + + + /** + * 查询变电站id + * + * @param subIds 变电站索引集合 + * @param scale 电压等级 + */ + List getSubIdByScale(@Param("subIds") List subIds, @Param("scale") String scale); + + + /** + * 查询监测点id + * + * @param lineIds 监测点索引集合 + * @param loadType 干扰源类型 + */ + List getLineIdByLoadType(@Param("lineIds") List lineIds, @Param("loadType") String loadType); + + + /** + * 查询终端id + * + * @param deviceIds 终端索引集合 + * @param manufacturer 制造厂家 + */ + List getDeviceIdByManufacturer(@Param("deviceIds") List deviceIds, @Param("manufacturer") String manufacturer); + + + List getDeviceIdByPowerFlag(@Param("lineIds")List lineIds, @Param("powerFlag")Integer manufacturer); + + + /** + * 获取监测点信息 + * + * @param id 监测点id + * @return 结果 + */ + LineDetailVO getLineSubGdDetail(@Param("id") String id); + + List getLineDetail(@Param("ids") List ids); + + List queryMonitorByUser(@Param("userIds")List userIds); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/OverlimitMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/OverlimitMapper.java new file mode 100644 index 0000000..a050dd3 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/OverlimitMapper.java @@ -0,0 +1,17 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Overlimit; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface OverlimitMapper extends BaseMapper { + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/RmpEventDetailMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/RmpEventDetailMapper.java new file mode 100644 index 0000000..32106f6 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/RmpEventDetailMapper.java @@ -0,0 +1,20 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 暂态事件明细 + * + * @author yzh + * @date 2022/10/12 + */ +@Mapper +public interface RmpEventDetailMapper extends BaseMapper { + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/TreeMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/TreeMapper.java new file mode 100644 index 0000000..bbd603b --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/TreeMapper.java @@ -0,0 +1,45 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalTree; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2022/2/28 + */ +public interface TreeMapper { + + /** + * 根据供电公司索引获取出省会的信息 + * @param gdIndexes 供电公司索引 + * @return 省会信息 + */ + List getProvinceList(@Param("gdIndex")List gdIndexes); + + /** + * 获取出供电公司的信息 + * @param gdIndexes 供电公司索引 + * @return 供电公司信息 + */ + List getGdList(@Param("gdIndex")List gdIndexes); + + /** + * 获取出变电站的信息 + * @param subIndexes 变电站索引 + * @return 变电站信息 + */ + List getSubList(@Param("subIndex")List subIndexes); + + /** + * 根据监测点索引获取监测点级五层树数据 + * @param lineIndexes 监测点索引 + * @return 监测点信息 + */ + List getLineList(@Param("lineIndex")List lineIndexes); + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/UserReportPOMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/UserReportPOMapper.java new file mode 100644 index 0000000..cae8451 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/UserReportPOMapper.java @@ -0,0 +1,20 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportPO; +import org.apache.ibatis.annotations.Param; + +/** + * + * Description: + * Date: 2024/4/25 10:07【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface UserReportPOMapper extends BaseMapper { + +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/VoltageMapper.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/VoltageMapper.java new file mode 100644 index 0000000..b6457d7 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/VoltageMapper.java @@ -0,0 +1,37 @@ +package com.njcn.product.terminal.mysqlTerminal.mapper; + + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.terminal.mysqlTerminal.pojo.po.LineDetail; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Voltage; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author cdf + * @since 2022-01-04 + */ +public interface VoltageMapper extends BaseMapper { + + /** + * 查询装置下母线号是否已被占用 + * @param devIndex 装置索引 + * @param num 线路号 + * @return 母线信息 + */ + List getVoltageByNum(@Param("devIndex") String devIndex, @Param("num") List num); + + + /** + * 通过母线id获取下层所有监测点详情 + * @author cdf + * @date 2023/5/24 + */ + List getLineDetailByBusBarId(@Param("busBarId")String busBarId); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptLineMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptLineMapper.xml new file mode 100644 index 0000000..baa9482 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptLineMapper.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptMapper.xml new file mode 100644 index 0000000..66a1124 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/DeptMapper.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LedgerScaleMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LedgerScaleMapper.xml new file mode 100644 index 0000000..e38b190 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LedgerScaleMapper.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LineMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LineMapper.xml new file mode 100644 index 0000000..3c4f6e0 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/LineMapper.xml @@ -0,0 +1,400 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/TreeMapper.xml b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/TreeMapper.xml new file mode 100644 index 0000000..8170d0c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/mapper/mapping/TreeMapper.xml @@ -0,0 +1,413 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/constant/ValidMessage.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/constant/ValidMessage.java new file mode 100644 index 0000000..cc4a9d5 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/constant/ValidMessage.java @@ -0,0 +1,77 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.constant; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年12月17日 10:16 + */ +public interface ValidMessage { + + String MISS_PREFIX="字段不能为空,请检查"; + + String ID_NOT_BLANK = "id不能为空,请检查id参数"; + + String ID_FORMAT_ERROR = "id格式错误,请检查id参数"; + + String DICT_TYPE_ID_NOT_BLANK = "typeId不能为空,请检查typeId参数"; + + String DICT_TYPE_ID_FORMAT_ERROR = "typeId格式错误,请检查typeId参数"; + + String NAME_NOT_BLANK = "名称不能为空,请检查name参数"; + + String NAME_FORMAT_ERROR = "名称格式错误,存在特殊符号或超过20字符,请检查name参数"; + + String INDUSTRY_NOT_BLANK = "行业不能为空,请检查industry参数"; + String INDUSTRY_FORMAT_ERROR = "行业格式错误,请检查industry参数"; + String ADDR_NOT_BLANK = "所属区域不能为空,请检查addr参数"; + + String CODE_NOT_BLANK = "编号不能为空,请检查code参数"; + + String CODE_FORMAT_ERROR = "编号格式错误,请检查code参数"; + + String SORT_NOT_NULL = "排序不能为空,请检查sort参数"; + + String SORT_FORMAT_ERROR = "排序格式错误,请检查sort参数"; + + String OPEN_LEVEL_NOT_NULL = "开启等级不能为空,请检查openLevel参数"; + + String OPEN_LEVEL_FORMAT_ERROR = "开启等级格式错误,请检查openLevel参数"; + + String OPEN_DESCRIBE_NOT_NULL = "开启描述不能为空,请检查openDescribe参数"; + + String OPEN_DESCRIBE_FORMAT_ERROR = "开启描述格式错误,请检查openDescribe参数"; + + String AREA_NOT_BLANK = "行政区域不能为空,请检查area参数"; + + String AREA_FORMAT_ERROR = "行政区域格式错误,请检查area参数"; + + String PID_NOT_BLANK = "父节点不能为空,请检查pid参数"; + + String PID_FORMAT_ERROR = "父节点格式错误,请检查pid参数"; + + String COLOR_NOT_BLANK = "主题色不能为空,请检查color参数"; + + String COLOR_FORMAT_ERROR = "主题色格式错误,请检查color参数"; + + String LOGO_NOT_BLANK = "iconUrl不能为空,请检查iconUrl参数"; + + String FAVICON_NOT_BLANK = "faviconUrl不能为空,请检查faviconUrl参数"; + + String REMARK_NOT_BLANK = "描述不能为空,请检查remark参数"; + + String REMARK_FORMAT_ERROR = "描述格式错误,请检查remark参数"; + + String PARAM_FORMAT_ERROR = "参数值非法"; + + String IP_FORMAT_ERROR = "IP格式非法"; + + String DEVICE_VERSION_NOT_BLANK = "装置版本json文件不能为空,请检查deviceVersionFile参数"; + + String SEARCH_DATA_ERROR = "搜索值过长,请检查搜索参数"; + String SPECIAL_REGEX = "搜索值包含特殊字符"; + + String NAME_SPECIAL_REGEX = "包含特殊字符"; + + String DATA_TOO_LONG = "参数过长,请检查参数"; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetBase.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetBase.java new file mode 100644 index 0000000..896ae4f --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetBase.java @@ -0,0 +1,41 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/5/10 + */ +@Data +public class DeptGetBase implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 单位索引 + */ + private String unitId; + + /** + * 单位名称 + */ + private String unitName; + + /** + * 部门层级 1.全国 2.省级 3.市级 4.县级 (具体根据单位层级调整) + * @author cdf + * @date 2023/6/26 + */ + private Integer deptLevel; + + /** + * 所有子级单位索引 + */ + private List unitChildrenList; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetChildrenMoreDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetChildrenMoreDTO.java new file mode 100644 index 0000000..3d0180b --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeptGetChildrenMoreDTO.java @@ -0,0 +1,24 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2023/4/24 + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class DeptGetChildrenMoreDTO extends DeptGetBase { + + @ApiModelProperty(name = "lineBaseList",value = "主网监测点信息") + private List lineBaseList; + + @ApiModelProperty(name = "pwMonitorIds",value = "配网监测点信息") + private List pwMonitorIds; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeviceType.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeviceType.java new file mode 100644 index 0000000..00e0b1e --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/DeviceType.java @@ -0,0 +1,42 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.List; + + +/** + * 设备状态类 + * @author hongawen + * @version 1.0.0 + * @date 2022年02月11日 14:54 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DeviceType implements Serializable { + + /** + * 终端模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + private List devModel; + + /** + * 终端状态(0:投运;1:热备用;2:停运) + */ + private List runFlag; + + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + private List dataType ; + + /** + * 通讯状态(0:中断;1:正常) + */ + private List comFlag ; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/GeneralDeviceDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/GeneralDeviceDTO.java new file mode 100644 index 0000000..a2f735a --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/GeneralDeviceDTO.java @@ -0,0 +1,67 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年09月07日 10:48 + * name对应统计名称:如 区域:南京市、苏州市;电压等级:10kV、220kV... + * index对应统计索引:如 区域:南京市索引、苏州市索引;电压等级:10kV索引、220kV索引... + * gdIndexes:供电公司索引集合 + * subIndexes:变电站索引集合 + * deviceIndexes:终端索引集合 + * voltageIndexes:母线索引集合 + * lineIndexes:监测点索引集合 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class GeneralDeviceDTO implements Serializable { + + /** + * name对应统计名称:如 区域:南京市、苏州市;电压等级:10kV、220kV... + */ + @ApiModelProperty(name = "name", value = "名称") + private String name; + + /** + * index对应统计索引:如 区域:南京市索引、苏州市索引;电压等级:10kV索引、220kV索引... + */ + private String index; + + /** + * gdIndexes:供电公司索引集合 + */ + private List gdIndexes = new ArrayList<>(); + + /** + * subIndexes:变电站索引集合 + */ + private List subIndexes = new ArrayList<>(); + + /** + * deviceIndexes:终端索引集合 + */ + private List deviceIndexes = new ArrayList<>(); + + /** + * voltageIndexes:母线索引集合 + */ + private List voltageIndexes = new ArrayList<>(); + + /** + * lineIndexes:监测点索引集合 + */ + private List lineIndexes = new ArrayList<>(); + @ApiModelProperty(name = "tail", value = "总数") + private Integer tail; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerBaseInfo.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerBaseInfo.java new file mode 100644 index 0000000..9826715 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerBaseInfo.java @@ -0,0 +1,75 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDate; + +/** + * @Author: cdf + * @CreateTime: 2025-09-01 + * @Description: + */ +@Data +public class LedgerBaseInfo implements Serializable { + + private static final long serialVersionUID = 1L; + + private String lineId; + + private String lineName; + + private Integer num; + + private String voltageLevel; + + private String objName; + + private String userNo; + + private Double ct1; + + private Double ct2; + + private Double pt1; + + private Double pt2; + + private Integer ptType; + + private Integer timeInterval; + + private String busBarId; + + private String busBarName; + + /** + * 0:中断;1:正常 + */ + private Integer comFlag; + + /** + * 0:投运;1:热备用;2:停运 + */ + private Integer runFlag; + + private String devId; + + private String devName; + + private String ip; + + private String manufacturer; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") + private LocalDate loginTime; + + private String stationId; + + private String stationName; + + private String gdId; + + private String gdName; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerTreeDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerTreeDTO.java new file mode 100644 index 0000000..d959070 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LedgerTreeDTO.java @@ -0,0 +1,27 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import com.njcn.product.terminal.device.pojo.dto.OracleLedgerTreeDTO; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-29 + * @Description: + */ +@Data +public class LedgerTreeDTO { + + + private String name; + + private String id; + + private String pid; + + private Integer level; + + private List children = new ArrayList<>(); +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineDevGetDTO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineDevGetDTO.java new file mode 100644 index 0000000..8404e31 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineDevGetDTO.java @@ -0,0 +1,123 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; + +/** + * pqs + * + * @author cdf + * @date 2023/5/10 + */ +@Data +public class LineDevGetDTO { + /** + * 部门索引 + */ + private String unitId; + + private String unitName; + + /** + * 监测点索引 + */ + private String pointId; + + private String pointName; + + /** + * 装置监测点索引集合 + */ + private List monitorIds; + + /** + * 监测点电压等级 + */ + private String voltageLevel; + + /** + * 监测点统计间隔 + */ + private Integer interval; + + /** + * 装置索引 + */ + private String devId; + + /** + * 0.主网 1.配网 + */ + private Integer type; + + /** + * 1.I类监测点 2.II类监测点 3.III类监测点 + */ + private Integer lineType; + + /** + * pq返回干扰源类型 pms主网返回监测对象类型,配网返回监测点类别 + */ + private String lineTag; + + /** + * 监测点对象类型 + */ + private String objType; + + /** + * 监测点对象 + */ + private String objId; + + /** + * 装置通讯状态 + */ + private Integer comFlag; + + /** + * 装置数据最新更新时间 + */ + private LocalDateTime updateTime; + + /** + * 是否上送国网是否是上送国网监测点,0-否 1-是 + */ + private Integer isUpToGrid; + + /** + * 0.未上送 1.已上送 2.取消上送 3.待重新上送(用于典型负荷) + */ + private Integer isUploadHead; + + /** + * 0.未上送 1.已上送 2.取消上送 3.待重新上送(用于主网监测点) + */ + private Integer monitorUploadStatus; + + /** + * oracle监测点id + */ + private Integer oracleLineId; + + /** + * 接线方式 0.星型 1.星三角 2.三角 + */ + private String wiringMethod; + + /** + * 监测点统计间隔(解决MySQL关键字问题) + */ + private Integer timeInterval; + + + public void setTimeInterval(Integer timeInterval) { + if(Objects.nonNull(timeInterval)) { + this.interval = timeInterval; + this.timeInterval = timeInterval; + } + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineInfo.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineInfo.java new file mode 100644 index 0000000..92eb88c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/dto/LineInfo.java @@ -0,0 +1,30 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.dto; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-09-03 + * @Description: + */ +@Data +public class LineInfo { + + private String lineId; + + private String lineName; + + private String devId; + + private String ip; + + private Integer ct1; + + private Integer ct2; + + private Integer pt1; + + private Integer pt2; + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineBaseEnum.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineBaseEnum.java new file mode 100644 index 0000000..f7f443f --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineBaseEnum.java @@ -0,0 +1,63 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.enums; + +import lombok.Getter; + +import java.util.Arrays; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Getter +public enum LineBaseEnum { + + /** + * 系统拓扑各层级描述 + */ + PROJECT_LEVEL(0, "项目"), + PROVINCE_LEVEL(1, "省份"), + GD_LEVEL(2, "供电公司"), + SUB_LEVEL(3, "变电站"), + DEVICE_LEVEL(4, "终端"), + SUB_V_LEVEL(5, "母线"), + LINE_LEVEL(6, "监测点"), + USER_LEVEL(7,"用户"), + INVALID_LEVEL(-1, "非法拓扑等级"), + + + + /** + * 分布式光伏树层级 + */ + PV_UNIT_LEVEL(0,"单位"), + PV_SUB_LEVEL(1,"变电站"), + PV_SUB_AREA_LEVEL(2,"台区"), + + /** + * 电网标志 + */ + POWER_FLAG(0,"电网侧"), + POWER_FLAG_NOT(1,"非电网侧"), + + + + ; + + private final Integer code; + private final String message; + + LineBaseEnum(Integer code, String message) { + this.code = code; + this.message = message; + } + + public static LineBaseEnum getLineBaseEnumByCode(Integer code) { + return Arrays.stream(LineBaseEnum.values()) + .filter(lineBaseEnum -> lineBaseEnum.getCode().equals(code)) + .findAny() + .orElse(INVALID_LEVEL); + } + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineFlagEnum.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineFlagEnum.java new file mode 100644 index 0000000..5bf0f5c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/LineFlagEnum.java @@ -0,0 +1,35 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.enums; + +import lombok.Getter; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月23日 15:24 + */ +@Getter +public enum LineFlagEnum { + + /** + * 区分监测点的类型标志 + */ + //非网公司 + LINE_MONITOR_NOT_NET_COMPANY(0), + //网公司 + LINE_MONITOR_NET_COMPANY(1), + //所有公司 + LINE_MONITOR_ALL(2), + //电网侧 + LINE_POWER_GRID(0), + //非电网侧 + LINE_POWER(1), + //所有 + LINE_POWER_ALL(2); + + private final int flag; + + LineFlagEnum(int flag) { + this.flag = flag; + } + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/PowerFlagEnum.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/PowerFlagEnum.java new file mode 100644 index 0000000..89ec135 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/PowerFlagEnum.java @@ -0,0 +1,52 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.enums; + +import lombok.Getter; + +import java.util.Arrays; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Getter +public enum PowerFlagEnum { + + /** + * 系统拓扑各层级描述 + */ + GRID_SIDE(0, "电网侧"), + NO_GRID_SIDE(1, "非电网侧"), + NEW_ENERGY(2, "电网侧(新能源)"), + NO_NEW_ENERGY(3, "非电网侧(新能源)"), + SEND_NETWORK(4, "上送国网"), + PCC(5, "PCC"), + + + VIRTUAL_DEVICE(0,"虚拟终端"), + REAL_DEVICE(1,"实际终端"), + OFFLINE_DEICE(2,"离线终端") + + + + + + ; + + private final Integer code; + private final String message; + + PowerFlagEnum(Integer code, String message) { + this.code = code; + this.message = message; + } + + public static PowerFlagEnum getPowerFlagEnumByCode(Integer code) { + return Arrays.stream(PowerFlagEnum.values()) + .filter(x -> x.getCode().equals(code)) + .findAny() + .orElse(GRID_SIDE); + } + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/RunFlagEnum.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/RunFlagEnum.java new file mode 100644 index 0000000..1a2dbd8 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/RunFlagEnum.java @@ -0,0 +1,34 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.enums; + +import lombok.Getter; + +import java.util.Arrays; + +@Getter +public enum RunFlagEnum { + + /** + * 运行状态枚举 + */ + RUNNING(0, "运行"), + OVERHAUL(1, "检修"), + OFF_LINE(2, "停运"), + DEBUG(3, "调试"), + QUIT(4, "退运"); + + private final Integer status; + private final String remark; + + RunFlagEnum(Integer status, String remark) { + this.status = status; + this.remark = remark; + } + + public static String getRunFlagRemarkByStatus(Integer status) { + RunFlagEnum runFlagEnum = Arrays.stream(RunFlagEnum.values()) + .filter(runFlagEnum1 -> runFlagEnum1.getStatus().equals(status)) + .findAny() + .orElse(RUNNING); + return runFlagEnum.getRemark(); + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/StatisticsEnum.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/StatisticsEnum.java new file mode 100644 index 0000000..db24b2a --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/enums/StatisticsEnum.java @@ -0,0 +1,49 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.enums; + + +import lombok.Getter; + +import java.util.Arrays; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年03月18日 13:27 + */ +@Getter +public enum StatisticsEnum { + + /** + * 统计类型字典枚举 + */ + POWER_NETWORK("网络拓扑", "Power_Network"), + VOLTAGE_LEVEL("电压等级", "Voltage_Level"), + LOAD_TYPE("干扰源类型", "Load_Type"), + MANUFACTURER("终端厂家", "Manufacturer"), + POWER_FLAG("监测点性质", "Power_Flag"), + REPORT_TYPE("上报类型", "Report_Type"); + + private final String name; + + private final String code; + + StatisticsEnum(String name, String code) { + this.name = name; + this.code = code; + } + + + /** + * 没有匹配到,则默认为网络拓扑 + * @param code 统计类型code + * @return 统计枚举实例 + */ + public static StatisticsEnum getStatisticsEnumByCode(String code) { + return Arrays.stream(StatisticsEnum.values()) + .filter(statisticsEnum -> statisticsEnum.getCode().equalsIgnoreCase(code)) + .findAny() + .orElse(POWER_NETWORK); + } + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeptGetLineParam.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeptGetLineParam.java new file mode 100644 index 0000000..bf4b6ba --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeptGetLineParam.java @@ -0,0 +1,51 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.param; + + +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; + + +/** + * pqs + * + * @author cdf + * @date 2023/4/24 + */ +@Data +public class DeptGetLineParam { + + @NotBlank(message = "部门id不可为空") + @ApiModelProperty(name = "deptId",value = "部门id") + private String deptId; + + @ApiModelProperty(name = "serverName",value = "系统类型 0.event-boot 1.harmonic-boot") + private String serverName; + + @ApiModelProperty(name = "systemType",value = "0.只返回主网的监测点信息; 1.只返回配网的监测点信息; null、2.返回主网配网两种监测点信息") + private Integer systemType; + + @ApiModelProperty(name = "monitorStateAll",value = "true.只返回在线监测点信息 false.返回全部监测点信息") + private Boolean monitorStateRunning=true; + + @ApiModelProperty(name = "isUpToGrid",value = "0.非送国网 1.需要送国网的") + + private Integer isUpToGrid; + /** + * 0-电网侧 + * 1-非电网侧 + */ + @ApiModelProperty("电网侧标识") + @Range(min = 0, max = 2, message = "电网侧标识" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer powerFlag; + + /** + * 监测点运行状态(0:运行;1:检修;2:停运;3:调试;4:退运)pq使用 + */ + @ApiModelProperty("监测点运行状态") + @Range(min = 0, max = 2, message = "监测点运行状态" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer lineRunFlag; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeviceInfoParam.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeviceInfoParam.java new file mode 100644 index 0000000..196d5f1 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/DeviceInfoParam.java @@ -0,0 +1,218 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.common.pojo.dto.SimpleDTO; + +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.LineFlagEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.PowerFlagEnum; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月23日 19:04 + */ +@Data +@ApiModel +@NoArgsConstructor +public class DeviceInfoParam implements Serializable { + + /** + * 统计类型 + */ + @ApiModelProperty(name = "statisticalType", value = "统计类型", required = true) + private SimpleDTO statisticalType; + + @ApiModelProperty(name = "deptIndex", value = "部门索引", required = true) + @NotBlank(message = "部门索引不可为空") + private String deptIndex; + + @ApiModelProperty(name = "serverName", value = "服务名称") + private String serverName; + + + @ApiModelProperty(name = "scale", value = "电压等级") + private List scale; + + + @ApiModelProperty(name = "manufacturer", value = "终端厂家") + private List manufacturer; + + + @ApiModelProperty(name = "loadType", value = "干扰源类型") + private List loadType; + + /** + * xy添加 + * 默认true + * true statFlag = 1 + * false statFlag = 0 or 1 + */ + @ApiModelProperty(name = "statFlag", value = "人为干预是否参与统计") + private Boolean statFlag; + + /** + * 0-非网公司 + * 1-网公司 + * 2-全部数据 + */ + @ApiModelProperty("网公司标识") + @Range(min = 0, max = 2, message = "网公司标识" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer monitorFlag; + + /** + * 0-电网侧 + * 1-非电网侧 + */ + @ApiModelProperty("电网侧标识") + @Range(min = 0, max = 2, message = "电网侧标识" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer powerFlag; + + /** + * 0-极重要 + * 1-重要 + * 2-普通 + * 3-不重要 + */ + @ApiModelProperty("监测点等级") + private String lineGrade; + + /** + * 通讯状态(0:中断;1:正常) + */ + @ApiModelProperty("通讯状态") + @Range(min = 0, max = 2, message = "通讯状态" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer comFlagStatus; + + + /** + * 监测点运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + @ApiModelProperty("监测点运行状态") + @Range(min = 0, max = 2, message = "监测点运行状态" + ValidMessage.PARAM_FORMAT_ERROR) + private Integer lineRunFlag; + + /** + * 默认全部监测点 + * + * @param deptIndex 部门索引 + * @param serverName 服务名 + */ + public DeviceInfoParam(String deptIndex, String serverName) { + this.deptIndex = deptIndex; + this.serverName = serverName; + monitorFlag = LineFlagEnum.LINE_MONITOR_ALL.getFlag(); + powerFlag = LineFlagEnum.LINE_POWER_ALL.getFlag(); + } + + + /** + * 默认全部监测点 + * + * @param deptIndex 部门索引 + * @param serverName 服务名 + */ + public DeviceInfoParam(SimpleDTO statisticalType, String deptIndex, String serverName, List scale, List manufacturer, List loadType) { + this.statisticalType = statisticalType; + this.deptIndex = deptIndex; + this.serverName = serverName; + this.scale = scale; + this.manufacturer = manufacturer; + this.loadType = loadType; + monitorFlag = LineFlagEnum.LINE_MONITOR_ALL.getFlag(); + powerFlag = LineFlagEnum.LINE_POWER_ALL.getFlag(); + } + + /** + * 自定义上报方式、电网侧方式的统计 + */ + public DeviceInfoParam(SimpleDTO statisticalType, String deptIndex, String serverName, List scale, List manufacturer, List loadType, int monitorFlag, int powerFlag) { + this.statisticalType = statisticalType; + this.deptIndex = deptIndex; + this.serverName = serverName; + this.scale = scale; + this.manufacturer = manufacturer; + this.loadType = loadType; + this.monitorFlag = monitorFlag; + this.powerFlag = powerFlag; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class BusinessParam extends DeviceInfoParam { + + @ApiModelProperty("开始时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String searchEndTime; + + @ApiModelProperty("时间范围标志 0.查询展示天 1.查询展示月") + @Deprecated + private Integer timeFlag; + + @ApiModelProperty("统计类型 1.年 2.季 3.月 4.周 5.天") + private String reportFlag; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CompareBusinessParam extends BusinessParam { + + @ApiModelProperty("比较开始时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String periodBeginTime; + + @ApiModelProperty("比较结束时间") + @Pattern(regexp = PatternRegex.TIME_FORMAT, message = "时间格式错误") + private String periodEndTime; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CompareLimitParam extends BusinessParam { + + @ApiModelProperty("查询条数") + @NotNull(message = " 查询条数查询条数不能为空") + private Integer limit; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class GridDiagram extends BusinessParam { + + @ApiModelProperty("查询总数监测点") + private List coutList; + + @ApiModelProperty("查询告警监测点") + private List alarmList; + + @ApiModelProperty("是否是冀北电网一张图树 0:否 1:是") + private Integer type = 0; + } + + public Boolean isUserLedger() { + if (Objects.isNull(this.powerFlag) || !PowerFlagEnum.GRID_SIDE.getCode().equals(this.powerFlag)) { + return true; + } + return false; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/LargeScreenCountParam.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/LargeScreenCountParam.java new file mode 100644 index 0000000..8d7b10d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/LargeScreenCountParam.java @@ -0,0 +1,41 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.param; + +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-08-29 + * @Description: + */ +@Data +public class LargeScreenCountParam extends BaseParam { + + @ApiModelProperty(name="deptId",value="部门id") + private String deptId; + + @ApiModelProperty(name="lineId",value="监测点id") + private String lineId; + + @ApiModelProperty(name="runFlag",value="运行状态") + private Integer runFlag; + + @ApiModelProperty(name="runFlag",value="通讯状态") + private Integer comFlag; + + @ApiModelProperty(name="runFlag",value="暂降事件关联分析聚合id") + private String eventAssId; + + private String eventType; + + private Float eventValueMin; + + private Float eventValueMax; + + private Float eventDurationMin; + + private Float eventDurationMax; + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/UserReportParam.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/UserReportParam.java new file mode 100644 index 0000000..ce562aa --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/param/UserReportParam.java @@ -0,0 +1,215 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.param; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportProjectPO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportSensitivePO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportSubstationPO; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Pattern; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +/** + * Description: + * Date: 2024/4/25 10:07【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class UserReportParam { + + private String id; + + /** + * 填报人 + */ + @ApiModelProperty(value = "填报人") + private String reporter; + + /** + * 填报日期 + */ + @ApiModelProperty(value = "填报日期") + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") + private LocalDate reportDate; + + /** + * 填报部门 + */ + @ApiModelProperty(value = "填报部门") + private String orgId; + + /** + * 填报部门 + */ + @ApiModelProperty(value = "填报部门名称") + private String orgName; + + /** + * 工程预期投产日期 + */ + @ApiModelProperty(value = "工程预期投产日期") + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") + private LocalDate expectedProductionDate; + + /** + * 用户性质 + */ + @ApiModelProperty(value = "用户性质") + private Integer userType; + + /** + * 所属地市 + */ + @ApiModelProperty(value = "所属地市") + private String city; + + /** + * 归口管理部门 + */ + @ApiModelProperty(value = "归口管理部门") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String responsibleDepartment; + + /** + * 用户状态 + */ + @ApiModelProperty(value = "用户状态") + private Integer userStatus; + + /** + * 变电站 + */ + @ApiModelProperty(value = "变电站") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String substation; + + /** + * 变电站 + */ + @ApiModelProperty(value = "变电站id") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String stationId; + + /** + * 电压等级 + */ + @ApiModelProperty(value = "电压等级") + private String voltageLevel; + + /** + * 工程名称 + */ + @ApiModelProperty(value = "工程名称") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String projectName; + + /** + * 预测评估单位 + */ + @ApiModelProperty(value = "预测评估单位") + private String evaluationDept; + + @ApiModelProperty(value = "经度") + private BigDecimal longitude; + + @ApiModelProperty(value = "纬度") + private BigDecimal latitude; + + @ApiModelProperty(value = "额定容量") + private Double ratePower; + + /** + * 预测评估结论 + */ + @ApiModelProperty(value = "预测评估结论") + @Pattern(regexp = PatternRegex.DES400_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String evaluationConclusion; + + @ApiModelProperty("发起人自选审批人 Map") + private Map> startUserSelectAssignees; + + + @ApiModelProperty(value = "保存1,提交审批2") + private String saveOrCheckflag; + + @ApiModelProperty(value = "数据来源类型 0:正常审核流程 1:批量导入") + private Integer dataType; + + private UserReportProjectPO userReportProjectPO; + + private UserReportSensitivePO userReportSensitivePO; + + private UserReportSubstationPO userReportSubstationPO; + + + /** + * 流程实例的编号 + */ + + @ApiModelProperty(value = "流程实例的编号") + private String processInstanceId; + + @ApiModelProperty(value = "历史流程实例的编号") + private String historyInstanceId; + + /** + * 终端id + */ + @ApiModelProperty(value = "终端id") + private String devId; + + /** + * 监测点id + */ + @ApiModelProperty(value = "监测点id") + private String lineId; + + @Data + @EqualsAndHashCode(callSuper = true) + public static class UserReportUpdate extends UserReportParam { + + @ApiModelProperty("id") + private String id; + + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class UserReportQueryParam extends BaseParam { + + @ApiModelProperty(value = "所属区域") + private String city; + + @ApiModelProperty(value = "工程名称") + private String projectName; + + @ApiModelProperty(value = "填报部门") + private String orgId; + + @ApiModelProperty(value = "数据来源类型 0:正常审核流程 1:批量导入") + private Integer dataType; + + @ApiModelProperty(value = "审核状态") + private Integer status; + + } + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/DeptLine.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/DeptLine.java new file mode 100644 index 0000000..b56e3c9 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/DeptLine.java @@ -0,0 +1,31 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_dept_line") +public class DeptLine { + + private static final long serialVersionUID = 1L; + + /** + * 部门Id + */ + private String id; + + /** + * 监测点Id + */ + private String lineId; + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Device.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Device.java new file mode 100644 index 0000000..49b23f0 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Device.java @@ -0,0 +1,165 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_device") +public class Device implements Serializable{ + + private static final long serialVersionUID = 1L; + + /** + * 装置序号 + */ + @TableId + private String id; + + /** + * 装置模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + private Integer devModel; + + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + private Integer devDataType; + + /** + * 终端运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + private Integer runFlag; + + /** + * 通讯状态(0:中断;1:正常) + */ + private Integer comFlag; + + /** + * 设备制造商,字典表 + */ + private String manufacturer; + + /** + * 定检状态(0:未检 1:已检) + */ + private Integer checkFlag; + + /** + * 前置类型(MMS、CLD)字典表 + */ + private String frontType; + + /** + * 终端型号(570、580……)字典表 + */ + private String devType; + + /** + * 网络参数 + */ + private String ip; + + /** + * 召唤标志(0:周期触发;1:变为触发) + */ + private Integer callFlag; + + /** + * 端口 + */ + private Integer port; + + /** + * 装置识别码(3ds加密) + */ + private String series; + + /** + * 装置秘钥(3ds加密) + */ + private String devKey; + + /** + * 前置序号Id,前置表 + */ + private String nodeId; + + /** + * 投运时间 + */ + private LocalDate loginTime; + + /** + * 数据更新时间 + */ + private LocalDateTime updateTime; + + /** + * 本次定检时间,默认等于投运时间 + */ + private LocalDate thisTimeCheck; + + /** + * 下次定检时间,默认为投运时间后推3年,假如时间小于3个月则为待检 + */ + private LocalDate nextTimeCheck; + + /** + * 电度功能 0 关闭 1开启 + */ + private Integer electroplate; + + /** + * 对时功能 0 关闭, 1开启 + */ + private Integer onTime; + + /** + * 合同号 + */ + private String contract; + + /** + * 设备sim卡号 + */ + private String sim; + + + /** + * 装置系列 + */ + private String devSeries; + + + /** + * 监测装置安装位置 + */ + private String devLocation; + + + /** + * 监测厂家设备编号 + */ + private String devNo; + + + /** + * 告警功能 0:关闭 null、1:开启 + */ + private Integer isAlarm; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Line.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Line.java new file mode 100644 index 0000000..e1e927d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Line.java @@ -0,0 +1,66 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("pq_line") +public class Line extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 监测点Id + */ + private String id; + + /** + * 父节点(0为根节点) + */ + private String pid; + + /** + * 上层所有节点 + */ + private String pids; + + /** + * 名称 + */ + private String name; + + /** + * 等级:0-项目名称;1- 工程名称;2-单位;3-部门;4-终端;5-母线;6-监测点 + */ + private Integer level; + + /** + * 排序(默认为0,有特殊排序需要时候人为输入) + */ + private Integer sort; + + /** + * 备注 + */ + private String remark; + + /** + * 状态 0-删除;1-正常;默认正常 + */ + private Integer state; + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/LineDetail.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/LineDetail.java new file mode 100644 index 0000000..4f282e6 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/LineDetail.java @@ -0,0 +1,219 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_line_detail") +public class LineDetail { + + private static final long serialVersionUID = 1L; + + /** + * 监测点序号 + */ + private String id; + + + @TableField(exist = false) + private String monitorName; + + /** + * 线路号(在同一台设备中的监测点号) + */ + private Integer num; + + /** + * PT一次变比 + */ + private Float pt1; + + /** + * PT二次变比 + */ + private Float pt2; + + /** + * CT一次变比 + */ + private Float ct1; + + /** + * CT二次变比 + */ + private Float ct2; + + /** + * 设备容量 + */ + private Float devCapacity; + + /** + * 短路容量 + */ + private Float shortCapacity; + + /** + * 基准容量 + */ + private Float standardCapacity; + + /** + * 协议容量 + */ + private Float dealCapacity; + + /** + * 接线类型(0:星型接法;1:三角型接法;2:开口三角型接法) + */ + private Integer ptType; + + /** + * 测量间隔(1-10分钟) + */ + private Integer timeInterval; + + /** + * 干扰源类型,字典表 + */ + private String loadType; + + /** + * 行业类型,字典表 + */ + private String businessType; + + /** + * 网公司谐波监测平台标志(0-否;1-是),默认否 + */ + private Integer monitorFlag; + + /** + * 电网标志(0-电网侧;1-非电网侧) + */ + private Integer powerFlag; + + /** + * 国网谐波监测平台监测点号 + */ + private String monitorId; + + /** + * 监测点对象名称 + */ + @Deprecated + private String objName; + + /** + * 监测点对象id + */ + private String objId; + + /** + * 监测对象大类 + */ + private String bigObjType; + + /** + * 监测对象小类 + */ + private String smallObjType; + + /** + * 人为干预 0 不参与统计 1 参与统计 + */ + private Integer statFlag; + + /** + * 关联字典的终端等级 + */ + private String lineGrade; + + /** + * 备注 + */ + private String remark; + + + + /** + * 电网侧变电站 + */ + private String powerSubstationName; + /** + * 分类等级 + */ + private String calssificationGrade; + + + /** + * 上级电站 + */ + @Deprecated + private String superiorsSubstation; + + /** + * 挂接线路 + */ + @Deprecated + private String hangLine; + + /** + * 监测点拥有者 + */ + @Deprecated + private String owner; + + /** + * 拥有者职务 + */ + @Deprecated + private String ownerDuty; + + /** + * 拥有者联系方式 + */ + @Deprecated + private String ownerTel; + + /** + * 接线图 + */ + private String wiringDiagram; + /** + * 监测点接线相别(0,单相,1,三相,默认三相) + */ + private Integer ptPhaseType; + + /** + * 监测点实际安装位置 + */ + private String actualArea; + + /** + * 监测点运行状态(0:运行;1:检修;2:停运;3:调试;4:退运) + */ + private Integer runFlag; + + /** + * 新能源场站信息ID + */ + @Deprecated + private String newStationId; + + /** + * 通讯状态 + */ + @TableField(exist = false) + private Integer comFlag; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Overlimit.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Overlimit.java new file mode 100644 index 0000000..9dfcbed --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Overlimit.java @@ -0,0 +1,876 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_overlimit") +public class Overlimit implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 监测点序号 + */ + private String id; + + /** + * 频率限值 + */ + private Float freqDev; + + /** + * 电压波动 + */ + private Float voltageFluctuation; + + /** + * 电压上偏差限值 + */ + private Float voltageDev; + + /** + * 电压下偏差限值 + */ + private Float uvoltageDev; + + /** + * 三相电压不平衡度限值 + */ + private Float ubalance; + + /** + * 短时电压不平衡度限值 + */ + private Float shortUbalance; + + /** + * 闪变限值 + */ + private Float flicker; + + /** + * 电压总谐波畸变率限值 + */ + private Float uaberrance; + + /** + * 负序电流限值 + */ + private Float iNeg; + + /** + * 2次谐波电压限值 + */ + @TableField("uharm_2") + private Float uharm2; + + /** + * 3次谐波电压限值 + */ + @TableField("uharm_3") + private Float uharm3; + + /** + * 4次谐波电压限值 + */ + @TableField("uharm_4") + private Float uharm4; + + /** + * 5次谐波电压限值 + */ + @TableField("uharm_5") + private Float uharm5; + + /** + * 6次谐波电压限值 + */ + @TableField("uharm_6") + private Float uharm6; + + /** + * 7次谐波电压限值 + */ + @TableField("uharm_7") + private Float uharm7; + + /** + * 8次谐波电压限值 + */ + @TableField("uharm_8") + private Float uharm8; + + /** + * 9次谐波电压限值 + */ + @TableField("uharm_9") + private Float uharm9; + + /** + * 10次谐波电压限值 + */ + @TableField("uharm_10") + private Float uharm10; + + /** + * 11次谐波电压限值 + */ + @TableField("uharm_11") + private Float uharm11; + + /** + * 12次谐波电压限值 + */ + @TableField("uharm_12") + private Float uharm12; + + /** + * 13次谐波电压限值 + */ + @TableField("uharm_13") + private Float uharm13; + + /** + * 14次谐波电压限值 + */ + @TableField("uharm_14") + private Float uharm14; + + /** + * 15次谐波电压限值 + */ + @TableField("uharm_15") + private Float uharm15; + + /** + * 16次谐波电压限值 + */ + @TableField("uharm_16") + private Float uharm16; + + /** + * 17次谐波电压限值 + */ + @TableField("uharm_17") + private Float uharm17; + + /** + * 18次谐波电压限值 + */ + @TableField("uharm_18") + private Float uharm18; + + /** + * 19次谐波电压限值 + */ + @TableField("uharm_19") + private Float uharm19; + + /** + * 20次谐波电压限值 + */ + @TableField("uharm_20") + private Float uharm20; + + /** + * 21次谐波电压限值 + */ + @TableField("uharm_21") + private Float uharm21; + + /** + * 22次谐波电压限值 + */ + @TableField("uharm_22") + private Float uharm22; + + /** + * 23次谐波电压限值 + */ + @TableField("uharm_23") + private Float uharm23; + + /** + * 24次谐波电压限值 + */ + @TableField("uharm_24") + private Float uharm24; + + /** + * 25次谐波电压限值 + */ + @TableField("uharm_25") + private Float uharm25; + + /** + * 2次谐波电压限值 + */ + @TableField("uharm_26") + private Float uharm26; + + /** + * 3次谐波电压限值 + */ + @TableField("uharm_27") + private Float uharm27; + + /** + * 4次谐波电压限值 + */ + @TableField("uharm_28") + private Float uharm28; + + /** + * 5次谐波电压限值 + */ + @TableField("uharm_29") + private Float uharm29; + + /** + * 6次谐波电压限值 + */ + @TableField("uharm_30") + private Float uharm30; + + /** + * 7次谐波电压限值 + */ + @TableField("uharm_31") + private Float uharm31; + + /** + * 8次谐波电压限值 + */ + @TableField("uharm_32") + private Float uharm32; + + /** + * 9次谐波电压限值 + */ + @TableField("uharm_33") + private Float uharm33; + + /** + * 10次谐波电压限值 + */ + @TableField("uharm_34") + private Float uharm34; + + /** + * 11次谐波电压限值 + */ + @TableField("uharm_35") + private Float uharm35; + + /** + * 12次谐波电压限值 + */ + @TableField("uharm_36") + private Float uharm36; + + /** + * 13次谐波电压限值 + */ + @TableField("uharm_37") + private Float uharm37; + + /** + * 14次谐波电压限值 + */ + @TableField("uharm_38") + private Float uharm38; + + /** + * 15次谐波电压限值 + */ + @TableField("uharm_39") + private Float uharm39; + + /** + * 16次谐波电压限值 + */ + @TableField("uharm_40") + private Float uharm40; + + /** + * 17次谐波电压限值 + */ + @TableField("uharm_41") + private Float uharm41; + + /** + * 18次谐波电压限值 + */ + @TableField("uharm_42") + private Float uharm42; + + /** + * 19次谐波电压限值 + */ + @TableField("uharm_43") + private Float uharm43; + + /** + * 20次谐波电压限值 + */ + @TableField("uharm_44") + private Float uharm44; + + /** + * 21次谐波电压限值 + */ + @TableField("uharm_45") + private Float uharm45; + + /** + * 22次谐波电压限值 + */ + @TableField("uharm_46") + private Float uharm46; + + /** + * 23次谐波电压限值 + */ + @TableField("uharm_47") + private Float uharm47; + + /** + * 24次谐波电压限值 + */ + @TableField("uharm_48") + private Float uharm48; + + /** + * 25次谐波电压限值 + */ + @TableField("uharm_49") + private Float uharm49; + + /** + * 50次谐波电压限值 + */ + @TableField("uharm_50") + private Float uharm50; + + + + /** + * 2次谐波电流限值 + */ + @TableField("iharm_2") + private Float iharm2; + + /** + * 3次谐波电流限值 + */ + @TableField("iharm_3") + private Float iharm3; + + /** + * 4次谐波电流限值 + */ + @TableField("iharm_4") + private Float iharm4; + + /** + * 5次谐波电流限值 + */ + @TableField("iharm_5") + private Float iharm5; + + /** + * 6次谐波电流限值 + */ + @TableField("iharm_6") + private Float iharm6; + + /** + * 7次谐波电流限值 + */ + @TableField("iharm_7") + private Float iharm7; + + /** + * 8次谐波电流限值 + */ + @TableField("iharm_8") + private Float iharm8; + + /** + * 9次谐波电流限值 + */ + @TableField("iharm_9") + private Float iharm9; + + /** + * 10次谐波电流限值 + */ + @TableField("iharm_10") + private Float iharm10; + + /** + * 11次谐波电流限值 + */ + @TableField("iharm_11") + private Float iharm11; + + /** + * 12次谐波电流限值 + */ + @TableField("iharm_12") + private Float iharm12; + + /** + * 13次谐波电流限值 + */ + @TableField("iharm_13") + private Float iharm13; + + /** + * 14次谐波电流限值 + */ + @TableField("iharm_14") + private Float iharm14; + + /** + * 15次谐波电流限值 + */ + @TableField("iharm_15") + private Float iharm15; + + /** + * 16次谐波电流限值 + */ + @TableField("iharm_16") + private Float iharm16; + + /** + * 17次谐波电流限值 + */ + @TableField("iharm_17") + private Float iharm17; + + /** + * 18次谐波电流限值 + */ + @TableField("iharm_18") + private Float iharm18; + + /** + * 19次谐波电流限值 + */ + @TableField("iharm_19") + private Float iharm19; + + /** + * 20次谐波电流限值 + */ + @TableField("iharm_20") + private Float iharm20; + + /** + * 21次谐波电流限值 + */ + @TableField("iharm_21") + private Float iharm21; + + /** + * 22次谐波电流限值 + */ + @TableField("iharm_22") + private Float iharm22; + + /** + * 23次谐波电流限值 + */ + @TableField("iharm_23") + private Float iharm23; + + /** + * 24次谐波电流限值 + */ + @TableField("iharm_24") + private Float iharm24; + + /** + * 25次谐波电流限值 + */ + @TableField("iharm_25") + private Float iharm25; + + /** + * 2次谐波电压限值 + */ + @TableField("iharm_26") + private Float iharm26; + + /** + * 3次谐波电压限值 + */ + @TableField("iharm_27") + private Float iharm27; + + /** + * 4次谐波电压限值 + */ + @TableField("iharm_28") + private Float iharm28; + + /** + * 5次谐波电压限值 + */ + @TableField("iharm_29") + private Float iharm29; + + /** + * 6次谐波电压限值 + */ + @TableField("iharm_30") + private Float iharm30; + + /** + * 7次谐波电压限值 + */ + @TableField("iharm_31") + private Float iharm31; + + /** + * 8次谐波电压限值 + */ + @TableField("iharm_32") + private Float iharm32; + + /** + * 9次谐波电压限值 + */ + @TableField("iharm_33") + private Float iharm33; + + /** + * 10次谐波电压限值 + */ + @TableField("iharm_34") + private Float iharm34; + + /** + * 11次谐波电压限值 + */ + @TableField("iharm_35") + private Float iharm35; + + /** + * 12次谐波电压限值 + */ + @TableField("iharm_36") + private Float iharm36; + + /** + * 13次谐波电压限值 + */ + @TableField("iharm_37") + private Float iharm37; + + /** + * 14次谐波电压限值 + */ + @TableField("iharm_38") + private Float iharm38; + + /** + * 15次谐波电压限值 + */ + @TableField("iharm_39") + private Float iharm39; + + /** + * 16次谐波电压限值 + */ + @TableField("iharm_40") + private Float iharm40; + + /** + * 17次谐波电压限值 + */ + @TableField("iharm_41") + private Float iharm41; + + /** + * 18次谐波电压限值 + */ + @TableField("iharm_42") + private Float iharm42; + + /** + * 19次谐波电压限值 + */ + @TableField("iharm_43") + private Float iharm43; + + /** + * 20次谐波电压限值 + */ + @TableField("iharm_44") + private Float iharm44; + + /** + * 21次谐波电压限值 + */ + @TableField("iharm_45") + private Float iharm45; + + /** + * 22次谐波电压限值 + */ + @TableField("iharm_46") + private Float iharm46; + + /** + * 23次谐波电压限值 + */ + @TableField("iharm_47") + private Float iharm47; + + /** + * 24次谐波电压限值 + */ + @TableField("iharm_48") + private Float iharm48; + + /** + * 25次谐波电压限值 + */ + @TableField("iharm_49") + private Float iharm49; + + /** + * 50次谐波电压限值 + */ + @TableField("iharm_50") + private Float iharm50; + + + + /** + * 0.5次间谐波电压限值 + */ + @TableField("inuharm_1") + private Float inuharm1; + + /** + * 1.5次间谐波电压限值 + */ + @TableField("inuharm_2") + private Float inuharm2; + + /** + * 2.5次间谐波电压限值 + */ + @TableField("inuharm_3") + private Float inuharm3; + + /** + * 3.5次间谐波电压限值 + */ + @TableField("inuharm_4") + private Float inuharm4; + + /** + * 4.5次间谐波电压限值 + */ + @TableField("inuharm_5") + private Float inuharm5; + + /** + * 5.5次间谐波电压限值 + */ + @TableField("inuharm_6") + private Float inuharm6; + + /** + * 6.5次间谐波电压限值 + */ + @TableField("inuharm_7") + private Float inuharm7; + + /** + * 7.5次间谐波电压限值 + */ + @TableField("inuharm_8") + private Float inuharm8; + + /** + * 8.5次间谐波电压限值 + */ + @TableField("inuharm_9") + private Float inuharm9; + + /** + * 9.5次间谐波电压限值 + */ + @TableField("inuharm_10") + private Float inuharm10; + + /** + * 10.5次间谐波电压限值 + */ + @TableField("inuharm_11") + private Float inuharm11; + + /** + * 11.5次间谐波电压限值 + */ + @TableField("inuharm_12") + private Float inuharm12; + + /** + * 12.5次间谐波电压限值 + */ + @TableField("inuharm_13") + private Float inuharm13; + + /** + * 13.5次间谐波电压限值 + */ + @TableField("inuharm_14") + private Float inuharm14; + + /** + * 14.5次间谐波电压限值 + */ + @TableField("inuharm_15") + private Float inuharm15; + + /** + * 15.5次间谐波电压限值 + */ + @TableField("inuharm_16") + private Float inuharm16; + + public Overlimit(){} + + + public void buildIHarm(Float[] iHarmTem){ + this.iharm2= iHarmTem[0]; + this.iharm4= iHarmTem[2]; + this.iharm6= iHarmTem[4]; + this.iharm8= iHarmTem[6]; + this.iharm10= iHarmTem[8]; + this.iharm12= iHarmTem[10]; + this.iharm14= iHarmTem[12]; + this.iharm16= iHarmTem[14]; + this.iharm18= iHarmTem[16]; + this.iharm20= iHarmTem[18]; + this.iharm22= iHarmTem[20]; + this.iharm24= iHarmTem[22]; + this.iharm26= iHarmTem[24]; + this.iharm28= iHarmTem[26]; + this.iharm30= iHarmTem[28]; + this.iharm32= iHarmTem[30]; + this.iharm34= iHarmTem[32]; + this.iharm36= iHarmTem[34]; + this.iharm38= iHarmTem[36]; + this.iharm40= iHarmTem[38]; + this.iharm42= iHarmTem[40]; + this.iharm44= iHarmTem[42]; + this.iharm46= iHarmTem[44]; + this.iharm48= iHarmTem[46]; + this.iharm50= iHarmTem[48]; + + + + this.iharm3= iHarmTem[1]; + this.iharm5= iHarmTem[3]; + this.iharm7= iHarmTem[5]; + this.iharm9= iHarmTem[7]; + this.iharm11= iHarmTem[9]; + this.iharm13= iHarmTem[11]; + this.iharm15= iHarmTem[13]; + this.iharm17= iHarmTem[15]; + this.iharm19= iHarmTem[17]; + this.iharm21= iHarmTem[19]; + this.iharm23= iHarmTem[21]; + this.iharm25= iHarmTem[23]; + this.iharm27= iHarmTem[25]; + this.iharm29= iHarmTem[27]; + this.iharm31= iHarmTem[29]; + this.iharm33= iHarmTem[31]; + this.iharm35= iHarmTem[33]; + this.iharm37= iHarmTem[35]; + this.iharm39= iHarmTem[37]; + this.iharm41= iHarmTem[39]; + this.iharm43= iHarmTem[41]; + this.iharm45= iHarmTem[43]; + this.iharm47= iHarmTem[45]; + this.iharm49= iHarmTem[47]; + } + + public void buildUharm(Float resultEven,Float resultOdd){ + this.uharm2=resultEven; + this.uharm4=resultEven; + this.uharm6=resultEven; + this.uharm8=resultEven; + this.uharm10=resultEven; + this.uharm12=resultEven; + this.uharm14=resultEven; + this.uharm16=resultEven; + this.uharm18=resultEven; + this.uharm20=resultEven; + this.uharm22=resultEven; + this.uharm24=resultEven; + this.uharm26=resultEven; + this.uharm28=resultEven; + this.uharm30=resultEven; + this.uharm32=resultEven; + this.uharm34=resultEven; + this.uharm36=resultEven; + this.uharm38=resultEven; + this.uharm40=resultEven; + this.uharm42=resultEven; + this.uharm44=resultEven; + this.uharm46=resultEven; + this.uharm48=resultEven; + this.uharm50=resultEven; + + + this.uharm3=resultOdd; + this.uharm5=resultOdd; + this.uharm7=resultOdd; + this.uharm9=resultOdd; + this.uharm11=resultOdd; + this.uharm13=resultOdd; + this.uharm15=resultOdd; + this.uharm17=resultOdd; + this.uharm19=resultOdd; + this.uharm21=resultOdd; + this.uharm23=resultOdd; + this.uharm25=resultOdd; + this.uharm27=resultOdd; + this.uharm29=resultOdd; + this.uharm31=resultOdd; + this.uharm33=resultOdd; + this.uharm35=resultOdd; + this.uharm37=resultOdd; + this.uharm39=resultOdd; + this.uharm41=resultOdd; + this.uharm43=resultOdd; + this.uharm45=resultOdd; + this.uharm47=resultOdd; + this.uharm49=resultOdd; + } + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsDeviceUnit.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsDeviceUnit.java new file mode 100644 index 0000000..2c6b9d8 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsDeviceUnit.java @@ -0,0 +1,120 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @Description: 数据单位管理表 + * @Author: wr + * @Date: 2023/8/21 9:56 + */ +@Data +@TableName("pqs_device_unit") +public class PqsDeviceUnit { + + private static final long serialVersionUID = 1L; + + @TableId(value = "DEV_INDEX") + @ApiModelProperty(value = "终端编号") + private String devIndex; + + @TableField("UNIT_FREQUENCY") + @ApiModelProperty(value = "频率") + private String unitFrequency = "Hz"; + + @TableField("UNIT_FREQUENCY_DEV") + @ApiModelProperty(value = "频率偏差") + private String unitFrequencyDev = "Hz"; + + @TableField("PHASE_VOLTAGE") + @ApiModelProperty(value = "相电压有效值") + private String phaseVoltage = "kV"; + + @TableField("LINE_VOLTAGE") + @ApiModelProperty(value = "线电压有效值") + private String lineVoltage = "kV"; + + @TableField("VOLTAGE_DEV") + @ApiModelProperty(value = "电压上偏差") + private String voltageDev = "%"; + + @TableField("UVOLTAGE_DEV") + @ApiModelProperty(value = "电压下偏差") + private String uvoltageDev = "%"; + + @TableField("I_EFFECTIVE") + @ApiModelProperty(value = "电流有效值") + private String ieffective = "A"; + + @TableField("SINGLE_P") + @ApiModelProperty(value = "单相有功功率") + private String singleP = "kW"; + + @TableField("SINGLE_VIEW_P") + @ApiModelProperty(value = "单相视在功率") + private String singleViewP = "kVA"; + + @TableField("SINGLE_NO_P") + @ApiModelProperty(value = "单相无功功率") + private String singleNoP = "kVar"; + + @TableField("TOTAL_ACTIVE_P") + @ApiModelProperty(value = "总有功功率") + private String totalActiveP = "kW"; + + @TableField("TOTAL_VIEW_P") + @ApiModelProperty(value = "总视在功率") + private String totalViewP = "kVA"; + + @TableField("TOTAL_NO_P") + @ApiModelProperty(value = "总无功功率") + private String totalNoP = "kVar"; + + @TableField("V_FUND_EFFECTIVE") + @ApiModelProperty(value = "相(线)电压基波有效值") + private String vfundEffective = "kV"; + + @TableField("I_FUND") + @ApiModelProperty(value = "基波电流") + private String ifund = "A"; + + @TableField("FUND_ACTIVE_P") + @ApiModelProperty(value = "基波有功功率") + private String fundActiveP = "kW"; + + @TableField("FUND_NO_P") + @ApiModelProperty(value = "基波无功功率") + private String fundNoP = "kVar"; + + @TableField("V_DISTORTION") + @ApiModelProperty(value = "电压总谐波畸变率") + private String vdistortion = "%"; + + @TableField("V_HARMONIC_RATE") + @ApiModelProperty(value = "2~50次谐波电压含有率") + private String vharmonicRate = "%"; + + @TableField("I_HARMONIC") + @ApiModelProperty(value = "2~50次谐波电流有效值") + private String iharmonic = "A"; + + @TableField("P_HARMONIC") + @ApiModelProperty(value = "2~50次谐波有功功率") + private String pharmonic = "kW"; + + @TableField("I_IHARMONIC") + @ApiModelProperty(value = "0.5~49.5次间谐波电流有效值") + private String iiharmonic = "A"; + + @TableField("POSITIVE_V") + @ApiModelProperty(value = "正序电压") + private String positiveV = "kV"; + + @TableField("NO_POSITIVE_V") + @ApiModelProperty(value = "零序负序电压") + private String noPositiveV = "V"; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgass.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgass.java new file mode 100644 index 0000000..eb71bc9 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgass.java @@ -0,0 +1,46 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; + +/** + *

+ * 变压器逻辑节点关系表 + *

+ * + * @author wr + * @since 2023-07-19 + */ +@Getter +@Setter +@TableName("pqs_tflgass") +public class PqsTflgass extends BaseEntity { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "变压器跟逻辑节点关系Guid") + @TableId(value = "Ass_Index") + private String assIndex; + + @ApiModelProperty(value = "变压器台账Guid") + private String tfIndex; + + /** + * 上级逻辑节点 + */ + @ApiModelProperty(value = "上级逻辑节点") + private String logicBefore; + + /** + * 下级逻辑节点 + */ + @ApiModelProperty(value = "下级逻辑节点") + private String logicNext; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgploy.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgploy.java new file mode 100644 index 0000000..9ebcd50 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgploy.java @@ -0,0 +1,55 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; + +/** + *

+ * PQS_TfLgPloy变压器策略表 + *

+ * + * @author wr + * @since 2023-07-19 + */ +@Getter +@Setter +@TableName("pqs_tflgploy") +public class PqsTflgploy extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 变压器策略Guid + */ + @ApiModelProperty(value = "变压器策略Guid") + @TableId(value = "tp_Index") + private String tpIndex; + + /** + * 变压器策略名称 + */ + @ApiModelProperty(value = "变压器策略名称") + private String tpName; + + /** + * 变压器策略描述 + */ + @ApiModelProperty(value = "变压器策略描述") + private String tfDescribe; + + /** + * 0删除 1.正常 + */ + @ApiModelProperty(value = "0删除 1.正常") + @TableLogic(value="1",delval="0") + private Integer status; + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgployass.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgployass.java new file mode 100644 index 0000000..97b8946 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/PqsTflgployass.java @@ -0,0 +1,37 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; + +/** + *

+ * PQS_TfLgPloyAss策略、变压器关系表 + *

+ * + * @author wr + * @since 2023-07-19 + */ +@Getter +@Setter +@TableName("pqs_tflgployass") +public class PqsTflgployass extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 策略Guid(外键PQS_TfLgPloy中TP_Index) + */ + @ApiModelProperty(value = "策略Guid(外键PQS_TfLgPloy中TP_Index)") + private String tpIndex; + + /** + * 报告基础项Guid(外键PQS_Transformer中Tf_Index) + */ + @ApiModelProperty(value = "报告基础项Guid(外键PQS_Transformer中Tf_Index)") + private String tfIndex; + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/RmpEventDetailPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/RmpEventDetailPO.java new file mode 100644 index 0000000..15e2e4f --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/RmpEventDetailPO.java @@ -0,0 +1,127 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 暂降明细实体类 + * + * @author yzh + * @since 2022-10-12 18:34:55 + */ +@Data +@TableName("r_mp_event_detail") +@ApiModel(value="RmpEventDetail对象") +public class RmpEventDetailPO implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "暂时事件ID") + @TableId(value = "event_id", type = IdType.ASSIGN_ID) + private String eventId; + + @ApiModelProperty(value = "监测点ID") + private String measurementPointId; + + @ApiModelProperty(value = "监测点ID(复制)") + @TableField("measurement_point_id") + private String lineId; + + @ApiModelProperty(value = "统计类型") + private String eventType; + + @ApiModelProperty(value = "暂降原因(Event_Reason)") + @TableField("advance_reason") + private String advanceReason; + + @ApiModelProperty(value = "暂降类型(Event_Type)") + @TableField("advance_type") + private String advanceType; + + @ApiModelProperty(value = "事件关联分析表Guid") + private String eventassIndex; + + @ApiModelProperty(value = "dq计算持续时间 ") + private Double dqTime; + + @ApiModelProperty(value = "特征值计算更新时间(外键PQS_Relevance的Time字段)") + private LocalDateTime dealTime; + + @ApiModelProperty(value = "默认事件个数为0") + private Integer num; + + @ApiModelProperty(value = "波形文件是否从装置招到本地(0:未招,1:已招)默认值为0") + private Integer fileFlag; + + @ApiModelProperty(value = "特征值计算标志(0,未处理;1,已处理; 2,已处理,无结果;3,计算失败)默认值为0") + private Integer dealFlag; + + @ApiModelProperty(value = "处理结果第一条事件发生时间(读comtra文件获取)") + private LocalDateTime firstTime; + + @ApiModelProperty(value = "处理结果第一条事件暂降类型(字典表PQS_Dicdata)") + private String firstType; + + @ApiModelProperty(value = "处理结果第一条事件发生时间毫秒(读comtra文件获取)") + private Double firstMs; + + @ApiModelProperty(value = "暂降能量") + private Double energy; + + @ApiModelProperty(value = "暂降严重度") + private Double severity; + + @ApiModelProperty(value = "暂降源与监测位置关系 Upper:上游;Lower :下游;Unknown :未知;为空则是未计算") + private String sagsource; + + @ApiModelProperty(value = "开始时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") + private LocalDateTime startTime; + + @ApiModelProperty(value = "格式化开始时间") + @TableField(exist = false) + private String formatTime; + + + @ApiModelProperty(value = "持续时间,单位秒") + private Double duration; + + @ApiModelProperty(value = "特征幅值") + private Double featureAmplitude; + + @ApiModelProperty(value = "相别") + private String phase; + + @ApiModelProperty(value = "事件描述") + private String eventDescribe; + + @ApiModelProperty(value = "波形路径") + private String wavePath; + + @ApiModelProperty(value = "暂降核实原因") + @TableField("verify_reason") + private String verifyReason; + + @ApiModelProperty(value = "暂降核实原因详情") + @TableField("verify_reason_detail") + private String verifyReasonDetail; + + private Double transientValue; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createTime; + + @ApiModelProperty(value = "用于计算数量") + @TableField(exist = false) + private Integer count; + +} + diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportNormalPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportNormalPO.java new file mode 100644 index 0000000..93acbb0 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportNormalPO.java @@ -0,0 +1,53 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +/** + *

+ * 干扰源用户常态化管理 + *

+ * + * @author hongawen + * @since 2024-05-17 + */ +@Getter +@Setter +@TableName("supervision_user_report_normal") +public class UserReportNormalPO extends BaseEntity { + + private static final long serialVersionUID = 1L; + + private String id; + + /** + * 关联干扰源用户表 + */ + private String userReportId; + + /** + * 类型0:方案审查 1:治理工程 + */ + private Integer type; + + /** + * 报告存放路径 + */ + private String reportUrl; + + private String processInstanceId; + + private String historyInstanceId; + + /** + * 1:审批中;2:审批通过;3:审批不通过;4:已取消 + */ + private Integer status; + + private Integer state; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportPO.java new file mode 100644 index 0000000..7514d15 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportPO.java @@ -0,0 +1,184 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** + * + * Description: + * Date: 2024/4/25 10:07【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "supervision_user_report") +public class UserReportPO extends BaseEntity { + /** + * id + */ + @TableId(value = "id", type = IdType.ASSIGN_UUID) + private String id; + + /** + * 填报人 + */ + @TableField(value = "reporter") + private String reporter; + + /** + * 填报日期 + */ + @TableField(value = "report_date") + private LocalDate reportDate; + + /** + * 填报部门 + */ + @TableField(value = "org_id") + private String orgId; + + /** + * 工程预期投产日期 + */ + @TableField(value = "expected_production_date") + private LocalDate expectedProductionDate; + + /** + * 用户性质 + */ + @TableField(value = "user_type") + private Integer userType; + + /** + * 所属地市 + */ + @TableField(value = "city") + private String city; + + /** + * 归口管理部门 + */ + @TableField(value = "responsible_department") + private String responsibleDepartment; + + /** + * 用户状态 + */ + @TableField(value = "user_status") + private Integer userStatus; + + /** + * 变电站 + */ + @TableField(value = "substation") + private String substation; + + /** + * 电压等级 + */ + @TableField(value = "voltage_level") + private String voltageLevel; + + /** + * 用户编号 + */ + @TableField(value = "user_no") + private String userNo; + + /** + * 工程名称 + */ + @TableField(value = "project_name") + private String projectName; + + /** + * 预测评估单位 + */ + @TableField(value = "evaluation_dept") + private String evaluationDept; + + /** + * 预测评估结论 + */ + @TableField(value = "evaluation_conclusion") + private String evaluationConclusion; + + /** + * 流程实例的编号 + */ + @TableField(value = "process_instance_id") + private String processInstanceId; + + + @TableField(value = "history_instance_id") + private String historyInstanceId; + + /** + * 数据来源类型 0.正常流程审核入库 1.批量导入 + */ + @TableField(value = "data_type") + private Integer dataType; + + /** + * 电站id + */ + private String stationId; + + /** + * 额定容量 + */ + private Double ratePower; + + /** + * 经度 + */ + private BigDecimal longitude; + + + /** + * 纬度 + */ + private BigDecimal latitude; + + /** + * 终端id + */ + @TableField(value = "dev_id") + private String devId; + + /** + * 监测点id + */ + @TableField(value = "line_id") + private String lineId; + + /** + * 审批状态:1:审批中;2:审批通过;3:审批不通过;4:已取消 + */ + @TableField(value = "status") + private Integer status; + + + /** + * 状态:0-删除 1-正常 + */ + @TableField(value = "State") + private Integer state; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportProjectPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportProjectPO.java new file mode 100644 index 0000000..fb23ed5 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportProjectPO.java @@ -0,0 +1,96 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.common.pojo.constant.PatternRegex; + +import com.njcn.db.mybatisplus.bo.BaseEntity; +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Pattern; + +/** + * + * Description: + * Date: 2024/4/25 10:08【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "supervision_user_report_project") +public class UserReportProjectPO extends BaseEntity { + /** + * 关联id + */ + @TableId(value = "id", type = IdType.INPUT) + private String id; + + /** + * 用户协议容量 + */ + @TableField(value = "agreement_capacity") + @Pattern(regexp = PatternRegex.COORDINATE, message = ValidMessage.PARAM_FORMAT_ERROR) + private Double agreementCapacity; + + /** + * 非线性设备类型 + */ + @TableField(value = "nonlinear_device_type") + private String nonlinearDeviceType; + + /** + * 是否需要治理 + */ + @TableField(value = "need_governance") + private Integer needGovernance; + + /** + * 是否开展背景测试 + */ + @TableField(value = "background_test_performed") + private Integer backgroundTestPerformed; + + /** + * 可研报告告地址 + */ + @TableField(value = "feasibility_report") + private String feasibilityReport; + + /** + * 项目初步设计说明书告地址 + */ + @TableField(value = "preliminary_design_description") + private String preliminaryDesignDescription; + + /** + * 预测评估报告告地址 + */ + @TableField(value = "prediction_evaluation_report") + private String predictionEvaluationReport; + + /** + * 预测评估评审意见报告地址 + */ + @TableField(value = "prediction_evaluation_review_opinions") + private String predictionEvaluationReviewOpinions; + + /** + * 其他附件告地址 + */ + @TableField(value = "additional_attachments") + private String additionalAttachments; + + /** + * 数据状态 + */ + @TableField(value = "state") + private Integer state; +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportRenewalPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportRenewalPO.java new file mode 100644 index 0000000..fb90071 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportRenewalPO.java @@ -0,0 +1,67 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; + +import com.njcn.db.mybatisplus.bo.BaseEntity; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.UserReportParam; +import lombok.Data; + +/** + *

+ * 用户档案信息表 + *

+ * + * @author wr + * @since 2024-06-26 + */ +@Data +@TableName("supervision_user_report_renewal") +public class UserReportRenewalPO extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * id + */ + private String id; + + /** + * 常态化用户跟新后信息 + */ + private String userReportMessage; + + /** + * 常态化用户跟新后信息 + */ + @TableField(exist = false) + private UserReportParam userReportMessageJson; + + /** + * 流程实例的编号 + */ + private String processInstanceId; + + /** + * 历史流程实列 + */ + private String historyInstanceId; + + /** + * 1:审批中;2:审批通过;3:审批不通过;4:已取消 + */ + private Integer status; + /** + * 状态:0-删除 1-正常 + */ + private Integer state; + + public void setUserReportMessage(String userReportMessage) { + if(StrUtil.isNotBlank(userReportMessage)){ + this.userReportMessageJson= JSONObject.parseObject(userReportMessage,UserReportParam.class); + } + this.userReportMessage = userReportMessage; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSensitivePO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSensitivePO.java new file mode 100644 index 0000000..2be3fed --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSensitivePO.java @@ -0,0 +1,191 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.common.pojo.constant.PatternRegex; + +import com.njcn.db.mybatisplus.bo.BaseEntity; +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Pattern; + +/** + * + * Description: + * Date: 2024/4/25 10:09【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "supervision_user_report_sensitive") +public class UserReportSensitivePO extends BaseEntity { + /** + * 关联id + */ + @TableId(value = "id", type = IdType.INPUT) + private String id; + + /** + * PCC点 + */ + @TableField(value = "pcc_point") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String pccPoint; + + /** + * 行业 + */ + @TableField(value = "industry") + private String industry; + + /** + * 敏感装置名称 + */ + @TableField(value = "device_name") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String deviceName; + + /** + * 供电电源数量 + */ + @TableField(value = "power_supply_count") + private Integer powerSupplyCount; + + /** + * 敏感电能质量指标 + */ + @TableField(value = "energy_quality_index") + private String energyQualityIndex; + + /** + * 评估类型 + */ + @TableField(value = "evaluation_type") + private String evaluationType; + + /** + * 是否开展抗扰度测试 + */ + @TableField(value = "anti_interference_test") + private String antiInterferenceTest; + + /** + * 预测评估审核单位 + */ + @TableField(value = "evaluation_chek_dept") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String evaluationChekDept; + + /** + * 是否需要治理 + */ + @TableField(value = "need_governance") + private Integer needGovernance; + + /** + * 是否开展背景测试 + */ + @TableField(value = "background_test_performed") + private Integer backgroundTestPerformed; + + /** + * 用户接入变电站主接线示意图地址 + */ + @TableField(value = "substation_main_wiring_diagram") + private String substationMainWiringDiagram; + + /** + * 主要敏感设备清单 + */ + @TableField(value = "sensitive_devices") + private String sensitiveDevices; + + /** + * 抗扰度测试报告 + */ + @TableField(value = "anti_interference_report") + private String antiInterferenceReport; + + /** + * 背景电能质量测试报告 + */ + @TableField(value = "power_quality_report") + private String powerQualityReport; + + /** + * 可研报告地址 + */ + @TableField(value = "feasibility_report") + private String feasibilityReport; + + /** + * 项目初步设计说明书地址 + */ + @TableField(value = "preliminary_design_description") + private String preliminaryDesignDescription; + + /** + * 预测评估报告地址 + */ + @TableField(value = "prediction_evaluation_report") + private String predictionEvaluationReport; + + /** + * 预测评估评审意见报告地址 + */ + @TableField(value = "prediction_evaluation_review_opinions") + private String predictionEvaluationReviewOpinions; + + /** + * 其他附件 + */ + @TableField(value = "additional_attachments") + private String additionalAttachments; + + /** + * 数据状态 + */ + @TableField(value = "state") + private Integer state; + + /** + * 供电电源 + */ + @TableField(value = "power_supply") + private String powerSupply; + + /** + * 接入电压等级 + */ + @TableField(value = "supply_voltage_level") + private String supplyVoltageLevel; + + /** + * 负荷级别 + */ + @TableField(value = "load_level") + private String loadLevel; + + + /** + * 供电电源情况(单电源、双电源、多电源) + */ + @TableField(value = "power_supply_info") + private String powerSupplyInfo; + + /** + * 运维单位 + */ + @TableField(value = "maintenance_unit") + private String maintenanceUnit; + + +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSubstationPO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSubstationPO.java new file mode 100644 index 0000000..1203911 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/UserReportSubstationPO.java @@ -0,0 +1,142 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import com.njcn.product.terminal.mysqlTerminal.pojo.constant.ValidMessage; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.Pattern; +import java.math.BigDecimal; + +/** + * + * Description: + * Date: 2024/4/25 10:09【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@TableName(value = "supervision_user_report_substation") +public class UserReportSubstationPO extends BaseEntity { + @TableId(value = "id", type = IdType.INPUT) + private String id; + + /** + * PCC点 + */ + @TableField(value = "pcc_point") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String pccPoint; + + /** + * 基准短路容量(MVA) + */ + @TableField(value = "base_short_circuit_capacity") + @Pattern(regexp = PatternRegex.COORDINATE, message = ValidMessage.PARAM_FORMAT_ERROR) + private BigDecimal baseShortCircuitCapacity; + + /** + * 系统最小短路容量(MVA) + */ + @TableField(value = "min_short_circuit_capacity") + @Pattern(regexp = PatternRegex.COORDINATE, message = ValidMessage.PARAM_FORMAT_ERROR) + private BigDecimal minShortCircuitCapacity; + + /** + * PCC供电设备容量(MVA) + */ + @TableField(value = "pcc_equipment_capacity") + @Pattern(regexp = PatternRegex.COORDINATE, message = ValidMessage.PARAM_FORMAT_ERROR) + private BigDecimal pccEquipmentCapacity; + + /** + * 用户用电协议容量(MVA) + */ + @TableField(value = "user_agreement_capacity") + @Pattern(regexp = PatternRegex.COORDINATE, message = ValidMessage.PARAM_FORMAT_ERROR) + private BigDecimal userAgreementCapacity; + + /** + * 评估类型 + */ + @TableField(value = "evaluation_type") + private String evaluationType; + + /** + * 非线性负荷类型 + */ + @TableField(value = "nonlinear_load_type") + private String nonlinearLoadType; + + /** + * 预测评估审核单位 + */ + @TableField(value = "evaluation_chek_dept") + @Pattern(regexp = PatternRegex.DES32_REGEX, message = ValidMessage.DATA_TOO_LONG) + private String evaluationChekDept; + + /** + * 是否需要治理 + */ + @TableField(value = "need_governance") + private Integer needGovernance; + + /** + * 是否开展背景测试 + */ + @TableField(value = "background_test_performed") + private Integer backgroundTestPerformed; + + /** + * 用户接入变电站主接线示意图地址 + */ + @TableField(value = "substation_main_wiring_diagram") + private String substationMainWiringDiagram; + + /** + * 可研报告地址 + */ + @TableField(value = "feasibility_report") + private String feasibilityReport; + + /** + * 项目初步设计说明书地址 + */ + @TableField(value = "preliminary_design_description") + private String preliminaryDesignDescription; + + /** + * 预测评估报告地址 + */ + @TableField(value = "prediction_evaluation_report") + private String predictionEvaluationReport; + + /** + * 预测评估评审意见报告地址 + */ + @TableField(value = "prediction_evaluation_review_opinions") + private String predictionEvaluationReviewOpinions; + + /** + * 其他附件 + */ + @TableField(value = "additional_attachments") + private String additionalAttachments; + + /** + * 数据状态 + */ + @TableField(value = "state") + private Integer state; + + +} \ No newline at end of file diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Voltage.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Voltage.java new file mode 100644 index 0000000..6af1041 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/po/Voltage.java @@ -0,0 +1,42 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + *

+ * + *

+ * + * @author cdf + * @since 2022-01-04 + */ +@Data +@TableName("pq_voltage") +public class Voltage { + + private static final long serialVersionUID = 1L; + + /** + * 母线序号 + */ + private String id; + + /** + * 母线号(在同一台设备中的电压通道号) + */ + private Integer num; + + /** + * 电压等级Id,字典表 + */ + private String scale; + + /** + * 母线模型(0:虚拟母线;1:实际母线)默认是实际母线 + */ + private Integer model; + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/AdvanceEventDetailVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/AdvanceEventDetailVO.java new file mode 100644 index 0000000..972af7d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/AdvanceEventDetailVO.java @@ -0,0 +1,116 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * pqs + * + * @author cdf + * @date 2023/7/20 + */ +@Data +public class AdvanceEventDetailVO { + + + @ApiModelProperty(value = "暂时事件ID") + private String eventId; + + @ApiModelProperty(value = "监测点ID") + private String measurementPointId; + + @ApiModelProperty(value = "监测点ID(复制)") + private String lineId; + + @ApiModelProperty(value = "统计类型") + private String eventType; + + @ApiModelProperty(value = "暂降原因(Event_Reason)") + private String advanceReason; + + @ApiModelProperty(value = "暂降类型(Event_Type)") + private String advanceType; + + @ApiModelProperty(value = "事件关联分析表Guid") + private String eventassIndex; + + @ApiModelProperty(value = "dq计算持续时间 ") + private Double dqTime; + + @ApiModelProperty(value = "特征值计算更新时间(外键PQS_Relevance的Time字段)") + @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss") + private LocalDateTime dealTime; + + @ApiModelProperty(value = "默认事件个数为0") + private Integer num; + + @ApiModelProperty(value = "波形文件是否从装置招到本地(0:未招,1:已招)默认值为0") + private Integer fileFlag; + + @ApiModelProperty(value = "特征值计算标志(0,未处理;1,已处理; 2,已处理,无结果;3,计算失败)默认值为0") + private Integer dealFlag; + + @ApiModelProperty(value = "处理结果第一条事件发生时间(读comtra文件获取)") + @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss") + private LocalDateTime firstTime; + + @ApiModelProperty(value = "处理结果第一条事件暂降类型(字典表PQS_Dicdata)") + private String firstType; + + @ApiModelProperty(value = "处理结果第一条事件发生时间毫秒(读comtra文件获取)") + private Integer firstMs; + + @ApiModelProperty(value = "暂降能量") + private Double energy; + + @ApiModelProperty(value = "暂降严重度") + private Double severity; + + @ApiModelProperty(value = "暂降源与监测位置关系 Upper:上游;Lower :下游;Unknown :未知;为空则是未计算") + private String sagsource; + + @ApiModelProperty(value = "开始时间") + @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss.SSS") + private LocalDateTime startTime; + + @ApiModelProperty(value = "持续时间,单位秒") + private Integer duration; + + @ApiModelProperty(value = "特征幅值") + private Double featureAmplitude; + + @ApiModelProperty(value = "相别") + private String phase; + + @ApiModelProperty(value = "事件描述") + private String eventDescribe; + + @ApiModelProperty(value = "波形路径") + private String wavePath; + + private Double transientValue; + + @ApiModelProperty(value = "供电公司名称") + private String gdName; + + @ApiModelProperty(value = "变电站名称") + private String subName; + + @ApiModelProperty(value = "监测点名称") + private String lineName; + + @ApiModelProperty(value = "母线节点id") + private String busBarId; + + @ApiModelProperty(value = "母线电压等级") + private String voltageId; + + @ApiModelProperty(value = "特征值是否计算") + private String featureAmplitudeFlag; + + @ApiModelProperty(value = "录波文件是否存在") + private String boFileFlag; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDataVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDataVO.java new file mode 100644 index 0000000..0a0e8e8 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDataVO.java @@ -0,0 +1,52 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import lombok.Data; + +/** + * @author denghuajun + * @date 2022/2/23 + * 保存line信息表 + */ +@Data +public class LineDataVO { + /** + * 监测点Id + */ + private String id; + + /** + * 父节点(0为根节点) + */ + private String pid; + + /** + * 上层所有节点 + */ + private String pids; + + /** + * 名称 + */ + private String name; + + /** + * 等级:0-项目名称;1- 工程名称;2-单位;3-部门;4-终端;5-母线;6-监测点 + */ + private Integer level; + + /** + * 排序(默认为0,有特殊排序需要时候人为输入) + */ + private Integer sort; + + /** + * 备注 + */ + private String remark; + + /** + * 状态 0-删除;1-正常;默认正常 + */ + private Integer state; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailDataVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailDataVO.java new file mode 100644 index 0000000..0391836 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailDataVO.java @@ -0,0 +1,135 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * @author denghuajun + * @date 2022/2/23 + * 监测点信息 + */ +@Data +@ApiModel +public class LineDetailDataVO { + + private String lineId; + + @ApiModelProperty(name = "id",value = "监测点序号") + private Integer id; + + @ApiModelProperty(name = "lineName",value = "监测点名称") + private String lineName; + + @ApiModelProperty(name = "areaName",value = "工程名称") + private String areaName; + + @ApiModelProperty(name = "gdName",value = "单位") + private String gdName; + + @ApiModelProperty(name = "bdName",value = "部门") + private String bdName; + + @ApiModelProperty(name = "scale",value = "电压等级") + private String scale; + + @ApiModelProperty(name = "manufacturer",value = "厂家") + private String manufacturer; + + @ApiModelProperty(name = "devId",value = "终端Id") + private String devId; + + @ApiModelProperty(name = "devName",value = "终端名称") + private String devName; + + @ApiModelProperty(name = "ip",value = "网络参数") + private String ip; + + @ApiModelProperty(name = "runFlag",value = "终端运行状态") + private String runFlag; + + @ApiModelProperty(name = "comFlag",value = "通讯状态") + private String comFlag; + + @ApiModelProperty(name = "loadType",value = "干扰源类型") + private String loadType; + + @ApiModelProperty(name = "businessType",value = "行业类型") + private String businessType; + + @ApiModelProperty(name = "objName",value = "监测点对象名称") + private String objName; + + @ApiModelProperty(name = "ptType",value = "接线方式") + private String ptType; + + @ApiModelProperty(name = "pt",value = "PT变比") + private String pt; + + @ApiModelProperty(name = "ct",value = "CT变比") + private String ct; + + @ApiModelProperty(name = "standardCapacity",value = "基准容量(MVA)") + private Float standardCapacity; + + @ApiModelProperty(name = "shortCapacity",value = "最小短路容量(MVA)") + private Float shortCapacity; + + @ApiModelProperty(name = "devCapacity",value = "供电设备容量(MVA)") + private Float devCapacity; + + @ApiModelProperty(name = "dealCapacity",value = "用户协议容量(MVA)") + private Float dealCapacity; + + @ApiModelProperty(name = "powerFlag",value = "电网标志(0-电网侧;1-非电网侧)") + private Integer powerFlag; + + /** + * 测量间隔(1-10分钟) + */ + @ApiModelProperty(name = "timeInterval",value = "测量间隔(1-10分钟)") + private Integer timeInterval; + + /** + * 监测点拥有者 + */ + @ApiModelProperty(name = "owner",value = "监测点拥有者") + private String owner; + + /** + * 拥有者职务 + */ + @ApiModelProperty(name = "ownerDuty",value = "拥有者职务") + private String ownerDuty; + + /** + * 拥有者联系方式 + */ + @ApiModelProperty(name = "ownerTel",value = "拥有者联系方式") + private String ownerTel; + + /** + * 接线图 + */ + @ApiModelProperty(name = "wiringDiagram",value = "接线图") + private String wiringDiagram; + @ApiModelProperty(name = "ptPhaseType",value = "监测点接线相别(0,单相,1,三相,默认三相)") + private Integer ptPhaseType; + + @ApiModelProperty(name = "投运日期") + private LocalDate loginTime; + + @ApiModelProperty(name = "最新数据时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updateTime; + + @ApiModelProperty(name = "监测对象信息ID") + private String objId; + + @ApiModelProperty(name = "对象类型大类") + private String bigObjType; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailVO.java new file mode 100644 index 0000000..42f5796 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/LineDetailVO.java @@ -0,0 +1,109 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * @author denghuajun + * @version 1.0.0 + * @date 2022年05月06日 15:38 + */ +@Data +public class LineDetailVO implements Serializable { + + @ApiModelProperty("供电公司名称") + private String gdName; + + @ApiModelProperty("变电站名称") + private String subName; + + @ApiModelProperty("终端名称") + private String devName; + + @ApiModelProperty("网络参数") + private String ip; + + @ApiModelProperty("监测点名称") + private String lineName; + + @ApiModelProperty("母线名称") + private String volName; + + /** + * (0:运行;1:检修;2:停运;3:调试;4:退运) + */ + @ApiModelProperty("监测点运行状态") + private Integer runFlag; + @Data + public static class Detail extends LineDetailVO implements Serializable{ + + @ApiModelProperty("区域id") + private String areaId; + + @ApiModelProperty("区域名称") + private String areaName; + + @ApiModelProperty("终端id") + private String devId; + + @ApiModelProperty("监测点Id") + private String lineId; + + @ApiModelProperty("测量间隔(1-10分钟)") + private Integer timeInterval; + + @ApiModelProperty("接线类型") + private Integer ptType; + + @ApiModelProperty("电压等级") + private String voltageLevel; + + @ApiModelProperty("数据更新时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timeID; + + @ApiModelProperty("终端等级") + private String lineGrade; + + @ApiModelProperty("通讯状态(0:中断;1:正常)") + private Integer comFlag; + + @ApiModelProperty("PT一次变比") + private Double PT1; + + @ApiModelProperty("PT二次变比") + private Double PT2; + + @ApiModelProperty("CT一次变比") + private Double CT1; + + @ApiModelProperty("CT二次变比") + private Double CT2; + + @ApiModelProperty("套餐流量") + private Float flowMeal; + + @ApiModelProperty("已用流量") + private Float statisValue; + + @ApiModelProperty("已用流量占比") + private Float flowProportion; + } + + @Data + public static class noDataLineInfo extends LineDetailVO implements Serializable{ + + @ApiModelProperty("监测点Id") + private String lineId; + + @ApiModelProperty("终端id") + private String devId; + + @ApiModelProperty("最新数据时间") + private LocalDateTime updateTime; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalShowVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalShowVO.java new file mode 100644 index 0000000..8810ddc --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalShowVO.java @@ -0,0 +1,23 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @Author: cdf + * @CreateTime: 2025-09-05 + * @Description: + */ +@EqualsAndHashCode(callSuper = true) +@Data +public class TerminalShowVO extends LedgerBaseInfo { + + private String stationVoltageLevel; + + private Double lng; + + private Double lat; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalTree.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalTree.java new file mode 100644 index 0000000..200fdff --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/TerminalTree.java @@ -0,0 +1,80 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * pqs + * 终端树实体 + * @author cdf + * @date 2021/7/19 + */ +@ApiModel +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TerminalTree implements Serializable { + @ApiModelProperty(name = "index",value = "序号") + private Integer index; + + private String id; + @ApiModelProperty(name = "parentId",value = "父id") + private String pid; + @ApiModelProperty(name = "level",value = "等级") + private Integer level; + @ApiModelProperty(name = "name",value = "名称") + private String name; + @ApiModelProperty(name = "sort",value = "排序") + private Integer sort; + @ApiModelProperty(name = "comFlag",value = "设备状态") + private Integer comFlag; + + @ApiModelProperty(name = "children",value = "子节点") + private List children = new ArrayList<>(); + + private String pids; + + /** + * 终端厂家 + */ + private String manufacturer; + + /** + * 电压等级Id,字典表 + */ + private String scale; + + /** + * 干扰源类型,字典表 + */ + private String loadType; + + /** + * 接线方式 + */ + private Integer ptType; + + /** + * 电网标志(0-电网侧;1-非电网侧) + */ + private Integer powerFlag; + + /** + * 电网侧变电站 + */ + private String powerSubstationName; + + /** + * 电网侧变电站 + */ + private String objName; + + private String objId; +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/UserLedgerVO.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/UserLedgerVO.java new file mode 100644 index 0000000..a9cd426 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/pojo/vo/UserLedgerVO.java @@ -0,0 +1,24 @@ +package com.njcn.product.terminal.mysqlTerminal.pojo.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @Author: cdf + * @CreateTime: 2025-03-24 + * @Description: 用户台账 + */ +@Data +public class UserLedgerVO implements Serializable { + private static final long serialVersionUID = 1L; + + private String id; + + private String projectName; + + private String stationId; + + private String city; + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommGeneralService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommGeneralService.java new file mode 100644 index 0000000..811f41c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommGeneralService.java @@ -0,0 +1,518 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.common.ServerEnum; +import com.njcn.common.utils.EnumUtils; +import com.njcn.product.cnuser.user.pojo.dto.DeptDTO; +import com.njcn.product.system.dict.mapper.DictDataMapper; +import com.njcn.product.system.dict.pojo.enums.DicDataTypeEnum; +import com.njcn.product.system.dict.pojo.po.DictData; +import com.njcn.product.terminal.mysqlTerminal.mapper.DeptLineMapper; +import com.njcn.product.cnuser.user.mapper.DeptMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeviceType; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.GeneralDeviceDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.LineBaseEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.PowerFlagEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.StatisticsEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam; +import com.njcn.product.cnuser.user.pojo.po.Dept; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.DeptLine; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ +@Service +@RequiredArgsConstructor +public class CommGeneralService { + + private final DeptMapper deptMapper; + + private final DeptLineMapper deptLineMapper; + + private final DeptLineService deptLineService; + + private final DictDataMapper dictDataMapper; + + private final TerminalBaseService terminalBaseService; + + + /** + * 根据部门id获取部门所拥有的监测点 + * @param deptId + * @return + */ + public List getRunLineIdsByDept(String deptId){ + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.like(Dept::getPids,deptId).eq(Dept::getState, DataStateEnum.ENABLE.getCode()); + List deptAndChildren = deptMapper.selectList(lambdaQueryWrapper); + List deptIds = deptAndChildren.stream().map(Dept::getId).distinct().collect(Collectors.toList()); + deptIds.add(deptId); + + List deptLineList = deptLineMapper.getLineIdByDeptIds(deptIds, Stream.of(0).collect(Collectors.toList())); + return deptLineList; + } + + /** + * 根据部门id获取部门所拥有的监测点 + * @param param + * @return + */ + public List getRunLineIdsByDept(LargeScreenCountParam param){ + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.like(Dept::getPids,param.getDeptId()).eq(Dept::getState, DataStateEnum.ENABLE.getCode()); + List deptAndChildren = deptMapper.selectList(lambdaQueryWrapper); + List deptIds = deptAndChildren.stream().map(Dept::getId).distinct().collect(Collectors.toList()); + deptIds.add(param.getDeptId()); + + List deptLineList = deptLineMapper.getLineIdByDeptIds(deptIds, Stream.of(0).collect(Collectors.toList())); + return deptLineList; + } + + + /** + * 根据部门id获取部门所拥有的监测点 + * @param deptId + * @return + */ + public List getAllLineIdsByDept(String deptId){ + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.like(Dept::getPids,deptId).eq(Dept::getState, DataStateEnum.ENABLE.getCode()); + List deptAndChildren = deptMapper.selectList(lambdaQueryWrapper); + List deptIds = deptAndChildren.stream().map(Dept::getId).distinct().collect(Collectors.toList()); + deptIds.add(deptId); + + List deptLineList = deptLineMapper.getLineIdByDeptIds(deptIds, Stream.of(0,1,2).collect(Collectors.toList())); + return deptLineList; + } + + + /** + * 根据部门id、远程服务名、远程客户端类型,以部门的方式 + * + * @param deviceInfoParam 终端查询条件 + * @param runFlag 终端状态 + * @param devModel 终端模型 + * @return 部门分类终端信息 + */ + public List getDeviceInfo(DeviceInfoParam deviceInfoParam, + List runFlag, + List devModel) { + //定义待返回终端信息 + List deviceInfos = new ArrayList<>(); + //初始化终端查询条件 + DeviceType deviceType = new DeviceType(); + if (CollectionUtil.isEmpty(devModel)) { + /** + * 终端模型(0:虚拟设备;1:实际设备;2:离线设备;)默认是实际设备 + */ + deviceType.setDevModel(null); + } else { + deviceType.setDevModel(devModel); + } + if (CollectionUtil.isEmpty(runFlag)) { + /** + * 终端状态(0:投运;1:热备用;2:停运) + */ + deviceType.setRunFlag(null); + } else { + deviceType.setRunFlag(runFlag); + } + if(ObjectUtil.isNotNull(deviceInfoParam.getComFlagStatus())){ + deviceType.setComFlag(Arrays.asList(deviceInfoParam.getComFlagStatus())); + } + filterDataType(deviceType, deviceInfoParam.getServerName()); + + // 初始化部门筛选条件 + List deptType = Stream.of(0,1,2,3).collect(Collectors.toList()); + // 获取包括当前部门的后代所有部门信息 + List deptInfos = deptMapper.getDeptDescendantIndexes(deviceInfoParam.getDeptIndex(), deptType); + // 过滤非直接后代部门,集合直接子部门 + List directDeptInfos = deptInfos.stream() + .filter(deptDTO -> deptDTO.getPid().equals(deviceInfoParam.getDeptIndex())).sorted(Comparator.comparing(DeptDTO::getSort)) + .collect(Collectors.toList()); + if (CollectionUtil.isEmpty(directDeptInfos)) { + // 没有直接子部门(树的最底层),获取当前部门所有信息 + List dept = deptInfos.stream() + .filter(deptDTO -> deptDTO.getId().equals(deviceInfoParam.getDeptIndex())) + .collect(Collectors.toList()); + deviceInfos.add(getGeneralDeviceInfo( + dept.get(0), + deviceType, + Collections.singletonList(deviceInfoParam.getDeptIndex()), + deviceInfoParam)); + } else { + for (DeptDTO directDeptDTO : directDeptInfos) { + //筛选pids包含该id的所有部门 直接子部门下属所有部门 + List descendantDeptDTO = deptInfos.stream() + .filter(d -> d.getPids().contains(directDeptDTO.getId())) + .collect(Collectors.toList()); + //形成需要查询监测点的部门索引 + List indexes = descendantDeptDTO.stream() + .map(DeptDTO::getId) + .distinct() + .collect(Collectors.toList()); + indexes.add(directDeptDTO.getId()); + GeneralDeviceDTO generalDeviceInfo = getGeneralDeviceInfo(directDeptDTO, deviceType, indexes, deviceInfoParam); + deviceInfos.add(generalDeviceInfo); + } + } + + + //判断统计类型 + if (deviceInfoParam.getStatisticalType() == null) { + deviceInfoParam.setStatisticalType(new SimpleDTO()); + } + StatisticsEnum statisticsEnum = StatisticsEnum.getStatisticsEnumByCode(deviceInfoParam.getStatisticalType().getCode()); + switch (statisticsEnum) { + case VOLTAGE_LEVEL: + return filterDataByScale(deviceInfos, deviceInfoParam.getScale()); + case LOAD_TYPE: + return filterDataByLoadType(deviceInfos, deviceInfoParam.getLoadType()); + case MANUFACTURER: + return filterDataByManufacturer(deviceInfos, deviceInfoParam.getManufacturer()); + case POWER_FLAG: + return filterDataByPowerFlag(deviceInfos, deviceInfoParam.getManufacturer()); + default: + return deviceInfos; + } + } + + + /** + * 筛选数据类型 + */ + private void filterDataType(DeviceType deviceType, String serverName) { + ServerEnum serverEnum = EnumUtils.getServerEnumByName(serverName); + List dataType = new ArrayList<>(); + dataType.add(2); + switch (serverEnum) { + case EVENT: + dataType.add(0); + break; + case HARMONIC: + dataType.add(1); + break; + default: + dataType.add(0); + dataType.add(1); + break; + } + /** + * 数据类型(0:暂态系统;1:稳态系统;2:两个系统) + */ + deviceType.setDataType(dataType); + } + + + + /** + * 根据部门id集合获取监测点信息 + * + * @param directDeptDTO 入参deptIndex的直接子部门 + * @param deviceType + * @param ids 直接子部门以及后代部门id集合 + * @param deviceInfoParam + * @return + */ + private GeneralDeviceDTO getGeneralDeviceInfo(DeptDTO directDeptDTO, + DeviceType deviceType, + List ids, + DeviceInfoParam deviceInfoParam) { + GeneralDeviceDTO generalDeviceDTO = new GeneralDeviceDTO(); + generalDeviceDTO.setIndex(directDeptDTO.getId()); + // type:部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + if (directDeptDTO.getType() == 0) { + generalDeviceDTO.setName(directDeptDTO.getArea()); + } else { + generalDeviceDTO.setName(directDeptDTO.getName()); + } + // 根据部门ids集合查询是否绑定监测点 部门和监测点关联关系中间表:pq_dept_line 可以一对多 + List deptLines = deptLineService.selectDeptBindLines(ids); + // 返回空数据 + if (CollectionUtil.isEmpty(deptLines)) { + return generalDeviceDTO; + } + // 提取该部门及其子部门所有监测点id + List lineIds = deptLines.stream().map(DeptLine::getLineId).collect(Collectors.toList()); + // 获取line详细数据 :根据监测点id,获取所有监测点 联查 pq_line、pq_line_detail + List lines = terminalBaseService.getLineByCondition(lineIds, deviceInfoParam); + // 返回空数据 + if (CollectionUtil.isEmpty(lines)) { + return generalDeviceDTO; + } + + //1.筛选出母线id,理论上监测点的pids中第六个id为母线id 联查: pq_line t1 ,pq_voltage t2 + List voltageIds=lines.stream().map(Line::getPid).collect(Collectors.toList()); + //再根据电压等级筛选合法母线信息 + List voltages = terminalBaseService.getVoltageByCondition(voltageIds, deviceInfoParam.getScale()); + + //2.筛选出终端id,理论上监测点的pids中第五个id为终端id + List devIds=voltages.stream().map(Line::getPid).collect(Collectors.toList()); + // 再根据终端条件筛选合法终端信息 联查:pq_line t1,pq_device t2 + List devices = terminalBaseService.getDeviceByCondition(devIds, deviceType, deviceInfoParam.getManufacturer()); + + //3.筛选出变电站id,理论上监测点的pids中第四个id为变电站id 联查: pq_line t1 ,pq_substation t2 + List subIds=devices.stream().map(Line::getPid).collect(Collectors.toList()); + List sub = terminalBaseService.getSubByCondition(subIds, new ArrayList<>()); + + //筛选最终的数据 + dealDeviceData(generalDeviceDTO, lines, devices, voltages, sub); + return generalDeviceDTO; + } + + + private List filterDataByScale(List deviceInfos, List scales) { + List generalDeviceDTOS = new ArrayList<>(); + List subIds = new ArrayList<>(), lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + subIds.addAll(generalDeviceDTO.getSubIndexes()); + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果电压等级集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(scales)) { + List scaleDictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()); + scales = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(scales); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : scales) { + List voltageScaleIds = terminalBaseService.getSubIdByScale(subIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, voltageScaleIds, LineBaseEnum.SUB_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + + /** + * 处理各节点索引集合 + * + * @param generalDeviceDTO 终端信息综合体 + * @param lines 监测点信息 + * @param devices 终端信息 + */ + private void dealDeviceData(GeneralDeviceDTO generalDeviceDTO, List lines, List devices) { + List gdIndexes = new ArrayList<>(), subIndexes = new ArrayList<>(), deviceIndexes = new ArrayList<>(), voltageIndexes = new ArrayList<>(), lineIndexes = new ArrayList<>(); + //筛选出供电公司、变电站、终端索引集合 + for (Line device : devices) { + String[] ids = device.getPids().split(","); + gdIndexes.add(ids[2]); + subIndexes.add(ids[3]); + deviceIndexes.add(device.getId()); + } + //筛选出母线、监测点集合 + for (Line line : lines) { + String[] ids = line.getPids().split(","); + if (deviceIndexes.contains(ids[4])) { + lineIndexes.add(line.getId()); + voltageIndexes.add(ids[5]); + } + } + //排重,入参到终端综合体 + generalDeviceDTO.setGdIndexes(gdIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setSubIndexes(subIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setDeviceIndexes(deviceIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setVoltageIndexes(voltageIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setLineIndexes(lineIndexes.stream().distinct().collect(Collectors.toList())); + + } + + /** + * 取多条件筛选后的交集索引,填充到部门统计中 + * + * @param generalDeviceDTO 部门信息 + * @param lines 筛选后的监测点信息 + * @param devices 筛选后的终端信息 + * @param voltages 筛选后的母线信息 + */ + private void dealDeviceData(GeneralDeviceDTO generalDeviceDTO, List lines, List devices, List voltages, List sub) { + List gdIndexes = new ArrayList<>(), subIndexes = new ArrayList<>(), deviceIndexes = new ArrayList<>(), voltageIndexes = new ArrayList<>(), lineIndexes = new ArrayList<>(); + List devIds = devices.stream().map(Line::getId).distinct().collect(Collectors.toList()); + List volIds = voltages.stream().map(Line::getId).distinct().collect(Collectors.toList()); + List subIds = sub.stream().map(Line::getId).distinct().collect(Collectors.toList()); + for (Line line : lines) { + String[] idsArray = line.getPids().split(","); + //监测点同时满足条件筛选后的终端、母线信息,才是最终的结果 + if (devIds.contains(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]) && + volIds.contains(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()])&& + subIds.contains(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]) + ) { + gdIndexes.add(idsArray[LineBaseEnum.GD_LEVEL.getCode()]); + subIndexes.add(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]); + deviceIndexes.add(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]); + voltageIndexes.add(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()]); + lineIndexes.add(line.getId()); + } + } + //排重,入参到终端综合体 + generalDeviceDTO.setGdIndexes(gdIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setSubIndexes(subIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setDeviceIndexes(deviceIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setVoltageIndexes(voltageIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setLineIndexes(lineIndexes.stream().distinct().collect(Collectors.toList())); + } + + + + private List filterDataByLoadType(List deviceInfos, List loadType) { + List generalDeviceDTOS = new ArrayList<>(); + List lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果干扰源集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(loadType)) { + List scaleDictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getCode()); + loadType = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(loadType); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : loadType) { + List lineLoadTypeIds = terminalBaseService.getLineIdByLoadType(lineIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, lineLoadTypeIds, LineBaseEnum.LINE_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + private List filterDataByManufacturer(List deviceInfos, List manufacturer) { + List generalDeviceDTOS = new ArrayList<>(); + List deviceIds = new ArrayList<>(), lineIds = new ArrayList<>(); + for (GeneralDeviceDTO generalDeviceDTO : deviceInfos) { + deviceIds.addAll(generalDeviceDTO.getDeviceIndexes()); + lineIds.addAll(generalDeviceDTO.getLineIndexes()); + } + //如果终端厂家集合为空,则查询所有的电压等级 + if (CollectionUtil.isEmpty(manufacturer)) { + List scaleDictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_MANUFACTURER.getCode()); + manufacturer = scaleDictData.stream().map(dictData -> { + SimpleDTO simpleDTO = new SimpleDTO(); + BeanUtil.copyProperties(dictData, simpleDTO); + return simpleDTO; + }).collect(Collectors.toList()); + } + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(manufacturer); + } + List lines = terminalBaseService.getLineById(lineIds); + for (SimpleDTO simpleDTO : manufacturer) { + List voltageScaleIds = terminalBaseService.getDeviceIdByManufacturer(deviceIds, simpleDTO.getId()); + generalDeviceDTOS.add(assembleDataByLine(simpleDTO, lines, voltageScaleIds, LineBaseEnum.DEVICE_LEVEL.getCode())); + } + return generalDeviceDTOS; + } + + private List filterDataByPowerFlag(List deviceInfos, List manufacturer) { + List generalDeviceDTOS = new ArrayList<>(); + List deviceIds = deviceInfos.stream().flatMap(x->x.getLineIndexes().stream()).collect(Collectors.toList()); + List lineIds = deviceInfos.stream().flatMap(x->x.getLineIndexes().stream()).collect(Collectors.toList()); + //监测点为空,则返回空的分类数据 + if (CollectionUtil.isEmpty(lineIds)) { + return assembleCommonData(manufacturer); + } + SimpleDTO dto; + List lines = terminalBaseService.getLineById(lineIds); + for (int i = 0; i < 6; i++) { + List powerFlagIds = terminalBaseService.getDeviceIdByPowerFlag(deviceIds, i); + dto=new SimpleDTO(); + PowerFlagEnum enumByCode = PowerFlagEnum.getPowerFlagEnumByCode(i); + dto.setId(enumByCode.getCode().toString()); + dto.setName(enumByCode.getMessage()); + generalDeviceDTOS.add(assembleDataByLine(dto, lines, powerFlagIds, LineBaseEnum.LINE_LEVEL.getCode())); + } + + return generalDeviceDTOS; + } + + + /** + * 当该部门不存在监测点时,返回空的分类数据 + * + * @param simpleDTOS 分类类别 + * @return . + */ + private List assembleCommonData(List simpleDTOS) { + return simpleDTOS.stream().map(this::assembleData).collect(Collectors.toList()); + } + + /** + * 当该部门不存在监测点时,返回空的分类数据 + * + * @param simpleDTO 基础数据 + * @return . + */ + private GeneralDeviceDTO assembleData(SimpleDTO simpleDTO) { + GeneralDeviceDTO generalDeviceDTO = new GeneralDeviceDTO(); + generalDeviceDTO.setName(simpleDTO.getName()); + generalDeviceDTO.setIndex(simpleDTO.getId()); + return generalDeviceDTO; + } + + + /** + * 筛选对应等级的id + * + * @param simpleDTO 分类信息 + * @param lines 所有监测点 + * @param keyIds 待筛选的id + * @param level 待筛选的层级 + */ + private GeneralDeviceDTO assembleDataByLine(SimpleDTO simpleDTO, List lines, List keyIds, Integer level) { + GeneralDeviceDTO generalDeviceDTO = assembleData(simpleDTO); + if (CollectionUtil.isNotEmpty(keyIds)) { + List tempLines = lines.stream().filter(line -> { + String[] idsArray = line.getPids().split(","); + if (level.equals(LineBaseEnum.LINE_LEVEL.getCode())) { + return keyIds.contains(line.getId()); + } else { + return keyIds.contains(idsArray[level]); + } + }).collect(Collectors.toList()); + List gdIndexes = new ArrayList<>(), subIndexes = new ArrayList<>(), deviceIndexes = new ArrayList<>(), voltageIndexes = new ArrayList<>(), lineIndexes = new ArrayList<>(); + for (Line line : tempLines) { + String[] idsArray = line.getPids().split(","); + gdIndexes.add(idsArray[LineBaseEnum.GD_LEVEL.getCode()]); + subIndexes.add(idsArray[LineBaseEnum.SUB_LEVEL.getCode()]); + deviceIndexes.add(idsArray[LineBaseEnum.DEVICE_LEVEL.getCode()]); + voltageIndexes.add(idsArray[LineBaseEnum.SUB_V_LEVEL.getCode()]); + lineIndexes.add(line.getId()); + } + //排重,入参到终端综合体 + generalDeviceDTO.setGdIndexes(gdIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setSubIndexes(subIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setDeviceIndexes(deviceIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setVoltageIndexes(voltageIndexes.stream().distinct().collect(Collectors.toList())); + generalDeviceDTO.setLineIndexes(lineIndexes.stream().distinct().collect(Collectors.toList())); + } + return generalDeviceDTO; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommTerminalService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommTerminalService.java new file mode 100644 index 0000000..a51bf1b --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/CommTerminalService.java @@ -0,0 +1,33 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + + + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeptGetChildrenMoreDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeptGetLineParam; + +import java.util.List; +import java.util.Map; + +/** + * pqs + * + * @author cdf + * @date 2023/5/10 + */ + +public interface CommTerminalService { + + + + /** + * 根据单位获取单位监测点 + * @author cdf + * @date 2023/5/10 + */ + List deptGetLine(DeptGetLineParam deptGetLineParam); + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/DeptLineService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/DeptLineService.java new file mode 100644 index 0000000..b06c96a --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/DeptLineService.java @@ -0,0 +1,38 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.DeptLine; + + +import java.util.List; +import java.util.Map; + +/** + * @author denghuajun + * @date 2022/1/12 17:30 + * + */ +public interface DeptLineService extends IService { + + + /** + * 根据部门ids集合查询是否绑定监测点 + * @param ids 部门ids + * @return 查询结果 + */ + List selectDeptBindLines(List ids); + + + /** + * 获取根据单位分组的监测点集合信息 + * param 系统类型 0暂态 1稳态 2 双类型 + * param type 台账类型 1监测点 2母线 3 装置 + * @author cdf + * @date 2023/5/10 + */ + Map> lineDevGet(List devType, Integer type, Integer lineRunFlag); + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/LineService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/LineService.java new file mode 100644 index 0000000..ba88b15 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/LineService.java @@ -0,0 +1,39 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerTreeDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDetailDataVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalTree; + +import java.util.List; + + +/** + * 监测点类 + * @author denghuajun + * @date 2022/2/23 + * + */ +public interface LineService extends IService { + + List getTree(); + + /** + * 5层树排除设备 母线监测点合并 + * + * @author cdf + * @date 2022/1/13 + */ + List getTerminalTreeForFive(DeviceInfoParam deviceInfoParam); + + /** + * 获取监测点详情 + * @param id 监测点id + * @return 结果 + */ + LineDetailDataVO getLineDetailData(String id); + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/TerminalBaseService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/TerminalBaseService.java new file mode 100644 index 0000000..51b32ca --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/TerminalBaseService.java @@ -0,0 +1,130 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + +import com.njcn.common.pojo.dto.SimpleDTO; + +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeviceType; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +public interface TerminalBaseService { + + + + /** + * 根据监测点id,获取所有监测点 + * + * @param lineIds 监测点id + * @return 监测点数据 + */ + List getLineById(List lineIds); + + /** + * 根据监测点id,获取所有监测点 + * + * @param lineIds 监测点id + * @param deviceInfoParam 监测点查询条件 + * @return 监测点数据 + */ + List getLineByCondition(List lineIds, DeviceInfoParam deviceInfoParam); + + /** + * 根据终端id,获取所有对应终端 + * + * @param devIds 终端id + * @param deviceType 终端条件筛选 + * @return 终端数据 + */ + List getDeviceById(List devIds, DeviceType deviceType); + + + /** + * 功能描述: 根据id查询变电站信息 + * + * @param list + * @return java.util.List + * @author xy + * @date 2022/2/21 18:47 + */ + List getSubstationById(List list); + + + /** + * 查询终端信息 + * + * @param devIds 终端索引 + * @param deviceType 终端筛选条件 + * @param manufacturer 终端厂家 + */ + List getDeviceByCondition(List devIds, DeviceType deviceType, List manufacturer); + + /** + * 查询母线信息 + * + * @param voltageIds 母线索引 + * @param scale 电压等级 + */ + List getVoltageByCondition(List voltageIds, List scale); + + /** + * 查询变电站信息 + * + * @param subIds 变电站索引 + * @param scale 电压等级 + */ + List getSubByCondition(List subIds, List scale); + + /** + * 根据指定电压等级查询母线id + * + * @param voltageIds 母线id + * @param scale 电压等级 + */ + /* List getVoltageIdByScale(List voltageIds, String scale); +*/ + /** + * 根据指定电压等级查询母线id + * @param subIds + * @param scale + * @return: java.util.List + * @Author: wr + * @Date: 2024/10/12 15:58 + */ + List getSubIdByScale(List subIds, String scale); + + /** + * 根据干扰源获取对应的监测点id + * + * @param lineIds 监测点id + * @param loadType 干扰源类型 + */ + List getLineIdByLoadType(List lineIds, String loadType); + + /** + * 根据终端厂家获取对应的终端id + * + * @param deviceIds 终端id + * @param manufacturer 终端厂家 + */ + List getDeviceIdByManufacturer(List deviceIds, String manufacturer); + /** + * 根据监测点性质获取监测信息 + * + * @param lineIds 监测点id + * @param manufacturer 监测点性质 + */ + List getDeviceIdByPowerFlag(List lineIds, Integer manufacturer); + + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/UserReportPOService.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/UserReportPOService.java new file mode 100644 index 0000000..9175e87 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/UserReportPOService.java @@ -0,0 +1,25 @@ +package com.njcn.product.terminal.mysqlTerminal.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.UserReportParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportPO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.UserLedgerVO; + +import java.util.List; + +/** + * Description: + * Date: 2024/4/25 10:07【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface UserReportPOService extends IService { + + + + List selectUserList(UserReportParam userReportParam); + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/CommTerminalServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/CommTerminalServiceImpl.java new file mode 100644 index 0000000..bae8cce --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/CommTerminalServiceImpl.java @@ -0,0 +1,130 @@ +package com.njcn.product.terminal.mysqlTerminal.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.njcn.common.pojo.enums.common.ServerEnum; +import com.njcn.common.utils.EnumUtils; + +import com.njcn.product.cnuser.user.pojo.dto.DeptDTO; +import com.njcn.product.cnuser.user.mapper.DeptMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeptGetBase; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeptGetChildrenMoreDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeptGetLineParam; +import com.njcn.product.terminal.mysqlTerminal.service.CommTerminalService; +import com.njcn.product.terminal.mysqlTerminal.service.DeptLineService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * pqs + * + * @author cdf + * @date 2023/5/10 + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class CommTerminalServiceImpl implements CommTerminalService { + + //redis前缀 + private final String commTerminal = "commTerminal#"; + + private final DeptLineService deptLineService; + private final DeptMapper deptMapper; + + + @Override + public List deptGetLine(DeptGetLineParam deptGetLineParam) { + List result = new ArrayList<>(); + List temDept = getDeptChildrenByParent(deptGetLineParam); + Map deptMap = temDept.stream().collect(Collectors.toMap(DeptGetBase::getUnitId, DeptGetBase::getUnitName)); + Map> map = deptLineService.lineDevGet(filterDataTypeNew(deptGetLineParam.getServerName()), + 1,deptGetLineParam.getLineRunFlag()); + temDept.forEach(item -> { + DeptGetChildrenMoreDTO deptGetChildrenMoreDTO = new DeptGetChildrenMoreDTO(); + deptGetChildrenMoreDTO.setUnitId(item.getUnitId()); + deptGetChildrenMoreDTO.setUnitName(item.getUnitName()); + deptGetChildrenMoreDTO.setUnitChildrenList(item.getUnitChildrenList()); + deptGetChildrenMoreDTO.setDeptLevel(item.getDeptLevel()); + List deptIds = item.getUnitChildrenList(); + if (CollectionUtil.isNotEmpty(deptIds)) { + List lineList = new ArrayList<>(); + deptIds.forEach(i -> { + if (map.containsKey(i)) { + map.get(i).forEach(x->{ + if(deptMap.containsKey(x.getUnitId())){ + x.setUnitName(deptMap.get(x.getUnitId())); + } + }); + lineList.addAll(map.get(i)); + } + }); + + //去重 + ArrayList collect = lineList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>( + Comparator.comparing(LineDevGetDTO::getPointId) + )), ArrayList::new)); + + deptGetChildrenMoreDTO.setLineBaseList(collect); + } + result.add(deptGetChildrenMoreDTO); + }); + return result; + } + + /** + * 基础获取单位信息 + * @author cdf + * @date 2023/5/10 + */ + + public List getDeptChildrenByParent(DeptGetLineParam deptGetLineParam) { + /*List redisResult = (List) redisUtil.getObjectByKey(commTerminal + deptGetLineParam.getDeptId()); + if (CollectionUtil.isNotEmpty(redisResult)) { + return redisResult; + }*/ + List result = new ArrayList<>(); + List deptDTOList = deptMapper.getDeptDescendantIndexes(deptGetLineParam.getDeptId(), Stream.of(0, 1).collect(Collectors.toList())); + deptDTOList.forEach(it -> { + DeptGetBase deptGetBase = new DeptGetBase(); + deptGetBase.setUnitId(it.getId()); + deptGetBase.setUnitName(it.getName()); + deptGetBase.setDeptLevel(getDeptLevel(it.getPids())); + List deptChildren = deptDTOList.stream().filter(deptDTO -> deptDTO.getPids().contains(it.getId())).map(DeptDTO::getId).collect(Collectors.toList()); + deptChildren.add(it.getId()); + deptGetBase.setUnitChildrenList(deptChildren); + result.add(deptGetBase); + }); + return result; + } + + + private Integer getDeptLevel(String pids) { + List list = Arrays.stream(pids.split(",")).map(String::trim).collect(Collectors.toList()); + return list.size(); + } + + private List filterDataTypeNew(String serverName) { + List devType = new ArrayList<>(); + devType.add(2); + ServerEnum serverEnum = EnumUtils.getServerEnumByName(serverName); + switch (serverEnum) { + case EVENT: + devType.add(0); + break; + case HARMONIC: + devType.add(1); + break; + default: + devType.add(0); + devType.add(1); + break; + } + return devType; + } +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/DeptLineServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/DeptLineServiceImpl.java new file mode 100644 index 0000000..eab7dfd --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/DeptLineServiceImpl.java @@ -0,0 +1,48 @@ +package com.njcn.product.terminal.mysqlTerminal.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.terminal.mysqlTerminal.mapper.DeptLineMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LineDevGetDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.DeptLine; +import com.njcn.product.terminal.mysqlTerminal.service.DeptLineService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author denghuajun + * @date 2022/1/12 17:32 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeptLineServiceImpl extends ServiceImpl implements DeptLineService { + + private final DeptLineMapper deptLineMapper; + + + @Override + public List selectDeptBindLines(List ids) { + return this.lambdaQuery().in(DeptLine::getId, ids).list(); + } + + @Override + public Map> lineDevGet(List devDataType, Integer type, Integer lineRunFlag) { + List deptLines = deptLineMapper.lineDevGet(devDataType, type, lineRunFlag); + return deptLines.stream().collect(Collectors.groupingBy(LineDevGetDTO::getUnitId)); + } + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/LineServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/LineServiceImpl.java new file mode 100644 index 0000000..ce1f1f1 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/LineServiceImpl.java @@ -0,0 +1,336 @@ +package com.njcn.product.terminal.mysqlTerminal.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.utils.PubUtils; +import com.njcn.product.system.dict.mapper.DictDataMapper; +import com.njcn.product.system.other.mapper.AreaMapper; +import com.njcn.product.terminal.mysqlTerminal.mapper.*; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.GeneralDeviceDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerTreeDTO; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.LineBaseEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.enums.StatisticsEnum; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.UserReportParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Device; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.LineDetail; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDataVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.LineDetailDataVO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalTree; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.UserLedgerVO; +import com.njcn.product.terminal.mysqlTerminal.service.CommGeneralService; +import com.njcn.product.terminal.mysqlTerminal.service.LineService; +import com.njcn.product.terminal.mysqlTerminal.service.UserReportPOService; +import com.njcn.product.terminal.utils.TerminalUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * 监测点类 + * + * @author denghuajun + * @date 2022/2/23 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class LineServiceImpl extends ServiceImpl implements LineService { + + private final DeviceMapper deviceMapper; + + private final TreeMapper treeMapper; + private final CommGeneralService commGeneralService; + private final UserReportPOService userReportPOService; + private final DictDataMapper dictDataMapper; + private final LineDetailMapper lineDetailMapper; + private final AreaMapper areaMapper; + private final VoltageMapper voltageMapper; + + @Override + public List getTree() { + + List deviceList = deviceMapper.selectList(new LambdaQueryWrapper().eq(Device::getRunFlag,0).eq(Device::getDevModel,1)); + List devList = this.baseMapper.selectList(new LambdaQueryWrapper().in(Line::getId,deviceList.stream().map(Device::getId).collect(Collectors.toList()))); + + List ledgerList = this.baseMapper.selectList(new LambdaQueryWrapper().in(Line::getLevel, Stream.of(LineBaseEnum.GD_LEVEL.getCode(),LineBaseEnum.SUB_LEVEL.getCode(),LineBaseEnum.SUB_V_LEVEL.getCode(),LineBaseEnum.LINE_LEVEL.getCode()).collect(Collectors.toList()))); + List monitorList = ledgerList.stream().filter(it->Objects.equals(it.getLevel(),LineBaseEnum.LINE_LEVEL.getCode())).collect(Collectors.toList()); + List busBarList = ledgerList.stream().filter(it->Objects.equals(it.getLevel(),LineBaseEnum.SUB_V_LEVEL.getCode())).collect(Collectors.toList()); + Map busBarMap = busBarList.stream().collect(Collectors.toMap(Line::getId, Function.identity())); + List stationList = ledgerList.stream().filter(it->Objects.equals(it.getLevel(),LineBaseEnum.SUB_LEVEL.getCode())).collect(Collectors.toList()); + List gdList = ledgerList.stream().filter(it->Objects.equals(it.getLevel(),LineBaseEnum.GD_LEVEL.getCode())).collect(Collectors.toList()); + + + + List lineDtoList = monitorList.stream().map(it->{ + LedgerTreeDTO oracleLedgerTreeDTO = new LedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getId()); + String busName = busBarMap.get(it.getPid()).getName(); + oracleLedgerTreeDTO.setName(busName+"_"+it.getName()); + oracleLedgerTreeDTO.setPid(it.getPids().split(StrUtil.COMMA)[LineBaseEnum.DEVICE_LEVEL.getCode()]); + oracleLedgerTreeDTO.setLevel(4); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + + List devDtoList = devList.stream().map(it->{ + LedgerTreeDTO oracleLedgerTreeDTO = new LedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getId()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid(it.getPid()); + oracleLedgerTreeDTO.setLevel(3); + oracleLedgerTreeDTO.setChildren(lineDtoList.stream().filter(line-> Objects.equals(it.getId(),line.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + List stationDtoList = stationList.stream().map(it->{ + LedgerTreeDTO oracleLedgerTreeDTO = new LedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getId()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid(it.getPid()); + oracleLedgerTreeDTO.setLevel(2); + oracleLedgerTreeDTO.setChildren(devDtoList.stream().filter(dev->Objects.equals(it.getId(),dev.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + List gdDtoList = gdList.stream().map(it->{ + LedgerTreeDTO oracleLedgerTreeDTO = new LedgerTreeDTO(); + oracleLedgerTreeDTO.setId(it.getId()); + oracleLedgerTreeDTO.setName(it.getName()); + oracleLedgerTreeDTO.setPid("0"); + oracleLedgerTreeDTO.setLevel(1); + oracleLedgerTreeDTO.setChildren(stationDtoList.stream().filter(sub->Objects.equals(it.getId(),sub.getPid())).collect(Collectors.toList())); + return oracleLedgerTreeDTO; + }).collect(Collectors.toList()); + return gdDtoList; + } + + + + + /** + * 5层树排除设备 母线监测点合并 + * + * @author cdf + * @date 2022/1/13 + */ + @Override + public List getTerminalTreeForFive(DeviceInfoParam deviceInfoParam) { + //deviceInfoParam.setDeptIndex(RequestUtil.getDeptIndex()); + // 获取所有数据 + List generalDeviceDTOList = commGeneralService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList())); + // 判断所有数据集合状态 + if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) { + // 创建集合 + List taiZhang = new ArrayList<>(); + // 获取用户 + UserReportParam userReportParam = new UserReportParam(); + List userReportPOList = userReportPOService.selectUserList(userReportParam); + userReportPOList = userReportPOList.stream().filter(it -> StrUtil.isNotBlank(it.getStationId())).collect(Collectors.toList()); + Map userMap = userReportPOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity())); + + // 遍历集合 + for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) { + // 创建实体类 + TerminalTree terminalTree = new TerminalTree(); + // 判断监测点索引集合状态 + if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) { + continue; + } + // 通过供电公司索引查询省会 + List proList = treeMapper.getProvinceList(generalDeviceDTO.getGdIndexes()); + // 通过供电公司索引查询供电公司信息 + List gdList = treeMapper.getGdList(generalDeviceDTO.getGdIndexes()); + // 通过供电站索引查询供电站信息 + List subList = treeMapper.getSubList(generalDeviceDTO.getSubIndexes()); + // 通过监测点索引查询监测点信息 + List lineList = treeMapper.getLineList(generalDeviceDTO.getLineIndexes()); + + List userLineList = lineList.stream().filter(it->StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList()); + List otherLineList = lineList.stream().filter(it->StrUtil.isBlank(it.getObjId())).collect(Collectors.toList()); + + Map> temMap = new HashMap<>(); + if(CollUtil.isNotEmpty(userLineList)) { + Map> objMap = userLineList.stream().collect(Collectors.groupingBy(TerminalTree::getObjId)); + List temList = new ArrayList<>(); + objMap.forEach((objId, monitorList) -> { + UserLedgerVO userLedgerVO = userMap.get(objId); + TerminalTree tree = new TerminalTree(); + tree.setLevel(LineBaseEnum.USER_LEVEL.getCode()); + tree.setPid(userLedgerVO.getStationId()); + tree.setId(userLedgerVO.getId()); + tree.setChildren(monitorList); + int devSize = (int) monitorList.stream().map(x -> { + // 获取父id字符串,通过 逗号 分割 成一个数组 + String[] pid = x.getPids().split(StrUtil.COMMA); + return pid[LineBaseEnum.DEVICE_LEVEL.getCode()]; + }).distinct().count(); + tree.setName(userLedgerVO.getProjectName()); + //特殊处理,用户层级下面的装置数量临时存到pids字段。 + tree.setPids(String.valueOf(devSize)); + temList.add(tree); + }); + temMap = temList.stream().collect(Collectors.groupingBy(TerminalTree::getPid)); + } + + + + //处理变电站 + dealChildrenData(subList, otherLineList, temMap,true); + + //监测点前面加序号,后面不需要删除下面两行就行 + //Integer[] arr = {1}; + //subList.forEach(item->item.getChildren().forEach(it->it.setName((arr[0]++ +"_"+it.getName())))); + //处理供电公司 + dealChildrenData(gdList, subList, null,false); + + if (deviceInfoParam.getStatisticalType().getCode().equalsIgnoreCase(StatisticsEnum.POWER_NETWORK.getCode())) { + terminalTree.setChildren(gdList); + } else { + //还需要额外处理省会 + dealChildrenData(proList, gdList, null,false); + terminalTree.setChildren(proList); + } + terminalTree.setId(generalDeviceDTO.getIndex()); + terminalTree.setName(generalDeviceDTO.getName()); + terminalTree.setLevel(0); + taiZhang.add(terminalTree); + } + return taiZhang; + } else { + return new ArrayList<>(); + } + } + + + @Override + public LineDetailDataVO getLineDetailData(String id) { + if (StringUtils.isEmpty(id)) { + return new LineDetailDataVO(); + } else { + //根据id查询当前信息的pids + List pids = Arrays.asList(this.baseMapper.selectById(id).getPids().split(",")); + List list = new ArrayList(pids); + list.add(id); + List lineDataVOList = this.baseMapper.getLineDetail(list); + LineDetailDataVO lineDetailDataVO = new LineDetailDataVO(); + String areaId = "", devId = "", voId = ""; + for (LineDataVO lineDataVO : lineDataVOList) { + switch (lineDataVO.getLevel()) { + case 1: + areaId = lineDataVO.getName(); + break; + case 2: + lineDetailDataVO.setGdName(lineDataVO.getName()); + break; + case 3: + lineDetailDataVO.setBdName(lineDataVO.getName()); + break; + case 4: + devId = lineDataVO.getId(); + lineDetailDataVO.setDevName(lineDataVO.getName()); + break; + case 5: + voId = lineDataVO.getId(); + break; + case 6: + lineDetailDataVO.setLineName(lineDataVO.getName()); + break; + default: + break; + } + } + lineDetailDataVO.setAreaName(areaMapper.selectById(areaId).getName()); + lineDetailDataVO.setScale(dictDataMapper.selectById(voltageMapper.selectById(voId).getScale()).getName()); + LineDetail lineDetail = lineDetailMapper.selectById(id); + Device device = deviceMapper.selectById(devId); + lineDetailDataVO.setManufacturer(dictDataMapper.selectById(device.getManufacturer()).getName()); + lineDetailDataVO.setComFlag(TerminalUtils.comFlag(device.getComFlag())); + lineDetailDataVO.setRunFlag(TerminalUtils.lineRunFlag(lineDetail.getRunFlag())); + lineDetailDataVO.setIp(device.getIp()); + lineDetailDataVO.setLoginTime(device.getLoginTime()); + lineDetailDataVO.setDevId(device.getId()); + lineDetailDataVO.setBusinessType(dictDataMapper.selectById(lineDetail.getBusinessType()).getName()); + lineDetailDataVO.setLoadType(dictDataMapper.selectById(lineDetail.getLoadType()).getName()); + lineDetailDataVO.setObjName(lineDetail.getObjName()); + lineDetailDataVO.setId(lineDetail.getNum()); + lineDetailDataVO.setPtType(TerminalUtils.ptType(lineDetail.getPtType())); + lineDetailDataVO.setPt(lineDetail.getPt1() + "/" + lineDetail.getPt2()); + lineDetailDataVO.setCt(lineDetail.getCt1() + "/" + lineDetail.getCt2()); + lineDetailDataVO.setDealCapacity(lineDetail.getDealCapacity()); + lineDetailDataVO.setDevCapacity(lineDetail.getDevCapacity()); + lineDetailDataVO.setShortCapacity(lineDetail.getShortCapacity()); + lineDetailDataVO.setStandardCapacity(lineDetail.getStandardCapacity()); + lineDetailDataVO.setTimeInterval(lineDetail.getTimeInterval()); + lineDetailDataVO.setOwner(lineDetail.getOwner()); + lineDetailDataVO.setOwnerDuty(lineDetail.getOwnerDuty()); + lineDetailDataVO.setOwnerTel(lineDetail.getOwnerTel()); + lineDetailDataVO.setWiringDiagram(lineDetail.getWiringDiagram()); + lineDetailDataVO.setPtPhaseType(lineDetail.getPtPhaseType()); + lineDetailDataVO.setUpdateTime(device.getUpdateTime()); + return lineDetailDataVO; + } + + } + + /** + * 处理变电站 + * + * @param targetData + * @param childrenData + * @param isLine + */ + private void dealChildrenData(List targetData, List childrenData,Map> userLineMap, boolean isLine) { + // 创建一个map集合,用于封装对象 + Map> groupLine; + if (isLine) { + // 通过stream流分组 + groupLine = childrenData.stream().collect(Collectors.groupingBy(terminalTree -> { + // 获取父id字符串,通过 逗号 分割 成一个数组 + String[] pid = terminalTree.getPids().split(StrUtil.COMMA); + return pid[LineBaseEnum.SUB_LEVEL.getCode()]; + })); + } else { + groupLine = childrenData.stream().collect(Collectors.groupingBy(TerminalTree::getPid)); + } + //变电站 + targetData.forEach(terminalTree -> { + List terminalTrees = new ArrayList<>(); + if(groupLine.containsKey(terminalTree.getId())) { + terminalTrees.addAll(groupLine.get(terminalTree.getId()).stream().sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList())); + } + if (isLine) { + //变电站集合 + int size = (int) terminalTrees.stream().map(x -> { + // 获取父id字符串,通过 逗号 分割 成一个数组 + String[] pid = x.getPids().split(StrUtil.COMMA); + return pid[LineBaseEnum.DEVICE_LEVEL.getCode()]; + }).distinct().count(); + + int devSize = 0; + if(userLineMap.containsKey(terminalTree.getId())){ + List userList = userLineMap.get(terminalTree.getId()); + devSize= (int) userList.stream().mapToDouble(it->Integer.parseInt(it.getPids())).sum(); + terminalTrees.addAll(userList); + } + int sumDev = size+devSize; + terminalTree.setName(terminalTree.getName() + "(" +sumDev+ "台装置)"); + terminalTree.setChildren(terminalTrees); + } else { + terminalTree.setChildren(terminalTrees); + } + }); + } + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/TerminalBaseServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/TerminalBaseServiceImpl.java new file mode 100644 index 0000000..07cc70c --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/TerminalBaseServiceImpl.java @@ -0,0 +1,196 @@ +package com.njcn.product.terminal.mysqlTerminal.service.impl; + +import cn.afterturn.easypoi.excel.ExcelExportUtil; +import cn.afterturn.easypoi.excel.ExcelImportUtil; +import cn.afterturn.easypoi.excel.entity.ExportParams; +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.text.StrBuilder; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.dto.SimpleDTO; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.common.utils.PubUtils; + +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; + +import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.dto.DeviceType; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.DeviceInfoParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line; + +import com.njcn.product.terminal.mysqlTerminal.service.TerminalBaseService; +import com.njcn.web.utils.RequestUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ss.usermodel.Workbook; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.net.HttpURLConnection; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * pqs + * + * @author cdf + * @date 2022/1/4 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class TerminalBaseServiceImpl extends ServiceImpl implements TerminalBaseService { + + private final LineMapper lineMapper; + + + + + + + @Override + public List getSubstationById(List list) { + return this.lambdaQuery().in(Line::getId, list).list(); + } + + @Override + public List getLineById(List lineIds) { + return Collections.emptyList(); + } + + @Override + public List getLineByCondition(List ids, DeviceInfoParam deviceInfoParam) { + return this.baseMapper.getLineByCondition(ids, deviceInfoParam); + } + + @Override + public List getDeviceById(List devIds, DeviceType deviceType) { + return Collections.emptyList(); + } + + @Override + public List getDeviceByCondition(List devIds, DeviceType deviceType, List manufacturer) { + return this.baseMapper.getDeviceByCondition(devIds, deviceType, manufacturer); + } + + @Override + public List getVoltageByCondition(List voltageIds, List scale) { + return this.baseMapper.getVoltageByCondition(voltageIds, scale); + } + + @Override + public List getSubByCondition(List subIds, List scale) { + return this.baseMapper.getSubByCondition(subIds, scale); + } +/* + + @Override + public List getVoltageIdByScale(List voltageIds, String scale) { + return this.baseMapper.getVoltageIdByScale(voltageIds, scale); + } +*/ + + @Override + public List getSubIdByScale(List subIds, String scale) { + return this.baseMapper.getSubIdByScale(subIds, scale); + } + + @Override + public List getLineIdByLoadType(List lineIds, String loadType) { + return this.baseMapper.getLineIdByLoadType(lineIds, loadType); + } + + @Override + public List getDeviceIdByManufacturer(List deviceIds, String manufacturer) { + return this.baseMapper.getDeviceIdByManufacturer(deviceIds, manufacturer); + } + + @Override + public List getDeviceIdByPowerFlag(List lineIds, Integer manufacturer) { + return this.baseMapper.getDeviceIdByPowerFlag(lineIds, manufacturer); + } + + + + + + + + + /** + * 根据条件查询出台账信息 + * + * @param name 名称 + * @param pid 父id + * @param level 层级 + * @param state 状态 0 删除 1 正常 + * @return 终端信息 + */ + private Line queryLine(LambdaQueryWrapper lineLambdaQueryWrapper, String name, String pid, Integer level, Integer state) { + lineLambdaQueryWrapper.clear(); + lineLambdaQueryWrapper.eq(Line::getName, name) + .eq(Line::getPid, pid) + .eq(Line::getLevel, level) + .eq(Line::getState, state); + return this.baseMapper.selectOne(lineLambdaQueryWrapper); + } + + /** + * 组装台账信息,稍后入库 + * + * @param name 名称 + * @param level 等级 + * @param pid 父ID + * @param pids 上层所有ID + */ + private Line assembleLine(String name, Integer level, String pid, List pids) { + Line line = new Line(); + line.setName(name); + line.setLevel(level); + line.setPid(pid); + line.setPids(String.join(",", pids)); + line.setSort(0); + line.setState(DataStateEnum.ENABLE.getCode()); + return line; + } + + private Line assembleLine(String name, Integer level, String pid, String pids, Integer sort) { + Line line = new Line(); + line.setName(name); + line.setLevel(level); + line.setPid(pid); + line.setPids(pids); + line.setSort(sort); + line.setState(DataStateEnum.ENABLE.getCode()); + return line; + } + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/UserReportPOServiceImpl.java b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/UserReportPOServiceImpl.java new file mode 100644 index 0000000..c13813d --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/mysqlTerminal/service/impl/UserReportPOServiceImpl.java @@ -0,0 +1,54 @@ +package com.njcn.product.terminal.mysqlTerminal.service.impl; + + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.product.terminal.mysqlTerminal.mapper.UserReportPOMapper; +import com.njcn.product.terminal.mysqlTerminal.pojo.param.UserReportParam; +import com.njcn.product.terminal.mysqlTerminal.pojo.po.UserReportPO; +import com.njcn.product.terminal.mysqlTerminal.pojo.vo.UserLedgerVO; +import com.njcn.product.terminal.mysqlTerminal.service.UserReportPOService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Description: + * Date: 2024/4/25 10:07【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class UserReportPOServiceImpl extends ServiceImpl implements UserReportPOService { + + + + + + @Override + public List selectUserList(UserReportParam userReportParam) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + + if(StrUtil.isNotBlank(userReportParam.getCity())){ + lambdaQueryWrapper.in(UserReportPO::getCity,Stream.of(userReportParam.getCity()).collect(Collectors.toList())); + } + if(StrUtil.isNotBlank(userReportParam.getStationId())){ + lambdaQueryWrapper.eq(UserReportPO::getStationId,userReportParam.getStationId()); + } + + lambdaQueryWrapper.eq(UserReportPO::getState,DataStateEnum.ENABLE.getCode()); + + List list = this.list(lambdaQueryWrapper); + return BeanUtil.copyToList(list,UserLedgerVO.class); + } + + + +} diff --git a/cn-terminal/src/main/java/com/njcn/product/terminal/utils/TerminalUtils.java b/cn-terminal/src/main/java/com/njcn/product/terminal/utils/TerminalUtils.java new file mode 100644 index 0000000..e2ac660 --- /dev/null +++ b/cn-terminal/src/main/java/com/njcn/product/terminal/utils/TerminalUtils.java @@ -0,0 +1,79 @@ +package com.njcn.product.terminal.utils; + +/** + * @Author: cdf + * @CreateTime: 2025-09-09 + * @Description: + */ +public class TerminalUtils { + + public static String comFlag(Integer comFlag) { + switch (comFlag) { + case 0: + return "中断"; + case 1: + return "正常"; + default: + return ""; + } + } + + public static String runFlag(Integer runFlag) { + switch (runFlag) { + case 0: + return "投运"; + case 1: + return "热备用"; + case 2: + return "停运"; + default: + return ""; + } + } + + //监测点运行状态(0:投运;1:检修;2:停运;3:调试;4:退运) + public static String lineRunFlag(Integer runFlag) { + switch (runFlag) { + case 0: + return "投运"; + case 1: + return "检修"; + case 2: + return "停运"; + case 3: + return "调试"; + case 4: + return "退运"; + default: + return ""; + } + } + + public static Integer getRunFlag(String runFlag) { + switch (runFlag) { + case "投运": + return 0; + case "热备用": + return 1; + case "停运": + return 2; + default: + return -1; + } + } + + + public static String ptType(Integer ptType) { + switch (ptType) { + case 0: + return "星型接线"; + case 1: + return "三角型接线"; + case 2: + return "开口三角型接线"; + default: + return ""; + } + } + +} diff --git a/cn-user/.gitignore b/cn-user/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-user/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-user/pom.xml b/cn-user/pom.xml new file mode 100644 index 0000000..a943723 --- /dev/null +++ b/cn-user/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + + cn-user + 1.0.0 + cn-user + cn-user + + + + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/AuthController.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/AuthController.java new file mode 100644 index 0000000..6d33c2f --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/AuthController.java @@ -0,0 +1,146 @@ +//package com.njcn.product.cnuser.user.controller; +// +//import cn.hutool.core.date.DateUnit; +//import cn.hutool.core.util.ObjectUtil; +//import cn.hutool.core.util.StrUtil; +//import com.alibaba.fastjson.JSON; +//import com.njcn.common.bean.CustomCacheUtil; +//import com.njcn.common.pojo.annotation.OperateInfo; +//import com.njcn.common.pojo.constant.OperateType; +//import com.njcn.common.pojo.constant.SecurityConstants; +//import com.njcn.common.pojo.enums.common.LogEnum; +//import com.njcn.common.pojo.enums.response.CommonResponseEnum; +//import com.njcn.common.pojo.exception.BusinessException; +//import com.njcn.common.pojo.response.HttpResult; +//import com.njcn.common.utils.JwtUtil; +//import com.njcn.common.utils.LogUtil; +//import com.njcn.common.utils.RSAUtil; +//import com.njcn.product.cnuser.user.pojo.constant.UserValidMessage; +//import com.njcn.product.cnuser.user.pojo.param.SysUserParam; +//import com.njcn.product.cnuser.user.pojo.po.SysUser; +//import com.njcn.product.cnuser.user.pojo.po.Token; +//import com.njcn.product.cnuser.user.service.ISysUserService; +//import com.njcn.product.cnuser.user.pojo.enums.UserResponseEnum; +// +//import com.njcn.web.controller.BaseController; +//import com.njcn.web.utils.HttpResultUtil; +//import com.njcn.web.utils.RequestUtil; +//import io.swagger.annotations.Api; +//import io.swagger.annotations.ApiOperation; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.web.bind.annotation.*; +// +//import javax.servlet.http.HttpServletRequest; +//import java.security.KeyPair; +//import java.util.Base64; +//import java.util.HashMap; +//import java.util.Map; +// +// +//@Slf4j +//@RestController +//@Api(tags = "登录/注销") +//@RequestMapping("/admin") +//@RequiredArgsConstructor +//public class AuthController extends BaseController { +// +// private final ISysUserService sysUserService; +// private final CustomCacheUtil customCacheUtil; +// private KeyPair keyPair; +// +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.AUTHENTICATE) +// @PostMapping("/login") +// @ApiOperation("登录") +// public HttpResult login(@RequestBody SysUserParam.LoginParam param, HttpServletRequest request) { +// String methodDescribe = getMethodDescribe("login"); +// LogUtil.njcnDebug(log, "{},登录参数为:{}", methodDescribe, param); +// byte[] decode = Base64.getDecoder().decode(param.getUsername()); +// String username = new String(decode); +// String password = null; +// +// try { +// password = RSAUtil.decrypt(param.getPassword(), keyPair.getPrivate()); +// } catch (Exception e) { +// throw new BusinessException(UserResponseEnum.RSA_DECRYT_ERROR); +// } +// // 因不确定是否能登陆成功先将登陆名保存到request,一遍记录谁执行了登录操作 +// request.setAttribute(SecurityConstants.AUTHENTICATE_USERNAME, username); +// SysUser user = sysUserService.getUserByLoginNameAndPassword(username, password); +// if (ObjectUtil.isNull(user)) { +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, UserValidMessage.LOGIN_FAILED); +// } else { +// String accessToken = JwtUtil.getAccessToken(user.getId(),username); +// String refreshToken = JwtUtil.getRefreshToken(accessToken); +// Token token = new Token(); +// token.setAccessToken(accessToken); +// token.setRefreshToken(refreshToken); +// +// Map map = new HashMap<>(); +// map.put("name", user.getName()); +// map.put("id", user.getId()); +// map.put("loginName",user.getLoginName()); +// +// token.setUserInfo(map); +// +// customCacheUtil.putWithExpireTime(accessToken, JSON.toJSONString(user), DateUnit.DAY.getMillis() * Integer.MAX_VALUE); +// sysUserService.updateLoginTime(user.getId()); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, token, methodDescribe); +// } +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_SERIOUS, operateType = OperateType.LOGOUT) +// @ApiOperation("注销登录") +// @PostMapping("/logout") +// public HttpResult logout() { +// String methodDescribe = getMethodDescribe("logout"); +// LogUtil.njcnDebug(log, "{},注销登录", methodDescribe); +// String accessToken = RequestUtil.getAccessToken(); +// if (StrUtil.isNotBlank(accessToken)) { +// customCacheUtil.remove(accessToken); +// +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); +// } +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @ApiOperation("刷新accessToken") +// @GetMapping("/refreshToken") +// public HttpResult refreshToken(HttpServletRequest request) { +// String methodDescribe = getMethodDescribe("refreshToken"); +// LogUtil.njcnDebug(log, "{},刷新token", methodDescribe); +// String accessToken = RequestUtil.getAccessToken(); +// +// Token token = new Token(); +// if (StrUtil.isNotBlank(accessToken)) { +// Map map = JwtUtil.parseToken(accessToken); +// String userId = (String) map.get(SecurityConstants.USER_ID); +// SysUser user = sysUserService.getById(userId); +// String accessTokenNew = JwtUtil.getAccessToken(userId, user.getLoginName()); +// request.setAttribute(SecurityConstants.AUTHENTICATE_USERNAME, user.getLoginName()); +//// String refreshTokenNew = JwtUtil.getRefreshToken(accessTokenNew); +// +// token.setAccessToken(accessTokenNew); +// token.setRefreshToken(accessToken); +// +// customCacheUtil.putWithExpireTime(accessTokenNew, JSON.toJSONString(user), DateUnit.DAY.getMillis() * Integer.MAX_VALUE); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, token, methodDescribe); +// } else { +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); +// } +// } +// +// @OperateInfo(info = LogEnum.SYSTEM_COMMON) +// @ApiOperation("获取RSA公钥") +// @GetMapping("/getPublicKey") +// public HttpResult publicKey(@RequestParam("username") String username, HttpServletRequest request) throws Exception { +// String methodDescribe = getMethodDescribe("publicKey"); +// LogUtil.njcnDebug(log, "{},获取RSA公钥", methodDescribe); +// // 因不确定是否能登陆成功先将登陆名保存到request,一遍记录谁执行了登录操作 +// request.setAttribute(SecurityConstants.AUTHENTICATE_USERNAME, username); +// keyPair = RSAUtil.generateKeyPair(); +// return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, RSAUtil.publicKeyToString(keyPair.getPublic()), methodDescribe); +// } +//} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/DeptController.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/DeptController.java new file mode 100644 index 0000000..533c786 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/DeptController.java @@ -0,0 +1,70 @@ +package com.njcn.product.cnuser.user.controller; + + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.lang.tree.Tree; +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.constant.OperateType; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.product.cnuser.user.pojo.vo.DeptAllTreeVO; +import com.njcn.product.cnuser.user.service.IDeptService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.*; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import springfox.documentation.annotations.ApiIgnore; + +import java.util.List; +import java.util.Objects; + +/** + *

+ * 前端控制器(部门信息) + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Validated +@Slf4j +@RestController +@RequestMapping("/dept") +@Api(tags = "部门管理") +@AllArgsConstructor +public class DeptController extends BaseController { + + private final IDeptService deptService; + + + + + /** + * 根据登录用户获取部门树 + */ + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/loginDeptTree") + @ApiOperation("根据登录用户获取部门树") + public HttpResult loginDeptTree(@RequestParam("deptIndex")String deptIndex) { + String methodDescribe = getMethodDescribe("loginDeptTree"); + List result = deptService.loginDeptTree(deptIndex); + if (!result.isEmpty()) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } else { + + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe); + } + } + + + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysFunctionController.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysFunctionController.java new file mode 100644 index 0000000..a9a9540 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysFunctionController.java @@ -0,0 +1,168 @@ +package com.njcn.product.cnuser.user.controller; + +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.constant.SecurityConstants; +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.JwtUtil; +import com.njcn.common.utils.LogUtil; +import com.njcn.product.cnuser.user.pojo.param.SysFunctionParam; +import com.njcn.product.cnuser.user.pojo.param.SysRoleParam; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.vo.MenuVO; +import com.njcn.product.cnuser.user.service.ISysFunctionService; +import com.njcn.product.cnuser.user.service.ISysRoleFunctionService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.logging.log4j.util.Strings; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; + + +/** + * @author caozehui + * @date 2024-11-15 + */ +@Slf4j +@Api(tags = "菜单(资源)管理") +@RestController +@RequestMapping("/sysFunction") +@RequiredArgsConstructor +public class SysFunctionController extends BaseController { + private final ISysFunctionService sysFunctionService; + private final ISysRoleFunctionService sysRoleFunctionService; + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getTree") + @ApiOperation("按照名称模糊查询菜单树") + @ApiImplicitParam(name = "keyword", value = "查询参数", required = true) + public HttpResult> getFunctionTreeByKeyword(@RequestParam @Validated String keyword) { + String methodDescribe = getMethodDescribe("getFunctionTreeByKeyword"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, keyword); + List result = sysFunctionService.getFunctionTreeByKeyword(keyword); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/functionTreeNoButton") + @ApiOperation("菜单树-不包括按钮") + public HttpResult> getFunctionTreeNoButton() { + String methodDescribe = getMethodDescribe("getFunctionTreeNoButton"); + List list = sysFunctionService.getFunctionTree(false); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增菜单") + @ApiImplicitParam(name = "functionParam", value = "菜单数据", required = true) + public HttpResult add(@RequestBody @Validated SysFunctionParam functionParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},菜单数据为:{}", methodDescribe, functionParam); + boolean result = sysFunctionService.addFunction(functionParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改菜单") + @ApiImplicitParam(name = "functionParam", value = "菜单数据", required = true) + public HttpResult update(@RequestBody @Validated SysFunctionParam.UpdateParam functionParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},更新的菜单信息为:{}", methodDescribe, functionParam); + boolean result = sysFunctionService.updateFunction(functionParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) + @PostMapping("/delete") + @ApiOperation("删除菜单") + @ApiImplicitParam(name = "id", value = "菜单id", required = true) + public HttpResult delete(@RequestParam String id) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},删除的菜单id为:{}", methodDescribe, id); + boolean result = sysFunctionService.deleteFunction(id); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getMenu") + @ApiOperation("获取菜单") + public HttpResult> getMenu(HttpServletRequest request) { + String methodDescribe = getMethodDescribe("getMenu"); + String tokenStr = request.getHeader(SecurityConstants.AUTHORIZATION_KEY); + if (StrUtil.isNotBlank(tokenStr)) { + tokenStr = tokenStr.replace(SecurityConstants.AUTHORIZATION_PREFIX, Strings.EMPTY); + String userId = (String) (JwtUtil.parseToken(tokenStr).get("userId")); + List list = sysFunctionService.getMenuByUserId(userId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getButton") + @ApiOperation("获取按钮") + public HttpResult>> getButton(HttpServletRequest request) { + String methodDescribe = getMethodDescribe("getButton"); + String tokenStr = request.getHeader(SecurityConstants.AUTHORIZATION_KEY); + if (StrUtil.isNotBlank(tokenStr)) { + tokenStr = tokenStr.replace(SecurityConstants.AUTHORIZATION_PREFIX, Strings.EMPTY); + String userId = (String) JwtUtil.parseToken(tokenStr).get("userId"); + Map> map = sysFunctionService.getButtonByUserId(userId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, map, methodDescribe); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/getFunctionsByRoleId") + @ApiOperation("获取角色id绑定的菜单(资源)") + @ApiImplicitParam(name = "id", value = "角色id", required = true) + public HttpResult> getFunctionsByRoleId(@RequestParam @Validated String id) { + String methodDescribe = getMethodDescribe("getFunctionsByRoleId"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, id); + List sysFunctions = sysRoleFunctionService.listFunctionByRoleId(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, sysFunctions, methodDescribe); + } + + @OperateInfo(operateType = OperateType.UPDATE, info = LogEnum.SYSTEM_MEDIUM) + @PostMapping("/assignFunctionByRoleId") + @ApiOperation("角色分配菜单") + @ApiImplicitParam(name = "roleFunctionComponent", value = "角色信息", required = true) + public HttpResult assignFunctionByRoleId(@RequestBody @Validated SysRoleParam.RoleBindFunction param) { + String methodDescribe = getMethodDescribe("assignFunctionByRoleId"); + LogUtil.njcnDebug(log, "{},传入的角色id和资源id集合为:{}", methodDescribe, param); + boolean result = sysRoleFunctionService.updateRoleFunction(param.getRoleId(), param.getFunctionIds()); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysRoleController.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysRoleController.java new file mode 100644 index 0000000..bca2609 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysRoleController.java @@ -0,0 +1,104 @@ +package com.njcn.product.cnuser.user.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.product.cnuser.user.pojo.param.SysRoleParam; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.service.ISysRoleService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author caozehui + * @date 2024-11-11 + */ +@Slf4j +@Api(tags = "角色管理") +@RestController +@RequestMapping("/sysRole") +@RequiredArgsConstructor +public class SysRoleController extends BaseController { + private final ISysRoleService sysRoleService; + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/list") + @ApiOperation("分页查询角色") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> list(@RequestBody @Validated SysRoleParam.QueryParam queryParam) { + String methodDescribe = getMethodDescribe("list"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam); + Page result = sysRoleService.listRole(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增角色信息") + @ApiImplicitParam(name = "roleParam", value = "角色信息", required = true) + public HttpResult add(@RequestBody @Validated SysRoleParam sysRoleParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},角色信息数据为:{}", methodDescribe, sysRoleParam); + boolean result = sysRoleService.addRole(sysRoleParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改角色信息") + @ApiImplicitParam(name = "updateParam", value = "角色信息", required = true) + public HttpResult update(@RequestBody @Validated SysRoleParam.UpdateParam updateParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},角色信息数据为:{}", methodDescribe, updateParam); + boolean result = sysRoleService.updateRole(updateParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) + @PostMapping("/delete") + @ApiOperation("删除角色信息") + @ApiImplicitParam(name = "ids", value = "角色id集合", required = true) + public HttpResult delete(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},角色信息数据为:{}", methodDescribe, ids); + boolean result = sysRoleService.deleteRole(ids); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/simpleList") + @ApiOperation("查询所有角色作为下拉框") + public HttpResult> simpleList() { + String methodDescribe = getMethodDescribe("simpleList"); + List result = sysRoleService.simpleList(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysUserController.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysUserController.java new file mode 100644 index 0000000..e1ea0cc --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/controller/SysUserController.java @@ -0,0 +1,127 @@ +package com.njcn.product.cnuser.user.controller; + +import cn.hutool.core.util.StrUtil; +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.DataStateEnum; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.product.cnuser.user.pojo.param.SysUserParam; +import com.njcn.product.cnuser.user.pojo.po.SysUser; +import com.njcn.product.cnuser.user.service.ISysUserService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + + +/** + * @author caozehui + * @since 2024-11-08 + */ +@Slf4j +@Api(tags = "用户管理") +@RestController +@RequestMapping("/sysUser") +@RequiredArgsConstructor +public class SysUserController extends BaseController { + + private final ISysUserService sysUserService; + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @PostMapping("/list") + @ApiOperation("分页查询用户列表") + @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true) + public HttpResult> list(@RequestBody @Validated SysUserParam.SysUserQueryParam queryParam) { + String methodDescribe = getMethodDescribe("list"); + LogUtil.njcnDebug(log, "{},查询数据为:{}", methodDescribe, queryParam); + Page result = sysUserService.listUser(queryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.ADD) + @PostMapping("/add") + @ApiOperation("新增用户") + @ApiImplicitParam(name = "addUserParam", value = "新增用户", required = true) + public HttpResult add(@RequestBody @Validated SysUserParam.SysUserAddParam addUserParam) { + String methodDescribe = getMethodDescribe("add"); + LogUtil.njcnDebug(log, "{},用户数据为:{}", methodDescribe, addUserParam); + boolean result = sysUserService.addUser(addUserParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/update") + @ApiOperation("修改用户") + @ApiImplicitParam(name = "updateUserParam", value = "修改用户", required = true) + public HttpResult update(@RequestBody @Validated SysUserParam.SysUserUpdateParam updateUserParam) { + String methodDescribe = getMethodDescribe("update"); + LogUtil.njcnDebug(log, "{},用户数据为:{}", methodDescribe, updateUserParam); + boolean result = sysUserService.updateUser(updateUserParam); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.DELETE) + @PostMapping("/delete") + @ApiOperation("批量删除用户") + @ApiImplicitParam(name = "ids", value = "用户id", required = true) + public HttpResult delete(@RequestBody List ids) { + String methodDescribe = getMethodDescribe("delete"); + LogUtil.njcnDebug(log, "{},用户id为:{}", methodDescribe, String.join(StrUtil.COMMA, ids)); + boolean result = sysUserService.deleteUser(ids); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON, operateType = OperateType.UPDATE) + @PostMapping("/updatePassword") + @ApiOperation("修改密码") + @ApiImplicitParams({ + @ApiImplicitParam(name = "id", value = "用户id", required = true), + @ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true), + @ApiImplicitParam(name = "newPassword", value = "新密码", required = true) + }) + public HttpResult updatePassword(@RequestBody @Validated SysUserParam.SysUserUpdatePasswordParam param) { + String methodDescribe = getMethodDescribe("updatePassword"); + LogUtil.njcnDebug(log, "{},用户id:{},用户旧密码:{},新密码:{}", methodDescribe, param.getId(), param.getOldPassword(), param.getNewPassword()); + boolean result = sysUserService.updatePassword(param); + if (result) { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe); + } + } + + @OperateInfo(info = LogEnum.SYSTEM_COMMON) + @GetMapping("/getAll") + @ApiOperation("获取所有用户") + public HttpResult> getAll() { + String methodDescribe = getMethodDescribe("getAll"); + LogUtil.njcnDebug(log, "{},查询所有用户", methodDescribe); + List result = sysUserService.lambdaQuery().eq(SysUser::getState, DataStateEnum.ENABLE.getCode()).list(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/DeptMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/DeptMapper.java new file mode 100644 index 0000000..07a39d8 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/DeptMapper.java @@ -0,0 +1,36 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import com.njcn.product.cnuser.user.pojo.dto.DeptDTO; +import com.njcn.product.cnuser.user.pojo.po.Dept; +import com.njcn.product.cnuser.user.pojo.vo.DeptAllTreeVO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + *

+ * Mapper 接口 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface DeptMapper extends BaseMapper { + + /** + * 根据条件获取后代部门索引 + * @param id 部门id + * @param type 指定部门类型 + * @return 后代部门索引 + */ + List getDeptDescendantIndexes(@Param("id")String id, @Param("type")List type); + + /** + * + * @return 部门树 + */ + List getAllDeptTree(@Param("id")String id, @Param("type")List type); + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysFunctionMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysFunctionMapper.java new file mode 100644 index 0000000..3868d09 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysFunctionMapper.java @@ -0,0 +1,30 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.github.yulichang.base.MPJBaseMapper; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.vo.MenuVO; + + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface SysFunctionMapper extends MPJBaseMapper { + + /** + * 根据用户id获取菜单列表 + * @param userId 用户id + * @return 菜单列表 + */ + List getMenuByUserId(String userId); + + /* + * 根据用户id获取按钮列表 + * @param userId 用户id + * @return 按钮列表 + */ + List getButtonByUserId(String userId); +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleFunctionMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleFunctionMapper.java new file mode 100644 index 0000000..c48f674 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleFunctionMapper.java @@ -0,0 +1,24 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.github.yulichang.base.MPJBaseMapper; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.po.SysRoleFunction; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface SysRoleFunctionMapper extends MPJBaseMapper { + + /** + * 根据角色id获取角色拥有的菜单(资源)列表 + * + * @param roleId 角色id + * @return 角色拥有的菜单(资源)列表 + */ + List getFunctionListByRoleId(@Param("roleId") String roleId); +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleMapper.java new file mode 100644 index 0000000..1eb8c43 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysRoleMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.github.yulichang.base.MPJBaseMapper; +import com.njcn.product.cnuser.user.pojo.po.SysRole; + +/** + * @author caozehui + * @date 2024-11-11 + */ +public interface SysRoleMapper extends MPJBaseMapper { + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserMapper.java new file mode 100644 index 0000000..a7bdc10 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.github.yulichang.base.MPJBaseMapper; +import com.njcn.product.cnuser.user.pojo.po.SysUser; + +/** + * @author caozehui + * @since 2024-11-08 + */ +public interface SysUserMapper extends MPJBaseMapper { + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserRoleMapper.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserRoleMapper.java new file mode 100644 index 0000000..a396798 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/SysUserRoleMapper.java @@ -0,0 +1,23 @@ +package com.njcn.product.cnuser.user.mapper; + +import com.github.yulichang.base.MPJBaseMapper; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.pojo.po.SysUserRole; + + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface SysUserRoleMapper extends MPJBaseMapper { + /** + * 根据用户id获取角色详情 + * + * @param userId 用户id + * @return 角色结果集 + */ + List getRoleListByUserId(String userId); +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysFunctionMapper.xml b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysFunctionMapper.xml new file mode 100644 index 0000000..dc69943 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysFunctionMapper.xml @@ -0,0 +1,31 @@ + + + + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleFunctionMapper.xml b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleFunctionMapper.xml new file mode 100644 index 0000000..8558246 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleFunctionMapper.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleMapper.xml b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleMapper.xml new file mode 100644 index 0000000..4b3edc2 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysRoleMapper.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserMapper.xml b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserMapper.xml new file mode 100644 index 0000000..bba56ac --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserMapper.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserRoleMapper.xml b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserRoleMapper.xml new file mode 100644 index 0000000..cf2176f --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/mapper/mapping/SysUserRoleMapper.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/FunctionConst.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/FunctionConst.java new file mode 100644 index 0000000..4ba74c6 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/FunctionConst.java @@ -0,0 +1,33 @@ +package com.njcn.product.cnuser.user.pojo.constant; + +/** + * @author caozehui + * @data 2024/11/12 + */ +public interface FunctionConst { + /** + * 资源类型:0-菜单 + */ + int TYPE_MENU =0; + + /** + * 资源类型:1-按钮 + */ + int TYPE_BUTTON =1; + + /** + * 资源类型:2-公共资源 + */ + int TYPE_PUBLIC =2; + + /** + * 资源类型:3-服务间调用资源 + */ + int TYPE_SERVICE_INVOKE_FUNCTION =3; + + /** + * 顶级父节点ID + */ + String FATHER_PID = "0"; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/RoleConst.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/RoleConst.java new file mode 100644 index 0000000..4522cd2 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/RoleConst.java @@ -0,0 +1,28 @@ +package com.njcn.product.cnuser.user.pojo.constant; + +/** + * @author caozehui + * @data 2024/11/11 + */ +public interface RoleConst { + /** + * 角色类型:0-超级管理员 + */ + int TYPE_SUPER_ADMINISTRATOR = 0; + + /** + * 角色类型:1-管理员 + */ + int TYPE_ADMINISTRATOR = 1; + + /** + * 角色类型:2-用户 + */ + int TYPE_USER = 2; + + /** + * 角色类型:3-APP角色 + */ + int TYPE_APP = 3; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserConst.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserConst.java new file mode 100644 index 0000000..c593567 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserConst.java @@ -0,0 +1,16 @@ +package com.njcn.product.cnuser.user.pojo.constant; + +/** + * @author caozehui + * @data 2024/11/11 + */ +public interface UserConst { + Integer STATE_DELETE = 0; + Integer STATE_ENABLE = 1; + Integer STATE_LOCKED = 2; + Integer STATE_WAITING_FOR_APPROVAL = 3; + Integer STATE_SLEEPING = 4; + Integer STATE_PASSWORD_EXPIRED = 5; + + String SUPER_ADMIN = "root"; +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserValidMessage.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserValidMessage.java new file mode 100644 index 0000000..31877ac --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/constant/UserValidMessage.java @@ -0,0 +1,49 @@ +package com.njcn.product.cnuser.user.pojo.constant; + +/** + * @author caozehui + * @data 2024/11/8 + */ +public interface UserValidMessage { + + String ID_NOT_BLANK = "id不能为空,请检查id参数"; + + String ID_FORMAT_ERROR = "id格式错误,请检查id参数"; + + String DEPT_ID_FORMAT_ERROR = "部门id格式错误,请检查deptId参数"; + + String NAME_NOT_BLANK = "名称不能为空,请检查name参数"; + + String NAME_FORMAT_ERROR = "名称格式错误,请检查name参数"; + + String CODE_NOT_BLANK = "编码不能为空,请检查code参数"; + + String LOGIN_NAME_NOT_BLANK = "登录名不能为空,请检查loginName参数"; + + String LOGIN_NAME_FORMAT_ERROR = "登录名格式错误,需以字母开头,长度为3-16位的字母或数字"; + + String PASSWORD_NOT_BLANK = "密码不能为空,请检查password参数"; + + String PASSWORD_FORMAT_ERROR = "密码格式错误,需要包含特殊字符字母数字8-16位"; + + String PHONE_FORMAT_ERROR = "电话号码格式错误,请检查phone参数"; + + String EMAIL_FORMAT_ERROR = "邮箱格式错误,请检查email参数"; + + String OLD_PASSWORD_NOT_BLANK = "旧密码不能为空,请检查oldPassword参数"; + + String NEW_PASSWORD_NOT_BLANK = "新密码不能为空,请检查newPassword参数"; + + String PID_NOT_BLANK = "父节点id不能为空,请检查pid参数"; + + String SORT_NOT_NULL = "排序不能为空,请检查sort参数"; + + String TYPE_NOT_BLANK = "类型不能为空,请检查type参数"; + + String PARAM_FORMAT_ERROR = "参数值非法"; + + String LOGIN_FAILED = "登录失败,用户名或密码错误"; + + String FUNCTION_NAME_FORMAT_ERROR = "菜单名称格式错误,只能包含字母、数字、中文、下划线、中划线、空格,长度为1-32个字符"; + String FUNCTION_CODE_FORMAT_ERROR = "菜单编码格式错误,只能包含字母、数字、下划线、中划线、空格,长度为1-32个字符"; +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/DeptDTO.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/DeptDTO.java new file mode 100644 index 0000000..003369a --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/DeptDTO.java @@ -0,0 +1,46 @@ +package com.njcn.product.cnuser.user.pojo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2022年02月11日 14:08 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class DeptDTO implements Serializable { + + private String id; + + private String pid; + + private String pids; + + private String name; + + private String code; + + /** + * 专项分析类型区分 + */ + private Integer specialType; + + private String area; + + private String remark; + + private Integer sort; + + /** + * 部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + */ + private Integer type; + + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/UserDTO.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/UserDTO.java new file mode 100644 index 0000000..fc94173 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/dto/UserDTO.java @@ -0,0 +1,48 @@ +package com.njcn.product.cnuser.user.pojo.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年05月08日 15:12 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class UserDTO { + + private String userIndex; + + private String username; + + private String nickname; + + private String password; + + /** + * 角色集合 + */ + private List roleName; + + /** + * sm4加密秘钥 + */ + private String secretKey; + + /** + * sm4中间过程校验 + */ + private String standBy; + + private String deptIndex; + + private Integer type; + + private String headSculpture; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/enums/UserResponseEnum.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/enums/UserResponseEnum.java new file mode 100644 index 0000000..6d691ae --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/enums/UserResponseEnum.java @@ -0,0 +1,37 @@ +package com.njcn.product.cnuser.user.pojo.enums; + +import lombok.Getter; + +/** + * @author caozehui + * @data 2024/11/9 + */ +@Getter +public enum UserResponseEnum { + LOGIN_NAME_REPEAT("A010001", "登录名重复,请检查loginName参数"), + REGISTER_PHONE_FAIL("A010002", "该号码已被注册"), + USER_NAME_REPEAT("A010003", "用户名重复,请检查name参数"), + REGISTER_EMAIL_FAIL("A010004", "该邮箱已被注册"), + NAME_OR_CODE_REPEAT("A010005", "名称或编码已存在"), + EXISTS_SAME_MENU_CHILDREN("A010006", "该层级下已存在相同名称或相同编码或相同路径或相同组件地址的菜单"), + EXISTS_CHILDREN_NOT_UPDATE("A010008", "该菜单下存在子节点,无法将菜单修改为按钮"), + EXISTS_CHILDREN_NOT_DELETE("A010007", "该节点下存在子节点,无法删除"), + SUPER_ADMINSTRATOR_ROLE_CANNOT_UPDATE("A010009", "禁止修改超级管理员角色"), + SUPER_ADMINSTRATOR_ROLE_CANNOT_DELETE("A010009", "禁止删除超级管理员角色"), + SUPER_ADMIN_CANNOT_DELETE("A010010", "禁止删除超级管理员用户"), + COMPONENT_NOT_BLANK("A010011", "组件地址不能为空"), + FUNCTION_PATH_FORMAT_ERROR("A010012", "菜单路由地址格式错误,只能包含字母、数字、下划线、中划线、空格、斜线、反斜线,长度为1-32个字符"), + FUNCTION_COMPONENT_FORMAT_ERROR("A010013","菜单组件地址格式错误,只能包含字母、数字、下划线、中划线、空格、斜线、反斜线,长度为1-32个字符" ), + SUPER_ADMIN_REPEAT("A010013","超级管理员已存在,请勿重复添加" ), + RSA_DECRYT_ERROR("A010014","RSA解密失败" ), + PASSWORD_SAME("A010015", "新密码不能与旧密码相同"), + OLD_PASSWORD_ERROR("A010016", "旧密码错误"), ; + + private String code; + private String message; + + UserResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysFunctionParam.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysFunctionParam.java new file mode 100644 index 0000000..9149efa --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysFunctionParam.java @@ -0,0 +1,74 @@ +package com.njcn.product.cnuser.user.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.cnuser.user.pojo.constant.UserValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +/** + * @author caozehui + * @data 2024/11/12 + */ +@Data +public class SysFunctionParam { + @ApiModelProperty("父节点") + @NotBlank(message = UserValidMessage.PID_NOT_BLANK) + private String pid; + + @ApiModelProperty("名称") + @NotBlank(message = UserValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.FUNCTION_NAME_REGEX, message = UserValidMessage.FUNCTION_NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("编码") + @NotBlank(message = UserValidMessage.CODE_NOT_BLANK) + @Pattern(regexp = PatternRegex.FUNCTION_CODE_REGEX, message = UserValidMessage.FUNCTION_CODE_FORMAT_ERROR) + private String code; + + @ApiModelProperty("路径") + private String path; + + @ApiModelProperty("组件地址") + private String component; + + @ApiModelProperty("图标") + private String icon; + + @ApiModelProperty("排序") + @NotNull(message = UserValidMessage.SORT_NOT_NULL) + @Range(min = 0, max = 999, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer sort; + + @ApiModelProperty("资源类型") + @NotNull(message = UserValidMessage.TYPE_NOT_BLANK) + @Range(min = 0, max = 3, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer type; + + @ApiModelProperty("描述") + private String remark; + + @Data + @EqualsAndHashCode(callSuper = true) + public static class QueryParam extends BaseParam { + @ApiModelProperty("名称") + @Pattern(regexp = PatternRegex.FUNCTION_NAME_REGEX, message = UserValidMessage.FUNCTION_NAME_FORMAT_ERROR) + private String name; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class UpdateParam extends SysFunctionParam { + + @ApiModelProperty("id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.ID_FORMAT_ERROR) + private String id; + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysRoleParam.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysRoleParam.java new file mode 100644 index 0000000..d55a9cd --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysRoleParam.java @@ -0,0 +1,83 @@ +package com.njcn.product.cnuser.user.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.cnuser.user.pojo.constant.UserValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Range; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * @author caozehui + * @data 2024/11/11 + */ +@Data +public class SysRoleParam { + + + @ApiModelProperty("名称") + @NotBlank(message = UserValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.DEPT_NAME_REGEX, message = UserValidMessage.NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("编码") + @NotNull(message = UserValidMessage.CODE_NOT_BLANK) + private String code; + + /** + * 角色类型 0:超级管理员;1:管理员;2:普通用户 + */ + @ApiModelProperty("类型") + @Range(min = 0, max = 2, message = UserValidMessage.PARAM_FORMAT_ERROR) + private Integer type; + + @ApiModelProperty("描述") + private String remark; + + /** + * 更新操作实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class UpdateParam extends SysRoleParam { + + @ApiModelProperty("id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.ID_FORMAT_ERROR) + private String id; + + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class QueryParam extends BaseParam { + @ApiModelProperty("名称") + private String name; + + @ApiModelProperty("编码") + private String code; + + @ApiModelProperty("类型") + private Integer type; + } + + /** + * 角色绑定菜单(资源)参数 + */ + @Data + public static class RoleBindFunction { + @ApiModelProperty("角色id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.ID_FORMAT_ERROR) + private String roleId; + + @ApiModelProperty("菜单ids") + private List functionIds; + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysUserParam.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysUserParam.java new file mode 100644 index 0000000..e98c8dc --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/param/SysUserParam.java @@ -0,0 +1,104 @@ +package com.njcn.product.cnuser.user.pojo.param; + +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.product.cnuser.user.pojo.constant.UserValidMessage; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.List; + +/** + * @author caozehui + * @data 2024/11/8 + */ +@Data +public class SysUserParam { + + @ApiModelProperty("用户名(别名)") + @NotBlank(message = UserValidMessage.NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.USERNAME_REGEX, message = UserValidMessage.NAME_FORMAT_ERROR) + private String name; + + @ApiModelProperty("部门Id") + private String deptId; + + @ApiModelProperty("电话号码") + @Pattern(regexp = PatternRegex.PHONE_REGEX_OR_NULL, message = UserValidMessage.PHONE_FORMAT_ERROR) + private String phone; + + @ApiModelProperty("邮箱") + @Pattern(regexp = PatternRegex.EMAIL_REGEX_OR_NULL, message = UserValidMessage.EMAIL_FORMAT_ERROR) + private String email; + + @ApiModelProperty("角色ids") + private List roleIds; + + @Data + @EqualsAndHashCode(callSuper = true) + public static class SysUserAddParam extends SysUserParam { + + @ApiModelProperty("登录名") + @NotBlank(message = UserValidMessage.LOGIN_NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.LOGIN_NAME_REGEX, message = UserValidMessage.LOGIN_NAME_FORMAT_ERROR) + private String loginName; + + @ApiModelProperty("密码") + @NotBlank(message = UserValidMessage.PASSWORD_NOT_BLANK) + @Pattern(regexp = PatternRegex.PASSWORD_REGEX, message = UserValidMessage.PASSWORD_FORMAT_ERROR) + private String password; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class SysUserUpdateParam extends SysUserParam { + + @ApiModelProperty("用户表Id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.ID_FORMAT_ERROR) + private String id; + + } + + @Data + public static class SysUserUpdatePasswordParam { + @ApiModelProperty("用户Id") + @NotBlank(message = UserValidMessage.ID_NOT_BLANK) + @Pattern(regexp = PatternRegex.SYSTEM_ID, message = UserValidMessage.ID_FORMAT_ERROR) + private String id; + + @ApiModelProperty("旧密码") + @NotBlank(message = UserValidMessage.OLD_PASSWORD_NOT_BLANK) + @Pattern(regexp = PatternRegex.PASSWORD_REGEX, message = UserValidMessage.PASSWORD_FORMAT_ERROR) + private String oldPassword; + + @ApiModelProperty("新密码") + @NotBlank(message = UserValidMessage.NEW_PASSWORD_NOT_BLANK) + @Pattern(regexp = PatternRegex.PASSWORD_REGEX, message = UserValidMessage.PASSWORD_FORMAT_ERROR) + private String newPassword; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class SysUserQueryParam extends BaseParam { + @ApiModelProperty("用户名(别名)") + private String name; + + } + + @Data + public static class LoginParam { + @ApiModelProperty("登录名") + @NotBlank(message = UserValidMessage.LOGIN_NAME_NOT_BLANK) + @Pattern(regexp = PatternRegex.LOGIN_NAME_REGEX, message = UserValidMessage.LOGIN_NAME_FORMAT_ERROR) + private String username; + + @ApiModelProperty("密码") + @NotBlank(message = UserValidMessage.PASSWORD_NOT_BLANK) + @Pattern(regexp = PatternRegex.PASSWORD_REGEX, message = UserValidMessage.PASSWORD_FORMAT_ERROR) + private String password; + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Dept.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Dept.java new file mode 100644 index 0000000..d19a542 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Dept.java @@ -0,0 +1,75 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * + * @author hongawen + * @since 2021-12-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_dept") +public class Dept extends BaseEntity { + + private static final long serialVersionUID = 1L; + + /** + * 部门表Id + */ + private String id; + + /** + * 父节点Id(0为根节点) + */ + private String pid; + + /** + * 上层所有节点Id + */ + private String pids; + + /** + * 部门名称 + */ + private String name; + + /** + * 部门编号 + */ + private String code; + + /** + * 专项分析类型区分 + */ + private Integer specialType; + + /** + * (sys_Area)行政区域Id,自定义部门无需填写部门 + */ + private String area; + + /** + * 部门类型 0-非自定义;1-web自定义;2-App自定义;3-web测试 + */ + private Integer type; + + /** + * 排序 + */ + private Integer sort; + + /** + * 部门描述 + */ + private String remark; + + /** + * 部门状态 0-删除;1-正常;默认正常 + */ + private Integer state; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysFunction.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysFunction.java new file mode 100644 index 0000000..f6ad2a6 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysFunction.java @@ -0,0 +1,88 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-15 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_function") +public class SysFunction extends BaseEntity implements Serializable { + private static final long serialVersionUID = -30909841321495323L; + + /** + * 资源表Id + */ + private String id; + + /** + * 节点(0为根节点) + */ + private String pid; + + /** + * 上层所有节点 + */ + private String pids; + + /** + * 名称 + */ + private String name; + + /** + * 编码 + */ + private String code; + + /** + * 路径 + */ + private String path; + + /** + * 组件地址 + */ + private String component; + + /** + * 图标(没有图标默认为:“Null”) + */ + private String icon; + + /** + * 排序 + */ + private Integer sort; + + /** + * 资源类型:0-菜单、1-按钮、2-公共资源、3-服务间调用资源 + */ + private Integer type; + + /** + * 权限资源描述 + */ + private String remark; + + /** + * 权限资源状态:0-删除 1-正常 + */ + private Integer state; + + /** + * 子节点 + */ + @TableField(exist = false) + private List children; +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRole.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRole.java new file mode 100644 index 0000000..b16a58f --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRole.java @@ -0,0 +1,50 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; + +/** + * @author caozehui + * @date 2024-11-11 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_role") +public class SysRole extends BaseEntity implements Serializable { + private static final long serialVersionUID = 183697621480953314L; + + /** + * 角色表Id + */ + private String id; + + /** + * 角色名称 + */ + private String name; + + /** + * 编码,有需要用做匹配时候用(关联字典表id) + */ + private String code; + + /** + * 类型:0-超级管理员;1-管理员角色;2-普通角色,默认普通角色 + */ + private Integer type; + + /** + * 描述 + */ + private String remark; + + /** + * 状态:0-删除;1-正常;默认正常 + */ + private Integer state; +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRoleFunction.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRoleFunction.java new file mode 100644 index 0000000..4c7541f --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysRoleFunction.java @@ -0,0 +1,27 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author caozehui + * @date 2024-11-15 + */ +@Data +@TableName("sys_role_function") +public class SysRoleFunction implements Serializable { + private static final long serialVersionUID = -32044506851166587L; + /** + * 角色表Id + */ + private String roleId; + + /** + * 资源表Id + */ + private String functionId; + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUser.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUser.java new file mode 100644 index 0000000..beb8890 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUser.java @@ -0,0 +1,97 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import java.time.LocalDateTime; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.List; + +/** + * @author caozehui + * @since 2024-11-08 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("sys_user") +public class SysUser extends BaseEntity implements Serializable { + + private static final long serialVersionUID = -54771740356521149L; + + /** + * 用户表Id + */ + private String id; + + /** + * 用户名(别名) + */ + private String name; + + /** + * 登录名 + */ + private String loginName; + + /** + * 密码 + */ + private String password; + + /** + * 部门Id + */ + private String deptId; + + /** + * 电话号码 + */ + private String phone; + + /** + * 邮箱 + */ + private String email; + + /** + * 最后一次登录时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JsonDeserialize(using = LocalDateTimeDeserializer.class) + @JsonSerialize(using = LocalDateTimeSerializer.class) + private LocalDateTime loginTime; + + /** + * 密码错误次数 + */ + private Integer loginErrorTimes; + + /** + * 用户密码错误锁定时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @JsonDeserialize(using = LocalDateTimeDeserializer.class) + @JsonSerialize(using = LocalDateTimeSerializer.class) + private LocalDateTime lockTime; + + /** + * 用户状态 0-删除;1-正常;2-锁定;3-待审核;4-休眠;5-密码过期 + */ + private Integer state; + + @TableField(exist = false) + private List roleIds; + + @TableField(exist = false) + private List roleNames; +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUserRole.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUserRole.java new file mode 100644 index 0000000..a315a8e --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/SysUserRole.java @@ -0,0 +1,27 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @author caozehui + * @date 2024-11-12 + */ +@Data +@TableName("sys_user_role") +public class SysUserRole implements Serializable { + private static final long serialVersionUID = 725290952766199948L; + /** + * 用户Id + */ + private String userId; + + /** + * 角色Id + */ + private String roleId; + +} + diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Token.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Token.java new file mode 100644 index 0000000..e7335b4 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/po/Token.java @@ -0,0 +1,16 @@ +package com.njcn.product.cnuser.user.pojo.po; + +import lombok.Data; + +import java.util.Map; + +@Data +public class Token { + + private String accessToken; + + private String refreshToken; + + private Map userInfo; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/DeptAllTreeVO.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/DeptAllTreeVO.java new file mode 100644 index 0000000..51f6eec --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/DeptAllTreeVO.java @@ -0,0 +1,32 @@ +package com.njcn.product.cnuser.user.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author denghuajun + * @version 1.0.0 + * @date 2022年04月15日 11:28 + */ +@Data +public class DeptAllTreeVO { + + @ApiModelProperty("id") + private String id; + + @ApiModelProperty("名称") + private String name; + + @ApiModelProperty("父节点id") + private String pid; + + @ApiModelProperty("父节点集合") + private String pids; + + private Integer sort; + + @ApiModelProperty("子节点详细信息") + private List children; +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MenuVO.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MenuVO.java new file mode 100644 index 0000000..a1cf148 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MenuVO.java @@ -0,0 +1,13 @@ +package com.njcn.product.cnuser.user.pojo.vo; + +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.vo.MetaVO; +import lombok.Data; + +@Data +public class MenuVO extends SysFunction { + + private String redirect; + + private MetaVO meta; +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MetaVO.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MetaVO.java new file mode 100644 index 0000000..11d6666 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/pojo/vo/MetaVO.java @@ -0,0 +1,49 @@ +package com.njcn.product.cnuser.user.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class MetaVO { + + /** + * 菜单和面包屑对应的图标 + */ + private String icon; + + /** + * 路由标题 (用作 document.title || 菜单的名称) + */ + private String title; + + /** + * 路由外链时填写的访问地址 + */ + @JsonProperty("isLink") + private String isLink; + + /** + * 是否在菜单中隐藏 (通常列表详情页需要隐藏) + */ + @JsonProperty("isHide") + private boolean isHide; + + /** + * 菜单是否全屏 (示例:数据大屏页面) + */ + @JsonProperty("isFull") + private boolean isFull; + + /** + * 菜单是否固定在标签页中 (首页通常是固定项) + */ + @JsonProperty("isAffix") + private boolean isAffix; + + /** + * 当前路由是否缓存 + */ + @JsonProperty("isKeepAlive") + private boolean isKeepAlive; + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/IDeptService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/IDeptService.java new file mode 100644 index 0000000..fe1cf4f --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/IDeptService.java @@ -0,0 +1,29 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.po.Dept; +import com.njcn.product.cnuser.user.pojo.vo.DeptAllTreeVO; + + +import java.util.List; + +/** + *

+ * 服务类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +public interface IDeptService extends IService { + + + /** + * 根据登录用户获取区域树 + * @return 结果 + */ + List loginDeptTree(String deptIndex); + + + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysFunctionService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysFunctionService.java new file mode 100644 index 0000000..872e210 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysFunctionService.java @@ -0,0 +1,71 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.param.SysFunctionParam; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.vo.MenuVO; + + +import java.util.List; +import java.util.Map; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface ISysFunctionService extends IService { + + /** + * 根据关键字模糊查询菜单(资源)树 + * + * @param keyword 关键字 + * @return 菜单(资源)树 + */ + List getFunctionTreeByKeyword(String keyword); + + /** + * 添加菜单(资源) + * + * @param functionParam 资源参数 + * @return 是否添加成功 + */ + boolean addFunction(SysFunctionParam functionParam); + + /** + * 修改菜单(资源) + * + * @param functionParam 资源参数 + * @return 是否更新成功 + */ + boolean updateFunction(SysFunctionParam.UpdateParam functionParam); + + /** + * 删除菜单(资源) + * + * @param id 资源id + */ + boolean deleteFunction(String id); + + /** + * 获取树形结构的菜单(资源 + * + * @param isContainButton 是否包含按钮 + * @return 树形结构的资源 + */ + List getFunctionTree(boolean isContainButton); + + /** + * 根据用户id获取菜单 + * + * @return 路由菜单 + */ + List getMenuByUserId(String userId); + + /** + * 根据用户id获取按钮 + * @param userId 用户id + * @return 按钮 + */ + Map> getButtonByUserId(String userId); + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleFunctionService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleFunctionService.java new file mode 100644 index 0000000..5b082fc --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleFunctionService.java @@ -0,0 +1,47 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.po.SysRoleFunction; + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface ISysRoleFunctionService extends IService { + + /** + * 获取角色id绑定的菜单(资源) + * + * @param roleId 角色id + * @return 菜单(资源)列表 + */ + List listFunctionByRoleId(String roleId); + + /** + * 更新角色菜单(资源)关联数据 + * + * @param roleId 角色id + * @param functionIds 菜单(资源)ids + * @return 成功返回true,失败返回false + */ + boolean updateRoleFunction(String roleId, List functionIds); + + /** + * 根据角色ids删除角色资源关联数据 + * + * @param roleIds + * @return 成功返回true,失败返回false + */ + boolean deleteRoleFunctionByRoleIds(List roleIds); + + /** + * 根据菜单(资源)ids删除角色资源关联数据 + * + * @param functionIds 菜单(资源)ids + * @return 成功返回true,失败返回false + */ + boolean deleteRoleFunctionByFunctionIds(List functionIds); +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleService.java new file mode 100644 index 0000000..a95abfe --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysRoleService.java @@ -0,0 +1,53 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.param.SysRoleParam; +import com.njcn.product.cnuser.user.pojo.po.SysRole; + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-11 + */ +public interface ISysRoleService extends IService { + + /** + * 分页查询角色列表 + * + * @param queryParam 查询参数 + */ + Page listRole(SysRoleParam.QueryParam queryParam); + + /** + * 新增角色 + * + * @param sysRoleParam 角色参数 + * @return 是否成功 + */ + boolean addRole(SysRoleParam sysRoleParam); + + /** + * 更新角色 + * + * @param updateParam 更新参数 + * @return 是否成功 + */ + boolean updateRole(SysRoleParam.UpdateParam updateParam); + + /** + * 删除角色 + * + * @param ids 角色id列表 + * @return 是否成功 + */ + boolean deleteRole(List ids); + + /** + * 查询所有角色作为下拉框 + * + * @return 角色列表 + */ + List simpleList(); +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserRoleService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserRoleService.java new file mode 100644 index 0000000..b5eb954 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserRoleService.java @@ -0,0 +1,56 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.pojo.po.SysUserRole; + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +public interface ISysUserRoleService extends IService { + + /** + * 根据用户id获取角色 + * + * @param userId 用户id + * @return 角色信息 + */ + List listRoleByUserId(String userId); + + /** + * 新增用户角色关联数据 + * + * @param userId 用户id + * @param roleIds 角色id + * @return 成功返回true,失败返回false + */ + boolean addUserRole(String userId, List roleIds); + + /** + * 修改用户角色关联数据 + * + * @param userId 用户id + * @param roleIds 角色id + * @return 成功返回true,失败返回false + */ + boolean updateUserRole(String userId, List roleIds); + + /** + * 根据用户id删除用户角色关联数据 + * + * @param userIds 用户ids + * @return 成功返回true,失败返回false + */ + boolean deleteUserRoleByUserIds(List userIds); + + /** + * 根据角色id删除用户角色关联数据 + * + * @param roleIds 角色ids + * @return 成功返回true,失败返回false + */ + boolean deleteUserRoleByRoleIds(List roleIds); +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserService.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserService.java new file mode 100644 index 0000000..66f1d22 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/ISysUserService.java @@ -0,0 +1,106 @@ +package com.njcn.product.cnuser.user.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnuser.user.pojo.param.SysUserParam; +import com.njcn.product.cnuser.user.pojo.po.SysUser; + +import java.util.List; + +/** + * @author caozehui + * @since 2024-11-08 + */ +public interface ISysUserService extends IService { + + /** + * 分页查询用户列表 + * + * @param queryParam 分页查询参数 + * @return 分页查询结果 + */ + Page listUser(SysUserParam.SysUserQueryParam queryParam); + + /** + * 根据登录名查询用户 + * + * @param loginName + * @return 用户对象,如果没有查询到则返回null + */ + SysUser getUserByLoginName(String loginName); + + /** + * 根据手机号查询用户 + * + * @param phone 手机号 + * @param isExcludeSelf 是否排除自己 + * @param id 排除自己时需要传入自己的ID + * @return 用户对象,如果没有查询到则返回null + */ + SysUser getUserByPhone(String phone, boolean isExcludeSelf, String id); + + /** + * 根据用户名(别名)查询用户 + * + * @param name 用户名(别名) + * @param isExcludeSelf 是否排除自己 + * @param id 排除自己时需要传入自己的ID + * @return 用户对象,如果没有查询到则返回null + */ + SysUser getUserByName(String name, boolean isExcludeSelf, String id); + + /** + * 根据邮箱查询用户 + * @param email 邮箱 + * @param isExcludeSelf 是否排除自己 + * @param id 排除自己时需要传入自己的ID + * @return 用户对象,如果没有查询到则返回null + */ + SysUser getUserByEmail(String email, boolean isExcludeSelf, String id); + + /** + * 新增用户 + * + * @param addUserParam 新增用户参数 + * @return 结果,true表示新增成功,false表示新增失败 + */ + boolean addUser(SysUserParam.SysUserAddParam addUserParam); + + /** + * 更新用户 + * + * @param updateUserParam 更新用户参数 + * @return 结果,true表示更新成功,false表示更新失败 + */ + boolean updateUser(SysUserParam.SysUserUpdateParam updateUserParam); + + /** + * 修改密码 + * @return 结果,true表示修改成功,false表示修改失败 + */ + boolean updatePassword(SysUserParam.SysUserUpdatePasswordParam param); + + /** + * 批量删除用户 + * + * @param ids 用户ID列表 + * @return 结果,true表示删除成功,false表示删除失败 + */ + boolean deleteUser(List ids); + + /** + * 根据登录名和密码查询用户 + * + * @param loginName 登录名 + * @param password 密码 + * @return 用户对象,如果没有查询到则返回null + */ + SysUser getUserByLoginNameAndPassword(String loginName, String password); + + /** + * 更新用户登录时间为当前时间 + * + * @param userId + */ + boolean updateLoginTime(String userId); +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/DeptServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/DeptServiceImpl.java new file mode 100644 index 0000000..615cae1 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/DeptServiceImpl.java @@ -0,0 +1,75 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.lang.tree.Tree; +import cn.hutool.core.lang.tree.TreeNode; +import cn.hutool.core.lang.tree.TreeUtil; +import cn.hutool.core.text.StrPool; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; + +import com.njcn.product.cnuser.user.mapper.DeptMapper; +import com.njcn.product.cnuser.user.pojo.po.Dept; +import com.njcn.product.cnuser.user.pojo.vo.DeptAllTreeVO; +import com.njcn.product.cnuser.user.service.IDeptService; +import com.njcn.web.factory.PageFactory; +import com.njcn.web.utils.RequestUtil; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + *

+ * 服务实现类 + *

+ * + * @author hongawen + * @since 2021-12-13 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeptServiceImpl extends ServiceImpl implements IDeptService { + + + + + + + @Override + public List loginDeptTree(String deptIndex) { + List deptList = this.baseMapper.getAllDeptTree(deptIndex, Stream.of(0).collect(Collectors.toList())); + return deptList.stream() + .filter(deptVO -> deptVO.getId().equals(deptIndex)) + .peek(deptFirst -> deptFirst.setChildren(getChildrens(deptFirst, deptList))) + .collect(Collectors.toList()); + } + + /** + * 递归查找所有部门的下级部门 + */ + private List getChildrens(DeptAllTreeVO deptFirst, List allDept) { + return allDept.stream().filter(dept -> dept.getPid().equals(deptFirst.getId())) + .peek(deptVo -> { + deptVo.setChildren(getChildrens(deptVo, allDept)); + }).sorted(Comparator.comparing(DeptAllTreeVO::getSort)).collect(Collectors.toList()); + } + + +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysFunctionServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysFunctionServiceImpl.java new file mode 100644 index 0000000..324bda8 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysFunctionServiceImpl.java @@ -0,0 +1,234 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.constant.PatternRegex; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.cnuser.user.pojo.constant.FunctionConst; +import com.njcn.product.cnuser.user.pojo.enums.UserResponseEnum; +import com.njcn.product.cnuser.user.mapper.SysFunctionMapper; +import com.njcn.product.cnuser.user.pojo.param.SysFunctionParam; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.vo.MenuVO; +import com.njcn.product.cnuser.user.pojo.vo.MetaVO; +import com.njcn.product.cnuser.user.service.ISysFunctionService; +import com.njcn.product.cnuser.user.service.ISysRoleFunctionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * @author caozehui + * @date 2024-11-12 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SysFunctionServiceImpl extends ServiceImpl implements ISysFunctionService { + + private final ISysRoleFunctionService sysRoleFunctionService; + + @Override + public List getFunctionTreeByKeyword(String keyword) { + List functionTree = this.getFunctionTree(true); + filterTreeByName(functionTree, keyword); + return functionTree; + } + + @Override + @Transactional + public boolean addFunction(SysFunctionParam functionParam) { + functionParam.setName(functionParam.getName().trim()); + functionParam.setPath(functionParam.getPath().trim()); + functionParam.setComponent(functionParam.getComponent().trim()); + checkFunctionParam(functionParam, false); + SysFunction function = new SysFunction(); + BeanUtil.copyProperties(functionParam, function); + function.setState(DataStateEnum.ENABLE.getCode()); + if (Objects.equals(functionParam.getPid(), FunctionConst.FATHER_PID)) { + function.setPids(FunctionConst.FATHER_PID); + } else { + SysFunction fatherFunction = this.lambdaQuery().eq(SysFunction::getId, functionParam.getPid()).one(); + if (Objects.equals(fatherFunction.getPid(), FunctionConst.FATHER_PID)) { + function.setPids(functionParam.getPid()); + } else { + String pidS = fatherFunction.getPids(); + function.setPids(pidS + "," + functionParam.getPid()); + } + } + return this.save(function); + } + + @Override + @Transactional + public boolean updateFunction(SysFunctionParam.UpdateParam param) { + param.setName(param.getName().trim()); + boolean result = false; + param.setPath(param.getPath().trim()); + param.setComponent(param.getComponent().trim()); + checkFunctionParam(param, true); + SysFunction oldFunction = this.lambdaQuery().eq(SysFunction::getId, param.getId()).eq(SysFunction::getState, DataStateEnum.ENABLE.getCode()).one(); + List childrenList = this.lambdaQuery().eq(SysFunction::getPid, param.getId()).eq(SysFunction::getState, DataStateEnum.ENABLE.getCode()).list(); + if (oldFunction.getType().equals(FunctionConst.TYPE_MENU) && param.getType().equals(FunctionConst.TYPE_BUTTON) && !CollectionUtils.isEmpty(childrenList)) { + throw new BusinessException(UserResponseEnum.EXISTS_CHILDREN_NOT_UPDATE); + } else { + SysFunction function = new SysFunction(); + BeanUtil.copyProperties(param, function); + result = this.updateById(function); + } + return result; + } + + @Override + @Transactional + public boolean deleteFunction(String id) { + boolean result1 = false; + sysRoleFunctionService.deleteRoleFunctionByFunctionIds(Collections.singletonList(id)); + List childrenList = this.lambdaQuery().eq(SysFunction::getState, DataStateEnum.ENABLE.getCode()).eq(SysFunction::getPid, id).list(); + if (CollectionUtils.isEmpty(childrenList)) { + result1 = this.lambdaUpdate().set(SysFunction::getState, DataStateEnum.DELETED.getCode()).in(SysFunction::getId, id).update(); + } else { + throw new BusinessException(UserResponseEnum.EXISTS_CHILDREN_NOT_DELETE); + } + return result1; + } + + @Override + public List getFunctionTree(boolean isContainButton) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(SysFunction::getState, DataStateEnum.ENABLE.getCode()); + if (isContainButton) { + wrapper.in(SysFunction::getType, FunctionConst.TYPE_MENU, FunctionConst.TYPE_BUTTON); + } else { + wrapper.in(SysFunction::getType, FunctionConst.TYPE_MENU); + } + List allFunctions = this.list(wrapper); + return allFunctions.stream().filter(fun -> Objects.equals(FunctionConst.FATHER_PID, fun.getPid())).peek(funS -> funS.setChildren(getChildrenList(funS, allFunctions))).sorted(Comparator.comparingInt(SysFunction::getSort)).collect(Collectors.toList()); + } + + @Override + public List getMenuByUserId(String userId) { + List menu = this.baseMapper.getMenuByUserId(userId); + menu.stream().forEach(m -> { + MetaVO meta = new MetaVO(); + meta.setIcon(m.getIcon()); + meta.setTitle(m.getName()); + meta.setIsLink(""); + meta.setHide(false); + meta.setFull(false); + meta.setAffix(false); + if("home".equals(m.getCode())){ + meta.setAffix(true); + } + meta.setKeepAlive(true); + m.setMeta(meta); + m.setName(m.getCode()); + }); + return menu.stream().filter(fun -> Objects.equals(FunctionConst.FATHER_PID, fun.getPid())).peek(funS -> { + List childrenList = getChildrenList(funS, menu); + if (ObjectUtil.isNull(childrenList) || childrenList.size() == 0) { + funS.setRedirect(null); + } else { + funS.setRedirect(funS.getComponent()); + funS.setComponent(null); + } + funS.setChildren(childrenList); + }).sorted(Comparator.comparingInt(MenuVO::getSort)).collect(Collectors.toList()); + } + + @Override + public Map> getButtonByUserId(String userId) { + List sysFunctions = this.baseMapper.getButtonByUserId(userId); + + Map> buttonMap = new HashMap<>(); + sysFunctions.stream().collect(Collectors.groupingBy(SysFunction::getPid)).forEach((k, v) -> { + SysFunction fatherFunction = this.getById(k); + if (ObjectUtil.isNotNull(fatherFunction)) { + buttonMap.put(fatherFunction.getCode(), v.stream().map(SysFunction::getCode).collect(Collectors.toList())); + } + }); + return buttonMap; + } + + private List getChildrenList(T currMenu, List categories) { + return categories.stream().filter(o -> Objects.equals(o.getPid(), currMenu.getId())).peek(o -> o.setChildren(getChildrenList(o, categories))).sorted(Comparator.comparingInt(SysFunction::getSort)).collect(Collectors.toList()); + } + + /** + * 校验参数, + * 1.检查是否存在相同名称的菜单 + * 名称 && 路径做唯一判断 + */ + private void checkFunctionParam(SysFunctionParam functionParam, boolean isExcludeSelf) { + if (functionParam.getType().equals(FunctionConst.TYPE_MENU)) { + if (StrUtil.isBlank(functionParam.getComponent())) { + throw new BusinessException(UserResponseEnum.COMPONENT_NOT_BLANK); + } + if (StrUtil.isBlank(functionParam.getPath()) || !Pattern.matches(PatternRegex.FUNCTION_PATH_REGEX, functionParam.getPath())) { + throw new BusinessException(UserResponseEnum.FUNCTION_PATH_FORMAT_ERROR); + } + if(StrUtil.isBlank(functionParam.getComponent()) || !Pattern.matches(PatternRegex.FUNCTION_COMPONENT_REGEX, functionParam.getComponent())){ + throw new BusinessException(UserResponseEnum.FUNCTION_COMPONENT_FORMAT_ERROR); + } + } + LambdaQueryWrapper functionLambdaQueryWrapper = new LambdaQueryWrapper<>(); + // 同一个pid下,名称、编码、路径、组件地址不能重复 + functionLambdaQueryWrapper + .eq(SysFunction::getPid, functionParam.getPid()) + .eq(SysFunction::getState, DataStateEnum.ENABLE.getCode()) + .and(obj -> obj.eq(SysFunction::getName, functionParam.getName()).or() + .eq(SysFunction::getCode, functionParam.getCode()).or() + .eq(StrUtil.isNotBlank(functionParam.getPath()), SysFunction::getPath, functionParam.getPath()).or() + .eq(StrUtil.isNotBlank(functionParam.getComponent()), SysFunction::getComponent, functionParam.getComponent()) + ); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (functionParam instanceof SysFunctionParam.UpdateParam) { + functionLambdaQueryWrapper.ne(SysFunction::getId, ((SysFunctionParam.UpdateParam) functionParam).getId()); + } + } + int countByAccount = this.count(functionLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(UserResponseEnum.EXISTS_SAME_MENU_CHILDREN); + } + } + + private List filterTreeByName(List tree, String keyword) { + if (CollectionUtils.isEmpty(tree) || !StrUtil.isNotBlank(keyword)) { + return tree; + } + filter(tree, keyword); + return tree; + } + + private void filter(List list, String keyword) { + for (int i = list.size() - 1; i >= 0; i--) { + SysFunction function = list.get(i); + List children = function.getChildren(); + if (!function.getName().contains(keyword)) { + if (!CollectionUtils.isEmpty(children)) { + filter(children, keyword); + } + if (CollectionUtils.isEmpty(function.getChildren())) { + list.remove(i); + } + } +// else { +// if (!CollectionUtils.isEmpty(children)) { +// filter(children, keyword); +// } +// } + } + } +} \ No newline at end of file diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleFunctionServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleFunctionServiceImpl.java new file mode 100644 index 0000000..89aecea --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleFunctionServiceImpl.java @@ -0,0 +1,68 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.cnuser.user.mapper.SysRoleFunctionMapper; +import com.njcn.product.cnuser.user.pojo.po.SysFunction; +import com.njcn.product.cnuser.user.pojo.po.SysRoleFunction; +import com.njcn.product.cnuser.user.service.ISysRoleFunctionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SysRoleFunctionServiceImpl extends ServiceImpl implements ISysRoleFunctionService { + + @Override + public List listFunctionByRoleId(String roleId) { + return this.baseMapper.getFunctionListByRoleId(roleId); + } + + @Override + @Transactional + public boolean updateRoleFunction(String roleId, List functionIds) { + //删除原有关系 + this.deleteRoleFunctionByRoleIds(Collections.singletonList(roleId)); + //新增关系 + List roleFunctions = new ArrayList<>(); + functionIds.forEach(functionId -> { + SysRoleFunction roleFunction = new SysRoleFunction(); + roleFunction.setRoleId(roleId); + roleFunction.setFunctionId(functionId); + roleFunctions.add(roleFunction); + }); + if (CollectionUtil.isEmpty(roleFunctions)) { + return true; + } else { + return this.saveBatch(roleFunctions); + } + } + + @Override + @Transactional + public boolean deleteRoleFunctionByRoleIds(List roleIds) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.in(SysRoleFunction::getRoleId, roleIds); + return this.remove(lambdaQuery); + } + + @Override + @Transactional + public boolean deleteRoleFunctionByFunctionIds(List functionIds) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.in(SysRoleFunction::getFunctionId, functionIds); + return this.remove(lambdaQuery); + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleServiceImpl.java new file mode 100644 index 0000000..4784bb1 --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysRoleServiceImpl.java @@ -0,0 +1,128 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.cnuser.user.mapper.SysRoleMapper; +import com.njcn.product.cnuser.user.pojo.constant.RoleConst; +import com.njcn.product.cnuser.user.pojo.enums.UserResponseEnum; +import com.njcn.product.cnuser.user.pojo.param.SysRoleParam; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.service.ISysRoleFunctionService; +import com.njcn.product.cnuser.user.service.ISysRoleService; +import com.njcn.product.cnuser.user.service.ISysUserRoleService; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-11 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SysRoleServiceImpl extends ServiceImpl implements ISysRoleService { + + private final ISysUserRoleService sysUserRoleService; + private final ISysRoleFunctionService sysRoleFunctionService; + + @Override + public Page listRole(SysRoleParam.QueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + queryWrapper.like(StrUtil.isNotBlank(queryParam.getName()), "sys_role.name", queryParam.getName()).eq(StrUtil.isNotBlank(queryParam.getCode()), "sys_role.code", queryParam.getCode()).eq(ObjectUtil.isNotNull(queryParam.getType()), "sys_role.type", queryParam.getType()); + } +// if (queryParam.getType().equals(0)) { +// queryWrapper.in("sys_role.type", queryParam.getType(), 1); +// } else if (queryParam.getType().equals(1)) { +// queryWrapper.eq("sys_role.type", 2); +// } + queryWrapper.eq("sys_role.state", DataStateEnum.ENABLE.getCode()).orderByDesc("sys_role.Update_Time"); + return this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + } + + @Override + @Transactional + public boolean addRole(SysRoleParam sysRoleParam) { + sysRoleParam.setName(sysRoleParam.getName().trim()); + checkRepeat(sysRoleParam, false); + SysRole role = new SysRole(); + BeanUtil.copyProperties(sysRoleParam, role); + //默认为正常状态 + role.setState(DataStateEnum.ENABLE.getCode()); + return this.save(role); + } + + @Override + @Transactional + public boolean updateRole(SysRoleParam.UpdateParam updateParam) { + updateParam.setName(updateParam.getName().trim()); + checkRepeat(updateParam, true); + //不能修改超级管理员角色 + Integer count = this.lambdaQuery() + .in(SysRole::getType, RoleConst.TYPE_SUPER_ADMINISTRATOR) + .eq(SysRole::getId, updateParam.getId()).eq(SysRole::getState, DataStateEnum.ENABLE.getCode()).count(); + if (count > 0) { + throw new BusinessException(UserResponseEnum.SUPER_ADMINSTRATOR_ROLE_CANNOT_UPDATE); + } + SysRole role = new SysRole(); + BeanUtil.copyProperties(updateParam, role); + return this.updateById(role); + } + + @Override + @Transactional + public boolean deleteRole(List ids) { + //不能删除超级管理员角色 + Integer count = this.lambdaQuery() + .in(SysRole::getType, RoleConst.TYPE_SUPER_ADMINISTRATOR) + .in(SysRole::getId, ids).eq(SysRole::getState, DataStateEnum.ENABLE.getCode()).count(); + if (count > 0) { + throw new BusinessException(UserResponseEnum.SUPER_ADMINSTRATOR_ROLE_CANNOT_DELETE); + } + // 删除角色和用户的绑定 + sysUserRoleService.deleteUserRoleByRoleIds(ids); + //删除角色和资源的绑定 + sysRoleFunctionService.deleteRoleFunctionByRoleIds(ids); + return this.lambdaUpdate().set(SysRole::getState, DataStateEnum.DELETED.getCode()).in(SysRole::getId, ids).update(); + } + + @Override + public List simpleList() { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.select(SysRole::getId, SysRole::getName).eq(SysRole::getState, DataStateEnum.ENABLE.getCode()); + return this.baseMapper.selectList(lambdaQueryWrapper); + } + + /** + * 校验参数,检查是否存在相同名称或编码的角色 + */ + private void checkRepeat(SysRoleParam roleParam, boolean isExcludeSelf) { + LambdaQueryWrapper roleLambdaQueryWrapper = new LambdaQueryWrapper<>(); + roleLambdaQueryWrapper + .eq(SysRole::getState, DataStateEnum.ENABLE.getCode()) + .and(w -> w.eq(SysRole::getName, roleParam.getName()).or().eq(SysRole::getCode, roleParam.getCode())); + //更新的时候,需排除当前记录 + if (isExcludeSelf) { + if (roleParam instanceof SysRoleParam.UpdateParam) { + roleLambdaQueryWrapper.ne(SysRole::getId, ((SysRoleParam.UpdateParam) roleParam).getId()); + } + } + int countByAccount = this.count(roleLambdaQueryWrapper); + //大于等于1个则表示重复 + if (countByAccount >= 1) { + throw new BusinessException(UserResponseEnum.NAME_OR_CODE_REPEAT); + } + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserRoleServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserRoleServiceImpl.java new file mode 100644 index 0000000..07ac67e --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserRoleServiceImpl.java @@ -0,0 +1,79 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.cnuser.user.mapper.SysUserRoleMapper; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.pojo.po.SysUserRole; +import com.njcn.product.cnuser.user.service.ISysUserRoleService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @author caozehui + * @date 2024-11-12 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SysUserRoleServiceImpl extends ServiceImpl implements ISysUserRoleService { + + @Override + public List listRoleByUserId(String userId) { + return this.baseMapper.getRoleListByUserId(userId); + } + + @Override + @Transactional + public boolean addUserRole(String userId, List roleIds) { + List userRoles = new ArrayList<>(); + if (!CollectionUtil.isEmpty(roleIds)) { + roleIds.forEach(id -> { + SysUserRole userRole = new SysUserRole(); + userRole.setUserId(userId); + userRole.setRoleId(id); + userRoles.add(userRole); + }); + } + return this.saveBatch(userRoles); + } + + @Override + @Transactional + public boolean updateUserRole(String userId, List roleIds) { + //删除原有关系 + this.deleteUserRoleByUserIds(Collections.singletonList(userId)); + //新增关系 + List userROles = new ArrayList<>(); + roleIds.forEach(role -> { + SysUserRole userRole = new SysUserRole(); + userRole.setUserId(userId); + userRole.setRoleId(role); + userROles.add(userRole); + }); + return this.saveBatch(userROles); + } + + @Override + @Transactional + public boolean deleteUserRoleByUserIds(List userIds) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.in(SysUserRole::getUserId, userIds); + return this.remove(lambdaQuery); + } + + @Override + @Transactional + public boolean deleteUserRoleByRoleIds(List roleIds) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.in(SysUserRole::getRoleId, roleIds); + return this.remove(lambdaQuery); + } +} diff --git a/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserServiceImpl.java b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserServiceImpl.java new file mode 100644 index 0000000..d1a6dca --- /dev/null +++ b/cn-user/src/main/java/com/njcn/product/cnuser/user/service/impl/SysUserServiceImpl.java @@ -0,0 +1,212 @@ +package com.njcn.product.cnuser.user.service.impl; + +import cn.hutool.core.date.LocalDateTimeUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.utils.sm.Sm4Utils; +import com.njcn.db.mybatisplus.constant.DbConstant; +import com.njcn.product.cnuser.user.pojo.constant.RoleConst; +import com.njcn.product.cnuser.user.pojo.constant.UserConst; +import com.njcn.product.cnuser.user.pojo.enums.UserResponseEnum; +import com.njcn.product.cnuser.user.mapper.SysUserMapper; +import com.njcn.product.cnuser.user.pojo.po.SysRole; +import com.njcn.product.cnuser.user.pojo.po.SysUser; +import com.njcn.product.cnuser.user.service.ISysUserRoleService; +import com.njcn.product.cnuser.user.pojo.param.SysUserParam; +import com.njcn.product.cnuser.user.service.ISysUserService; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @author caozehui + * @date 2024-11-08 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class SysUserServiceImpl extends ServiceImpl implements ISysUserService { + + private final ISysUserRoleService sysUserRoleService; + + @Override + public Page listUser(SysUserParam.SysUserQueryParam queryParam) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (ObjectUtil.isNotNull(queryParam)) { + queryWrapper.like(StrUtil.isNotBlank(queryParam.getName()), "sys_user.name", queryParam.getName()) + .between(ObjectUtil.isAllNotEmpty(queryParam.getSearchBeginTime(), queryParam.getSearchEndTime()), "sys_user.Login_Time", queryParam.getSearchBeginTime(), queryParam.getSearchEndTime()); + //排序 + if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) { + queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy())); + } else { + queryWrapper.orderByDesc("sys_user.update_time"); + } + } else { + queryWrapper.orderByDesc("sys_user.update_time"); + } + queryWrapper.ne("sys_user.state", UserConst.STATE_DELETE); + Page page = this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper); + page.getRecords().forEach(sysUser -> { + List sysRoles = sysUserRoleService.listRoleByUserId(sysUser.getId()); + sysUser.setRoleIds(sysRoles.stream().map(SysRole::getId).collect(Collectors.toList())); + sysUser.setRoleNames(sysRoles.stream().map(SysRole::getName).collect(Collectors.toList())); + }); + return page; + } + + @Override + public SysUser getUserByLoginName(String loginName) { + return this.lambdaQuery().ne(SysUser::getState, UserConst.STATE_DELETE).eq(SysUser::getLoginName, loginName).one(); + } + + @Override + public SysUser getUserByPhone(String phone, boolean isExcludeSelf, String id) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.eq(SysUser::getPhone, phone).ne(SysUser::getState, UserConst.STATE_DELETE); + if (isExcludeSelf) { + lambdaQuery.ne(SysUser::getId, id); + } + return this.baseMapper.selectOne(lambdaQuery); + } + + @Override + public SysUser getUserByName(String name, boolean isExcludeSelf, String id) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.eq(SysUser::getName, name).ne(SysUser::getState, UserConst.STATE_DELETE); + if (isExcludeSelf) { + lambdaQuery.ne(SysUser::getId, id); + } + return this.baseMapper.selectOne(lambdaQuery); + } + + @Override + public SysUser getUserByEmail(String email, boolean isExcludeSelf, String id) { + LambdaQueryWrapper lambdaQuery = new LambdaQueryWrapper<>(); + lambdaQuery.eq(SysUser::getEmail, email).ne(SysUser::getState, UserConst.STATE_DELETE); + if (isExcludeSelf) { + lambdaQuery.ne(SysUser::getId, id); + } + return this.baseMapper.selectOne(lambdaQuery); + } + + @Override + @Transactional + public boolean addUser(SysUserParam.SysUserAddParam addUserParam) { + addUserParam.setName(addUserParam.getName().trim()); + addUserParam.setLoginName(addUserParam.getLoginName().trim()); + if (UserConst.SUPER_ADMIN.equals(addUserParam.getLoginName())) { + throw new BusinessException(UserResponseEnum.SUPER_ADMIN_REPEAT); + } + if (!Objects.isNull(getUserByLoginName(addUserParam.getLoginName()))) { + throw new BusinessException(UserResponseEnum.LOGIN_NAME_REPEAT); + } + checkRepeat(addUserParam, false, null); + SysUser sysUser = new SysUser(); + BeanUtils.copyProperties(addUserParam, sysUser); + String secretkey = Sm4Utils.globalSecretKey; + Sm4Utils sm4 = new Sm4Utils(secretkey); + sysUser.setPassword(sm4.encryptData_ECB(sysUser.getPassword())); + sysUser.setLoginTime(LocalDateTimeUtil.now()); + sysUser.setLoginErrorTimes(0); + sysUser.setState(UserConst.STATE_ENABLE); + boolean result = this.save(sysUser); + sysUserRoleService.addUserRole(sysUser.getId(), addUserParam.getRoleIds()); + return result; + } + + @Override + @Transactional + public boolean updateUser(SysUserParam.SysUserUpdateParam updateUserParam) { + updateUserParam.setName(updateUserParam.getName().trim()); + checkRepeat(updateUserParam, true, updateUserParam.getId()); + SysUser sysUser = new SysUser(); + BeanUtils.copyProperties(updateUserParam, sysUser); + sysUserRoleService.updateUserRole(sysUser.getId(), updateUserParam.getRoleIds()); + return this.updateById(sysUser); + } + + @Override + @Transactional + public boolean updatePassword(SysUserParam.SysUserUpdatePasswordParam param) { + if (param.getOldPassword().equals(param.getNewPassword())) { + throw new BusinessException(UserResponseEnum.PASSWORD_SAME); + } + SysUser user = lambdaQuery().ne(SysUser::getState, UserConst.STATE_DELETE).eq(SysUser::getId, param.getId()).one(); + if (ObjectUtil.isNotNull(user)) { + String secretkey = Sm4Utils.globalSecretKey; + Sm4Utils sm4 = new Sm4Utils(secretkey); + if (sm4.encryptData_ECB(param.getOldPassword()).equals(user.getPassword())) { + user.setPassword(sm4.encryptData_ECB(param.getNewPassword())); + return this.updateById(user); + }else { + throw new BusinessException(UserResponseEnum.OLD_PASSWORD_ERROR); + } + } + return false; + } + + @Override + @Transactional + public boolean deleteUser(List ids) { + for (String id : ids) { + List sysRoles = sysUserRoleService.listRoleByUserId(id); + for (SysRole sysRole : sysRoles) { + if (sysRole.getType().equals(RoleConst.TYPE_SUPER_ADMINISTRATOR)) { + throw new BusinessException(UserResponseEnum.SUPER_ADMIN_CANNOT_DELETE); // 超级管理员角色不能删除 + } + } + } + // 删除用户角色关联数据 + sysUserRoleService.deleteUserRoleByUserIds(ids); + return this.lambdaUpdate() + .set(SysUser::getState, UserConst.STATE_DELETE) + .in(SysUser::getId, ids) + .update(); + } + + @Override + public SysUser getUserByLoginNameAndPassword(String loginName, String password) { + String secretkey = Sm4Utils.globalSecretKey; + Sm4Utils sm4 = new Sm4Utils(secretkey); + return this.lambdaQuery().ne(SysUser::getState, UserConst.STATE_DELETE) + .eq(SysUser::getLoginName, loginName) + .eq(SysUser::getPassword, sm4.encryptData_ECB(password)).one(); + } + + @Override + public boolean updateLoginTime(String userId) { + return this.lambdaUpdate().eq(SysUser::getId, userId).set(SysUser::getLoginTime, LocalDateTimeUtil.now()).update(); + } + + /** + * 校验重复 + * + * @param sysUserParam 检查对象 + * @param isExcludeSelf 是否排除自己 + * @param id 排除自己id + */ + private void checkRepeat(SysUserParam sysUserParam, boolean isExcludeSelf, String id) { + if (!Objects.isNull(getUserByName(sysUserParam.getName(), isExcludeSelf, id))) { + throw new BusinessException(UserResponseEnum.USER_NAME_REPEAT); + } + if (StringUtils.isNotBlank(sysUserParam.getPhone()) && !Objects.isNull(getUserByPhone(sysUserParam.getPhone(), isExcludeSelf, id))) { + throw new BusinessException(UserResponseEnum.REGISTER_PHONE_FAIL); + } + if (StringUtils.isNotBlank(sysUserParam.getEmail()) && !Objects.isNull(getUserByEmail(sysUserParam.getEmail(), isExcludeSelf, id))) { + throw new BusinessException(UserResponseEnum.REGISTER_EMAIL_FAIL); + } + } +} diff --git a/cn-zutai/.gitignore b/cn-zutai/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/cn-zutai/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/cn-zutai/pom.xml b/cn-zutai/pom.xml new file mode 100644 index 0000000..fe358ed --- /dev/null +++ b/cn-zutai/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + + cn-zutai + 1.0.0 + cn-zutai + cn-zutai + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + + com.njcn + common-oss + 1.0.0 + + + com.njcn + common-web + + + + + com.google.code.gson + gson + + + com.njcn + pqs-influx + 1.0.0 + compile + + + + + diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsConfigurationController.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsConfigurationController.java new file mode 100644 index 0000000..0d15940 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsConfigurationController.java @@ -0,0 +1,110 @@ +package com.njcn.product.cnzutai.zutai.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +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.minioss.bo.MinIoUploadResDTO; +import com.njcn.product.cnzutai.zutai.pojo.param.CsConfigurationParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsConfigurationVO; +import com.njcn.product.cnzutai.zutai.service.CsConfigurationService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Objects; + +/** +* (cs_configuration)表控制层 +* +* @author xxxxx +*/ +@Slf4j +@RestController +@RequestMapping("/cs-harmonic-boot/csconfiguration") +@Api(tags = "组态项目") +@AllArgsConstructor +public class CsConfigurationController extends BaseController { + + private final CsConfigurationService csConfigurationService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("新增组态项目") + @ApiImplicitParam(name = "csConfigurationParm", value = "新增组态项目参数", required = true) + public HttpResult add(@RequestBody @Validated CsConfigurationParm csConfigurationParm){ + String methodDescribe = getMethodDescribe("add"); + + boolean save = csConfigurationService.add(csConfigurationParm); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, save, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/audit") + @ApiOperation("修改组态项目") + @ApiImplicitParam(name = "auditParm", value = "修改组态项目参数", required = true) + public HttpResult audit(@RequestBody @Validated CsConfigurationParm.CsConfigurationAuditParam auditParm){ + String methodDescribe = getMethodDescribe("audit"); + + boolean save = csConfigurationService.audit (auditParm); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, save, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @GetMapping("/active") + @ApiOperation("激活组态项目") + public HttpResult active(@RequestParam("id")String id){ + String methodDescribe = getMethodDescribe("active"); + boolean active = csConfigurationService.active(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, active, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @GetMapping("/getActive") + @ApiOperation("获取激活组态项目") + public HttpResult getActive(){ + String methodDescribe = getMethodDescribe("active"); + CsConfigurationPO active = csConfigurationService.getActive(); + if(Objects.nonNull(active)){ + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, active, methodDescribe); + }else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryPage") + @ApiOperation("组态项目分页查询") + @ApiImplicitParam(name = "csConfigurationQueryParam", value = "组态项目查询参数", required = true) + public HttpResult> queryPage(@RequestBody @Validated CsConfigurationParm.CsConfigurationQueryParam csConfigurationQueryParam ){ + String methodDescribe = getMethodDescribe("queryPage"); + + IPage page = csConfigurationService.queryPage (csConfigurationQueryParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPLOAD) + @PostMapping("/uploadImage") + @ApiOperation("上传底图") + @ApiImplicitParam(name = "file", value = "底图文件", required = true) + public HttpResult uploadImage(@RequestParam("file") MultipartFile issuesFile){ + String methodDescribe = getMethodDescribe("uploadImage"); + String filePath = csConfigurationService.uploadImage(issuesFile); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,new MinIoUploadResDTO(issuesFile.getOriginalFilename(),filePath), methodDescribe); + } + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsPagePOController.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsPagePOController.java new file mode 100644 index 0000000..85c785d --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/CsPagePOController.java @@ -0,0 +1,69 @@ +package com.njcn.product.cnzutai.zutai.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +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.product.cnzutai.zutai.pojo.param.CsPageParm; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsPageVO; +import com.njcn.product.cnzutai.zutai.service.CsPagePOService; +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 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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** +* (cs_page)表控制层 +* +* @author xxxxx +*/ +@RestController +@RequestMapping("/cs-harmonic-boot/cspage") +@Api(tags = "组态项目页面") +@AllArgsConstructor +public class CsPagePOController extends BaseController { + private final CsPagePOService csPagePOService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("新增组态页面") +// @ApiImplicitParam(name = "csPageParm", value = "新增组态项目参数", required = true) + public HttpResult add( @Validated CsPageParm csPageParm){ + String methodDescribe = getMethodDescribe("add"); + + boolean flag = csPagePOService.add (csPageParm); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, flag, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/audit") + @ApiOperation("修改组态页面") + public HttpResult audit( @Validated CsPageParm.CsPageParmAuditParam auditParm){ + String methodDescribe = getMethodDescribe("audit"); + + boolean save = csPagePOService.audit (auditParm); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, save, methodDescribe); + } + + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/queryPage") + @ApiOperation("组态页面分页查询") + @ApiImplicitParam(name = "csPageParam", value = "组态项目查询参数", required = true) + public HttpResult> queryPage(@RequestBody @Validated CsPageParm.CsPageParmQueryParam csPageParam ){ + String methodDescribe = getMethodDescribe("queryPage"); + + IPage page = csPagePOService.queryPage (csPageParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/ElementController.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/ElementController.java new file mode 100644 index 0000000..b87fe4a --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/ElementController.java @@ -0,0 +1,68 @@ +package com.njcn.product.cnzutai.zutai.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; + +import com.njcn.product.cnzutai.zutai.pojo.param.ElementParam; +import com.njcn.product.cnzutai.zutai.service.IElementService; +import com.njcn.product.cnzutai.zutai.pojo.po.CsElement; +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 org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/7/12 16:07 + */ +@RestController +@RequestMapping("cs-system-boot/csElement") +@Api(tags = "组态图元") +@AllArgsConstructor +public class ElementController extends BaseController { + + private final IElementService csElementService; + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/add") + @ApiOperation("新增图元") + public HttpResult add(@Validated ElementParam param){ + String methodDescribe = getMethodDescribe("add"); + CsElement csElement = csElementService.addElement(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, csElement, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/find") + @ApiOperation("查询图元") + public HttpResult> find(){ + String methodDescribe = getMethodDescribe("find"); + List list = csElementService.findElement(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/delete") + @ApiOperation("删除图元") + @ApiImplicitParam(name = "id", value = "图元Id", required = true) + public HttpResult deleteById(@RequestParam("id") String id){ + String methodDescribe = getMethodDescribe("deleteById"); + csElementService.deleteById(id); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/RealTimeDataController.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/RealTimeDataController.java new file mode 100644 index 0000000..f20b452 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/controller/RealTimeDataController.java @@ -0,0 +1,43 @@ +package com.njcn.product.cnzutai.zutai.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.common.LogEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.HttpResultUtil; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsRtDataVO; +import com.njcn.product.cnzutai.zutai.pojo.vo.RealTimeDataVo; +import com.njcn.product.cnzutai.zutai.service.ILineTargetService; +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.web.bind.annotation.*; + +import java.util.List; + +/** + * Description: + * Date: 2025/09/10 下午 7:46【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Slf4j +@RestController +@RequestMapping("/data") +@Api(tags = "装置数据") +@AllArgsConstructor +public class RealTimeDataController extends BaseController { + private final ILineTargetService lineTargetService; + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/realTimeData") + @ApiOperation("设备监控-》准实时数据") + public HttpResult> realTimeData(@RequestParam String pageId) { + String methodDescribe = getMethodDescribe("realTimeData"); + List lineData = lineTargetService.getLineData(pageId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, lineData, methodDescribe); + } +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsConfigurationMapper.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsConfigurationMapper.java new file mode 100644 index 0000000..baf8c36 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsConfigurationMapper.java @@ -0,0 +1,19 @@ +package com.njcn.product.cnzutai.zutai.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; + +import com.njcn.product.cnzutai.zutai.pojo.param.CsConfigurationParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO; +import org.apache.ibatis.annotations.Param; + +/** + * Description: + * Date: 2023/5/31 10:53【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CsConfigurationMapper extends BaseMapper { + Page queryPage(Page temppage, @Param("temp") CsConfigurationParm.CsConfigurationQueryParam csConfigurationQueryParam); +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsElementMapper.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsElementMapper.java new file mode 100644 index 0000000..fa0dd9b --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsElementMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.cnzutai.zutai.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.cnzutai.zutai.pojo.po.CsElement; + +/** + *

+ * 组态图元库 Mapper 接口 + *

+ * + * @author xuyang + * @since 2023-06-14 + */ +public interface CsElementMapper extends BaseMapper { + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsPagePOMapper.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsPagePOMapper.java new file mode 100644 index 0000000..7da5f04 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/CsPagePOMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.cnzutai.zutai.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO; + +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CsPagePOMapper extends BaseMapper { +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsConfigurationMapper.xml b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsConfigurationMapper.xml new file mode 100644 index 0000000..72fcf12 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsConfigurationMapper.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + id, `name`, `status`, create_by, create_time, update_by, update_time + + + + \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsPagePOMapper.xml b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsPagePOMapper.xml new file mode 100644 index 0000000..b000f4c --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/mapper/mapping/CsPagePOMapper.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + id, pid, `name`, `path`, `status`, create_by, create_time, update_by, update_time + + \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/AskRealTimeDataDTO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/AskRealTimeDataDTO.java new file mode 100644 index 0000000..61e08f7 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/AskRealTimeDataDTO.java @@ -0,0 +1,19 @@ +package com.njcn.product.cnzutai.zutai.pojo.dto; + +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2025/09/18 下午 1:59【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class AskRealTimeDataDTO { + private String pageId; + private List lineIdList; + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/RealTimeDataDTO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/RealTimeDataDTO.java new file mode 100644 index 0000000..23f41d1 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/RealTimeDataDTO.java @@ -0,0 +1,25 @@ +package com.njcn.product.cnzutai.zutai.pojo.dto; + +import com.njcn.product.cnzutai.zutai.pojo.vo.RealTimeDataVo; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * Description: + * Date: 2025/09/18 下午 2:00【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class RealTimeDataDTO { + private Integer code; + private String message; + private Integer type =1; +// private List realTimeDataVoList; +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/ZuTaiDTO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/ZuTaiDTO.java new file mode 100644 index 0000000..865c4aa --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/dto/ZuTaiDTO.java @@ -0,0 +1,50 @@ +package com.njcn.product.cnzutai.zutai.pojo.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/6/14 20:07 + */ +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class ZuTaiDTO { + + private List json; + + @Data + @JsonIgnoreProperties(ignoreUnknown = true) + public static class DiagramElement{ + + private String id; + private String title; + private String keyId; + private String type; + private boolean resize; + private boolean rotate; + private boolean lock; + private boolean active; + private boolean hide; + private String tag; + private boolean use_proportional_scaling; + private String lineId; + private List lineList; + private String lineName; + @JsonProperty("UID") + private List> uid; + @JsonProperty("UIDNames") + + private List uidNames; + private List unit; + + } + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/enums/CsSystemResponseEnum.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/enums/CsSystemResponseEnum.java new file mode 100644 index 0000000..32d42ef --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/enums/CsSystemResponseEnum.java @@ -0,0 +1,35 @@ +package com.njcn.product.cnzutai.zutai.pojo.enums; + +import lombok.Getter; + +/** + * @author xuyang + * @version 1.0.0 + * @date 2023年04月17日 10:50 + */ +@Getter +public enum CsSystemResponseEnum { + + /** + * A0301 ~ A0399 用于治理系统模块的枚举 + *

+ */ + DICT_REPEAT("A0301","字典数据重复!"), + SAME_DATA_ERROR("A0301","数据重复"), + + CS_SYSTEM_COMMON_ERROR("A00302","治理系统模块异常"), + BIND_TARGET_ERROR("A00601","指标参数绑定异常"), + + + ; + + private final String code; + + private final String message; + + CsSystemResponseEnum(String code, String message) { + this.code = code; + this.message = message; + } + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsConfigurationParm.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsConfigurationParm.java new file mode 100644 index 0000000..902c44c --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsConfigurationParm.java @@ -0,0 +1,64 @@ +package com.njcn.product.cnzutai.zutai.pojo.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; + +/** + * Description: + * Date: 2023/5/31 10:35【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class CsConfigurationParm { + + + /** + * 组态项目名称 + */ + @ApiModelProperty(value = "组态项目名称") + @NotBlank(message="组态项目名称不能为空") + private String name; + + private String remark; + + private List projectIds; + + + private Integer orderBy; + + private String fileContent; + + + + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CsConfigurationAuditParam extends CsConfigurationParm { + @ApiModelProperty("Id") + @NotBlank(message = "id不为空") + private String id; + @ApiModelProperty(value = "状态") + private String status; + } + + /** + * 分页查询实体 + */ + @Data + @EqualsAndHashCode(callSuper = true) + public static class CsConfigurationQueryParam extends BaseParam { + private String id; + + } + + + + +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsPageParm.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsPageParm.java new file mode 100644 index 0000000..d3a6ac6 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/CsPageParm.java @@ -0,0 +1,53 @@ +package com.njcn.product.cnzutai.zutai.pojo.param; + +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.constraints.NotBlank; + +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +public class CsPageParm { + + /** + * 组态项目id + */ + @ApiModelProperty(value="组态项目id") + private String pid; + + private MultipartFile multipartFile; + + /** + * 组态页面文件路径 + */ + @ApiModelProperty(value = "组态页面json文件") + private String jsonFile; + + @Data + @EqualsAndHashCode(callSuper = true) + public static class CsPageParmAuditParam extends CsPageParm { + @ApiModelProperty("Id") + @NotBlank(message = "id不为空") + private String id; + @ApiModelProperty(value = "状态") + private String status; + } + @Data + @EqualsAndHashCode(callSuper = true) + public static class CsPageParmQueryParam extends BaseParam { + @ApiModelProperty("pid") + private String pid; + } +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/ElementParam.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/ElementParam.java new file mode 100644 index 0000000..8326594 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/param/ElementParam.java @@ -0,0 +1,45 @@ +package com.njcn.product.cnzutai.zutai.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/7/12 16:23 + */ +@Data +public class ElementParam { + + @ApiModelProperty(value = "组件分类") + @NotBlank(message="组件分类不能为空!") + private String elementType; + + @ApiModelProperty(value = "组件子类型") + @NotBlank(message="组件子类型不能为空!") + private String elementSonType; + + @ApiModelProperty(value = "组件编码") + private String elementCode; + + @ApiModelProperty(value = "组件名称") + private String elementName; + + @ApiModelProperty(value = "组件标识") + private String elementMark; + + @ApiModelProperty(value = "图元文件") + @NotNull(message="图元文件不能为空!") + private MultipartFile multipartFile; + + @ApiModelProperty(value = "图元类型") + @NotBlank(message="图元类型不能为空!") + private String elementForm; + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsConfigurationPO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsConfigurationPO.java new file mode 100644 index 0000000..2b2f5b9 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsConfigurationPO.java @@ -0,0 +1,72 @@ +package com.njcn.product.cnzutai.zutai.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Description: + * Date: 2023/5/31 10:35【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "cs_configuration") +public class CsConfigurationPO extends BaseEntity { + /** + * id + */ + @TableId(value = "id", type = IdType.ASSIGN_UUID) + private String id; + + /** + * 组态项目名称 + */ + @TableField(value = "`name`") + private String name; + + @TableField(value = "image_path") + private String imagePath; + + @TableField(value = "remark") + private String remark; + @TableField(value = "project_ids") + private String projectIds; + + @TableField(value = "order_By") + private Integer orderBy; + + /** + * 是否激活 0.否 1.是 + */ + private Integer active; + + + /** + * 状态 0:删除 1:正常 + */ + @TableField(value = "`status`") + private String status; + + + + public static final String COL_ID = "id"; + + public static final String COL_NAME = "name"; + + public static final String COL_STATUS = "status"; + + public static final String COL_CREATE_BY = "create_by"; + + public static final String COL_CREATE_TIME = "create_time"; + + public static final String COL_UPDATE_BY = "update_by"; + + public static final String COL_UPDATE_TIME = "update_time"; +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsElement.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsElement.java new file mode 100644 index 0000000..1608df1 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsElement.java @@ -0,0 +1,70 @@ +package com.njcn.product.cnzutai.zutai.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + *

+ * 组态图元库 + *

+ * + * @author xuyang + * @since 2023-06-14 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("cs_element") +public class CsElement extends BaseEntity { + + private static final long serialVersionUID = 1L; + + + /** + * id + */ + private String id; + + /** + * 图元文件路径 + */ + private String path; + + /** + * 组件分类 + */ + private String elementType; + + /** + * 组件子类型 + */ + private String elementSonType; + + /** + * 组件编码 + */ + private String elementCode; + + /** + * 组件名称 + */ + private String elementName; + + /** + * 组件标识 + */ + private String elementMark; + + /** + * 状态 + */ + private Integer status; + + /** + * 图元类型 + */ + private String elementForm; + + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsPagePO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsPagePO.java new file mode 100644 index 0000000..6bdfea9 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/po/CsPagePO.java @@ -0,0 +1,77 @@ +package com.njcn.product.cnzutai.zutai.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.njcn.db.mybatisplus.bo.BaseEntity; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "cs_page") +public class CsPagePO extends BaseEntity { + /** + * id + */ + @TableId(value = "id", type = IdType.ASSIGN_UUID) + private String id; + + /** + * 组态项目id + */ + @TableField(value = "pid") + private String pid; + + /** + * 组态页面名称 + */ + @TableField(value = "`name`") + private String name; + /*排序id + * */ + @TableField(value = "k_id") + private String kId; + + /** + * 组态页面文件路径 + */ + @TableField(value = "`path`") + private String path; + + /** + * 组态页面状态 + */ + @TableField(value = "`status`") + private String status; + + + + public static final String COL_ID = "id"; + + public static final String COL_PID = "pid"; + + public static final String COL_NAME = "name"; + public static final String COL_KID = "k_id"; + + public static final String COL_PATH = "path"; + + public static final String COL_STATUS = "status"; + + public static final String COL_CREATE_BY = "create_by"; + + public static final String COL_CREATE_TIME = "create_time"; + + public static final String COL_UPDATE_BY = "update_by"; + + public static final String COL_UPDATE_TIME = "update_time"; +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsConfigurationVO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsConfigurationVO.java new file mode 100644 index 0000000..cb92356 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsConfigurationVO.java @@ -0,0 +1,54 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + + +import com.njcn.db.mybatisplus.bo.BaseEntity; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2023/5/31 10:35【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data + +public class CsConfigurationVO extends BaseEntity { + /** + * id + */ + private String id; + + /** + * 组态项目名称 + */ + @ApiModelProperty(value = "组态项目名称") + private String name; + + private String fileContent; + + private Integer orderBy; + + private Integer active; + + + private List projectIds; + + + @ApiModelProperty(value = "操作人") + private String operater; + + @ApiModelProperty(value = "备注") + private String remark; + + /** + * 状态 0:删除 1:正常 + */ + @ApiModelProperty(value = "组态项目状态") + private String status; + + +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsPageVO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsPageVO.java new file mode 100644 index 0000000..d762b8c --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsPageVO.java @@ -0,0 +1,71 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +public class CsPageVO { + /** + * id + */ + @ApiModelProperty(value="id") + private String id; + + /** + * 组态项目id + */ + @ApiModelProperty(value="组态项目id") + private String pid; + + @ApiModelProperty(value="前端使用") + @JsonProperty("kId") // 强制前端使用 kId + private String kId; + + @ApiModelProperty(value="组态项目名称") + private String configurationName; + + + /** + * 组态页面名称 + */ + @ApiModelProperty(value="组态页面名称") + private String name; + @ApiModelProperty(value = "操作人") + private String operater; + + /** + * 组态页面文件路径 + */ + @ApiModelProperty(value="组态页面文件路径") + private String path; + + private String createBy; + + @JsonFormat( + pattern = "yyyy-MM-dd HH:mm:ss" + ) + private LocalDateTime createTime; + + private String updateBy; + + @JsonFormat( + pattern = "yyyy-MM-dd HH:mm:ss" + ) + private LocalDateTime updateTime; + + +} \ No newline at end of file diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsRtDataVO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsRtDataVO.java new file mode 100644 index 0000000..9398a16 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/CsRtDataVO.java @@ -0,0 +1,52 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.Instant; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/6/25 13:31 + */ +@Data +public class CsRtDataVO { + + @ApiModelProperty("图元id") + private String id; + + @ApiModelProperty("最新数据时间") +// @JsonSerialize(using = InstantDateSerializer.class) + private Instant time; + + @ApiModelProperty("监测点id") + private String lineId; + + @ApiModelProperty("相别") + private String phaseType; + + @ApiModelProperty("数据类型") + private String valueType; + + @ApiModelProperty("实时数据值,3.1415926则显示暂无数据") + private Double value; + + @ApiModelProperty("指标显示名称") + private String statisticalName; + + @ApiModelProperty("指标单位") + private String unit; + + @ApiModelProperty("指标名称") + private String target; + + @ApiModelProperty("指标最大值") + private Double maxValue; + + @ApiModelProperty("指标最小值") + private Double minValue; + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/DataArrayTreeVO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/DataArrayTreeVO.java new file mode 100644 index 0000000..b561420 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/DataArrayTreeVO.java @@ -0,0 +1,27 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/6/14 13:36 + */ +@Data +public class DataArrayTreeVO { + + private String id; + + private String name; + + private String showName; + + private List children = new ArrayList<>(); + + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/ElementsVO.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/ElementsVO.java new file mode 100644 index 0000000..028fdbb --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/ElementsVO.java @@ -0,0 +1,21 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/6/2 15:26 + */ +@Data +public class ElementsVO implements Serializable { + + private String id; + + private String json; + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/RealTimeDataVo.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/RealTimeDataVo.java new file mode 100644 index 0000000..10bf55f --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/pojo/vo/RealTimeDataVo.java @@ -0,0 +1,51 @@ +package com.njcn.product.cnzutai.zutai.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; +import java.time.Instant; + +/** + * @author xy + */ +@Data +public class RealTimeDataVo implements Serializable { + + @ApiModelProperty("数据时间") +// @JsonSerialize(using = InstantDateSerializer.class) + private Instant time; + + @ApiModelProperty("指标id") + private String id; + + @ApiModelProperty("指标名称") + private String name; + + @ApiModelProperty("指标别名") + private String otherName; + + @ApiModelProperty("相别") + private String phase; + + @ApiModelProperty("单位") + private String unit; + + @ApiModelProperty("排序") + private Integer sort; + + @ApiModelProperty("平均值") + private Double avgValue; + + @ApiModelProperty("A相值") + private Double valueA; + + @ApiModelProperty("B相值") + private Double valueB; + + @ApiModelProperty("C相值") + private Double valueC; + + @ApiModelProperty("无相值") + private Double valueM; +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsConfigurationService.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsConfigurationService.java new file mode 100644 index 0000000..f9077e9 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsConfigurationService.java @@ -0,0 +1,33 @@ +package com.njcn.product.cnzutai.zutai.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; + +import com.njcn.product.cnzutai.zutai.pojo.param.CsConfigurationParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsConfigurationVO; +import org.springframework.web.multipart.MultipartFile; + +/** + * + * Description: + * Date: 2023/5/31 10:53【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CsConfigurationService extends IService{ + + + boolean add(CsConfigurationParm csConfigurationParm); + + boolean audit(CsConfigurationParm.CsConfigurationAuditParam auditParm); + + boolean active(String id); + + CsConfigurationPO getActive(); + + IPage queryPage(CsConfigurationParm.CsConfigurationQueryParam csConfigurationQueryParam); + + String uploadImage(MultipartFile issuesFile); +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsPagePOService.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsPagePOService.java new file mode 100644 index 0000000..c062cc4 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/CsPagePOService.java @@ -0,0 +1,34 @@ +package com.njcn.product.cnzutai.zutai.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnzutai.zutai.pojo.param.CsPageParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsPageVO; + + +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface CsPagePOService extends IService{ + + + boolean add(CsPageParm csPageParm); + + boolean audit(CsPageParm.CsPageParmAuditParam auditParm); + + IPage queryPage(CsPageParm.CsPageParmQueryParam csPageParam); + + /** + * 根据id获取组态页面数据 + * @param id + * @return + */ + CsPagePO queryById(String id); + + } diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/IElementService.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/IElementService.java new file mode 100644 index 0000000..c08ceef --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/IElementService.java @@ -0,0 +1,36 @@ +package com.njcn.product.cnzutai.zutai.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.cnzutai.zutai.pojo.param.ElementParam; +import com.njcn.product.cnzutai.zutai.pojo.po.CsElement; + + +import java.util.List; + +/** + *

+ * 组态图元库 服务类 + *

+ * + * @author xuyang + * @since 2023-06-14 + */ +public interface IElementService extends IService { + + /** + * 新增组态图元 + * @param param 图元参数 + */ + CsElement addElement(ElementParam param); + + /** + * 组态图元数据查询 + */ + List findElement(); + + /** + * 组态图元数据查询 + */ + void deleteById(String id); + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/ILineTargetService.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/ILineTargetService.java new file mode 100644 index 0000000..e0e1c8e --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/ILineTargetService.java @@ -0,0 +1,28 @@ +package com.njcn.product.cnzutai.zutai.service; + + + +import com.njcn.product.cnzutai.zutai.pojo.vo.CsRtDataVO; +import com.njcn.product.cnzutai.zutai.pojo.vo.DataArrayTreeVO; + +import java.util.List; + +/** + * @author xuyang + */ +public interface ILineTargetService { + + /** + * 根据监测点Id获取对应指标 + * @param lineId + * @return + */ + List getLineTarget(String lineId); + + /** + * 获取绑定指标的数据 + * @param id + */ + List getLineData(String id); + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsConfigurationServiceImpl.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsConfigurationServiceImpl.java new file mode 100644 index 0000000..205e5ee --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsConfigurationServiceImpl.java @@ -0,0 +1,225 @@ +package com.njcn.product.cnzutai.zutai.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.cnzutai.zutai.mapper.CsPagePOMapper; +import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO; +import com.njcn.product.cnzutai.zutai.service.CsConfigurationService; +import com.njcn.product.cnzutai.zutai.mapper.CsConfigurationMapper; +import com.njcn.product.cnzutai.zutai.pojo.param.CsConfigurationParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsConfigurationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.stream.Collectors; + +/** + * + * Description: + * Date: 2023/5/31 10:53【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CsConfigurationServiceImpl extends ServiceImpl implements CsConfigurationService { + + private final FileStorageUtil fileStorageUtil; + private final CsPagePOMapper csPagePOMapper; + + //private final UserFeignClient userFeignClient; + + //private final RoleEngineerDevFeignClient roleEngineerDevFeignClient; + + @Override + @Transactional(rollbackFor = {Exception.class}) + public boolean add(CsConfigurationParm csConfigurationParm) { + CsConfigurationPO csConfigurationPO = new CsConfigurationPO(); + + BeanUtils.copyProperties(csConfigurationParm,csConfigurationPO); + + List projectIds = csConfigurationParm.getProjectIds(); + if(CollectionUtils.isEmpty(projectIds)){ + throw new BusinessException("请选择项目"); + } + String projects = String.join(",", projectIds); + + csConfigurationPO.setProjectIds(projects); + //排序不填给个100往后排 + csConfigurationPO.setOrderBy(Objects.isNull(csConfigurationParm.getOrderBy())?100:csConfigurationParm.getOrderBy()); + csConfigurationPO.setImagePath(csConfigurationParm.getFileContent()); + csConfigurationPO.setActive(0); + csConfigurationPO.setStatus("1"); + boolean save = this.save(csConfigurationPO); + + String name = csConfigurationPO.getName(); + Integer count = this.lambdaQuery().eq(CsConfigurationPO::getName, name).eq(CsConfigurationPO::getStatus, "1").count(); + if(count>1){ + throw new BusinessException("存在相同的组态项目名称"); + } + return save; + } + + @Override + public boolean audit(CsConfigurationParm.CsConfigurationAuditParam auditParm) { + CsConfigurationPO tem = this.getById(auditParm.getId()); + if(Objects.isNull(tem)){ + throw new BusinessException(CommonResponseEnum.FAIL,"未查询到项目信息,无法操作!"); + } + + + CsConfigurationPO csConfigurationPO = new CsConfigurationPO(); + if(Objects.equals(auditParm.getStatus(),"0")){ + csConfigurationPO.setId(auditParm.getId()); + csConfigurationPO.setStatus("0"); + boolean b = this.updateById(csConfigurationPO); + + if(StrUtil.isNotBlank(tem.getImagePath())){ + fileStorageUtil.deleteFile(tem.getImagePath()); + } + + CsPagePO csPagePO = new CsPagePO(); + csPagePO.setStatus("0"); + csPagePOMapper.update(csPagePO,new LambdaUpdateWrapper().eq(CsPagePO::getPid,csConfigurationPO.getId())); + return b; + } + + BeanUtils.copyProperties(auditParm,csConfigurationPO); + List projectIds = auditParm.getProjectIds(); + if(!CollectionUtils.isEmpty(projectIds)){ + String projects = String.join(",", projectIds); + csConfigurationPO.setProjectIds(projects); + + } + if(!Objects.isNull(auditParm.getOrderBy())){ + csConfigurationPO.setOrderBy(auditParm.getOrderBy()==0?100:auditParm.getOrderBy()); + } + + if(!Objects.isNull(auditParm.getFileContent())){ + if(StrUtil.isNotBlank(tem.getImagePath())){ + fileStorageUtil.deleteFile(tem.getImagePath()); + } + + String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(auditParm.getFileContent()), OssPath.CONFIGURATIONPATH, OssPath.CONFIGURATIONNAME); + csConfigurationPO.setImagePath(s); + } + + boolean b = this.updateById(csConfigurationPO); + + return b; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean active(String id) { + CsConfigurationPO csConfigurationPO = this.lambdaQuery().eq(CsConfigurationPO::getId,id).one(); + if(Objects.isNull(csConfigurationPO)){ + throw new BusinessException("未查询到项目组态图"); + } + this.lambdaUpdate().set(CsConfigurationPO::getActive,0).update(); + this.lambdaUpdate().set(CsConfigurationPO::getActive,1).eq(CsConfigurationPO::getId, id).update(); + return true; + } + + @Override + public CsConfigurationPO getActive() { + CsConfigurationPO csConfigurationPO = this.lambdaQuery().eq(CsConfigurationPO::getActive,1).one(); + return csConfigurationPO; + } + + + @Override + public IPage queryPage(CsConfigurationParm.CsConfigurationQueryParam csConfigurationQueryParam) { + Page returnpage = new Page<> (csConfigurationQueryParam.getPageNum(), csConfigurationQueryParam.getPageSize ( )); + Page temppage = new Page<> (csConfigurationQueryParam.getPageNum(), csConfigurationQueryParam.getPageSize ( )); + + List data1 = new ArrayList<>(); //roleEngineerDevFeignClient.getRoleProject().getData(); + /* if(CollectionUtils.isEmpty(data1)){ + return returnpage; + }*/ + //+无线项目id + //data1.add(DataParam.WIRELESS_PROJECT_ID); + Page csConfigurationPOPage = this.getBaseMapper().queryPage(temppage,csConfigurationQueryParam); + + List collect1 = csConfigurationPOPage.getRecords().stream().map(CsConfigurationPO::getCreateBy).collect(Collectors.toList()); + Map collect2 = new HashMap<>(); + /* if(!CollectionUtils.isEmpty(collect1)){ + List data = userFeignClient.appuserByIdList(collect1).getData(); + collect2 = data.stream().collect(Collectors.toMap(User::getId, User::getName, (e1, e2) -> e1 + "," + e2)); + + } else { + collect2 = new HashMap<>(); + }*/ + + List collect = csConfigurationPOPage.getRecords().stream().map(page -> { + CsConfigurationVO csDevModelPageVO = new CsConfigurationVO(); + BeanUtils.copyProperties(page, csDevModelPageVO); + + if(StringUtils.isEmpty(page.getProjectIds())){ + csDevModelPageVO.setProjectIds(new ArrayList<>()); + }else { + csDevModelPageVO.setProjectIds( Arrays.asList(page.getProjectIds().split(","))); + + } + if(Objects.isNull(page.getImagePath())){ + csDevModelPageVO.setFileContent(null); + + }else { + + try { + InputStream fileStream = fileStorageUtil.getFileStream(page.getImagePath()); + String text = new BufferedReader( + new InputStreamReader(fileStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); + csDevModelPageVO.setFileContent(text); + }catch (Exception e){ + e.printStackTrace(); + } + + } + + + csDevModelPageVO.setOperater(collect2.get(csDevModelPageVO.getCreateBy())); + return csDevModelPageVO; + }).collect(Collectors.toList()); + returnpage.setRecords(collect); + returnpage.setTotal(csConfigurationPOPage.getTotal()); + + + + return returnpage; + } + + @Override + public String uploadImage(MultipartFile issuesFile) { + return fileStorageUtil.getFileUrl( fileStorageUtil.uploadMultipart(issuesFile, OssPath.CONFIGURATIONPATH)); + } + + /*将strin写入Json文件,返回一个InputStream*/ + public InputStream writeJsonStringToInputStream(String jsonString) { + // 转换为输入流 + ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); + return inputStream; + } +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsElementServiceImpl.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsElementServiceImpl.java new file mode 100644 index 0000000..9734422 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsElementServiceImpl.java @@ -0,0 +1,65 @@ +package com.njcn.product.cnzutai.zutai.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.cnzutai.zutai.pojo.param.ElementParam; +import com.njcn.product.cnzutai.zutai.mapper.CsElementMapper; +import com.njcn.product.cnzutai.zutai.pojo.enums.CsSystemResponseEnum; +import com.njcn.product.cnzutai.zutai.pojo.po.CsElement; +import com.njcn.product.cnzutai.zutai.service.IElementService; +import lombok.AllArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Objects; + +/** + *

+ * 组态图元库 服务实现类 + *

+ * + * @author xuyang + * @since 2023-07-12 + */ +@Service +@AllArgsConstructor +public class CsElementServiceImpl extends ServiceImpl implements IElementService { + + private final FileStorageUtil fileStorageUtil; + + @Override + public CsElement addElement(ElementParam param) { + CsElement po = this.lambdaQuery().eq(CsElement::getStatus,1) + .eq(CsElement::getElementCode,param.getElementCode()) + .eq(CsElement::getElementName,param.getElementName()) + .eq(CsElement::getElementMark,param.getElementMark()).one(); + if (!Objects.isNull(po)){ + throw new BusinessException(CsSystemResponseEnum.SAME_DATA_ERROR); + } + CsElement csElement = new CsElement(); + BeanUtils.copyProperties(param,csElement); + String path = fileStorageUtil.uploadMultipart(param.getMultipartFile(), OssPath.ELEMENT); + csElement.setPath(path); + csElement.setStatus(1); + this.saveOrUpdate(csElement); + csElement.setPath(path); + return csElement; + } + + @Override + public List findElement() { + List list = this.lambdaQuery().eq(CsElement::getStatus,1).list(); + return list; + } + + @Override + public void deleteById(String id) { + CsElement csElement = this.lambdaQuery().eq(CsElement::getId,id).one(); + csElement.setStatus(0); + this.updateById(csElement); + } +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsPagePOServiceImpl.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsPagePOServiceImpl.java new file mode 100644 index 0000000..1583086 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/CsPagePOServiceImpl.java @@ -0,0 +1,151 @@ +package com.njcn.product.cnzutai.zutai.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.njcn.oss.constant.OssPath; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.cnzutai.zutai.service.CsPagePOService; +import com.njcn.product.cnzutai.zutai.mapper.CsConfigurationMapper; +import com.njcn.product.cnzutai.zutai.mapper.CsPagePOMapper; +import com.njcn.product.cnzutai.zutai.pojo.param.CsPageParm; +import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO; +import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsPageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +/** + * + * Description: + * Date: 2023/5/31 14:31【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +public class CsPagePOServiceImpl extends ServiceImpl implements CsPagePOService { + private final FileStorageUtil fileStorageUtil; + private final CsConfigurationMapper csConfigurationMapper; + // private final UserFeignClient userFeignClient; + + @Override + @Transactional(rollbackFor = {Exception.class}) + public boolean add(CsPageParm csPageParm) { + QueryWrapper csPagePOQueryWrapper = new QueryWrapper<>(); + String pid = csPageParm.getPid(); + csPagePOQueryWrapper.eq("pid",pid); + List csPagePOList = this.baseMapper.selectList(csPagePOQueryWrapper); + if(CollUtil.isNotEmpty(csPagePOList)){ + //先删除旧的json文件 + for(CsPagePO csPagePO : csPagePOList){ + if(StrUtil.isNotBlank(csPagePO.getPath())){ + fileStorageUtil.deleteFile(csPagePO.getPath()); + } + } + } + this.getBaseMapper().delete(csPagePOQueryWrapper); + InputStream inputStream = null; + MultipartFile multipartFile = csPageParm.getMultipartFile(); + try { + inputStream = multipartFile.getInputStream(); // 获取文件的输入流 + String text = new BufferedReader( + new InputStreamReader(inputStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); + List csPagePOS = JSONUtil.toList(text, CsPagePO.class); + csPagePOS.forEach(temp->{ + String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(temp.getPath()), OssPath.CONFIGURATIONPATH, OssPath.CONFIGURATIONNAME); + temp.setPid(pid); + temp.setStatus("1"); + temp.setPath(s); + this.save(temp); + }); + } catch (IOException e) { + throw new RuntimeException(e); + } + finally { + try { + inputStream.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return true; + } + + @Override + @Transactional(rollbackFor = {Exception.class}) + public boolean audit(CsPageParm.CsPageParmAuditParam auditParm) { +// CsPagePO csPagePO = new CsPagePO(); +// CsPagePO byId = this.getById(auditParm.getId()); +// fileStorageUtil.deleteFile(byId.getPath()); +// BeanUtils.copyProperties(auditParm, csPagePO); +// String s = fileStorageUtil.uploadMultipart(auditParm.getMultipartFile(), HarmonicConstant.CONFIGURATIONPATH); +// +// csPagePO.setPath(s); +// +// return this.updateById(csPagePO); + return true; + } + + @Override + public IPage queryPage(CsPageParm.CsPageParmQueryParam csPageParam) { + Page returnpage = new Page<> (csPageParam.getPageNum(), csPageParam.getPageSize ( )); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq(StrUtil.isNotBlank (csPageParam.getPid()),CsPagePO.COL_PID,csPageParam.getPid()). + like(StrUtil.isNotBlank (csPageParam.getSearchValue()),CsPagePO.COL_NAME,csPageParam.getSearchValue()). + eq ("status",1); + // orderByAsc(CsPagePO.COL_KID) + + IPage pageData = this.page(new Page<>(csPageParam.getPageNum(), csPageParam.getPageSize()), queryWrapper); + + List collect = pageData.getRecords().stream().map(temp -> { + CsPageVO csPageVO = new CsPageVO(); + CsConfigurationPO csConfigurationPO = csConfigurationMapper.selectById(temp.getPid()); + BeanUtils.copyProperties(temp, csPageVO); + csPageVO.setConfigurationName(csConfigurationPO.getName()); + InputStream fileStream = fileStorageUtil.getFileStream(temp.getPath()); + String text = new BufferedReader( + new InputStreamReader(fileStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); + csPageVO.setPath(text); +// csPageVO.setOperater(collect2.get(csPageVO.getCreateBy())); + return csPageVO; + }).collect(Collectors.toList()); + returnpage.setRecords(collect); + returnpage.setTotal(pageData.getTotal()); + + return returnpage; + } + + @Override + public CsPagePO queryById(String id) { + return this.lambdaQuery().eq(CsPagePO::getId,id).one(); + } + + + /*将strin写入Json文件,返回一个InputStream*/ + public InputStream writeJsonStringToInputStream(String jsonString) { + // 转换为输入流 + ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); + return inputStream; + } + + +} diff --git a/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/LineTargetServiceImpl.java b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/LineTargetServiceImpl.java new file mode 100644 index 0000000..87c3911 --- /dev/null +++ b/cn-zutai/src/main/java/com/njcn/product/cnzutai/zutai/service/impl/LineTargetServiceImpl.java @@ -0,0 +1,471 @@ +package com.njcn.product.cnzutai.zutai.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.njcn.common.pojo.exception.BusinessException; + +import com.njcn.influx.pojo.dto.StatisticalDataDTO; +import com.njcn.influx.service.CommonService; +import com.njcn.oss.utils.FileStorageUtil; +import com.njcn.product.cnzutai.zutai.pojo.dto.ZuTaiDTO; +import com.njcn.product.cnzutai.zutai.pojo.enums.CsSystemResponseEnum; +import com.njcn.product.cnzutai.zutai.pojo.vo.CsRtDataVO; +import com.njcn.product.cnzutai.zutai.pojo.vo.DataArrayTreeVO; +import com.njcn.product.cnzutai.zutai.service.CsPagePOService; +import com.njcn.product.cnzutai.zutai.service.ILineTargetService; + +import lombok.AllArgsConstructor; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * 类的介绍: + * + * @author xuyang + * @version 1.0.0 + * @createTime 2023/6/1 10:11 + */ +@Service +@AllArgsConstructor +public class LineTargetServiceImpl implements ILineTargetService { + + + + private final FileStorageUtil fileStorageUtil; + + private final CsPagePOService csPagePOService; + + private final CommonService commonService; + + + @Override + public List getLineTarget(String lineId) { +// List setList = new ArrayList<>(); +// String devId = csLedgerFeignClient.findDevByLineId(lineId).getData(); +// //1.获取监测点的安装位置 +// List lineList = csLineFeignClient.queryLineById(Collections.singletonList(lineId)).getData(); +// if (CollectionUtils.isEmpty(lineList)){ +// return new ArrayList(); +// } +// CsLinePO line = csLineFeignClient.queryLineById(Collections.singletonList(lineId)).getData().get(0); +// String code = dicDataFeignClient.getDicDataById(line.getPosition()).getData().getCode(); +// String modelId = null; +// List dataSetList = new ArrayList<>(); +// //治理监测点 +// if (Objects.equals(code, DicDataEnum.OUTPUT_SIDE.getCode())){ +// modelId = devModelRelationFeignClient.getModelByType(devId,0).getData(); +// dataSetList = dataSetFeignClient.getDataSet(modelId,0).getData(); +// } +// //电网侧监测点 +// else if (Objects.equals(code, DicDataEnum.GRID_SIDE.getCode())){ +// modelId = devModelRelationFeignClient.getModelByType(devId,1).getData(); +// dataSetList = dataSetFeignClient.getDataSet(modelId,1).getData(); +// } +// //负载侧监测点 +// else if (Objects.equals(code, DicDataEnum.LOAD_SIDE.getCode())){ +// modelId = devModelRelationFeignClient.getModelByType(devId,1).getData(); +// dataSetList = dataSetFeignClient.getDataSet(modelId,2).getData(); +// } +// setList = dataSetList.stream().map(LineTargetVO::getId).collect(Collectors.toList()); +// return dataArrayFeignClient.getDataArray(setList).getData(); + return null; + } + + @Override + public List getLineData(String id) { + List result = new ArrayList<>(); + String path = csPagePOService.queryById(id).getPath(); + InputStream inputStream = fileStorageUtil.getFileStream(path); + ZuTaiDTO zuTaiDto = analysisJson(inputStream); + + zuTaiDto.getJson().forEach(item->{ + if (!CollectionUtils.isEmpty(item.getUidNames())){ + for (int i = 0; i < item.getUidNames().size(); i++) { + String temp = item.getUidNames().get(i); + String targetTag = null; + String phasic = null; + String dataType = null; +// String[] tmepUidName = temp.split(" / "); +// if(tmepUidName.length==2){ +// targetTag = tmepUidName[0]; +// phasic = "T"; +// dataType = tmepUidName[1]; +// }else if (tmepUidName.length==3){ +// targetTag = tmepUidName[0]; +// phasic = tmepUidName[1]; +// dataType = tmepUidName[2]; +// } + + if (CollectionUtils.isEmpty(item.getUid()) || StringUtils.isEmpty(item.getLineId())){ + throw new BusinessException(CsSystemResponseEnum.BIND_TARGET_ERROR); + } + List tempUid = item.getUid().get(i); + String s = tempUid.get(tempUid.size() - 1); + String[] tempTable = s.replace("$", "").split("#"); + result.add(getLineRtData(item.getId(),item.getLineId(),tempTable[3],tempTable[0],tempTable[1],tempTable[2].toUpperCase(),temp,item.getUnit().get(i))); + } + + } + + + }); + return result; + } + + /** + * 解析json文件 + */ + public ZuTaiDTO analysisJson(InputStream inputStream) { + + ObjectMapper mapper = new ObjectMapper(); + + String text = new BufferedReader( + new InputStreamReader(inputStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); + + + ZuTaiDTO config = null; + try { + config = mapper.readValue(text, ZuTaiDTO.class); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + return config; + } + + /** + * 通过orm框架获取数据 + * @param id 图元Id + * @param lineId 监测点Id + * @param tableName 表名称 + * @param columnName 字段名称 + * @param phasic 相别 + * @param dataType 数据类型 + * @param target 数据名称 + * @return + */ + public CsRtDataVO getLineRtData(String id,String lineId, String tableName, String columnName, String phasic, String dataType, String target,String uint) { + CsRtDataVO csRtDataVO = new CsRtDataVO(); + StatisticalDataDTO statisticalDataDTO = commonService.getLineRtData(lineId,tableName,columnName,phasic,dataType); + if(Objects.isNull(statisticalDataDTO)){ + statisticalDataDTO = new StatisticalDataDTO(); + statisticalDataDTO.setLineId(lineId); + statisticalDataDTO.setPhaseType(phasic); + statisticalDataDTO.setValueType(dataType); + statisticalDataDTO.setValue(3.1415926); + } else { + statisticalDataDTO.setValue(BigDecimal.valueOf(statisticalDataDTO.getValue()).setScale(4, RoundingMode.HALF_UP).doubleValue()); + } + String targetTag = null; + String targetPhasic = null; + String targetDataType = null; + + String[] tmepUidName = target.split(" / "); + if(tmepUidName.length==2){ + targetTag = tmepUidName[0]; + targetDataType = getDataType(tmepUidName[1]) ; + }else if (tmepUidName.length==3){ + targetTag = tmepUidName[0]; + targetPhasic = tmepUidName[1]; + targetDataType =getDataType(tmepUidName[2]) ; + } else if (tmepUidName.length==4) { + targetTag = tmepUidName[1]; + targetPhasic = tmepUidName[2]; + targetDataType =getDataType(tmepUidName[3]) ; + } + statisticalDataDTO.setStatisticalName((Objects.isNull(targetPhasic)?"":targetPhasic+"相_")+targetTag+"_"+targetDataType); + statisticalDataDTO.setTarget(columnName + "$" + phasic + "$" + dataType); + BeanUtils.copyProperties(statisticalDataDTO,csRtDataVO); + csRtDataVO.setId(id); + csRtDataVO.setUnit(uint); + return csRtDataVO; + } + + public String getDataType(String statItem){ + String valueTypeName = ""; + switch (statItem) { + case "max": + valueTypeName = "最大值"; + break; + case "min": + valueTypeName = "最小值"; + break; + case "avg": + valueTypeName = "平均值"; + break; + case "cp95": + valueTypeName = "cp95值"; + break; + default: + break; + } + return valueTypeName; + } + public static void main(String[] args) { + ObjectMapper mapper = new ObjectMapper(); + String temp ="{\n" + + " \"canvasCfg\": {\n" + + " \"width\": 1920,\n" + + " \"height\": 1080,\n" + + " \"scale\": 1,\n" + + " \"color\": \"\",\n" + + " \"img\": \"\",\n" + + " \"guide\": true,\n" + + " \"adsorp\": true,\n" + + " \"adsorp_diff\": 5,\n" + + " \"transform_origin\": {\n" + + " \"x\": 0,\n" + + " \"y\": 0\n" + + " },\n" + + " \"drag_offset\": {\n" + + " \"x\": 0,\n" + + " \"y\": 0\n" + + " }\n" + + " },\n" + + " \"gridCfg\": {\n" + + " \"enabled\": true,\n" + + " \"align\": true,\n" + + " \"size\": 10\n" + + " },\n" + + " \"json\": [\n" + + " {\n" + + " \"id\": \"c53cccb8c65201c192d8c57fbdb4d993-fGe6GgykpF\",\n" + + " \"title\": \"传输设备\",\n" + + " \"keyId\": \"\",\n" + + " \"type\": \"svg\",\n" + + " \"binfo\": {\n" + + " \"left\": 380,\n" + + " \"top\": 120,\n" + + " \"width\": 50,\n" + + " \"height\": 50,\n" + + " \"angle\": 0\n" + + " },\n" + + " \"resize\": true,\n" + + " \"rotate\": true,\n" + + " \"lock\": false,\n" + + " \"active\": false,\n" + + " \"hide\": false,\n" + + " \"props\": {\n" + + " \"fill\": \"#FF0000\"\n" + + " },\n" + + " \"tag\": \"c53cccb8c65201c192d8c57fbdb4d993\",\n" + + " \"common_animations\": {\n" + + " \"val\": \"\",\n" + + " \"delay\": \"delay-0s\",\n" + + " \"speed\": \"slow\",\n" + + " \"repeat\": \"infinite\"\n" + + " },\n" + + " \"use_proportional_scaling\": true,\n" + + " \"events\": [],\n" + + " \"lineId\": \"782d0aa0bfbe47b83f54f9b31b2d6c9a\",\n" + + " \"lineList\": [\n" + + " \"52e34eb68eeb13fa515737048772d204\",\n" + + " \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" + + " \"158445294c3f9b4507b6b19df403e467\",\n" + + " \"782d0aa0bfbe47b83f54f9b31b2d6c9a\"\n" + + " ],\n" + + " \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQ-COM_7 / 10kV母线_胜境11C线\",\n" + + " \"UID\": [\n" + + " [\n" + + " \"rms\",\n" + + " \"B\",\n" + + " \"$rms#B#max#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"B\",\n" + + " \"$rms#B#min#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"B\",\n" + + " \"$rms#B#avg#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"C\",\n" + + " \"$rms#C#max#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"C\",\n" + + " \"$rms#C#min#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"C\",\n" + + " \"$rms#C#avg#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"rms\",\n" + + " \"C\",\n" + + " \"$rms#C#cp95#data_v#NO$\"\n" + + " ]\n" + + " ],\n" + + " \"UIDName\": [\n" + + " \"相电压总有效值 / B / max\",\n" + + " \"相电压总有效值 / B / min\",\n" + + " \"相电压总有效值 / B / avg\",\n" + + " \"相电压总有效值 / C / max\",\n" + + " \"相电压总有效值 / C / min\",\n" + + " \"相电压总有效值 / C / avg\",\n" + + " \"相电压总有效值 / C / cp95\"\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"id\": \"d09fd211e9908c5fea5cc38c9447e268-mVLhsvkxPK\",\n" + + " \"title\": \"断路器\",\n" + + " \"keyId\": \"\",\n" + + " \"type\": \"svg\",\n" + + " \"binfo\": {\n" + + " \"left\": 610,\n" + + " \"top\": 270,\n" + + " \"width\": 50,\n" + + " \"height\": 50,\n" + + " \"angle\": 0\n" + + " },\n" + + " \"resize\": true,\n" + + " \"rotate\": true,\n" + + " \"lock\": false,\n" + + " \"active\": false,\n" + + " \"hide\": false,\n" + + " \"props\": {\n" + + " \"fill\": \"#FF0000\"\n" + + " },\n" + + " \"tag\": \"d09fd211e9908c5fea5cc38c9447e268\",\n" + + " \"common_animations\": {\n" + + " \"val\": \"\",\n" + + " \"delay\": \"delay-0s\",\n" + + " \"speed\": \"slow\",\n" + + " \"repeat\": \"infinite\"\n" + + " },\n" + + " \"use_proportional_scaling\": true,\n" + + " \"events\": [],\n" + + " \"lineId\": \"14a81218e58fa62465d232ff22eba30e\",\n" + + " \"lineList\": [\n" + + " \"52e34eb68eeb13fa515737048772d204\",\n" + + " \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" + + " \"591f9f6ad50db9e2dfb3f467682f7789\",\n" + + " \"14a81218e58fa62465d232ff22eba30e\"\n" + + " ],\n" + + " \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQCOM_3 / 10kV母线_东方12E线\",\n" + + " \"UID\": [\n" + + " [\n" + + " \"p\",\n" + + " \"p_2\",\n" + + " \"A\",\n" + + " \"$p_2#A#max#data_harmpower_p#NO$\"\n" + + " ],\n" + + " [\n" + + " \"p\",\n" + + " \"p_2\",\n" + + " \"A\",\n" + + " \"$p_2#A#min#data_harmpower_p#NO$\"\n" + + " ]\n" + + " \n" + + " ],\n" + + " \"UIDName\": [\n" + + " \"有功功率 / 2次有功功率 / A / max\",\n" + + " \"有功功率 / 2次有功功率 / A / min\"\n" + + " \n" + + " ]\n" + + " },\n" + + " {\n" + + " \"id\": \"ea37cb9e81e7dfd44babc986c3547a04-oJTFPUPGC3\",\n" + + " \"title\": \"电灯\",\n" + + " \"keyId\": \"\",\n" + + " \"type\": \"svg\",\n" + + " \"binfo\": {\n" + + " \"left\": 270,\n" + + " \"top\": 460,\n" + + " \"width\": 50,\n" + + " \"height\": 50,\n" + + " \"angle\": 0\n" + + " },\n" + + " \"resize\": true,\n" + + " \"rotate\": true,\n" + + " \"lock\": false,\n" + + " \"active\": false,\n" + + " \"hide\": false,\n" + + " \"props\": {\n" + + " \"fill\": \"#FF0000\"\n" + + " },\n" + + " \"tag\": \"ea37cb9e81e7dfd44babc986c3547a04\",\n" + + " \"common_animations\": {\n" + + " \"val\": \"\",\n" + + " \"delay\": \"delay-0s\",\n" + + " \"speed\": \"slow\",\n" + + " \"repeat\": \"infinite\"\n" + + " },\n" + + " \"use_proportional_scaling\": true,\n" + + " \"events\": [],\n" + + " \"lineId\": \"14a81218e58fa62465d232ff22eba30e\",\n" + + " \"lineList\": [\n" + + " \"52e34eb68eeb13fa515737048772d204\",\n" + + " \"d02b5cc062e6a0e0bcb784c2df6b2e98\",\n" + + " \"591f9f6ad50db9e2dfb3f467682f7789\",\n" + + " \"14a81218e58fa62465d232ff22eba30e\"\n" + + " ],\n" + + " \"lineName\": \"无锡供电公司 / 110kV下甸桥变 / PQCOM_3 / 10kV母线_东方12E线\",\n" + + " \"UID\": [\n" + + " [\n" + + " \"v_neg\",\n" + + " \"$v_neg#max#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"v_neg\",\n" + + " \"$v_neg#min#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"v_neg\",\n" + + " \"$v_neg#cp95#data_v#NO$\"\n" + + " ],\n" + + " [\n" + + " \"v_neg\",\n" + + " \"$v_neg#avg#data_v#NO$\"\n" + + " ]\n" + + " ],\n" + + " \"UIDName\": [\n" + + " \"电压负序分量 / max\",\n" + + " \"电压负序分量 / min\",\n" + + " \"电压负序分量 / avg\",\n" + + " \"电压负序分量 / cp95\"\n" + + " ]\n" + + " }\n" + + " ]\n" + + "}"; + ZuTaiDTO config = null; + try { + config = mapper.readValue(temp, ZuTaiDTO.class); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + + } +} + + + diff --git a/event_smart/.gitignore b/event_smart/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/event_smart/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/event_smart/pom.xml b/event_smart/pom.xml new file mode 100644 index 0000000..f8c8686 --- /dev/null +++ b/event_smart/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + + com.njcn.product + CN_Product + 1.0.0 + + + event_smart + + + + + com.njcn + njcn-common + 0.0.1 + + + + com.njcn + common-redis + 1.0.0 + + + + + + org.springframework.boot + spring-boot-starter-websocket + 2.7.12 + + + + + com.baomidou + dynamic-datasource-spring-boot-starter + 3.5.1 + + + + + com.njcn + spingboot2.3.12 + 2.3.12 + + + + com.njcn + mybatis-plus + 0.0.1 + + + + + com.oracle.database.jdbc + ojdbc8 + 21.6.0.0 + + + com.oracle.database.nls + orai18n + 21.1.0.0 + + + + + org.springframework.boot + spring-boot-starter-security + + + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + + + com.njcn + common-event + 1.0.0 + + + common-microservice + com.njcn + + + common-web + com.njcn + + + + + + com.google.guava + guava + 32.1.3-jre + + + + cn.afterturn + easypoi-spring-boot-starter + 4.4.0 + + + + + + + event_smart + + + org.springframework.boot + spring-boot-maven-plugin + + + package + + repackage + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + + src/main/resources + + **/* + + + + src/main/java + + **/*.xml + + + + + + + diff --git a/event_smart/src/main/java/com/njcn/product/event/EventSmartApplication.java b/event_smart/src/main/java/com/njcn/product/event/EventSmartApplication.java new file mode 100644 index 0000000..f6c6e67 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/EventSmartApplication.java @@ -0,0 +1,18 @@ +package com.njcn.product.event; + +import lombok.extern.slf4j.Slf4j; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@Slf4j +@SpringBootApplication(scanBasePackages = "com.njcn") +//@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WavePicComponent.class)) +@MapperScan("com.njcn.**.mapper") +public class EventSmartApplication { + + public static void main(String[] args) { + SpringApplication.run(EventSmartApplication.class, args); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/config/PqlineCache.java b/event_smart/src/main/java/com/njcn/product/event/devcie/config/PqlineCache.java new file mode 100644 index 0000000..fdc8aeb --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/config/PqlineCache.java @@ -0,0 +1,81 @@ +package com.njcn.product.event.devcie.config; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import com.njcn.product.event.devcie.mapper.PqLineMapper; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import com.njcn.product.event.transientes.service.PqsDeptsService; +import com.njcn.redis.utils.RedisUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Description: + * Date: 2025/07/28 上午 9:32【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Component +@Slf4j +public class PqlineCache { + @Autowired + private PqLineMapper pqLineMapper; + @Autowired + private RedisUtil redisUtil; + @Autowired + private PqsDeptslineService pqsDeptslineService; + @Autowired + + private PqsDeptsService pqsDeptsService; + private final static String NAME_KEY = "LineCache:"; + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + @PostConstruct + public void init() { + log.info("系统启动中。。。加载pqline"); + List pqLines = pqLineMapper.selectList(null); + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+"pqLineList",pqLines); + List list = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState, 1).list(); + for (PqsDepts pqsDepts : list) { + List deptAndChildren = pqsDeptsService.findDeptAndChildren(pqsDepts.getDeptsIndex()); + List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + + List result = new ArrayList<>(); + if(CollUtil.isNotEmpty(deptslineIds)){ + if(deptslineIds.size()> 1000 ){ + List> listList = CollUtil.split(deptslineIds,1000); + for(List li : listList){ + List temList = pqLineMapper.getRunMonitorIds(li); + result.addAll(temList); + } + }else { + result= pqLineMapper.getRunMonitorIds(deptslineIds); + } + } + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+pqsDepts.getDeptsIndex(),result); + } + + List deptsList = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list(); + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+"AllDept",deptsList); + } + + @PreDestroy + public void destroy() { + log.info("系统运行结束"); + redisUtil.deleteKeysByString(NAME_KEY); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/job/LineCacheJob.java b/event_smart/src/main/java/com/njcn/product/event/devcie/job/LineCacheJob.java new file mode 100644 index 0000000..0504e6f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/job/LineCacheJob.java @@ -0,0 +1,79 @@ +package com.njcn.product.event.devcie.job; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import com.njcn.product.event.devcie.mapper.PqDeviceMapper; +import com.njcn.product.event.devcie.mapper.PqLineMapper; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import com.njcn.product.event.transientes.service.PqsDeptsService; +import com.njcn.redis.utils.RedisUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Description: + * Date: 2025/08/05 上午 10:17【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Component +@EnableScheduling +public class LineCacheJob { + @Autowired + private PqLineMapper pqLineMapper; + @Autowired + private RedisUtil redisUtil; + @Autowired + private PqsDeptslineService pqsDeptslineService; + @Autowired + private PqsDeptsService pqsDeptsService; + + @Autowired + private PqDeviceMapper pqDeviceMapper; + + private final static String NAME_KEY = "LineCache:"; + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + @Scheduled(cron="0 0 1 * * ?" ) // 每3钟执行一次 + public void lineCache(){ + redisUtil.deleteKeysByString(NAME_KEY); + + List pqLines = pqLineMapper.selectList(null); + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+"pqLineList",pqLines); + List list = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState, 1).list(); + for (PqsDepts pqsDepts : list) { + List deptAndChildren = pqsDeptsService.findDeptAndChildren(pqsDepts.getDeptsIndex()); + List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + + List result = new ArrayList<>(); + if(CollUtil.isNotEmpty(deptslineIds)){ + if(deptslineIds.size()> 1000 ){ + List> listList = CollUtil.split(deptslineIds,1000); + for(List li : listList){ + List temList = pqLineMapper.getRunMonitorIds(li); + result.addAll(temList); + } + }else { + result= pqLineMapper.getRunMonitorIds(deptslineIds); + } + } + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+pqsDepts.getDeptsIndex(),result); + } + + List deptsList = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list(); + redisUtil.saveByKey(NAME_KEY + StrUtil.DASHED+"AllDept",deptsList); + + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceDetailMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceDetailMapper.java new file mode 100644 index 0000000..4cb6ec5 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceDetailMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqDeviceDetail; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/12 + */ +public interface PqDeviceDetailMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceMapper.java new file mode 100644 index 0000000..08352a7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqDeviceMapper.java @@ -0,0 +1,29 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.devcie.pojo.dto.DeviceDeptDTO; +import com.njcn.product.event.devcie.pojo.po.PqDevice; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDeviceMapper extends BaseMapper { + List queryListByIds(@Param("ids") List ids); + + Page selectDeviceDTOPage(Page pqsEventdetailPage, @Param("searchValue") String searchValue,@Param("devIndexs") List devIndexs); + + Page queryListByLineIds(Page pqsEventdetailPage, @Param("searchValue") String searchValue,@Param("lineIds") List lineIds); + + + List selectDeviceDept(); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqGdCompanyMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqGdCompanyMapper.java new file mode 100644 index 0000000..83f81d8 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqGdCompanyMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqGdCompany; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqGdCompanyMapper extends BaseMapper { + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLineMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLineMapper.java new file mode 100644 index 0000000..f285ab1 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLineMapper.java @@ -0,0 +1,28 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqLineMapper extends BaseMapper { + + List getBaseLineInfo(@Param("ids")List ids); + + + List getBaseLedger(@Param("ids")List ids,@Param("searchValue")String searchValue); + + + List getRunMonitorIds(@Param("ids")List ids); + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLinedetailMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLinedetailMapper.java new file mode 100644 index 0000000..c56bfcc --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqLinedetailMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqLinedetail; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface PqLinedetailMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqSubstationMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqSubstationMapper.java new file mode 100644 index 0000000..c3ce358 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqSubstationMapper.java @@ -0,0 +1,20 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.dto.SubstationDTO; +import com.njcn.product.event.devcie.pojo.po.PqSubstation; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqSubstationMapper extends BaseMapper { + List queryListByIds(@Param("ids")List ids); +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqsStationMapMapper.java b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqsStationMapMapper.java new file mode 100644 index 0000000..0adf451 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/PqsStationMapMapper.java @@ -0,0 +1,17 @@ +package com.njcn.product.event.devcie.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqsStationMap; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsStationMapMapper extends BaseMapper { + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqDeviceMapper.xml b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqDeviceMapper.xml new file mode 100644 index 0000000..f78e6f7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqDeviceMapper.xml @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + DEV_INDEX, GD_INDEX, SUB_INDEX, "NAME", "STATUS", DEVTYPE, LOGONTIME, UPDATETIME, + NODE_INDEX, PORTID, DEVFLAG, DEV_SERIES, DEV_KEY, IP, DEVMODEL, CALLFLAG, DATATYPE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqLineMapper.xml b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqLineMapper.xml new file mode 100644 index 0000000..6ecb2c3 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqLineMapper.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + LINE_INDEX, GD_INDEX, SUB_INDEX, SUBV_INDEX, DEV_INDEX, "NAME", PT1, PT2, CT1, CT2, + DEVCMP, DLCMP, JZCMP, XYCMP, SUBV_NO, "SCALE", SUBV_NAME + + + + + + + + + + + + diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqSubstationMapper.xml b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqSubstationMapper.xml new file mode 100644 index 0000000..f15fd61 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/mapper/mapping/PqSubstationMapper.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + SUB_INDEX, GD_INDEX, "NAME", "SCALE" + + + + \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDTO.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDTO.java new file mode 100644 index 0000000..f2f0b09 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDTO.java @@ -0,0 +1,45 @@ +package com.njcn.product.event.devcie.pojo.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * Description: + * Date: 2025/06/27 下午 3:25【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class DeviceDTO { + private Integer devId; + private String devName; + private Integer stationId; + private String stationName; + private String gdName; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updateTime; + private String devFlag; + private String ip; + private String manufacturerName; + + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate thisTimeCheck; + + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate nextTimeCheck; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime logonTime; + + private String deptName; + //通讯状态 + private Integer runFlag=0; + //装置通讯状态(0:中断;1:正常) + private Integer status; + private double onLineRate=0.00; + private double integrityRate = 0.00; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDeptDTO.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDeptDTO.java new file mode 100644 index 0000000..b158f55 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/DeviceDeptDTO.java @@ -0,0 +1,18 @@ +package com.njcn.product.event.devcie.pojo.dto; + +import lombok.Data; + +/** + * Description: + * Date: 2025/06/27 下午 3:25【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class DeviceDeptDTO { + private Integer devId; + private String deptId; + private String deptName; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/LedgerBaseInfoDTO.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/LedgerBaseInfoDTO.java new file mode 100644 index 0000000..6a25a34 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/LedgerBaseInfoDTO.java @@ -0,0 +1,41 @@ +package com.njcn.product.event.devcie.pojo.dto; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ +@Data +public class LedgerBaseInfoDTO { + private String gdName; + private String gdIndex; + + private Integer lineId; + + private String lineName; + + private Integer busBarId; + + private String busBarName; + + private String scale; + + private Integer devId; + + private String devName; + + private String objName; + + private Integer stationId; + + private String stationName; + //通讯状态 + private Integer runFlag=0; + + private Integer eventCount; + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/PqsDeptDTO.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/PqsDeptDTO.java new file mode 100644 index 0000000..167e08a --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/PqsDeptDTO.java @@ -0,0 +1,70 @@ +package com.njcn.product.event.devcie.pojo.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * Description: + * Date: 2025/07/29 下午 3:15【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class PqsDeptDTO { + /** + * 部门表Guid + */ + private String deptsIndex; + + /** + * 部门名称 + */ + + private String deptsname; + + /** + * 排序 + */ + + private Integer deptsDesc; + + /** + * (关联表PQS_User)用户表Guid + */ + + private String userIndex; + + /** + * 更新时间 + */ + + private LocalDateTime updatetime; + + /** + * 部门描述 + */ + + private String deptsDescription; + + /** + * 角色状态0:删除;1:正常; + */ + + private Integer state; + + /** + * 行政区域 + */ + + private String area; + + private String areaName; + + + private Integer customDept; + + + private String parentnodeid; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/SubstationDTO.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/SubstationDTO.java new file mode 100644 index 0000000..6e9b9dc --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/dto/SubstationDTO.java @@ -0,0 +1,22 @@ +package com.njcn.product.event.devcie.pojo.dto; + +import lombok.Data; + +/** + * Description: + * Date: 2025/06/27 下午 3:37【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class SubstationDTO { + + private Integer stationId; + private String stationName; + private String gdName; + private double longitude; + private double latitude; + private Integer runFlag=0;; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDevice.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDevice.java new file mode 100644 index 0000000..658964c --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDevice.java @@ -0,0 +1,127 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.time.LocalDateTime; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠? + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_DEVICE") +public class PqDevice { + /** + * 靠靠 + */ + @TableId(value = "DEV_INDEX", type = IdType.INPUT) + private Integer devIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "SUB_INDEX") + private Integer subIndex; + + /** + * 靠靠 + */ + @TableField(value = "\"NAME\"") + private String name; + + /** + * 靠靠靠(0:靠;1:靠) + */ + @TableField(value = "\"STATUS\"") + private Integer status; + + /** + * (靠縋QS_Dicdata)靠靠Guid + */ + @TableField(value = "DEVTYPE") + private String devtype; + + /** + * 靠靠 + */ + @TableField(value = "LOGONTIME") + private LocalDateTime logontime; + + /** + * 靠靠靠 + */ + @TableField(value = "UPDATETIME") + private LocalDateTime updatetime; + + /** + * 靠縉odeInformation)靠靠靠,靠靠靠靠靠靠靠? + */ + @TableField(value = "NODE_INDEX") + private Integer nodeIndex; + + /** + * 靠ID,靠靠靠 + */ + @TableField(value = "PORTID") + private Long portid; + + /** + * 靠靠(0:靠;1:靠;2:靠) + */ + @TableField(value = "DEVFLAG") + private Integer devflag; + + /** + * 靠靠?靠3ds靠 + */ + @TableField(value = "DEV_SERIES") + private String devSeries; + + /** + * 靠靠,靠3ds靠 + */ + @TableField(value = "DEV_KEY") + private String devKey; + + /** + * IP靠 + */ + @TableField(value = "IP") + private String ip; + + /** + * 靠靠(0:靠靠;1:靠靠) + */ + @TableField(value = "DEVMODEL") + private Integer devmodel; + + /** + * 靠靠? + */ + @TableField(value = "CALLFLAG") + private Integer callflag; + + /** + * 靠靠(0:靠靠;1:靠靠;2:靠靠) + */ + @TableField(value = "DATATYPE") + private Integer datatype; +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDeviceDetail.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDeviceDetail.java new file mode 100644 index 0000000..031cc5e --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqDeviceDetail.java @@ -0,0 +1,70 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/12 + */ +@TableName(value = "PQ_DEVICEDETAIL") +@Data +public class PqDeviceDetail { + + + @TableId + @TableField(value = "DEV_INDEX") + private Long devIndex; + + @TableField(value = "Manufacturer") + private String manufacturer; + + @TableField(value = "CheckFlag") + private Long checkFlag; + + @TableField(value="ThisTimeCheck") + private LocalDate ThisTimeCheck; + + @TableField(value="NextTimeCheck") + private LocalDate NextTimeCheck; + + @TableField(value="DATAPLAN") + private Long dataplan; + + @TableField(value="NEWTRAFFIC") + private Long newtraffic; + + + @TableField(value = "electroplate") + private Integer electroplate = 0; + + @TableField(value = "ONTIME") + private Integer ontime; + @TableField(value = "contract") + private String contract; + + @TableField(value = "DEV_CATENA") + private String devCatnea; + + @TableField(value = "SIM") + private String sim; + + @TableField(value = "DEV_NO") + private String devNo; + + @TableField(value = "DEV_LOCATION") + private String devLocation; + + @TableField(value = "IS_ALARM") + private Integer isAlarm; + + + + + } diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqGdCompany.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqGdCompany.java new file mode 100644 index 0000000..8082e7d --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqGdCompany.java @@ -0,0 +1,27 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/9 + */ +@Data +@TableName(value = "PQ_GDINFORMATION") +public class PqGdCompany { + + @TableId + @TableField(value="GD_INDEX") + private Long gdIndex; + + @TableField(value="NAME") + private String name; + + @TableField(value="PROVINCE_INDEX") + private Long provinceIndex; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLine.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLine.java new file mode 100644 index 0000000..31f7a12 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLine.java @@ -0,0 +1,132 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠? + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_LINE") +public class PqLine { + /** + * 靠靠 + */ + @TableId(value = "LINE_INDEX", type = IdType.INPUT) + private Integer lineIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "SUB_INDEX") + private Integer subIndex; + + /** + * 靠靠 + */ + @TableField(value = "SUBV_INDEX") + private Integer subvIndex; + + /** + * 靠靠 + */ + @TableField(value = "DEV_INDEX") + private Integer devIndex; + + /** + * 靠靠 + */ + @TableField(value = "\"NAME\"") + private String name; + + /** + * PT靠靠 + */ + @TableField(value = "PT1") + private Double pt1; + + /** + * PT靠靠 + */ + @TableField(value = "PT2") + private Double pt2; + + /** + * CT靠靠 + */ + @TableField(value = "CT1") + private Double ct1; + + /** + * CT靠靠 + */ + @TableField(value = "CT2") + private Double ct2; + + /** + * 靠靠 + */ + @TableField(value = "DEVCMP") + private Double devcmp; + + /** + * 靠靠 + */ + @TableField(value = "DLCMP") + private Double dlcmp; + + /** + * 靠靠 + */ + @TableField(value = "JZCMP") + private Double jzcmp; + + /** + * 靠靠 + */ + @TableField(value = "XYCMP") + private Double xycmp; + + /** + * 靠?靠靠靠靠靠靠? + */ + @TableField(value = "SUBV_NO") + private Integer subvNo; + + /** + * (靠PQS_Dictionary?靠靠Guid + */ + @TableField(value = "\"SCALE\"") + private String scale; + + /** + * 靠靠 + */ + @TableField(value = "SUBV_NAME") + private String subvName; + + @TableField(exist = false) + private String subName; + + @TableField(exist = false) + private String deptName; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLinedetail.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLinedetail.java new file mode 100644 index 0000000..c227c41 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqLinedetail.java @@ -0,0 +1,52 @@ +package com.njcn.product.event.devcie.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("PQ_LINEDETAIL") +public class PqLinedetail { + + @TableId(value = "LINE_INDEX", type = IdType.INPUT) + private Integer lineIndex; + + private Integer gdIndex; + + private Integer subIndex; + + private String lineName; + + private Integer pttype; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date lastTime; + + private Integer tinterval; + + private String loadtype; + + private String businesstype; + + private String remark; + + private String monitorId; + + private Integer powerid; + + private String objname; + + @TableField(fill = FieldFill.INSERT) + private Integer statflag; + + private String lineGrade; + + private String powerSubstationName; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqSubstation.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqSubstation.java new file mode 100644 index 0000000..edc0c5e --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqSubstation.java @@ -0,0 +1,45 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 靠靠靠 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQ_SUBSTATION") +public class PqSubstation { + /** + * 靠靠? + */ + @TableId(value = "SUB_INDEX", type = IdType.INPUT) + private Integer subIndex; + + /** + * 靠靠靠 + */ + @TableField(value = "GD_INDEX") + private Integer gdIndex; + + /** + * 靠靠? + */ + @TableField(value = "\"NAME\"") + private String name; + + @TableField(value = "\"SCALE\"") + private String scale; +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsDeptsline.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsDeptsline.java new file mode 100644 index 0000000..4bc3653 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsDeptsline.java @@ -0,0 +1,31 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQS_DEPTSLINE") +public class PqsDeptsline { + /** + * 部门表Guid + */ + @TableField(value = "DEPTS_INDEX") + private String deptsIndex; + + @TableField(value = "LINE_INDEX") + private Integer lineIndex; + + @TableField(value = "SYSTYPE") + private String systype; +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsStationMap.java b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsStationMap.java new file mode 100644 index 0000000..b885cb8 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/pojo/po/PqsStationMap.java @@ -0,0 +1,58 @@ +package com.njcn.product.event.devcie.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/11 + */ +@TableName(value="PQS_MAP") +@Data +public class PqsStationMap { + + + @TableId + @TableField(value = "MAP_INDEX") + private String mapIndex; + + + @TableField(value = "SUB_INDEX") + private Long subIndex; + + + @TableField(value = "GD_INDEX") + private Long gdIndex; + + //经度 + + @TableField(value = "LONGITUDE") + private Float longItude; + + //纬度 + + @TableField(value = "LATITUDE") + private Float latItude; + + //数据状态 + + @TableField(value = "STATE") + private Long state; + + //用户ID + + @TableField(value = "USER_INDEX") + private String userIndex; + + //更新时间 + + @TableField(value = "UPDATETIME") + private Date updateTime; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqDeviceService.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqDeviceService.java new file mode 100644 index 0000000..f33513e --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqDeviceService.java @@ -0,0 +1,26 @@ +package com.njcn.product.event.devcie.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.devcie.pojo.dto.DeviceDeptDTO; +import com.njcn.product.event.devcie.pojo.po.PqDevice; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDeviceService extends IService{ + + List queryListByIds(List lineIds); + + Page selectDeviceDTOPage(Page pqsEventdetailPage, String searchValue, List devIndexs); + + List selectDeviceDept(); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqLineService.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqLineService.java new file mode 100644 index 0000000..d04181b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqLineService.java @@ -0,0 +1,24 @@ +package com.njcn.product.event.devcie.service; + +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.baomidou.mybatisplus.extension.service.IService; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqLineService extends IService{ + + + List getBaseLineInfo(List ids); + + List getBaseLedger(@Param("ids") List ids, @Param("searchValue") String searchValue); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqSubstationService.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqSubstationService.java new file mode 100644 index 0000000..15ca5bd --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqSubstationService.java @@ -0,0 +1,20 @@ +package com.njcn.product.event.devcie.service; + +import com.njcn.product.event.devcie.pojo.dto.SubstationDTO; +import com.njcn.product.event.devcie.pojo.po.PqSubstation; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqSubstationService extends IService{ + + List queryListByIds(List lineIds); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqsDeptslineService.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqsDeptslineService.java new file mode 100644 index 0000000..048a45f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/PqsDeptslineService.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.devcie.service; + +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.baomidou.mybatisplus.extension.service.IService; + /** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptslineService extends IService{ + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqDeviceServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqDeviceServiceImpl.java new file mode 100644 index 0000000..4447b6a --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqDeviceServiceImpl.java @@ -0,0 +1,38 @@ +package com.njcn.product.event.devcie.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.devcie.pojo.dto.DeviceDeptDTO; +import org.springframework.stereotype.Service; + +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.devcie.pojo.po.PqDevice; +import com.njcn.product.event.devcie.mapper.PqDeviceMapper; +import com.njcn.product.event.devcie.service.PqDeviceService; +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqDeviceServiceImpl extends ServiceImpl implements PqDeviceService{ + + @Override + public List queryListByIds(List lineIds) { + return this.baseMapper.queryListByIds(lineIds); + } + + @Override + public Page selectDeviceDTOPage(Page pqsEventdetailPage, String searchValue, List devIndexs) { + return this.baseMapper.selectDeviceDTOPage(pqsEventdetailPage,searchValue,devIndexs); + } + + @Override + public List selectDeviceDept() { + return this.baseMapper.selectDeviceDept(); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqLineServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqLineServiceImpl.java new file mode 100644 index 0000000..077a9ff --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqLineServiceImpl.java @@ -0,0 +1,69 @@ +package com.njcn.product.event.devcie.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.devcie.mapper.PqLineMapper; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.njcn.product.event.devcie.service.PqLineService; +import org.springframework.util.CollectionUtils; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:43【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqLineServiceImpl extends ServiceImpl implements PqLineService{ + + + @Override + public List getBaseLineInfo(List ids){ + List ledgerBaseInfoDTOS = new ArrayList<>(); + + if(CollectionUtils.isEmpty(ids)){ + return ledgerBaseInfoDTOS; + } + if(ids.size()>1000){ + List> listIds = CollUtil.split(ids,1000); + for(List itemIds : listIds){ + List temp =this.baseMapper.getBaseLineInfo(itemIds); + ledgerBaseInfoDTOS.addAll(temp); + } + }else { + List temp =this.baseMapper.getBaseLineInfo(ids); + ledgerBaseInfoDTOS.addAll(temp); + } + return ledgerBaseInfoDTOS; + } + + @Override + public List getBaseLedger(List ids,String searchValue) { + List ledgerBaseInfoDTOS = new ArrayList<>(); + + if(CollectionUtils.isEmpty(ids)){ + return ledgerBaseInfoDTOS; + } + if(ids.size()>1000){ + List> listIds = CollUtil.split(ids,1000); + for(List itemIds : listIds){ + List temp =this.baseMapper.getBaseLedger(itemIds,searchValue); + ledgerBaseInfoDTOS.addAll(temp); + } + }else { + List temp =this.baseMapper.getBaseLedger(ids,searchValue); + ledgerBaseInfoDTOS.addAll(temp); + } + return ledgerBaseInfoDTOS; + }; + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqSubstationServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqSubstationServiceImpl.java new file mode 100644 index 0000000..6e045de --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqSubstationServiceImpl.java @@ -0,0 +1,26 @@ +package com.njcn.product.event.devcie.service.impl; + +import com.njcn.product.event.devcie.pojo.dto.SubstationDTO; +import org.springframework.stereotype.Service; + +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.devcie.pojo.po.PqSubstation; +import com.njcn.product.event.devcie.mapper.PqSubstationMapper; +import com.njcn.product.event.devcie.service.PqSubstationService; +/** + * + * Description: + * Date: 2025/06/19 下午 1:48【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqSubstationServiceImpl extends ServiceImpl implements PqSubstationService{ + + @Override + public List queryListByIds(List lineIds) { + return this.baseMapper.queryListByIds(lineIds); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqsDeptslineServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqsDeptslineServiceImpl.java new file mode 100644 index 0000000..661c392 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/devcie/service/impl/PqsDeptslineServiceImpl.java @@ -0,0 +1,19 @@ +package com.njcn.product.event.devcie.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsDeptslineMapper; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsDeptslineServiceImpl extends ServiceImpl implements PqsDeptslineService{ + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/controller/EasyPoiWordExportController.java b/event_smart/src/main/java/com/njcn/product/event/report/controller/EasyPoiWordExportController.java new file mode 100644 index 0000000..5de4cfa --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/controller/EasyPoiWordExportController.java @@ -0,0 +1,49 @@ +package com.njcn.product.event.report.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.report.pojo.param.ReportExportParam; +import com.njcn.product.event.report.service.EasyPoiWordExportService; +import com.njcn.product.event.report.utils.WordTemplate; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; + +/** + * @Author: cdf + * @CreateTime: 2025-09-23 + * @Description: + */ +@Api(tags = "报告导出") +@RequestMapping("report") +@RestController +@RequiredArgsConstructor +@Slf4j +public class EasyPoiWordExportController extends BaseController { + + private final EasyPoiWordExportService easyPoiWordExportService; + + + @OperateInfo + @PostMapping("/get") + @ApiOperation("") + public void test(HttpServletResponse response, @RequestBody ReportExportParam param) { + String methodDescribe = getMethodDescribe("test"); + try { + easyPoiWordExportService.test(response,param); + } catch (Exception e) { + throw new RuntimeException(e); + } + // return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/pojo/dto/BjCustomReportDTO.java b/event_smart/src/main/java/com/njcn/product/event/report/pojo/dto/BjCustomReportDTO.java new file mode 100644 index 0000000..878b0d7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/pojo/dto/BjCustomReportDTO.java @@ -0,0 +1,46 @@ +package com.njcn.product.event.report.pojo.dto; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-09-24 + * @Description: + */ +@Data +public class BjCustomReportDTO { + // 日期格式化(如“2025年09月17日”) + private String dateFormat; + // 总监测装置数量 + private Integer totalDevice; + // 总变电站数量 + private Integer totalSubstation; + // 总母线数量 + private Integer totalBus; + // 母线电压等级列表(如“220kV母线XX条、110kV母线XX条、10kV母线XX条”) + private String busVoltageList; + //亦庄涉及变电站22座,母线102条,其中:110kV母线7条,10kV母线95条。 + private String areaInfo; + // 统计日期范围(如“2025年09月17日16:46-16:53”) + private String dateRange; + // 北京地区总事件数 + private Integer bjTotalEvent; + // 北京地区涉及变电站数 + private Integer totalEventSubstation; + // 北京地区涉及母线数 + private Integer bjTotalBus; + // 变电站电压等级说明(如“220kV变电站X座、110kV变电站X座、10kV变电站X座”) + private String stationVoltage; + // 发生暂降的母线数 + private Integer busEventNum; + // 残余电压范围(如“16.48%-86.99%”) + private String residualVoltageRange; + // 持续时间范围(如“0.05s-0.086s”) + private String durationRange; + // 受影响用户类型(如“半导体企业、地铁、医院、政府机关”) + private String objTypeList; + // 受影响用户总数 + private Integer affectedUserCount; + // 暂降区域说明(如“亦庄经济开发区、通州新城、中心城区”) + private String areaContent; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/pojo/param/ReportExportParam.java b/event_smart/src/main/java/com/njcn/product/event/report/pojo/param/ReportExportParam.java new file mode 100644 index 0000000..6669c5f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/pojo/param/ReportExportParam.java @@ -0,0 +1,30 @@ +package com.njcn.product.event.report.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-09-24 + * @Description: + */ +@Data +public class ReportExportParam { + + @ApiModelProperty("部门id") + private String deptId; + + @ApiModelProperty("开始时间") + private String searchBeginTime; + + @ApiModelProperty("结束时间") + private String searchEndTime; + + @ApiModelProperty("部门集合") + private List deptList; + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/service/EasyPoiWordExportService.java b/event_smart/src/main/java/com/njcn/product/event/report/service/EasyPoiWordExportService.java new file mode 100644 index 0000000..6c25e6c --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/service/EasyPoiWordExportService.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.report.service; + +import com.njcn.product.event.report.pojo.param.ReportExportParam; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; + +import javax.servlet.http.HttpServletResponse; + +/** + * @Author: cdf + * @CreateTime: 2025-09-23 + * @Description: + */ +public interface EasyPoiWordExportService { + + void test(HttpServletResponse response, ReportExportParam param); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/service/impl/EasyPoiWordExportServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/report/service/impl/EasyPoiWordExportServiceImpl.java new file mode 100644 index 0000000..b9dc8ff --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/service/impl/EasyPoiWordExportServiceImpl.java @@ -0,0 +1,253 @@ +package com.njcn.product.event.report.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.text.StrBuilder; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.event.devcie.mapper.PqLineMapper; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.dto.PqsDeptDTO; +import com.njcn.product.event.report.pojo.dto.BjCustomReportDTO; +import com.njcn.product.event.report.pojo.param.ReportExportParam; +import com.njcn.product.event.report.service.EasyPoiWordExportService; +import com.njcn.product.event.report.utils.WordTemplate; +import com.njcn.product.event.transientes.mapper.*; +import com.njcn.product.event.transientes.pojo.enums.DicTypeEnum; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.po.*; +import com.njcn.product.event.transientes.service.CommGeneralService; +import com.njcn.product.event.transientes.service.MsgEventConfigService; +import lombok.RequiredArgsConstructor; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.DoubleStream; + +/** + * @Author: cdf + * @CreateTime: 2025-09-23 + * @Description: + */ +@Service +@RequiredArgsConstructor +public class EasyPoiWordExportServiceImpl implements EasyPoiWordExportService { + + private final CommGeneralService commGeneralService; + + private final PqLineMapper pqLineMapper; + + private final PqsDicDataMapper pqsDicDataMapper; + + private final PqsDicTypeMapper pqsDicTypeMapper; + + private final PqsDeptsMapper pqsDeptsMapper; + + private final PqsEventdetailMapper pqsEventdetailMapper; + + private final MsgEventConfigService msgEventConfigService; + private final PqUserLineAssMapper pqUserLineAssMapper; + private final PqUserLedgerMapper pqUserLedgerMapper; + private final PqsDicTreeMapper pqsDicTreeMapper; + + + public void test(HttpServletResponse response, ReportExportParam param) { + try { + List deptIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if (CollUtil.isEmpty(deptIds)) { + throw new BusinessException(CommonResponseEnum.FAIL, "当前部门未绑定监测点"); + } + + //字典信息 + PqsDicType pqsDicType = pqsDicTypeMapper.selectOne(new LambdaQueryWrapper().eq(PqsDicType::getDicTypeName, DicTypeEnum.VOLTAGE.getDicName())); + List pqsDicDataList = pqsDicDataMapper.selectList(new LambdaQueryWrapper().eq(PqsDicData::getDicType, pqsDicType.getDicTypeIndex())); + Map pqsDicDataMap = pqsDicDataList.stream().collect(Collectors.toMap(PqsDicData::getDicIndex, dic -> dic)); + + List pqsDicTreePOList = pqsDicTreeMapper.selectList(null); + Map treePOMap = pqsDicTreePOList.stream().collect(Collectors.toMap(PqsDicTreePO::getId,tree->tree)); + + BjCustomReportDTO bjReportDTO = new BjCustomReportDTO(); + ledgerAssemble(bjReportDTO,param,deptIds,pqsDicDataMap); + + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .between(PqsEventdetail::getTimeid,DateUtil.parse(param.getSearchBeginTime(),DatePattern.NORM_DATETIME_PATTERN),DateUtil.parse(param.getSearchEndTime(),DatePattern.NORM_DATETIME_PATTERN)); + if (deptIds.size() > 1000) { + List> listList = CollUtil.split(deptIds, 1000); + lambdaQueryWrapper.and(w->{ + w.or(i->{ + for(List ids : listList){ + i.in(PqsEventdetail::getLineid,ids); + } + }); + }); + } else { + lambdaQueryWrapper.in(PqsEventdetail::getLineid,deptIds); + } + + List pqsEventdetailList = pqsEventdetailMapper.selectList(lambdaQueryWrapper); + bjReportDTO.setBjTotalEvent(pqsEventdetailList.size()); + List lineIds = pqsEventdetailList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List ledgerBaseInfoDTOList = pqLineMapper.getBaseLedger(lineIds,null); + long stationCount = ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getStationId).distinct().count(); + bjReportDTO.setTotalEventSubstation((int)stationCount); + long busCount = ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getBusBarId).distinct().count(); + bjReportDTO.setBjTotalBus((int)busCount); + String busVoltageStr = busVoltageDeal(ledgerBaseInfoDTOList,pqsDicDataMap); + bjReportDTO.setStationVoltage(busVoltageStr); + + double min = pqsEventdetailList.stream().mapToDouble(PqsEventdetail::getEventvalue).min().getAsDouble()*100; + double max = pqsEventdetailList.stream().mapToDouble(PqsEventdetail::getEventvalue).max().getAsDouble()*100; + bjReportDTO.setResidualVoltageRange(min+"%-"+max+"%"); + + double minPersisTime = pqsEventdetailList.stream().mapToDouble(PqsEventdetail::getPersisttime).min().getAsDouble()/1000; + double maxPersisTime = pqsEventdetailList.stream().mapToDouble(PqsEventdetail::getPersisttime).max().getAsDouble()/1000; + bjReportDTO.setDurationRange(minPersisTime+"s-"+maxPersisTime+"s"); + + List pqUserLineAssPOS = pqUserLineAssMapper.selectList(new LambdaQueryWrapper().in(PqUserLineAssPO::getLineIndex,lineIds)); + List userIds = pqUserLineAssPOS.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + List pqUserLedgerPOList = pqUserLedgerMapper.selectList(new LambdaQueryWrapper().in(PqUserLedgerPO::getId,userIds)); + Map> stringListMap = pqUserLedgerPOList.stream().collect(Collectors.groupingBy(PqUserLedgerPO::getSmallObjType)); + + String treeStr = userToStr(stringListMap,treePOMap); + + bjReportDTO.setObjTypeList(treeStr); + bjReportDTO.setAffectedUserCount(pqUserLedgerPOList.size()); + + ObjectMapper mapper = new ObjectMapper(); + Map map = mapper.convertValue(bjReportDTO,Map.class); + + WordTemplate.generateWordDownload("template/test.docx", response, "aa.docx", map); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void addUserDataToTable(XWPFDocument document) { + // 创建表格 + // 填充数据到表格(此处为示例代码框架,实际需完善表格创建和数据填充逻辑) + // 例如:创建表头、添加数据行等 + } + + /** + * 组装台账 + * @param bjReportDTO + * @param param + * @param deptIds + */ + private void ledgerAssemble(BjCustomReportDTO bjReportDTO,ReportExportParam param,List deptIds,Map pqsDicDataMap){ + bjReportDTO.setDateRange(param.getSearchBeginTime()+"至"+param.getSearchEndTime()); + + //台账信息 + List ledgerList = new ArrayList<>(); + if (deptIds.size() > 1000) { + List> listList = CollUtil.split(deptIds, 1000); + for (List ids : listList) { + List temList = pqLineMapper.getBaseLedger(ids, null); + ledgerList.addAll(temList); + } + } else { + ledgerList = pqLineMapper.getBaseLedger(deptIds, null); + } + + + long devCount = ledgerList.stream().map(LedgerBaseInfoDTO::getDevId).distinct().count(); + long stationCount = ledgerList.stream().map(LedgerBaseInfoDTO::getStationId).distinct().count(); + long busCount = ledgerList.stream().map(LedgerBaseInfoDTO::getBusBarId).distinct().count(); + + Map> scaleMap = ledgerList.stream().collect(Collectors.groupingBy(LedgerBaseInfoDTO::getScale)); + String result = scaleMap.entrySet().stream() + .map(entry -> { + String scale = entry.getKey(); + long busNum = entry.getValue().stream() + .map(LedgerBaseInfoDTO::getBusBarId) + .distinct() + .count(); + return pqsDicDataMap.get(scale).getDicName() + "母线" + busNum + "条"; + }) + // 用分号连接 + .collect(Collectors.joining(StrUtil.COMMA)); + bjReportDTO.setBusVoltageList(result); + + StringBuilder temStr = new StringBuilder(); + List pqsDeptsList = pqsDeptsMapper.getDeptList(param.getDeptList()); + Map deptMap = pqsDeptsList.stream().collect(Collectors.toMap(PqsDeptDTO::getDeptsIndex,PqsDeptDTO::getDeptsname)); + for (String deptId : param.getDeptList()) { + String deptName = deptMap.get(deptId); + StrBuilder strBuilderInner = new StrBuilder(deptName+"涉及变电站"); + List temIds = commGeneralService.getLineIdsByRedis(deptId); + List dtoList = pqLineMapper.getBaseLedger(temIds, null); + + long innerStation = dtoList.stream().map(LedgerBaseInfoDTO::getStationId).distinct().count(); + long innerBus = dtoList.stream().map(LedgerBaseInfoDTO::getStationId).distinct().count(); + + strBuilderInner.append(String.valueOf(innerStation)).append("座,母线").append(String.valueOf(innerBus)).append("条,其中:"); + Map> scaleInnerMap = dtoList.stream().collect(Collectors.groupingBy(LedgerBaseInfoDTO::getScale)); + String resultContent = scaleInnerMap.entrySet().stream() + .map(entry -> { + String scale = entry.getKey(); + long busNum = entry.getValue().stream() + .map(LedgerBaseInfoDTO::getBusBarId) + .distinct() + .count(); + return pqsDicDataMap.get(scale).getDicName() + "母线" + busNum + "条"; + }) + // 用分号连接 + .collect(Collectors.joining(StrUtil.COMMA)); + strBuilderInner.append(resultContent).append(";"); + temStr.append(strBuilderInner); + } + bjReportDTO.setAreaInfo(temStr.toString()); + + bjReportDTO.setDateFormat(DateUtil.format(DateUtil.parse(param.getSearchBeginTime()), DatePattern.NORM_DATE_PATTERN)); + bjReportDTO.setTotalDevice((int) devCount); + bjReportDTO.setTotalSubstation((int) stationCount); + bjReportDTO.setTotalBus((int) busCount); + } + + + private String busVoltageDeal(List ledgerList,Map pqsDicDataMap){ + Map> scaleMap = ledgerList.stream().collect(Collectors.groupingBy(LedgerBaseInfoDTO::getScale)); + String result = scaleMap.entrySet().stream() + .map(entry -> { + String scale = entry.getKey(); + long busNum = entry.getValue().stream() + .map(LedgerBaseInfoDTO::getBusBarId) + .distinct() + .count(); + return pqsDicDataMap.get(scale).getDicName() + "母线" + busNum + "条"; + }) + // 用分号连接 + .collect(Collectors.joining(StrUtil.COMMA)); + return result; + } + + private String userToStr(Map> stringListMap,Map treePOMap){ + String result = stringListMap.entrySet().stream() + .map(entry -> { + String scale = entry.getKey(); + long busNum = entry.getValue().stream() + .map(PqUserLedgerPO::getId) + .distinct() + .count(); + return treePOMap.get(scale).getName(); + }) + // 用分号连接 + .collect(Collectors.joining(StrUtil.COMMA)); + return result; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/report/utils/WordTemplate.java b/event_smart/src/main/java/com/njcn/product/event/report/utils/WordTemplate.java new file mode 100644 index 0000000..0df4936 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/report/utils/WordTemplate.java @@ -0,0 +1,119 @@ +package com.njcn.product.event.report.utils; + +import cn.afterturn.easypoi.word.WordExportUtil; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import java.io.*; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Author: cdf + * @CreateTime: 2025-09-23 + * @Description: + */ +public class WordTemplate { + + public static void main(String[] args) throws Exception { + // 模板文件路径 + // 1. 处理模板路径并获取输入流 + String temPath = getTemplateInputStream("template/test.docx"); + if (temPath == null) { + throw new FileNotFoundException("模板文件不存在: template/test.docx"); + } + // 准备数据 + Map map = new HashMap<>(); + map.put("title", "用户信息表"); + map.put("userList", getUsersData()); // 假设getUsersData()方法返回用户数据列表 + // 导出 Word 文档 + XWPFDocument doc = WordExportUtil.exportWord07(temPath, map); + try (FileOutputStream outStream = new FileOutputStream("user_info.docx")) { + doc.write(outStream); + } + } + + private static List> getUsersData() { + // 返回模拟用户数据(实际需从数据库或其他数据源获取) + return new ArrayList<>(); + } + + + /** + * 生成Word文档(响应到浏览器下载) + * + * @param templatePath 模板路径 + * @param response HttpServletResponse + * @param fileName 下载文件名(如“20250917电压暂降监测报告.docx”) + * @param data 数据Map + */ + public static void generateWordDownload(String templatePath, javax.servlet.http.HttpServletResponse response, String fileName, Map data) throws Exception { + // 设置响应头 + response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1")); + response.setCharacterEncoding("UTF-8"); + // 1. 处理模板路径并获取输入流 + String temPath = getTemplateInputStream(templatePath); + if (temPath == null) { + throw new FileNotFoundException("模板文件不存在: " + templatePath); + } + // 渲染文档并响应 + XWPFDocument document = WordExportUtil.exportWord07(temPath, data); + try (OutputStream outputStream = response.getOutputStream()) { + document.write(outputStream); + } catch (Exception e) { + + } finally { + document.close(); + } + } + + /** + * 导出Word文档,带模板文件检查 + * + * @param templatePath 模板文件路径(支持classpath路径和绝对路径) + * @param data 导出数据 + * @param outputPath 输出文件路径 + * @throws IOException 当模板不存在或IO操作失败时抛出 + */ + public static void exportWord(String templatePath, Map data, String outputPath) throws IOException { + // 1. 处理模板路径并获取输入流 + String temPath = getTemplateInputStream(templatePath); + if (temPath == null) { + throw new FileNotFoundException("模板文件不存在: " + templatePath); + } + + // 3. 写入输出文件 + try (FileOutputStream outStream = new FileOutputStream(outputPath); XWPFDocument doc = WordExportUtil.exportWord07(temPath, data)) { + // 2. 导出Word文档 + doc.write(outStream); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * 获取模板文件输入流(优先从classpath查找,再查找绝对路径) + * + * @param templatePath 模板路径 + * @return 输入流,若文件不存在则返回null + */ + private static String getTemplateInputStream(String templatePath) { + // 1. 尝试从classpath资源加载(适用于Spring Boot项目的resources目录) + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + URL url = classLoader.getResource(templatePath); + if (url != null) { + return url.getPath(); + } + + // 2. 尝试从绝对路径加载 + File file = new File(templatePath); + if (file.exists() && file.isFile()) { + return file.getPath(); + } + return null; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventGateController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventGateController.java new file mode 100644 index 0000000..d75bc5f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventGateController.java @@ -0,0 +1,365 @@ +package com.njcn.product.event.transientes.controller; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +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.event.file.pojo.dto.WaveDataDTO; +import com.njcn.product.event.devcie.mapper.PqLineMapper; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.product.event.transientes.mapper.PqUserLedgerMapper; +import com.njcn.product.event.transientes.mapper.PqUserLineAssMapper; +import com.njcn.product.event.transientes.pojo.param.MonitorTerminalParam; +import com.njcn.product.event.transientes.pojo.param.SimulationMsgParam; +import com.njcn.product.event.transientes.pojo.po.*; +import com.njcn.product.event.transientes.service.*; +import com.njcn.product.event.transientes.service.impl.MsgEventInfoServiceImpl; +import com.njcn.product.event.transientes.websocket.WebSocketServer; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static com.njcn.product.event.transientes.pojo.constant.RedisConstant.REDIS_DEPT_INDEX; + +/** + * @Author: cdf + * @CreateTime: 2025-06-23 + * @Description: + */ +@Api(tags = "暂降接收") +@RequestMapping("accept") +@RestController +@RequiredArgsConstructor +@Slf4j +public class EventGateController extends BaseController { + private final MsgEventInfoServiceImpl msgEventInfoServiceImpl; + private final PqUserLineAssMapper pqUserLineAssMapper; + private final PqUserLedgerMapper pqUserLedgerMapper; + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + + private final WebSocketServer webSocketServer; + + private final PqsDeptslineService pqsDeptslineService; + + private final PqsDeptsService pqsDeptsService; + + private final PqsUserService pqsUserService; + + private final PqsUsersetService pqsUsersetService; + + private final PqLineMapper pqLineMapper; + + private final EventGateService eventGateService; + + private final MsgEventConfigService msgEventConfigService; + + private final MsgEventInfoService msgEventInfoService; + + private final RedisUtil redisUtil; + + + @OperateInfo + @GetMapping("/eventMsg") + @ApiOperation("接收远程推送的暂态事件") + @ApiImplicitParam(name = "eventMsg", value = "暂态事件json字符", required = true) + public HttpResult eventMsg(@RequestParam("msg") String msg) { + String methodDescribe = getMethodDescribe("eventMsg"); + log.info("收到前置推送暂降事件:"+msg); + + JSONObject jsonObject; + try { + //下面一行代码正式环境需要放开 + jsonObject = new JSONObject(msg); + //下面一行代码正式环境需要放开 + //jsonObject = test(); + + if (msgEventConfigService.getEventType().contains(jsonObject.get("wavetype").toString()) + && Float.parseFloat(jsonObject.get("eventvalue").toString()) <= msgEventConfigService.getEventValue() + && (Float.parseFloat(jsonObject.get("persisttime").toString())*1000) >= msgEventConfigService.getEventDuration()) { + //过滤重要暂降事件 + Integer lineId = Integer.valueOf(jsonObject.get("lineid").toString()); + List assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper().eq(PqUserLineAssPO::getLineIndex,lineId)); + + String str ="/"; + if(CollUtil.isNotEmpty(assList)){ + List userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + List poList = pqUserLedgerMapper.selectList(new LambdaQueryWrapper().select(PqUserLedgerPO::getId,PqUserLedgerPO::getCustomerName).in(PqUserLedgerPO::getId,userIds)); + str = poList.stream().map(PqUserLedgerPO::getCustomerName).collect(Collectors.joining(StrUtil.COMMA)); + } + + List deptsList = (List)redisUtil.getObjectByKey(REDIS_DEPT_INDEX+ StrUtil.DASHED+"AllDept"); + Map deptsMap = deptsList.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex,dept->dept)); + + List deptslineList = pqsDeptslineService.lambdaQuery().eq(PqsDeptsline::getLineIndex,lineId).list(); + List deptIds = deptslineList.stream().map(PqsDeptsline::getDeptsIndex).collect(Collectors.toList()); + Set set =getAllParentIdsWithChildrenBatch(deptIds,deptsMap); + jsonObject.putOpt("objName",str); + jsonObject.putOpt("dept", String.join(StrUtil.COMMA, set)); + + webSocketServer.sendMessageToAll(jsonObject.toString()); + } + + } catch (Exception e) { + e.printStackTrace(); + log.error("暂降json格式异常!{}", e.getMessage()); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + public Set getAllParentIdsRecursive(String deptId, Map deptMap, Set result) { + if (deptId == null || result.contains(deptId)) { + return result; + } + + result.add(deptId); // 添加当前ID + PqsDepts dept = deptMap.get(deptId); + if (dept != null && dept.getParentnodeid() != null) { + getAllParentIdsRecursive(dept.getParentnodeid(), deptMap, result); // 递归处理父节点 + } + return result; + } + + // 批量处理入口方法 + public Set getAllParentIdsWithChildrenBatch(Collection deptIds, Map deptMap) { + Set result = new HashSet<>(); + for (String deptId : deptIds) { + getAllParentIdsRecursive(deptId, deptMap, result); + } + return result; + } + + @OperateInfo + @GetMapping("/testEvent") + @ApiOperation("接收远程推送的暂态事件") + public HttpResult testEvent() { + String methodDescribe = getMethodDescribe("testEvent"); + log.info("模拟测试发送暂降事件-------------------------"); + + JSONObject jsonObject; + try { + //下面一行代码正式环境需要放开 + jsonObject = test(); + + if (msgEventConfigService.getEventType().contains(jsonObject.get("wavetype").toString()) &&Float.parseFloat(jsonObject.get("eventvalue").toString()) <= msgEventConfigService.getEventValue()) { + webSocketServer.sendMessageToAll(jsonObject.toString()); + + //开始发送短信 + try { + sendMessage(jsonObject); + }catch (Exception e){ + log.error("短信组装发送失败!失败原因{}",e.getMessage()); + } + + } + + } catch (Exception e) { + log.error("暂降json格式异常!{}", e.getMessage()); + } + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + //测试模拟,正式环境删除 + private PqsEventdetail createEvent(JSONObject jsonObject, LocalDateTime now) { + PqsEventdetail pqsEventdetail = new PqsEventdetail(); + pqsEventdetail.setEventdetailIndex(jsonObject.get("eventdetail_index").toString()); + pqsEventdetail.setLineid(Integer.valueOf(jsonObject.get("lineid").toString())); + pqsEventdetail.setTimeid(now); + pqsEventdetail.setMs(new BigDecimal(jsonObject.get("ms").toString())); + pqsEventdetail.setWavetype(Integer.valueOf(jsonObject.get("wavetype").toString())); + pqsEventdetail.setPersisttime(Double.valueOf(jsonObject.get("persisttime").toString())); + pqsEventdetail.setEventvalue(Double.valueOf(jsonObject.get("eventvalue").toString())); + pqsEventdetail.setEventreason(jsonObject.get("eventreason").toString()); + pqsEventdetail.setEventtype(jsonObject.get("eventtype").toString()); + + return pqsEventdetail; + } + + //测试模拟,正式环境删除 + private JSONObject test() { + /*----------------------------------------------------------------------------------------*/ + //以下部分为测试数据后续删除 + List pqLineList = pqLineMapper.selectList(new LambdaQueryWrapper<>()); + List lineList = pqLineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList()); + List baseInfoDTOList = pqLineMapper.getBaseLineInfo(lineList); + Map map = baseInfoDTOList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + Random random = new Random(); + Integer lineId = lineList.get(random.nextInt(lineList.size())); + LedgerBaseInfoDTO dto = map.get(lineId); + + LocalDateTime now = LocalDateTime.now(); + String timeStr = DateUtil.format(now, DatePattern.NORM_DATETIME_PATTERN); + Long ms = (long) random.nextInt(999); + + Integer[] temArr = new Integer[]{1, 3}; + Integer wave = random.nextInt(2); + + + Double per = (double)random.nextInt(5000); + + double minV = 0.1; + double maxV = 0.9; + Double eventValue = minV + (maxV - minV) * Math.random(); + + String id = IdUtil.simpleUUID(); + + JSONObject tem = new JSONObject(); + tem.set("eventdetail_index", id); + tem.set("lineid", lineId.toString()); + tem.set("timeid", timeStr); + tem.set("ms", ms.toString()); + tem.set("wavetype", temArr[wave]); + tem.set("persisttime", per.toString()); + tem.set("eventvalue", eventValue); + tem.set("eventreason", "97a56e0f-b546-4c1e-b27c-52463fc1d82f"); + tem.set("eventtype", "676683a0-7f80-43e6-8df8-bea8ed235d67"); + tem.set("gdname", "测试供电公司"); + tem.set("bdname", dto.getStationName()); + tem.set("pointname", dto.getLineName()); + + /* PqsEventdetail pqsEventdetail = createEvent(tem, now); + if (msgEventConfigService.getEventType().contains(tem.get("wavetype").toString())) { + webSocketServer.sendMessageToAll(tem.toString()); + } + pqsEventdetailService.save(pqsEventdetail);*/ + /*----------------------------------------------------------------------------------------*/ + + return tem; + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/getTransientAnalyseWave") + @ApiOperation("暂态事件波形分析") + public HttpResult getTransientAnalyseWave(@RequestBody MonitorTerminalParam param) { + String methodDescribe = getMethodDescribe("getTransientAnalyseWave"); + WaveDataDTO wave = eventGateService.getTransientAnalyseWave(param); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, wave, methodDescribe); + } + + + @OperateInfo(info = LogEnum.BUSINESS_COMMON) + @PostMapping("/simulationSend") + @ApiOperation("模拟发送短信") + public HttpResult simulationSend(@RequestBody @Validated SimulationMsgParam param) { + String methodDescribe = getMethodDescribe("simulationSend"); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + + private void sendMessage(JSONObject jsonObject) throws Exception{ + Integer lineId = Integer.valueOf(jsonObject.get("lineid").toString()); + List pqLineDept = pqsDeptslineService.lambdaQuery().eq(PqsDeptsline::getLineIndex, lineId).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + Set deptIds = pqLineDept.stream().map(PqsDeptsline::getDeptsIndex).collect(Collectors.toSet()); + Set resultIds = getAllParentDeptIds(deptIds); + + List pqsUserSetList = pqsUsersetService.lambdaQuery().eq(PqsUserSet::getIsNotice, 1).in(PqsUserSet::getDeptsIndex, resultIds).list(); + if (CollUtil.isEmpty(pqsUserSetList)) { + //当前事件未找到用户信息,判断为不需要发送短信用户 + return; + } + List pqsUserList = pqsUserService.lambdaQuery().select(PqsUser::getUserIndex,PqsUser::getPhone,PqsUser::getName).in(PqsUser::getUserIndex, pqsUserSetList.stream().map(PqsUserSet::getUserIndex).collect(Collectors.toList())).list(); + List userIds = pqsUserList.stream().map(PqsUser::getUserIndex).collect(Collectors.toList()); + List poList = pqsUserSetList.stream().filter(it -> userIds.contains(it.getUserIndex())).collect(Collectors.toList()); + if (CollUtil.isNotEmpty(poList)) { + StringBuilder stringBuilder = new StringBuilder(jsonObject.get("timeid").toString()); + List list = pqLineMapper.getBaseLineInfo(Stream.of(lineId).collect(Collectors.toList())); + LedgerBaseInfoDTO ledgerBaseInfoDTO = list.get(0); + BigDecimal bigDecimal = new BigDecimal(jsonObject.get("eventvalue").toString()).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP); + stringBuilder.append(".").append(jsonObject.get("ms").toString()).append(", ").append(ledgerBaseInfoDTO.getStationName()).append(ledgerBaseInfoDTO.getLineName()) + .append("发生暂降事件,事件特征幅值").append(bigDecimal).append("%,持续时间:").append(jsonObject.get("persisttime").toString()).append("S"); + //TODO 发送短信 + // System.out.println(stringBuilder); + + List resultList = new ArrayList<>(); + for (PqsUser user : pqsUserList) { + MsgEventInfo msgEventInfo = new MsgEventInfo(); + msgEventInfo.setEventIndex(jsonObject.get("eventdetail_index").toString()); + msgEventInfo.setMsgContent(stringBuilder.toString()); + msgEventInfo.setMsgIndex(IdUtil.simpleUUID()); + msgEventInfo.setPhone(user.getPhone()); + msgEventInfo.setSendResult(0); + msgEventInfo.setUserId(user.getUserIndex()); + msgEventInfo.setUserName(user.getName()); + msgEventInfo.setIsHandle(0); + msgEventInfo.setSendTime(LocalDateTime.now()); + resultList.add(msgEventInfo); + } + msgEventInfoService.saveBatch(resultList); + } + } + + /** + * 获取远程短信平台token + */ + private String apiToken() { + + return "token"; + } + + private boolean apiSend(){ + return false; + } + + + public Set getAllParentDeptIds(Set deptIds) { + // 首次获取直接父级 + List allDeptList = pqsDeptsService.lambdaQuery().list(); + // 递归获取所有父级 + Set result = recursivelyGetParentIds(deptIds, allDeptList); + return result; + } + + /** + * 递归获取所有父级ID + * + * @param currentParentIds 当前层级的父级ID集合 + * @return 所有层级的父级ID集合 + */ + private Set recursivelyGetParentIds(Set currentParentIds, List allDeptList) { + Set result = new HashSet<>(currentParentIds); + Set nextLevelParentIds = new HashSet<>(); + List parentDeptList = allDeptList.stream().filter(it -> currentParentIds.contains(it.getDeptsIndex())).collect(Collectors.toList()); + for (PqsDepts pqsDepts : parentDeptList) { + if (!pqsDepts.getParentnodeid().equals("0")) { + nextLevelParentIds.add(pqsDepts.getParentnodeid()); + } + } + // 如果有更高层级的父级,继续递归 + if (!nextLevelParentIds.isEmpty()) { + Set deeperParentIds = recursivelyGetParentIds(nextLevelParentIds, allDeptList); + result.addAll(deeperParentIds); + } + return result; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventRightController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventRightController.java new file mode 100644 index 0000000..8a38304 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/EventRightController.java @@ -0,0 +1,130 @@ +package com.njcn.product.event.transientes.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.devcie.pojo.po.PqGdCompany; +import com.njcn.product.event.devcie.pojo.po.PqSubstation; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.po.*; +import com.njcn.product.event.transientes.pojo.vo.EventDetailVO; +import com.njcn.product.event.transientes.pojo.vo.UserLedgerStatisticVO; +import com.njcn.product.event.transientes.service.*; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.*; + +/** + * @Author: cdf + * @CreateTime: 2025-06-23 + * @Description: + */ +@Api(tags = "暂降接收") +@RequestMapping("right") +@RestController +@RequiredArgsConstructor +@Slf4j +public class EventRightController extends BaseController { + + private final EventRightService eventRightService; + + + @OperateInfo + @PostMapping("/rightEvent") + @ApiOperation("右侧表头") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightEvent(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightEvent"); + UserLedgerStatisticVO userLedgerStatisticVO = eventRightService.userLedgerStatisticClone(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, userLedgerStatisticVO, methodDescribe); + } + + + @OperateInfo + @PostMapping("/rightImportUser") + @ApiOperation("右侧重要用户") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightImportUser(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightImportUser"); + List result = eventRightService.rightImportUser(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/rightEventOpen") + @ApiOperation("右侧表头点击事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightEventOpen(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightEventOpen"); + Page page = eventRightService.rightEventOpenClone(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + @OperateInfo + @PostMapping("/rightEventOpenClone") + @ApiOperation("右侧表头点击事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightEventOpenClone(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightEventOpenClone"); + Page page = eventRightService.rightEventOpen(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + @OperateInfo + @PostMapping("/rightEventOpenForDetail") + @ApiOperation("右侧表头点击事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightEventOpenForDetail(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightEventOpenForDetail"); + Page page = eventRightService.rightEventOpenForDetail(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + + + @OperateInfo + @PostMapping("/rightEventDevOpen") + @ApiOperation("右侧表头终端点击事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightEventDevOpen(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightEventDevOpen"); + Page page = eventRightService.rightEventDevOpen(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, page, methodDescribe); + } + + + @OperateInfo + @PostMapping("/rightImportOpenDetail") + @ApiOperation("右侧表头终端点击事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "", required = true) + public HttpResult rightImportOpenDetail(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightImportOpenDetail"); + PqUserLedgerPO po = eventRightService.rightImportOpenDetail(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, po, methodDescribe); + } + + + @GetMapping("gdSelect") + public HttpResult> gdSelect() { + String methodDescribe = getMethodDescribe("gdSelect"); + List list = eventRightService.gdSelect(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + + + @GetMapping("bdSelect") + public HttpResult> bdSelect() { + String methodDescribe = getMethodDescribe("bdSelect"); + List list = eventRightService.bdSelect(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/LargeScreenCountController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/LargeScreenCountController.java new file mode 100644 index 0000000..ce561f3 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/LargeScreenCountController.java @@ -0,0 +1,265 @@ +package com.njcn.product.event.transientes.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.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.param.MessageEventFeedbackParam; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import com.njcn.product.event.transientes.pojo.vo.*; +import com.njcn.product.event.transientes.service.LargeScreenCountService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * Description: + * Date: 2025/06/19 下午 3:00【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Slf4j +@Api(tags = "大屏统计") +@RestController +@RequestMapping("/largescreen") +@RequiredArgsConstructor +public class LargeScreenCountController extends BaseController { + + private final LargeScreenCountService largeScreenCountService; + + @OperateInfo + @PostMapping("/initLedger") + @ApiOperation("台账规模统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult initLedger(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("initLedger"); + largeScreenCountService.initLedger(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe); + } + + @OperateInfo + @PostMapping("/ledgercount") + @ApiOperation("台账规模统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult scaleStatistics(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("scaleStatistics"); + LedgerCountVO result = largeScreenCountService.scaleStatistics(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/alarmAnalysis") + @ApiOperation("告警统计分析") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult alarmAnalysis(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("alarmAnalysis"); + AlarmAnalysisVO result = largeScreenCountService.alarmAnalysis(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + @OperateInfo + @PostMapping("/alarmAnalysisDetail") + @ApiOperation("告警统计分析详情") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult alarmAnalysisDetail(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("alarmAnalysisDetail"); + AlarmAnalysisVO result = largeScreenCountService.alarmAnalysisDetail(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo + @PostMapping("/eventTablePage") + @ApiOperation("告警统计分析详情") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> eventTablePage(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("alarmAnalysisDetail"); + Page result = largeScreenCountService.eventTablePage(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/eventTrend") + @ApiOperation("暂降事件趋势") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> eventTrend(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("eventTrend"); + List result = largeScreenCountService.eventTrend(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/eventList") + @ApiOperation("暂降事件列表") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> eventList(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("eventList"); + Page result = largeScreenCountService.eventList(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo + @PostMapping("/noDealEventList") + @ApiOperation("未处理暂降事件列表") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> noDealEventList(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("noDealEventList"); + List result = largeScreenCountService.noDealEventList(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + @OperateInfo + @PostMapping("/mapCount") + @ApiOperation("地图统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> mapCount(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("mapCount"); + List result = largeScreenCountService.mapCount(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + @OperateInfo(operateType= OperateType.UPDATE) + @PostMapping("/lookEvent") + @ApiOperation("处理暂降事件") + @ApiImplicitParam(name = "eventIds", value = "暂降事件id", required = true) + public HttpResult lookEvent(@RequestBody List eventIds) { + String methodDescribe = getMethodDescribe("lookEvent"); + boolean result = largeScreenCountService.lookEvent(eventIds); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @GetMapping("/eventMsgDetail") + @ApiOperation("暂降事件列表详情按钮") + @ApiImplicitParam(name = "eventId", value = "暂降事件id", required = true) + public HttpResult eventMsgDetail(@RequestParam("eventId")String eventId) { + String methodDescribe = getMethodDescribe("eventMsgDetail"); + EventMsgDetailVO result = largeScreenCountService.eventMsgDetail(eventId); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/msgSendList") + @ApiOperation("远程通知列表") + @ApiImplicitParam(name = "largeScreenCountParam", value = "参数", required = true) + public HttpResult> msgSendList(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("msgSendList"); + List result = largeScreenCountService.msgSendList(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/hasSendMsgPage") + @ApiOperation("已发送短信列表") + @ApiImplicitParam(name = "largeScreenCountParam", value = "参数", required = true) + public HttpResult> hasSendMsgPage(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("hasSendMsgPage"); + Page result = largeScreenCountService.hasSendMsgPage(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(operateType = OperateType.ADD) + @PostMapping("/msgHandle") + @ApiOperation("短信处理") + @ApiImplicitParam(name = "eventId", value = "暂降事件id", required = true) + public HttpResult msgHandle(@RequestBody @Validated MessageEventFeedbackParam messageEventFeedbackParam) { + String methodDescribe = getMethodDescribe("msgHandle"); + largeScreenCountService.msgHandle(messageEventFeedbackParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } + + + @OperateInfo + @PostMapping("/devFlagCount") + @ApiOperation("终端运行统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult devFlagCount(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("devFlagCount"); + DeviceCountVO deviceCountVO = largeScreenCountService.devFlagCount(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, deviceCountVO, methodDescribe); + } + @OperateInfo + @PostMapping("/devDetail") + @ApiOperation("终端运行统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> devDetail(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("devDetail"); + List deviceDTOList = largeScreenCountService.devDetail(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, deviceDTOList, methodDescribe); + } + + @OperateInfo + @PostMapping("/areaDevCount") + @ApiOperation("区域终端统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> areaDevCount(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("areaDevCount"); + List result = largeScreenCountService.regionDevCount(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/substationCount") + @ApiOperation("变电站统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> substationCount(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("substationCount"); + List result = largeScreenCountService.substationCount(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo + @PostMapping("/regionDevCount") + @ApiOperation("区域终端统计") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> rightUserStatistic(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("rightUserStatistic"); + List result = largeScreenCountService.regionDevCount(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + + + + @OperateInfo + @PostMapping("/eventPage") + @ApiOperation("分页查询暂降事件") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> eventPage(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("eventPage"); + Page result = largeScreenCountService.eventPage(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + @OperateInfo + @PostMapping("/devicePage") + @ApiOperation("终端分页查询") + @ApiImplicitParam(name = "largeScreenCountParam", value = "查询参数", required = true) + public HttpResult> devicePage(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("devicePage"); + Page result = largeScreenCountService.devicePage(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + + @OperateInfo(operateType= OperateType.UPDATE) + @PostMapping("/userEventList") + @ApiOperation("查询暂降事件") + @ApiImplicitParam(name = "eventIds", value = "暂降事件id", required = true) + public HttpResult> userEventList(@RequestBody LargeScreenCountParam largeScreenCountParam) { + String methodDescribe = getMethodDescribe("userEventList"); + Page result = largeScreenCountService.userEventList(largeScreenCountParam); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/MsgEventConfigController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/MsgEventConfigController.java new file mode 100644 index 0000000..13dc44e --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/MsgEventConfigController.java @@ -0,0 +1,53 @@ +package com.njcn.product.event.transientes.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.constant.OperateType; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.transientes.pojo.po.MsgEventConfig; +import com.njcn.product.event.transientes.service.MsgEventConfigService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * @Author: cdf + * @CreateTime: 2025-06-27 + * @Description: + */ +@Api(tags = "暂降平台配置") +@RequestMapping("config") +@RestController +@RequiredArgsConstructor +@Slf4j +public class MsgEventConfigController extends BaseController { + + private final MsgEventConfigService msgEventConfigService; + + @OperateInfo(operateType = OperateType.ADD) + @PostMapping("/eventConfig") + @ApiOperation("暂降平台配置") + @ApiImplicitParam(name = "msgEventConfig", value = "实体", required = true) + @Transactional(rollbackFor = Exception.class) + public HttpResult eventConfig(@RequestBody @Validated MsgEventConfig msgEventConfig) { + String methodDescribe = getMethodDescribe("eventConfig"); + msgEventConfigService.eventConfig(msgEventConfig); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe); + } + + @OperateInfo + @GetMapping("/queryConfig") + @ApiOperation("接收远程推送的暂态事件") + public HttpResult queryConfig() { + String methodDescribe = getMethodDescribe("queryConfig"); + MsgEventConfig msgEventConfig = msgEventConfigService.queryConfig(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, msgEventConfig, methodDescribe); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqUserLedgerController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqUserLedgerController.java new file mode 100644 index 0000000..4f87727 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqUserLedgerController.java @@ -0,0 +1,54 @@ +package com.njcn.product.event.transientes.controller; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.transientes.pojo.param.PqUserLedgerParam; +import com.njcn.product.event.transientes.pojo.po.PqUserLedgerPO; +import com.njcn.product.event.transientes.service.PqUserLedgerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@RestController +@RequestMapping("/pqUser/ledger") +public class PqUserLedgerController { + + @Autowired + private PqUserLedgerService pqUserLedgerService; + + // 添加记录 + @PostMapping("addLedger") + public boolean addLedger(@RequestBody PqUserLedgerParam ledgerParam) { + return pqUserLedgerService.addLedger(ledgerParam); + } + + // 更新记录 + @PostMapping("updateLedger") + public boolean updateLedger(@RequestBody PqUserLedgerParam ledgerParam) { + return pqUserLedgerService.updateLedger(ledgerParam); + } + + // 删除记录 + @PostMapping("deleteLedger") + public boolean deleteLedger(@RequestBody List ids) { + return pqUserLedgerService.deleteLedger(ids); + } + + // 查询单条记录 + @GetMapping("/getLedgerById") + public PqUserLedgerPO getLedgerById(@PathVariable String id) { + return pqUserLedgerService.getLedgerById(id); + } + + // 查询所有记录 + @GetMapping + public Page pageList(@RequestBody PqUserLedgerParam ledgerParam) { + return pqUserLedgerService.pageList(ledgerParam); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqsDicTreeController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqsDicTreeController.java new file mode 100644 index 0000000..57a98b9 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/controller/PqsDicTreeController.java @@ -0,0 +1,46 @@ +package com.njcn.product.event.transientes.controller; + +import com.njcn.common.pojo.annotation.OperateInfo; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.transientes.pojo.po.PqsDicTreePO; +import com.njcn.product.event.transientes.service.PqsDicTreeService; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-01 + * @Description: + */ +@Api(tags = "字典树") +@RequestMapping("dicTree") +@RestController +@RequiredArgsConstructor +@Slf4j +public class PqsDicTreeController extends BaseController { + + private final PqsDicTreeService pqsDicTreeService; + + + @OperateInfo + @GetMapping("/getDicTree") + @ApiOperation("获取树结构") + public HttpResult> getDicTree(@RequestParam("code") String code){ + String methodDescribe = getMethodDescribe("getDicTree"); + + List pqsDicTreePOList = pqsDicTreeService.getDicTree(code); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pqsDicTreePOList, methodDescribe); + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/filter/JwtRequestFilter.java b/event_smart/src/main/java/com/njcn/product/event/transientes/filter/JwtRequestFilter.java new file mode 100644 index 0000000..6a38736 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/filter/JwtRequestFilter.java @@ -0,0 +1,82 @@ +package com.njcn.product.event.transientes.filter; + +import cn.hutool.json.JSONObject; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.transientes.utils.JwtUtil; +import io.jsonwebtoken.ExpiredJwtException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +@Slf4j +public class JwtRequestFilter extends OncePerRequestFilter { + + private final UserDetailsService userDetailsService; + private final JwtUtil jwtUtil; + + public JwtRequestFilter(UserDetailsService userDetailsService, JwtUtil jwtUtil) { + this.userDetailsService = userDetailsService; + this.jwtUtil = jwtUtil; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + System.out.println(55); + + final String authorizationHeader = request.getHeader("Authorization"); + String username = null; + String jwt = null; + if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { + jwt = authorizationHeader.substring(7); + try { + username = jwtUtil.extractUsername(jwt); + } catch (ExpiredJwtException e) { + log.error(e.getMessage()); + sendErrorResponse(response,CommonResponseEnum.TOKEN_EXPIRE_JWT); + return; + } catch (Exception e) { + log.error(e.getMessage()); + sendErrorResponse(response,CommonResponseEnum.PARSE_TOKEN_ERROR); + return; + } + } + + if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { + UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); + + if (jwtUtil.validateToken(jwt, userDetails)) { + UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = + new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); + } + } + chain.doFilter(request, response); + } + + private void sendErrorResponse(HttpServletResponse response, CommonResponseEnum error) throws IOException { + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("application/json;charset=UTF-8"); + + HttpResult httpResult = new HttpResult<>(); + httpResult.setCode(error.getCode()); + httpResult.setMessage(error.getMessage()); + + response.getWriter().write(new JSONObject(httpResult, false).toString()); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/handler/ControllerUtil.java b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/ControllerUtil.java new file mode 100644 index 0000000..d8807d0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/ControllerUtil.java @@ -0,0 +1,37 @@ +package com.njcn.product.event.transientes.handler; + +import com.njcn.common.pojo.constant.LogInfo; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.MethodArgumentNotValidException; + +import java.lang.reflect.Method; +import java.util.Objects; + +/** + * @author hongawen + * @version 1.0.0 + * @date 2021年06月22日 10:25 + */ +@Slf4j +public class ControllerUtil { + + /** + * 针对methodArgumentNotValidException 异常的处理 + * @author cdf + */ + public static String getMethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) { + String operate = LogInfo.UNKNOWN_OPERATE; + Method method = null; + try { + method = methodArgumentNotValidException.getParameter().getMethod(); + if (!Objects.isNull(method) && method.isAnnotationPresent(ApiOperation.class)) { + ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); + operate = apiOperation.value(); + } + }catch (Exception e){ + log.error("根据方法参数非法异常获取@ApiOperation注解值失败,参数非法异常信息:{},方法名:{},异常信息:{}",methodArgumentNotValidException.getMessage(),method,e.getMessage()); + } + return operate; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/handler/GlobalBusinessExceptionHandler.java b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/GlobalBusinessExceptionHandler.java new file mode 100644 index 0000000..652e479 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/GlobalBusinessExceptionHandler.java @@ -0,0 +1,252 @@ +package com.njcn.product.event.transientes.handler; + +import cn.hutool.core.text.StrFormatter; +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.common.utils.LogUtil; +import com.njcn.web.utils.HttpResultUtil; +import com.njcn.web.utils.ReflectCommonUtil; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.json.JSONException; +import org.springframework.validation.ObjectError; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.util.NestedServletException; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 全局通用业务异常处理器 + * + * @author hongawen + * @version 1.0.0 + * @date 2021年04月20日 18:04 + */ +@Slf4j +@AllArgsConstructor +@RestControllerAdvice +public class GlobalBusinessExceptionHandler { + + + + private final ThreadPoolExecutor executor = new ThreadPoolExecutor( + 4, 8, 30, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(100), + // 队列满时由主线程执行 + new ThreadPoolExecutor.CallerRunsPolicy() + ); + + + /** + * 捕获业务功能异常,通常为业务数据抛出的异常 + * + * @param businessException 业务异常 + */ + @ExceptionHandler(BusinessException.class) + public HttpResult handleBusinessException(BusinessException businessException) { + String operate = ReflectCommonUtil.getMethodDescribeByException(businessException); + // recodeBusinessExceptionLog(businessException, businessException.getMessage()); + return HttpResultUtil.assembleBusinessExceptionResult(businessException, null, operate); + } + + + /** + * 空指针异常捕捉 + * + * @param nullPointerException 空指针异常 + */ + @ExceptionHandler(NullPointerException.class) + public HttpResult handleNullPointerException(NullPointerException nullPointerException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage(), nullPointerException); + //recodeBusinessExceptionLog(nullPointerException, CommonResponseEnum.NULL_POINTER_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NULL_POINTER_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(nullPointerException)); + } + + /** + * 算数运算异常 + * + * @param arithmeticException 算数运算异常,由于除数为0引起的异常 + */ + @ExceptionHandler(ArithmeticException.class) + public HttpResult handleArithmeticException(ArithmeticException arithmeticException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage(), arithmeticException); + // recodeBusinessExceptionLog(arithmeticException, CommonResponseEnum.ARITHMETIC_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ARITHMETIC_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(arithmeticException)); + } + + /** + * 类型转换异常捕捉 + * + * @param classCastException 类型转换异常 + */ + @ExceptionHandler(ClassCastException.class) + public HttpResult handleClassCastException(ClassCastException classCastException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage(), classCastException); + // recodeBusinessExceptionLog(classCastException, CommonResponseEnum.CLASS_CAST_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.CLASS_CAST_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(classCastException)); + } + + + /** + * 索引下标越界异常捕捉 + * + * @param indexOutOfBoundsException 索引下标越界异常 + */ + @ExceptionHandler(IndexOutOfBoundsException.class) + public HttpResult handleIndexOutOfBoundsException(IndexOutOfBoundsException indexOutOfBoundsException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage(), indexOutOfBoundsException); + // recodeBusinessExceptionLog(indexOutOfBoundsException, CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.INDEX_OUT_OF_BOUNDS_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(indexOutOfBoundsException)); + } + + /** + * 前端请求后端,请求中参数的媒体方式不支持异常 + * + * @param httpMediaTypeNotSupportedException 请求中参数的媒体方式不支持异常 + */ + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public HttpResult httpMediaTypeNotSupportedExceptionHandler(HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage(), httpMediaTypeNotSupportedException); + // 然后提取错误提示信息进行返回 + // recodeBusinessExceptionLog(httpMediaTypeNotSupportedException, CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.HTTP_MEDIA_TYPE_NOT_SUPPORTED_EXCEPTION, null, ReflectCommonUtil.getMethodDescribeByException(httpMediaTypeNotSupportedException)); + } + + /** + * 前端请求后端,参数校验异常捕捉 + * RequestBody注解参数异常 + * + * @param methodArgumentNotValidException 参数校验异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public HttpResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException) { + // 从异常对象中拿到allErrors数据 + String messages = methodArgumentNotValidException.getBindingResult().getAllErrors() + .stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";")); + // 然后提取错误提示信息进行返回 + LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages); + // recodeBusinessExceptionLog(methodArgumentNotValidException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages, ControllerUtil.getMethodArgumentNotValidException(methodArgumentNotValidException)); + } + + /** + * 前端请求后端,参数校验异常捕捉 + * PathVariable注解、RequestParam注解参数异常 + * + * @param constraintViolationException 参数校验异常 + */ + @ExceptionHandler(ConstraintViolationException.class) + public HttpResult constraintViolationExceptionExceptionHandler(ConstraintViolationException constraintViolationException) { + String exceptionMessage = constraintViolationException.getMessage(); + StringBuilder messages = new StringBuilder(); + if (exceptionMessage.indexOf(StrUtil.COMMA) > 0) { + String[] tempMessage = exceptionMessage.split(StrUtil.COMMA); + Stream.of(tempMessage).forEach(message -> { + messages.append(message.substring(message.indexOf(StrUtil.COLON) + 2)).append(';'); + }); + } else { + messages.append(exceptionMessage.substring(exceptionMessage.indexOf(StrUtil.COLON) + 2)); + } + // 然后提取错误提示信息进行返回 + LogUtil.njcnDebug(log, "参数校验异常,异常为:{}", messages); + // recodeBusinessExceptionLog(constraintViolationException, CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage()); + List> constraintViolationList = new ArrayList<>(constraintViolationException.getConstraintViolations()); + ConstraintViolation constraintViolation = constraintViolationList.get(0); + Class rootBeanClass = constraintViolation.getRootBeanClass(); + //判断校验参数异常捕获的根源是controller还是service处 + if (rootBeanClass.getName().endsWith("Controller")) { + String methodName = constraintViolation.getPropertyPath().toString().substring(0, constraintViolation.getPropertyPath().toString().indexOf(StrUtil.DOT)); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByClassAndMethodName(rootBeanClass, methodName)); + } else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.METHOD_ARGUMENT_NOT_VALID_EXCEPTION, messages.toString(), ReflectCommonUtil.getMethodDescribeByException(constraintViolationException)); + } + + } + + + /** + * 索引下标越界异常捕捉 + * + * @param illegalArgumentException 参数校验异常 + */ + @ExceptionHandler(IllegalArgumentException.class) + public HttpResult handleIndexOutOfBoundsException(IllegalArgumentException illegalArgumentException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(), illegalArgumentException); + // recodeBusinessExceptionLog(illegalArgumentException, CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.ILLEGAL_ARGUMENT_EXCEPTION, illegalArgumentException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(illegalArgumentException)); + } + + + /** + * 未声明异常捕捉 + * + * @param exception 未声明异常 + */ + @ExceptionHandler(Exception.class) + public HttpResult handleException(Exception exception) { + //针对fallbackFactory降级异常特殊处理 + Exception tempException = exception; + String exceptionCause = CommonResponseEnum.UN_DECLARE.getMessage(); + String code = CommonResponseEnum.UN_DECLARE.getCode(); + if (exception instanceof NestedServletException) { + Throwable cause = exception.getCause(); + if (cause instanceof AssertionError) { + if (cause.getCause() instanceof BusinessException) { + tempException = (BusinessException) cause.getCause(); + BusinessException tempBusinessException = (BusinessException) cause.getCause(); + exceptionCause = tempBusinessException.getMessage(); + code = tempBusinessException.getCode(); + } + } + } + LogUtil.logExceptionStackInfo(exceptionCause, tempException); + // recodeBusinessExceptionLog(exception, exceptionCause); + //判断方法上是否有自定义注解,做特殊处理 +// Method method = ReflectCommonUtil.getMethod(exception); +// if (!Objects.isNull(method)){ +// if(method.isAnnotationPresent(ReturnMsg.class)){ +// return HttpResultUtil.assembleResult(code, null, StrFormatter.format("{}",exceptionCause)); +// } +// } + return HttpResultUtil.assembleResult(code, null, StrFormatter.format("{}{}{}", ReflectCommonUtil.getMethodDescribeByException(tempException), StrUtil.C_COMMA, exceptionCause)); + } + + + /** + * json解析异常 + * + * @param jsonException json参数 + */ + @ExceptionHandler(JSONException.class) + public HttpResult handleIndexOutOfBoundsException(JSONException jsonException) { + LogUtil.logExceptionStackInfo(CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage(), jsonException); + // recodeBusinessExceptionLog(jsonException, CommonResponseEnum.JSON_CONVERT_EXCEPTION.getMessage()); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.JSON_CONVERT_EXCEPTION, jsonException.getMessage(), ReflectCommonUtil.getMethodDescribeByException(jsonException)); + } +/* + private void recodeBusinessExceptionLog(Exception businessException, String methodDescribe) { + HttpServletRequest httpServletRequest = HttpServletUtil.getRequest(); + Future future = executor.submit(() -> { + HttpServletUtil.setRequest(httpServletRequest); + sysLogAuditService.recodeBusinessExceptionLog(businessException, methodDescribe); + }); + try { + // 抛出 ExecutionException + future.get(); + } catch (ExecutionException | InterruptedException e) { + log.error("保存审计日志异常,异常为:" + e.getMessage()); + } + }*/ + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/handler/SqlExecuteTimeInterceptor.java b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/SqlExecuteTimeInterceptor.java new file mode 100644 index 0000000..6e334dc --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/handler/SqlExecuteTimeInterceptor.java @@ -0,0 +1,57 @@ +//package com.njcn.gather.event.transientes.handler; +// +//import org.apache.ibatis.executor.statement.StatementHandler; +//import org.apache.ibatis.plugin.*; +//import org.apache.ibatis.session.ResultHandler; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.stereotype.Component; +// +//import java.sql.Statement; +//import java.util.Properties; +// +///** +// * @Author: cdf +// * @CreateTime: 2025-07-14 +// * @Description: +// */ +//@Intercepts({ +// @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), +// @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), +// @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class}) +//}) +//@Component +//public class SqlExecuteTimeInterceptor implements Interceptor { +// private static final Logger logger = LoggerFactory.getLogger(SqlExecuteTimeInterceptor.class); +// +// @Override +// public Object intercept(Invocation invocation) throws Throwable { +// long startTime = System.currentTimeMillis(); +// try { +// return invocation.proceed(); +// } finally { +// long endTime = System.currentTimeMillis(); +// long executeTime = endTime - startTime; +// +// // 获取 SQL 语句 +// StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); +// String sql = statementHandler.getBoundSql().getSql(); +// +// // 打印执行时间和 SQL +// logger.info("SQL 执行时间: {}ms, SQL: {}", executeTime, sql); +// } +// } +// +// @Override +// public Object plugin(Object target) { +// if (target instanceof StatementHandler) { +// return Plugin.wrap(target, this); +// } +// return target; +// } +// +// @Override +// public void setProperties(Properties properties) { +// // 可配置参数 +// } +//} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MessageEventFeedbackMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MessageEventFeedbackMapper.java new file mode 100644 index 0000000..886ab4d --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MessageEventFeedbackMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.MessageEventFeedback; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ + +public interface MessageEventFeedbackMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventConfigMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventConfigMapper.java new file mode 100644 index 0000000..c2d55dd --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventConfigMapper.java @@ -0,0 +1,12 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.MsgEventConfig; +import org.apache.ibatis.annotations.Mapper; + +/** + * MSG_EVENT_CONFIG表Mapper接口 + */ +@Mapper +public interface MsgEventConfigMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventInfoMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventInfoMapper.java new file mode 100644 index 0000000..b808df1 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/MsgEventInfoMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface MsgEventInfoMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqDevicedetailMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqDevicedetailMapper.java new file mode 100644 index 0000000..b64dcc0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqDevicedetailMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqDeviceDetail; + +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDevicedetailMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLedgerMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLedgerMapper.java new file mode 100644 index 0000000..228dae5 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLedgerMapper.java @@ -0,0 +1,14 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqUserLedgerPO; +import com.njcn.product.event.transientes.pojo.po.PqUserLineAssPO; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface PqUserLedgerMapper extends BaseMapper { + + + List getUserByParam(@Param("lineIds") List lineIds, @Param("searchValue")String searchValue); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLineAssMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLineAssMapper.java new file mode 100644 index 0000000..00db368 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqUserLineAssMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqUserLineAssPO; + +public interface PqUserLineAssMapper extends BaseMapper { + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptsMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptsMapper.java new file mode 100644 index 0000000..049dc5f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptsMapper.java @@ -0,0 +1,22 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.dto.PqsDeptDTO; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:57【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptsMapper extends BaseMapper { + List findDeptAndChildren(@Param("deptId") String deptId); + + List getDeptList(@Param("deptIds") List deptIds); +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptslineMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptslineMapper.java new file mode 100644 index 0000000..b3877a7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDeptslineMapper.java @@ -0,0 +1,20 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptslineMapper extends BaseMapper { + + List getPhoneUser(@Param("lineId")String lineId); +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicDataMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicDataMapper.java new file mode 100644 index 0000000..24d2d10 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicDataMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsDicData; + +public interface PqsDicDataMapper extends BaseMapper { + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTreeMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTreeMapper.java new file mode 100644 index 0000000..63bdd22 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTreeMapper.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsDicTreePO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +public interface PqsDicTreeMapper extends BaseMapper { + + @Select("SELECT ID,NAME,CODE,PARENT_ID as parentId,level FROM PQS_DICTREE " + + "START WITH CODE = #{code} " + + "CONNECT BY PRIOR ID = PARENT_ID") + List selectChildrenByCode(@Param("code") String code); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTypeMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTypeMapper.java new file mode 100644 index 0000000..178bc66 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsDicTypeMapper.java @@ -0,0 +1,10 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsDicData; +import com.njcn.product.event.transientes.pojo.po.PqsDicType; + +public interface PqsDicTypeMapper extends BaseMapper { + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsEventdetailMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsEventdetailMapper.java new file mode 100644 index 0000000..1d398f6 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsEventdetailMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; + +/** + * + * Description: + * Date: 2025/06/20 上午 10:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsEventdetailMapper extends BaseMapper { +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsIntegrityMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsIntegrityMapper.java new file mode 100644 index 0000000..236a350 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsIntegrityMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsIntegrity; + +/** + * + * Description: + * Date: 2025/07/29 下午 6:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsIntegrityMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsOnlinerateMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsOnlinerateMapper.java new file mode 100644 index 0000000..410fdfa --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsOnlinerateMapper.java @@ -0,0 +1,15 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsOnlinerate; + +/** + * + * Description: + * Date: 2025/07/29 下午 6:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsOnlinerateMapper extends BaseMapper { +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserMapper.java new file mode 100644 index 0000000..4145355 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserMapper.java @@ -0,0 +1,9 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsUser; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface PqsUserMapper extends BaseMapper { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserSetMapper.java b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserSetMapper.java new file mode 100644 index 0000000..f4b7a6a --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/PqsUserSetMapper.java @@ -0,0 +1,13 @@ +package com.njcn.product.event.transientes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.njcn.product.event.transientes.pojo.po.PqsUserSet; + +/** + * @Author: cdf + * @CreateTime: 2025-06-24 + * @Description: + */ +public interface PqsUserSetMapper extends BaseMapper { + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqDevicedetailMapper.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqDevicedetailMapper.xml new file mode 100644 index 0000000..babd49a --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqDevicedetailMapper.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + DEV_INDEX, MANUFACTURER, CHECKFLAG, THISTIMECHECK, NEXTTIMECHECK, ONLINERATETJ, DATAPLAN, + NEWTRAFFIC, ELECTROPLATE, ONTIME, CONTRACT, SIM, DEV_CATENA, DEV_LOCATION, DEV_NO + + diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqUserLedger.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqUserLedger.xml new file mode 100644 index 0000000..2643b63 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqUserLedger.xml @@ -0,0 +1,17 @@ + + + + + + + diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptsMapper.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptsMapper.xml new file mode 100644 index 0000000..cf3a642 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptsMapper.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + DEPTS_INDEX, DEPTSNAME, DEPTS_DESC, USER_INDEX, UPDATETIME, DEPTS_DESCRIPTION, "STATE", + AREA, CUSTOM_DEPT, PARENTNODEID + + + + + + \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptslineMapper.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptslineMapper.xml new file mode 100644 index 0000000..e3ffaae --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsDeptslineMapper.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + DEPTS_INDEX, LINE_INDEX, SYSTYPE + + + + \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsEventdetailMapper.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsEventdetailMapper.xml new file mode 100644 index 0000000..8871c1b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsEventdetailMapper.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + EVENTDETAIL_INDEX, LINEID, TIMEID, MS, "DESCRIBE", WAVETYPE, PERSISTTIME, EVENTVALUE, + EVENTREASON, EVENTTYPE, EVENTASS_INDEX, DQTIME, DEALTIME, DEALFLAG, NUM, FILEFLAG, + FIRSTTIME, FIRSTTYPE, FIRSTMS, WAVENAME, ENERGY, SEVERITY, LOOK_FLAG + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsOnlinerateMapper.xml b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsOnlinerateMapper.xml new file mode 100644 index 0000000..cc58789 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/mapper/mapping/PqsOnlinerateMapper.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + TIMEID, DEV_INDEX, ONLINEMIN, OFFLINEMIN + + \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/DicTreeEnum.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/DicTreeEnum.java new file mode 100644 index 0000000..9195891 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/DicTreeEnum.java @@ -0,0 +1,24 @@ +package com.njcn.product.event.transientes.pojo; + +import lombok.Getter; + +@Getter +public enum DicTreeEnum { + + BJ_USER("BJ_USER","半导体及精密加工"), + OI_USER("OI_USER","其他敏感用户"), + OT_USER("OT_USER","其他干扰源用户"), + + + ; + + private final String code; + + private final String dicName; + + + DicTreeEnum(String code, String dicName) { + this.code = code; + this.dicName = dicName; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/constant/RedisConstant.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/constant/RedisConstant.java new file mode 100644 index 0000000..abed817 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/constant/RedisConstant.java @@ -0,0 +1,13 @@ +package com.njcn.product.event.transientes.pojo.constant; + +/** + * @Author: cdf + * @CreateTime: 2025-07-30 + * @Description: + */ + +public class RedisConstant { + + public static final String REDIS_DEPT_INDEX ="LineCache:"; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/enums/DicTypeEnum.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/enums/DicTypeEnum.java new file mode 100644 index 0000000..ec65d02 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/enums/DicTypeEnum.java @@ -0,0 +1,33 @@ +package com.njcn.product.event.transientes.pojo.enums; + +import lombok.Data; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + + +@Getter +@RequiredArgsConstructor +public enum DicTypeEnum { + + VOLTAGE(5,"电压等级") + + + + + ; + + + + + + + + + private final Integer number; + + private final String dicName; + + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/LargeScreenCountParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/LargeScreenCountParam.java new file mode 100644 index 0000000..e08b6f6 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/LargeScreenCountParam.java @@ -0,0 +1,65 @@ +package com.njcn.product.event.transientes.pojo.param; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.njcn.web.pojo.param.BaseParam; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +/** + * Description: + * Date: 2025/06/19 下午 3:38【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class LargeScreenCountParam extends BaseParam { + @ApiModelProperty(name="deptId",value="部门id") + private String deptId; + @ApiModelProperty(name="type",value="类型(1年 2季度 3月份 4周 5日)") + private Integer type; + + @ApiModelProperty(name="eventtype",value="类型(0 暂降事件 1远程通知)") + private Integer eventtype; + + @ApiModelProperty(name="eventDeep",value="0.普通事件 1.严重事件 null.全部事件") + private Integer eventDeep; + + @ApiModelProperty(name="t通讯状态",value="0.离线 1.在线") + private String state; + + private Integer sendResult; + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate startTime; + @JsonFormat(pattern = "yyyy-MM-dd") + private LocalDate endTime; + + @ApiModelProperty(value = "字典树 对象大类") + private String bigObjType; + @ApiModelProperty(value = "字典树 对象大小") + private String smallObjType; + + private List eventIds; + + private Integer gdIndex; + + private Integer bdId; + + private String devName; + + private Float eventValueMin; + + private Float eventValueMax; + + private Float eventDurationMin; + + private Float eventDurationMax; + + @ApiModelProperty(value = "导出标识") + private Boolean exportFlag = false; + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MessageEventFeedbackParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MessageEventFeedbackParam.java new file mode 100644 index 0000000..9ab3fe4 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MessageEventFeedbackParam.java @@ -0,0 +1,38 @@ +package com.njcn.product.event.transientes.pojo.param; + + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.springframework.format.annotation.DateTimeFormat; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.time.LocalDate; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +@Data +public class MessageEventFeedbackParam { + + @NotBlank(message = "暂降事件id不可为空") + private String eventIndex; + + @NotNull(message = "是否影响敏感用户不可为空") + @ApiModelProperty(value = " 0.否 1.是") + private Integer isSensitive; + + @ApiModelProperty(value = "方案") + private String influenceFactors; + + @DateTimeFormat(pattern = "yyyy-MM-dd") + @ApiModelProperty(value = "处理时间") + private LocalDate dealDate; + + @ApiModelProperty(value = "原因") + private String dealScheme; + + private String remark; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MonitorTerminalParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MonitorTerminalParam.java new file mode 100644 index 0000000..7d387b8 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MonitorTerminalParam.java @@ -0,0 +1,30 @@ +package com.njcn.product.event.transientes.pojo.param; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * <监测点波形入参> + * + * @author wr + * @createTime: 2023-03-23 + */ +@Data +public class MonitorTerminalParam { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "id") + @NotBlank(message = "id不能为空") + private String id; + + @ApiModelProperty(value = "区分主配网(0:主网 1:配网)") + @NotNull(message = "区分类别不能为空") + private Integer type; + + @ApiModelProperty(value = "区分系统(0:pq 1:pms)") + @NotNull(message = "区分系统不能为空") + private Integer systemType; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MsgEventConfigParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MsgEventConfigParam.java new file mode 100644 index 0000000..f7f1e30 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/MsgEventConfigParam.java @@ -0,0 +1,49 @@ +package com.njcn.product.event.transientes.pojo.param; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-07-01 + * @Description: + */ +@Data +public class MsgEventConfigParam { + + + /** + * 主键ID + */ + private String id; + + /** + * 严重通知标识 + */ + @NotNull(message = "严重通知标识不可为空") + private Integer seriousNotice; + + /** + * 普通通知标识 + */ + @NotNull(message = "普通通知标识不可为空") + private Integer normalNotic; + + /** + * 语音类型 + */ + @NotNull(message = "语音类型不可为空") + private Integer voiceType; + + /** + * 屏幕通知标识 + */ + @NotNull(message = "屏幕通知标识不可为空") + private Integer screenNotic; + + @NotBlank(message = "事件类型不可为空") + private List eventTypeList; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/PqUserLedgerParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/PqUserLedgerParam.java new file mode 100644 index 0000000..b540d01 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/PqUserLedgerParam.java @@ -0,0 +1,44 @@ +package com.njcn.product.event.transientes.pojo.param; + +import com.njcn.web.pojo.param.BaseParam; +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@Data +public class PqUserLedgerParam extends BaseParam { + private static final long serialVersionUID = 1L; + + + private String id; + + private String powerSupplyArea; + + private String customerName; + + private String electricityAddress; + + private String industryType; + + private String voltageLevel; + + private String importantLevel; + + private String substationName; + + private String busbarName; + + private String operationUnit; + + private String manufacturer; + + private String bigObjType; + + private String smallObjType; + + private Integer isShow; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/SimulationMsgParam.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/SimulationMsgParam.java new file mode 100644 index 0000000..6b6a27c --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/param/SimulationMsgParam.java @@ -0,0 +1,21 @@ +package com.njcn.product.event.transientes.pojo.param; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * @Author: cdf + * @CreateTime: 2025-07-01 + * @Description: + */ +@Data +public class SimulationMsgParam { + + @NotBlank(message = "号码不可为空") + private String phone; + + @NotBlank(message = "短信内容不可为空") + private String msg; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MessageEventFeedback.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MessageEventFeedback.java new file mode 100644 index 0000000..4a6570e --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MessageEventFeedback.java @@ -0,0 +1,35 @@ +package com.njcn.product.event.transientes.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: 暂降远程通知反馈 + */ +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("MSG_EVENT_FEEDBACK") +public class MessageEventFeedback { + + @TableId(type = IdType.INPUT) + private String id; + + private String eventIndex; + + private Integer isSensitive; + + private String influenceFactors; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date dealDate; + + private String dealScheme; + + private String remark; + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventConfig.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventConfig.java new file mode 100644 index 0000000..45b210f --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventConfig.java @@ -0,0 +1,84 @@ +package com.njcn.product.event.transientes.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-06-27 + * @Description: + */ +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import java.util.List; + +import lombok.Data; +import lombok.ToString; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +/** + * MSG_EVENT_CONFIG表实体类 + */ +@Data +@TableName("MSG_EVENT_CONFIG") +@ToString +public class MsgEventConfig implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 主键ID + */ + @TableId("ID") + private String id; + + /** + * 严重通知标识 + */ + @TableField("SERIOUS_NOTICE") + @NotNull(message = "严重通知标识不可为空") + private Integer seriousNotice; + + /** + * 普通通知标识 + */ + @TableField("NORMAL_NOTIC") + @NotNull(message = "普通通知标识不可为空") + private Integer normalNotic; + + /** + * 语音类型 + */ + @TableField("VOICE_TYPE") + @NotNull(message = "语音类型不可为空") + private Integer voiceType; + + /** + * 屏幕通知标识 + */ + @TableField("SCREEN_NOTIC") + @NotNull(message = "屏幕通知标识不可为空") + private Integer screenNotic; + + /** + * 暂降类型,以逗号隔开 + */ + private String eventType; + + /** + * 暂降残余电压告警阈值 + */ + private Float eventValue; + + /** + * 暂降持续时间告警阈值 + */ + private Integer eventDuration; + + + @NotEmpty(message = "事件类型不可为空") + @TableField(exist = false) + private List eventTypeList; + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventInfo.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventInfo.java new file mode 100644 index 0000000..088b701 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/MsgEventInfo.java @@ -0,0 +1,66 @@ +package com.njcn.product.event.transientes.pojo.po; + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ + +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + * 消息事件信息实体 + */ +@Data +@TableName("MSG_EVENT_INFO") +public class MsgEventInfo implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 消息索引 + */ + private String msgIndex; + + /** + * 用户ID + */ + private String userId; + + private String userName; + + /** + * 发送时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime sendTime; + + /** + * 消息内容 + */ + private String msgContent; + + /** + * 事件索引 + */ + private String eventIndex; + + /** + * 手机号 + */ + private String phone; + + /** + * 发送结果 + */ + private Integer sendResult; + + /** + * 是否反馈 + */ + private Integer isHandle; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqDevicedetailaaa.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqDevicedetailaaa.java new file mode 100644 index 0000000..5cff653 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqDevicedetailaaa.java @@ -0,0 +1,94 @@ +//package com.njcn.gather.event.transientes.pojo.po; +// +//import com.baomidou.mybatisplus.annotation.IdType; +//import com.baomidou.mybatisplus.annotation.TableField; +//import com.baomidou.mybatisplus.annotation.TableId; +//import com.baomidou.mybatisplus.annotation.TableName; +//import java.time.LocalDateTime; +//import lombok.Data; +//import lombok.NoArgsConstructor; +// +///** +// * +// * Description: +// * Date: 2025/06/19 下午 1:47【需求编号】 +// * +// * @author clam +// * @version V1.0.0 +// */ +///** +// * 靠靠靠? +// */ +//@Data +//@NoArgsConstructor +//@TableName(value = "PQ_DEVICEDETAIL") +//public class PqDevicedetail { +// /** +// * 靠靠 +// */ +// @TableId(value = "DEV_INDEX", type = IdType.INPUT) +// private Integer devIndex; +// +// /** +// * (靠PQS_Dicdata)靠靠縂uid +// */ +// @TableField(value = "MANUFACTURER") +// private String manufacturer; +// +// /** +// * 靠靠(0:靠 1:靠) +// */ +// @TableField(value = "CHECKFLAG") +// private Integer checkflag; +// +// /** +// * 靠靠靠 +// */ +// @TableField(value = "THISTIMECHECK") +// private LocalDateTime thistimecheck; +// +// /** +// * 靠靠靠(靠靠靠靠靠3靠靠靠靠靠靠靠) +// */ +// @TableField(value = "NEXTTIMECHECK") +// private LocalDateTime nexttimecheck; +// +// /** +// * 靠靠靠? +// */ +// @TableField(value = "ONLINERATETJ") +// private Integer onlineratetj; +// +// @TableField(value = "DATAPLAN") +// private Integer dataplan; +// +// @TableField(value = "NEWTRAFFIC") +// private Integer newtraffic; +// +// @TableField(value = "ELECTROPLATE") +// private Integer electroplate; +// +// @TableField(value = "ONTIME") +// private Integer ontime; +// +// /** +// * 合同 +// */ +// @TableField(value = "CONTRACT") +// private String contract; +// +// /** +// * sim卡号 +// */ +// @TableField(value = "SIM") +// private String sim; +// +// @TableField(value = "DEV_CATENA") +// private String devCatena; +// +// @TableField(value = "DEV_LOCATION") +// private String devLocation; +// +// @TableField(value = "DEV_NO") +// private String devNo; +//} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLedgerPO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLedgerPO.java new file mode 100644 index 0000000..63a3076 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLedgerPO.java @@ -0,0 +1,108 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@Data +@TableName(value = "pq_user_ledger") +public class PqUserLedgerPO implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId + @TableField(value = "id") + private String id; + + @TableField(value = "POWER_SUPPLY_AREA") + private String powerSupplyArea; + + @TableField(value = "CUSTOMER_NAME") + private String customerName; + + @TableField(value = "ELECTRICITY_ADDRESS") + private String electricityAddress; + + @TableField(value = "INDUSTRY_TYPE") + private String industryType; + + @TableField(value = "VOLTAGE_LEVEL") + private String voltageLevel; + + @TableField(value = "IMPORTANT_LEVEL") + private String importantLevel; + + @TableField(value = "SUBSTATION_NAME") + private String substationName; + + @TableField(value = "BUSBAR_NAME") + private String busbarName; + + @TableField(value = "OPERATION_UNIT") + private String operationUnit; + + @TableField(value = "MANUFACTURER") + private String manufacturer; + + @TableField(value = "BIG_OBJ_TYPE") + private String bigObjType; + + @TableField(value = "SMALL_OBJ_TYPE") + private String smallObjType; + + /** + * 设备或对象的分类小类 + */ + @TableField(value = "CREATE_BY") + private String createBy; + + @TableField(value = "UPDATE_BY") + private String updateBy; + + + /** + * 创建时间(自动填充) + */ + @TableField(value = "CREATE_TIME") + private LocalDateTime createTime; + + /** + * 更新时间(自动填充) + */ + @TableField(value = "UPDATE_TIME") + private LocalDateTime updateTime; + + @TableField(value = "IS_SHOW") + private Integer isShow; + + @TableField(exist = false) + private Integer eventCount = 0; + + @TableField(exist = false) + private List eventIds; + + @TableField(exist = false) + private String deptName; + + @TableField(exist = false) + private String gdName; + + @TableField(exist = false) + private String station; + + @TableField(exist = false) + private String info; + + @TableField(exist = false) + private List eventList; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLineAssPO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLineAssPO.java new file mode 100644 index 0000000..2237144 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqUserLineAssPO.java @@ -0,0 +1,25 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@Data +@TableName(value = "pq_user_line_ass") +public class PqUserLineAssPO { + + @TableField(value = "USER_INDEX") + private String userIndex; + + @TableField(value = "LINE_INDEX") + private Integer lineIndex; + + + @TableField(exist = false) + private String userName; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDepts.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDepts.java new file mode 100644 index 0000000..0b991d7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDepts.java @@ -0,0 +1,79 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.time.LocalDateTime; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:57【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +/** + * 部门表 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQS_DEPTS") +public class PqsDepts { + /** + * 部门表Guid + */ + @TableId(value = "DEPTS_INDEX", type = IdType.INPUT) + private String deptsIndex; + + /** + * 部门名称 + */ + @TableField(value = "DEPTSNAME") + private String deptsname; + + /** + * 排序 + */ + @TableField(value = "DEPTS_DESC") + private Integer deptsDesc; + + /** + * (关联表PQS_User)用户表Guid + */ + @TableField(value = "USER_INDEX") + private String userIndex; + + /** + * 更新时间 + */ + @TableField(value = "UPDATETIME") + private LocalDateTime updatetime; + + /** + * 部门描述 + */ + @TableField(value = "DEPTS_DESCRIPTION") + private String deptsDescription; + + /** + * 角色状态0:删除;1:正常; + */ + @TableField(value = "\"STATE\"") + private Integer state; + + /** + * 行政区域 + */ + @TableField(value = "AREA") + private String area; + + @TableField(value = "CUSTOM_DEPT") + private Integer customDept; + + @TableField(value = "PARENTNODEID") + private String parentnodeid; +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicData.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicData.java new file mode 100644 index 0000000..e92f1b0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicData.java @@ -0,0 +1,49 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/12 + */ +@TableName(value = "PQS_DICDATA") +@Data +public class PqsDicData { + + @TableId + @TableField(value = "DIC_INDEX") + private String dicIndex; + + @TableField(value = "DIC_NAME") + private String dicName; + + @TableField(value = "DIC_TYPE") + private String dicType; + + @TableField(value = "DIC_NUMBER") + private Integer dicNumber; + + @TableField(value = "UPDATETIME") + private Date updateTime; + + @TableField(value = "USER_INDEX") + private String userIndex; + + //事件等级 + @TableField(value = "DIC_LEAVE") + private Integer dicLeave; + + @TableField(value = "STATE") + private Integer state; + @TableField(value = "TRIPHASE") + private Integer triphase; + + @TableField(value = "BACK_UP") + private String backUp;} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicTreePO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicTreePO.java new file mode 100644 index 0000000..1c3b0b5 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicTreePO.java @@ -0,0 +1,48 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@Data +@TableName(value = "PQS_DICTREE") +public class PqsDicTreePO { + @TableId // 标记主键字段 + @TableField(value ="ID") // 显式指定列名(默认按字段名映射,可省略) + private String id; + + @TableField(value ="NAME") + private String name; + + @TableField(value ="CODE") + private String code; + + @TableField(value ="PARENT_ID") + private String parentId; + + @TableField(value ="DIC_VALUE") + private String dicValue; + + @TableField(value ="CREATE_BY") + private String createBy; + + @TableField(value ="CREATE_TIME") + private Date createTime; + + @TableField(value ="UPDATE_BY") + private String updateBy; + + @TableField(value ="UPDATE_TIME") + private Date updateTime; + + @TableField(exist = false) + private Integer level; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicType.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicType.java new file mode 100644 index 0000000..1cdc3f4 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsDicType.java @@ -0,0 +1,39 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * @Author: cdf + * @CreateTime: 2025-09-24 + * @Description: + */ +@TableName(value="PQS_DICTYPE") +@Data +public class PqsDicType { + + @TableId(value = "DICTYPE_INDEX") + private String dicTypeIndex; + + @TableField(value = "DICTYPE_NAME") + private String dicTypeName; + + @TableField(value = "DICTYPE_NUMBER") + private Integer dicTypeNumber; + + @TableField(value = "DICTYPE_DESCRIBE") + private String dicTypeDiscribe; + + @TableField(value = "USER_INDEX") + private String userIndex; + + @TableField(value = "UPDATETIME") + private Date updateTime; + + @TableField(value = "STATE") + private Integer state; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsEventdetail.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsEventdetail.java new file mode 100644 index 0000000..eab2338 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsEventdetail.java @@ -0,0 +1,107 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/06/20 上午 10:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQS_EVENTDETAIL") +public class PqsEventdetail { + @TableId(value = "EVENTDETAIL_INDEX", type = IdType.INPUT) + private String eventdetailIndex; + + @TableField(value = "LINEID") + private Integer lineid; + + @TableField(value = "TIMEID") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timeid; + + @TableField(value = "MS") + private BigDecimal ms; + + @TableField(value = "\"DESCRIBE\"") + private String describe; + + @TableField(value = "WAVETYPE") + private Integer wavetype; + + @TableField(value = "PERSISTTIME") + private Double persisttime; + + @TableField(value = "EVENTVALUE") + private Double eventvalue; + + @TableField(value = "EVENTREASON") + private String eventreason; + + @TableField(value = "EVENTTYPE") + private String eventtype; + + @TableField(value = "EVENTASS_INDEX") + private String eventassIndex; + + @TableField(value = "DQTIME") + private Double dqtime; + + @TableField(value = "DEALTIME") + private LocalDateTime dealtime; + + @TableField(value = "DEALFLAG") + private Integer dealflag; + + @TableField(value = "NUM") + private BigDecimal num; + + @TableField(value = "FILEFLAG") + private Integer fileflag; + + @TableField(value = "FIRSTTIME") + private LocalDateTime firsttime; + + @TableField(value = "FIRSTTYPE") + private String firsttype; + + @TableField(value = "FIRSTMS") + private BigDecimal firstms; + + @TableField(value = "WAVENAME") + private String wavename; + + @TableField(value = "ENERGY") + private Double energy; + + @TableField(value = "SEVERITY") + private Double severity; + + @TableField(value = "LOOK_FLAG") + private Integer lookFlag; + + @TableField(value = "NOTICE_FLAG") + private Integer noticeFlag; + + @TableField(exist = false) + private Integer eventSeverity; + + @TableField(exist = false) + private String stationName; + + @TableField(exist = false) + private String busBarName; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsIntegrity.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsIntegrity.java new file mode 100644 index 0000000..f6db708 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsIntegrity.java @@ -0,0 +1,34 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; + +/** + * CN_Gather + * + * @author cdf + * @date 2025/8/9 + */ + + +@TableName(value="PQS_INTEGRITY") +@Data +public class PqsIntegrity { + + @TableField(value="TIMEID") + private LocalDate timeID; + + @TableField(value="Line_index") + private Integer lineIndex; + + @TableField(value="due") + private Integer due; + + @TableField(value="real") + private Integer real; + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsOnlinerate.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsOnlinerate.java new file mode 100644 index 0000000..0a3f419 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsOnlinerate.java @@ -0,0 +1,32 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import java.time.LocalDateTime; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * Description: + * Date: 2025/07/29 下午 6:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +@NoArgsConstructor +@TableName(value = "PQS_ONLINERATE") +public class PqsOnlinerate { + @TableField(value = "TIMEID" ) + private LocalDateTime timeid; + + @TableField(value = "DEV_INDEX") + private Integer devIndex; + + @TableField(value = "ONLINEMIN") + private Integer onlinemin; + + @TableField(value = "OFFLINEMIN") + private Integer offlinemin; +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUser.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUser.java new file mode 100644 index 0000000..c43e6ac --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUser.java @@ -0,0 +1,58 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; + +import java.util.Date; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +@Data +@TableName("PQS_USER") +public class PqsUser { + + @TableId(type = IdType.INPUT) + private String userIndex; + + private String name; + + private String loginname; + + private String password; + + private String phone; + + private String email; + + @TableField(fill = FieldFill.INSERT) + private Date registertime; + + private Date psdvalidity; + + private Date logintime; + + private Integer state; + + private Integer mark; + + private String limitIpstart; + + private String limitIpend; + + private String limitTime; + + private Integer loginErrorTimes; + + @TableField("CASUAL_USER") + private Integer casualUser; + + private Date firsterrorTime; + + + private Date lockTime; + + private String referralCode; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUserSet.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUserSet.java new file mode 100644 index 0000000..8137326 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/po/PqsUserSet.java @@ -0,0 +1,49 @@ +package com.njcn.product.event.transientes.pojo.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + * @Author: cdf + * @CreateTime: 2025-06-24 + * @Description: + */ +@Data +@TableName("PQS_USERSET") +public class PqsUserSet implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 用户设置索引 + */ + @TableId("USERSET_INDEX") + private String usersetIndex; + + /** + * 用户索引 + */ + @TableField("USER_INDEX") + private String userIndex; + + /** + * 是否通知(0-否,1-是) + */ + @TableField("ISNOTICE") + private Integer isNotice; + + /** + * 角色组索引 + */ + @TableField("ROLEGP_INDEX") + private String roleGpIndex; + + /** + * 部门索引 + */ + @TableField("DEPTS_INDEX") + private String deptsIndex; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/AlarmAnalysisVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/AlarmAnalysisVO.java new file mode 100644 index 0000000..bfe528b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/AlarmAnalysisVO.java @@ -0,0 +1,41 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2025/06/20 上午 9:29【需求编号】 + * + * @author clam + * @version V1.0.0 + */ + +@Data +public class AlarmAnalysisVO { + @ApiModelProperty(name="eventCount",value="暂降次数") + private Integer eventCount; + @ApiModelProperty(name="aLarmCount",value="告警事件统计") + private Integer aLarmCount; + @ApiModelProperty(name="warnCount",value="预警事件统计") + private Integer warnCount; + @ApiModelProperty(name="noticeCount",value="远程通知统计") + private Integer noticeCount; + @ApiModelProperty(name="lookALarmCount",value="告警事件处置数") + private Integer lookALarmCount; + @ApiModelProperty(name="lookWarnCount",value="预警事件处置数") + private Integer lookWarnCount; + @ApiModelProperty(name="lookNoticeCount",value="远程通知处置数") + private Integer lookNoticeCount; + + List eventdetails; + List aLarmEvent; + List warnEvent; + List noticeEvent; + List lookALarmEvent; + List lookWarnEvent; + List lookNoticeEvent; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/DeviceCountVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/DeviceCountVO.java new file mode 100644 index 0000000..d3cdc32 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/DeviceCountVO.java @@ -0,0 +1,18 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import lombok.Data; + +/** + * Description: + * Date: 2025/07/28 上午 8:50【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class DeviceCountVO { + private Integer allCount; + private Integer onLine; + private Integer offLine; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventDetailVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventDetailVO.java new file mode 100644 index 0000000..3b622c0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventDetailVO.java @@ -0,0 +1,52 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * Description: + * Date: 2025/06/20 下午 2:50【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class EventDetailVO { + + private String eventdetail_index; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime timeid; + + private BigDecimal ms; + + private String wavetype; + + private Double eventvalue; + + private Integer lookFlag; + + private Integer noticeFlag; + + private Integer lineid; + + private String pointname; + private String gdName; + private String busName; + private String devName; + + private String persisttime; + + + private String bdname; + + private String objName; + + private Integer needDealFlag; + private long msgEventInfoSize; + //1告警,2预警 + private Integer eventSeverity; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventMsgDetailVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventMsgDetailVO.java new file mode 100644 index 0000000..d77e2c4 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventMsgDetailVO.java @@ -0,0 +1,35 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import lombok.Data; + +import java.util.Date; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: 暂降远程通知详情 + */ +@Data +public class EventMsgDetailVO { + + private String eventIndex; + + private Integer isSensitive; + + private String influenceFactors; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date dealDate; + + private String dealScheme; + + private String remark; + + private String objName; + + private List msgList; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventTrendVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventTrendVO.java new file mode 100644 index 0000000..6ca36a9 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/EventTrendVO.java @@ -0,0 +1,18 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import lombok.Data; + +import java.time.LocalDate; + +/** + * Description: + * Date: 2025/06/20 上午 11:33【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class EventTrendVO { + private LocalDate localDate; + private Integer eventCount; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/LedgerCountVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/LedgerCountVO.java new file mode 100644 index 0000000..e0e9665 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/LedgerCountVO.java @@ -0,0 +1,31 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.dto.SubstationDTO; +import lombok.Data; + +import java.util.List; + +/** + * Description: + * Date: 2025/06/19 下午 3:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class LedgerCountVO { + + private long allSubCount; + private long allDevCount; + private long allLineCount; + private long runDevCount; + private long runSubCount; + private long runLineCount; + + private List allSubList; + private List allDevList; + private List allLineList; + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/MapCountVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/MapCountVO.java new file mode 100644 index 0000000..a5e682b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/MapCountVO.java @@ -0,0 +1,28 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * Description: + * Date: 2025/06/26 上午 8:50【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class MapCountVO { + private String deptsIndex; + private String deptsName; + private Integer lineCount; + private Integer eventCount; + private Integer noticeCount; + + private List lineList = new ArrayList<>(); + private List eventList = new ArrayList<>(); + private List noticeList = new ArrayList<>(); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/PqsDicTreeVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/PqsDicTreeVO.java new file mode 100644 index 0000000..ffdcb64 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/PqsDicTreeVO.java @@ -0,0 +1,36 @@ +package com.njcn.product.event.transientes.pojo.vo; + + +import lombok.Data; + +import java.util.Date; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-01 + * @Description: + */ +@Data +public class PqsDicTreeVO { + + private String id; + + private String name; + + private String code; + + private String parentId; + + private String dicValue; + + private String createBy; + + private Date createTime; + + private String updateBy; + + private Date updateTime; + + private List children; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/RegionDevCountVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/RegionDevCountVO.java new file mode 100644 index 0000000..4f35776 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/RegionDevCountVO.java @@ -0,0 +1,28 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import lombok.Data; + +/** + * Description: + * Date: 2025/07/28 上午 10:26【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class RegionDevCountVO { + + /** + * 部门表Guid + */ + private String deptsIndex; + + /** + * 部门名称 + */ + private String deptsname; + private String areaName; + private Integer allCount; + private Integer onLine; + private Integer offLine; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/SubStationCountVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/SubStationCountVO.java new file mode 100644 index 0000000..29d86f0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/SubStationCountVO.java @@ -0,0 +1,63 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * Description: + * Date: 2025/07/29 上午 11:03【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Data +public class SubStationCountVO { + private Integer stationId; + private String stationName; + private String gdName; + private double longitude; + private double latitude; + private Integer lineCount; + private Integer eventCount; + + private List lineEventDetails; + + + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class LineEventDetail { + private String gdName; + private String gdIndex; + + private Integer lineId; + + private String lineName; + + private Integer busBarId; + + private String busBarName; + + private Integer devId; + + private String devName; + + private String objName; + + private Integer stationId; + + private String stationName; + //通讯状态 + private Integer runFlag=0; + + private Integer eventCount; + + private List pqsEventdetails; + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/UserLedgerStatisticVO.java b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/UserLedgerStatisticVO.java new file mode 100644 index 0000000..2f6f0ce --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/pojo/vo/UserLedgerStatisticVO.java @@ -0,0 +1,63 @@ +package com.njcn.product.event.transientes.pojo.vo; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: 大屏右侧实体 + */ +@Data +public class UserLedgerStatisticVO { + + @ApiModelProperty(value = "半导体及精密加工大类id") + private String importId; + + private Integer importNum = 0; + + private Integer importDevNum = 0; + + @ApiModelProperty(value = "其他敏感用户大类id") + private String otherImportId; + + private Integer otherImportNum = 0; + + private Integer otherImportDevNum = 0; + + @ApiModelProperty(value = "其他干扰源大类id") + private String otherId; + + private Integer otherNum = 0; + + private Integer otherDevNum = 0; + + private List innerList = new ArrayList<>(); + + + + @Data + public static class Inner{ + + private String treeId; + + private String parentId; + + private String customId; + + private String name; + + private String code; + + private Integer count; + + private List eventList; + + private List children; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthController.java b/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthController.java new file mode 100644 index 0000000..e9a64e9 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthController.java @@ -0,0 +1,102 @@ +package com.njcn.product.event.transientes.security; + +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.response.HttpResult; +import com.njcn.product.event.transientes.utils.JwtUtil; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.controller.BaseController; +import com.njcn.web.utils.HttpResultUtil; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +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.RestController; + +import javax.validation.constraints.NotBlank; + +@RestController +@Slf4j +@RequiredArgsConstructor +public class AuthController extends BaseController { + + private final String eventRedisKey = "event_smart_"; + + + private final AuthenticationManager authenticationManager; + + + private final JwtUtil jwtUtil; + + private final RedisUtil redisUtil; + + + + + + @PostMapping("/cn_authenticate") + @ApiOperation("登录认证") + public HttpResult createAuthenticationToken(@RequestBody @Validated AuthRequest authRequest) { + String methodDescribe = getMethodDescribe("createAuthenticationToken"); + //log.info("Authentication request - username: {}, password: {}",authRequest.getUsername(),authRequest.getPassword()); + try { + boolean hasFlag = redisUtil.hasKey(eventRedisKey+authRequest.getUsername()); + if(hasFlag){ + String pass = redisUtil.getRawValue(eventRedisKey+authRequest.getUsername()); + + // 执行认证,内部会调用 UserDetailsService 加载用户信息 + Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequest.getUsername(),pass)); + + // 将认证信息存入 SecurityContext + SecurityContextHolder.getContext().setAuthentication(authentication); + + // 直接从 Authentication 对象中获取已加载的 UserDetails,避免重复查询 + MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal(); + + // 获取用户部门(假设 CustomUserDetails 包含部门信息) + String department = userDetails.getDeptId(); + + final String jwt = jwtUtil.generateToken(userDetails); + + AuthResponse authResponse = new AuthResponse(); + authResponse.setToken(jwt); + authResponse.setDeptId(department); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, authResponse, methodDescribe); + }else { + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } catch (Exception e) { + e.printStackTrace(); + return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe); + } + } +} + +// 认证请求类 +class AuthRequest { + + @NotBlank(message = "用户名不可为空") + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthResponse.java b/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthResponse.java new file mode 100644 index 0000000..ddf6230 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/security/AuthResponse.java @@ -0,0 +1,20 @@ +package com.njcn.product.event.transientes.security; + +import lombok.Data; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +@Data +public class AuthResponse { + + private String token; + + private String deptId; + + private String roleId; + + private String userIndex; +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetails.java b/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetails.java new file mode 100644 index 0000000..471ab25 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetails.java @@ -0,0 +1,64 @@ +package com.njcn.product.event.transientes.security; + +import lombok.Data; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +@Data +public class MyUserDetails implements UserDetails { + + private String userId; // 用户唯一标识 + private String username; // 用户名 + private String password; // 密码 + private String deptId; // 部门信息 + private Collection authorities; // 权限集合 + private boolean accountNonExpired; // 账户是否未过期 + private boolean accountNonLocked; // 账户是否未锁定 + private boolean credentialsNonExpired; // 凭证是否未过期 + private boolean enabled; // 账户是否启用 + + public MyUserDetails(String userId,String username, String password, String deptId,Collection authorities) { + this.userId = userId; + this.username = username; + this.password = password; + this.deptId = deptId; + this.authorities = authorities; + } + + @Override + public String getPassword() { + return this.password; + } + + @Override + public String getUsername() { + return this.username; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} \ No newline at end of file diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetailsService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetailsService.java new file mode 100644 index 0000000..5915763 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/security/MyUserDetailsService.java @@ -0,0 +1,66 @@ +package com.njcn.product.event.transientes.security; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.njcn.product.event.transientes.mapper.PqsUserMapper; +import com.njcn.product.event.transientes.mapper.PqsUserSetMapper; +import com.njcn.product.event.transientes.pojo.po.PqsUser; +import com.njcn.product.event.transientes.pojo.po.PqsUserSet; +import com.njcn.redis.utils.RedisUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +public class MyUserDetailsService implements UserDetailsService { + + private final PqsUserMapper pqsUserMapper; + + private final PqsUserSetMapper pqsUserSetMapper; + + private final RedisUtil redisUtil; + + + + @Override + public MyUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + + + if("system_event".equals(username)){ + return new MyUserDetails("12345678910","system_event", "@#001njcnpqs","10001", + new ArrayList<>()); + } + + + if(redisUtil.hasKey("event_smart_"+username)){ + String password = redisUtil.getRawValue("event_smart_"+username); + // 这里应该从数据库中获取用户信息,本示例使用硬编码用户 + PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + String encodedPassword = passwordEncoder.encode(password); + + LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); + userWrapper.eq(PqsUser::getLoginname,username); + PqsUser pqsUser = pqsUserMapper.selectOne(userWrapper); + if(Objects.isNull(pqsUser)){ + throw new UsernameNotFoundException("User not found with username: " + username); + } + + LambdaQueryWrapper userSetWrapper = new LambdaQueryWrapper<>(); + userSetWrapper.eq(PqsUserSet::getUserIndex,pqsUser.getUserIndex()); + PqsUserSet pqsUserSet = pqsUserSetMapper.selectOne(userSetWrapper); + String deptId = pqsUserSet.getDeptsIndex(); + + + return new MyUserDetails(pqsUser.getUserIndex(),pqsUser.getLoginname(), encodedPassword,deptId, + new ArrayList<>()); + }else { + throw new UsernameNotFoundException("User not found with username: " + username); + } + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/security/SecurityConfig.java b/event_smart/src/main/java/com/njcn/product/event/transientes/security/SecurityConfig.java new file mode 100644 index 0000000..1f1b5cb --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/security/SecurityConfig.java @@ -0,0 +1,57 @@ +package com.njcn.product.event.transientes.security; + +import com.njcn.product.event.transientes.filter.JwtRequestFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private JwtRequestFilter jwtRequestFilter; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + //.antMatchers("/cn_authenticate","/ws/**","/accept/testEvent","/accept/eventMsg").permitAll() // 允许访问认证接口 + .antMatchers("/**").permitAll() // 允许访问认证接口 + .anyRequest().authenticated() + .and() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 使用无状态会话 + + http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/CommGeneralService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/CommGeneralService.java new file mode 100644 index 0000000..aa557ae --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/CommGeneralService.java @@ -0,0 +1,52 @@ +package com.njcn.product.event.transientes.service; + +import cn.hutool.core.util.StrUtil; +import com.njcn.product.event.devcie.pojo.po.PqsDeptsline; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.redis.utils.RedisUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import static com.njcn.product.event.transientes.pojo.constant.RedisConstant.REDIS_DEPT_INDEX; + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ +@Service +@RequiredArgsConstructor +public class CommGeneralService { + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + + private final PqsDeptslineService pqsDeptslineService; + private final PqsDeptsService pqsDeptsService; + private final RedisUtil redisUtil; + + /** + * 根据部门id获取部门所拥有的监测点 + * @param largeScreenCountParam + * @return + */ + public List getLineIdsByDept(LargeScreenCountParam largeScreenCountParam){ + List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + return deptslineIds; + + } + + + public List getLineIdsByRedis(String deptId){ + List deptLineIds = (List) redisUtil.getObjectByKey( REDIS_DEPT_INDEX+ StrUtil.DASHED+deptId); + return deptLineIds; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventGateService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventGateService.java new file mode 100644 index 0000000..7fca510 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventGateService.java @@ -0,0 +1,15 @@ +package com.njcn.product.event.transientes.service; + +import com.njcn.event.file.pojo.dto.WaveDataDTO; +import com.njcn.product.event.transientes.pojo.param.MonitorTerminalParam; + +public interface EventGateService { + + + /** + * 功能描述: 暂态事件波形分析 + * @param param + * @return + */ + WaveDataDTO getTransientAnalyseWave(MonitorTerminalParam param); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventRightService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventRightService.java new file mode 100644 index 0000000..6edbef5 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/EventRightService.java @@ -0,0 +1,48 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.pojo.po.PqGdCompany; +import com.njcn.product.event.devcie.pojo.po.PqSubstation; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.po.PqUserLedgerPO; +import com.njcn.product.event.transientes.pojo.vo.EventDetailVO; +import com.njcn.product.event.transientes.pojo.vo.UserLedgerStatisticVO; + +import java.util.List; + +public interface EventRightService { + + + UserLedgerStatisticVO userLedgerStatistic(LargeScreenCountParam param); + + + Page rightEventOpen(LargeScreenCountParam param); + + Page rightEventOpenForDetail(LargeScreenCountParam param); + + + Page rightEventDevOpen(LargeScreenCountParam param); + + + + + List rightImportUser(LargeScreenCountParam param); + + + PqUserLedgerPO rightImportOpenDetail(LargeScreenCountParam param); + + + + List gdSelect(); + + List bdSelect(); + + + + + /*-------------------------------------------------------*/ + UserLedgerStatisticVO userLedgerStatisticClone(LargeScreenCountParam param); + + Page rightEventOpenClone(LargeScreenCountParam param); + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/LargeScreenCountService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/LargeScreenCountService.java new file mode 100644 index 0000000..7f3ed9b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/LargeScreenCountService.java @@ -0,0 +1,64 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.pojo.dto.DeviceDTO; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.param.MessageEventFeedbackParam; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import com.njcn.product.event.transientes.pojo.vo.*; + +import java.util.List; + +/** + * Description: + * Date: 2025/06/19 下午 3:05【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface LargeScreenCountService { + + void initLedger(LargeScreenCountParam largeScreenCountParam); + + LedgerCountVO scaleStatistics(LargeScreenCountParam largeScreenCountParam); + + AlarmAnalysisVO alarmAnalysis(LargeScreenCountParam largeScreenCountParam); + + List eventTrend(LargeScreenCountParam largeScreenCountParam); + + Page eventList(LargeScreenCountParam largeScreenCountParam); + + List noDealEventList(LargeScreenCountParam largeScreenCountParam); + + + boolean lookEvent(List ids); + + List mapCount(LargeScreenCountParam largeScreenCountParam); + + EventMsgDetailVO eventMsgDetail(String eventId); + + List msgSendList(LargeScreenCountParam largeScreenCountParam); + + Page hasSendMsgPage(LargeScreenCountParam largeScreenCountParam); + + boolean msgHandle(MessageEventFeedbackParam messageEventFeedbackParam); + + + AlarmAnalysisVO alarmAnalysisDetail(LargeScreenCountParam largeScreenCountParam); + + Page eventTablePage(LargeScreenCountParam largeScreenCountParam); + + DeviceCountVO devFlagCount(LargeScreenCountParam largeScreenCountParam); + + List devDetail(LargeScreenCountParam largeScreenCountParam); + + List regionDevCount(LargeScreenCountParam largeScreenCountParam); + + List substationCount(LargeScreenCountParam largeScreenCountParam); + + Page eventPage(LargeScreenCountParam largeScreenCountParam); + + Page devicePage(LargeScreenCountParam largeScreenCountParam); + + Page userEventList(LargeScreenCountParam largeScreenCountParam); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/MessageEventFeedbackService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MessageEventFeedbackService.java new file mode 100644 index 0000000..3156159 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MessageEventFeedbackService.java @@ -0,0 +1,7 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.MessageEventFeedback; + +public interface MessageEventFeedbackService extends IService { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventConfigService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventConfigService.java new file mode 100644 index 0000000..697f077 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventConfigService.java @@ -0,0 +1,20 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.MsgEventConfig; + +import java.util.List; + +public interface MsgEventConfigService extends IService { + + boolean eventConfig(MsgEventConfig msgEventConfig); + + + MsgEventConfig queryConfig(); + + List getEventType(); + + Float getEventValue(); + + Integer getEventDuration(); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventInfoService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventInfoService.java new file mode 100644 index 0000000..43db3bd --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/MsgEventInfoService.java @@ -0,0 +1,11 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; + +import java.util.List; + +public interface MsgEventInfoService extends IService { + + List getMsgByIds(List ids); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqDevicedetailService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqDevicedetailService.java new file mode 100644 index 0000000..1730877 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqDevicedetailService.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.transientes.service; + +import com.njcn.product.event.devcie.pojo.po.PqDeviceDetail; +import com.baomidou.mybatisplus.extension.service.IService; + /** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqDevicedetailService extends IService{ + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqUserLedgerService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqUserLedgerService.java new file mode 100644 index 0000000..64484ae --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqUserLedgerService.java @@ -0,0 +1,26 @@ +package com.njcn.product.event.transientes.service; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.param.PqUserLedgerParam; +import com.njcn.product.event.transientes.pojo.po.PqUserLedgerPO; + +import java.util.List; + +public interface PqUserLedgerService extends IService { + // 添加记录 + boolean addLedger(PqUserLedgerParam ledgerParam); + + // 更新记录 + boolean updateLedger(PqUserLedgerParam ledgerParam); + + // 删除记录(物理删除) + boolean deleteLedger(List ids); + + // 查询单条记录 + PqUserLedgerPO getLedgerById(String id); + + // 查询所有记录 + Page pageList(PqUserLedgerParam param); +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDeptsService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDeptsService.java new file mode 100644 index 0000000..a9f6649 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDeptsService.java @@ -0,0 +1,24 @@ +package com.njcn.product.event.transientes.service; + +import com.njcn.product.event.devcie.pojo.dto.PqsDeptDTO; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.List; + +/** + * + * Description: + * Date: 2025/06/19 下午 3:57【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsDeptsService extends IService{ + + + List findDeptAndChildren( String deptId); + + List getDeptList( List deptIds); + + } diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDicTreeService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDicTreeService.java new file mode 100644 index 0000000..97cf056 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsDicTreeService.java @@ -0,0 +1,14 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.PqsDicTreePO; + +import java.util.List; + +public interface PqsDicTreeService extends IService { + + + + List getDicTree(String code); + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsEventdetailService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsEventdetailService.java new file mode 100644 index 0000000..cabf8ca --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsEventdetailService.java @@ -0,0 +1,17 @@ +package com.njcn.product.event.transientes.service; + +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + * + * Description: + * Date: 2025/06/20 上午 10:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsEventdetailService extends IService{ + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsOnlinerateService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsOnlinerateService.java new file mode 100644 index 0000000..23a77cf --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsOnlinerateService.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.transientes.service; + +import com.njcn.product.event.transientes.pojo.po.PqsOnlinerate; +import com.baomidou.mybatisplus.extension.service.IService; + /** + * + * Description: + * Date: 2025/07/29 下午 6:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsOnlinerateService extends IService{ + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUserService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUserService.java new file mode 100644 index 0000000..5a82bc9 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUserService.java @@ -0,0 +1,14 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.PqsUser; + +/** + * Description: + * Date: 2025/06/27 上午 9:45【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsUserService extends IService { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUsersetService.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUsersetService.java new file mode 100644 index 0000000..50243f4 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/PqsUsersetService.java @@ -0,0 +1,18 @@ +package com.njcn.product.event.transientes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.njcn.product.event.transientes.pojo.po.PqsUserSet; + +/** + * + * Description: + * Date: 2025/06/26 下午 2:27【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +public interface PqsUsersetService extends IService{ + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventGateServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventGateServiceImpl.java new file mode 100644 index 0000000..4c306fd --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventGateServiceImpl.java @@ -0,0 +1,76 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.event.file.component.WaveFileComponent; +import com.njcn.event.file.pojo.dto.WaveDataDTO; +import com.njcn.event.file.pojo.enums.WaveFileResponseEnum; +import com.njcn.product.event.devcie.mapper.PqLinedetailMapper; +import com.njcn.product.event.devcie.pojo.po.PqDevice; +import com.njcn.product.event.devcie.pojo.po.PqLine; +import com.njcn.product.event.devcie.pojo.po.PqLinedetail; +import com.njcn.product.event.devcie.service.PqDeviceService; +import com.njcn.product.event.devcie.service.PqLineService; +import com.njcn.product.event.transientes.pojo.param.MonitorTerminalParam; +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; +import com.njcn.product.event.transientes.service.EventGateService; +import com.njcn.product.event.transientes.service.PqsEventdetailService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.InputStream; +import java.util.Objects; + +/** + * @Author: cdf + * @CreateTime: 2025-06-30 + * @Description: + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class EventGateServiceImpl implements EventGateService { + + private final PqsEventdetailService pqsEventdetailService; + private final PqDeviceService pqDeviceService; + private final WaveFileComponent waveFileComponent; + private final PqLineService pqLineService; + private final PqLinedetailMapper pqLinedetailMapper; + @Value("${WAVEPATH}") + private String WAVEPATH; + @Override + public WaveDataDTO getTransientAnalyseWave(MonitorTerminalParam param) { + WaveDataDTO waveDataDTO; + //获取暂降事件 + PqsEventdetail eventDetail = pqsEventdetailService.getById(param.getId()); + Integer lineid = eventDetail.getLineid(); + PqLine pqLine = pqLineService.getById(lineid); + PqLinedetail pqLinedetail = pqLinedetailMapper.selectById(lineid); + PqDevice device = pqDeviceService.getById(pqLine.getDevIndex()); + String waveName = eventDetail.getWavename(); + String cfgPath, datPath; + if (StrUtil.isBlank(waveName)) { + throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); + } + cfgPath = WAVEPATH+"/"+device.getIp()+"/"+waveName+".CFG"; + datPath = WAVEPATH+"/"+device.getIp()+"/"+waveName+".DAT"; + log.info("本地磁盘波形文件路径----" + cfgPath); + InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath); + InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath); + if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) { + throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND); + } + waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1); + + waveDataDTO = waveFileComponent.getValidData(waveDataDTO); + + waveDataDTO.setPtType(pqLinedetail.getPttype()); + waveDataDTO.setPt(pqLine.getPt1()/ pqLine.getPt2()); + waveDataDTO.setCt(pqLine.getCt1()/ pqLine.getCt2()); + waveDataDTO.setMonitorName(pqLine.getName()); + return waveDataDTO; + + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventRightServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventRightServiceImpl.java new file mode 100644 index 0000000..6157527 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/EventRightServiceImpl.java @@ -0,0 +1,983 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.njcn.product.event.devcie.mapper.PqGdCompanyMapper; +import com.njcn.product.event.devcie.mapper.PqSubstationMapper; +import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO; +import com.njcn.product.event.devcie.pojo.po.*; +import com.njcn.product.event.devcie.service.PqLineService; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.product.event.transientes.mapper.PqUserLedgerMapper; +import com.njcn.product.event.transientes.mapper.PqUserLineAssMapper; +import com.njcn.product.event.transientes.mapper.PqsDicTreeMapper; +import com.njcn.product.event.transientes.pojo.DicTreeEnum; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.po.*; +import com.njcn.product.event.transientes.pojo.vo.EventDetailVO; +import com.njcn.product.event.transientes.pojo.vo.UserLedgerStatisticVO; +import com.njcn.product.event.transientes.service.*; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * @Author: cdf + * @CreateTime: 2025-06-30 + * @Description: + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class EventRightServiceImpl implements EventRightService { + + + private final PqUserLineAssMapper pqUserLineAssMapper; + + private final PqUserLedgerMapper pqUserLedgerMapper; + + private final PqsDicTreeMapper pqsDicTreeMapper; + + private final PqsEventdetailService pqsEventdetailService; + + private final MsgEventConfigService msgEventConfigService; + + private final PqLineService pqLineService; + + private final PqSubstationMapper pqSubstationMapper; + private final CommGeneralService commGeneralService; + + private final PqGdCompanyMapper pqGdCompanyMapper; + + private final PqsDeptslineService pqsDeptslineService; + + private final PqsDeptsService pqsDeptsService; + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + + + + @Override + public UserLedgerStatisticVO userLedgerStatistic(LargeScreenCountParam param) { + UserLedgerStatisticVO result = new UserLedgerStatisticVO(); + + // 1. 获取字典树数据 + List dicTreeList = getAllDicTrees(); + Map treeMap = getDicTreeMap(dicTreeList); + setResultIds(result, treeMap); + + // 2. 获取线路ID列表 + List lineIds = commGeneralService.getLineIdsByDept(param); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + + // 3. 获取用户线路关联数据 + List assList = getUserLineAssociations(lineIds); + if (CollUtil.isEmpty(assList)) { + return result; + } + + // 4. 获取用户台账信息 + Set assUserIds = assList.stream() + .map(PqUserLineAssPO::getUserIndex) + .collect(Collectors.toSet()); + List userLedgers = getUserLedgers(new ArrayList<>(assUserIds),null,false); + if (CollUtil.isEmpty(userLedgers)) { + return result; + } + + // 5. 获取事件和线路数据 + List events = getEventsInTimeRange(param, lineIds); + List lines = getLines(lineIds); + + // 6. 按用户类型分组处理 + Map> userMap = userLedgers.stream() + .collect(Collectors.groupingBy(PqUserLedgerPO::getBigObjType)); + + // 7. 构建结果 + buildResult(result, treeMap, userMap, assList, events, lines,dicTreeList); + + return result; + } + + + private List getAllDicTrees(){ + return pqsDicTreeMapper.selectList(new LambdaQueryWrapper<>()); + } + + private Map getDicTreeMap(List dicTreeList) { + List touList = dicTreeList.stream().filter(it -> Objects.equals(it.getCode(), DicTreeEnum.BJ_USER.getCode())||Objects.equals(it.getCode(), DicTreeEnum.OI_USER.getCode())||Objects.equals(it.getCode(), DicTreeEnum.OT_USER.getCode())).collect(Collectors.toList()); + Map treeMap = touList.stream().collect(Collectors.toMap(PqsDicTreePO::getCode, Function.identity())); + return treeMap; + } + + private void setResultIds (UserLedgerStatisticVO result,Map treeMap){ + treeMap.forEach((tree, obj) -> { + if (tree.equals(DicTreeEnum.BJ_USER.getCode())) { + result.setImportId(obj.getId()); + } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) { + result.setOtherImportId(obj.getId()); + } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) { + result.setOtherId(obj.getId()); + } + }); + } + + + private List getUserLineAssociations(List lineIds){ + LambdaQueryWrapper assQuery = new LambdaQueryWrapper<>(); + // assQuery.in(PqUserLineAssPO::getLineIndex, lineIds); + + if(lineIds.size()>1000){ + List> lineList = CollUtil.split(lineIds, 1000); + assQuery.and(w -> { + for (List ids : lineList) { + w.or(wIn -> wIn.in(PqUserLineAssPO::getLineIndex, ids)); + } + }); + }else { + assQuery.in(PqUserLineAssPO::getLineIndex, lineIds); + } + + return pqUserLineAssMapper.selectList(assQuery); + } + + private List getEventsInTimeRange(LargeScreenCountParam param,List lineIds){ + //查询时间段的暂降事件 + LambdaQueryWrapper eventQuery = new LambdaQueryWrapper<>(); + eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))) + .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()); + if (lineIds.size() > 1000) { + List> listLineIds = CollUtil.split(lineIds, 1000); + eventQuery.and(w -> { + for (List ids : listLineIds) { + w.or(wIn -> wIn.in(PqsEventdetail::getLineid, ids)); + } + }); + } else { + eventQuery.in(PqsEventdetail::getLineid, lineIds); + } + List eventdetailList = pqsEventdetailService.list(eventQuery); + if(CollUtil.isNotEmpty(eventdetailList)){ + eventdetailList.forEach(it->it.setPersisttime(BigDecimal.valueOf(it.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).doubleValue())); + } + return eventdetailList; + } + + private List getUserLedgers(List assUserIds,LargeScreenCountParam param,boolean queryFlag){ + LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); + if(assUserIds.size()>1000){ + List> assUserIdsList = CollUtil.split(assUserIds, 1000); + userWrapper.and(w -> { + for (List ids : assUserIdsList) { + w.or(wIn -> wIn.in(PqUserLedgerPO::getId, ids)); + } + }); + }else { + userWrapper.in(PqUserLedgerPO::getId, assUserIds); + } + if(queryFlag){ + if(StrUtil.isNotBlank(param.getBigObjType())){ + //对象大类不为空 + userWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType()); + } + if(StrUtil.isNotBlank(param.getSmallObjType())){ + //对象大类不为空 + userWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType()); + } + if(Objects.nonNull(param.getGdIndex())){ + userWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex()); + } + if(StrUtil.isNotBlank(param.getSearchValue())){ + userWrapper.like(PqUserLedgerPO::getCustomerName,param.getSearchValue()); + } + } + return pqUserLedgerMapper.selectList(userWrapper); + } + private List getLines(List lineIds){ + LambdaQueryWrapper lineQuery = new LambdaQueryWrapper<>(); + if (lineIds.size() > 1000) { + List> listLineIds = CollUtil.split(lineIds, 1000); + + lineQuery.and(w -> { + for (List ids : listLineIds) { + w.or(wIn -> wIn.in(PqLine::getLineIndex, ids)); + } + }); + } else { + lineQuery.in(PqLine::getLineIndex, lineIds); + } + return pqLineService.list(lineQuery); + } + + + private void buildResult(UserLedgerStatisticVO result,Map treeMap,Map> userMap,List assList,List eventdetailList, List lineList,List dicTreePOList){ + List innerList = new ArrayList<>(); + Map allTreeMap = dicTreePOList.stream().collect(Collectors.toMap(PqsDicTreePO::getId,dept->dept)); + + treeMap.forEach((tree, obj) -> { + //获取对象大类的用户 + List oneList = userMap.get(obj.getId()); + + if (tree.equals(DicTreeEnum.BJ_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setImportNum(count[0]); + result.setImportDevNum(count[1]); + } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setOtherImportNum(count[0]); + result.setOtherImportDevNum(count[1]); + } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setOtherNum(count[0]); + result.setOtherDevNum(count[1]); + } + + UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner(); + inner.setName(obj.getName()); + + inner.setCount(0); + + List childrenList = new ArrayList<>(); + if(CollUtil.isNotEmpty(oneList)) { + Map> smallMap = oneList.stream().collect(Collectors.groupingBy(PqUserLedgerPO::getSmallObjType)); + smallMap.forEach((key, userList) -> { + UserLedgerStatisticVO.Inner item = new UserLedgerStatisticVO.Inner(); + Integer[] count = getEventCount(userList, assList, eventdetailList, false); + item.setCount(count[0]); + item.setTreeId(key); + item.setParentId(obj.getId()); + item.setName(allTreeMap.containsKey(key) ? allTreeMap.get(key).getName() : "/"); + childrenList.add(item); + }); + inner.setChildren(childrenList); + innerList.add(inner); + } + }); + + result.setInnerList(innerList); + } + + + private void buildResultClone(UserLedgerStatisticVO result,Map treeMap,Map> userMap,List assList,List eventdetailList, List lineList,List dicTreePOList){ + List innerList = new ArrayList<>(); + Map allTreeMap = dicTreePOList.stream().collect(Collectors.toMap(PqsDicTreePO::getId,dept->dept)); + + treeMap.forEach((tree, obj) -> { + //获取对象大类的用户 + List oneList = userMap.get(obj.getId()); + + + if (tree.equals(DicTreeEnum.BJ_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setImportNum(oneList.size()); + result.setImportDevNum(count[1]); + } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setOtherImportNum(oneList.size()); + result.setOtherImportDevNum(count[1]); + } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) { + Integer[] count = getEventCount(oneList, assList, eventdetailList,true); + result.setOtherNum(oneList.size()); + result.setOtherDevNum(count[1]); + } + + UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner(); + inner.setName(obj.getName()); + + inner.setCount(0); + + List childrenList = new ArrayList<>(); + if(CollUtil.isNotEmpty(oneList)) { + Map> smallMap = oneList.stream().collect(Collectors.groupingBy(PqUserLedgerPO::getSmallObjType)); + smallMap.forEach((key, userList) -> { + UserLedgerStatisticVO.Inner item = new UserLedgerStatisticVO.Inner(); + Integer[] count = getEventCount(userList, assList, eventdetailList, false); + item.setCount(count[0]); + item.setTreeId(key); + item.setParentId(obj.getId()); + item.setName(allTreeMap.containsKey(key) ? allTreeMap.get(key).getName() : "/"); + childrenList.add(item); + }); + inner.setChildren(childrenList); + innerList.add(inner); + } + }); + + result.setInnerList(innerList); + } + + +/* @Override + public Page rightEventOpen(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)); + + // 1. 获取线路ID + List lineIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + + // 2. 获取用户线路关联 + List assList = getUserLineAssociations(lineIds); + if (CollUtil.isEmpty(assList)) { + return result; + } + + // 3. 获取用户台账 + List userLedgers = getFilteredUserLedgers(assList, param); + if (CollUtil.isEmpty(userLedgers)) { + return result; + } + + // 4. 获取事件数据 + List lineUseList = assList.stream() + .map(PqUserLineAssPO::getLineIndex) + .distinct() + .collect(Collectors.toList()); + + Page eventPage = getEventsPage(param, lineUseList); + if (CollUtil.isEmpty(eventPage.getRecords())) { + return result; + } + + // 5. 构建结果 + buildEventDetailResult(result, eventPage, assList, userLedgers); + + return result; + }*/ + + + + + @Override + public Page rightEventOpen(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)); + List deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if(CollUtil.isEmpty(deptLineIds)){ + return result; + } + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + PqSubstation pqSubstation = null; + if(Objects.nonNull(param.getBdId())){ + pqSubstation = pqSubstationMapper.selectOne(new LambdaQueryWrapper().eq(PqSubstation::getSubIndex,param.getBdId())); + if(Objects.isNull(pqSubstation)){ + return result; + } + queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex()); + + } + PqGdCompany pqGdCompany = null; + if(Objects.nonNull(param.getGdIndex())){ + pqGdCompany = pqGdCompanyMapper.selectOne(new LambdaQueryWrapper().eq(PqGdCompany::getGdIndex,param.getGdIndex())); + if(Objects.isNull(pqGdCompany)){ + return result; + } + queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex()); + } + + if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) { + + if(deptLineIds.size()>1000){ + List> assUserIdsList = CollUtil.split(deptLineIds, 1000); + queryWrapper.and(w -> { + for (List ids : assUserIdsList) { + w.or(wIn -> wIn.in(PqLine::getLineIndex, ids)); + } + }); + }else { + queryWrapper.in(PqLine::getLineIndex, deptLineIds); + } + + List pqLineList = pqLineService.list(queryWrapper); + deptLineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList()); + } + + if(CollUtil.isEmpty(deptLineIds)){ + return result; + } + + + + //获取用户监测点关系符合部门监测点的 + List assList = getUserLineAssociations(deptLineIds); + if(CollUtil.isEmpty(assList)){ + return result; + } + List userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + if(CollUtil.isEmpty(userIds)){ + return result; + } + //获取符合条件的用户 + List pqUserLedgerPOList =getUserLedgers(userIds,param,true); + + if(CollUtil.isEmpty(pqUserLedgerPOList)){ + return result; + } + Map pqMap = pqUserLedgerPOList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId,Function.identity())); + List pUserIds = pqUserLedgerPOList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + List assListLast = assList.stream().filter(it->pUserIds.contains(it.getUserIndex())).collect(Collectors.toList()); + List lineUseList = assListLast.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + + //查询时间段的暂降事件 + LambdaQueryWrapper eventQuery = new LambdaQueryWrapper<>(); + eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))) + .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType()).orderByDesc(PqsEventdetail::getTimeid) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()); + + if (lineUseList.size() > 1000) { + List> listLineIds = CollUtil.split(lineUseList, 1000); + eventQuery.and(w -> { + for (List ids : listLineIds) { + w.or(wIn -> wIn.in(PqsEventdetail::getLineid, ids)); + } + }); + } else { + eventQuery.in(PqsEventdetail::getLineid, lineUseList); + } + Page page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),eventQuery); + List temResultList = page.getRecords(); + if(CollUtil.isEmpty(temResultList)){ + return result; + } + + List ids = temResultList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List dtoList = pqLineService.getBaseLineInfo(ids); + Map lineMap = dtoList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId,Function.identity())); + Map> temMap = assListLast.stream().filter(it->ids.contains(it.getLineIndex())).collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserIndex,Collectors.toList()))); + + List resultList = new ArrayList<>(); + for(PqsEventdetail pqsEventdetail : temResultList){ + EventDetailVO eventDetailVO = new EventDetailVO(); + BeanUtil.copyProperties(pqsEventdetail,eventDetailVO); + List userTemIds = temMap.get(pqsEventdetail.getLineid()); + String objName = userTemIds.stream().map(it->pqMap.get(it).getCustomerName()).collect(Collectors.joining("; ")); + eventDetailVO.setObjName(objName); + LedgerBaseInfoDTO dto = lineMap.get(pqsEventdetail.getLineid()); + eventDetailVO.setBdname(dto.getStationName()); + eventDetailVO.setGdName(dto.getGdName()); + eventDetailVO.setBusName(dto.getBusBarName()); + eventDetailVO.setLineid(dto.getLineId()); + eventDetailVO.setPointname(dto.getLineName()); + eventDetailVO.setEventdetail_index(pqsEventdetail.getEventdetailIndex()); + eventDetailVO.setDevName(dto.getDevName()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(pqsEventdetail.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).toString()); + resultList.add(eventDetailVO); + } + result.setTotal(page.getTotal()); + result.setRecords(resultList); + return result; + } + + + @Override + public Page rightEventOpenForDetail(LargeScreenCountParam param) { + + Page result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)); + + //查询时间段的暂降事件 + LambdaQueryWrapper eventQuery = new LambdaQueryWrapper<>(); + eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))) + .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType()).orderByDesc(PqsEventdetail::getTimeid) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getEventdetailIndex,param.getEventIds()); + + Page page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),eventQuery); + List temResultList = page.getRecords(); + if(CollUtil.isEmpty(temResultList)){ + return result; + } + + List ids = temResultList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List dtoList = pqLineService.getBaseLineInfo(ids); + Map lineMap = dtoList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId,Function.identity())); + + //获取用户监测点关系符合部门监测点的 + List assList = getUserLineAssociations(ids); + if(CollUtil.isEmpty(assList)){ + return result; + } + List userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + if(CollUtil.isEmpty(userIds)){ + return result; + } + Map> temMap = assList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserIndex,Collectors.toList()))); + + //获取符合条件的用户 + List pqUserLedgerPOList =getUserLedgers(userIds,param,true); + + if(CollUtil.isEmpty(pqUserLedgerPOList)){ + return result; + } + Map pqMap = pqUserLedgerPOList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId,Function.identity())); + + List resultList = new ArrayList<>(); + for(PqsEventdetail pqsEventdetail : temResultList){ + EventDetailVO eventDetailVO = new EventDetailVO(); + BeanUtil.copyProperties(pqsEventdetail,eventDetailVO); + List userTemIds = temMap.get(pqsEventdetail.getLineid()); + String objName = userTemIds.stream().map(it->pqMap.get(it).getCustomerName()).collect(Collectors.joining("; ")); + eventDetailVO.setObjName(objName); + LedgerBaseInfoDTO dto = lineMap.get(pqsEventdetail.getLineid()); + eventDetailVO.setBdname(dto.getStationName()); + eventDetailVO.setGdName(dto.getGdName()); + eventDetailVO.setBusName(dto.getBusBarName()); + eventDetailVO.setLineid(dto.getLineId()); + eventDetailVO.setPointname(dto.getLineName()); + eventDetailVO.setEventdetail_index(pqsEventdetail.getEventdetailIndex()); + eventDetailVO.setDevName(dto.getDevName()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(pqsEventdetail.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).toString()); + resultList.add(eventDetailVO); + } + result.setTotal(page.getTotal()); + result.setRecords(resultList); + return result; + } + + @Override + public Page rightEventDevOpen(LargeScreenCountParam param) { + Page result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)); + List lineIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if(CollUtil.isEmpty(lineIds)){ + return result; + } + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + PqSubstation pqSubstation = null; + if(Objects.nonNull(param.getBdId())){ + pqSubstation = pqSubstationMapper.selectOne(new LambdaQueryWrapper().eq(PqSubstation::getSubIndex,param.getBdId())); + if(Objects.isNull(pqSubstation)){ + return result; + } + queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex()); + + } + PqGdCompany pqGdCompany = null; + if(Objects.nonNull(param.getGdIndex())){ + pqGdCompany = pqGdCompanyMapper.selectOne(new LambdaQueryWrapper().eq(PqGdCompany::getGdIndex,param.getGdIndex())); + if(Objects.isNull(pqGdCompany)){ + return result; + } + queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex()); + } + + if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) { + + if(lineIds.size()>1000){ + List> assUserIdsList = CollUtil.split(lineIds, 1000); + queryWrapper.and(w -> { + for (List ids : assUserIdsList) { + w.or(wIn -> wIn.in(PqLine::getLineIndex, ids)); + } + }); + }else { + queryWrapper.in(PqLine::getLineIndex, lineIds); + } + + List pqLineList = pqLineService.list(queryWrapper); + lineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList()); + } + + if(CollUtil.isEmpty(lineIds)){ + return result; + } + + List assPOList =getUserLineAssociations(lineIds); + if(CollUtil.isEmpty(assPOList)){ + return result; + } + + List userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + + if(userIds.size() > 1000){ + List> userIdList = CollUtil.split(userIds,1000); + lambdaQueryWrapper.and(ad->{ + for(List ids : userIdList){ + ad.or(o->o.in(PqUserLedgerPO::getId,ids)); + } + }); + }else { + lambdaQueryWrapper.in(PqUserLedgerPO::getId,userIds); + } + + if(StrUtil.isNotBlank(param.getBigObjType())){ + //对象大类不为空 + lambdaQueryWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType()); + } + if(StrUtil.isNotBlank(param.getSmallObjType())){ + //对象大类不为空 + lambdaQueryWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType()); + } + + if(Objects.nonNull(param.getGdIndex())){ + lambdaQueryWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex()); + } + + if(StrUtil.isNotBlank(param.getSearchValue())){ + lambdaQueryWrapper.eq(PqUserLedgerPO::getCustomerName,param.getSearchValue()); + } + + List userList = pqUserLedgerMapper.selectList(lambdaQueryWrapper); + if(CollUtil.isEmpty(userList)){ + return result; + } + List userTemIds = userList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + + List aassList = assPOList.stream().filter(it->userTemIds.contains(it.getUserIndex())).collect(Collectors.toList()); + List ids = aassList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + List eventdetailList = getEventsInTimeRange(param,ids); + if(CollUtil.isEmpty(eventdetailList)){ + return result; + } + List temLineIds = eventdetailList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List lastUserList = aassList.stream().filter(it->temLineIds.contains(it.getLineIndex())).map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + + Page page = pqUserLedgerMapper.selectPage(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),new LambdaQueryWrapper().in(PqUserLedgerPO::getId,lastUserList).orderByAsc(PqUserLedgerPO::getSmallObjType,PqUserLedgerPO::getUpdateTime)); + if(CollUtil.isEmpty(page.getRecords())){ + return page; + } + + List lastIds = page.getRecords().stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + List lastAssList = aassList.stream().filter(it->lastIds.contains(it.getUserIndex())).collect(Collectors.toList()); + + List monitorIds = lastAssList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + List pqLineList = pqLineService.list(new LambdaQueryWrapper().in(PqLine::getLineIndex,monitorIds)); + + List pqSubstationList = pqSubstationMapper.selectList(new LambdaQueryWrapper().in(PqSubstation::getSubIndex,pqLineList.stream().map(PqLine::getSubIndex).collect(Collectors.toList()))); + Map subMap = pqSubstationList.stream().collect(Collectors.toMap(PqSubstation::getSubIndex,sub->sub)); + pqLineList.forEach(it->it.setSubName(subMap.get(it.getSubIndex()).getName())); + + Map> objMap = lastAssList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getUserIndex,Collectors.mapping(PqUserLineAssPO::getLineIndex,Collectors.toList()))); + Map> lastMap = new HashMap<>(); + objMap.forEach((k,vList)->{ + lastMap.put(k,pqLineList.stream().filter(it->vList.contains(it.getLineIndex())).collect(Collectors.toList())); + }); + page.getRecords().forEach(item-> { + if(objMap.containsKey(item.getId())){ + List countObj = eventdetailList.stream().filter(it->objMap.get(item.getId()).contains(it.getLineid())).collect(Collectors.toList()); + item.setEventCount(countObj.size()); + item.setEventIds(countObj.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList())); + + if(param.getExportFlag()){ + item.setEventList(countObj); + if(lastMap.containsKey(item.getId())){ + List abList = lastMap.get(item.getId()); + Map lineMap= abList.stream().collect(Collectors.toMap(PqLine::getLineIndex,Function.identity())); + for(PqsEventdetail pqsEventdetail:countObj){ + if(lineMap.containsKey(pqsEventdetail.getLineid())){ + PqLine pqLine = lineMap.get(pqsEventdetail.getLineid()); + pqsEventdetail.setBusBarName(pqLine.getSubvName()); + pqsEventdetail.setStationName(pqLine.getSubName()); + } + + } + } + } + + } + if(lastMap.containsKey(item.getId())){ + List abList = lastMap.get(item.getId()); + item.setSubstationName(abList.stream().map(PqLine::getSubName).distinct().collect(Collectors.joining(StrUtil.COMMA))); + item.setInfo(abList.stream().map(items->items.getSubName()+"_"+items.getSubvName()).distinct().collect(Collectors.joining("; "))); + } + }); + return page; + } + + + + @Override + public List rightImportUser(LargeScreenCountParam param) { + List result = new ArrayList<>(); + List deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if(CollUtil.isEmpty(deptLineIds)){ + return result; + } + + List assPOList = getUserLineAssociations(deptLineIds); + if(CollUtil.isEmpty(assPOList)){ + return result; + } + List userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + + LambdaQueryWrapper userQuery = new LambdaQueryWrapper<>(); + if(userIds.size() > 1000){ + List> userIdList = CollUtil.split(userIds,1000); + userQuery.and(ad->{ + for(List ids : userIdList){ + ad.or(o->o.in(PqUserLedgerPO::getId,ids)); + } + }); + }else { + userQuery.in(PqUserLedgerPO::getId,userIds); + } + userQuery.eq(PqUserLedgerPO::getIsShow,1); + List poList = pqUserLedgerMapper.selectList(userQuery); + if(CollUtil.isEmpty(poList)){ + return result; + } + + List ids = poList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + List assTemList = assPOList.stream().filter(it->ids.contains(it.getUserIndex())).collect(Collectors.toList()); + + //获取监测id,用于查询暂降表 + List lineIds = assTemList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + + List eventList = pqsEventdetailService.lambdaQuery(). + in(PqsEventdetail::getLineid,lineIds) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .between(PqsEventdetail::getTimeid,DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))).list(); + if(CollUtil.isEmpty(eventList)){ + poList.forEach(item->{ + UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner(); + inner.setCustomId(item.getId()); + inner.setName(item.getCustomerName()); + inner.setCount(0); + result.add(inner); + }); + return result; + } + + Map> assMap = assTemList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getUserIndex,Collectors.mapping(PqUserLineAssPO::getLineIndex,Collectors.toList()))); + poList.forEach(item->{ + UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner(); + inner.setCustomId(item.getId()); + inner.setName(item.getCustomerName()); + List LIds = assMap.get(item.getId()); + List eventIds = eventList.stream().filter(it -> LIds.contains(it.getLineid())).map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + inner.setEventList(eventIds); + inner.setCount(eventIds.size()); + result.add(inner); + }); + return result; + } + + @Override + public PqUserLedgerPO rightImportOpenDetail(LargeScreenCountParam param) { + List deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId()); + if(CollUtil.isEmpty(deptLineIds)){ + return null; + } + + PqUserLedgerPO po = pqUserLedgerMapper.selectOne(new LambdaQueryWrapper().eq(PqUserLedgerPO::getId,param.getSearchValue())); + + PqsDicTreePO pqsDicTreePO = pqsDicTreeMapper.selectOne(new LambdaQueryWrapper().eq(PqsDicTreePO::getId,po.getSmallObjType())); + po.setSmallObjType(pqsDicTreePO.getName()); + List pqUserLineAssPOS = pqUserLineAssMapper.selectList(new LambdaQueryWrapper().eq(PqUserLineAssPO::getUserIndex,po.getId())); + List lastAss = pqUserLineAssPOS.stream().filter(it->deptLineIds.contains(it.getLineIndex())).collect(Collectors.toList()); + + List lineIds = lastAss.stream().map(PqUserLineAssPO::getLineIndex).collect(Collectors.toList()); + List ledgerBaseInfoDTOList = pqLineService.getBaseLedger(lineIds,null); + po.setGdName(ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getGdName).distinct().collect(Collectors.joining(";"))); + po.setSubstationName(ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getStationName).distinct().collect(Collectors.joining(";"))); + po.setBusbarName(ledgerBaseInfoDTOList.stream().map(it->it.getStationName()+"_"+it.getBusBarName()).distinct().collect(Collectors.joining(";"))); + + return po; + } + + @Override + public List gdSelect() { + return pqGdCompanyMapper.selectList(null); + } + + @Override + public List bdSelect() { + return pqSubstationMapper.selectList(null); + } + + private Integer[] getEventCount(List oneList, List assList, List pqsEventdetailList,boolean devFlag) { + Integer[] count = new Integer[]{0, 0}; + //用户的id + if(CollUtil.isNotEmpty(oneList)){ + List userIds = oneList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + //获取用户关联监测点 + List lineTemIds = assList.stream().filter(it -> userIds.contains(it.getUserIndex())).map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + //用户的暂降事件次数 + List eventdetailList = pqsEventdetailList.stream().filter(it -> lineTemIds.contains(it.getLineid())).collect(Collectors.toList()); + count[0] = eventdetailList.size(); + if(devFlag) { + List lastLineIds = eventdetailList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List userLastIds = assList.stream().filter(it->lastLineIds.contains(it.getLineIndex())).map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + long devCount = oneList.stream().filter(it->userLastIds.contains(it.getId())).count(); + count[1] = (int) devCount; + } + } + return count; + } + + @Override + public UserLedgerStatisticVO userLedgerStatisticClone(LargeScreenCountParam param) { + UserLedgerStatisticVO result = new UserLedgerStatisticVO(); + + // 1. 获取字典树数据 + List dicTreeList = getAllDicTrees(); + Map treeMap = getDicTreeMap(dicTreeList); + setResultIds(result, treeMap); + + // 2. 获取线路ID列表 + List lineIds = commGeneralService.getLineIdsByDept(param); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + + // 3. 获取用户线路关联数据 + List assList = getUserLineAssociations(lineIds); + if (CollUtil.isEmpty(assList)) { + return result; + } + + // 4. 获取用户台账信息 + Set assUserIds = assList.stream() + .map(PqUserLineAssPO::getUserIndex) + .collect(Collectors.toSet()); + List userLedgers = getUserLedgers(new ArrayList<>(assUserIds),null,false); + if (CollUtil.isEmpty(userLedgers)) { + return result; + } + + // 5. 获取事件和线路数据 + List events = getEventsInTimeRange(param, lineIds); + List lines = getLines(lineIds); + + // 6. 按用户类型分组处理 + Map> userMap = userLedgers.stream() + .collect(Collectors.groupingBy(PqUserLedgerPO::getBigObjType)); + + // 7. 构建结果 + buildResultClone(result, treeMap, userMap, assList, events, lines,dicTreeList); + + return result; + } + + @Override + public Page rightEventOpenClone(LargeScreenCountParam param) { + Page result = new Page<>(); + + // 2. 获取线路ID列表 + List lineIds = commGeneralService.getLineIdsByDept(param); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + PqSubstation pqSubstation = null; + if(Objects.nonNull(param.getBdId())){ + pqSubstation = pqSubstationMapper.selectOne(new LambdaQueryWrapper().eq(PqSubstation::getSubIndex,param.getBdId())); + if(Objects.isNull(pqSubstation)){ + return result; + } + queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex()); + + } + PqGdCompany pqGdCompany = null; + if(Objects.nonNull(param.getGdIndex())){ + pqGdCompany = pqGdCompanyMapper.selectOne(new LambdaQueryWrapper().eq(PqGdCompany::getGdIndex,param.getGdIndex())); + if(Objects.isNull(pqGdCompany)){ + return result; + } + queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex()); + } + + if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) { + List pqLineList = pqLineService.list(queryWrapper); + lineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList()); + } + + if(CollUtil.isEmpty(lineIds)){ + return result; + } + + // 3. 获取用户线路关联数据 + List assList = getUserLineAssociations(lineIds); + if (CollUtil.isEmpty(assList)) { + return result; + } + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.orderByAsc(PqUserLedgerPO::getSmallObjType,PqUserLedgerPO::getUpdateTime); + if(StrUtil.isNotBlank(param.getBigObjType())){ + //对象大类不为空 + lambdaQueryWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType()); + } + if(StrUtil.isNotBlank(param.getSmallObjType())){ + //对象大类不为空 + lambdaQueryWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType()); + } + if(Objects.nonNull(param.getGdIndex())){ + lambdaQueryWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex()); + } + if(StrUtil.isNotBlank(param.getSearchValue())){ + lambdaQueryWrapper.like(PqUserLedgerPO::getCustomerName,param.getSearchValue()); + } + List assIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + if(assIds.size()>1000){ + List> userIds = CollUtil.split(assIds, 1000); + lambdaQueryWrapper.and(w -> { + for (List ids : userIds) { + w.or(wIn -> wIn.in(PqUserLedgerPO::getId, ids)); + } + }); + }else { + lambdaQueryWrapper.in(PqUserLedgerPO::getId, assIds); + } + + Page page = pqUserLedgerMapper.selectPage(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),lambdaQueryWrapper); + if(CollUtil.isEmpty(page.getRecords())){ + return result; + } + List userIds = page.getRecords().stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + List assPOList = assList.stream().filter(it->userIds.contains(it.getUserIndex())).collect(Collectors.toList()); + List lineTemIds = assPOList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + + List ledgerList = pqLineService.getBaseLedger(lineTemIds,null); + + List pqsDeptslineList = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getLineIndex,lineTemIds).eq(PqsDeptsline::getSystype,sysTypeZt).list(); + Map deptLineMap = pqsDeptslineList.stream().collect(Collectors.toMap(PqsDeptsline::getLineIndex,dept->dept)); + + Map deptTemMap = new HashMap<>(); + List pqsDeptsList = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list(); + Map deptMap = pqsDeptsList.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex,dept->dept)); + deptLineMap.forEach((k,v)->{ + deptTemMap.put(k,deptMap.get(v.getDeptsIndex()).getDeptsname()); + }); + + + Map> assMap = assPOList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getUserIndex,Collectors.mapping(PqUserLineAssPO::getLineIndex,Collectors.toList()))); + + for(PqUserLedgerPO po :page.getRecords()){ + if(assMap.containsKey(po.getId())){ + List temIds = assMap.get(po.getId()); + List temList = ledgerList.stream().filter(it->temIds.contains(it.getLineId())).collect(Collectors.toList()); + po.setGdName(temList.stream().map(LedgerBaseInfoDTO::getGdName).distinct().collect(Collectors.joining(";"))); + po.setStation(temList.stream().map(LedgerBaseInfoDTO::getStationName).distinct().collect(Collectors.joining(";"))); + po.setInfo(temList.stream().map(it->it.getStationName()+"_"+it.getBusBarName()).distinct().collect(Collectors.joining(";"))); + po.setDeptName(temList.stream().map(LedgerBaseInfoDTO::getLineId).distinct().map(deptTemMap::get).distinct().collect(Collectors.joining(";"))); + } + + } + + return page; + } + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/LargeScreenCountServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/LargeScreenCountServiceImpl.java new file mode 100644 index 0000000..9bdcc63 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/LargeScreenCountServiceImpl.java @@ -0,0 +1,1539 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.*; +import cn.hutool.core.util.IdUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.njcn.common.pojo.enums.common.DataStateEnum; +import com.njcn.common.pojo.enums.response.CommonResponseEnum; +import com.njcn.common.pojo.exception.BusinessException; +import com.njcn.product.event.devcie.mapper.*; +import com.njcn.product.event.devcie.pojo.dto.*; +import com.njcn.product.event.devcie.pojo.po.*; +import com.njcn.product.event.transientes.mapper.*; +import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam; +import com.njcn.product.event.transientes.pojo.param.MessageEventFeedbackParam; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import com.njcn.product.event.transientes.pojo.po.MessageEventFeedback; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; +import com.njcn.product.event.transientes.pojo.po.*; +import com.njcn.product.event.transientes.pojo.vo.*; +import com.njcn.product.event.devcie.service.*; +import com.njcn.product.event.transientes.service.*; +import com.njcn.product.event.devcie.service.PqsDeptslineService; +import com.njcn.redis.utils.RedisUtil; +import com.njcn.web.factory.PageFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Description: + * Date: 2025/06/19 下午 3:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class LargeScreenCountServiceImpl implements LargeScreenCountService { + + private final PqsDeptslineService pqsDeptslineService; + private final PqsDeptsService pqsDeptsService; + private final PqLineService pqLineService; + private final PqSubstationService pqSubstationService; + private final PqDeviceService pqDeviceService; + private final PqsEventdetailService pqsEventdetailService; + private final PqLineMapper pqLineMapper; + private final MsgEventInfoService msgEventInfoService; + private final MessageEventFeedbackService messageEventFeedbackService; + private final CommGeneralService commGeneralService; + private final MsgEventConfigService msgEventConfigService; + private final PqsUsersetService pqsUsersetService; + private final PqsUserService pqsUserService; + private final PqLinedetailMapper pqLinedetailMapper; + private final RedisUtil redisUtil; + private final PqsOnlinerateService pqsOnlinerateService; + + private final PqsIntegrityMapper pqsIntegrityMapper; + + private final PqUserLedgerMapper pqUserLedgerMapper; + + private final PqUserLineAssMapper pqUserLineAssMapper; + + private final PqsStationMapMapper pqsStationMapMapper; + + private final PqsDicDataMapper pqsDicDataMapper; + + private final PqGdCompanyMapper pqGdCompanyMapper; + + private final PqSubstationMapper pqSubstationMapper; + + private final PqDeviceDetailMapper pqDeviceDetailMapper; + + @Value("${SYS_TYPE_ZT}") + private String sysTypeZt; + private final static String NAME_KEY = "LineCache:"; + + + private List lineIds = new ArrayList<>(); + + + @Override + public void initLedger(LargeScreenCountParam largeScreenCountParam) { + lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam); + } + + @Override + public LedgerCountVO scaleStatistics(LargeScreenCountParam largeScreenCountParam) { + LedgerCountVO ledgerCountVO = new LedgerCountVO(); + //根据用户获取当前部门及子部门id + //lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam); + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + } + List pqLineList = new ArrayList<>(); + if(lineIds.size()>1000){ + List> listIds = CollUtil.split(lineIds,1000); + for(List itemIds : listIds){ + List temp =pqLineService.lambdaQuery().in(PqLine::getLineIndex, itemIds).list(); + pqLineList.addAll(temp); + } + }else { + List temp = pqLineService.lambdaQuery().in(PqLine::getLineIndex, lineIds).list(); + pqLineList.addAll(temp); + } + //统计总数 + List allLineIds = pqLineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList()); + List allSubList = pqLineList.stream().map(PqLine::getSubIndex).distinct().collect(Collectors.toList()); + long allSubCount =allSubList.stream().count(); + List devList = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList()); + long allDevCount = devList.stream().count(); + + long allLineCount = pqLineList.stream().map(PqLine::getLineIndex).distinct().count(); + //在运总数 + List list = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devList).eq(PqDevice::getDevflag, 0).list(); + List runDevList = list.stream().map(PqDevice::getDevIndex).collect(Collectors.toList()); + long runDevCount = runDevList.stream().count(); + List runSubList = list.stream().map(PqDevice::getSubIndex).distinct().collect(Collectors.toList()); + long runSubCount = runSubList.stream().count(); + List ledgerBaseInfoDTOS = pqLineService.getBaseLineInfo(allLineIds); + List runLineList = ledgerBaseInfoDTOS.stream().filter(temp->Objects.equals(temp.getRunFlag(),1)).map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList()); + + long runLineCount = runLineList.stream().count(); + + + + ledgerCountVO.setAllSubCount(allSubCount); + ledgerCountVO.setAllDevCount(allDevCount); + ledgerCountVO.setAllLineCount(allLineCount); + ledgerCountVO.setRunDevCount(runDevCount); + ledgerCountVO.setRunSubCount(runSubCount); + ledgerCountVO.setRunLineCount(runLineCount); + + ledgerBaseInfoDTOS.stream().forEach(temp->temp.setRunFlag(runLineList.contains(temp.getLineId())?1:0)); + ledgerCountVO.setAllLineList(ledgerBaseInfoDTOS); + List deviceDTOS = pqDeviceService.queryListByIds(devList); + deviceDTOS =deviceDTOS.stream().distinct().collect(Collectors.toList()); + deviceDTOS.forEach(temp-> temp.setRunFlag(runDevList.contains(temp.getDevId())?1:0)); + ledgerCountVO.setAllDevList(deviceDTOS); + List substationDTOS = pqSubstationService.queryListByIds(allSubList); + substationDTOS.forEach(temp->temp.setRunFlag(runSubList.contains(temp.getStationId())?1:0)); + ledgerCountVO.setAllSubList(substationDTOS); + return ledgerCountVO; + } + + @Override + public AlarmAnalysisVO alarmAnalysis(LargeScreenCountParam largeScreenCountParam) { + AlarmAnalysisVO alarmAnalysisVO = new AlarmAnalysisVO(); + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + + //根据用户获取当前部门及子部门id + + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + + } + List eventdetails = new ArrayList<>(); + if(lineIds.size()>1000){ + List> listIds = CollUtil.split(lineIds,1000); + for(List itemIds : listIds){ + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid,startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,listIds) + .orderByDesc(PqsEventdetail::getTimeid).list() + ; + eventdetails.addAll(temp); + } + }else { + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,lineIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + + Integer eventCount = eventdetails.size(); + // 告警 + List aLarmEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() < 0.5).collect(Collectors.toList()); + // 预警 + List warnEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() >= 0.5&& temp.getEventvalue() <0.9).collect(Collectors.toList()); + List eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + //通知 + + List msgEventInfoList =msgEventInfoService.getMsgByIds(eventIds); + msgEventInfoList = msgEventInfoList.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime,Comparator.reverseOrder())).collect(Collectors.toList()); + + + + List lookALarmEvent = aLarmEvent.stream().filter(temp ->Objects.equals(temp.getLookFlag(),1 )).collect(Collectors.toList()); + List lookWarnEvent = warnEvent.stream().filter(temp ->Objects.equals(temp.getLookFlag(),1 ) ).collect(Collectors.toList()); + List handleMsg = msgEventInfoList.stream().filter(temp -> Objects.equals(temp.getIsHandle(), 1)).collect(Collectors.toList()); + + Integer aLarmCount =aLarmEvent.size(); + Integer warnCount =warnEvent.size(); + Integer noticeCount =msgEventInfoList.size(); + Integer lookALarmCount =lookALarmEvent.size(); + Integer lookWarnCount =lookWarnEvent.size(); + Integer lookNoticeCount =handleMsg.size(); + + alarmAnalysisVO.setEventCount(eventCount); + alarmAnalysisVO.setALarmCount(aLarmCount); + alarmAnalysisVO.setWarnCount(warnCount); + alarmAnalysisVO.setNoticeCount(noticeCount); + alarmAnalysisVO.setLookALarmCount(lookALarmCount); + alarmAnalysisVO.setLookWarnCount(lookWarnCount); + alarmAnalysisVO.setLookNoticeCount(lookNoticeCount); + +// +// alarmAnalysisVO.setEventdetails(change(eventdetails,msgEventInfoList)); +// alarmAnalysisVO.setALarmEvent(change(aLarmEvent,msgEventInfoList)); +// alarmAnalysisVO.setWarnEvent(change(warnEvent,msgEventInfoList)); +// alarmAnalysisVO.setNoticeEvent(msgEventInfoList); +// alarmAnalysisVO.setLookALarmEvent(change(lookALarmEvent,msgEventInfoList)); +// alarmAnalysisVO.setLookWarnEvent(change(lookWarnEvent,msgEventInfoList)); +// alarmAnalysisVO.setLookNoticeEvent(handleMsg); + + + + return alarmAnalysisVO; + } + + @Override + public List eventTrend(LargeScreenCountParam largeScreenCountParam) { + List eventTrendVOList = new ArrayList<>(); + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + // List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + //获取对应监测点id + //List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + //List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + + } + LocalDate startDate = LocalDate.parse(DateUtil.format(startTime, DatePattern.NORM_DATE_PATTERN)); + LocalDate endDate = LocalDate.parse(DateUtil.format(endTime, DatePattern.NORM_DATE_PATTERN)); + List eventdetails = new ArrayList<>(); + if(lineIds.size()>1000){ + List> listIds = CollUtil.split(lineIds,1000); + for(List itemIds : listIds){ + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,listIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + }else { + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,lineIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + + if (Objects.equals(largeScreenCountParam.getEventtype(), 1)) { + List eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + //通知 + List msgEventInfoList =msgEventInfoService.getMsgByIds(eventIds); + // 使用 for 循环处理日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + EventTrendVO eventTrendVO = new EventTrendVO(); + eventTrendVO.setLocalDate(date); + LocalDate finalDate = date; + List collect = msgEventInfoList.stream().filter(temp -> Objects.equals(DateUtil.format(temp.getSendTime(), DatePattern.NORM_DATE_PATTERN), DateUtil.format(finalDate.atStartOfDay(), DatePattern.NORM_DATE_PATTERN))).collect(Collectors.toList()); + eventTrendVO.setEventCount(collect.size()); + eventTrendVOList.add(eventTrendVO); + } + + + } else { + + // 使用 for 循环处理日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + EventTrendVO eventTrendVO = new EventTrendVO(); + eventTrendVO.setLocalDate(date); + LocalDate finalDate = date; + List collect = eventdetails.stream().filter(temp -> Objects.equals(DateUtil.format(temp.getTimeid(), DatePattern.NORM_DATE_PATTERN), DateUtil.format(finalDate.atStartOfDay(), DatePattern.NORM_DATE_PATTERN))).collect(Collectors.toList()); + eventTrendVO.setEventCount(collect.size()); + eventTrendVOList.add(eventTrendVO); + } + } + + + + return eventTrendVOList; + } + + @Override + public Page eventList(LargeScreenCountParam largeScreenCountParam) { + Page pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + //根据用户获取当前部门及子部门id + //List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + //获取对应监测点id + //List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + //List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).distinct().collect(Collectors.toList()); + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + + } + List pqLineList = pqLineService.getBaseLineInfo(lineIds); + Map ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (lineIds.size()>1000) { + List> idPartitions = CollUtil.split(lineIds,1000); + + queryWrapper.lambda() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .and(ew->{ + for(List pList: idPartitions){ + ew.or(w->w.in(PqsEventdetail::getLineid, pList)); + } + }).orderByDesc(PqsEventdetail::getTimeid); + + + } else { + queryWrapper.lambda() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getLineid, lineIds) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .orderByDesc(PqsEventdetail::getTimeid); + } + //查询需要发送短息处理的部门反推监测点 + + List noticeLineIds = new ArrayList<>(); + List pqsUserList = pqsUserService.lambdaQuery().eq(PqsUser::getState, 1).list(); + if(!CollectionUtils.isEmpty(pqsUserList)){ + List collect = pqsUserList.stream().map(PqsUser::getUserIndex).collect(Collectors.toList()); + List pqsUserSetList = pqsUsersetService.lambdaQuery().eq(PqsUserSet::getIsNotice, 1).in(PqsUserSet::getUserIndex,collect).list(); + List noticeDept = pqsUserSetList.stream().map(temp -> { + return pqsDeptsService.findDeptAndChildren(temp.getDeptsIndex()); + }).flatMap(Collection::stream).distinct().collect(Collectors.toList()); + //获取对应监测点id + if(!CollectionUtils.isEmpty(noticeDept)){ + List noticeLine = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, noticeDept).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + noticeLineIds = noticeLine.stream().map(PqsDeptsline::getLineIndex).distinct().collect(Collectors.toList()); + } + + } + + IPage list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage,queryWrapper); + List finalNoticeLineIds = noticeLineIds; + List collect = list.getRecords().stream().map(temp -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + eventDetailVO.setEventdetail_index(temp.getEventdetailIndex()); + eventDetailVO.setTimeid(temp.getTimeid()); + eventDetailVO.setMs(temp.getMs()); + eventDetailVO.setWavetype(temp.getWavetype().toString()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString()); + eventDetailVO.setEventvalue(temp.getEventvalue()); + eventDetailVO.setLookFlag(temp.getLookFlag()); + eventDetailVO.setNoticeFlag(temp.getNoticeFlag()); + if(ledgerBaseInfoDTOMap.containsKey(temp.getLineid())){ + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName()); + } + eventDetailVO.setNeedDealFlag(finalNoticeLineIds.contains(temp.getLineid())?1:0); + return eventDetailVO; + }).collect(Collectors.toList()); + Page returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + returnpage.setRecords(collect); + returnpage.setTotal(list.getTotal()); + return returnpage; + } + + @Override + public List noDealEventList(LargeScreenCountParam largeScreenCountParam) { + List result = new ArrayList<>(); + DateTime startTime = DateUtil.beginOfDay(DateUtil.parse(largeScreenCountParam.getSearchBeginTime())); + DateTime endTime = DateUtil.endOfDay(DateUtil.parse(largeScreenCountParam.getSearchEndTime())); + + List deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId()); + if (CollUtil.isEmpty(deptslineIds)) { + return result; + } + List allList = new ArrayList<>(); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + if(deptslineIds.size()>1000){ + List> idList = CollUtil.split(deptslineIds,1000); + for(List ids:idList){ + lambdaQueryWrapper.clear(); + lambdaQueryWrapper.between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .in(PqsEventdetail::getLineid, ids) + .and(wrapper -> wrapper.eq(PqsEventdetail::getLookFlag, 0).or().isNull(PqsEventdetail::getLookFlag)); + List eventList = pqsEventdetailService.list(lambdaQueryWrapper); + allList.addAll(eventList); + } + }else { + lambdaQueryWrapper.between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid, deptslineIds) + .and(wrapper -> wrapper.eq(PqsEventdetail::getLookFlag, 0).or().isNull(PqsEventdetail::getLookFlag)); + List eventList = pqsEventdetailService.list(lambdaQueryWrapper); + allList.addAll(eventList); + } + + + if (CollUtil.isNotEmpty(allList)) { + List ids = allList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List pqLineList = pqLineService.getBaseLineInfo(ids); + Map ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + Map userMap; + Map> assMap; + List assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper().in(PqUserLineAssPO::getLineIndex,ids)); + if (CollUtil.isNotEmpty(assList)) { + List userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + List poList = pqUserLedgerMapper.selectList(new LambdaQueryWrapper().in(PqUserLedgerPO::getId,userIds)); + userMap = poList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId,Function.identity())); + assMap = assList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex)); + }else { + userMap = new HashMap<>(); + assMap = new HashMap<>(); + } + + for(PqsEventdetail it : allList){ + EventDetailVO eventDetailVO = new EventDetailVO(); + eventDetailVO.setEventdetail_index(it.getEventdetailIndex()); + eventDetailVO.setTimeid(it.getTimeid()); + eventDetailVO.setMs(it.getMs()); + eventDetailVO.setWavetype(it.getWavetype().toString()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(it.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString()); + eventDetailVO.setEventvalue(it.getEventvalue()); + if (ledgerBaseInfoDTOMap.containsKey(it.getLineid())) { + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(it.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + } + if(assMap.containsKey(eventDetailVO.getLineid())) { + List temList = assMap.get(eventDetailVO.getLineid()).stream().map(PqUserLineAssPO::getUserIndex).collect(Collectors.toList()); + String str = temList.stream().map(its -> userMap.containsKey(its)?userMap.get(its).getCustomerName() + "; ":"/").collect(Collectors.joining()); + eventDetailVO.setObjName(str); + } + result.add(eventDetailVO); + } + } + result = result.stream().sorted(Comparator.comparing(EventDetailVO::getTimeid)).collect(Collectors.toList()); + return result; + } + + @Override + public boolean lookEvent(List ids) { + if(ids.size()>1000){ + List> eventIds = CollUtil.split(ids,1000); + for(List needIds : eventIds){ + LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); + updateWrapper.in(PqsEventdetail::getEventdetailIndex, needIds).set(PqsEventdetail::getLookFlag, DataStateEnum.ENABLE.getCode()); + pqsEventdetailService.update(updateWrapper); + } + }else { + LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); + updateWrapper.in(PqsEventdetail::getEventdetailIndex, ids).set(PqsEventdetail::getLookFlag, DataStateEnum.ENABLE.getCode()); + pqsEventdetailService.update(updateWrapper); + } + return true; + } + + @Override + public List mapCount(LargeScreenCountParam largeScreenCountParam) { + List result = new ArrayList<>(); + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + //根据用户获取当前部门及子部门id + List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + deptAndChildren.remove(largeScreenCountParam.getDeptId()); + //获取对应监测点id + List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + if (CollectionUtils.isEmpty(deptslines)) { + throw new BusinessException("部门下暂无监测点"); + } + + + List list = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list(); + Map stringPqsDeptsMap = list.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex, Function.identity(), (key1, key2) -> key2)); + Map> collect = deptslines.stream().collect(Collectors.groupingBy(PqsDeptsline::getDeptsIndex)); + + List ids = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + List ledgerBaseInfoDTOS = pqLineService.getBaseLineInfo(ids); + + collect.forEach((k, v) -> { + List temList = v.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + MapCountVO mapCountVO = new MapCountVO(); + mapCountVO.setDeptsIndex(k); + mapCountVO.setDeptsName(stringPqsDeptsMap.get(k).getDeptsname()); + + List temLedger = ledgerBaseInfoDTOS.stream().filter(it->temList.contains(it.getLineId())).collect(Collectors.toList()); + mapCountVO.setLineList(temLedger); + mapCountVO.setLineCount(temLedger.size()); + List deptslineIds = v.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + List eventdetails = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .in(PqsEventdetail::getLineid, deptslineIds).list(); + mapCountVO.setEventCount(eventdetails.size()); + + List eveIdndex = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + List temp = new ArrayList<>(); + if(!CollectionUtils.isEmpty(eveIdndex)){ + temp =msgEventInfoService.getMsgByIds(eveIdndex); + } + List change = change(eventdetails,temp); + + mapCountVO.setEventList(change); + mapCountVO.setNoticeCount(temp.size()); + mapCountVO.setNoticeList(temp); + result.add(mapCountVO); + }); + return result; + } + + @Override + public EventMsgDetailVO eventMsgDetail(String eventId) { + EventMsgDetailVO eventMsgDetailVO = new EventMsgDetailVO(); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(MessageEventFeedback::getEventIndex, eventId); + MessageEventFeedback messageEventFeedback = messageEventFeedbackService.getOne(lambdaQueryWrapper); + if (Objects.nonNull(messageEventFeedback)) { + BeanUtil.copyProperties(messageEventFeedback, eventMsgDetailVO); + if(messageEventFeedback.getIsSensitive() == 1){ + PqsEventdetail pqsEventdetail = pqsEventdetailService.lambdaQuery().eq(PqsEventdetail::getEventdetailIndex,eventId).one(); + PqLinedetail pqLinedetail = pqLinedetailMapper.selectById(pqsEventdetail.getLineid()); + eventMsgDetailVO.setObjName(pqLinedetail.getObjname()); + } + } + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(MsgEventInfo::getEventIndex, eventId); + List msgEventInfoList = msgEventInfoService.list(queryWrapper); + eventMsgDetailVO.setMsgList(msgEventInfoList); + + return eventMsgDetailVO; + } + + @Override + public List msgSendList(LargeScreenCountParam largeScreenCountParam) { + List result = new ArrayList<>(); + // List ids = commGeneralService.getLineIdsByDept(largeScreenCountParam); + if (CollUtil.isEmpty(lineIds)) { + return result; + } + List allEventList = new ArrayList<>(); + if (lineIds.size() > 1000) { + List> listIds = CollUtil.split(lineIds, 1000); + for (List itemIds : listIds) { + List pqsEventdetailList = pqsEventdetailService.lambdaQuery().in(PqsEventdetail::getLineid, itemIds).select(PqsEventdetail::getEventdetailIndex).list(); + allEventList.addAll(pqsEventdetailList); + } + } else { + List pqsEventdetailList = pqsEventdetailService.lambdaQuery().in(PqsEventdetail::getLineid, lineIds).select(PqsEventdetail::getEventdetailIndex).list(); + allEventList.addAll(pqsEventdetailList); + } + if (CollUtil.isEmpty(allEventList)) { + return result; + } + + List eventIds = allEventList.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + result =msgEventInfoService.getMsgByIds(eventIds); + result = result.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime, Comparator.reverseOrder())).collect(Collectors.toList()); + if (result.size() > 200) { + result = result.subList(0, 200); + } + return result; + } + + @Override + public Page hasSendMsgPage(LargeScreenCountParam largeScreenCountParam) { + DateTime start = DateUtil.beginOfDay(DateUtil.parse(largeScreenCountParam.getSearchBeginTime())); + DateTime end = DateUtil.endOfDay(DateUtil.parse(largeScreenCountParam.getSearchEndTime())); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(!StringUtils.isEmpty(largeScreenCountParam.getSendResult()),MsgEventInfo::getSendResult,largeScreenCountParam.getSendResult()); + lambdaQueryWrapper.orderByDesc(MsgEventInfo::getSendTime).between(MsgEventInfo::getSendTime,start,end); + return msgEventInfoService.page(new Page<>(PageFactory.getPageNum(largeScreenCountParam),PageFactory.getPageSize(largeScreenCountParam)),lambdaQueryWrapper); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean msgHandle(MessageEventFeedbackParam messageEventFeedbackParam) { + + PqsEventdetail pqsEventdetail = pqsEventdetailService.lambdaQuery().eq(PqsEventdetail::getEventdetailIndex,messageEventFeedbackParam.getEventIndex()).one(); + if(Objects.isNull(pqsEventdetail.getLookFlag())|| pqsEventdetail.getLookFlag() == 0){ + throw new BusinessException(CommonResponseEnum.FAIL,"当前事件暂未处理,请先处理!"); + } + + MessageEventFeedback messageEventFeedback = messageEventFeedbackService.lambdaQuery().eq(MessageEventFeedback::getEventIndex, messageEventFeedbackParam.getEventIndex()).one(); + if (Objects.nonNull(messageEventFeedback)) { + throw new BusinessException(CommonResponseEnum.FAIL,"请勿重复处理!"); + } + MessageEventFeedback po = new MessageEventFeedback(); + BeanUtil.copyProperties(messageEventFeedbackParam, po); + po.setId(IdUtil.simpleUUID()); + messageEventFeedbackService.save(po); + pqsEventdetailService.lambdaUpdate().set(PqsEventdetail::getNoticeFlag,DataStateEnum.ENABLE.getCode()).eq(PqsEventdetail::getEventdetailIndex,messageEventFeedbackParam.getEventIndex()).update(); + msgEventInfoService.lambdaUpdate().set(MsgEventInfo::getIsHandle,DataStateEnum.ENABLE.getCode()).eq(MsgEventInfo::getEventIndex,messageEventFeedbackParam.getEventIndex()).update(); + return true; + } + + @Override + public AlarmAnalysisVO alarmAnalysisDetail(LargeScreenCountParam largeScreenCountParam) { + AlarmAnalysisVO alarmAnalysisVO = new AlarmAnalysisVO(); + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + + //根据用户获取当前部门及子部门id + //List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + //获取对应监测点id + //List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + //List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + + } + List eventdetails = new ArrayList<>(); + if(lineIds.size()>1000){ + List> listIds = CollUtil.split(lineIds,1000); + for(List itemIds : listIds){ + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid,startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,listIds) + .orderByDesc(PqsEventdetail::getTimeid).list() + ; + eventdetails.addAll(temp); + } + }else { + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,lineIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + + Integer eventCount = eventdetails.size(); + // 告警 + List aLarmEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() < 0.5).collect(Collectors.toList()); + // 预警 + List warnEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() >= 0.5&& temp.getEventvalue() <0.9).collect(Collectors.toList()); + List eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()); + //通知 + List msgEventInfoList =msgEventInfoService.getMsgByIds(eventIds); + + msgEventInfoList = msgEventInfoList.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime,Comparator.reverseOrder())).collect(Collectors.toList()); + + + + List lookALarmEvent = aLarmEvent.stream().filter(temp ->Objects.equals(temp.getLookFlag(),1 )).collect(Collectors.toList()); + List lookWarnEvent = warnEvent.stream().filter(temp ->Objects.equals(temp.getLookFlag(),1 ) ).collect(Collectors.toList()); + List handleMsg = msgEventInfoList.stream().filter(temp -> Objects.equals(temp.getIsHandle(), 1)).collect(Collectors.toList()); + + Integer aLarmCount =aLarmEvent.size(); + Integer warnCount =warnEvent.size(); + Integer noticeCount =msgEventInfoList.size(); + Integer lookALarmCount =lookALarmEvent.size(); + Integer lookWarnCount =lookWarnEvent.size(); + Integer lookNoticeCount =handleMsg.size(); + + alarmAnalysisVO.setEventCount(eventCount); + alarmAnalysisVO.setALarmCount(aLarmCount); + alarmAnalysisVO.setWarnCount(warnCount); + alarmAnalysisVO.setNoticeCount(noticeCount); + alarmAnalysisVO.setLookALarmCount(lookALarmCount); + alarmAnalysisVO.setLookWarnCount(lookWarnCount); + alarmAnalysisVO.setLookNoticeCount(lookNoticeCount); + + + alarmAnalysisVO.setEventdetails(change(eventdetails,msgEventInfoList)); + alarmAnalysisVO.setALarmEvent(change(aLarmEvent,msgEventInfoList)); + alarmAnalysisVO.setWarnEvent(change(warnEvent,msgEventInfoList)); + alarmAnalysisVO.setNoticeEvent(msgEventInfoList); + alarmAnalysisVO.setLookALarmEvent(change(lookALarmEvent,msgEventInfoList)); + alarmAnalysisVO.setLookWarnEvent(change(lookWarnEvent,msgEventInfoList)); + alarmAnalysisVO.setLookNoticeEvent(handleMsg); + + + + return alarmAnalysisVO; + } + + @Override + public Page eventTablePage(LargeScreenCountParam largeScreenCountParam) { + Page result = new Page<>(PageFactory.getPageNum(largeScreenCountParam),PageFactory.getPageSize(largeScreenCountParam)); + //起始时间 + LocalDateTime startTime; + //结束时间 + LocalDateTime endTime; + if (largeScreenCountParam.getType() == 3) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else if (largeScreenCountParam.getType() == 4) { + //起始时间 + startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + //结束时间 + endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER); + } else { + throw new BusinessException("统计类型有误类型"); + } + + //List lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam); + if (CollectionUtils.isEmpty(lineIds)) { + throw new BusinessException("部门下暂无监测点"); + } + + + + List eventType = msgEventConfigService.getEventType(); + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper + .between(PqsEventdetail::getTimeid,startTime, endTime) + .in(PqsEventdetail::getWavetype,eventType) + .orderByDesc(PqsEventdetail::getTimeid); + if(Objects.nonNull(largeScreenCountParam.getEventDeep())){ + if (largeScreenCountParam.getEventDeep() == 0) { + lambdaQueryWrapper.ge(PqsEventdetail::getEventvalue, 0.5).lt(PqsEventdetail::getEventvalue, 0.9); + } else if (largeScreenCountParam.getEventDeep() == 1) { + lambdaQueryWrapper.lt(PqsEventdetail::getEventvalue, 0.5); + } + } + if(lineIds.size()>1000){ + List> splitList = CollUtil.split(lineIds,1000); + lambdaQueryWrapper.and(ew->{ + for (int i = 0; i < splitList.size(); i++) { + List batch = splitList.get(i); + if (i == 0) { + ew.in(PqsEventdetail::getLineid, batch); // 第一个条件不加 or + } else { + ew.or().in(PqsEventdetail::getLineid, batch); // 后续条件加 or + } + } + }); + }else { + lambdaQueryWrapper.in(PqsEventdetail::getLineid, lineIds); + } + Page page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(largeScreenCountParam),PageFactory.getPageSize(largeScreenCountParam)),lambdaQueryWrapper); + result.setTotal(page.getTotal()); + if(CollUtil.isEmpty(page.getRecords())){ + return result; + } + List ids = page.getRecords().stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List pqLineList = pqLineService.getBaseLineInfo(ids); + Map ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + List resultList = new ArrayList<>(); + for(PqsEventdetail pqsEventdetail : page.getRecords()){ + EventDetailVO eventDetailVO = new EventDetailVO(); + BeanUtil.copyProperties(pqsEventdetail,eventDetailVO); + if(ledgerBaseInfoDTOMap.containsKey(pqsEventdetail.getLineid())){ + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(pqsEventdetail.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName()); + } + resultList.add(eventDetailVO); + } + result.setRecords(resultList); + return result; + } + + @Override + public DeviceCountVO devFlagCount(LargeScreenCountParam largeScreenCountParam) { + DeviceCountVO deviceCountVO = new DeviceCountVO(); + List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + List deptslineIds = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+largeScreenCountParam.getDeptId()); + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList()); + List devIndexs = pqLineList.stream().map(PqLine::getDevIndex).collect(Collectors.toList()); + + //在运总数 + List list = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devIndexs).eq(PqDevice::getDevflag, 0).list(); + + long onLine = list.stream().filter(temp -> Objects.equals(temp.getStatus(), 1)).count(); + long Offline = list.stream().filter(temp -> Objects.equals(temp.getStatus(), 0)).count(); + deviceCountVO.setAllCount(list.size()); + // deviceCountVO.setOnLine((int) onLine); + // deviceCountVO.setOffLine((int) Offline); + + //临时调整 + deviceCountVO.setOnLine(list.size()); + deviceCountVO.setOffLine(0); + + return deviceCountVO; + } + + @Override + public List devDetail(LargeScreenCountParam largeScreenCountParam) { + DeviceCountVO deviceCountVO = new DeviceCountVO(); + List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + List deptslineIds = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+largeScreenCountParam.getDeptId()); + +// List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); +// List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); +// List deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList()); + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList()); + List devIndexs = pqLineList.stream().map(PqLine::getDevIndex).collect(Collectors.toList()); + + + List deviceDTOList = pqDeviceService.queryListByIds(devIndexs); + deviceDTOList = deviceDTOList.stream().filter(temp->Objects.equals(temp.getDevFlag(),0)).collect(Collectors.toList()); + return deviceDTOList; + } + + @Override + public List regionDevCount(LargeScreenCountParam largeScreenCountParam) { + List result = new ArrayList<>(); + List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + List deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId()); + if(deptAndChildren.size()>1){ + deptAndChildren.remove(largeScreenCountParam.getDeptId()); + } + List pqDeviceList = pqDeviceService.lambdaQuery().eq(PqDevice::getDevflag, 0).list(); + +// List deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list(); + List list = pqsDeptsService.getDeptList(deptAndChildren); + list.forEach(temp->{ + RegionDevCountVO regionDevCountVO = new RegionDevCountVO(); + regionDevCountVO.setDeptsIndex(temp.getDeptsIndex()); + regionDevCountVO.setDeptsname(temp.getDeptsname()); + regionDevCountVO.setAreaName(temp.getAreaName()); + List deptslineIds =(List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+temp.getDeptsIndex()); + List collect = pqLineList.stream().filter(pqLine -> deptslineIds.contains(pqLine.getLineIndex())).collect(Collectors.toList()); + List devIndexs = collect.stream().map(PqLine::getDevIndex).collect(Collectors.toList()); + List tempDeviceList = pqDeviceList.stream().filter(pqDevice -> devIndexs.contains(pqDevice.getDevIndex())).collect(Collectors.toList()); + //在运总数 + //TODO 零时调整 + //long onLine = tempDeviceList.stream().filter(pqDevice -> Objects.equals(pqDevice.getStatus(), 1)).count(); + //long Offline = tempDeviceList.stream().filter(pqDevice ->Objects.equals(pqDevice.getStatus(), 0)).count(); + regionDevCountVO.setAllCount(tempDeviceList.size()); + + regionDevCountVO.setOnLine((int) tempDeviceList.size()); + regionDevCountVO.setOffLine((int) 0); + result.add(regionDevCountVO); + }); + return result; + } + + private List getUserLineAssociations(List lineIds){ + LambdaQueryWrapper assQuery = new LambdaQueryWrapper<>(); + assQuery.in(PqUserLineAssPO::getLineIndex, lineIds); + + if(lineIds.size()>1000){ + List> lineList = CollUtil.split(lineIds, 1000); + assQuery.and(w -> { + for (List ids : lineList) { + w.or(wIn -> wIn.in(PqUserLineAssPO::getLineIndex, ids)); + } + }); + }else { + assQuery.in(PqUserLineAssPO::getLineIndex, lineIds); + } + + return pqUserLineAssMapper.selectList(assQuery); + } + + private List getUserLedgers(List assUserIds){ + LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); + if(assUserIds.size()>1000){ + List> assUserIdsList = CollUtil.split(assUserIds, 1000); + userWrapper.and(w -> { + for (List ids : assUserIdsList) { + w.or(wIn -> wIn.in(PqUserLedgerPO::getId, ids)); + } + }); + }else { + userWrapper.in(PqUserLedgerPO::getId, assUserIds); + } + return pqUserLedgerMapper.selectList(userWrapper); + } + @Override + public List substationCount(LargeScreenCountParam largeScreenCountParam) { + LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay(); + LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay()); + + List deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId()); + if(CollUtil.isEmpty(deptslineIds)){ + return new ArrayList<>(); + } + //查询暂态事件 + List eventdetails = new ArrayList<>(); + if(deptslineIds.size()>1000){ + List> listIds = CollUtil.split(deptslineIds,1000); + for(List itemIds : listIds){ + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid,startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,itemIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + }else { + List temp = pqsEventdetailService.lambdaQuery() + .between(PqsEventdetail::getTimeid, startTime, endTime) + .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .in(PqsEventdetail::getLineid,deptslineIds) + .orderByDesc(PqsEventdetail::getTimeid).list(); + eventdetails.addAll(temp); + } + + if(CollUtil.isEmpty(eventdetails)){ + return new ArrayList<>(); + } + + List lineIds = eventdetails.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + //List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + //pqLineList = pqLineList.stream().filter(temp->lineIds.contains(temp.getLineIndex())).collect(Collectors.toList()); + + List assPOList = getUserLineAssociations(lineIds); + List userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList()); + + Map> lineAssMap = assPOList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserIndex,Collectors.toList()))); + + List pqUserLedgerPOList = getUserLedgers(userIds); + + List subStationCountVOS = new ArrayList<>(); + List ledgerBaseInfoDTOS = pqLineService.getBaseLedger(lineIds,null); + //Map ledgerBaseInfoDTOMap = ledgerBaseInfoDTOS.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + List subIndexs = ledgerBaseInfoDTOS.stream().map(LedgerBaseInfoDTO::getStationId).collect(Collectors.toList()); + List pqsStationMapList = pqsStationMapMapper.selectList(new LambdaQueryWrapper().in(PqsStationMap::getSubIndex,subIndexs).eq(PqsStationMap::getState,1)); + Map stationMapMap = pqsStationMapList.stream().collect(Collectors.toMap(PqsStationMap::getSubIndex,dept->dept)); + + Map> substationDTOMap= ledgerBaseInfoDTOS.stream().collect(Collectors.groupingBy(LedgerBaseInfoDTO::getStationId)); + + Map> collect = eventdetails.stream().collect(Collectors.groupingBy(PqsEventdetail::getLineid)); + + substationDTOMap.forEach((k,v)->{ + LedgerBaseInfoDTO ledgerBaseInfoDTO = v.get(0); + SubStationCountVO subStationCountVO = new SubStationCountVO(); + subStationCountVO.setStationId(k); + subStationCountVO.setStationName(ledgerBaseInfoDTO.getStationName()); + subStationCountVO.setGdName(ledgerBaseInfoDTO.getGdName()); + + if(stationMapMap.containsKey(k.longValue())){ + PqsStationMap pqsStationMap = stationMapMap.get(k.longValue()); + if(Objects.nonNull(pqsStationMap.getLongItude())){ + subStationCountVO.setLongitude(pqsStationMap.getLongItude()); + }else { + subStationCountVO.setLongitude(0); + } + + if(Objects.nonNull(pqsStationMap.getLatItude())){ + subStationCountVO.setLatitude(pqsStationMap.getLatItude()); + }else { + subStationCountVO.setLatitude(0); + } + }else { + subStationCountVO.setLongitude(0); + subStationCountVO.setLatitude(0); + } + List tempLineIds = v.stream().map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList()); + subStationCountVO.setLineCount(tempLineIds.size()); + List tempEventList = eventdetails.stream().filter(temp -> tempLineIds.contains(temp.getLineid())).collect(Collectors.toList()); + subStationCountVO.setEventCount(tempEventList.size()); + v.forEach(item->{ + String obj = ""; + if(lineAssMap.containsKey(item.getLineId())){ + List userIndex = lineAssMap.get(item.getLineId()); + obj = pqUserLedgerPOList.stream().filter(it->userIndex.contains(it.getId())).map(PqUserLedgerPO::getCustomerName).collect(Collectors.joining(";")); + } + item.setObjName(StrUtil.isNotBlank(obj)? obj:"/"); + item.setEventCount(collect.get(item.getLineId()).size()); + }); + subStationCountVO.setLineEventDetails(v); + subStationCountVOS.add(subStationCountVO); + }); + return subStationCountVOS; + } + + @Override + public Page eventPage(LargeScreenCountParam largeScreenCountParam) { + Page pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay(); + LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay()); + + List deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId()); + + List ledgerList = new ArrayList<>(); + List pqUserLedgerPOList = new ArrayList<>(); + List assList = new ArrayList<>(); + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper + .between(PqsEventdetail::getTimeid, startTime, endTime) + .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration()) + .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue()) + .orderByDesc(PqsEventdetail::getTimeid); + + if(Objects.nonNull(largeScreenCountParam.getEventtype())){ + queryWrapper.eq(PqsEventdetail::getWavetype,largeScreenCountParam.getEventtype()); + }else { + queryWrapper.in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType()); + } + + if(Objects.nonNull(largeScreenCountParam.getEventDurationMin()) ||Objects.nonNull(largeScreenCountParam.getEventDurationMax())){ + queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventDurationMin()),PqsEventdetail::getPersisttime,largeScreenCountParam.getEventDurationMin()); + queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventDurationMax()),PqsEventdetail::getPersisttime,largeScreenCountParam.getEventDurationMax()); + } + + if(Objects.nonNull(largeScreenCountParam.getEventValueMin()) ||Objects.nonNull(largeScreenCountParam.getEventValueMax())){ + queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventValueMin()),PqsEventdetail::getEventvalue,largeScreenCountParam.getEventValueMin()); + queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventValueMax()),PqsEventdetail::getEventvalue,largeScreenCountParam.getEventValueMax()); + } + + if(StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())){ + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.select(PqUserLedgerPO::getId,PqUserLedgerPO::getCustomerName); + lambdaQueryWrapper.like(PqUserLedgerPO::getCustomerName,largeScreenCountParam.getSearchValue()); + List lineTemUserIds = new ArrayList<>(); + pqUserLedgerPOList = pqUserLedgerMapper.selectList(lambdaQueryWrapper); + if(CollUtil.isNotEmpty(pqUserLedgerPOList)) { + List userIds = pqUserLedgerPOList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList()); + assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper().in(PqUserLineAssPO::getUserIndex, userIds)); + List assIds = assList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList()); + lineTemUserIds = deptslineIds.stream().filter(assIds::contains).collect(Collectors.toList()); + } + + ledgerList = pqLineService.getBaseLedger(deptslineIds,largeScreenCountParam.getSearchValue()); + lineTemUserIds.addAll(ledgerList.stream().map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList())); + if(CollUtil.isEmpty(lineTemUserIds)){ + return new Page<>(); + } + if (lineTemUserIds.size()>1000) { + List> idPartitions = CollUtil.split(lineTemUserIds,1000); + queryWrapper.and(ew->{ + for(List pList: idPartitions){ + ew.or(w->w.in(PqsEventdetail::getLineid, pList)); + } + }); + } else { + queryWrapper.in(PqsEventdetail::getLineid, lineTemUserIds); + } + + }else { + if (deptslineIds.size()>1000) { + List> idPartitions = CollUtil.split(deptslineIds,1000); + queryWrapper.and(ew->{ + for(List pList: idPartitions){ + ew.or(w->w.in(PqsEventdetail::getLineid, pList)); + } + }); + } else { + queryWrapper.in(PqsEventdetail::getLineid, deptslineIds); + } + } + + IPage list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage,queryWrapper); + if(CollUtil.isEmpty(list.getRecords())){ + return new Page<>(); + } + List pageLineIds = list.getRecords().stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + List pageLedger = pqLineService.getBaseLedger(pageLineIds,null); + Map ledgerBaseInfoDTOMap = pageLedger.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + List assLastList = pqUserLedgerMapper.getUserByParam(pageLineIds,null); + Map> mapObj = assLastList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserName,Collectors.toList()))); + + List collect = list.getRecords().stream().map(temp -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + eventDetailVO.setEventdetail_index(temp.getEventdetailIndex()); + eventDetailVO.setTimeid(temp.getTimeid()); + eventDetailVO.setMs(temp.getMs()); + eventDetailVO.setWavetype(temp.getWavetype().toString()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString()); + eventDetailVO.setEventvalue(temp.getEventvalue()); + eventDetailVO.setLookFlag(temp.getLookFlag()); + eventDetailVO.setNoticeFlag(temp.getNoticeFlag()); + if(ledgerBaseInfoDTOMap.containsKey(temp.getLineid())){ + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName()); + } + String objName ="/"; + if(mapObj.containsKey(eventDetailVO.getLineid())){ + objName = String.join(";", mapObj.get(eventDetailVO.getLineid())); + } + eventDetailVO.setObjName(objName); + return eventDetailVO; + }).collect(Collectors.toList()); + Page returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + returnpage.setRecords(collect); + returnpage.setTotal(list.getTotal()); + return returnpage; + } + @Override + public Page devicePage(LargeScreenCountParam largeScreenCountParam) { + TimeInterval timeInterval = new TimeInterval(); + log.info("开始查询:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay(); + LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay()); + Page pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + + + List deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId()); + + + if(Objects.isNull(largeScreenCountParam.getGdIndex())){ + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList()); + }else { + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex()) && Objects.equals(temp.getGdIndex(),largeScreenCountParam.getGdIndex())).collect(Collectors.toList()); + } + if(CollUtil.isEmpty(pqLineList)){ + return new Page<>(); + } + + List devIndexs = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList()); + log.info("完成从redis获取信息:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + //在运总数 + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + if(StrUtil.isNotBlank(largeScreenCountParam.getState())){ + + if(largeScreenCountParam.getState().equals("0")){ + return new Page<>(); + } + } + if(StrUtil.isNotBlank(largeScreenCountParam.getDevName())){ + lambdaQueryWrapper.like(StrUtil.isNotEmpty(largeScreenCountParam.getDevName()),PqDevice::getName,largeScreenCountParam.getDevName()); + } + lambdaQueryWrapper.in(PqDevice::getDevIndex, devIndexs); + + List pqDeviceList = pqDeviceService.list(lambdaQueryWrapper); + + log.info("完成设备查询sql:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + List runDevList = pqDeviceList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList()); + if(CollUtil.isEmpty(runDevList)){ + return new Page<>(); + } + + List pqsDicDataList = pqsDicDataMapper.selectList(new LambdaQueryWrapper().eq(PqsDicData::getDicType,"cbb2de8a-87da-4ae9-a35c-aaab999c7bc7")); + Map pqsDicDataMap = pqsDicDataList.stream().collect(Collectors.toMap(PqsDicData::getDicIndex,Function.identity())); + + List bdList = new ArrayList<>(); + if(StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())){ + List substationList = pqSubstationMapper.selectList(new LambdaQueryWrapper().like(PqSubstation::getName,largeScreenCountParam.getSearchValue())); + bdList = substationList.stream().map(PqSubstation::getSubIndex).collect(Collectors.toList()); + } + + Page page = pqDeviceService.lambdaQuery().in(CollUtil.isNotEmpty(bdList),PqDevice::getSubIndex,bdList) + .in(PqDevice::getDevIndex,runDevList).page(new Page<>(PageFactory.getPageNum(largeScreenCountParam),PageFactory.getPageSize(largeScreenCountParam))); + log.info("完成设备部门查询:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + // pqsEventdetailPage = pqDeviceService.selectDeviceDTOPage(pqsEventdetailPage,largeScreenCountParam.getSearchValue(),runDevList); + log.info("完成设备分页查询sql:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + + List deviceDTOList = page.getRecords(); + if(!CollectionUtils.isEmpty(deviceDTOList)){ + + //临时处理 + deviceDTOList.forEach(it->it.setStatus(1)); + + List devIds = deviceDTOList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList()); + log.info("在线率查询sql开始:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + List onlineList = pqsOnlinerateService.lambdaQuery().in(PqsOnlinerate::getDevIndex,devIds).between(PqsOnlinerate::getTimeid, startTime, endTime).list(); + log.info("在线率查询sql结束:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + + List inteList = pqLineList.stream().filter(it->devIds.contains(it.getDevIndex())).collect(Collectors.toList()); + Map> lineMap = inteList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex,Collectors.mapping(PqLine::getLineIndex,Collectors.toList()))); + List inteIds = inteList.stream().map(PqLine::getLineIndex).collect(Collectors.toList()); + + Map inteDevMap = new HashMap<>(); + log.info("完整性查询sql开始:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + List pqsIntegrityList = pqsIntegrityMapper.selectList(new LambdaQueryWrapper().in(PqsIntegrity::getLineIndex,inteIds).between(PqsIntegrity::getTimeID, startTime, endTime)); + log.info("完整性查询sql结束:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + lineMap.forEach((dev,lineList)->{ + double rate = pqsIntegrityList.stream().filter(it->lineList.contains(it.getLineIndex())).mapToDouble(it->it.getReal()*1.0/(it.getDue())).average().orElse(0.0); + inteDevMap.put(dev,rate); + }); + + List deviceDetailList = pqDeviceDetailMapper.selectList(new LambdaQueryWrapper().in(PqDeviceDetail::getDevIndex,devIds)); + Map devMap = deviceDetailList.stream().collect(Collectors.toMap(PqDeviceDetail::getDevIndex,Function.identity())); + + List gdIds = deviceDTOList.stream().map(PqDevice::getGdIndex).collect(Collectors.toList()); + List pqGdCompanyList = pqGdCompanyMapper.selectList(new LambdaQueryWrapper().in(PqGdCompany::getGdIndex,gdIds)); + Map gdMap = pqGdCompanyList.stream().collect(Collectors.toMap(PqGdCompany::getGdIndex,Function.identity())); + + List bdIds = deviceDTOList.stream().map(PqDevice::getSubIndex).collect(Collectors.toList()); + List substationList = pqSubstationMapper.selectList(new LambdaQueryWrapper().in(PqSubstation::getSubIndex,bdIds)); + Map bdMap = substationList.stream().collect(Collectors.toMap(PqSubstation::getSubIndex,Function.identity())); + + List lineList = pqLineList.stream().filter(it->devIds.contains(it.getDevIndex())).collect(Collectors.toList()); + List deptslineList = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getLineIndex,lineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList())).eq(PqsDeptsline::getSystype,sysTypeZt).list(); + + Map pqsDeptsMap = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list().stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex,Function.identity())); + + Map map = deptslineList.stream().collect(Collectors.toMap(PqsDeptsline::getLineIndex,Function.identity())); + Map temMap = new HashMap<>(); + map.forEach((lineId,deptline)->{ + String deptName = pqsDeptsMap.get(deptline.getDeptsIndex()).getDeptsname(); + temMap.put(lineId,deptName); + }); + + lineList.forEach(it->it.setDeptName(temMap.get(it.getLineIndex()))); + Map> pqLineMap = lineList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex)); + + List result = new ArrayList<>(); + for(PqDevice pqDevice : deviceDTOList){ + DeviceDTO dto = new DeviceDTO(); + dto.setDevId(pqDevice.getDevIndex()); + dto.setDevName(pqDevice.getName()); + dto.setIp(pqDevice.getIp()); + List tempList = onlineList.stream().filter(temp -> Objects.equals(temp.getDevIndex(), pqDevice.getDevIndex())).collect(Collectors.toList()); + if(!CollectionUtils.isEmpty(tempList)){ + double asDouble = tempList.stream().mapToDouble(temp -> (double) (temp.getOnlinemin() * 100) / (temp.getOfflinemin() + temp.getOnlinemin())).average().getAsDouble(); + dto.setOnLineRate(new BigDecimal(asDouble).setScale(2, RoundingMode.UP).doubleValue()); + } + dto.setIntegrityRate(inteDevMap.containsKey(pqDevice.getDevIndex())? BigDecimal.valueOf(inteDevMap.get(pqDevice.getDevIndex()) * 100).setScale(2,RoundingMode.UP).doubleValue():0); + + PqDeviceDetail pqDeviceDetail = devMap.get(pqDevice.getDevIndex().longValue()); + dto.setManufacturerName(pqDeviceDetail.getManufacturer()); + dto.setStatus(pqDevice.getStatus()); + dto.setRunFlag(pqDevice.getStatus()); + dto.setThisTimeCheck(pqDeviceDetail.getThisTimeCheck()); + dto.setNextTimeCheck(pqDeviceDetail.getNextTimeCheck()); + dto.setUpdateTime(pqDevice.getUpdatetime()); + dto.setGdName(gdMap.get(pqDevice.getGdIndex().longValue()).getName()); + dto.setStationName(bdMap.get(pqDevice.getSubIndex()).getName()); + dto.setLogonTime(pqDevice.getLogontime()); + dto.setDeptName(pqLineMap.get(pqDevice.getDevIndex()).get(0).getDeptName()); + + if(pqsDicDataMap.containsKey(pqDeviceDetail.getManufacturer())){ + dto.setManufacturerName(pqsDicDataMap.get(pqDeviceDetail.getManufacturer()).getDicName()); + } + result.add(dto); + + } + pqsEventdetailPage.setRecords(result); + pqsEventdetailPage.setTotal(page.getTotal()); + } + log.info("所有程序结束:"+timeInterval.intervalMs()+"ms; "+timeInterval.intervalSecond()+"s"); + + return pqsEventdetailPage; + } + /* @Override + public Page devicePage(LargeScreenCountParam largeScreenCountParam) { + LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay(); + LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay()); + Page pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + List pqLineList = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList"); + List deptslineIds = (List) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+largeScreenCountParam.getDeptId()); + + + if(Objects.isNull(largeScreenCountParam.getGdIndex())){ + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList()); + }else { + pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex()) && Objects.equals(temp.getGdIndex(),largeScreenCountParam.getGdIndex())).collect(Collectors.toList()); + } + if(CollUtil.isEmpty(pqLineList)){ + return new Page<>(); + } + + List devIndexs = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList()); + //在运总数 + List pqDeviceList = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devIndexs).eq(PqDevice::getDevflag, 0).list(); + List runDevList = pqDeviceList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList()); + + pqsEventdetailPage = pqDeviceService.selectDeviceDTOPage(pqsEventdetailPage,largeScreenCountParam.getSearchValue(),runDevList,largeScreenCountParam.getState()); + List deviceDTOList = pqsEventdetailPage.getRecords(); + if(!CollectionUtils.isEmpty(deviceDTOList)){ + List devIds = deviceDTOList.stream().map(DeviceDTO::getDevId).collect(Collectors.toList()); + List list = pqsOnlinerateService.lambdaQuery().in(PqsOnlinerate::getDevIndex,devIds).between(PqsOnlinerate::getTimeid, startTime, endTime).list(); + + List inteList = pqLineList.stream().filter(it->devIds.contains(it.getDevIndex())).collect(Collectors.toList()); + Map> lineMap = inteList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex,Collectors.mapping(PqLine::getLineIndex,Collectors.toList()))); + List inteIds = inteList.stream().map(PqLine::getLineIndex).collect(Collectors.toList()); + + Map inteDevMap = new HashMap<>(); + List pqsIntegrityList = pqsIntegrityMapper.selectList(new LambdaQueryWrapper().in(PqsIntegrity::getLineIndex,inteIds)); + lineMap.forEach((dev,lineList)->{ + double rate = pqsIntegrityList.stream().filter(it->lineList.contains(it.getLineIndex())).mapToDouble(it->it.getReal()*1.0/(it.getDue()+it.getReal())).average().orElse(0.0); + inteDevMap.put(dev,rate); + }); + + + for (DeviceDTO record : pqsEventdetailPage.getRecords()) { + List tempList = list.stream().filter(temp -> Objects.equals(temp.getDevIndex(), record.getDevId())).collect(Collectors.toList()); + if(!CollectionUtils.isEmpty(tempList)){ + double asDouble = tempList.stream().mapToDouble(temp -> { + return Double.valueOf(temp.getOnlinemin()*100) / (temp.getOfflinemin() + temp.getOnlinemin()); + }).average().getAsDouble(); + record.setOnLineRate(new BigDecimal(asDouble).setScale(2, RoundingMode.UP).doubleValue()); + record.setIntegrityRate(inteDevMap.containsKey(record.getDevId())? new BigDecimal(inteDevMap.get(record.getDevId())*100).setScale(2,RoundingMode.UP).doubleValue():0); + } + + } + } + + + return pqsEventdetailPage; + }*/ + + @Override + public Page userEventList(LargeScreenCountParam largeScreenCountParam) { + Page pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + + List eventIds = largeScreenCountParam.getEventIds(); + if (CollectionUtils.isEmpty(eventIds)){ + return new Page<>(); + } + + + QueryWrapper queryWrapper = new QueryWrapper<>(); + if (eventIds.size()>1000) { + List> idPartitions = CollUtil.split(eventIds,1000); + + queryWrapper.lambda() + .and(ew->{ + for(List pList: idPartitions){ + ew.or(w->w.in(PqsEventdetail::getEventdetailIndex, pList)); + } + }).orderByDesc(PqsEventdetail::getTimeid); + + + } else { + queryWrapper.lambda() + .in(PqsEventdetail::getEventdetailIndex, eventIds) + .orderByDesc(PqsEventdetail::getTimeid); + } + IPage list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage,queryWrapper); + List indexIds = list.getRecords().stream().map(PqsEventdetail::getLineid).collect(Collectors.toList()); + List pqLineList = pqLineService.getBaseLineInfo(indexIds); + Map ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + List collect = list.getRecords().stream().map(temp -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + eventDetailVO.setEventdetail_index(temp.getEventdetailIndex()); + eventDetailVO.setTimeid(temp.getTimeid()); + eventDetailVO.setMs(temp.getMs()); + eventDetailVO.setWavetype(temp.getWavetype().toString()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString()); + eventDetailVO.setEventvalue(temp.getEventvalue()); + eventDetailVO.setLookFlag(temp.getLookFlag()); + eventDetailVO.setNoticeFlag(temp.getNoticeFlag()); + if(ledgerBaseInfoDTOMap.containsKey(temp.getLineid())){ + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName()); + } + return eventDetailVO; + }).collect(Collectors.toList()); + Page returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize()); + returnpage.setRecords(collect); + returnpage.setTotal(list.getTotal()); + return returnpage; + } + + private List change(List list,List handleMsg){ + List result = new ArrayList<>(); + if(CollectionUtils.isEmpty(list)){ + return result; + } + List lineidList = list.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList()); + + + List pqLineList = pqLineService.getBaseLineInfo(lineidList); + Map ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity())); + + result = list.stream().map(temp -> { + EventDetailVO eventDetailVO = new EventDetailVO(); + eventDetailVO.setEventdetail_index(temp.getEventdetailIndex()); + eventDetailVO.setTimeid(temp.getTimeid()); + eventDetailVO.setMs(temp.getMs()); + eventDetailVO.setWavetype(temp.getWavetype().toString()); + eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString()); + eventDetailVO.setEventvalue(temp.getEventvalue()); + eventDetailVO.setLookFlag(temp.getLookFlag()); + eventDetailVO.setNoticeFlag(temp.getNoticeFlag()); + if( temp.getEventvalue()< 0.5){ + eventDetailVO.setEventSeverity(1); + }else{ + eventDetailVO.setEventSeverity(2); + } + eventDetailVO.setMsgEventInfoSize(handleMsg.stream().filter(msg->Objects.equals(msg.getEventIndex(),temp.getEventdetailIndex())).count()); + if(ledgerBaseInfoDTOMap.containsKey(temp.getLineid())){ + LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid()); + eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId()); + eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName()); + eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName()); + eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName()); + eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName()); + eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName()); + } + return eventDetailVO; + }).collect(Collectors.toList()); + + return result; + } + + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MessageEventFeedbackServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MessageEventFeedbackServiceImpl.java new file mode 100644 index 0000000..62ef8b4 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MessageEventFeedbackServiceImpl.java @@ -0,0 +1,16 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.MessageEventFeedbackMapper; +import com.njcn.product.event.transientes.pojo.po.MessageEventFeedback; +import com.njcn.product.event.transientes.service.MessageEventFeedbackService; +import org.springframework.stereotype.Service; + +/** + * @Author: cdf + * @CreateTime: 2025-06-26 + * @Description: + */ +@Service +public class MessageEventFeedbackServiceImpl extends ServiceImpl implements MessageEventFeedbackService { +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventConfigServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventConfigServiceImpl.java new file mode 100644 index 0000000..c6b4531 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventConfigServiceImpl.java @@ -0,0 +1,104 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.MsgEventConfigMapper; +import com.njcn.product.event.transientes.pojo.po.MsgEventConfig; +import com.njcn.product.event.transientes.service.MsgEventConfigService; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import javax.annotation.PostConstruct; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +/** + * @Author: cdf + * @CreateTime: 2025-06-27 + * @Description: + */ +@Service +@Lazy(false) // 确保服务在启动时立即初始化 +public class MsgEventConfigServiceImpl extends ServiceImpl implements MsgEventConfigService { + + /** + * 暂降类型 + */ + public List eventType = Stream.of("1","3").collect(Collectors.toList()); + + /** + * 暂降残余电压阈值 只查询小于0.7的暂降事件 + */ + public Float eventValue = 0.7f; + + /** + * 暂降残余电压阈值 只查询大于50ms的暂降事件 + */ + public Integer eventDuration = 50; + + + + @Transactional(rollbackFor = Exception.class) + @Override + public boolean eventConfig(MsgEventConfig msgEventConfig) { + this.remove(new LambdaQueryWrapper<>()); + msgEventConfig.setId(IdUtil.simpleUUID()); + String tem = String.join(StrUtil.COMMA, msgEventConfig.getEventTypeList()); + msgEventConfig.setEventType(tem); + this.save(msgEventConfig); + eventType = msgEventConfig.getEventTypeList(); + eventValue = msgEventConfig.getEventValue(); + eventDuration= msgEventConfig.getEventDuration(); + return true; + } + + @Override + public MsgEventConfig queryConfig() { + MsgEventConfig msgEventConfig = this.getOne(new LambdaQueryWrapper<>()); + msgEventConfig.setEventTypeList(Arrays.asList(msgEventConfig.getEventType().split(StrUtil.COMMA))); + return msgEventConfig; + } + + + @PostConstruct + public void init() { + System.out.println("------------------------------------------------------------------------------"); + MsgEventConfig config = this.getOne(new LambdaQueryWrapper<>()); + if(Objects.nonNull(config)){ + if (StrUtil.isNotBlank(config.getEventType())) { + eventType = Arrays.asList(config.getEventType().split(StrUtil.COMMA)); + } + if(Objects.nonNull(config.getEventValue())){ + eventValue = config.getEventValue(); + } + if(Objects.nonNull(config.getEventDuration())){ + eventDuration = config.getEventDuration(); + } + } + System.out.println(config); + } + + + @Override + public List getEventType() { + return eventType; + } + + @Override + public Float getEventValue() { + return eventValue; + } + + @Override + public Integer getEventDuration() { + return eventDuration; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventInfoServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventInfoServiceImpl.java new file mode 100644 index 0000000..579bd56 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/MsgEventInfoServiceImpl.java @@ -0,0 +1,39 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.collection.CollUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.MsgEventInfoMapper; +import com.njcn.product.event.transientes.pojo.po.MsgEventInfo; +import com.njcn.product.event.transientes.service.MsgEventInfoService; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-06-25 + * @Description: + */ +@Service +public class MsgEventInfoServiceImpl extends ServiceImpl implements MsgEventInfoService { + @Override + public List getMsgByIds(List ids) { + //通知 + List msgEventInfoList = new ArrayList<>(); + if(!CollectionUtils.isEmpty(ids)){ + if(ids.size()>1000){ + List> listEven = CollUtil.split(ids,1000); + for(List pList: listEven){ + List temp = this.lambdaQuery().in(MsgEventInfo::getEventIndex,pList).list(); + msgEventInfoList.addAll(temp); + } + }else { + List temp = this.lambdaQuery().in(MsgEventInfo::getEventIndex,ids).list(); + msgEventInfoList.addAll(temp); + } + } + return msgEventInfoList; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqDevicedetailServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqDevicedetailServiceImpl.java new file mode 100644 index 0000000..ee3e5f7 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqDevicedetailServiceImpl.java @@ -0,0 +1,19 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.njcn.product.event.devcie.pojo.po.PqDeviceDetail; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqDevicedetailMapper; +import com.njcn.product.event.transientes.service.PqDevicedetailService; +/** + * + * Description: + * Date: 2025/06/19 下午 1:47【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqDevicedetailServiceImpl extends ServiceImpl implements PqDevicedetailService{ + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqUserLedgerServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqUserLedgerServiceImpl.java new file mode 100644 index 0000000..20aba8b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqUserLedgerServiceImpl.java @@ -0,0 +1,65 @@ +package com.njcn.product.event.transientes.service.impl; + +import cn.hutool.core.bean.BeanUtil; +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.product.event.transientes.mapper.PqUserLedgerMapper; +import com.njcn.product.event.transientes.pojo.param.PqUserLedgerParam; +import com.njcn.product.event.transientes.pojo.po.PqUserLedgerPO; +import com.njcn.product.event.transientes.service.PqUserLedgerService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +/** + * @Author: cdf + * @CreateTime: 2025-07-28 + * @Description: + */ +@Service +public class PqUserLedgerServiceImpl extends ServiceImpl implements PqUserLedgerService { + + @Autowired + private PqUserLedgerMapper ledgerMapper; + + @Override + public boolean addLedger(PqUserLedgerParam ledgerParam) { + PqUserLedgerPO ledger = new PqUserLedgerPO(); + BeanUtil.copyProperties(ledgerParam,ledger); + ledger.setId(UUID.randomUUID().toString()); + ledger.setCreateTime(LocalDateTime.now()); + ledger.setUpdateTime(LocalDateTime.now()); + return ledgerMapper.insert(ledger) > 0; + } + + @Override + public boolean updateLedger(PqUserLedgerParam ledgerParam) { + PqUserLedgerPO ledger = new PqUserLedgerPO(); + BeanUtil.copyProperties(ledgerParam,ledger); + ledger.setUpdateTime(LocalDateTime.now()); + return ledgerMapper.updateById(ledger) > 0; + } + + @Override + public boolean deleteLedger(List ids) { + // 物理删除(直接删除记录) + return ledgerMapper.deleteBatchIds(ids) > 0; + } + + @Override + public PqUserLedgerPO getLedgerById(String id) { + return ledgerMapper.selectById(id); + } + + @Override + public Page pageList(PqUserLedgerParam param) { + Page page = new Page<>(); + Page pageResult = ledgerMapper.selectPage(page,new LambdaQueryWrapper()); + return page; + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDeptsServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDeptsServiceImpl.java new file mode 100644 index 0000000..2959b0c --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDeptsServiceImpl.java @@ -0,0 +1,32 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.njcn.product.event.devcie.pojo.dto.PqsDeptDTO; +import org.springframework.stereotype.Service; + +import java.util.List; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsDeptsMapper; +import com.njcn.product.event.transientes.pojo.po.PqsDepts; +import com.njcn.product.event.transientes.service.PqsDeptsService; +/** + * + * Description: + * Date: 2025/06/19 下午 3:57【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsDeptsServiceImpl extends ServiceImpl implements PqsDeptsService{ + + @Override + public List findDeptAndChildren(String deptId) { + return this.getBaseMapper().findDeptAndChildren(deptId); + } + + @Override + public List getDeptList(List deptIds) { + return this.getBaseMapper().getDeptList(deptIds); + + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDicTreeServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDicTreeServiceImpl.java new file mode 100644 index 0000000..9021e98 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsDicTreeServiceImpl.java @@ -0,0 +1,31 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsDicTreeMapper; +import com.njcn.product.event.transientes.pojo.po.PqsDicTreePO; +import com.njcn.product.event.transientes.service.PqsDicTreeService; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @Author: cdf + * @CreateTime: 2025-08-01 + * @Description: + */ +@Service +public class PqsDicTreeServiceImpl extends ServiceImpl implements PqsDicTreeService { + + + /** + * 获取字典树 + */ + + @Override + public List getDicTree(String code){ + List pqsDicTreePOList = this.getBaseMapper().selectChildrenByCode(code); + return pqsDicTreePOList; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsEventdetailServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsEventdetailServiceImpl.java new file mode 100644 index 0000000..76dea48 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsEventdetailServiceImpl.java @@ -0,0 +1,22 @@ +package com.njcn.product.event.transientes.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.pojo.po.PqsEventdetail; +import com.njcn.product.event.transientes.mapper.PqsEventdetailMapper; +import com.njcn.product.event.transientes.service.PqsEventdetailService; + +/** + * + * Description: + * Date: 2025/06/20 上午 10:06【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsEventdetailServiceImpl extends ServiceImpl implements PqsEventdetailService{ + + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsOnlinerateServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsOnlinerateServiceImpl.java new file mode 100644 index 0000000..590bb92 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsOnlinerateServiceImpl.java @@ -0,0 +1,19 @@ +package com.njcn.product.event.transientes.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsOnlinerateMapper; +import com.njcn.product.event.transientes.pojo.po.PqsOnlinerate; +import com.njcn.product.event.transientes.service.PqsOnlinerateService; +/** + * + * Description: + * Date: 2025/07/29 下午 6:40【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsOnlinerateServiceImpl extends ServiceImpl implements PqsOnlinerateService{ + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUserServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUserServiceImpl.java new file mode 100644 index 0000000..7c9df0b --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUserServiceImpl.java @@ -0,0 +1,19 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsUserMapper; +import com.njcn.product.event.transientes.pojo.po.PqsUser; +import com.njcn.product.event.transientes.service.PqsUserService; +import org.springframework.stereotype.Service; + +/** + * Description: + * Date: 2025/06/27 上午 9:46【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsUserServiceImpl extends ServiceImpl implements PqsUserService { + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUsersetServiceImpl.java b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUsersetServiceImpl.java new file mode 100644 index 0000000..8f375b0 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/service/impl/PqsUsersetServiceImpl.java @@ -0,0 +1,21 @@ +package com.njcn.product.event.transientes.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.njcn.product.event.transientes.mapper.PqsUserSetMapper; +import com.njcn.product.event.transientes.pojo.po.PqsUserSet; +import org.springframework.stereotype.Service; + + +import com.njcn.product.event.transientes.service.PqsUsersetService; +/** + * + * Description: + * Date: 2025/06/26 下午 2:27【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Service +public class PqsUsersetServiceImpl extends ServiceImpl implements PqsUsersetService{ + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/utils/JwtUtil.java b/event_smart/src/main/java/com/njcn/product/event/transientes/utils/JwtUtil.java new file mode 100644 index 0000000..fc6bcff --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/utils/JwtUtil.java @@ -0,0 +1,85 @@ +package com.njcn.product.event.transientes.utils; + +import com.njcn.product.event.transientes.security.MyUserDetails; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +@Component +public class JwtUtil { + + private final String userId = "userId"; + private final String userName = "userName"; + private final String deptId = "deptId"; + + + private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); + private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 1000000000L; // 100000小时 + + // 生成JWT令牌 + public String generateToken(MyUserDetails userDetails) { + Map claims = new HashMap<>(); + claims.put(userId,userDetails.getUserId()); + claims.put(userName,userDetails.getUsername()); + claims.put(deptId,userDetails.getDeptId()); + return createToken(claims, userDetails.getUsername()); + } + + private String createToken(Map claims, String subject) { + return Jwts.builder() + .setClaims(claims) + .setSubject(subject) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) + .signWith(SECRET_KEY, SignatureAlgorithm.HS256) + .compact(); + } + + // 验证令牌 + public Boolean validateToken(String token, UserDetails userDetails) { + final String username = extractUsername(token); + return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); + } + + // 提取用户名 + public String extractUsername(String token) { + return extractClaim(token, it->it.get(userName).toString()); + } + + // 提取用户ID + public String extractUserId(String token) { + return extractClaim(token,it->it.get(userId).toString()); + } + + // 提取用户部门 + public String extractDepartment(String token) { + return extractClaim(token, it->it.get(deptId).toString()); + } + + // 提取过期时间 + public Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + private T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + private Claims extractAllClaims(String token) { + return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody(); + } + + private Boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketConfig.java b/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketConfig.java new file mode 100644 index 0000000..e8fb7f6 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketConfig.java @@ -0,0 +1,41 @@ +package com.njcn.product.event.transientes.websocket; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; +import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; + +/** + * Description: + * Date: 2024/12/13 15:09【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Configuration +public class WebSocketConfig { + + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } + + /** + * 通信文本消息和二进制缓存区大小 + * 避免对接 第三方 报文过大时,Websocket 1009 错误 + * + * @return + */ + + @Bean + public ServletServerContainerFactoryBean createWebSocketContainer() { + ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); + // 在此处设置bufferSize + container.setMaxTextMessageBufferSize(10240000); + container.setMaxBinaryMessageBufferSize(10240000); + container.setMaxSessionIdleTimeout(15 * 60000L); + return container; + } + + +} diff --git a/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketServer.java b/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketServer.java new file mode 100644 index 0000000..c643e48 --- /dev/null +++ b/event_smart/src/main/java/com/njcn/product/event/transientes/websocket/WebSocketServer.java @@ -0,0 +1,147 @@ +package com.njcn.product.event.transientes.websocket; + +import cn.hutool.core.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Description: + * Date: 2024/12/13 15:11【需求编号】 + * + * @author clam + * @version V1.0.0 + */ +@Slf4j +@Component +@ServerEndpoint(value = "/ws/{userId}") +public class WebSocketServer { + + private static final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap lastHeartbeatTime = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap heartbeatExecutors = new ConcurrentHashMap<>(); + private static final long HEARTBEAT_TIMEOUT = 60; // 60秒超时 + + @OnOpen + public void onOpen(Session session, @PathParam("userId") String userId) { + if (StrUtil.isNotBlank(userId)) { + sessions.put(userId, session); + lastHeartbeatTime.put(userId, System.currentTimeMillis()); + sendMessage(session, "连接成功"); + System.out.println("用户 " + userId + " 已连接"); + + // 启动心跳检测 + startHeartbeat(session, userId); + } else { + try { + session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "用户ID不能为空")); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @OnMessage + public void onMessage(String message, Session session, @PathParam("userId") String userId) { + if ("alive".equalsIgnoreCase(message)) { + // 更新最后心跳时间 + lastHeartbeatTime.put(userId, System.currentTimeMillis()); + sendMessage(session, "over"); + } else { + // 处理业务消息 + System.out.println("收到用户 " + userId + " 的消息: " + message); + // TODO: 处理业务逻辑 + } + } + + @OnClose + public void onClose(Session session, CloseReason closeReason, @PathParam("userId") String userId) { + // 移除用户并取消心跳检测 + sessions.remove(userId); + lastHeartbeatTime.remove(userId); + ScheduledExecutorService executor = heartbeatExecutors.remove(userId); + if (executor != null) { + executor.shutdownNow(); + } + System.out.println("用户 " + userId + " 已断开连接,状态码: " + closeReason.getCloseCode()); + } + + @OnError + public void onError(Session session, Throwable throwable, @PathParam("userId") String userId) { + System.out.println("用户 " + userId + " 发生错误: " + throwable.getMessage()); + try { + session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "发生错误")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void sendMessageToUser(String userId, String message) { + Session session = sessions.get(userId); + if (session != null && session.isOpen()) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage()); + } + } else { + System.out.println("webSocket用户 " + userId + " 不在线或会话已关闭"); + } + } + + private final Object lock = new Object(); + + public void sendMessageToAll(String message) { + sessions.forEach((userId, session) -> { + System.out.println("给用户推送消息" + userId); + if (session.isOpen()) { + synchronized (lock) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息给用户 " + userId + " 失败: " + e.getMessage()); + } + } + } + }); + } + + private void sendMessage(Session session, String message) { + try { + session.getBasicRemote().sendText(message); + } catch (IOException e) { + System.out.println("发送消息失败: " + e.getMessage()); + } + } + + private void startHeartbeat(Session session, String userId) { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + heartbeatExecutors.put(userId, executor); + + // 定期检查心跳 + executor.scheduleAtFixedRate(() -> { + long lastTime = lastHeartbeatTime.getOrDefault(userId, 0L); + long currentTime = System.currentTimeMillis(); + + // 如果超过30秒没有收到心跳 + if (currentTime - lastTime > HEARTBEAT_TIMEOUT * 1000) { + try { + System.out.println("用户 " + userId + " 心跳超时,关闭连接"); + session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "心跳超时")); + } catch (IOException e) { + System.out.println("关闭用户 " + userId + " 连接时出错: " + e.getMessage()); + } + executor.shutdown(); + heartbeatExecutors.remove(userId); + } + }, 0, 5, TimeUnit.SECONDS); // 每5秒检查一次 + } +} \ No newline at end of file diff --git a/event_smart/src/main/resources/application-dev.yml b/event_smart/src/main/resources/application-dev.yml new file mode 100644 index 0000000..2c95ddb --- /dev/null +++ b/event_smart/src/main/resources/application-dev.yml @@ -0,0 +1,53 @@ +spring: + application: + name: event_smart + + datasource: + dynamic: + primary: master + strict: false # 是否严格匹配数据源,默认false + druid: # 如果使用Druid连接池 + validation-query: SELECT 1 FROM DUAL # 达梦专用校验SQL + initial-size: 10 + # 初始化大小,最小,最大 + min-idle: 20 + maxActive: 500 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + testWhileIdle: true + testOnBorrow: true + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + datasource: + master: + url: jdbc:oracle:thin:@192.168.1.51:1521:pqsbase + username: pqsadmin_bj + password: pqsadmin + driver-class-name: oracle.jdbc.OracleDriver +# salve: +# driver-class-name: dm.jdbc.driver.DmDriver +# url: jdbc:dm://192.168.1.21:5236/PQSADMIN?useUnicode=true&characterEncoding=utf-8 +# username: PQSADMINLN +# password: Pqsadmin123 + + + + redis: + database: 10 + host: localhost + port: 6379 + timeout: 5000 + lettuce: + pool: + max-active: 8 + max-wait: 8000 + max-idle: 8 + min-idle: 0 + + diff --git a/event_smart/src/main/resources/application-prod.yml b/event_smart/src/main/resources/application-prod.yml new file mode 100644 index 0000000..334d60d --- /dev/null +++ b/event_smart/src/main/resources/application-prod.yml @@ -0,0 +1,55 @@ +server: + port: 18093 +spring: + application: + name: event_smart + datasource: + dynamic: + primary: master + strict: false # 是否严格匹配数据源,默认false + druid: # 如果使用Druid连接池 + validation-query: SELECT 1 FROM DUAL # 达梦专用校验SQL + initial-size: 10 + # 初始化大小,最小,最大 + min-idle: 20 + maxActive: 500 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + testWhileIdle: true + testOnBorrow: true + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + poolPreparedStatements: true + maxPoolPreparedStatementPerConnectionSize: 20 + datasource: + master: + url: jdbc:oracle:thin:@192.168.10.34:11521:pqsbase + username: pqsadmin + password: Pqsadmin_123 + driver-class-name: oracle.jdbc.OracleDriver +# salve: +# driver-class-name: dm.jdbc.driver.DmDriver +# url: jdbc:dm://192.168.1.21:5236/PQSADMIN?useUnicode=true&characterEncoding=utf-8 +# username: PQSADMINLN +# password: Pqsadmin123 + + + + redis: + database: 10 + host: localhost + port: 16379 + password: "Pqsadmin@#1qaz" + timeout: 5000 + lettuce: + pool: + max-active: 20 + max-wait: 8000 + max-idle: 8 + min-idle: 0 + + diff --git a/event_smart/src/main/resources/application.yml b/event_smart/src/main/resources/application.yml new file mode 100644 index 0000000..aebfa05 --- /dev/null +++ b/event_smart/src/main/resources/application.yml @@ -0,0 +1,72 @@ +#当前服务的基本信息 +microservice: + ename: 12345 + name: 12345 +server: + port: 18093 +spring: + application: + name: event_smart + profiles: + active: dev + + +#mybatis配置信息 +mybatis-plus: + mapper-locations: classpath*:com/njcn/**/mapping/*.xml + #别名扫描 + type-aliases-package: com.njcn.product.event.**.pojo + configuration: + #驼峰命名 + map-underscore-to-camel-case: true + #配置sql日志输出 + #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + #关闭日志输出 + log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl + global-config: + db-config: + #指定主键生成策略 + id-type: assign_uuid + + +SYS_TYPE_ZT: 1cfcd6e2-c5fe-4b15-988a-32b90f1170c1 +SYS_TYPE_WT: 983f9dfe-4f9a-4c96-89d8-7d425a1f1d6c +db: + type: oracle + +#文件位置配置 +business: + #处理波形数据位置 + wavePath: D://Comtrade + #wavePath: /usr/local/comtrade + #处理临时数据 + tempPath: D://file + #tempPath: /usr/local/file + #文件存储的方式 3.本地存储 + file: + storage: 3 +#oss服务器配置 +min: + io: + endpoint: http://192.168.1.13:9009 + accessKey: minio + secretKey: minio@123 + bucket: excelreport + #华为obs服务器配置 +huawei: + access-key: J9GS9EA79PZ60OK23LWP + security-key: BirGrAFDSLxU8ow5fffyXgZRAmMRb1R1AdqCI60d + obs: + bucket: test-8601 + endpoint: https://obs.cn-east-3.myhuaweicloud.com + # 单位为秒 + expire: 3600 +#线程池配置信息 +threadPool: + corePoolSize: 10 + maxPoolSize: 20 + queueCapacity: 500 + keepAliveSeconds: 60 +WAVEPATH: D:/Comtrade + + diff --git a/event_smart/src/main/resources/logback.xml b/event_smart/src/main/resources/logback.xml new file mode 100644 index 0000000..e972d91 --- /dev/null +++ b/event_smart/src/main/resources/logback.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + UTF-8 + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + UTF-8 + + + + + + + + ${logHomeDir}/${log.projectName}/debug/debug.log + + + + + DEBUG + + ACCEPT + + DENY + + + + + + ${logHomeDir}/${log.projectName}/debug/debug.log.%d{yyyy-MM-dd}.%i.log + + 10MB + + ${log.maxHistory:-30} + + + + + + + + + + ${log.pattern} + + UTF-8 + + + + + + + INFO + ACCEPT + DENY + + + ${logHomeDir}/${log.projectName}/info/info.log + + + + ${logHomeDir}/${log.projectName}/info/info.log.%d{yyyy-MM-dd}.%i.log + + 10MB + ${log.maxHistory:-30} + + + + ${log.pattern} + + UTF-8 + + + + + + + + ${logHomeDir}/${log.projectName}/error/error.log + + + ERROR + ACCEPT + DENY + + + + ${logHomeDir}/${log.projectName}/error/error.log.%d{yyyy-MM-dd}.%i.log + + 10MB + ${log.maxHistory:-30} + + + + ${log.pattern} + + UTF-8 + + + + + + + + + + + + + + + + + + + + + + + diff --git a/event_smart/src/main/resources/template/test.docx b/event_smart/src/main/resources/template/test.docx new file mode 100644 index 0000000..3c7d4ae Binary files /dev/null and b/event_smart/src/main/resources/template/test.docx differ diff --git a/event_smart/src/test/java/com/njcn/product/event/EventSmartApplicationTests.java b/event_smart/src/test/java/com/njcn/product/event/EventSmartApplicationTests.java new file mode 100644 index 0000000..310ef47 --- /dev/null +++ b/event_smart/src/test/java/com/njcn/product/event/EventSmartApplicationTests.java @@ -0,0 +1,13 @@ +package com.njcn.product.event; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EventSmartApplicationTests { + + @Test + void contextLoads() { + } + +}