diff --git a/blade-biz-common/src/main/java/org/springblade/common/constant/factorydata/FactoryDataConstants.java b/blade-biz-common/src/main/java/org/springblade/common/constant/factorydata/FactoryDataConstants.java index 043da032f..d73575d69 100644 --- a/blade-biz-common/src/main/java/org/springblade/common/constant/factorydata/FactoryDataConstants.java +++ b/blade-biz-common/src/main/java/org/springblade/common/constant/factorydata/FactoryDataConstants.java @@ -12,6 +12,11 @@ public abstract class FactoryDataConstants { String DELAYED = "true"; + /** + * 如果不需要 "" + */ + String DEVAUTH = ""; + /** * 定义交换机 */ @@ -20,19 +25,19 @@ public abstract class FactoryDataConstants { /** * 作业节点数据推送 */ - String NODE_DATA_PUSH = "factory.data.exchange.topic.nodeDataPush"; + String NODE_DATA_PUSH = "factory.data.exchange.topic.nodeDataPush" + DEVAUTH; /** * 推送节点数据延时推送 */ - String NODE_DATA_PUSH_DELAYED = "factory.data.exchange.topic.nodeDataPushDelayed"; + String NODE_DATA_PUSH_DELAYED = "factory.data.exchange.topic.nodeDataPushDelayed" + DEVAUTH; /** * 工厂订单数据 */ - String FACTORY_ORDER = "factory.data.exchange.topic.factoryOrder"; + String FACTORY_ORDER = "factory.data.exchange.topic.factoryOrder" + DEVAUTH; /** * 工厂数据转暂存单 */ - String ADVANCE_ORDER = "factory.data.exchange.topic.advanceOrder"; + String ADVANCE_ORDER = "factory.data.exchange.topic.advanceOrder" + DEVAUTH; } @@ -45,37 +50,37 @@ public abstract class FactoryDataConstants { /** * 工厂数据转暂存单 */ - String ADVANCE_ORDER = "factory.data.queue.advanceOrder"; + String ADVANCE_ORDER = "factory.data.queue.advanceOrder" + DEVAUTH; /** * 志邦作业节点数据推送 */ - String ZBOM_NODE_DATA_PUSH = "factory.data.queue.zbom.nodeDataPush"; - String ZBOM_FACTORY_ORDER = "factory.data.queue.zbom.factoryOrder"; + String ZBOM_NODE_DATA_PUSH = "factory.data.queue.zbom.nodeDataPush" + DEVAUTH; + String ZBOM_FACTORY_ORDER = "factory.data.queue.zbom.factoryOrder" + DEVAUTH; /** * 索菲亚工厂订单 */ - String SFY_FACTORY_ORDER = "factory.data.queue.sfy.factoryOrder"; + String SFY_FACTORY_ORDER = "factory.data.queue.sfy.factoryOrder" + DEVAUTH; /** * 我乐工厂订单 */ - String OLO_FACTORY_ORDER = "factory.data.queue.olo.factoryOrder"; + String OLO_FACTORY_ORDER = "factory.data.queue.olo.factoryOrder" + DEVAUTH; /** * 金牌工厂订单 */ - String JP_FACTORY_ORDER = "factory.data.queue.jp.factoryOrder"; + String JP_FACTORY_ORDER = "factory.data.queue.jp.factoryOrder" + DEVAUTH; /** * 皮阿诺作业节点数据推送 */ - String PIANO_NODE_DATA_PUSH = "factory.data.queue.piano.nodeDataPush"; + String PIANO_NODE_DATA_PUSH = "factory.data.queue.piano.nodeDataPush" + DEVAUTH; /** * 梦天作业节点数据推送 */ - String MENGTIAN_NODE_DATA_PUSH = "factory.data.queue.mengtian.nodeDataPush"; + String MENGTIAN_NODE_DATA_PUSH = "factory.data.queue.mengtian.nodeDataPush" + DEVAUTH; /** * 欧派作业节点数据推送 */ - String OPPEIN_NODE_DATA_PUSH = "factory.data.queue.oppein.nodeDataPush"; + String OPPEIN_NODE_DATA_PUSH = "factory.data.queue.oppein.nodeDataPush" + DEVAUTH; } /** @@ -85,36 +90,36 @@ public abstract class FactoryDataConstants { /** * 工厂数据转暂存单 */ - String ADVANCE_ORDER = "advanceOrder"; + String ADVANCE_ORDER = "advanceOrder" + DEVAUTH; /** * 志邦作业节点数据推送 */ - String ZBOM_NODE_DATA_PUSH = "zbom.nodeDataPush"; - String ZBOM_FACTORY_ORDER = "zbom.factoryOrder"; + String ZBOM_NODE_DATA_PUSH = "zbom.nodeDataPush" + DEVAUTH; + String ZBOM_FACTORY_ORDER = "zbom.factoryOrder" + DEVAUTH; /** * 索菲亚工厂订单 */ - String SFY_FACTORY_ORDER = "sfy.factoryOrder"; + String SFY_FACTORY_ORDER = "sfy.factoryOrder" + DEVAUTH; /** * 我乐工厂订单 */ - String OLO_FACTORY_ORDER = "olo.factoryOrder"; + String OLO_FACTORY_ORDER = "olo.factoryOrder" + DEVAUTH; /** * 金牌工厂订单 */ - String JP_FACTORY_ORDER = "jp.factoryOrder"; + String JP_FACTORY_ORDER = "jp.factoryOrder" + DEVAUTH; /** * 皮阿诺作业节点数据推送 */ - String PIANO_NODE_DATA_PUSH = "piano.nodeDataPush"; + String PIANO_NODE_DATA_PUSH = "piano.nodeDataPush" + DEVAUTH; /** * 梦天作业节点数据推送 */ - String MENGTIAN_NODE_DATA_PUSH = "mengtian.nodeDataPush"; + String MENGTIAN_NODE_DATA_PUSH = "mengtian.nodeDataPush" + DEVAUTH; /** * 欧派作业节点数据推送 */ - String OPPEIN_NODE_DATA_PUSH = "oppein.nodeDataPush"; + String OPPEIN_NODE_DATA_PUSH = "oppein.nodeDataPush" + DEVAUTH; } } diff --git a/blade-service-api/logpm-factory-data-api/src/main/java/com/logpm/factorydata/enums/BrandEnums.java b/blade-service-api/logpm-factory-data-api/src/main/java/com/logpm/factorydata/enums/BrandEnums.java index e15b14363..1f04ee1a7 100644 --- a/blade-service-api/logpm-factory-data-api/src/main/java/com/logpm/factorydata/enums/BrandEnums.java +++ b/blade-service-api/logpm-factory-data-api/src/main/java/com/logpm/factorydata/enums/BrandEnums.java @@ -17,7 +17,7 @@ public enum BrandEnums implements Serializable { ZB(1, "志邦"), SNM(2, "诗尼曼"), PAN(3, "皮阿诺"), - MTMM(4, "梦天木门"), + MTMM(4, "梦天"), OP(5, "欧派"), SFY(6, "索菲亚"), JP(7, "金牌"), diff --git a/blade-service-api/logpm-trunkline-api/src/main/java/com/logpm/trunkline/entity/TrunklineAdvanceEntity.java b/blade-service-api/logpm-trunkline-api/src/main/java/com/logpm/trunkline/entity/TrunklineAdvanceEntity.java index 3b22b75be..e490d3e59 100644 --- a/blade-service-api/logpm-trunkline-api/src/main/java/com/logpm/trunkline/entity/TrunklineAdvanceEntity.java +++ b/blade-service-api/logpm-trunkline-api/src/main/java/com/logpm/trunkline/entity/TrunklineAdvanceEntity.java @@ -54,7 +54,7 @@ public class TrunklineAdvanceEntity extends TenantEntity { /** 订单总数 */ @ApiModelProperty(name = "订单总数",notes = "") private Integer totalNum ; - /** 订单总数 */ + /** 是否干仓配 */ @ApiModelProperty(name = "是否干仓配",notes = "") private Integer isGcp ; /** 品名 */ diff --git a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/java/com/logpm/factorydata/base/feign/FactoryDataBaseClient.java b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/java/com/logpm/factorydata/base/feign/FactoryDataBaseClient.java index ed6498a4f..9e2860d06 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/java/com/logpm/factorydata/base/feign/FactoryDataBaseClient.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/java/com/logpm/factorydata/base/feign/FactoryDataBaseClient.java @@ -12,6 +12,7 @@ import com.logpm.factorydata.base.service.FactoryWarehouseBindService; import com.logpm.factorydata.base.vo.FactoryWarehouseBindVO; import lombok.AllArgsConstructor; import org.springblade.core.redis.cache.BladeRedis; +import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tool.api.R; import org.springframework.web.bind.annotation.RestController; @@ -43,6 +44,7 @@ public class FactoryDataBaseClient implements IFactoryDataBaseClient { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(FactoryWarehouseBindEntity::getBrand, brand); queryWrapper.eq(FactoryWarehouseBindEntity::getSiteName, siteName); + String tenantId = AuthUtil.getTenantId(); List warehouseList = bindService.list(queryWrapper); if (CollUtil.isNotEmpty(warehouseList)) { FactoryWarehouseBindEntity entity = warehouseList.get(0); diff --git a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-dev.yml b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-dev.yml index 799bda9d3..64d569938 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-dev.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-dev.yml @@ -68,4 +68,6 @@ spring: url: ${blade.datasource.factorydata-base.627683.url} username: ${blade.datasource.factorydata-base.627683.username} password: ${blade.datasource.factorydata-base.627683.password} - +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-prod.yml b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-prod.yml index 2c57bcc0c..203dc5d1b 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-prod.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-prod.yml @@ -33,13 +33,15 @@ spring: url: ${blade.datasource.report.master.url} username: ${blade.datasource.report.master.username} password: ${blade.datasource.report.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.report.slave.url} - username: ${blade.datasource.report.slave.username} - password: ${blade.datasource.report.slave.password} - + url: ${blade.datasource.report.627683.url} + username: ${blade.datasource.report.627683.username} + password: ${blade.datasource.report.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-test.yml b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-test.yml index 6b951cc09..0e63c1a97 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-test.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-base/src/main/resources/application-test.yml @@ -59,13 +59,15 @@ spring: url: ${blade.datasource.factorydata-base.master.url} username: ${blade.datasource.factorydata-base.master.username} password: ${blade.datasource.factorydata-base.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-base.slave.url} - username: ${blade.datasource.factorydata-base.slave.username} - password: ${blade.datasource.factorydata-base.slave.password} - + url: ${blade.datasource.factorydata-base.627683.url} + username: ${blade.datasource.factorydata-base.627683.username} + password: ${blade.datasource.factorydata-base.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/pom.xml b/blade-service/logpm-factory-data/logpm-factory-data-olo/pom.xml index a3f8fa1a4..a995a3f8b 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/pom.xml +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/pom.xml @@ -68,6 +68,7 @@ 3.2.0.RELEASE compile + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/aspect/AnnotationAspect.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/aspect/AnnotationAspect.java index b5a9dc38d..76f6235b2 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/aspect/AnnotationAspect.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/aspect/AnnotationAspect.java @@ -4,13 +4,49 @@ import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; import org.springblade.core.secure.utils.AuthUtil; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; +import java.lang.reflect.Method; + @Aspect @Component public class AnnotationAspect { + /** + * 定义一个切点,匹配所有带有@Async("asyncExecutor")注解的方法。 + * 注意:实际上Spring Framework自带对@Async("asyncExecutor")的处理,直接这样配置可能会导致预期之外的行为。 + */ + @Around("@annotation(org.springframework.scheduling.annotation.Async)") + public Object asyncAroundAsyncMethods(ProceedingJoinPoint joinPoint) throws Throwable { + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + + Async myAsync = method.getAnnotation(Async.class); + String annotationValue = myAsync.value(); + + if(StringUtil.isNotBlank(annotationValue) && annotationValue.equals("asyncExecutor")){ + // 在方法执行前的操作 + String tenantId = AuthUtil.getTenantId(); + DynamicDataSourceContextHolder.push(tenantId); + + // 执行原方法 + Object result = joinPoint.proceed(); + + // 在方法执行后的操作 + DynamicDataSourceContextHolder.poll(); + + return result; + }else{ + return joinPoint.proceed(); + } + + } + /** * 该方法为一个切面,用于对标记了@RabbitListener注解的方法进行增强,主要增加了日志记录和数据源上下文处理的功能。 * diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/ExecutorConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/ExecutorConfig.java new file mode 100644 index 000000000..4d12cb748 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/ExecutorConfig.java @@ -0,0 +1,79 @@ +package com.logpm.factorydata.olo.config; + +import lombok.extern.slf4j.Slf4j; +import org.slf4j.MDC; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskDecorator; +import org.springframework.http.HttpHeaders; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@Slf4j +@EnableAsync +public class ExecutorConfig { + + @Bean + public Executor asyncExecutor() { + log.info("start async executor"); + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); +// 配置核心线程数 + threadPoolTaskExecutor.setCorePoolSize(10); +// 配置最大线程数 + threadPoolTaskExecutor.setMaxPoolSize(20); +// 配置队列大小 + threadPoolTaskExecutor.setQueueCapacity(50); +// 配置线程池中线程的名称前缀 + threadPoolTaskExecutor.setThreadNamePrefix("ASYNC_THREAD_"); +// HelloWorldServiceImpl rejection-policy: 当pool已经达到max size时,如何处理新任务: +// CallerRunsPolicy: 不在新线程中执行任务,而是由调用者所在的线程来执行; +// AbortPolicy: 拒绝执行新任务,并抛出RejectedExecutionException异常; +// DiscardPolicy:丢弃当前将要加入队列的任务; +// DiscardOldestPolicy:丢弃任务队列中最旧的任务; + threadPoolTaskExecutor.setRejectedExecutionHandler( + new ThreadPoolExecutor.CallerRunsPolicy() + ); + threadPoolTaskExecutor.setTaskDecorator(new ContextCopyingDecorator()); + threadPoolTaskExecutor.initialize(); + return threadPoolTaskExecutor; + } + + + static class ContextCopyingDecorator implements TaskDecorator { + @Nonnull + @Override + public Runnable decorate(@Nonnull Runnable runnable) { + RequestAttributes context = RequestContextHolder.currentRequestAttributes(); + HttpHeaders headers = (HttpHeaders) ThreadLocalUtil.get("bladeContext"); + Map mdcMap = MDC.getCopyOfContextMap(); + return () -> { + try { + ThreadLocalUtil.put("bladeContext", headers); + if (mdcMap != null && !mdcMap.isEmpty()) { + MDC.setContextMap(mdcMap); + } + RequestContextHolder.setRequestAttributes(context); + + runnable.run(); + } finally { + RequestContextHolder.resetRequestAttributes(); + if (mdcMap != null) { + mdcMap.clear(); + } + ThreadLocalUtil.clear(); + MDC.clear(); + } + }; + } + } + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/InterceptorAdapterConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/InterceptorAdapterConfig.java new file mode 100644 index 000000000..1662e1839 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/config/InterceptorAdapterConfig.java @@ -0,0 +1,32 @@ +package com.logpm.factorydata.olo.config; + +import com.logpm.factorydata.olo.interceptor.FactoryAccountsInterceptor; +import com.logpm.factorydata.olo.interceptor.LocalServerLoginAccountsInterceptor; +import com.logpm.factorydata.olo.service.IFactoryTokenService; +import lombok.AllArgsConstructor; +import org.springblade.core.redis.cache.BladeRedis; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@AllArgsConstructor +public class InterceptorAdapterConfig implements WebMvcConfigurer { + + private final IFactoryTokenService factoryTokenService; + + private final BladeRedis redis; + + private final Environment environment; + + + @Override + public void addInterceptors(InterceptorRegistry interceptorRegistry) { +// interceptorRegistry.addInterceptor(new FactoryAccountsInterceptor(factoryTokenService)) +// .addPathPatterns("/**").order(1); + interceptorRegistry.addInterceptor(new LocalServerLoginAccountsInterceptor(redis, environment)) + .addPathPatterns("/**").order(2); + + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/controller/OrderController.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/controller/OrderController.java index 50ef271a2..224fd9b22 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/controller/OrderController.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/controller/OrderController.java @@ -18,6 +18,7 @@ import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * 工厂订单 前端控制器 @@ -40,7 +41,8 @@ public class OrderController { @ApiOperation(value = "工厂订单", notes = "工厂订单") public R order(@RequestBody List> param) { log.info("接收工厂订单:{} ", JSONUtil.toJsonStr(param)); - List vos = BeanUtil.toBean(param, List.class); + // 将param转成List + List vos = param.stream().map(p -> BeanUtil.toBean(p, DeliveryNoteVO.class)).collect(Collectors.toList()); String res = ""; try { res = service.order(vos); diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/DeliveryNoteEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/DeliveryNoteEntity.java index 204b91e91..deddb4273 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/DeliveryNoteEntity.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/DeliveryNoteEntity.java @@ -24,7 +24,7 @@ public class DeliveryNoteEntity extends BaseEntity { @ApiModelProperty(name = "发运汇总单号") private String shipmentNo; @ApiModelProperty(name = "发运分单号") - private String shipmentSpliNo; + private String shipmentSplitNo; @ApiModelProperty(name = "顾客姓名") private String endingCustomer; @ApiModelProperty(name = "顾客地址") diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/FactoryToken.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/FactoryToken.java new file mode 100644 index 000000000..c48f02a93 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/entity/FactoryToken.java @@ -0,0 +1,32 @@ +package com.logpm.factorydata.olo.entity; + +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 org.springblade.core.mp.base.BaseEntity; + +import java.util.Date; + +@Data +@TableName("factory_token") +@ApiModel(value = "FactoryToken对象", description = "工厂账户token") +public class FactoryToken extends BaseEntity { + + @ApiModelProperty("token") + private String token; + + @ApiModelProperty("token摘要") + private String tokenAbst; + + @JsonFormat( + pattern = "yyyy-MM-dd HH:mm:ss" + ) + @ApiModelProperty("过期时间") + private Date expireTime; + + @ApiModelProperty("企业id") + private String corpid; + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/FactoryAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/FactoryAccountsInterceptor.java new file mode 100644 index 000000000..119aa1bb2 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/FactoryAccountsInterceptor.java @@ -0,0 +1,87 @@ +package com.logpm.factorydata.olo.interceptor; + +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.olo.service.IFactoryTokenService; +import com.logpm.factorydata.olo.wrapper.RequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@Log4j2 +@AllArgsConstructor +public class FactoryAccountsInterceptor implements HandlerInterceptor { + + private final IFactoryTokenService factoryTokenService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + try { + + RequestWrapper myRequestWrapper = new RequestWrapper(request); + String body = myRequestWrapper.getBody(); + JSONObject jsonObject = JSONObject.parseObject(body); + //获取头中参数 + String token = request.getHeader("Authorization"); + String corpId = request.getHeader("corpid"); + if(StringUtil.isBlank(corpId)){ + corpId = jsonObject.getString("corpid"); + } + if(!StringUtil.hasLength(token)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token有误"))); + return false; + } + if(!StringUtil.hasLength(corpId)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,corpId有误"))); + return false; + } + + log.info("##########preHandle: token={}",token); + //验证token + boolean b = factoryTokenService.verifyToken(token,corpId); + if(!b){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token不存在或已过期"))); + return false; + } + return true; + } catch (Exception e) { + returnJson(response,JSONObject.toJSONString(R.fail(500,"服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null){ + writer.close(); + } + } + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + HandlerInterceptor.super.afterCompletion(request, response, handler, ex); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/LocalServerLoginAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/LocalServerLoginAccountsInterceptor.java new file mode 100644 index 000000000..be5af954f --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/interceptor/LocalServerLoginAccountsInterceptor.java @@ -0,0 +1,100 @@ +package com.logpm.factorydata.olo.interceptor; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.olo.wrapper.CustomHttpServletRequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.cache.CacheNames; +import org.springblade.common.constant.LauncherConstant; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.redis.cache.BladeRedis; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@Log4j2 +@AllArgsConstructor +public class LocalServerLoginAccountsInterceptor extends HandlerInterceptorAdapter { + + private final BladeRedis bladeRedis; + private final Environment environment; + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + + + try { + CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(request); + String account ="shujutongbu"; + JSONObject data =bladeRedis.get(CacheNames.LOCAL_SERVER_USER+account); + if(Objects.isNull(data)){ + String url = "http://"+ LauncherConstant.loginAddr(Objects.requireNonNull(environment.getActiveProfiles()[0]))+"/blade-auth/oauth/token"; + HttpRequest urlRequest = HttpRequest.post(url); + urlRequest.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + urlRequest.header("Tenant-Id", "627683"); + + Map params = new HashMap<>(); + params.put("grant_type", "local_server"); + params.put("scope", "all"); + params.put("username", account); + params.put("tenantId", "627683"); + HttpResponse execute = urlRequest.form(params).execute(); + String body = execute.body(); + data = JSONObject.parseObject(body); + bladeRedis.setEx(CacheNames.LOCAL_SERVER_USER+account,data,3200L); + } + + // 修改或添加header + + // 发送登录请求 + log.info("##########preHandle: request={}", request); + + wrappedRequest.addHeader("Blade-Auth", "bearer "+data.getString("access_token")); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Blade-Auth","bearer "+data.get("access_token") ); + httpHeaders.add( "Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + ThreadLocalUtil.put("bladeContext", httpHeaders); + + + // 用包装后的request替换原始request + request = wrappedRequest; + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + return true; + } catch (Exception e) { + returnJson(response, JSONObject.toJSONString(R.fail(500, "服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.java new file mode 100644 index 000000000..30511083f --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the dreamlu.net developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: Chill 庄骞 (smallchill@163.com) + */ +package com.logpm.factorydata.olo.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.logpm.factorydata.olo.entity.FactoryToken; + +/** + * 工厂账号接口日志 Mapper 接口 + * + * @author zhy + * @since 2023-03-28 + */ +public interface FactoryTokenMapper extends BaseMapper { + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.xml b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.xml new file mode 100644 index 000000000..a803123c1 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mapper/FactoryTokenMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mq/FactoryOrderListener.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mq/FactoryOrderListener.java index 9580e5945..b697f2d21 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mq/FactoryOrderListener.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/mq/FactoryOrderListener.java @@ -9,18 +9,20 @@ import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; +import cn.hutool.json.JSONArray; +import cn.hutool.json.JSONConfig; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.logpm.factorydata.base.feign.IFactoryDataBaseClient; import com.logpm.factorydata.base.vo.FactoryWarehouseBindVO; import com.logpm.factorydata.enums.BrandEnums; +import com.logpm.factorydata.enums.SaxStatusEnums; import com.logpm.factorydata.feign.IFactoryDataClient; import com.logpm.factorydata.olo.entity.DeliveryNoteEntity; import com.logpm.factorydata.olo.entity.FactoryOrderLogEntity; import com.logpm.factorydata.olo.service.DeliveryNoteService; import com.logpm.factorydata.olo.service.FactoryOrderLogService; -import com.logpm.factorydata.olo.util.ThreadPoolUtil; import com.logpm.factorydata.olo.vo.DeliveryNoteVO; import com.logpm.factorydata.vo.SendMsg; import com.logpm.trunkline.entity.TrunklineAdvanceDetailEntity; @@ -36,6 +38,7 @@ import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -91,7 +94,9 @@ public class FactoryOrderListener { if (CollUtil.isNotEmpty(res)) { String content = res.get(0); if (StrUtil.isNotEmpty(content)) { - vos = JSONUtil.toBean(content, List.class); + JSONConfig config = new JSONConfig(); + config.setIgnoreCase(Boolean.TRUE); + vos = new JSONArray(content, config).toList(DeliveryNoteVO.class); } } } @@ -127,7 +132,7 @@ public class FactoryOrderListener { DeliveryNoteEntity entity = new DeliveryNoteEntity(); entity.setLogId(ObjectUtil.isNotEmpty(logId) ? logId.toString() : null); entity.setShipmentNo(vo.getSHIPMENT_NO()); - entity.setShipmentSpliNo(vo.getSHIPMENT_SPLIT_NO()); + entity.setShipmentSplitNo(vo.getSHIPMENT_SPLIT_NO()); entity.setEndingCustomer(vo.getENDING_CUSTOMER()); entity.setZgkdz(vo.getZGKDZ()); entity.setEndingCustomerTel(vo.getENDING_CUSTOMER_TEL()); @@ -160,13 +165,18 @@ public class FactoryOrderListener { deliveryNoteService.saveBatch(entities); // 处理暂存单 buildAdvance(entities); + FactoryOrderLogEntity logEntity1 = new FactoryOrderLogEntity(); + logEntity1.setSaxStatus(SaxStatusEnums.SUCCESS.getCode()); + logEntity1.setId(logId); + logService.saveOrUpdate(logEntity1); } } } - private void buildAdvance(List vos) { + @Async("asyncExecutor") + public void buildAdvance(List vos) { // 新起线程构建暂存单发送mq - ThreadPoolUtil.getThreadPool().submit(() -> { +// ThreadPoolUtil.getThreadPool().submit(() -> { Long startWarehouseId = null; String startWarehouseName = null; String tenantId = null; @@ -208,20 +218,21 @@ public class FactoryOrderListener { advanceEntity.setSiteName(""); advanceEntity.setArea(""); advanceEntity.setTotalNum(CollUtil.isNotEmpty(value) ? value.size() : 0); - advanceEntity.setPackName(""); + advanceEntity.setPackCode(""); advanceEntity.setWarehouseId(startWarehouseId); advanceEntity.setWarehouseName(startWarehouseName); advanceEntity.setIsGcp(0); - advanceEntity.setSystemType("线下"); - advanceEntity.setMatingType(""); + advanceEntity.setSystemType("线上"); + advanceEntity.setMatingType("1"); advanceEntity.setWaybillStatus("0"); advanceEntity.setWaybillNo(""); advanceEntity.setFreezeStatus("0"); List packageList = new ArrayList<>(); for (DeliveryNoteEntity orderPackageDTO : value) { + advanceEntity.setPackName(orderPackageDTO.getSpace()); advanceEntity.setCarrierName(orderPackageDTO.getCarrierName()); advanceEntity.setSenderName(""); advanceEntity.setSenderPhone(""); @@ -233,7 +244,7 @@ public class FactoryOrderListener { advanceEntity.setDealerName(orderPackageDTO.getCustomerName()); advanceEntity.setStoreCode(orderPackageDTO.getCustomerCode()); advanceEntity.setStoreName(orderPackageDTO.getCustomerName()); - advanceEntity.setServiceNum(orderPackageDTO.getShipmentSpliNo()); + advanceEntity.setServiceNum(orderPackageDTO.getShipmentSplitNo()); advanceEntity.setCustomerName(orderPackageDTO.getEndingCustomer()); advanceEntity.setCustomerPhone(orderPackageDTO.getEndingCustomerTel()); advanceEntity.setCustomerAddress(orderPackageDTO.getZgkdz()); @@ -252,7 +263,7 @@ public class FactoryOrderListener { advanceDetailEntity.setOrderCode(orderPackageDTO.getCrmSo()); advanceDetailEntity.setBrand(BrandEnums.OLO.getValue()); - advanceDetailEntity.setSystemType("线下"); + advanceDetailEntity.setSystemType("线上"); advanceDetailEntity.setFirstPackName(orderPackageDTO.getMaterialCategory()); // 获取映射志邦映射品类信息 //二级品类名称 @@ -266,7 +277,7 @@ public class FactoryOrderListener { advanceDetailEntity.setQuantity((StrUtil.isNotBlank(orderPackageDTO.getQty()) && NumberUtil.isNumber(orderPackageDTO.getQty())) ? Convert.toInt(orderPackageDTO.getQty()) : 0); advanceDetailEntity.setOrderPackageCode(orderPackageDTO.getSn()); advanceDetailEntity.setTrainNumber(orderPackageDTO.getShipmentNo()); - advanceDetailEntity.setServiceNum(orderPackageDTO.getShipmentSpliNo()); + advanceDetailEntity.setServiceNum(orderPackageDTO.getShipmentSplitNo()); advanceDetailEntity.setWaybillNo(""); advanceDetailEntity.setPackageStatus("0"); advanceDetailEntity.setWeight(StrUtil.isNotBlank(orderPackageDTO.getSnWeight()) ? new BigDecimal(orderPackageDTO.getSnWeight()) : BigDecimal.ZERO); @@ -297,7 +308,7 @@ public class FactoryOrderListener { factoryDataClient.sendMessage(sendMsg); } } - }); +// }); } diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/IFactoryTokenService.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/IFactoryTokenService.java new file mode 100644 index 000000000..ef703922b --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/IFactoryTokenService.java @@ -0,0 +1,15 @@ +package com.logpm.factorydata.olo.service; + +import com.logpm.factorydata.olo.entity.FactoryToken; +import org.springblade.core.mp.base.BaseService; + +import java.security.NoSuchAlgorithmException; + +/** + * 工厂推送数据接口 + */ +public interface IFactoryTokenService extends BaseService { + + + boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException; +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/DeliveryNoteServiceImpl.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/DeliveryNoteServiceImpl.java index 51f34a21c..1d72b9cdf 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/DeliveryNoteServiceImpl.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/DeliveryNoteServiceImpl.java @@ -2,7 +2,6 @@ package com.logpm.factorydata.olo.service.impl; import cn.hutool.core.io.FileUtil; import cn.hutool.json.JSONUtil; -import com.alibaba.fastjson.JSONObject; import com.logpm.factorydata.enums.SaxStatusEnums; import com.logpm.factorydata.feign.IFactoryDataClient; import com.logpm.factorydata.olo.entity.DeliveryNoteEntity; @@ -24,6 +23,7 @@ import org.springblade.core.mp.base.BaseServiceImpl; import org.springblade.core.oss.model.BladeFile; import org.springblade.core.tool.api.R; import org.springblade.resource.feign.IOssClient; +import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -49,12 +49,13 @@ public class DeliveryNoteServiceImpl extends BaseServiceImpl vo) { // 1 上传数据到 minio 获取到地址 - String url = uploadFile(JSONObject.toJSONString(vo)); + String url = uploadFile(JSONUtil.toJsonStr(vo)); // 2 保存地址到数据库 FactoryOrderLogEntity logEntity = new FactoryOrderLogEntity(); logEntity.setType(1); diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/FactoryTokenServiceImpl.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/FactoryTokenServiceImpl.java new file mode 100644 index 000000000..1958c145a --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/service/impl/FactoryTokenServiceImpl.java @@ -0,0 +1,62 @@ +package com.logpm.factorydata.olo.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.logpm.factorydata.olo.entity.FactoryToken; +import com.logpm.factorydata.olo.mapper.FactoryTokenMapper; +import com.logpm.factorydata.olo.service.IFactoryTokenService; +import lombok.AllArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springblade.core.mp.base.BaseServiceImpl; +import org.springblade.core.redis.cache.BladeRedis; +import org.springframework.stereotype.Service; + +import java.security.NoSuchAlgorithmException; +import java.util.Objects; + +@AllArgsConstructor +@Service +public class FactoryTokenServiceImpl extends BaseServiceImpl implements IFactoryTokenService { + + private static final Logger logger = LoggerFactory.getLogger(FactoryTokenServiceImpl.class); + + private final BladeRedis bladeRedis; + + @Override + public boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException { + logger.info("#########verifyToken: 验证token开始"); + //先生成token摘要 +// String tokenAbst = MD5Utils.md5Hex(token.getBytes(StandardCharsets.UTF_8)); + + //编写查询条件 + String key = "corpId:" + corpId; + FactoryToken factoryToken = bladeRedis.get(key); + + if (Objects.isNull(factoryToken)) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("token", token); + factoryToken = baseMapper.selectOne(queryWrapper); + } + + + if (Objects.isNull(factoryToken)) { + logger.error("#########verifyToken: token1验证不通过 token={},corpid={}", token, corpId); + return false; + } + logger.info("#########verifyToken: 验证token 传入token {} 验证token {}", token, factoryToken.getToken()); + if (!factoryToken.getToken().equals(token)) { + logger.error("#########verifyToken: token2验证不通过 token={},corpid={}", token, corpId); + return false; + } + + + Long expireTimeLong = factoryToken.getExpireTime().getTime(); + Long now = System.currentTimeMillis(); + //判断是否过期 + if (now > expireTimeLong) { + logger.error("#########verifyToken: token验证不通过 已过期 token={},corpId={}", token, corpId); + return false; + } + return true; + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/util/ThreadPoolUtil.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/util/ThreadPoolUtil.java deleted file mode 100644 index fcaf39488..000000000 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/util/ThreadPoolUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.logpm.factorydata.olo.util; - -import cn.hutool.core.thread.ExecutorBuilder; -import cn.hutool.core.thread.ThreadFactoryBuilder; -import lombok.extern.slf4j.Slf4j; - -import java.util.concurrent.ExecutorService; - -/** - * @author zhaoqiaobo - * @create 2024-03-14 10:26 - */ -@Slf4j -public class ThreadPoolUtil { - - private ThreadPoolUtil() { - } - - /** - * 线程池 - */ - public static ExecutorService executor = null; - - static { - init(); - } - - synchronized public static void init() { - if (null != executor) { - executor.shutdownNow(); - } - executor = ExecutorBuilder.create() - .setCorePoolSize(8) - .setMaxPoolSize(20) - .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("logpm-factory-data-sfy-").build()) - .useSynchronousQueue().build(); - } - - public static ExecutorService getThreadPool() { - return executor; - } - -} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/CustomHttpServletRequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/CustomHttpServletRequestWrapper.java new file mode 100644 index 000000000..447a11ad6 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/CustomHttpServletRequestWrapper.java @@ -0,0 +1,38 @@ +package com.logpm.factorydata.olo.wrapper; + +import org.springframework.http.HttpHeaders; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { + + private final HttpHeaders headers; + + public CustomHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + headers = new HttpHeaders(); + } + + @Override + public String getHeader(String name) { + String headerValue = headers.getFirst(name); + return headerValue != null ? headerValue : super.getHeader(name); + } + + @Override + public Enumeration getHeaderNames() { + List names = Collections.list(super.getHeaderNames()); + headers.forEach((key, value) -> names.add(key)); + return Collections.enumeration(names); + } + + // 其他需要覆盖的方法... + + public void addHeader(String name, String value) { + headers.add(name, value); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/RequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/RequestWrapper.java similarity index 95% rename from blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/RequestWrapper.java rename to blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/RequestWrapper.java index 47c38a56d..6e0e96342 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/RequestWrapper.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/java/com/logpm/factorydata/olo/wrapper/RequestWrapper.java @@ -1,4 +1,4 @@ -package com.logpm.factorydata.zbom.config; +package com.logpm.factorydata.olo.wrapper; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; @@ -46,13 +46,17 @@ public class RequestWrapper extends HttpServletRequestWrapper { public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); ServletInputStream servletInputStream = new ServletInputStream() { + @Override public boolean isFinished() { return false; } + @Override public boolean isReady() { return false; } + @Override public void setReadListener(ReadListener readListener) {} + @Override public int read() throws IOException { return byteArrayInputStream.read(); } diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-prod.yml b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-prod.yml index 5a3241f3e..4e04b9630 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-prod.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-prod.yml @@ -33,13 +33,15 @@ spring: url: ${blade.datasource.factorydata-olo.master.url} username: ${blade.datasource.factorydata-olo.master.username} password: ${blade.datasource.factorydata-olo.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-olo.slave.url} - username: ${blade.datasource.factorydata-olo.slave.username} - password: ${blade.datasource.factorydata-olo.slave.password} - + url: ${blade.datasource.factorydata-olo.627683.url} + username: ${blade.datasource.factorydata-olo.627683.username} + password: ${blade.datasource.factorydata-olo.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-test.yml b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-test.yml index 866eaee96..3cbea6a0b 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-test.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-olo/src/main/resources/application-test.yml @@ -59,13 +59,15 @@ spring: url: ${blade.datasource.factorydata-olo.master.url} username: ${blade.datasource.factorydata-olo.master.username} password: ${blade.datasource.factorydata-olo.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-olo.slave.url} - username: ${blade.datasource.factorydata-olo.slave.username} - password: ${blade.datasource.factorydata-olo.slave.password} - + url: ${blade.datasource.factorydata-olo.627683.url} + username: ${blade.datasource.factorydata-olo.627683.username} + password: ${blade.datasource.factorydata-olo.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-piano/src/main/java/com/logpm/factorydata/PianoFactoryDataApplication.java b/blade-service/logpm-factory-data/logpm-factory-data-piano/src/main/java/com/logpm/factorydata/PianoFactoryDataApplication.java deleted file mode 100644 index 7c6d86087..000000000 --- a/blade-service/logpm-factory-data/logpm-factory-data-piano/src/main/java/com/logpm/factorydata/PianoFactoryDataApplication.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.logpm.factorydata; - -import org.springblade.common.constant.ModuleNameConstant; -import org.springblade.core.cloud.client.BladeCloudApplication; -import org.springblade.core.launch.BladeApplication; - -/** - * 工厂数据基础服务启动类 - * - * @Author zqb - * @Date 2024/3/14 - **/ -@BladeCloudApplication -public class PianoFactoryDataApplication { - - public static void main(String[] args) { - BladeApplication.run(ModuleNameConstant.LOGPM_FACTORY_DATA_BASE_NAME, PianoFactoryDataApplication.class, args); - } - -} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/aspect/AnnotationAspect.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/aspect/AnnotationAspect.java index 1c949f0fc..8a8b9f354 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/aspect/AnnotationAspect.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/aspect/AnnotationAspect.java @@ -4,13 +4,49 @@ import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; import org.springblade.core.secure.utils.AuthUtil; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; +import java.lang.reflect.Method; + @Aspect @Component public class AnnotationAspect { + /** + * 定义一个切点,匹配所有带有@Async("asyncExecutor")注解的方法。 + * 注意:实际上Spring Framework自带对@Async("asyncExecutor")的处理,直接这样配置可能会导致预期之外的行为。 + */ + @Around("@annotation(org.springframework.scheduling.annotation.Async)") + public Object asyncAroundAsyncMethods(ProceedingJoinPoint joinPoint) throws Throwable { + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + + Async myAsync = method.getAnnotation(Async.class); + String annotationValue = myAsync.value(); + + if(StringUtil.isNotBlank(annotationValue) && annotationValue.equals("asyncExecutor")){ + // 在方法执行前的操作 + String tenantId = AuthUtil.getTenantId(); + DynamicDataSourceContextHolder.push(tenantId); + + // 执行原方法 + Object result = joinPoint.proceed(); + + // 在方法执行后的操作 + DynamicDataSourceContextHolder.poll(); + + return result; + }else{ + return joinPoint.proceed(); + } + + } + /** * 该方法为一个切面,用于对标记了@RabbitListener注解的方法进行增强,主要增加了日志记录和数据源上下文处理的功能。 * diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/ExecutorConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/ExecutorConfig.java new file mode 100644 index 000000000..68ee9b419 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/ExecutorConfig.java @@ -0,0 +1,79 @@ +package com.logpm.factorydata.suofeiya.config; + +import lombok.extern.slf4j.Slf4j; +import org.slf4j.MDC; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskDecorator; +import org.springframework.http.HttpHeaders; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@Slf4j +@EnableAsync +public class ExecutorConfig { + + @Bean + public Executor asyncExecutor() { + log.info("start async executor"); + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); +// 配置核心线程数 + threadPoolTaskExecutor.setCorePoolSize(10); +// 配置最大线程数 + threadPoolTaskExecutor.setMaxPoolSize(20); +// 配置队列大小 + threadPoolTaskExecutor.setQueueCapacity(50); +// 配置线程池中线程的名称前缀 + threadPoolTaskExecutor.setThreadNamePrefix("ASYNC_THREAD_"); +// HelloWorldServiceImpl rejection-policy: 当pool已经达到max size时,如何处理新任务: +// CallerRunsPolicy: 不在新线程中执行任务,而是由调用者所在的线程来执行; +// AbortPolicy: 拒绝执行新任务,并抛出RejectedExecutionException异常; +// DiscardPolicy:丢弃当前将要加入队列的任务; +// DiscardOldestPolicy:丢弃任务队列中最旧的任务; + threadPoolTaskExecutor.setRejectedExecutionHandler( + new ThreadPoolExecutor.CallerRunsPolicy() + ); + threadPoolTaskExecutor.setTaskDecorator(new ContextCopyingDecorator()); + threadPoolTaskExecutor.initialize(); + return threadPoolTaskExecutor; + } + + + static class ContextCopyingDecorator implements TaskDecorator { + @Nonnull + @Override + public Runnable decorate(@Nonnull Runnable runnable) { + RequestAttributes context = RequestContextHolder.currentRequestAttributes(); + HttpHeaders headers = (HttpHeaders) ThreadLocalUtil.get("bladeContext"); + Map mdcMap = MDC.getCopyOfContextMap(); + return () -> { + try { + ThreadLocalUtil.put("bladeContext", headers); + if (mdcMap != null && !mdcMap.isEmpty()) { + MDC.setContextMap(mdcMap); + } + RequestContextHolder.setRequestAttributes(context); + + runnable.run(); + } finally { + RequestContextHolder.resetRequestAttributes(); + if (mdcMap != null) { + mdcMap.clear(); + } + ThreadLocalUtil.clear(); + MDC.clear(); + } + }; + } + } + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/InterceptorAdapterConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/InterceptorAdapterConfig.java new file mode 100644 index 000000000..c68f16e09 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/config/InterceptorAdapterConfig.java @@ -0,0 +1,28 @@ +package com.logpm.factorydata.suofeiya.config; + +import com.logpm.factorydata.suofeiya.interceptor.FactoryAccountsInterceptor; +import com.logpm.factorydata.suofeiya.interceptor.LocalServerLoginAccountsInterceptor; +import com.logpm.factorydata.suofeiya.service.IFactoryTokenService; +import lombok.AllArgsConstructor; +import org.springblade.core.redis.cache.BladeRedis; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@AllArgsConstructor +public class InterceptorAdapterConfig implements WebMvcConfigurer { + + private final IFactoryTokenService factoryTokenService; + private final BladeRedis redis; + private final Environment environment; + + @Override + public void addInterceptors(InterceptorRegistry interceptorRegistry) { +// interceptorRegistry.addInterceptor(new FactoryAccountsInterceptor(factoryTokenService)) +// .addPathPatterns("/**").order(1); + interceptorRegistry.addInterceptor(new LocalServerLoginAccountsInterceptor(redis, environment)) + .addPathPatterns("/**").order(2); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/entity/FactoryToken.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/entity/FactoryToken.java new file mode 100644 index 000000000..21a77ce43 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/entity/FactoryToken.java @@ -0,0 +1,32 @@ +package com.logpm.factorydata.suofeiya.entity; + +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 org.springblade.core.mp.base.BaseEntity; + +import java.util.Date; + +@Data +@TableName("factory_token") +@ApiModel(value = "FactoryToken对象", description = "工厂账户token") +public class FactoryToken extends BaseEntity { + + @ApiModelProperty("token") + private String token; + + @ApiModelProperty("token摘要") + private String tokenAbst; + + @JsonFormat( + pattern = "yyyy-MM-dd HH:mm:ss" + ) + @ApiModelProperty("过期时间") + private Date expireTime; + + @ApiModelProperty("企业id") + private String corpid; + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/FactoryAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/FactoryAccountsInterceptor.java new file mode 100644 index 000000000..a34aa97e9 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/FactoryAccountsInterceptor.java @@ -0,0 +1,87 @@ +package com.logpm.factorydata.suofeiya.interceptor; + +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.suofeiya.service.IFactoryTokenService; +import com.logpm.factorydata.suofeiya.wrapper.RequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@Log4j2 +@AllArgsConstructor +public class FactoryAccountsInterceptor implements HandlerInterceptor { + + private final IFactoryTokenService factoryTokenService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + try { + + RequestWrapper myRequestWrapper = new RequestWrapper(request); + String body = myRequestWrapper.getBody(); + JSONObject jsonObject = JSONObject.parseObject(body); + //获取头中参数 + String token = request.getHeader("Authorization"); + String corpId = request.getHeader("corpid"); + if(StringUtil.isBlank(corpId)){ + corpId = jsonObject.getString("corpid"); + } + if(!StringUtil.hasLength(token)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token有误"))); + return false; + } + if(!StringUtil.hasLength(corpId)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,corpId有误"))); + return false; + } + + log.info("##########preHandle: token={}",token); + //验证token + boolean b = factoryTokenService.verifyToken(token,corpId); + if(!b){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token不存在或已过期"))); + return false; + } + return true; + } catch (Exception e) { + returnJson(response,JSONObject.toJSONString(R.fail(500,"服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null){ + writer.close(); + } + } + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + HandlerInterceptor.super.afterCompletion(request, response, handler, ex); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/LocalServerLoginAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/LocalServerLoginAccountsInterceptor.java new file mode 100644 index 000000000..7cc09abec --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/interceptor/LocalServerLoginAccountsInterceptor.java @@ -0,0 +1,100 @@ +package com.logpm.factorydata.suofeiya.interceptor; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.suofeiya.wrapper.CustomHttpServletRequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.cache.CacheNames; +import org.springblade.common.constant.LauncherConstant; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.redis.cache.BladeRedis; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@Log4j2 +@AllArgsConstructor +public class LocalServerLoginAccountsInterceptor extends HandlerInterceptorAdapter { + + private final BladeRedis bladeRedis; + private final Environment environment; + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + + + try { + CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(request); + String account ="shujutongbu"; + JSONObject data =bladeRedis.get(CacheNames.LOCAL_SERVER_USER+account); + if(Objects.isNull(data)){ + String url = "http://"+ LauncherConstant.loginAddr(Objects.requireNonNull(environment.getActiveProfiles()[0]))+"/blade-auth/oauth/token"; + HttpRequest urlRequest = HttpRequest.post(url); + urlRequest.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + urlRequest.header("Tenant-Id", "627683"); + + Map params = new HashMap<>(); + params.put("grant_type", "local_server"); + params.put("scope", "all"); + params.put("username", account); + params.put("tenantId", "627683"); + HttpResponse execute = urlRequest.form(params).execute(); + String body = execute.body(); + data = JSONObject.parseObject(body); + bladeRedis.setEx(CacheNames.LOCAL_SERVER_USER+account,data,3200L); + } + + // 修改或添加header + + // 发送登录请求 + log.info("##########preHandle: request={}", request); + + wrappedRequest.addHeader("Blade-Auth", "bearer "+data.getString("access_token")); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Blade-Auth","bearer "+data.get("access_token") ); + httpHeaders.add( "Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + ThreadLocalUtil.put("bladeContext", httpHeaders); + + + // 用包装后的request替换原始request + request = wrappedRequest; + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + return true; + } catch (Exception e) { + returnJson(response, JSONObject.toJSONString(R.fail(500, "服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.java new file mode 100644 index 000000000..b7cfc1c81 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the dreamlu.net developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: Chill 庄骞 (smallchill@163.com) + */ +package com.logpm.factorydata.suofeiya.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.logpm.factorydata.suofeiya.entity.FactoryToken; + +/** + * 工厂账号接口日志 Mapper 接口 + * + * @author zhy + * @since 2023-03-28 + */ +public interface FactoryTokenMapper extends BaseMapper { + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.xml b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.xml new file mode 100644 index 000000000..97dc57a35 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mapper/FactoryTokenMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mq/FactoryOrderListener.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mq/FactoryOrderListener.java index a366aec37..9a336b699 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mq/FactoryOrderListener.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/mq/FactoryOrderListener.java @@ -23,7 +23,6 @@ import com.logpm.factorydata.suofeiya.service.DeliveryNoteService; import com.logpm.factorydata.suofeiya.service.FactoryOrderLogService; import com.logpm.factorydata.suofeiya.service.OrderInfoService; import com.logpm.factorydata.suofeiya.service.PackageInfoService; -import com.logpm.factorydata.suofeiya.util.ThreadPoolUtil; import com.logpm.factorydata.suofeiya.vo.DeliveryNoteVO; import com.logpm.factorydata.suofeiya.vo.OrderInfoVO; import com.logpm.factorydata.suofeiya.vo.PackageInfoVO; @@ -41,6 +40,7 @@ import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -103,12 +103,12 @@ public class FactoryOrderListener { } if (ObjectUtil.isNotNull(vo)) { // 1 解析数据保存入库 - // 车牌与出场日期判断唯一 - String truckNo = vo.getTruckNo(); - String gpsLeaveWhTime = vo.getGpsLeaveWhTime(); - List list = deliveryNoteService.list(Wrappers.lambdaQuery().eq(DeliveryNoteEntity::getTruckNo, truckNo).eq(DeliveryNoteEntity::getGpsLeaveWhTime, gpsLeaveWhTime)); + // 车次号唯一 + String logisticID = vo.getLogisticID(); + List list = deliveryNoteService.list(Wrappers.lambdaQuery() + .eq(DeliveryNoteEntity::getLogisticID, logisticID)); if (CollUtil.isNotEmpty(list)) { - log.error("车牌{}与出场日期{} 数据已经处理过了, logId: {}", truckNo, gpsLeaveWhTime, logId); + log.error("车次号{} 数据已经处理过了, logId: {}", logisticID, logId); return; } // 处理额外的字段 @@ -150,153 +150,152 @@ public class FactoryOrderListener { } } - private void buildAdvance(DeliveryNoteVO vo) { + @Async("asyncExecutor") + public void buildAdvance(DeliveryNoteVO vo) { // 新起线程构建暂存单发送mq - ThreadPoolUtil.getThreadPool().submit(() -> { - Long startWarehouseId = null; - String startWarehouseName = null; - String tenantId = null; - // 获取工厂基地绑定的始发仓信息 - List details = vo.getOrderInfo(); - if (CollUtil.isEmpty(details)) { - return; - } - R warehouseByBrandAndSiteName = baseClient.getWarehouseByBrandAndSiteName(BrandEnums.SFY.getValue(), BrandEnums.SFY.getValue()); - if (ObjectUtil.equal(HttpConstants.HTTP.HTTP_RESOURCE_CODE.SUCCESS_CODE, warehouseByBrandAndSiteName.getCode())) { - FactoryWarehouseBindVO data = warehouseByBrandAndSiteName.getData(); - if (ObjectUtil.isNotNull(data)) { - startWarehouseId = data.getWarehouseId(); - startWarehouseName = data.getWarehouseName(); - tenantId = data.getTenantId(); - } + Long startWarehouseId = null; + String startWarehouseName = null; + String tenantId = null; + // 获取工厂基地绑定的始发仓信息 + List details = vo.getOrderInfo(); + if (CollUtil.isEmpty(details)) { + return; + } + R warehouseByBrandAndSiteName = baseClient.getWarehouseByBrandAndSiteName(BrandEnums.SFY.getValue(), BrandEnums.SFY.getValue()); + if (ObjectUtil.equal(HttpConstants.HTTP.HTTP_RESOURCE_CODE.SUCCESS_CODE, warehouseByBrandAndSiteName.getCode())) { + FactoryWarehouseBindVO data = warehouseByBrandAndSiteName.getData(); + if (ObjectUtil.isNotNull(data)) { + startWarehouseId = data.getWarehouseId(); + startWarehouseName = data.getWarehouseName(); + tenantId = data.getTenantId(); } - Map> advanceMap = new HashMap<>(); - List packageInfos = vo.getPackageInfo(); - // 一个车次号 + 一个订单 一个暂存单 - if (CollUtil.isNotEmpty(packageInfos)) { - for (PackageInfoVO packageInfo : packageInfos) { - String advanceKey = packageInfo.getOrderNo(); - if (advanceMap.containsKey(advanceKey)) { - advanceMap.get(advanceKey).add(packageInfo); - } else { - ArrayList packageInfoVOS = new ArrayList<>(); - packageInfoVOS.add(packageInfo); - advanceMap.put(advanceKey, packageInfoVOS); - } + } + Map> advanceMap = new HashMap<>(); + List packageInfos = vo.getPackageInfo(); + // 一个车次号 + 一个订单 一个暂存单 + if (CollUtil.isNotEmpty(packageInfos)) { + for (PackageInfoVO packageInfo : packageInfos) { + String advanceKey = packageInfo.getOrderNo(); + if (advanceMap.containsKey(advanceKey)) { + advanceMap.get(advanceKey).add(packageInfo); + } else { + ArrayList packageInfoVOS = new ArrayList<>(); + packageInfoVOS.add(packageInfo); + advanceMap.put(advanceKey, packageInfoVOS); } } + } - // 组装暂存单数据 - List advances = new ArrayList<>(); - for (OrderInfoVO orderInfoVO : details) { - List packageList = new ArrayList<>(); - if (CollUtil.isEmpty(advanceMap)) { - return; - } - List packageInfoVOS = advanceMap.get(orderInfoVO.getOrderNo()); - if (ObjectUtil.isEmpty(packageInfoVOS)) { - return; - } + // 组装暂存单数据 + List advances = new ArrayList<>(); + for (OrderInfoVO orderInfoVO : details) { + List packageList = new ArrayList<>(); + if (CollUtil.isEmpty(advanceMap)) { + return; + } + List packageInfoVOS = advanceMap.get(orderInfoVO.getOrderNo()); + if (ObjectUtil.isEmpty(packageInfoVOS)) { + continue; + } - TrunklineAdvanceEntity advanceEntity = new TrunklineAdvanceEntity(); - advanceEntity.setTenantId(tenantId); - advanceEntity.setStatus(0); - advanceEntity.setIsDeleted(0); - advanceEntity.setHasPackage(CollUtil.isNotEmpty(packageInfoVOS) ? 1 : 0); - advanceEntity.setOrderType(vo.getOrderType()); - advanceEntity.setBrand(BrandEnums.SFY.getValue()); - advanceEntity.setSiteName(""); - advanceEntity.setArea(""); - advanceEntity.setTotalNum(CollUtil.isNotEmpty(packageInfoVOS) ? packageInfoVOS.size() : 0); - advanceEntity.setPackName(""); - advanceEntity.setPackCode(""); - advanceEntity.setWarehouseId(startWarehouseId); - advanceEntity.setWarehouseName(startWarehouseName); + TrunklineAdvanceEntity advanceEntity = new TrunklineAdvanceEntity(); + advanceEntity.setTenantId(tenantId); + advanceEntity.setStatus(0); + advanceEntity.setIsDeleted(0); + advanceEntity.setHasPackage(CollUtil.isNotEmpty(packageInfoVOS) ? 1 : 0); + advanceEntity.setOrderType(vo.getOrderType()); + advanceEntity.setBrand(BrandEnums.SFY.getValue()); + advanceEntity.setSiteName(""); + advanceEntity.setArea(""); + advanceEntity.setTotalNum(CollUtil.isNotEmpty(packageInfoVOS) ? packageInfoVOS.size() : 0); + advanceEntity.setPackName(""); + advanceEntity.setPackCode(""); + advanceEntity.setWarehouseId(startWarehouseId); + advanceEntity.setWarehouseName(startWarehouseName); - advanceEntity.setIsGcp(0); - advanceEntity.setCarrierName(vo.getCarrierNo()); - advanceEntity.setSystemType("线下"); - advanceEntity.setMatingType(""); - advanceEntity.setSenderName(vo.getSendAddr()); - advanceEntity.setSenderPhone(""); - advanceEntity.setSenderAddress(vo.getSendAddr()); - advanceEntity.setWaybillStatus("0"); - advanceEntity.setWaybillNo(""); - advanceEntity.setTrainNumber(vo.getLogisticID()); - advanceEntity.setFreezeStatus("0"); - advanceEntity.setOrderCode(orderInfoVO.getOrderNo()); - advanceEntity.setServiceNum(orderInfoVO.getMainOrderNo()); - advanceEntity.setSenderFactory(vo.getSendAddr()); + advanceEntity.setIsGcp(0); + advanceEntity.setCarrierName(vo.getCarrierNo()); + advanceEntity.setSystemType("线上"); + advanceEntity.setMatingType("1"); + advanceEntity.setSenderName(vo.getSendAddr()); + advanceEntity.setSenderPhone(""); + advanceEntity.setSenderAddress(vo.getSendAddr()); + advanceEntity.setWaybillStatus("0"); + advanceEntity.setWaybillNo(""); + advanceEntity.setTrainNumber(vo.getLogisticID()); + advanceEntity.setFreezeStatus("0"); + advanceEntity.setOrderCode(orderInfoVO.getOrderNo()); + advanceEntity.setServiceNum(orderInfoVO.getMainOrderNo()); + advanceEntity.setSenderFactory(vo.getSendAddr()); - for (PackageInfoVO orderPackageDTO : packageInfoVOS) { - advanceEntity.setDealerCode(orderPackageDTO.getDealerNo()); - advanceEntity.setDealerName(orderPackageDTO.getDealerName()); - advanceEntity.setStoreCode(orderPackageDTO.getDealerNo()); - advanceEntity.setStoreName(orderPackageDTO.getDealerName()); - advanceEntity.setCustomerName(orderInfoVO.getReceiver()); - advanceEntity.setCustomerPhone(orderInfoVO.getReceiveTel()); - advanceEntity.setCustomerAddress(orderInfoVO.getReceiveAddr()); - // 封装包件 - TrunklineAdvanceDetailEntity advanceDetailEntity = new TrunklineAdvanceDetailEntity(); - advanceDetailEntity.setWarehouseId(startWarehouseId); - advanceDetailEntity.setWarehouseName(startWarehouseName); + for (PackageInfoVO orderPackageDTO : packageInfoVOS) { + advanceEntity.setDealerCode(orderPackageDTO.getDealerNo()); + advanceEntity.setDealerName(orderPackageDTO.getDealerName()); + advanceEntity.setStoreCode(orderPackageDTO.getDealerNo()); + advanceEntity.setStoreName(orderPackageDTO.getDealerName()); + advanceEntity.setCustomerName(orderInfoVO.getReceiver()); + advanceEntity.setCustomerPhone(orderInfoVO.getReceiveTel()); + advanceEntity.setCustomerAddress(orderInfoVO.getReceiveAddr()); + // 封装包件 + TrunklineAdvanceDetailEntity advanceDetailEntity = new TrunklineAdvanceDetailEntity(); + advanceDetailEntity.setWarehouseId(startWarehouseId); + advanceDetailEntity.setWarehouseName(startWarehouseName); // advanceDetailEntity.setIncomingWarehouseId(0L); // advanceDetailEntity.setIncomingWarehouseName(""); - // 根据遗留单标识赋值 - advanceEntity.setLegacyStatus("0"); - if (StrUtil.contains(orderInfoVO.getOrderNo(), "遗")) { - advanceEntity.setLegacyStatus("1"); - } - advanceDetailEntity.setOrderCode(orderPackageDTO.getOrderNo()); - advanceDetailEntity.setBrand(BrandEnums.SFY.getValue()); - advanceDetailEntity.setSystemType("线下"); - // 一级品类名称 - advanceDetailEntity.setFirstPackName(orderPackageDTO.getPlDepart()); - advanceDetailEntity.setFirstPackCode(""); - // 获取映射品类信息 - // 二级品类名称 - advanceDetailEntity.setSecondPackName(orderPackageDTO.getPlDepart()); - // 三级品类名称 - advanceDetailEntity.setThirdPackName(orderPackageDTO.getPlDepart()); - advanceDetailEntity.setMaterialName(orderPackageDTO.getPlDepart()); - advanceDetailEntity.setSiteName(""); - advanceDetailEntity.setSiteCode(""); - advanceDetailEntity.setQuantity(1); - advanceDetailEntity.setOrderPackageCode(orderPackageDTO.getPaNo()); - advanceDetailEntity.setTrainNumber(""); - advanceDetailEntity.setServiceNum(orderInfoVO.getMainOrderNo()); - advanceDetailEntity.setWaybillNo(""); - advanceDetailEntity.setPackageStatus("0"); - advanceDetailEntity.setWeight(StrUtil.isNotBlank(orderPackageDTO.getWeight()) ? new BigDecimal(orderPackageDTO.getWeight()) : BigDecimal.ZERO); - advanceDetailEntity.setVolume(StrUtil.isNotBlank(orderPackageDTO.getVolume()) ? new BigDecimal(orderPackageDTO.getVolume()) : BigDecimal.ZERO); -// advanceDetailEntity.setChargeType(0); - advanceDetailEntity.setSupple(""); - advanceDetailEntity.setManifest(""); - advanceDetailEntity.setReturnNum(""); - advanceDetailEntity.setSendDateStr(vo.getGpsLeaveWhTime()); - advanceDetailEntity.setCarNumber(vo.getTruckNo()); - advanceDetailEntity.setGoodsMan(""); - advanceDetailEntity.setTenantId(tenantId); - advanceDetailEntity.setStatus(0); - advanceDetailEntity.setIsDeleted(0); - JSONObject entries = JSONUtil.parseObj(advanceDetailEntity); - packageList.add(entries); + // 根据遗留单标识赋值 + advanceEntity.setLegacyStatus("0"); + if (StrUtil.contains(orderInfoVO.getOrderNo(), "遗")) { + advanceEntity.setLegacyStatus("1"); } - // 转成json对象,然后将包件明细放到detail中 - JSONObject entries = JSONUtil.parseObj(advanceEntity); - entries.set("details", JSONUtil.toJsonStr(packageList)); - advances.add(entries); + advanceDetailEntity.setOrderCode(orderPackageDTO.getOrderNo()); + advanceDetailEntity.setBrand(BrandEnums.SFY.getValue()); + advanceDetailEntity.setSystemType("线上"); + // 一级品类名称 + advanceDetailEntity.setFirstPackName(orderPackageDTO.getPlDepart()); + advanceDetailEntity.setFirstPackCode(""); + // 获取映射品类信息 + // 二级品类名称 + advanceDetailEntity.setSecondPackName(orderPackageDTO.getPlDepart()); + // 三级品类名称 + advanceDetailEntity.setThirdPackName(orderPackageDTO.getPlDepart()); + advanceDetailEntity.setMaterialName(orderPackageDTO.getPlDepart()); + advanceDetailEntity.setSiteName(""); + advanceDetailEntity.setSiteCode(""); + advanceDetailEntity.setQuantity(1); + advanceDetailEntity.setOrderPackageCode(orderPackageDTO.getPaNo()); + advanceDetailEntity.setTrainNumber(""); + advanceDetailEntity.setServiceNum(orderInfoVO.getMainOrderNo()); + advanceDetailEntity.setWaybillNo(""); + advanceDetailEntity.setPackageStatus("0"); + advanceDetailEntity.setWeight(StrUtil.isNotBlank(orderPackageDTO.getWeight()) ? new BigDecimal(orderPackageDTO.getWeight()) : BigDecimal.ZERO); + advanceDetailEntity.setVolume(StrUtil.isNotBlank(orderPackageDTO.getVolume()) ? new BigDecimal(orderPackageDTO.getVolume()) : BigDecimal.ZERO); +// advanceDetailEntity.setChargeType(0); + advanceDetailEntity.setSupple(""); + advanceDetailEntity.setManifest(""); + advanceDetailEntity.setReturnNum(""); + advanceDetailEntity.setSendDateStr(vo.getGpsLeaveWhTime()); + advanceDetailEntity.setCarNumber(vo.getTruckNo()); + advanceDetailEntity.setGoodsMan(""); + advanceDetailEntity.setTenantId(tenantId); + advanceDetailEntity.setStatus(0); + advanceDetailEntity.setIsDeleted(0); + JSONObject entries = JSONUtil.parseObj(advanceDetailEntity); + packageList.add(entries); } - // 将组装好的暂存单发送到 MQ ,由暂存单服务统一消费SendMsg. - if (CollUtil.isNotEmpty(advances)) { - for (JSONObject advance : advances) { - SendMsg sendMsg = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.ADVANCE_ORDER) - .routingKey(FactoryDataConstants.Mq.RoutingKeys.ADVANCE_ORDER).message(JSONUtil.toJsonStr(advance)).build(); - factoryDataClient.sendMessage(sendMsg); - } + // 转成json对象,然后将包件明细放到detail中 + JSONObject entries = JSONUtil.parseObj(advanceEntity); + entries.set("details", JSONUtil.toJsonStr(packageList)); + advances.add(entries); + } + // 将组装好的暂存单发送到 MQ ,由暂存单服务统一消费SendMsg. + if (CollUtil.isNotEmpty(advances)) { + for (JSONObject advance : advances) { + SendMsg sendMsg = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.ADVANCE_ORDER) + .routingKey(FactoryDataConstants.Mq.RoutingKeys.ADVANCE_ORDER).message(JSONUtil.toJsonStr(advance)).build(); + factoryDataClient.sendMessage(sendMsg); } - }); + } } } diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/IFactoryTokenService.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/IFactoryTokenService.java new file mode 100644 index 000000000..3c6ab42b7 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/IFactoryTokenService.java @@ -0,0 +1,15 @@ +package com.logpm.factorydata.suofeiya.service; + +import com.logpm.factorydata.suofeiya.entity.FactoryToken; +import org.springblade.core.mp.base.BaseService; + +import java.security.NoSuchAlgorithmException; + +/** + * 工厂推送数据接口 + */ +public interface IFactoryTokenService extends BaseService { + + + boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException; +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/impl/DeliveryNoteServiceImpl.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/impl/DeliveryNoteServiceImpl.java index 74441a56e..62ad27075 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/impl/DeliveryNoteServiceImpl.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/service/impl/DeliveryNoteServiceImpl.java @@ -54,7 +54,7 @@ public class DeliveryNoteServiceImpl extends BaseServiceImpl implements IFactoryTokenService { + + private static final Logger logger = LoggerFactory.getLogger(FactoryTokenServiceImpl.class); + + private final BladeRedis bladeRedis; + + @Override + public boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException { + logger.info("#########verifyToken: 验证token开始"); + //先生成token摘要 +// String tokenAbst = MD5Utils.md5Hex(token.getBytes(StandardCharsets.UTF_8)); + + //编写查询条件 + String key = "corpId:" + corpId; + FactoryToken factoryToken = bladeRedis.get(key); + + if (Objects.isNull(factoryToken)) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("token", token); + factoryToken = baseMapper.selectOne(queryWrapper); + } + + + if (Objects.isNull(factoryToken)) { + logger.error("#########verifyToken: token1验证不通过 token={},corpid={}", token, corpId); + return false; + } + logger.info("#########verifyToken: 验证token 传入token {} 验证token {}", token, factoryToken.getToken()); + if (!factoryToken.getToken().equals(token)) { + logger.error("#########verifyToken: token2验证不通过 token={},corpid={}", token, corpId); + return false; + } + + + Long expireTimeLong = factoryToken.getExpireTime().getTime(); + Long now = System.currentTimeMillis(); + //判断是否过期 + if (now > expireTimeLong) { + logger.error("#########verifyToken: token验证不通过 已过期 token={},corpId={}", token, corpId); + return false; + } + return true; + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/util/ThreadPoolUtil.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/util/ThreadPoolUtil.java deleted file mode 100644 index c4095d9c5..000000000 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/util/ThreadPoolUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.logpm.factorydata.suofeiya.util; - -import cn.hutool.core.thread.ExecutorBuilder; -import cn.hutool.core.thread.ThreadFactoryBuilder; -import lombok.extern.slf4j.Slf4j; - -import java.util.concurrent.ExecutorService; - -/** - * @author zhaoqiaobo - * @create 2024-03-14 10:26 - */ -@Slf4j -public class ThreadPoolUtil { - - private ThreadPoolUtil() { - } - - /** - * 线程池 - */ - public static ExecutorService executor = null; - - static { - init(); - } - - synchronized public static void init() { - if (null != executor) { - executor.shutdownNow(); - } - executor = ExecutorBuilder.create() - .setCorePoolSize(8) - .setMaxPoolSize(20) - .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("logpm-factory-data-sfy-").build()) - .useSynchronousQueue().build(); - } - - public static ExecutorService getThreadPool() { - return executor; - } - -} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/CustomHttpServletRequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/CustomHttpServletRequestWrapper.java new file mode 100644 index 000000000..3ae68bb9d --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/CustomHttpServletRequestWrapper.java @@ -0,0 +1,38 @@ +package com.logpm.factorydata.suofeiya.wrapper; + +import org.springframework.http.HttpHeaders; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { + + private final HttpHeaders headers; + + public CustomHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + headers = new HttpHeaders(); + } + + @Override + public String getHeader(String name) { + String headerValue = headers.getFirst(name); + return headerValue != null ? headerValue : super.getHeader(name); + } + + @Override + public Enumeration getHeaderNames() { + List names = Collections.list(super.getHeaderNames()); + headers.forEach((key, value) -> names.add(key)); + return Collections.enumeration(names); + } + + // 其他需要覆盖的方法... + + public void addHeader(String name, String value) { + headers.add(name, value); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/RequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/RequestWrapper.java new file mode 100644 index 000000000..b084a4045 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/java/com/logpm/factorydata/suofeiya/wrapper/RequestWrapper.java @@ -0,0 +1,75 @@ +package com.logpm.factorydata.suofeiya.wrapper; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class RequestWrapper extends HttpServletRequestWrapper { + private final String body; + public RequestWrapper(HttpServletRequest request) throws IOException { + super(request); + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try { + InputStream inputStream = request.getInputStream(); + if (inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } else { + stringBuilder.append(""); + } + } catch (IOException ex) { + throw ex; + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ex) { + throw ex; + } + } + } + body = stringBuilder.toString(); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); + ServletInputStream servletInputStream = new ServletInputStream() { + @Override + public boolean isFinished() { + return false; + } + @Override + public boolean isReady() { + return false; + } + @Override + public void setReadListener(ReadListener readListener) {} + @Override + public int read() throws IOException { + return byteArrayInputStream.read(); + } + }; + return servletInputStream; + + } + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(this.getInputStream())); + } + public String getBody() { + return this.body; + } + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-dev.yml b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-dev.yml index 93eef4be6..58c7ad0bc 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-dev.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-dev.yml @@ -59,13 +59,15 @@ spring: url: ${blade.datasource.factorydata-sfy.master.url} username: ${blade.datasource.factorydata-sfy.master.username} password: ${blade.datasource.factorydata-sfy.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-sfy.slave.url} - username: ${blade.datasource.factorydata-sfy.slave.username} - password: ${blade.datasource.factorydata-sfy.slave.password} - + url: ${blade.datasource.factorydata-sfy.627683.url} + username: ${blade.datasource.factorydata-sfy.627683.username} + password: ${blade.datasource.factorydata-sfy.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-prod.yml b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-prod.yml index 196090042..8cfdfb8b4 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-prod.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-prod.yml @@ -33,13 +33,15 @@ spring: url: ${blade.datasource.factorydata-sfy.master.url} username: ${blade.datasource.factorydata-sfy.master.username} password: ${blade.datasource.factorydata-sfy.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-sfy.slave.url} - username: ${blade.datasource.factorydata-sfy.slave.username} - password: ${blade.datasource.factorydata-sfy.slave.password} - + url: ${blade.datasource.factorydata-sfy.627683.url} + username: ${blade.datasource.factorydata-sfy.627683.username} + password: ${blade.datasource.factorydata-sfy.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-test.yml b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-test.yml index aa4bdc640..83ba070d6 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-test.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-suofeiya/src/main/resources/application-test.yml @@ -59,13 +59,15 @@ spring: url: ${blade.datasource.factorydata-sfy.master.url} username: ${blade.datasource.factorydata-sfy.master.username} password: ${blade.datasource.factorydata-sfy.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-sfy.slave.url} - username: ${blade.datasource.factorydata-sfy.slave.username} - password: ${blade.datasource.factorydata-sfy.slave.password} - + url: ${blade.datasource.factorydata-sfy.627683.url} + username: ${blade.datasource.factorydata-sfy.627683.username} + password: ${blade.datasource.factorydata-sfy.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/pom.xml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/pom.xml index d03f270ec..cc87f95c7 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/pom.xml +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/pom.xml @@ -54,6 +54,20 @@ logpm-factory-data-base-api ${bladex.project.version} + + org.springblade + blade-starter-oss + + + io.minio + minio + + + org.springblade + blade-resource-api + 3.2.0.RELEASE + compile + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/aspect/AnnotationAspect.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/aspect/AnnotationAspect.java index 554dff7af..6dafedc97 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/aspect/AnnotationAspect.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/aspect/AnnotationAspect.java @@ -4,13 +4,49 @@ import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; import org.springblade.core.secure.utils.AuthUtil; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; +import java.lang.reflect.Method; + @Aspect @Component public class AnnotationAspect { + /** + * 定义一个切点,匹配所有带有@Async("asyncExecutor")注解的方法。 + * 注意:实际上Spring Framework自带对@Async("asyncExecutor")的处理,直接这样配置可能会导致预期之外的行为。 + */ + @Around("@annotation(org.springframework.scheduling.annotation.Async)") + public Object asyncAroundAsyncMethods(ProceedingJoinPoint joinPoint) throws Throwable { + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + + Async myAsync = method.getAnnotation(Async.class); + String annotationValue = myAsync.value(); + + if(StringUtil.isNotBlank(annotationValue) && annotationValue.equals("asyncExecutor")){ + // 在方法执行前的操作 + String tenantId = AuthUtil.getTenantId(); + DynamicDataSourceContextHolder.push(tenantId); + + // 执行原方法 + Object result = joinPoint.proceed(); + + // 在方法执行后的操作 + DynamicDataSourceContextHolder.poll(); + + return result; + }else{ + return joinPoint.proceed(); + } + + } + /** * 该方法为一个切面,用于对标记了@RabbitListener注解的方法进行增强,主要增加了日志记录和数据源上下文处理的功能。 * diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/ExecutorConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/ExecutorConfig.java new file mode 100644 index 000000000..028e504d8 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/ExecutorConfig.java @@ -0,0 +1,79 @@ +package com.logpm.factorydata.zbom.config; + +import lombok.extern.slf4j.Slf4j; +import org.slf4j.MDC; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskDecorator; +import org.springframework.http.HttpHeaders; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@Slf4j +@EnableAsync +public class ExecutorConfig { + + @Bean + public Executor asyncExecutor() { + log.info("start async executor"); + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); +// 配置核心线程数 + threadPoolTaskExecutor.setCorePoolSize(10); +// 配置最大线程数 + threadPoolTaskExecutor.setMaxPoolSize(20); +// 配置队列大小 + threadPoolTaskExecutor.setQueueCapacity(50); +// 配置线程池中线程的名称前缀 + threadPoolTaskExecutor.setThreadNamePrefix("ASYNC_THREAD_"); +// HelloWorldServiceImpl rejection-policy: 当pool已经达到max size时,如何处理新任务: +// CallerRunsPolicy: 不在新线程中执行任务,而是由调用者所在的线程来执行; +// AbortPolicy: 拒绝执行新任务,并抛出RejectedExecutionException异常; +// DiscardPolicy:丢弃当前将要加入队列的任务; +// DiscardOldestPolicy:丢弃任务队列中最旧的任务; + threadPoolTaskExecutor.setRejectedExecutionHandler( + new ThreadPoolExecutor.CallerRunsPolicy() + ); + threadPoolTaskExecutor.setTaskDecorator(new ContextCopyingDecorator()); + threadPoolTaskExecutor.initialize(); + return threadPoolTaskExecutor; + } + + + static class ContextCopyingDecorator implements TaskDecorator { + @Nonnull + @Override + public Runnable decorate(@Nonnull Runnable runnable) { + RequestAttributes context = RequestContextHolder.currentRequestAttributes(); + HttpHeaders headers = (HttpHeaders) ThreadLocalUtil.get("bladeContext"); + Map mdcMap = MDC.getCopyOfContextMap(); + return () -> { + try { + ThreadLocalUtil.put("bladeContext", headers); + if (mdcMap != null && !mdcMap.isEmpty()) { + MDC.setContextMap(mdcMap); + } + RequestContextHolder.setRequestAttributes(context); + + runnable.run(); + } finally { + RequestContextHolder.resetRequestAttributes(); + if (mdcMap != null) { + mdcMap.clear(); + } + ThreadLocalUtil.clear(); + MDC.clear(); + } + }; + } + } + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/InterceptorAdapterConfig.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/InterceptorAdapterConfig.java new file mode 100644 index 000000000..6ee97e0d1 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/config/InterceptorAdapterConfig.java @@ -0,0 +1,29 @@ +package com.logpm.factorydata.zbom.config; + +import com.logpm.factorydata.zbom.interceptor.LocalServerLoginAccountsInterceptor; +import com.logpm.factorydata.zbom.interceptor.ZbFactoryAccountsInterceptor; +import com.logpm.factorydata.zbom.pros.ZbFactoryProperties; +import com.logpm.factorydata.zbom.service.IFactoryTokenService; +import lombok.AllArgsConstructor; +import org.springblade.core.redis.cache.BladeRedis; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@AllArgsConstructor +public class InterceptorAdapterConfig implements WebMvcConfigurer { + + private final BladeRedis redis; + private final ZbFactoryProperties zbFactoryProperties; + private final Environment environment; + + @Override + public void addInterceptors(InterceptorRegistry interceptorRegistry) { + interceptorRegistry.addInterceptor(new ZbFactoryAccountsInterceptor(zbFactoryProperties)) + .addPathPatterns("/**").order(2); + interceptorRegistry.addInterceptor(new LocalServerLoginAccountsInterceptor(redis, environment)) + .addPathPatterns("/**").order(3); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/controller/OrderController.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/controller/OrderController.java index 8a1d9ddd7..0e348ef7d 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/controller/OrderController.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/controller/OrderController.java @@ -1,15 +1,19 @@ package com.logpm.factorydata.zbom.controller; import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; +import com.logpm.factorydata.enums.SaxStatusEnums; import com.logpm.factorydata.feign.IFactoryDataClient; import com.logpm.factorydata.vo.SendMsg; import com.logpm.factorydata.zbom.constants.ZbomConstants; +import com.logpm.factorydata.zbom.entity.FactoryLogEntity; import com.logpm.factorydata.zbom.entity.ZbFactoryOrderLogEntity; import com.logpm.factorydata.zbom.entity.ZbReceiptEntity; +import com.logpm.factorydata.zbom.service.FactoryLogService; import com.logpm.factorydata.zbom.service.IFactoryOrderLogService; import com.logpm.factorydata.zbom.service.IReceiptService; import com.logpm.factorydata.zbom.vo.ZBReceiptDTO; @@ -18,14 +22,29 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.IOUtils; +import org.jetbrains.annotations.NotNull; import org.springblade.common.constant.factorydata.FactoryDataConstants; +import org.springblade.common.utils.FileLogsUtil; +import org.springblade.core.oss.model.BladeFile; +import org.springblade.core.tool.api.R; +import org.springblade.resource.feign.IOssClient; +import org.springframework.http.MediaType; 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.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; /** * 工厂订单 前端控制器 @@ -41,8 +60,9 @@ import javax.servlet.http.HttpServletRequest; public class OrderController { private final IFactoryDataClient factoryDataClient; - private final IFactoryOrderLogService orderLogService; - private final IReceiptService receiptService; + private final FactoryLogService factoryLogService; + + private final IOssClient ossClient; @ResponseBody @@ -58,17 +78,61 @@ public class OrderController { } String corpId = request.getHeader("corpId"); zbReceiptDTO.setCorpId(corpId); - // 已经推送过的数据不再接收 - if (CollUtil.isNotEmpty(receiptService.list(Wrappers.lambdaQuery().eq(ZbReceiptEntity::getTaskCode, zbReceiptDTO.getTaskCode())))) { - return ZbResp.fail("该入库单号已推送过,无需重复推送"); - } - // 记录日志 - ZbFactoryOrderLogEntity logEntity = ZbFactoryOrderLogEntity.builder().content(JSONUtil.toJsonStr(zbReceiptDTO)).build(); - orderLogService.save(logEntity); - // 将消息发送给 mq,解析保存 - SendMsg build = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.FACTORY_ORDER).routingKey(FactoryDataConstants.Mq.RoutingKeys.ZBOM_FACTORY_ORDER).message(jsonStr).build(); + + // 1 上传数据到 minio 获取到地址 + String url = uploadFile(JSONUtil.toJsonStr(zbReceiptDTO)); + // 2 保存地址到数据库 + FactoryLogEntity logEntity = new FactoryLogEntity(); + logEntity.setType(1); + logEntity.setSaxStatus(SaxStatusEnums.NOMAL.getCode()); + logEntity.setLogUrl(url); + factoryLogService.save(logEntity); + + // 3 将消息发送给 mq,解析保存 + SendMsg build = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.FACTORY_ORDER) + .routingKey(FactoryDataConstants.Mq.RoutingKeys.ZBOM_FACTORY_ORDER) + .message(JSONUtil.toJsonStr(logEntity)).build(); factoryDataClient.sendMessage(build); return ZbResp.success("成功"); } + + private String uploadFile(String body) { + //文本内容和保存为本地文件 并上传 + String logPath = FileLogsUtil.saveFileLogs(body); + log.info(">>> 文件路径 {}", logPath); + + MultipartFile multi = getMultipartFile(logPath); + //上传到服务器 + R r = ossClient.fileUpload(multi, "zb-order-logs"); + if (r.isSuccess()) { + BladeFile data = (BladeFile) r.getData(); + // 删除本地文件 + FileUtil.del(logPath); + return data.getLink(); + } + return null; + } + + @NotNull + private MultipartFile getMultipartFile(String logPath) { + File file = new File(logPath); + + // File 转 MultipartFile + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , file.getName()); + try ( + InputStream input = Files.newInputStream(file.toPath()); + OutputStream os = item.getOutputStream()) { + // 流转移 + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + + return new CommonsMultipartFile(item); + } + } diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryLogEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryLogEntity.java new file mode 100644 index 000000000..2e9f08f13 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryLogEntity.java @@ -0,0 +1,58 @@ +package com.logpm.factorydata.zbom.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.springblade.core.mp.base.BaseEntity; + +@Data +@TableName("zb_factory_log") +@ApiModel(value = "接收工厂订单日志", description = "接收工厂订单日志") +@EqualsAndHashCode(callSuper = true) +public class FactoryLogEntity extends BaseEntity { + + /** + * 预留1 + */ + @ApiModelProperty(name = "预留1", notes = "") + private String reserve1; + /** + * 预留2 + */ + @ApiModelProperty(name = "预留2", notes = "") + private String reserve2; + /** + * 预留3 + */ + @ApiModelProperty(name = "预留3", notes = "") + private String reserve3; + /** + * 预留4 + */ + @ApiModelProperty(name = "预留4", notes = "") + private String reserve4; + /** + * 预留5 + */ + @ApiModelProperty(name = "预留5", notes = "") + private String reserve5; + /** + * 日志文件存放地址 + */ + @ApiModelProperty(name = "日志文件存放地址", notes = "") + private String logUrl; + /** + * 数据类型 1.入库数据 + */ + @ApiModelProperty(name = "数据类型 1.入库数据", notes = "") + private Integer type; + /** + * 解析状态 0 未解析 1 解析失败 2 已解析 + */ + @ApiModelProperty(name = "解析状态 0 未解析 1 解析失败 2 已解析", notes = "") + private Integer saxStatus; + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryToken.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryToken.java new file mode 100644 index 000000000..e72454914 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/FactoryToken.java @@ -0,0 +1,32 @@ +package com.logpm.factorydata.zbom.entity; + +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 org.springblade.core.mp.base.BaseEntity; + +import java.util.Date; + +@Data +@TableName("factory_token") +@ApiModel(value = "FactoryToken对象", description = "工厂账户token") +public class FactoryToken extends BaseEntity { + + @ApiModelProperty("token") + private String token; + + @ApiModelProperty("token摘要") + private String tokenAbst; + + @JsonFormat( + pattern = "yyyy-MM-dd HH:mm:ss" + ) + @ApiModelProperty("过期时间") + private Date expireTime; + + @ApiModelProperty("企业id") + private String corpid; + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbFactoryOrderLogEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbFactoryOrderLogEntity.java index ac2243b9f..c26a1e625 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbFactoryOrderLogEntity.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbFactoryOrderLogEntity.java @@ -11,7 +11,7 @@ import lombok.NoArgsConstructor; import org.springblade.core.mp.base.BaseEntity; /** - * 志邦发货单接收日志 + * 志邦发货单接收日志 替换为上传文件的记录方式 FactoryLogEntity * * @Author zqb * @Date 2024/3/26 diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbOrderPackageEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbOrderPackageEntity.java index e21e67bb4..afa4d8ba5 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbOrderPackageEntity.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbOrderPackageEntity.java @@ -21,6 +21,8 @@ import org.springblade.core.mp.base.BaseEntity; @EqualsAndHashCode(callSuper = true) public class ZbOrderPackageEntity extends BaseEntity { + @ApiModelProperty(name = "日志id", notes = "") + private String logId; /** * 关联入库单ID */ diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbPackageInfoEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbPackageInfoEntity.java index c6acb5737..bef3bdbb7 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbPackageInfoEntity.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbPackageInfoEntity.java @@ -21,7 +21,8 @@ import org.springblade.core.mp.base.BaseEntity; @EqualsAndHashCode(callSuper = true) public class ZbPackageInfoEntity extends BaseEntity { - + @ApiModelProperty(name = "日志id", notes = "") + private String logId; /** 物料编码 */ @ApiModelProperty(name = "物料编码", notes = "") private String itemCode; diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbReceiptEntity.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbReceiptEntity.java index 7b6553bea..cf96e56d0 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbReceiptEntity.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/entity/ZbReceiptEntity.java @@ -25,6 +25,8 @@ import javax.validation.constraints.NotEmpty; public class ZbReceiptEntity extends BaseEntity { + @ApiModelProperty(name = "日志id", notes = "") + private String logId; @ApiModelProperty(name = "工厂账号", notes = "") private String corpId; /** diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/FactoryAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/FactoryAccountsInterceptor.java new file mode 100644 index 000000000..2ccc2bf53 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/FactoryAccountsInterceptor.java @@ -0,0 +1,87 @@ +package com.logpm.factorydata.zbom.interceptor; + +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.zbom.service.IFactoryTokenService; +import com.logpm.factorydata.zbom.wrapper.RequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.StringUtil; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@Log4j2 +@AllArgsConstructor +public class FactoryAccountsInterceptor implements HandlerInterceptor { + + private final IFactoryTokenService factoryTokenService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + try { + + RequestWrapper myRequestWrapper = new RequestWrapper(request); + String body = myRequestWrapper.getBody(); + JSONObject jsonObject = JSONObject.parseObject(body); + //获取头中参数 + String token = request.getHeader("Authorization"); + String corpId = request.getHeader("corpid"); + if(StringUtil.isBlank(corpId)){ + corpId = jsonObject.getString("corpid"); + } + if(!StringUtil.hasLength(token)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token有误"))); + return false; + } + if(!StringUtil.hasLength(corpId)){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,corpId有误"))); + return false; + } + + log.info("##########preHandle: token={}",token); + //验证token + boolean b = factoryTokenService.verifyToken(token,corpId); + if(!b){ + returnJson(response,JSONObject.toJSONString(R.fail(203,"认证不通过,token不存在或已过期"))); + return false; + } + return true; + } catch (Exception e) { + returnJson(response,JSONObject.toJSONString(R.fail(500,"服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null){ + writer.close(); + } + } + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + HandlerInterceptor.super.afterCompletion(request, response, handler, ex); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/LocalServerLoginAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/LocalServerLoginAccountsInterceptor.java new file mode 100644 index 000000000..8d4e22760 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/LocalServerLoginAccountsInterceptor.java @@ -0,0 +1,100 @@ +package com.logpm.factorydata.zbom.interceptor; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import com.alibaba.fastjson.JSONObject; +import com.logpm.factorydata.zbom.wrapper.CustomHttpServletRequestWrapper; +import lombok.AllArgsConstructor; +import lombok.extern.log4j.Log4j2; +import org.springblade.common.cache.CacheNames; +import org.springblade.common.constant.LauncherConstant; +import org.springblade.common.exception.CustomerException; +import org.springblade.core.redis.cache.BladeRedis; +import org.springblade.core.tool.api.R; +import org.springblade.core.tool.utils.ThreadLocalUtil; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@Log4j2 +@AllArgsConstructor +public class LocalServerLoginAccountsInterceptor extends HandlerInterceptorAdapter { + + private final BladeRedis bladeRedis; + private final Environment environment; + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomerException { + + + try { + CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(request); + String account ="shujutongbu"; + JSONObject data =bladeRedis.get(CacheNames.LOCAL_SERVER_USER+account); + if(Objects.isNull(data)){ + String url = "http://"+ LauncherConstant.loginAddr(Objects.requireNonNull(environment.getActiveProfiles()[0]))+"/blade-auth/oauth/token"; + HttpRequest urlRequest = HttpRequest.post(url); + urlRequest.header("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + urlRequest.header("Tenant-Id", "627683"); + + Map params = new HashMap<>(); + params.put("grant_type", "local_server"); + params.put("scope", "all"); + params.put("username", account); + params.put("tenantId", "627683"); + HttpResponse execute = urlRequest.form(params).execute(); + String body = execute.body(); + data = JSONObject.parseObject(body); + bladeRedis.setEx(CacheNames.LOCAL_SERVER_USER+account,data,3200L); + } + + // 修改或添加header + + // 发送登录请求 + log.info("##########preHandle: request={}", request); + + wrappedRequest.addHeader("Blade-Auth", "bearer "+data.getString("access_token")); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add("Blade-Auth","bearer "+data.get("access_token") ); + httpHeaders.add( "Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0"); + ThreadLocalUtil.put("bladeContext", httpHeaders); + + + // 用包装后的request替换原始request + request = wrappedRequest; + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + return true; + } catch (Exception e) { + returnJson(response, JSONObject.toJSONString(R.fail(500, "服务异常,请联系管理员"))); + return false; + } + } + + private void returnJson(HttpServletResponse response, String json) { + PrintWriter writer = null; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + try { + writer = response.getWriter(); + writer.print(json); + + } catch (IOException e) { + System.out.println(e.getMessage()); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/ZbFactoryAccountsInterceptor.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/ZbFactoryAccountsInterceptor.java index 0c558d3fd..af55bbf83 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/ZbFactoryAccountsInterceptor.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/interceptor/ZbFactoryAccountsInterceptor.java @@ -1,9 +1,9 @@ package com.logpm.factorydata.zbom.interceptor; import com.alibaba.fastjson.JSONObject; -import com.logpm.factorydata.zbom.config.RequestWrapper; import com.logpm.factorydata.zbom.pros.ZbFactoryProperties; import com.logpm.factorydata.zbom.util.QmSignUntil; +import com.logpm.factorydata.zbom.wrapper.RequestWrapper; import lombok.AllArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springblade.core.tool.api.R; diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.java new file mode 100644 index 000000000..f24cb26b0 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the dreamlu.net developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: Chill 庄骞 (smallchill@163.com) + */ +package com.logpm.factorydata.zbom.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.logpm.factorydata.zbom.entity.FactoryLogEntity; +import org.apache.ibatis.annotations.Mapper; + +/** + * 接收发货单日志 Mapper + * + * @author zqb + * @since 2024-03-26 + */ +@Mapper +public interface FactoryLogMapper extends BaseMapper { + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.xml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.xml new file mode 100644 index 000000000..a18fd4864 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryLogMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.java new file mode 100644 index 000000000..676b8842a --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the dreamlu.net developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: Chill 庄骞 (smallchill@163.com) + */ +package com.logpm.factorydata.zbom.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.logpm.factorydata.zbom.entity.FactoryToken; + +/** + * 工厂账号接口日志 Mapper 接口 + * + * @author zhy + * @since 2023-03-28 + */ +public interface FactoryTokenMapper extends BaseMapper { + + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.xml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.xml new file mode 100644 index 000000000..f4b775aa8 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mapper/FactoryTokenMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mq/ZbomFactoryOrderListener.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mq/ZbomFactoryOrderListener.java index 4780ff841..fd49d73cc 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mq/ZbomFactoryOrderListener.java +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/mq/ZbomFactoryOrderListener.java @@ -4,9 +4,14 @@ import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.URLUtil; +import cn.hutool.json.JSONArray; +import cn.hutool.json.JSONConfig; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; @@ -15,6 +20,7 @@ import com.logpm.factorydata.base.feign.IFactoryDataBaseClient; import com.logpm.factorydata.base.vo.FactoryWarehouseBindVO; import com.logpm.factorydata.feign.IFactoryDataClient; import com.logpm.factorydata.vo.SendMsg; +import com.logpm.factorydata.zbom.entity.FactoryLogEntity; import com.logpm.factorydata.zbom.entity.ZbCategoryContrastEntity; import com.logpm.factorydata.zbom.entity.ZbOrderPackageEntity; import com.logpm.factorydata.zbom.entity.ZbPackageInfoEntity; @@ -23,7 +29,6 @@ import com.logpm.factorydata.zbom.mapper.ZbCategoryContrastMapper; import com.logpm.factorydata.zbom.service.IOrderPackageService; import com.logpm.factorydata.zbom.service.IPackageInfoService; import com.logpm.factorydata.zbom.service.IReceiptService; -import com.logpm.factorydata.zbom.util.ThreadPoolUtil; import com.logpm.factorydata.zbom.vo.OrderPackageDTO; import com.logpm.factorydata.zbom.vo.PackageInfoDTO; import com.logpm.factorydata.zbom.vo.ZBReceiptDTO; @@ -44,6 +49,7 @@ import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -86,11 +92,30 @@ public class ZbomFactoryOrderListener { )) @Transactional(rollbackFor = Exception.class) public void factoryOrder(String msg) { + log.info("处理志邦订单:{}", msg); if (StrUtil.isEmpty(msg)) { log.error("消息内容为空"); return; } - ZBReceiptDTO zbReceiptDTO = JSONUtil.toBean(msg, ZBReceiptDTO.class); + FactoryLogEntity logEntity = JSONUtil.toBean(msg, FactoryLogEntity.class); + if (ObjectUtil.isEmpty(logEntity)) { + log.error("消息内容为空"); + return; + } + // 去 minio 下载文件到本地,然后解析文件内容为实体对象 + ZBReceiptDTO zbReceiptDTO = null; + Long logId = logEntity.getId(); + String logUrl = logEntity.getLogUrl(); + if (StrUtil.isNotEmpty(logUrl)) { + List res = new ArrayList<>(); + FileUtil.readLines(URLUtil.url(logUrl), CharsetUtil.CHARSET_UTF_8, res); + if (CollUtil.isNotEmpty(res)) { + String content = res.get(0); + if (StrUtil.isNotEmpty(content)) { + zbReceiptDTO = JSONUtil.toBean(content, ZBReceiptDTO.class); + } + } + } if (ObjectUtil.isEmpty(zbReceiptDTO)) { log.error("消息内容为空"); return; @@ -102,7 +127,7 @@ public class ZbomFactoryOrderListener { return; } if (CollUtil.isNotEmpty(receiptService.list(Wrappers.lambdaQuery().eq(ZbReceiptEntity::getTaskCode, taskCode)))) { - log.error("入库单号已推送过了"); + log.error("入库单号 {} 已推送过了", taskCode); return; } // 查询当前这次推送的数据中的所有包件,校验其是否在数据库中已存在,存在则不保存 @@ -122,6 +147,7 @@ public class ZbomFactoryOrderListener { } } ZbReceiptEntity zbReceiptEntity = new ZbReceiptEntity(); + zbReceiptEntity.setLogId(ObjectUtil.isNotEmpty(logId) ? logId.toString() : null); BeanUtil.copyProperties(zbReceiptDTO, zbReceiptEntity); // 保存订单数据 receiptService.save(zbReceiptEntity); @@ -136,6 +162,7 @@ public class ZbomFactoryOrderListener { ZbOrderPackageEntity packageEntity = new ZbOrderPackageEntity(); BeanUtil.copyProperties(detail, packageEntity); packageEntity.setReceiptId(zbReceiptEntity.getId()); + packageEntity.setLogId(ObjectUtil.isNotEmpty(logId) ? logId.toString() : null); packageEntities.add(packageEntity); } // 保存包件数据 @@ -156,6 +183,7 @@ public class ZbomFactoryOrderListener { ZbPackageInfoEntity packageInfoEntity = new ZbPackageInfoEntity(); BeanUtil.copyProperties(item, packageInfoEntity); packageInfoEntity.setPackageId(detailId); + packageInfoEntity.setLogId(ObjectUtil.isNotEmpty(logId) ? logId.toString() : null); packageInfoEntities.add(packageInfoEntity); } } @@ -167,171 +195,169 @@ public class ZbomFactoryOrderListener { buildAdvance(zbReceiptDTO, packageCode); } - private void buildAdvance(ZBReceiptDTO zbReceiptDTO, Set packageCode) { + @Async("asyncExecutor") + public void buildAdvance(ZBReceiptDTO zbReceiptDTO, Set packageCode) { // 新起线程构建暂存单发送mq - ThreadPoolUtil.getThreadPool().submit(() -> { - Long startWarehouseId = null; - String startWarehouseName = null; - String tenantId = null; - // 获取工厂基地绑定的始发仓信息 - R warehouseByBrandAndSiteName = baseClient.getWarehouseByBrandAndSiteName(zbReceiptDTO.getSenderName(), zbReceiptDTO.getSenderName()); - if (ObjectUtil.equal(HttpConstants.HTTP.HTTP_RESOURCE_CODE.SUCCESS_CODE, warehouseByBrandAndSiteName.getCode())) { - FactoryWarehouseBindVO data = warehouseByBrandAndSiteName.getData(); - if (ObjectUtil.isNotNull(data)) { - startWarehouseId = data.getWarehouseId(); - startWarehouseName = data.getWarehouseName(); - tenantId = data.getTenantId(); - } + Long startWarehouseId = null; + String startWarehouseName = null; + String tenantId = null; + // 获取工厂基地绑定的始发仓信息 + R warehouseByBrandAndSiteName = baseClient.getWarehouseByBrandAndSiteName(zbReceiptDTO.getSenderName(), zbReceiptDTO.getSenderName()); + if (ObjectUtil.equal(HttpConstants.HTTP.HTTP_RESOURCE_CODE.SUCCESS_CODE, warehouseByBrandAndSiteName.getCode())) { + FactoryWarehouseBindVO data = warehouseByBrandAndSiteName.getData(); + if (ObjectUtil.isNotNull(data)) { + startWarehouseId = data.getWarehouseId(); + startWarehouseName = data.getWarehouseName(); + tenantId = data.getTenantId(); } - Map> advanceMap = new HashMap<>(); - List details = zbReceiptDTO.getDetails(); - // 入库单号 + 订单自编号 + 发车单号 一个暂存单 - for (OrderPackageDTO detail : details) { - if (packageCode.contains(detail.getPackageCode())) { - log.info(" 接收志邦数据:包条码 {} 已存在数据库中,不生成暂存单。", detail.getPackageCode()); - continue; - } - String taskCode = zbReceiptDTO.getTaskCode(); - String departCode = zbReceiptDTO.getDepartCode(); - String platformOrderCode = detail.getPlatformOrderCode(); - String advanceKey = taskCode + departCode + platformOrderCode; - if (advanceMap.containsKey(advanceKey)) { - advanceMap.get(advanceKey).add(detail); - } else { - ArrayList orderPackageDTOS = new ArrayList<>(); - orderPackageDTOS.add(detail); - advanceMap.put(advanceKey, orderPackageDTOS); - } + } + Map> advanceMap = new HashMap<>(); + List details = zbReceiptDTO.getDetails(); + // 入库单号 + 订单自编号 + 发车单号 一个暂存单 + for (OrderPackageDTO detail : details) { + if (packageCode.contains(detail.getPackageCode())) { + log.info(" 接收志邦数据:包条码 {} 已存在数据库中,不生成暂存单。", detail.getPackageCode()); + continue; + } + String taskCode = zbReceiptDTO.getTaskCode(); + String departCode = zbReceiptDTO.getDepartCode(); + String platformOrderCode = detail.getPlatformOrderCode(); + String advanceKey = taskCode + departCode + platformOrderCode; + if (advanceMap.containsKey(advanceKey)) { + advanceMap.get(advanceKey).add(detail); + } else { + ArrayList orderPackageDTOS = new ArrayList<>(); + orderPackageDTOS.add(detail); + advanceMap.put(advanceKey, orderPackageDTOS); } - // 组装暂存单数据 - List advances = new ArrayList<>(); - for (Map.Entry> stringListEntry : advanceMap.entrySet()) { - List value = stringListEntry.getValue(); - TrunklineAdvanceEntity advanceEntity = new TrunklineAdvanceEntity(); - advanceEntity.setTenantId(tenantId); - advanceEntity.setStatus(0); - advanceEntity.setIsDeleted(0); - advanceEntity.setHasPackage(CollUtil.isNotEmpty(zbReceiptDTO.getDetails()) ? 1 : 0); - advanceEntity.setOrderType(zbReceiptDTO.getOrderType()); - advanceEntity.setBrand(zbReceiptDTO.getSenderName()); - advanceEntity.setSiteName(""); - advanceEntity.setArea(""); - advanceEntity.setTotalNum(CollUtil.isNotEmpty(value) ? value.size() : 0); - advanceEntity.setPackName(""); - advanceEntity.setPackCode(""); - advanceEntity.setWarehouseId(startWarehouseId); - advanceEntity.setWarehouseName(startWarehouseName); + } + // 组装暂存单数据 + List advances = new ArrayList<>(); + for (Map.Entry> stringListEntry : advanceMap.entrySet()) { + List value = stringListEntry.getValue(); + TrunklineAdvanceEntity advanceEntity = new TrunklineAdvanceEntity(); + advanceEntity.setTenantId(tenantId); + advanceEntity.setStatus(0); + advanceEntity.setIsDeleted(0); + advanceEntity.setHasPackage(CollUtil.isNotEmpty(zbReceiptDTO.getDetails()) ? 1 : 0); + advanceEntity.setOrderType(zbReceiptDTO.getOrderType()); + advanceEntity.setBrand(zbReceiptDTO.getSenderName()); + advanceEntity.setSiteName(""); + advanceEntity.setArea(""); + advanceEntity.setTotalNum(CollUtil.isNotEmpty(value) ? value.size() : 0); + advanceEntity.setPackName(""); + advanceEntity.setPackCode(""); + advanceEntity.setWarehouseId(startWarehouseId); + advanceEntity.setWarehouseName(startWarehouseName); - advanceEntity.setIsGcp(0); - advanceEntity.setCarrierName(zbReceiptDTO.getVendorName()); - advanceEntity.setSystemType("线上"); - advanceEntity.setMatingType(""); - advanceEntity.setSenderName(zbReceiptDTO.getSenderName()); - advanceEntity.setSenderPhone(zbReceiptDTO.getSenderTel()); - advanceEntity.setSenderAddress(zbReceiptDTO.getSenderAddress()); - advanceEntity.setWaybillStatus("0"); - advanceEntity.setWaybillNo(""); - advanceEntity.setTrainNumber(zbReceiptDTO.getDepartCode()); - advanceEntity.setFreezeStatus("0"); + advanceEntity.setIsGcp(0); + advanceEntity.setCarrierName(zbReceiptDTO.getVendorName()); + advanceEntity.setSystemType("线上"); + advanceEntity.setMatingType("1"); + advanceEntity.setSenderName(zbReceiptDTO.getSenderName()); + advanceEntity.setSenderPhone(zbReceiptDTO.getSenderTel()); + advanceEntity.setSenderAddress(zbReceiptDTO.getSenderAddress()); + advanceEntity.setWaybillStatus("0"); + advanceEntity.setWaybillNo(""); + advanceEntity.setTrainNumber(zbReceiptDTO.getDepartCode()); + advanceEntity.setFreezeStatus("0"); - advanceEntity.setSenderFactory(zbReceiptDTO.getSenderName()); - List packageList = new ArrayList<>(); - for (OrderPackageDTO orderPackageDTO : value) { - advanceEntity.setOrderCode(orderPackageDTO.getPlatformOrderCode()); - advanceEntity.setDealerCode(orderPackageDTO.getCustomerCode()); - advanceEntity.setDealerName(orderPackageDTO.getCustomerName()); - advanceEntity.setStoreCode(orderPackageDTO.getCustomerCode()); - advanceEntity.setStoreName(orderPackageDTO.getCustomerName()); - advanceEntity.setServiceNum(orderPackageDTO.getRelationOrderCode()); - advanceEntity.setCustomerName(orderPackageDTO.getReceiverName()); - advanceEntity.setCustomerPhone(orderPackageDTO.getReceiverMobile()); - advanceEntity.setCustomerAddress(orderPackageDTO.getReceiverAddress()); + advanceEntity.setSenderFactory(zbReceiptDTO.getSenderName()); + List packageList = new ArrayList<>(); + for (OrderPackageDTO orderPackageDTO : value) { + advanceEntity.setOrderCode(orderPackageDTO.getPlatformOrderCode()); + advanceEntity.setDealerCode(orderPackageDTO.getCustomerCode()); + advanceEntity.setDealerName(orderPackageDTO.getCustomerName()); + advanceEntity.setStoreCode(orderPackageDTO.getCustomerCode()); + advanceEntity.setStoreName(orderPackageDTO.getCustomerName()); + advanceEntity.setServiceNum(orderPackageDTO.getRelationOrderCode()); + advanceEntity.setCustomerName(orderPackageDTO.getReceiverName()); + advanceEntity.setCustomerPhone(orderPackageDTO.getReceiverMobile()); + advanceEntity.setCustomerAddress(orderPackageDTO.getReceiverAddress()); - // 封装包件 - TrunklineAdvanceDetailEntity advanceDetailEntity = new TrunklineAdvanceDetailEntity(); - advanceDetailEntity.setWarehouseId(startWarehouseId); - advanceDetailEntity.setWarehouseName(startWarehouseName); + // 封装包件 + TrunklineAdvanceDetailEntity advanceDetailEntity = new TrunklineAdvanceDetailEntity(); + advanceDetailEntity.setWarehouseId(startWarehouseId); + advanceDetailEntity.setWarehouseName(startWarehouseName); // advanceDetailEntity.setIncomingWarehouseId(0L); // advanceDetailEntity.setIncomingWarehouseName(""); - // 根据志邦的一流单标识赋值 - advanceEntity.setLegacyStatus("0"); - if (ObjectUtil.equal(orderPackageDTO.getLegacyFlag(), "Y")) { - advanceEntity.setLegacyStatus("1"); - } + // 根据志邦的一流单标识赋值 + advanceEntity.setLegacyStatus("0"); + if (ObjectUtil.equal(orderPackageDTO.getLegacyFlag(), "Y")) { + advanceEntity.setLegacyStatus("1"); + } - advanceDetailEntity.setOrderCode(orderPackageDTO.getPlatformOrderCode()); - advanceDetailEntity.setBrand(zbReceiptDTO.getSenderName()); - advanceDetailEntity.setSystemType("线上"); - advanceDetailEntity.setFirstPackName(orderPackageDTO.getPackageTypeName()); - advanceDetailEntity.setFirstPackCode(orderPackageDTO.getPackageType()); - // 获取映射志邦映射品类信息 - ZbCategoryContrastEntity zbCategoryContrastEntity = buildZbCategoryContrastEntityCache(orderPackageDTO.getPackageClass()); - if (zbCategoryContrastEntity != null) { - advanceDetailEntity.setSecondPackName(zbCategoryContrastEntity.getSecondName());//二级品类名称 - advanceDetailEntity.setSecondPackCode(zbCategoryContrastEntity.getSecondCode());//二级品类 - advanceDetailEntity.setThirdPackName(zbCategoryContrastEntity.getThirdName());//三级品类名称 - advanceDetailEntity.setThirdPackCode(zbCategoryContrastEntity.getThirdCode());//三级品类 - } else { - advanceDetailEntity.setSecondPackName(StringUtil.isBlank(orderPackageDTO.getPackageClass()) ? "" : orderPackageDTO.getPackageClass());//二级品类名称 - advanceDetailEntity.setSecondPackCode("");//二级品类 - advanceDetailEntity.setThirdPackName(StringUtil.isBlank(orderPackageDTO.getPackageClass()) ? "" : orderPackageDTO.getPackageClass());//三级品类名称 - advanceDetailEntity.setThirdPackCode("");//三级品类 - } - advanceDetailEntity.setSiteName(""); - advanceDetailEntity.setSiteCode(""); - String planQty = orderPackageDTO.getPlanQty(); - advanceDetailEntity.setQuantity((StrUtil.isNotBlank(planQty) && NumberUtil.isNumber(planQty)) ? Convert.toInt(planQty) : 0); - advanceDetailEntity.setOrderPackageCode(orderPackageDTO.getPackageCode()); - advanceDetailEntity.setTrainNumber(zbReceiptDTO.getDepartCode()); - advanceDetailEntity.setServiceNum(orderPackageDTO.getRelationOrderCode()); - advanceDetailEntity.setWaybillNo(""); - advanceDetailEntity.setPackageStatus("0"); - advanceDetailEntity.setWeight(StrUtil.isNotBlank(orderPackageDTO.getTotalGrossWeight()) ? new BigDecimal(orderPackageDTO.getTotalGrossWeight()) : BigDecimal.ZERO); - advanceDetailEntity.setVolume(StrUtil.isNotBlank(orderPackageDTO.getTotalVolume()) ? new BigDecimal(orderPackageDTO.getTotalVolume()) : BigDecimal.ZERO); + advanceDetailEntity.setOrderCode(orderPackageDTO.getPlatformOrderCode()); + advanceDetailEntity.setBrand(zbReceiptDTO.getSenderName()); + advanceDetailEntity.setSystemType("线上"); + advanceDetailEntity.setFirstPackName(orderPackageDTO.getPackageTypeName()); + advanceDetailEntity.setFirstPackCode(orderPackageDTO.getPackageType()); + // 获取映射志邦映射品类信息 + ZbCategoryContrastEntity zbCategoryContrastEntity = buildZbCategoryContrastEntityCache(orderPackageDTO.getPackageClass()); + if (zbCategoryContrastEntity != null) { + advanceDetailEntity.setSecondPackName(zbCategoryContrastEntity.getSecondName());//二级品类名称 + advanceDetailEntity.setSecondPackCode(zbCategoryContrastEntity.getSecondCode());//二级品类 + advanceDetailEntity.setThirdPackName(zbCategoryContrastEntity.getThirdName());//三级品类名称 + advanceDetailEntity.setThirdPackCode(zbCategoryContrastEntity.getThirdCode());//三级品类 + } else { + advanceDetailEntity.setSecondPackName(StringUtil.isBlank(orderPackageDTO.getPackageClass()) ? "" : orderPackageDTO.getPackageClass());//二级品类名称 + advanceDetailEntity.setSecondPackCode("");//二级品类 + advanceDetailEntity.setThirdPackName(StringUtil.isBlank(orderPackageDTO.getPackageClass()) ? "" : orderPackageDTO.getPackageClass());//三级品类名称 + advanceDetailEntity.setThirdPackCode("");//三级品类 + } + advanceDetailEntity.setSiteName(""); + advanceDetailEntity.setSiteCode(""); + String planQty = orderPackageDTO.getPlanQty(); + advanceDetailEntity.setQuantity((StrUtil.isNotBlank(planQty) && NumberUtil.isNumber(planQty)) ? Convert.toInt(planQty) : 0); + advanceDetailEntity.setOrderPackageCode(orderPackageDTO.getPackageCode()); + advanceDetailEntity.setTrainNumber(zbReceiptDTO.getDepartCode()); + advanceDetailEntity.setServiceNum(orderPackageDTO.getRelationOrderCode()); + advanceDetailEntity.setWaybillNo(""); + advanceDetailEntity.setPackageStatus("0"); + advanceDetailEntity.setWeight(StrUtil.isNotBlank(orderPackageDTO.getTotalGrossWeight()) ? new BigDecimal(orderPackageDTO.getTotalGrossWeight()) : BigDecimal.ZERO); + advanceDetailEntity.setVolume(StrUtil.isNotBlank(orderPackageDTO.getTotalVolume()) ? new BigDecimal(orderPackageDTO.getTotalVolume()) : BigDecimal.ZERO); // advanceDetailEntity.setChargeType(0); - advanceDetailEntity.setSupple(""); - advanceDetailEntity.setManifest(""); - advanceDetailEntity.setReturnNum(""); - advanceDetailEntity.setSendDateStr(DateUtil.formatLocalDateTime(LocalDateTime.now())); - advanceDetailEntity.setCarNumber(""); - advanceDetailEntity.setGoodsMan(""); - advanceDetailEntity.setTenantId(tenantId); - advanceDetailEntity.setStatus(0); - advanceDetailEntity.setIsDeleted(0); - List itemJsons = new ArrayList<>(); - List items = orderPackageDTO.getItems(); - for (PackageInfoDTO item : items) { - TrunklineDetailProductEntity detailProductEntity = new TrunklineDetailProductEntity(); - detailProductEntity.setTenantId(tenantId); - detailProductEntity.setWarehouseId(startWarehouseId); - detailProductEntity.setWarehouseName(startWarehouseName); - detailProductEntity.setUnitNo(orderPackageDTO.getPackageCode()); - detailProductEntity.setProductCode(item.getItemCode()); - detailProductEntity.setProductName(item.getItemName()); - detailProductEntity.setQuantity(item.getPlanQty()); - detailProductEntity.setTenantId(TenantNum.HUITONGCODE); - detailProductEntity.setStatus(0); - detailProductEntity.setIsDeleted(0); - itemJsons.add(JSONUtil.parseObj(detailProductEntity)); - } - JSONObject entries = JSONUtil.parseObj(advanceDetailEntity); - entries.set("items", itemJsons); - packageList.add(entries); + advanceDetailEntity.setSupple(""); + advanceDetailEntity.setManifest(""); + advanceDetailEntity.setReturnNum(""); + advanceDetailEntity.setSendDateStr(DateUtil.formatLocalDateTime(LocalDateTime.now())); + advanceDetailEntity.setCarNumber(""); + advanceDetailEntity.setGoodsMan(""); + advanceDetailEntity.setTenantId(tenantId); + advanceDetailEntity.setStatus(0); + advanceDetailEntity.setIsDeleted(0); + List itemJsons = new ArrayList<>(); + List items = orderPackageDTO.getItems(); + for (PackageInfoDTO item : items) { + TrunklineDetailProductEntity detailProductEntity = new TrunklineDetailProductEntity(); + detailProductEntity.setTenantId(tenantId); + detailProductEntity.setWarehouseId(startWarehouseId); + detailProductEntity.setWarehouseName(startWarehouseName); + detailProductEntity.setUnitNo(orderPackageDTO.getPackageCode()); + detailProductEntity.setProductCode(item.getItemCode()); + detailProductEntity.setProductName(item.getItemName()); + detailProductEntity.setQuantity(item.getPlanQty()); + detailProductEntity.setStatus(0); + detailProductEntity.setIsDeleted(0); + itemJsons.add(JSONUtil.parseObj(detailProductEntity)); } - // 转成json对象,然后将包件明细放到detail中 - JSONObject entries = JSONUtil.parseObj(advanceEntity); - entries.set("details", JSONUtil.toJsonStr(packageList)); - advances.add(entries); + JSONObject entries = JSONUtil.parseObj(advanceDetailEntity); + entries.set("items", itemJsons); + packageList.add(entries); } - // 将组装好的暂存单发送到 MQ ,由暂存单服务统一消费SendMsg. - if (CollUtil.isNotEmpty(advances)) { - for (JSONObject advance : advances) { - SendMsg sendMsg = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.ADVANCE_ORDER) - .routingKey(FactoryDataConstants.Mq.RoutingKeys.ADVANCE_ORDER).message(JSONUtil.toJsonStr(advance)).build(); - factoryDataClient.sendMessage(sendMsg); - } + // 转成json对象,然后将包件明细放到detail中 + JSONObject entries = JSONUtil.parseObj(advanceEntity); + entries.set("details", JSONUtil.toJsonStr(packageList)); + advances.add(entries); + } + // 将组装好的暂存单发送到 MQ ,由暂存单服务统一消费SendMsg. + if (CollUtil.isNotEmpty(advances)) { + for (JSONObject advance : advances) { + SendMsg sendMsg = SendMsg.builder().exchange(FactoryDataConstants.Mq.Exchanges.ADVANCE_ORDER) + .routingKey(FactoryDataConstants.Mq.RoutingKeys.ADVANCE_ORDER).message(JSONUtil.toJsonStr(advance)).build(); + factoryDataClient.sendMessage(sendMsg); } - }); + } } private ZbCategoryContrastEntity buildZbCategoryContrastEntityCache(String packageClass) { diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/FactoryLogService.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/FactoryLogService.java new file mode 100644 index 000000000..97fb2001c --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/FactoryLogService.java @@ -0,0 +1,14 @@ +package com.logpm.factorydata.zbom.service; + +import com.logpm.factorydata.zbom.entity.FactoryLogEntity; +import org.springblade.core.mp.base.BaseService; + +/** + * 工厂订单日志 服务类 + * + * @Author zqb + * @Date 2024/4/26 + **/ +public interface FactoryLogService extends BaseService { + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/IFactoryTokenService.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/IFactoryTokenService.java new file mode 100644 index 000000000..87af56127 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/IFactoryTokenService.java @@ -0,0 +1,15 @@ +package com.logpm.factorydata.zbom.service; + +import com.logpm.factorydata.zbom.entity.FactoryToken; +import org.springblade.core.mp.base.BaseService; + +import java.security.NoSuchAlgorithmException; + +/** + * 工厂推送数据接口 + */ +public interface IFactoryTokenService extends BaseService { + + + boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException; +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryLogServiceImpl.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryLogServiceImpl.java new file mode 100644 index 000000000..95f402004 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryLogServiceImpl.java @@ -0,0 +1,22 @@ +package com.logpm.factorydata.zbom.service.impl; + +import com.logpm.factorydata.zbom.entity.FactoryLogEntity; +import com.logpm.factorydata.zbom.mapper.FactoryLogMapper; +import com.logpm.factorydata.zbom.service.FactoryLogService; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springblade.core.mp.base.BaseServiceImpl; +import org.springframework.stereotype.Service; + +/** + * 工厂订单日志 业务实现类 + * + * @Author zqb + * @Date 2024/4/26 + **/ +@Slf4j +@Service +@AllArgsConstructor +public class FactoryLogServiceImpl extends BaseServiceImpl implements FactoryLogService { + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryTokenServiceImpl.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryTokenServiceImpl.java new file mode 100644 index 000000000..115f84902 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/service/impl/FactoryTokenServiceImpl.java @@ -0,0 +1,62 @@ +package com.logpm.factorydata.zbom.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.logpm.factorydata.zbom.entity.FactoryToken; +import com.logpm.factorydata.zbom.mapper.FactoryTokenMapper; +import com.logpm.factorydata.zbom.service.IFactoryTokenService; +import lombok.AllArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springblade.core.mp.base.BaseServiceImpl; +import org.springblade.core.redis.cache.BladeRedis; +import org.springframework.stereotype.Service; + +import java.security.NoSuchAlgorithmException; +import java.util.Objects; + +@AllArgsConstructor +@Service +public class FactoryTokenServiceImpl extends BaseServiceImpl implements IFactoryTokenService { + + private static final Logger logger = LoggerFactory.getLogger(FactoryTokenServiceImpl.class); + + private final BladeRedis bladeRedis; + + @Override + public boolean verifyToken(String token, String corpId) throws NoSuchAlgorithmException { + logger.info("#########verifyToken: 验证token开始"); + //先生成token摘要 +// String tokenAbst = MD5Utils.md5Hex(token.getBytes(StandardCharsets.UTF_8)); + + //编写查询条件 + String key = "corpId:" + corpId; + FactoryToken factoryToken = bladeRedis.get(key); + + if (Objects.isNull(factoryToken)) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("token", token); + factoryToken = baseMapper.selectOne(queryWrapper); + } + + + if (Objects.isNull(factoryToken)) { + logger.error("#########verifyToken: token1验证不通过 token={},corpid={}", token, corpId); + return false; + } + logger.info("#########verifyToken: 验证token 传入token {} 验证token {}", token, factoryToken.getToken()); + if (!factoryToken.getToken().equals(token)) { + logger.error("#########verifyToken: token2验证不通过 token={},corpid={}", token, corpId); + return false; + } + + + Long expireTimeLong = factoryToken.getExpireTime().getTime(); + Long now = System.currentTimeMillis(); + //判断是否过期 + if (now > expireTimeLong) { + logger.error("#########verifyToken: token验证不通过 已过期 token={},corpId={}", token, corpId); + return false; + } + return true; + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/util/ThreadPoolUtil.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/util/ThreadPoolUtil.java deleted file mode 100644 index 911c162d6..000000000 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/util/ThreadPoolUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.logpm.factorydata.zbom.util; - -import cn.hutool.core.thread.ExecutorBuilder; -import cn.hutool.core.thread.ThreadFactoryBuilder; -import lombok.extern.slf4j.Slf4j; - -import java.util.concurrent.ExecutorService; - -/** - * @author zhaoqiaobo - * @create 2024-03-14 10:26 - */ -@Slf4j -public class ThreadPoolUtil { - - private ThreadPoolUtil() { - } - - /** - * 线程池 - */ - public static ExecutorService executor = null; - - static { - init(); - } - - synchronized public static void init() { - if (null != executor) { - executor.shutdownNow(); - } - executor = ExecutorBuilder.create() - .setCorePoolSize(8) - .setMaxPoolSize(20) - .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("logpm-factory-data-zbom-").build()) - .useSynchronousQueue().build(); - } - - public static ExecutorService getThreadPool() { - return executor; - } - -} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/CustomHttpServletRequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/CustomHttpServletRequestWrapper.java new file mode 100644 index 000000000..5639d49b7 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/CustomHttpServletRequestWrapper.java @@ -0,0 +1,38 @@ +package com.logpm.factorydata.zbom.wrapper; + +import org.springframework.http.HttpHeaders; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { + + private final HttpHeaders headers; + + public CustomHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + headers = new HttpHeaders(); + } + + @Override + public String getHeader(String name) { + String headerValue = headers.getFirst(name); + return headerValue != null ? headerValue : super.getHeader(name); + } + + @Override + public Enumeration getHeaderNames() { + List names = Collections.list(super.getHeaderNames()); + headers.forEach((key, value) -> names.add(key)); + return Collections.enumeration(names); + } + + // 其他需要覆盖的方法... + + public void addHeader(String name, String value) { + headers.add(name, value); + } +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/RequestWrapper.java b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/RequestWrapper.java new file mode 100644 index 000000000..9f82f1839 --- /dev/null +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/java/com/logpm/factorydata/zbom/wrapper/RequestWrapper.java @@ -0,0 +1,75 @@ +package com.logpm.factorydata.zbom.wrapper; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class RequestWrapper extends HttpServletRequestWrapper { + private final String body; + public RequestWrapper(HttpServletRequest request) throws IOException { + super(request); + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try { + InputStream inputStream = request.getInputStream(); + if (inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } else { + stringBuilder.append(""); + } + } catch (IOException ex) { + throw ex; + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ex) { + throw ex; + } + } + } + body = stringBuilder.toString(); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); + ServletInputStream servletInputStream = new ServletInputStream() { + @Override + public boolean isFinished() { + return false; + } + @Override + public boolean isReady() { + return false; + } + @Override + public void setReadListener(ReadListener readListener) {} + @Override + public int read() throws IOException { + return byteArrayInputStream.read(); + } + }; + return servletInputStream; + + } + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(this.getInputStream())); + } + public String getBody() { + return this.body; + } + +} diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-dev.yml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-dev.yml index a7d893991..ee4d16179 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-dev.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-dev.yml @@ -61,13 +61,15 @@ spring: url: ${blade.datasource.factorydata-zbom.master.url} username: ${blade.datasource.factorydata-zbom.master.username} password: ${blade.datasource.factorydata-zbom.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-zbom.slave.url} - username: ${blade.datasource.factorydata-zbom.slave.username} - password: ${blade.datasource.factorydata-zbom.slave.password} - + url: ${blade.datasource.factorydata-zbom.627683.url} + username: ${blade.datasource.factorydata-zbom.627683.username} + password: ${blade.datasource.factorydata-zbom.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-prod.yml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-prod.yml index 8409c79c3..5f0af11dc 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-prod.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-prod.yml @@ -33,13 +33,15 @@ spring: url: ${blade.datasource.factorydata-zbom.master.url} username: ${blade.datasource.factorydata-zbom.master.username} password: ${blade.datasource.factorydata-zbom.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-zbom.slave.url} - username: ${blade.datasource.factorydata-zbom.slave.username} - password: ${blade.datasource.factorydata-zbom.slave.password} - + url: ${blade.datasource.factorydata-zbom.627683.url} + username: ${blade.datasource.factorydata-zbom.627683.username} + password: ${blade.datasource.factorydata-zbom.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-test.yml b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-test.yml index 18f2aad8f..389c6c785 100644 --- a/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-test.yml +++ b/blade-service/logpm-factory-data/logpm-factory-data-zbom/src/main/resources/application-test.yml @@ -59,13 +59,15 @@ spring: url: ${blade.datasource.factorydata-zbom.master.url} username: ${blade.datasource.factorydata-zbom.master.username} password: ${blade.datasource.factorydata-zbom.master.password} - slave: + 627683: druid: #独立校验配置 validation-query: select 1 #oracle校验 #validation-query: select 1 from dual - url: ${blade.datasource.factorydata-zbom.slave.url} - username: ${blade.datasource.factorydata-zbom.slave.username} - password: ${blade.datasource.factorydata-zbom.slave.password} - + url: ${blade.datasource.factorydata-zbom.627683.url} + username: ${blade.datasource.factorydata-zbom.627683.username} + password: ${blade.datasource.factorydata-zbom.627683.password} +blade: + data-scope: + enabled: false diff --git a/blade-service/logpm-factory-data/pom.xml b/blade-service/logpm-factory-data/pom.xml index e491d97a0..ad5529046 100644 --- a/blade-service/logpm-factory-data/pom.xml +++ b/blade-service/logpm-factory-data/pom.xml @@ -12,9 +12,7 @@ pom 3.2.0.RELEASE - logpm-factory-data-zbom - logpm-factory-data-base logpm-factory-data-suofeiya logpm-factory-data-olo diff --git a/blade-service/logpm-trunkline/src/main/java/com/logpm/trunkline/mq/AdvanceOrderListener.java b/blade-service/logpm-trunkline/src/main/java/com/logpm/trunkline/mq/AdvanceOrderListener.java index c8addf46c..d03030a91 100644 --- a/blade-service/logpm-trunkline/src/main/java/com/logpm/trunkline/mq/AdvanceOrderListener.java +++ b/blade-service/logpm-trunkline/src/main/java/com/logpm/trunkline/mq/AdvanceOrderListener.java @@ -7,6 +7,7 @@ import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.logpm.trunkline.entity.TrunklineAdvanceDetailEntity; import com.logpm.trunkline.entity.TrunklineAdvanceEntity; @@ -60,11 +61,13 @@ public class AdvanceOrderListener { JSONObject entries = JSONUtil.parseObj(msg); JSONArray details = entries.getJSONArray("details"); TrunklineAdvanceEntity advanceEntity = JSONUtil.toBean(entries, TrunklineAdvanceEntity.class); + LambdaQueryWrapper eq = Wrappers.lambdaQuery() + .eq(TrunklineAdvanceEntity::getOrderCode, advanceEntity.getOrderCode()); + if (StrUtil.isNotEmpty(advanceEntity.getTrainNumber())) { + eq.eq(TrunklineAdvanceEntity::getTrainNumber, advanceEntity.getTrainNumber()); + } // 暂存单 订单自编号 + 车次号 唯一 - List advanceEntities = advanceService.list(Wrappers.lambdaQuery() - .eq(TrunklineAdvanceEntity::getOrderCode, advanceEntity.getOrderCode()) - .eq(TrunklineAdvanceEntity::getTrainNumber, advanceEntity.getTrainNumber()) - ); + List advanceEntities = advanceService.list(eq); // 暂存单存在 并且未开单 则将新数据添加到原来的暂存单上 // 如果已开单则新增暂存单 @@ -103,7 +106,7 @@ public class AdvanceOrderListener { } if (ObjectUtil.isNotNull(advanceEntity)) { String orderCode = advanceEntity.getOrderCode(); - if (orderCode.contains("遗")) { + if (StrUtil.isNotEmpty(orderCode) && orderCode.contains("遗")) { advanceEntity.setLegacyStatus("1"); } // 暂存单不存在则新增,暂存单存在则将暂存单明细往原暂存单中添加