Merge remote-tracking branch 'origin/main'

This commit is contained in:
liuzhaotian
2024-09-05 11:05:58 +08:00
30 changed files with 486 additions and 199 deletions
@@ -88,11 +88,6 @@ public class OperateLogAspect {
private Object around0(ProceedingJoinPoint joinPoint,
com.cf.imes.framework.operatelog.core.annotations.OperateLog operateLog,
Operation operation) throws Throwable {
// 目前,只有管理员,才记录操作日志!所以非管理员,直接调用,不进行记录
Integer userType = WebFrameworkUtils.getLoginUserType();
if (!Objects.equals(userType, UserTypeEnum.ADMIN.getValue())) {
return joinPoint.proceed();
}
// 记录开始时间
LocalDateTime startTime = LocalDateTime.now();
@@ -4,16 +4,42 @@ import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.cf.imes.framework.common.util.encrypt.AesUtils;
import com.cf.imes.framework.es.core.service.ESDocumentService;
import com.cf.imes.framework.es.core.service.ESDocumentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
/**
* @author there
@@ -21,20 +47,19 @@ import org.springframework.util.StringUtils;
@AutoConfiguration
@ConditionalOnClass(ElasticsearchClient.class)
@EnableConfigurationProperties(EsProperties.class)
@Slf4j
public class ChenfengElasticsearchAutoConfiguration {
//超时时间设置
public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 10000;
public static final int DEFAULT_SOCKET_TIMEOUT_MILLIS = 300000;
public static final int DEFAULT_CONNECT_REQUEST_TIMEOUT_MILLIS = 1000;
@Value("${chenfeng.encrypt.publicKey:}")
private String publicKey;
/**
* 同步方式
*
*/
@Bean
public ElasticsearchClient elasticsearchClient(EsProperties properties) {
return new ElasticsearchClient(getTransport(properties.getUris()));
public ElasticsearchClient elasticsearchClient(RestClientTransport transport) {
return new ElasticsearchClient(transport);
}
/**
@@ -42,44 +67,110 @@ public class ChenfengElasticsearchAutoConfiguration {
*
*/
@Bean
public ElasticsearchAsyncClient elasticsearchAsyncClient(EsProperties properties) {
return new ElasticsearchAsyncClient(getTransport(properties.getUris()));
public ElasticsearchAsyncClient elasticsearchAsyncClient(RestClientTransport transport) {
return new ElasticsearchAsyncClient(transport);
}
@Bean
private ESDocumentService esDocumentService(ElasticsearchClient elasticsearchClient, ElasticsearchAsyncClient elasticsearchAsyncClient) {
public ESDocumentService esDocumentService(ElasticsearchClient elasticsearchClient, ElasticsearchAsyncClient elasticsearchAsyncClient) {
return new ESDocumentServiceImpl(elasticsearchClient, elasticsearchAsyncClient);
}
/**
* 获取客户端 RestClientTransport
*/
private RestClientTransport getTransport(String hosts){
HttpHost[] httpHosts = toHttpHost(hosts);
RestClient restClient = getRestClient(httpHosts);
return new RestClientTransport(restClient, new JacksonJsonpMapper());
@Bean
public RestClientTransport getTransport(RestClient client){
return new RestClientTransport(client, new JacksonJsonpMapper());
}
/**
* 获取客户端RestClient
* @param httpHosts http数组
* chenfeng.encrypt.enabletrue
*
* @param properties es配置
*/
private RestClient getRestClient(HttpHost[] httpHosts){
return RestClient.builder(httpHosts).setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS);
requestConfigBuilder.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS);
requestConfigBuilder.setConnectionRequestTimeout(DEFAULT_CONNECT_REQUEST_TIMEOUT_MILLIS);
@Bean
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public RestClient getAuthRestClient(EsProperties properties) {
// 配置账号密码
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(AesUtils.decrypt(properties.getUsername(), publicKey), AesUtils.decrypt(properties.getPassword(), publicKey)));
RestClientBuilder.HttpClientConfigCallback httpClientConfigCallback = httpClientBuilder -> {
// 设置账号密码、连接信息
HttpAsyncClientBuilder httpAsyncClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(properties.getConnectionTimeout().toSecondsPart())
.setSocketTimeout(properties.getSocketTimeout().toSecondsPart())
.setConnectionRequestTimeout(properties.getConnectionRequestTimeout().toSecondsPart())
.build());
if (properties.isSecurityHttpSslEnable()) {
// 开启ssl配置连接证书
httpAsyncClientBuilder.setSSLContext(buildSSLContext()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
}
return httpAsyncClientBuilder;
};
return RestClient.builder(toHttpHost(properties.getUris(), properties.isSecurityHttpSslEnable())).setHttpClientConfigCallback(httpClientConfigCallback).build();
}
/**
* 获取客户端RestClient(默认)
* chenfeng.encrypt.enablefalse或者缺省
*
* @param properties es配置
*/
@Bean
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "false", matchIfMissing = true)
public RestClient getRestClient(EsProperties properties) {
return RestClient.builder(toHttpHost(properties.getUris(), properties.isSecurityHttpSslEnable())).setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(properties.getConnectionTimeout().toSecondsPart());
requestConfigBuilder.setSocketTimeout(properties.getSocketTimeout().toSecondsPart());
requestConfigBuilder.setConnectionRequestTimeout(properties.getConnectionRequestTimeout().toSecondsPart());
return requestConfigBuilder;
}).build();
}
/**
* 解析配置的字符串hosts,转为HttpHost对象数组
* 构建ssl请求信息
*
* @return
*/
private HttpHost[] toHttpHost(String hosts) {
private SSLContext buildSSLContext() {
SSLContext sslContext = null;
try {
ClassPathResource resource = new ClassPathResource("http_ca.crt");
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = resource.getInputStream()) {
trustedCa = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
sslContext = sslContextBuilder.build();
} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException |
KeyManagementException e) {
log.error("ES连接认证失败", e);
}
return sslContext;
}
/**
* 解析域名
*
* @param hosts 域名字符串
* @param isSslEnable 是否开启ssl
* @return
*/
private HttpHost[] toHttpHost(String hosts, boolean isSslEnable) {
if (!StringUtils.hasLength(hosts)) {
throw new RuntimeException("invalid elasticsearch configuration. elasticsearch.hosts不能为空!");
throw new IllegalArgumentException("invalid elasticsearch configuration. elasticsearch.hosts不能为空!");
}
// 多个IP逗号隔开
String[] hostArray = hosts.split(",");
@@ -87,14 +178,9 @@ public class ChenfengElasticsearchAutoConfiguration {
HttpHost httpHost;
for (int i = 0; i < hostArray.length; i++) {
String[] strings = hostArray[i].split(":");
httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), isSslEnable ? "https" : "http");
httpHosts[i] = httpHost;
}
return httpHosts;
}
}
@@ -2,12 +2,46 @@ package com.cf.imes.framework.es.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
/**
* es环境配置
* @author there
*/
@ConfigurationProperties(prefix = "spring.elasticsearch")
public class EsProperties {
private String uris;
/**
* Username for authentication with Elasticsearch.
*/
private String username;
/**
* Password for authentication with Elasticsearch.
*/
private String password;
/**
* Connection timeout used when communicating with Elasticsearch.
*/
private Duration connectionTimeout = Duration.ofSeconds(10);
/**
* Socket timeout used when communicating with Elasticsearch.
*/
private Duration socketTimeout = Duration.ofSeconds(30);
private Duration connectionRequestTimeout = Duration.ofSeconds(1);
/**
* Prefix added to the path of every request sent to Elasticsearch.
*/
private String pathPrefix;
private boolean securityHttpSslEnable = false;
public String getUris() {
return uris;
}
@@ -16,5 +50,59 @@ public class EsProperties {
this.uris = uris;
}
private String uris;
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Duration getConnectionTimeout() {
return this.connectionTimeout;
}
public void setConnectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public Duration getSocketTimeout() {
return this.socketTimeout;
}
public void setSocketTimeout(Duration socketTimeout) {
this.socketTimeout = socketTimeout;
}
public String getPathPrefix() {
return this.pathPrefix;
}
public void setPathPrefix(String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public boolean isSecurityHttpSslEnable() {
return securityHttpSslEnable;
}
public void setSecurityHttpSslEnable(boolean securityHttpSslEnable) {
this.securityHttpSslEnable = securityHttpSslEnable;
}
public Duration getConnectionRequestTimeout() {
return connectionRequestTimeout;
}
public void setConnectionRequestTimeout(Duration connectionRequestTimeout) {
this.connectionRequestTimeout = connectionRequestTimeout;
}
}
@@ -15,9 +15,9 @@ import org.springframework.context.annotation.Bean;
*/
@AutoConfiguration
@AutoConfigureBefore(DynamicDataSourceAutoConfiguration.class)
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public class ChenfengDataSourceEncryptConfiguration {
@Bean
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public DataSourceInitEvent getDataSourceInitEvent() {
return new ChenfengDataSourceEncryptInitEvent();
}
@@ -66,16 +66,18 @@ public class DefaultDBFieldHandler implements MetaObjectHandler {
}
// 从请求中获取到 Token
String authorization = obtainAuthorization(AUTHORIZATION_HEADER_NAME, TOKEN_PARAM_NAME);
Long organId = null;
/**
* 用户首次密码登陆的时候,不会有token带入,直接捕捉异常抛出即可,组织ID后续会根据用户登录的组织进行填入,
* 这里的组织ID字段填入即使为空也可,后续的请求中都会带有token,再从缓存中获取到 token 数据,再获取组织ID,填入即可
*/
Long organId = null;
try {
// 从请求中获取到 Token
String authorization = obtainAuthorization(AUTHORIZATION_HEADER_NAME, TOKEN_PARAM_NAME);
// 获取 token 对应的缓存数据,并得到组织 ID
OAuth2AccessTokenDO oAuth2AccessTokenDO = get(authorization);
organId = oAuth2AccessTokenDO.getOrganId();
@@ -20,13 +20,13 @@ import org.springframework.util.StringUtils;
* @since 2024/8/27 9:46
*/
@AutoConfiguration
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public class ChenfengRedisEncryptAutoConfiguration {
@Value("${chenfeng.encrypt.publicKey:}")
private String publicKey;
@Bean
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public RedissonAutoConfigurationCustomizer redissonAutoConfigurationCustomizer() {
return configuration -> {
Config redissonConfig = new Config();
@@ -157,5 +157,7 @@ chenfeng:
- infra_job_log
- infra_job_log
- infra_data_source_config
encrypt:
enable: false
publicKey: cfimes
debug: false
@@ -1,10 +1,12 @@
package com.cf.imes.module.executor.controller.admin.order;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.framework.web.config.WebProperties;
import com.cf.imes.framework.web.core.util.WebFrameworkUtils;
import com.cf.imes.module.executor.controller.admin.order.vo.order.*;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderBodyRespVO;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderRoomBodyRespVO;
@@ -21,6 +23,7 @@ import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.VO.OrderX
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.XMLReadUtil;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.webmvc.core.RequestService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
@@ -189,62 +192,90 @@ public class OrderController {
// api-生产单导入
@GetMapping("getApiData")
@Operation(summary = "生产单api数据导入新增")
@Parameter(name = "orderNo", description = "原订单号", required = true, example = "20230809027818")
@PreAuthorize("@ss.hasPermission('production:manager-list:create')")
public CommonResult<Long> test(@RequestParam(value = "orderNo", required = false, defaultValue = "20230809027818") String orderNo)
public CommonResult<Long> getApiData(@RequestParam(value = "orderNo") String orderNo)
throws InterruptedException, ExecutionException {
Long orderId = (Long) identifierGenerator.nextId(null);
Long organId = getUserOrganId();
// final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//// 从HttpServletRequest中提取servletPath
// String servletPath = request.getServletPath();
// System.out.println("servletPath = " + servletPath.startsWith(properties.getAdminApi().getPrefix()));
try {
Long orderId = (Long) identifierGenerator.nextId(null);
Long organId = getUserOrganId();
JSONObject oauth = apiDataAchieve.getApiToken(organId).get();
String token = oauth.getJSONObject("info").getString("access_token");
String shopId = oauth.getJSONObject("info").getString("shop_id");
JSONObject order = apiDataAchieve.getApiOrder(token, shopId, orderNo).get();
if (!order.getString("err_code").equals("0")) {
throw exception(PLATE_PLAN_DATA_ERROR);
}
if (order.getJSONArray("data") == null) {
throw exception(PLATE_PLAN_DATA_NULL);
}
JSONObject dataPlates = apiDataAchieve.getApiPlateProData(token, orderNo).get();
JSONObject dataParts = apiDataAchieve.getApiPartsMessage(token, orderNo).get();
JSONObject dataBody = apiDataAchieve.getApiBodyMessage(token, orderNo).get();
JSONObject dataGoods = apiDataAchieve.getApiGoodsMessage(token, orderNo).get();
JSONObject plate = apiDataAchieve.getApiPlateDetailMessage(token, orderNo).get();
JSONObject dataModule = apiDataAchieve.getApiGroupMessage(token, orderNo).get();
JSONObject block = apiDataAchieve.getApiBlocksMessage(token, orderNo).get();
Map<String, List<?>> listMap = apiTypeRealize.apiPlateDataChange(
order,
dataPlates,//板件生产信息
dataParts,// 配件信息
dataBody, // 柜体信息
dataGoods, // 商品信息
plate, // 板件明细
dataModule,// 加工组信息
block,// 板材数据
orderNo,// 原始板编号
orderId,
organId);
return success(orderService.importApiData(listMap));
} catch (Exception e) {
log.error("api数据导入异常", e);
throw exception(PLATE_PLAN_DATA_ERROR);
}
}
// public CommonResult<Long> test(@RequestParam(value = "orderNo") String orderNo)
// throws InterruptedException, ExecutionException {
//
// Long orderId = (Long) identifierGenerator.nextId(null);
// Long organId = getUserOrganId();
//
// JSONObject oauth = apiDataAchieve.getApiToken(organId).get();
// String token = oauth.getJSONObject("info").getString("access_token");
// String shopId = oauth.getJSONObject("info").getString("shop_id");
// JSONObject order = apiDataAchieve.getApiOrder(token, shopId, orderNo).get();
// if (!order.getString("err_code").equals("0")) {
// throw exception(PLATE_PLAN_DATA_ERROR);
// }
// if (order.getJSONArray("data") == null) {
// throw exception(PLATE_PLAN_DATA_NULL);
// }
// JSONObject dataPlates = apiDataAchieve.getApiPlateProData(token, orderNo).get();
// JSONObject dataParts = apiDataAchieve.getApiPartsMessage(token, orderNo).get();
// JSONObject dataBody = apiDataAchieve.getApiBodyMessage(token, orderNo).get();
// JSONObject dataGoods = apiDataAchieve.getApiGoodsMessage(token, orderNo).get();
// JSONObject plate = apiDataAchieve.getApiPlateDetailMessage(token, orderNo).get();
// JSONObject dataModule = apiDataAchieve.getApiGroupMessage(token, orderNo).get();
// JSONObject block = apiDataAchieve.getApiBlocksMessage(token, orderNo).get();
//
// CompletableFuture.runAsync(() -> {
//// System.out.println(String.join("-", Thread.currentThread().getName(), " i = " + i.getAndIncrement()));
// RequestContextHolder.setRequestAttributes(requestAttributes);
// try {
// orderService.importApiData(orderNo, orderId, organId);
// DynamicDataSourceContextHolder.push("slave");
// orderService.importApiData(order,dataPlates,dataParts,dataBody,dataGoods,plate,dataModule,block,orderNo, orderId, organId);
// DynamicDataSourceContextHolder.clear();
// } catch (Exception e) {
//
// log.error(" 1: ", e);
// }
// }, asyncExecutor).exceptionally(e -> {
// log.error("error", e);
// return null;
// });
// Long organId = SecurityFrameworkUtils.getLoginUser().getOrganId();
JSONObject oauth = apiDataAchieve.getApiToken(organId).get();
String token = oauth.getJSONObject("info").getString("access_token");
String shopId = oauth.getJSONObject("info").getString("shop_id");
JSONObject order = apiDataAchieve.getApiOrder(token, shopId, orderNo).get();
if (!order.getString("err_code").equals("0")) {
throw exception(PLATE_PLAN_DATA_ERROR);
}
if (order.getJSONArray("data") == null) {
throw exception(PLATE_PLAN_DATA_NULL);
}
JSONObject dataPlates = apiDataAchieve.getApiPlateProData(token, orderNo).get();
JSONObject dataParts = apiDataAchieve.getApiPartsMessage(token, orderNo).get();
JSONObject dataBody = apiDataAchieve.getApiBodyMessage(token, orderNo).get();
JSONObject dataGoods = apiDataAchieve.getApiGoodsMessage(token, orderNo).get();
JSONObject plate = apiDataAchieve.getApiPlateDetailMessage(token, orderNo).get();
JSONObject dataModule = apiDataAchieve.getApiGroupMessage(token, orderNo).get();
JSONObject block = apiDataAchieve.getApiBlocksMessage(token, orderNo).get();
Map<String, List<?>> listMap = apiTypeRealize.apiPlateDataChange(
order,
dataPlates,//板件生产信息
dataParts,// 配件信息
dataBody, // 柜体信息
dataGoods, // 商品信息
plate, // 板件明细
dataModule,// 加工组信息
block,// 板材数据
orderNo,// 原始板编号
orderId,
organId);
return success(orderService.importApiData(listMap));
//
// return success(orderId);
}
// }
@PostMapping("/importFile")
@Operation(summary = "生产单文件导入新增/导入板材")
@@ -256,7 +287,7 @@ public class OrderController {
})
@OperateLog(type = IMPORT)
@PreAuthorize("@ss.hasPermission('production:manager-list:create')")
public void exportTestTwo(@RequestPart("file") MultipartFile file,
public void exportFile(@RequestPart("file") MultipartFile file,
@RequestParam(value = "type") Integer type,
@RequestParam(value = "index", required = false, defaultValue = "0") Integer index,
@RequestParam(value = "id", required = false, defaultValue = "0") Long orderId,
@@ -105,7 +105,10 @@ public interface OrderService {
* @date 2024/3/30
*/
Long importApiData(Map<String, List<?>> listMap);
void importApiData(String orderNo, Long orderId, Long organId) throws InterruptedException, ExecutionException;
void importApiData(JSONObject order, JSONObject dataPlates, JSONObject dataParts
, JSONObject dataBody, JSONObject dataGoods
, JSONObject plates, JSONObject dataModule
, JSONObject dataBlocks, String orderNo,Long orderId, Long organId);
/**
* 文件数据导入
@@ -13,6 +13,7 @@ import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.mybatis.core.generator.SnowFlakeGenerator;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.web.core.util.WebFrameworkUtils;
import com.cf.imes.module.executor.controller.admin.order.vo.order.*;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderBodyRespVO;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderRoomBodyRespVO;
@@ -259,7 +260,9 @@ public class OrderServiceImpl implements OrderService {
orderBodyMapper.updateDeletedById(bodyIds, status, getUserOrganId(), orderId);// 柜体
orderGroupMapper.updateDeletedById(bodyIds, status, getUserOrganId(), orderId);// 加工组
plateMapper.updateDeletedById(plateDOList, status, getUserOrganId(), orderId);// 删小板
if (plateDOList != null && plateDOList.size() != 0) {
plateMapper.updateDeletedById(plateDOList, status, getUserOrganId(), orderId);// 删小板
}
// 删除大板
List<PlateDO> goodsIdList = plateMapper.selectPlateNum(orderId, getUserOrganId());
Map<Long, List<PlateDO>> goodsIdMap = goodsIdList.stream()
@@ -358,35 +361,22 @@ public class OrderServiceImpl implements OrderService {
@Override
// @Async
@Transactional(rollbackFor = Exception.class)
public void importApiData(String orderNo, Long orderId, Long organId) throws InterruptedException, ExecutionException {
public void importApiData(JSONObject order, JSONObject dataPlates, JSONObject dataParts
, JSONObject dataBody, JSONObject dataGoods
, JSONObject plates, JSONObject dataModule
, JSONObject dataBlocks, String orderNo,Long orderId, Long organId) {
// RequestContextHolder.setRequestAttributes(requestAttributes);
JSONObject oauth = apiDataAchieve.getApiToken(organId).get();
String token = oauth.getJSONObject("info").getString("access_token");
String shopId = oauth.getJSONObject("info").getString("shop_id");
JSONObject order = apiDataAchieve.getApiOrder(token, shopId, orderNo).get();
if (!order.getString("err_code").equals("0")) {
throw exception(PLATE_PLAN_DATA_ERROR);
}
if (order.getJSONArray("data") == null) {
throw exception(PLATE_PLAN_DATA_NULL);
}
JSONObject dataPlates = apiDataAchieve.getApiPlateProData(token, orderNo).get();
JSONObject dataParts = apiDataAchieve.getApiPartsMessage(token, orderNo).get();
JSONObject dataBody = apiDataAchieve.getApiBodyMessage(token, orderNo).get();
JSONObject dataGoods = apiDataAchieve.getApiGoodsMessage(token, orderNo).get();
JSONObject plate = apiDataAchieve.getApiPlateDetailMessage(token, orderNo).get();
JSONObject dataModule = apiDataAchieve.getApiGroupMessage(token, orderNo).get();
JSONObject block = apiDataAchieve.getApiBlocksMessage(token, orderNo).get();
String nickName = SecurityFrameworkUtils.getLoginUser().getNickname();
Map<String, List<?>> listMap = apiTypeRealize.apiPlateDataChange(
order,
dataPlates,//板件生产信息
dataParts,// 配件信息
dataBody, // 柜体信息
dataGoods, // 商品信息
plate, // 板件明细
plates, // 板件明细
dataModule,// 加工组信息
block,// 板材数据
dataBlocks,// 板材数据
orderNo,// 原始板编号
orderId,
organId);
@@ -395,7 +385,8 @@ public class OrderServiceImpl implements OrderService {
if (orderDOS != null && orderDOS.size() > 0) {
OrderDO orderDO = orderDOS.get(0);
validateCustomOrderNoExists(orderDO.getCustomOrderNo());
String nickName = SecurityFrameworkUtils.getLoginUser().getNickname();
orderDO.setCreator(nickName).setUpdater(nickName);
if (orderDO.getSalesman() == null || orderDO.getSalesman().equals("")) {
orderDO.setSalesman(nickName);
}
@@ -55,10 +55,9 @@ public class ApiDataAchieve {
@Async
public Future<JSONObject> getApiPlateProData(String token, String orderNo) {
JSONObject jsonPlatesData = new JSONObject();
jsonPlatesData.put("order_no", orderNo);//生产单号需要传入赋值
jsonPlatesData.put("order_no", "N" + orderNo);//生产单号需要传入赋值
jsonPlatesData.put("format", "json");
JSONObject dataPlates = apiDataProduction.getApiOrderMessage(token, jsonPlatesData);
return new AsyncResult<>(dataPlates);
}
@@ -68,10 +67,10 @@ public class ApiDataAchieve {
JSONObject jsonParts = new JSONObject();
jsonParts.put("curr_page", 1);
jsonParts.put("page_count", PARTS_PAGE_MAX);
jsonParts.put("order_no", orderNo);
jsonParts.put("order_no", "N" + orderNo);
JSONObject parts = apiDataProduction.getApiOrderPartsMessage(token, jsonParts);
if (!parts.getString("err_code").equals("0")) {
log.error("配件数据获取错误" + orderNo);
log.error("配件数据获取错误" + "N" + orderNo);
throw exception(PARTS_DATA_ERROR);
}
JSONObject dataParts = new JSONObject();
@@ -89,10 +88,10 @@ public class ApiDataAchieve {
JSONObject jsonBody = new JSONObject();
jsonBody.put("curr_page", 1);
jsonBody.put("page_count", PARTS_PAGE_MAX);
jsonBody.put("order_no", orderNo);
jsonBody.put("order_no", "N" + orderNo);
JSONObject body = apiDataProduction.getApiOrderBodyMessage(token, jsonBody);
if (!body.getString("err_code").equals("0")) {
log.error("柜体数据获取错误" + orderNo);
log.error("柜体数据获取错误" + "N" + orderNo);
throw exception(BODY_DATA_ERROR);
}
JSONObject dataBody = new JSONObject();
@@ -110,10 +109,10 @@ public class ApiDataAchieve {
JSONObject jsonGoods = new JSONObject();
jsonGoods.put("curr_page", 1);
jsonGoods.put("page_count", PARTS_PAGE_MAX);
jsonGoods.put("order_no", orderNo);
jsonGoods.put("order_no", "N" + orderNo);
JSONObject goods = apiDataProduction.getApiOrderGoodsMessage(token, jsonGoods);
if (!goods.getString("err_code").equals("0")) {
log.error("商品信息转换失败" + orderNo);
log.error("商品信息转换失败" + "N" + orderNo);
throw exception(GOODS_DATA_ERROR);
}
JSONObject dataGoods = new JSONObject();
@@ -131,10 +130,10 @@ public class ApiDataAchieve {
JSONObject jsonPlates = new JSONObject();
jsonPlates.put("curr_page", 1);
jsonPlates.put("page_count", PARTS_PAGE_MAX);
jsonPlates.put("order_no", orderNo);
jsonPlates.put("order_no", "N" + orderNo);
JSONObject plates = apiDataProduction.getApiBlocksDataMessage(token, jsonPlates);
if (!plates.getString("err_code").equals("0")) {
log.error("板材明细获取错误" + orderNo);
log.error("板材明细获取错误" + "N" + orderNo);
throw exception(PLATE_DATA_ERROR);
}
JSONObject plate = new JSONObject();
@@ -150,7 +149,7 @@ public class ApiDataAchieve {
@Async
public Future<JSONObject> getApiGroupMessage(String token, String orderNo) {
JSONObject jsonModule = new JSONObject();
jsonModule.put("order_no", orderNo);
jsonModule.put("order_no", "N" + orderNo);
JSONObject dataModule = apiDataProduction.getApiModuleTypeDataMessage(token, jsonModule);
return new AsyncResult<>(dataModule);
}
@@ -161,12 +160,10 @@ public class ApiDataAchieve {
JSONObject jsonBlocks = new JSONObject();
jsonBlocks.put("curr_page", 1);
jsonBlocks.put("page_count", PARTS_PAGE_MAX);
jsonBlocks.put("order_no", orderNo);
jsonBlocks.put("order_no", "N" + orderNo);
JSONObject blocks = apiDataProduction.getApiBlocksMessage(token, jsonBlocks);
if (!blocks.getString("err_code").equals("0")) {
// throw new IllegalArgumentException(String.valueOf(ErrorCodeConstants.PLATE_DATA_ERROR));
log.error("板材数据获取错误" + orderNo);
// throw exception(PLATE_DATA_ERROR);
log.error("板材数据获取错误" + "N" + orderNo);
}
JSONObject block = new JSONObject();
for (int i = 1; i <= blocks.getJSONObject("value").getInteger("PageCount"); i++) {
@@ -52,7 +52,7 @@ spring:
# password: JSm:g(*%lU4ZAkz06cd52KqT3)i1?H7W
slave: # 模拟从库,可根据自己需要修改
name: imes_prod
url: jdbc:mysql://192.168.1.205:8066/${spring.datasource.dynamic.datasource.slave.name}?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例
url: jdbc:mysql://192.168.1.205:3307/${spring.datasource.dynamic.datasource.slave.name}?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例
# url: jdbc:mysql://127.0.0.1:3306/${spring.datasource.dynamic.datasource.slave.name}?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT # MySQL Connector/J 5.X 连接的示例
# url: jdbc:postgresql://127.0.0.1:5432/${spring.datasource.dynamic.datasource.slave.name} # PostgreSQL 连接的示例
# url: jdbc:oracle:thin:@127.0.0.1:1521:xe # Oracle 连接的示例
@@ -42,19 +42,19 @@ public class PlanServiceImplTest extends BaseDbUnitTest {
@Resource
private PlanMapper planMapper;
@Test
public void testCreatePlan_success() {
// 准备参数
PlanSaveReqVO createReqVO = randomPojo(PlanSaveReqVO.class).setId(null);
// 调用
Long planId = planService.createPlan(createReqVO);
// 断言
assertNotNull(planId);
// 校验记录的属性是否正确
PlanDO plan = planMapper.selectById(planId);
assertPojoEquals(createReqVO, plan, "id");
}
// @Test
// public void testCreatePlan_success() {
// // 准备参数
// PlanSaveReqVO createReqVO = randomPojo(PlanSaveReqVO.class).setId(null);
//
// // 调用
// Long planId = planService.createPlan(createReqVO);
// // 断言
// assertNotNull(planId);
// // 校验记录的属性是否正确
// PlanDO plan = planMapper.selectById(planId);
// assertPojoEquals(createReqVO, plan, "id");
// }
@Test
public void testUpdatePlan_success() {
@@ -82,28 +82,28 @@ public class PlanServiceImplTest extends BaseDbUnitTest {
assertServiceException(() -> planService.updatePlan(updateReqVO), PLAN_NOT_EXISTS);
}
@Test
public void testDeletePlan_success() {
// mock 数据
PlanDO dbPlan = randomPojo(PlanDO.class);
planMapper.insert(dbPlan);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbPlan.getId();
// @Test
// public void testDeletePlan_success() {
// // mock 数据
// PlanDO dbPlan = randomPojo(PlanDO.class);
// planMapper.insert(dbPlan);// @Sql: 先插入出一条存在的数据
// // 准备参数
// Long id = dbPlan.getId();
//
// // 调用
// planService.deletePlan(id);
// // 校验数据不存在了
// assertNull(planMapper.selectById(id));
// }
// 调用
planService.deletePlan(id);
// 校验数据不存在了
assertNull(planMapper.selectById(id));
}
@Test
public void testDeletePlan_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> planService.deletePlan(id), PLAN_NOT_EXISTS);
}
// @Test
// public void testDeletePlan_notExists() {
// // 准备参数
// Long id = randomLongId();
//
// // 调用, 并断言异常
// assertServiceException(() -> planService.deletePlan(id), PLAN_NOT_EXISTS);
// }
@Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
@@ -42,21 +42,21 @@ public class RemainPlateController {
@PostMapping("/create")
@Operation(summary = "创建生产单余料板表(单个)")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasAnyPermissions('manage:remain-plate:create','placeorder:optimize')")
public CommonResult<Boolean> createRemainPlate(@Valid @RequestBody RemainPlateSaveReqVO createReqVO) {
return success(remainPlateService.createRemainPlate(createReqVO));
}
@PostMapping("/createMultiple")
@Operation(summary = "创建生产单余料板表(多个)")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasAnyPermissions('manage:remain-plate:create','placeorder:optimize')")
public CommonResult<Boolean> createRemainPlateMultiple(@Valid @RequestBody Set<RemainPlateSaveReqVO> createReqVOS) {
return success(remainPlateService.createRemainPlateMultiple(createReqVOS));
}
@PutMapping("/update")
@Operation(summary = "更新生产单余料板表")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:update')")
public CommonResult<Boolean> updateRemainPlate(@Valid @RequestBody RemainPlateSaveReqVO updateReqVO) {
remainPlateService.updateRemainPlate(updateReqVO);
return success(true);
@@ -64,7 +64,7 @@ public class RemainPlateController {
@PutMapping("/updateStatus")
@Operation(summary = "余料板批量核销")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:update')")
public CommonResult<Boolean> updateRemainPlate(@RequestBody RemainPlateUptReqVO updateReqVO) {
remainPlateService.updateRemainPlateStatus(updateReqVO.getId(),
updateReqVO.getStatus(),
@@ -75,7 +75,7 @@ public class RemainPlateController {
@PutMapping("/revertUpdate")
@Operation(summary = "余料板批量释放")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:update')")
public CommonResult<Boolean> revertRemainPlate(@RequestBody RemainPlateUptReqVO updateReqVO) {
remainPlateService.revertRemainPlateStatus(updateReqVO.getId(),updateReqVO.getStatus());
return success(true);
@@ -84,7 +84,7 @@ public class RemainPlateController {
@DeleteMapping("/delete")
@Operation(summary = "删除生产单余料板表")
@Parameter(name = "id", description = "编号", required = true)
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:delete')")
public CommonResult<Boolean> deleteRemainPlate(@RequestParam("id") Set<Long> ids) {
remainPlateService.deleteRemainPlate(ids);
return success(true);
@@ -93,7 +93,7 @@ public class RemainPlateController {
@GetMapping("/get")
@Operation(summary = "获得生产单余料板表")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:query')")
public CommonResult<RemainPlateRespVO> getRemainPlate(@RequestParam("id") Long id) {
RemainPlateDO remainPlate = remainPlateService.getRemainPlate(id);
return success(BeanUtils.toBean(remainPlate, RemainPlateRespVO.class));
@@ -101,7 +101,7 @@ public class RemainPlateController {
@GetMapping("/page")
@Operation(summary = "获得生产单余料板表分页")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasAnyPermissions('manage:remain-plate:query','placeorder:optimize')")
public CommonResult<PageResult<RemainPlateRespVO>> getRemainPlatePage(@Valid RemainPlatePageReqVO pageReqVO) {
PageResult<RemainPlateDO> pageResult = remainPlateService.getRemainPlatePage(pageReqVO);
return success(BeanUtils.toBean(pageResult, RemainPlateRespVO.class));
@@ -109,7 +109,7 @@ public class RemainPlateController {
@GetMapping("/pageAdd")
@Operation(summary = "获得生产单余料板可添加分页")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:query')")
public CommonResult<PageResult<RemainPlateRespVO>> getRemainPlatePageToAdd(@Valid RemainPlatePageReqVO pageReqVO) {
PageResult<RemainPlateDO> pageResult = remainPlateService.getRemainPlatePageToAdd(pageReqVO);
return success(BeanUtils.toBean(pageResult, RemainPlateRespVO.class));
@@ -117,7 +117,7 @@ public class RemainPlateController {
@GetMapping("/export-excel")
@Operation(summary = "导出生产单余料板表Excel")
@PreAuthorize("@ss.hasPermission('placeorder:remain')")
@PreAuthorize("@ss.hasPermission('manage:remain-plate:export')")
@OperateLog(type = EXPORT)
public void exportRemainPlateExcel(@Valid RemainPlatePageReqVO pageReqVO,
HttpServletResponse response) throws IOException {
@@ -161,5 +161,7 @@ chenfeng:
send-maximum-quantity-per-day: 10
begin-code: 9999 # 这里配置 9999 的原因是,测试方便。
end-code: 9999 # 这里配置 9999 的原因是,测试方便。
encrypt:
enable: false
publicKey: cfimes
debug: false
@@ -175,5 +175,7 @@ chenfeng:
send-maximum-quantity-per-day: 10
begin-code: 9999 # 这里配置 9999 的原因是,测试方便。
end-code: 9999 # 这里配置 9999 的原因是,测试方便。
encrypt:
enable: false
publicKey: cfimes
debug: false
@@ -12,13 +12,14 @@ public final class ErrorCodeConstants {
// ========== UREPORT template模块 1-003-001-000 ==========
public static final ErrorCode TEMPLATE_NOT_EXISTS = new ErrorCode(1_003_001_001, "报表模板信息不存在");
public static final ErrorCode DATATEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR = new ErrorCode(1_003_001_002, "内置模板操作权限不足");
public static final ErrorCode TEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR = new ErrorCode(1_003_001_002, "内置模板操作权限不足");
// ========== UREPORT datasource模块 1-003-002-000 ==========
public static final ErrorCode DATASOURCE_NOT_EXISTS = new ErrorCode(1_003_002_001, "报表数据源不存在");
public static final ErrorCode DATASOURCE_CONNECT_FAIL = new ErrorCode(1_003_002_002, "报表数据源连接失败");
public static final ErrorCode DATASOURCE_SPRINGBEAN_GET_FAIL = new ErrorCode(1_003_002_003, "无法获取springbean【{}】");
public static final ErrorCode DATASOURCE_SPRINGBEAN_METHODS_GET_FAIL = new ErrorCode(1_003_002_004, "获取springbean方法列表失败,请检查】");
public static final ErrorCode DATASOURCE_BUILDIN_OPERATION_PERMISSION_ERROR = new ErrorCode(1_003_001_002, "内置数据源操作权限不足");
// ========== UREPORT dataset模块 1-003-003-000 ==========
@@ -1,6 +1,5 @@
package com.cf.imes.module.report.controller.admin.datasource;
import com.bstek.common.config.DataSourceConfig;
import com.bstek.common.utils.MultipleJdbcTemplate;
import com.bstek.datasource.bean.DataSourceInfo;
import com.bstek.datasource.bean.PreviewParams;
@@ -47,9 +46,6 @@ public class ReportDatasourceController {
@Resource
private ReportDatasourceService datasourceService;
@Resource
private DataSourceConfig dataSourceConfig;
@Resource
private DataSourceService ureportDataSourceService;
@@ -117,12 +113,20 @@ public class ReportDatasourceController {
}
@GetMapping("/buildin/datasources")
@Operation(summary = "获取内置数据源")
@Operation(summary = "获取内置数据源列表")
// @PreAuthorize("@ss.hasPermission('report:datasource:query')")
public CommonResult<List<DataSourceInfo>> getBuildinDatasources() {
return CommonResult.success(dataSourceConfig.getDatasource());
public CommonResult<List<ReportDatasourceDO>> getBuildinDatasources() {
return CommonResult.success(datasourceService.getBuildinDatasourceList());
}
@PostMapping("/buildin/datasources")
@Operation(summary = "保存内置数据源")
public CommonResult<Boolean> saveBuildinDatasources(@Valid @RequestBody @NotEmpty(message = "内置数据源列表不能为空") List<ReportDatasourceSaveReqVO> reportDatasourceDOS) {
datasourceService.saveBuildinDatasources(reportDatasourceDOS);
return CommonResult.success(true);
}
@PostMapping("/datasource/connect")
@Operation(summary = "测试数据源连接")
// @PreAuthorize("@ss.hasPermission('report:datasource:query')")
@@ -28,7 +28,7 @@ public class ReportDatasourceRespVO {
@Schema(description = "数据源名称", example = "测试库")
private String name;
@Schema(description = "数据源类型,jdbc、spring、buildin、api", example = "0")
@Schema(description = "数据源类型,jdbc、spring、api", example = "0")
private Integer type;
@Schema(description = "数据源驱动类",example = "com.mysql.cj.jdbc.Driver")
@@ -2,6 +2,7 @@ package com.cf.imes.module.report.controller.admin.datasource.vo;
import com.cf.imes.module.report.controller.admin.dataset.vo.ReportDatasetSaveReqVO;
import com.cf.imes.module.report.validation.datasource.ReportDatasourceTypeInEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
@@ -36,10 +37,13 @@ public class ReportDatasourceSaveReqVO implements Serializable {
@Schema(description = "数据源名称", example = "测试库")
private String name;
@Schema(description = "数据源类型,jdbc、spring、buildin、api", example = "1")
@Schema(description = "数据源类型,jdbc、spring、api", example = "1")
@ReportDatasourceTypeInEnum
private String type;
@JsonIgnore
private Integer buildinType;
@Schema(description = "spring型数据源id")
private String beanId;
@@ -8,6 +8,7 @@ import com.cf.imes.framework.mybatis.core.dataobject.BaseDO;
import com.cf.imes.framework.mybatis.core.type.CompressObjectListTypeHandler;
import com.cf.imes.module.report.dal.dataobject.dataset.ReportDatasetDO;
import com.cf.imes.module.report.enums.datasource.ReportDatasourceTypeEnum;
import com.cf.imes.module.report.enums.template.ReportTemplateTypeEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@@ -48,10 +49,15 @@ public class ReportDatasourceDO extends BaseDO {
private String name;
/**
* 模板类型,0内置、1自定义
* 数据源类型:jdbc、spring、api
*/
private ReportDatasourceTypeEnum type;
/**
* 内置类型:0是、1否
*/
private ReportTemplateTypeEnum buildinType;
/**
* spring型数据源id
*/
@@ -2,6 +2,7 @@ package com.cf.imes.module.report.dal.mysql.datasource;
import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.module.report.dal.dataobject.datasource.ReportDatasourceDO;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
/**
@@ -12,4 +13,7 @@ import org.apache.ibatis.annotations.Mapper;
*/
@Mapper
public interface ReportDatasourceMapper extends BaseMapperX<ReportDatasourceDO> {
@Delete("DELETE FROM report_datasource WHERE buildin_type = 0")
int physicsDeleteBuildinDatasource();
}
@@ -15,8 +15,7 @@ import lombok.Getter;
public enum ReportDatasourceTypeEnum {
JDBC(0, "jdbc"),
SPRING(1, "spring"),
BUILDIN(2, "buildin"),
API(3, "api");
API(2, "api");
@EnumValue
private final Integer code;
@@ -85,4 +85,18 @@ public interface ReportDatasourceService {
* @return
*/
List<Field> getSpringBeanResultFieldList(String clazz);
/**
* 获取内置数据源列表
*
* @return
*/
List<ReportDatasourceDO> getBuildinDatasourceList();
/**
* 保存内置数据源列表
*
* @param buildinDatasources
*/
void saveBuildinDatasources(List<ReportDatasourceSaveReqVO> buildinDatasources);
}
@@ -17,7 +17,10 @@ import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.security.core.LoginUser;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.report.controller.admin.dataset.vo.ReportDatasetReqVO;
import com.cf.imes.module.report.controller.admin.dataset.vo.ReportDatasetSaveReqVO;
import com.cf.imes.module.report.controller.admin.datasource.vo.ReportBeanDatasourceRespVO;
import com.cf.imes.module.report.controller.admin.datasource.vo.ReportDatasourceReqVO;
import com.cf.imes.module.report.controller.admin.datasource.vo.ReportDatasourceSaveReqVO;
@@ -25,6 +28,7 @@ import com.cf.imes.module.report.dal.dataobject.dataset.ReportDatasetDO;
import com.cf.imes.module.report.dal.dataobject.datasource.ReportDatasourceDO;
import com.cf.imes.module.report.dal.mysql.dataset.ReportDatasetMapper;
import com.cf.imes.module.report.dal.mysql.datasource.ReportDatasourceMapper;
import com.cf.imes.module.report.enums.template.ReportTemplateTypeEnum;
import com.cf.imes.module.report.framework.ureport.annotation.CfReportSpringbeanDatasource;
import com.cf.imes.module.report.service.dataset.ReportDatasetService;
import com.cf.imes.module.report.util.SqlInjectionUtil;
@@ -55,6 +59,7 @@ import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASET_GET_FIE
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASET_SQL_ILLEGAL;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASET_SQL_INJECTION_RISK;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASET_SQL_REQUIRED;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASOURCE_BUILDIN_OPERATION_PERMISSION_ERROR;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASOURCE_NOT_EXISTS;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASOURCE_SPRINGBEAN_GET_FAIL;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATASOURCE_SPRINGBEAN_METHODS_GET_FAIL;
@@ -113,17 +118,6 @@ public class ReportDatasourceServiceImpl implements ReportDatasourceService {
datasetMapper.delete(new LambdaQueryWrapperX<ReportDatasetDO>().eq(ReportDatasetDO::getDatasourceId, id));
}
/**
* 校验数据源是否存在
*
* @param id
*/
private void validateDatasourceExists(Long id) {
if (datasourceMapper.selectById(id) == null) {
throw exception(DATASOURCE_NOT_EXISTS);
}
}
@Override
public ReportDatasourceDO getDatasource(Long id) {
ReportDatasourceDO reportDatasourceDO = datasourceMapper.selectById(id);
@@ -278,6 +272,52 @@ public class ReportDatasourceServiceImpl implements ReportDatasourceService {
}
}
@Override
public List<ReportDatasourceDO> getBuildinDatasourceList() {
List<ReportDatasourceDO> reportDatasourceDOS = datasourceMapper.selectList(new LambdaQueryWrapperX<ReportDatasourceDO>()
.eqIfPresent(ReportDatasourceDO::getBuildinType, ReportTemplateTypeEnum.SYSTEM)
.orderByDesc(ReportDatasourceDO::getCreateTime));
// 查询数据集
if (CollUtil.isNotEmpty(reportDatasourceDOS)) {
reportDatasourceDOS.forEach(reportDatasourceDO -> {
queryDatasetInSource(reportDatasourceDO);
});
}
return reportDatasourceDOS;
}
@Override
public void saveBuildinDatasources(List<ReportDatasourceSaveReqVO> buildinDatasources) {
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
boolean isSuperAdmin = loginUser != null && loginUser.getIsSupAdmin();
// 非超管不能操作内置模板
if (!isSuperAdmin) {
throw exception(DATASOURCE_BUILDIN_OPERATION_PERMISSION_ERROR);
}
// 全删内置数据源
int deleteNum = datasourceMapper.physicsDeleteBuildinDatasource();
log.info("[ReportDatasourceService][saveBuildinDatasources]删除内置数据源{}条", deleteNum);
buildinDatasources.forEach(ds -> {
// 新增数据源
ds.setBuildinType(ReportTemplateTypeEnum.SYSTEM.getType());
ds.setId(null);
Long datasourceId = createDatasource(ds);
List<ReportDatasetSaveReqVO> datasets = ds.getDatasets();
List<ReportDatasetSaveReqVO> batchInsertDataset = new ArrayList<>();
datasets.forEach(dataset -> {
// 新增数据集
dataset.setDatasourceId(datasourceId);
dataset.setId(null);
batchInsertDataset.add(dataset);
});
// 批量插入数据集
if (CollUtil.isNotEmpty(batchInsertDataset)) {
datasetService.batchCreateDataset(batchInsertDataset);
}
});
}
/**
* 查询数据源下的数据集
*
@@ -290,4 +330,15 @@ public class ReportDatasourceServiceImpl implements ReportDatasourceService {
reportDatasourceDO.setDatasets(datasetList);
}
}
/**
* 校验数据源是否存在
*
* @param id
*/
private void validateDatasourceExists(Long id) {
if (datasourceMapper.selectById(id) == null) {
throw exception(DATASOURCE_NOT_EXISTS);
}
}
}
@@ -69,7 +69,7 @@ import java.util.Map;
import java.util.Objects;
import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.DATATEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.TEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR;
import static com.cf.imes.module.report.enums.ErrorCodeConstants.TEMPLATE_NOT_EXISTS;
/**
@@ -261,7 +261,7 @@ public class ReportTemplateServiceImpl implements ReportTemplateService {
boolean isSuperAdmin = loginUser != null && loginUser.getIsSupAdmin();
// 非超管不能操作内置模板
if (ReportTemplateTypeEnum.SYSTEM.equals(templateDO.getType()) && !isSuperAdmin) {
throw exception(DATATEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR);
throw exception(TEMPLATE_BUILDIN_OPERATION_PERMISSION_ERROR);
}
}
@@ -336,7 +336,7 @@ public class ReportTemplateServiceImpl implements ReportTemplateService {
// 忽略转换的字段名,手动转列表
String ignorePropertieName = "datasets";
switch (ds.getType()) {
case JDBC, BUILDIN -> {
case JDBC -> {
// 转换对应的ureport对象
JdbcDatasourceDefinition jdbcDatasourceDefinition = BeanUtil.copyProperties(ds, JdbcDatasourceDefinition.class, ignorePropertieName);
datasetDefinitions.addAll(BeanUtils.toBean(datasetList, SqlDatasetDefinition.class));
@@ -28,7 +28,7 @@ import java.lang.annotation.Target;
validatedBy = {ReportDatasourceTypeInEnumValidator.class}
)
public @interface ReportDatasourceTypeInEnum {
String message() default "数据源类型[type]错误,请检查是否jdbc/spring/buildin/api";
String message() default "数据源类型[type]错误,请检查是否jdbc/spring/api";
Class<?>[] groups() default {};
@@ -28,7 +28,7 @@ import java.lang.annotation.Target;
validatedBy = {ReportTemplateTypeInEnumValidator.class}
)
public @interface ReportTemplateTypeInEnum {
String message() default "类型[type]错误,请检查是否0(内置)/1(自定义)";
String message() default "类型错误,请检查是否0(内置)/1(自定义)";
Class<?>[] groups() default {};
@@ -21,6 +21,9 @@ public class ReportTemplateTypeInEnumValidator implements ConstraintValidator<Re
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if (ObjectUtil.isNull(value)) {
return false;
}
ReportTemplateTypeEnum byType = ReportTemplateTypeEnum.fromType(value);
if (ObjectUtil.isNotNull(byType)) {
return true;
@@ -103,6 +103,8 @@ chenfeng:
organ: # 多租户相关配置项
enable: true
ignore-tables:
encrypt:
enable: false
publicKey: cfimes
debug: false