注释规范

This commit is contained in:
Chopper 2021-06-21 14:14:07 +08:00
parent 8403db9e75
commit c7e4af6175
132 changed files with 994 additions and 994 deletions

View File

@ -37,11 +37,11 @@ public class AdminApplication {
successHandler.setDefaultTargetUrl(this.adminServer.path("/")); successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests().antMatchers("/instances**").permitAll(); http.authorizeRequests().antMatchers("/instances**").permitAll();
http.authorizeRequests( http.authorizeRequests(
(authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**")).permitAll() // 授予公众对所有静态资产和登录页面的访问权限 (authorizeRequests) -> authorizeRequests.antMatchers(this.adminServer.path("/assets/**")).permitAll() //授予公众对所有静态资产和登录页面的访问权限
.antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated() //其他所有请求都必须经过验证 .antMatchers(this.adminServer.path("/login")).permitAll().anyRequest().authenticated() //其他所有请求都必须经过验证
).formLogin( ).formLogin(
(formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler).and() // 配置登录和注销 (formLogin) -> formLogin.loginPage(this.adminServer.path("/login")).successHandler(successHandler).and() //配置登录和注销
).logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))).httpBasic(Customizer.withDefaults()) // 启用HTTP基本支持这是Spring Boot Admin Client注册所必需的 ).logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))).httpBasic(Customizer.withDefaults()) //启用HTTP基本支持这是Spring Boot Admin Client注册所必需的
.csrf().disable() .csrf().disable()
.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600)); .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
} }

View File

@ -51,11 +51,11 @@ public class CartController {
@NotNull(message = "购买数量不能为空") @Min(value = 1, message = "加入购物车数量必须大于0") Integer num, @NotNull(message = "购买数量不能为空") @Min(value = 1, message = "加入购物车数量必须大于0") Integer num,
String cartType) { String cartType) {
try { try {
// 读取选中的列表 //读取选中的列表
cartService.add(skuId, num, cartType); cartService.add(skuId, num, cartType);
return ResultUtil.success(); return ResultUtil.success();
} catch (ServiceException se) { } catch (ServiceException se) {
log.error(se.getMsg(), se); log.info(se.getMsg(), se);
return ResultUtil.error(se.getResultCode().code(), se.getResultCode().message()); return ResultUtil.error(se.getResultCode().code(), se.getResultCode().message());
} catch (Exception e) { } catch (Exception e) {
log.error(ResultCode.CART_ERROR.message(), e); log.error(ResultCode.CART_ERROR.message(), e);
@ -157,7 +157,7 @@ public class CartController {
@GetMapping("/checked") @GetMapping("/checked")
public ResultMessage<TradeDTO> cartChecked(@NotNull(message = "读取选中列表") String way) { public ResultMessage<TradeDTO> cartChecked(@NotNull(message = "读取选中列表") String way) {
try { try {
// 读取选中的列表 //读取选中的列表
return ResultUtil.data(this.cartService.getCheckedTradeDTO(CartTypeEnum.valueOf(way))); return ResultUtil.data(this.cartService.getCheckedTradeDTO(CartTypeEnum.valueOf(way)));
} catch (ServiceException se) { } catch (ServiceException se) {
log.error(se.getMsg(), se); log.error(se.getMsg(), se);
@ -239,7 +239,7 @@ public class CartController {
@PostMapping(value = "/create/trade", consumes = "application/json", produces = "application/json") @PostMapping(value = "/create/trade", consumes = "application/json", produces = "application/json")
public ResultMessage<Object> crateTrade(@RequestBody TradeParams tradeParams) { public ResultMessage<Object> crateTrade(@RequestBody TradeParams tradeParams) {
try { try {
// 读取选中的列表 //读取选中的列表
return ResultUtil.data(this.cartService.createTrade(tradeParams)); return ResultUtil.data(this.cartService.createTrade(tradeParams));
} catch (ServiceException se) { } catch (ServiceException se) {
log.error(se.getMsg(), se); log.error(se.getMsg(), se);

View File

@ -67,7 +67,7 @@ public class BuyerAuthenticationFilter extends BasicAuthenticationFilter {
//从header中获取jwt //从header中获取jwt
String jwt = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue()); String jwt = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue());
try { try {
// 如果没有token 则return //如果没有token 则return
if (StrUtil.isBlank(jwt)) { if (StrUtil.isBlank(jwt)) {
chain.doFilter(request, response); chain.doFilter(request, response);
return; return;
@ -99,7 +99,7 @@ public class BuyerAuthenticationFilter extends BasicAuthenticationFilter {
String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString();
AuthUser authUser = new Gson().fromJson(json, AuthUser.class); AuthUser authUser = new Gson().fromJson(json, AuthUser.class);
// 校验redis中是否有权限 //校验redis中是否有权限
if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MEMBER) + jwt)) { if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MEMBER) + jwt)) {
//构造返回信息 //构造返回信息
List<GrantedAuthority> auths = new ArrayList<>(); List<GrantedAuthority> auths = new ArrayList<>();

View File

@ -48,35 +48,35 @@ public class BuyerSecurityConfig extends WebSecurityConfigurerAdapter {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
.authorizeRequests(); .authorizeRequests();
// 配置的url 不需要授权 //配置的url 不需要授权
for (String url : ignoredUrlsProperties.getUrls()) { for (String url : ignoredUrlsProperties.getUrls()) {
registry.antMatchers(url).permitAll(); registry.antMatchers(url).permitAll();
} }
registry registry
.and() .and()
// 禁止网页iframe //禁止网页iframe
.headers().frameOptions().disable() .headers().frameOptions().disable()
.and() .and()
.logout() .logout()
.permitAll() .permitAll()
.and() .and()
.authorizeRequests() .authorizeRequests()
// 任何请求 //任何请求
.anyRequest() .anyRequest()
// 需要身份认证 //需要身份认证
.authenticated() .authenticated()
.and() .and()
// 允许跨域 //允许跨域
.cors().configurationSource((CorsConfigurationSource) SpringContextUtil.getBean("corsConfigurationSource")).and() .cors().configurationSource((CorsConfigurationSource) SpringContextUtil.getBean("corsConfigurationSource")).and()
// 关闭跨站请求防护 //关闭跨站请求防护
.csrf().disable() .csrf().disable()
// 前后端分离采用JWT 不需要session //前后端分离采用JWT 不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and() .and()
// 自定义权限拒绝处理类 //自定义权限拒绝处理类
.exceptionHandling().accessDeniedHandler(accessDeniedHandler) .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and() .and()
// 添加JWT认证过滤器 //添加JWT认证过滤器
.addFilter(new BuyerAuthenticationFilter(authenticationManager(), cache)); .addFilter(new BuyerAuthenticationFilter(authenticationManager(), cache));
} }

View File

@ -50,9 +50,9 @@ class CartTest {
@Test @Test
void createTrade() { void createTrade() {
// TradeDTO allTradeDTO = cartService.getAllTradeDTO(); // TradeDTO allTradeDTO = cartService.getAllTradeDTO();
// Assert.assertNotNull(allTradeDTO); // Assert.assertNotNull(allTradeDTO);
// System.out.println(JsonUtil.objectToJson(allTradeDTO)); // System.out.println(JsonUtil.objectToJson(allTradeDTO));
cartService.createTrade(new TradeParams()); cartService.createTrade(new TradeParams());
} }

View File

@ -42,7 +42,7 @@ class FileTest {
} }
URL url = new URL(brand.getLogo()); URL url = new URL(brand.getLogo());
InputStream inputStream = url.openStream(); InputStream inputStream = url.openStream();
// 上传至第三方云服务或服务器 //上传至第三方云服务或服务器
brand.setLogo(fileManagerPlugin.inputStreamUpload(inputStream, brand.getId() + ".png")); brand.setLogo(fileManagerPlugin.inputStreamUpload(inputStream, brand.getId() + ".png"));
} catch (IOException e) { } catch (IOException e) {
log.error("上传你文件出错",e); log.error("上传你文件出错",e);

View File

@ -73,7 +73,7 @@ public class UploadController {
} }
if (StringUtils.isNotBlank(base64)) { if (StringUtils.isNotBlank(base64)) {
// base64上传 //base64上传
file = Base64DecodeMultipartFile.base64Convert(base64); file = Base64DecodeMultipartFile.base64Convert(base64);
} }
String result = ""; String result = "";
@ -81,9 +81,9 @@ public class UploadController {
File newFile = new File(); File newFile = new File();
try { try {
InputStream inputStream = file.getInputStream(); InputStream inputStream = file.getInputStream();
// 上传至第三方云服务或服务器 //上传至第三方云服务或服务器
result = fileManagerPlugin.inputStreamUpload(inputStream, fileKey); result = fileManagerPlugin.inputStreamUpload(inputStream, fileKey);
// 保存数据信息至数据库 //保存数据信息至数据库
newFile.setName(file.getOriginalFilename()); newFile.setName(file.getOriginalFilename());
newFile.setFileSize(file.getSize()); newFile.setFileSize(file.getSize());
newFile.setFileType(file.getContentType()); newFile.setFileType(file.getContentType());

View File

@ -48,18 +48,18 @@ public class CommonSecurityConfig extends WebSecurityConfigurerAdapter {
.authorizeRequests(); .authorizeRequests();
registry registry
.and() .and()
// 禁止网页iframe //禁止网页iframe
.headers().frameOptions().disable() .headers().frameOptions().disable()
.and() .and()
.authorizeRequests() .authorizeRequests()
// 任何请求 //任何请求
.anyRequest() .anyRequest()
// 需要身份认证 //需要身份认证
.permitAll() .permitAll()
.and() .and()
// 允许跨域 //允许跨域
.cors().configurationSource(corsConfigurationSource).and() .cors().configurationSource(corsConfigurationSource).and()
// 关闭跨站请求防护 //关闭跨站请求防护
.csrf().disable(); .csrf().disable();
} }

View File

@ -161,7 +161,7 @@ public class StockUpdateExecute implements OrderStatusChangeEvent {
//促销库存key 集合 //促销库存key 集合
List<String> promotionKey = new ArrayList<>(); List<String> promotionKey = new ArrayList<>();
// 循环订单 //循环订单
for (OrderItem orderItem : order.getOrderItems()) { for (OrderItem orderItem : order.getOrderItems()) {
skuKeys.add(GoodsSkuService.getStockCacheKey(orderItem.getSkuId())); skuKeys.add(GoodsSkuService.getStockCacheKey(orderItem.getSkuId()));
GoodsSku goodsSku = new GoodsSku(); GoodsSku goodsSku = new GoodsSku();
@ -221,7 +221,7 @@ public class StockUpdateExecute implements OrderStatusChangeEvent {
List<GoodsSku> goodsSkus = new ArrayList<>(); List<GoodsSku> goodsSkus = new ArrayList<>();
//sku库存key 集合 //sku库存key 集合
List<String> skuKeys = new ArrayList<>(); List<String> skuKeys = new ArrayList<>();
// 循环订单 //循环订单
for (OrderItem orderItem : order.getOrderItems()) { for (OrderItem orderItem : order.getOrderItems()) {
skuKeys.add(GoodsSkuService.getStockCacheKey(orderItem.getSkuId())); skuKeys.add(GoodsSkuService.getStockCacheKey(orderItem.getSkuId()));
GoodsSku goodsSku = new GoodsSku(); GoodsSku goodsSku = new GoodsSku();

View File

@ -112,7 +112,7 @@ public class GoodsMessageListener implements RocketMQListener<MessageExt> {
for (GoodsCompleteMessage goodsCompleteMessage : goodsCompleteMessageList) { for (GoodsCompleteMessage goodsCompleteMessage : goodsCompleteMessageList) {
Goods goods = goodsService.getById(goodsCompleteMessage.getGoodsId()); Goods goods = goodsService.getById(goodsCompleteMessage.getGoodsId());
if (goods != null) { if (goods != null) {
// 更新商品购买数量 //更新商品购买数量
if (goods.getBuyCount() == null) { if (goods.getBuyCount() == null) {
goods.setBuyCount(0); goods.setBuyCount(0);
} }
@ -126,7 +126,7 @@ public class GoodsMessageListener implements RocketMQListener<MessageExt> {
} }
GoodsSku goodsSku = goodsSkuService.getById(goodsCompleteMessage.getSkuId()); GoodsSku goodsSku = goodsSkuService.getById(goodsCompleteMessage.getSkuId());
if (goodsSku != null) { if (goodsSku != null) {
// 更新商品购买数量 //更新商品购买数量
if (goodsSku.getBuyCount() == null) { if (goodsSku.getBuyCount() == null) {
goodsSku.setBuyCount(0); goodsSku.setBuyCount(0);
} }

View File

@ -56,9 +56,9 @@ public class OrderMessageListener implements RocketMQListener<MessageExt> {
result = false; result = false;
} }
} }
// 如所有步骤顺利完成 //如所有步骤顺利完成
if (Boolean.TRUE.equals(result)) { if (Boolean.TRUE.equals(result)) {
// 清除记录信息的trade cache key //清除记录信息的trade cache key
cache.remove(key); cache.remove(key);
} }
break; break;

View File

@ -43,11 +43,11 @@ public class CancelOrderTaskExecute implements EveryMinuteExecute {
Setting setting = settingService.get(SettingEnum.ORDER_SETTING.name()); Setting setting = settingService.get(SettingEnum.ORDER_SETTING.name());
OrderSetting orderSetting = JSONUtil.toBean(setting.getSettingValue(), OrderSetting.class); OrderSetting orderSetting = JSONUtil.toBean(setting.getSettingValue(), OrderSetting.class);
if (orderSetting != null && orderSetting.getAutoCancel() != null) { if (orderSetting != null && orderSetting.getAutoCancel() != null) {
// 订单自动取消时间 = 当前时间 - 自动取消时间分钟数 //订单自动取消时间 = 当前时间 - 自动取消时间分钟数
DateTime cancelTime = DateUtil.offsetMinute(DateUtil.date(), -orderSetting.getAutoCancel()); DateTime cancelTime = DateUtil.offsetMinute(DateUtil.date(), -orderSetting.getAutoCancel());
LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.UNPAID.name()); queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.UNPAID.name());
// 订单创建时间 <= 订单自动取消时间 //订单创建时间 <= 订单自动取消时间
queryWrapper.le(Order::getCreateTime, cancelTime); queryWrapper.le(Order::getCreateTime, cancelTime);
List<Order> list = orderService.list(queryWrapper); List<Order> list = orderService.list(queryWrapper);
List<String> cancelSnList = list.stream().map(Order::getSn).collect(Collectors.toList()); List<String> cancelSnList = list.stream().map(Order::getSn).collect(Collectors.toList());

View File

@ -73,11 +73,11 @@ public class OrderEveryDayTaskExecute implements EveryDayExecute {
* @param orderSetting 订单设置 * @param orderSetting 订单设置
*/ */
private void completedOrder(OrderSetting orderSetting) { private void completedOrder(OrderSetting orderSetting) {
// 订单自动收货时间 = 当前时间 - 自动收货时间天数 //订单自动收货时间 = 当前时间 - 自动收货时间天数
DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoEvaluation()); DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoEvaluation());
LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.DELIVERED.name()); queryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.DELIVERED.name());
// 订单发货时间 >= 订单自动收货时间 //订单发货时间 >= 订单自动收货时间
queryWrapper.ge(Order::getLogisticsTime, receiveTime); queryWrapper.ge(Order::getLogisticsTime, receiveTime);
List<Order> list = orderService.list(queryWrapper); List<Order> list = orderService.list(queryWrapper);
List<String> receiveSnList = list.stream().map(Order::getSn).collect(Collectors.toList()); List<String> receiveSnList = list.stream().map(Order::getSn).collect(Collectors.toList());
@ -98,9 +98,9 @@ public class OrderEveryDayTaskExecute implements EveryDayExecute {
* @param orderSetting 订单设置 * @param orderSetting 订单设置
*/ */
private void memberEvaluation(OrderSetting orderSetting) { private void memberEvaluation(OrderSetting orderSetting) {
// 订单自动收货时间 = 当前时间 - 自动收货时间天数 //订单自动收货时间 = 当前时间 - 自动收货时间天数
DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoReceive()); DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoReceive());
// 订单完成时间 <= 订单自动好评时间 //订单完成时间 <= 订单自动好评时间
List<OrderItem> orderItems = orderItemService.waitEvaluate(receiveTime); List<OrderItem> orderItems = orderItemService.waitEvaluate(receiveTime);
for (OrderItem orderItem : orderItems) { for (OrderItem orderItem : orderItems) {

View File

@ -61,7 +61,7 @@ public class PromotionEverydayExecute implements EveryDayExecute {
@Autowired @Autowired
private PromotionGoodsService promotionGoodsService; private PromotionGoodsService promotionGoodsService;
// 系统设置 //系统设置
@Autowired @Autowired
private SettingService settingService; private SettingService settingService;
@ -108,7 +108,7 @@ public class PromotionEverydayExecute implements EveryDayExecute {
List<CouponVO> couponVOS = mongoTemplate.find(query, CouponVO.class); List<CouponVO> couponVOS = mongoTemplate.find(query, CouponVO.class);
if (!couponVOS.isEmpty()) { if (!couponVOS.isEmpty()) {
List<String> ids = new ArrayList<>(); List<String> ids = new ArrayList<>();
// // 关闭的优惠券活动 // //关闭的优惠券活动
for (CouponVO vo : couponVOS) { for (CouponVO vo : couponVOS) {
vo.setPromotionStatus(PromotionStatusEnum.END.name()); vo.setPromotionStatus(PromotionStatusEnum.END.name());
if (vo.getPromotionGoodsList() != null && !vo.getPromotionGoodsList().isEmpty()) { if (vo.getPromotionGoodsList() != null && !vo.getPromotionGoodsList().isEmpty()) {

View File

@ -31,23 +31,23 @@ public abstract class AbstractDelayQueueListen {
private void startDelayQueueMachine() { private void startDelayQueueMachine() {
log.info("延时队列机器{}开始运作", setDelayQueueName()); log.info("延时队列机器{}开始运作", setDelayQueueName());
// 监听redis队列 //监听redis队列
while (true) { while (true) {
try { try {
// 获取当前时间的时间戳 //获取当前时间的时间戳
long now = System.currentTimeMillis() / 1000; long now = System.currentTimeMillis() / 1000;
// 获取当前时间前需要执行的任务列表 //获取当前时间前需要执行的任务列表
Set<DefaultTypedTuple> tuples = cache.zRangeByScore(setDelayQueueName(), 0, now); Set<DefaultTypedTuple> tuples = cache.zRangeByScore(setDelayQueueName(), 0, now);
// 如果任务不为空 //如果任务不为空
if (!CollectionUtils.isEmpty(tuples)) { if (!CollectionUtils.isEmpty(tuples)) {
log.info("执行任务:{}", JSONUtil.toJsonStr(tuples)); log.info("执行任务:{}", JSONUtil.toJsonStr(tuples));
for (DefaultTypedTuple tuple : tuples) { for (DefaultTypedTuple tuple : tuples) {
String jobId = (String) tuple.getValue(); String jobId = (String) tuple.getValue();
// 移除缓存如果移除成功则表示当前线程处理了延时任务则执行延时任务 //移除缓存如果移除成功则表示当前线程处理了延时任务则执行延时任务
Long num = cache.zRemove(setDelayQueueName(), jobId); Long num = cache.zRemove(setDelayQueueName(), jobId);
// 如果移除成功, 则执行 //如果移除成功, 则执行
if (num > 0) { if (num > 0) {
ThreadPoolUtil.execute(() -> invoke(jobId)); ThreadPoolUtil.execute(() -> invoke(jobId));
} }
@ -57,7 +57,7 @@ public abstract class AbstractDelayQueueListen {
} catch (Exception e) { } catch (Exception e) {
log.error("处理延时任务发生异常,异常原因为{}", e.getMessage(), e); log.error("处理延时任务发生异常,异常原因为{}", e.getMessage(), e);
} finally { } finally {
// 间隔一秒钟搞一次 //间隔一秒钟搞一次
try { try {
TimeUnit.SECONDS.sleep(5L); TimeUnit.SECONDS.sleep(5L);
} catch (InterruptedException e) { } catch (InterruptedException e) {

View File

@ -29,7 +29,7 @@ public class BroadcastTimeTriggerExecutor implements TimeTriggerExecutor {
BroadcastMessage broadcastMessage = JSONUtil.toBean(JSONUtil.parseObj(object), BroadcastMessage.class); BroadcastMessage broadcastMessage = JSONUtil.toBean(JSONUtil.parseObj(object), BroadcastMessage.class);
if (broadcastMessage != null && broadcastMessage.getStudioId() != null) { if (broadcastMessage != null && broadcastMessage.getStudioId() != null) {
log.info("直播间消费:{}", broadcastMessage); log.info("直播间消费:{}", broadcastMessage);
// 修改直播间状态 //修改直播间状态
studioService.updateStudioStatus(broadcastMessage); studioService.updateStudioStatus(broadcastMessage);
} }
} }

View File

@ -42,19 +42,19 @@ public class PromotionTimeTriggerExecutor implements TimeTriggerExecutor {
@Override @Override
public void execute(Object object) { public void execute(Object object) {
PromotionMessage promotionMessage = JSONUtil.toBean(JSONUtil.parseObj(object), PromotionMessage.class); PromotionMessage promotionMessage = JSONUtil.toBean(JSONUtil.parseObj(object), PromotionMessage.class);
// 促销延时信息 //促销延时信息
if (promotionMessage != null && promotionMessage.getPromotionId() != null) { if (promotionMessage != null && promotionMessage.getPromotionId() != null) {
log.info("促销活动信息消费:{}", promotionMessage); log.info("促销活动信息消费:{}", promotionMessage);
// 如果为促销活动开始则需要发布促销活动结束的定时任务 //如果为促销活动开始则需要发布促销活动结束的定时任务
if (PromotionStatusEnum.START.name().equals(promotionMessage.getPromotionStatus())) { if (PromotionStatusEnum.START.name().equals(promotionMessage.getPromotionStatus())) {
if (!promotionService.updatePromotionStatus(promotionMessage)) { if (!promotionService.updatePromotionStatus(promotionMessage)) {
log.error("开始促销活动失败: {}", promotionMessage); log.error("开始促销活动失败: {}", promotionMessage);
return; return;
} }
// 促销活动开始后设置促销活动结束的定时任务 //促销活动开始后设置促销活动结束的定时任务
promotionMessage.setPromotionStatus(PromotionStatusEnum.END.name()); promotionMessage.setPromotionStatus(PromotionStatusEnum.END.name());
String uniqueKey = "{TIME_TRIGGER_" + promotionMessage.getPromotionType() + "}_" + promotionMessage.getPromotionId(); String uniqueKey = "{TIME_TRIGGER_" + promotionMessage.getPromotionType() + "}_" + promotionMessage.getPromotionId();
// 结束时间延时一分钟 //结束时间延时一分钟
long closeTime = promotionMessage.getEndTime().getTime() + 60000; long closeTime = promotionMessage.getEndTime().getTime() + 60000;
TimeTriggerMsg timeTriggerMsg = new TimeTriggerMsg(TimeExecuteConstant.PROMOTION_EXECUTOR, closeTime, promotionMessage, uniqueKey, rocketmqCustomProperties.getPromotionTopic()); TimeTriggerMsg timeTriggerMsg = new TimeTriggerMsg(TimeExecuteConstant.PROMOTION_EXECUTOR, closeTime, promotionMessage, uniqueKey, rocketmqCustomProperties.getPromotionTopic());
//添加延时任务 //添加延时任务
@ -69,7 +69,7 @@ public class PromotionTimeTriggerExecutor implements TimeTriggerExecutor {
PintuanOrderMessage pintuanOrderMessage = JSONUtil.toBean(JSONUtil.parseObj(object), PintuanOrderMessage.class); PintuanOrderMessage pintuanOrderMessage = JSONUtil.toBean(JSONUtil.parseObj(object), PintuanOrderMessage.class);
if (pintuanOrderMessage != null && pintuanOrderMessage.getPintuanId() != null) { if (pintuanOrderMessage != null && pintuanOrderMessage.getPintuanId() != null) {
log.info("拼团订单信息消费:{}", pintuanOrderMessage); log.info("拼团订单信息消费:{}", pintuanOrderMessage);
// 拼团订单自动处理 //拼团订单自动处理
orderService.agglomeratePintuanOrder(pintuanOrderMessage.getPintuanId(), pintuanOrderMessage.getOrderSn()); orderService.agglomeratePintuanOrder(pintuanOrderMessage.getPintuanId(), pintuanOrderMessage.getOrderSn());
} }
} }

View File

@ -20,12 +20,12 @@ public class MybatisPlusConfig {
return new PaginationInterceptor(); return new PaginationInterceptor();
//阻断解析器测试环境使用 //阻断解析器测试环境使用
// PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// //
// List<ISqlParser> sqlParserList = new ArrayList<>(); // List<ISqlParser> sqlParserList = new ArrayList<>();
// // 攻击 SQL 阻断解析器加入解析链 // //攻击 SQL 阻断解析器加入解析链
// sqlParserList.add(new BlockAttackSqlParser()); // sqlParserList.add(new BlockAttackSqlParser());
// paginationInterceptor.setSqlParserList(sqlParserList); // paginationInterceptor.setSqlParserList(sqlParserList);
// return paginationInterceptor; // return paginationInterceptor;
} }
} }

View File

@ -67,7 +67,7 @@ public class LimitInterceptor {
try { try {
Number count = redisTemplate.execute(limitScript, keys, limitCount, limitPeriod); Number count = redisTemplate.execute(limitScript, keys, limitCount, limitPeriod);
log.info("Access try count is {} for name={} and key = {}", count, name, key); log.info("Access try count is {} for name={} and key = {}", count, name, key);
// 如果缓存里没有值或者他的值小于限制频率 //如果缓存里没有值或者他的值小于限制频率
if (count.intValue() <= limitCount) { if (count.intValue() <= limitCount) {
return pjp.proceed(); return pjp.proceed();
} else { } else {

View File

@ -102,7 +102,7 @@ public class SystemLogAspect {
//请求参数 //请求参数
systemLogVO.setMapToParams(logParams); systemLogVO.setMapToParams(logParams);
//响应参数 此处数据太大了所以先注释掉 //响应参数 此处数据太大了所以先注释掉
// systemLogVO.setResponseBody(JSONUtil.toJsonStr(rvt)); // systemLogVO.setResponseBody(JSONUtil.toJsonStr(rvt));
//请求IP //请求IP
systemLogVO.setIp(IpUtils.getIpAddress(request)); systemLogVO.setIp(IpUtils.getIpAddress(request));
//IP地址 //IP地址

View File

@ -170,7 +170,7 @@ public class RedisCache implements Cache {
@Override @Override
public Long cumulative(Object key, Object value) { public Long cumulative(Object key, Object value) {
HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog(); HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog();
// add 方法对应 PFADD 命令 //add 方法对应 PFADD 命令
return operations.add(key, value); return operations.add(key, value);
} }
@ -179,7 +179,7 @@ public class RedisCache implements Cache {
public Long counter(Object key) { public Long counter(Object key) {
HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog(); HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog();
// add 方法对应 PFADD 命令 //add 方法对应 PFADD 命令
return operations.size(key); return operations.size(key);
} }
@ -198,7 +198,7 @@ public class RedisCache implements Cache {
@Override @Override
public Long mergeCounter(Object... key) { public Long mergeCounter(Object... key) {
HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog(); HyperLogLogOperations<Object, Object> operations = redisTemplate.opsForHyperLogLog();
// 计数器合并累加 //计数器合并累加
return operations.union(key[0], key); return operations.union(key[0], key);
} }
@ -223,7 +223,7 @@ public class RedisCache implements Cache {
*/ */
@Override @Override
public void incrementScore(String sortedSetName, String keyword) { public void incrementScore(String sortedSetName, String keyword) {
// x 的含义请见本方法的注释 //x 的含义请见本方法的注释
double x = 1.0; double x = 1.0;
this.redisTemplate.opsForZSet().incrementScore(sortedSetName, keyword, x); this.redisTemplate.opsForZSet().incrementScore(sortedSetName, keyword, x);
} }

View File

@ -44,7 +44,7 @@ public abstract class BaseElasticsearchService {
static { static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// 默认缓冲限制为100MB此处修改为30MB //默认缓冲限制为100MB此处修改为30MB
builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024)); builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
COMMON_OPTIONS = builder.build(); COMMON_OPTIONS = builder.build();
} }
@ -88,7 +88,7 @@ public abstract class BaseElasticsearchService {
protected void createIndexRequest(String index) { protected void createIndexRequest(String index) {
try { try {
CreateIndexRequest request = new CreateIndexRequest(index); CreateIndexRequest request = new CreateIndexRequest(index);
// Settings for this index //Settings for this index
request.settings(Settings.builder().put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards()).put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas())); request.settings(Settings.builder().put("index.number_of_shards", elasticsearchProperties.getIndex().getNumberOfShards()).put("index.number_of_replicas", elasticsearchProperties.getIndex().getNumberOfReplicas()));
//创建索引 //创建索引
@ -308,13 +308,13 @@ public abstract class BaseElasticsearchService {
PutMappingRequest request = new PutMappingRequest(index) PutMappingRequest request = new PutMappingRequest(index)
.source(source, XContentType.JSON); .source(source, XContentType.JSON);
// AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, // AcknowledgedResponse putMappingResponse = client.indices().putMapping(request,
// RequestOptions.DEFAULT); // RequestOptions.DEFAULT);
// //
// boolean acknowledged = putMappingResponse.isAcknowledged(); // boolean acknowledged = putMappingResponse.isAcknowledged();
// if (acknowledged) { // if (acknowledged) {
// log.error("Succeed to put mapping"); // log.error("Succeed to put mapping");
// } // }
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
AtomicReference response = new AtomicReference<AcknowledgedResponse>(); AtomicReference response = new AtomicReference<AcknowledgedResponse>();
client.indices().putMappingAsync( client.indices().putMappingAsync(

View File

@ -67,24 +67,24 @@ public class GlobalControllerExceptionHandler {
return ResultUtil.error(ResultCode.ERROR); return ResultUtil.error(ResultCode.ERROR);
} }
// /** // /**
// * 通用的接口映射异常处理方 // * 通用的接口映射异常处理方
// */ // */
// @Override // @Override
// protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { // protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
// if (ex instanceof MethodArgumentNotValidException) { // if (ex instanceof MethodArgumentNotValidException) {
// MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex; // MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
// return new ResponseEntity<>(new ResultUtil<>().setErrorMsg(exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status); // return new ResponseEntity<>(new ResultUtil<>().setErrorMsg(exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
// } // }
// if (ex instanceof MethodArgumentTypeMismatchException) { // if (ex instanceof MethodArgumentTypeMismatchException) {
// MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex; // MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
// logger.error("参数转换失败,方法:" + exception.getParameter().getMethod().getName() + ",参数:" + exception.getName() // logger.error("参数转换失败,方法:" + exception.getParameter().getMethod().getName() + ",参数:" + exception.getName()
// + ",信息:" + exception.getLocalizedMessage()); // + ",信息:" + exception.getLocalizedMessage());
// return new ResponseEntity<>(new ResultUtil<>().setErrorMsg("参数转换失败"), status); // return new ResponseEntity<>(new ResultUtil<>().setErrorMsg("参数转换失败"), status);
// } // }
// ex.printStackTrace(); // ex.printStackTrace();
// return new ResponseEntity<>(new ResultUtil<>().setErrorMsg("未知异常,请联系管理员"), status); // return new ResponseEntity<>(new ResultUtil<>().setErrorMsg("未知异常,请联系管理员"), status);
// } // }
/** /**
* bean校验未通过异常 * bean校验未通过异常

View File

@ -80,7 +80,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
* @return * @return
*/ */
private String cleanXSS2(String value) { private String cleanXSS2(String value) {
// 移除特殊标签 //移除特殊标签
value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;"); value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
value = value.replaceAll("'", "&#39;"); value = value.replaceAll("'", "&#39;");
@ -93,40 +93,40 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String cleanXSS(String value) { private String cleanXSS(String value) {
if (value != null) { if (value != null) {
//推荐使用ESAPI库来避免脚本攻击,value = ESAPI.encoder().canonicalize(value); //推荐使用ESAPI库来避免脚本攻击,value = ESAPI.encoder().canonicalize(value);
// // 避免空字符串 // //避免空字符串
// value = value.replaceAll(" ", ""); // value = value.replaceAll(" ", "");
// 避免script 标签 //避免script 标签
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE); Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免src形式的表达式 //避免src形式的表达式
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 删除单个的 </script> 标签 //删除单个的 </script> 标签
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE); scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 删除单个的<script ...> 标签 //删除单个的<script ...> 标签
scriptPattern = Pattern.compile("<script(.*?)>", scriptPattern = Pattern.compile("<script(.*?)>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免 eval(...) 形式表达式 //避免 eval(...) 形式表达式
scriptPattern = Pattern.compile("eval\\((.*?)\\)", scriptPattern = Pattern.compile("eval\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免 e­xpression(...) 表达式 //避免 e­xpression(...) 表达式
scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)", scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免 javascript: 表达式 //避免 javascript: 表达式
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免 vbscript:表达式 //避免 vbscript:表达式
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE); scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");
// 避免 onload= 表达式 //避免 onload= 表达式
scriptPattern = Pattern.compile("onload(.*?)=", scriptPattern = Pattern.compile("onload(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll(""); value = scriptPattern.matcher(value).replaceAll("");

View File

@ -73,7 +73,7 @@ public class SmsUtilAliImplService implements SmsUtil, AliSmsUtil {
//准备发送短信参数 //准备发送短信参数
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
// 验证码内容 //验证码内容
params.put("code", code); params.put("code", code);
//模版 默认为登录验证 //模版 默认为登录验证
@ -182,7 +182,7 @@ public class SmsUtilAliImplService implements SmsUtil, AliSmsUtil {
signNameList.add(sign.subList((i * 100), endPoint)); signNameList.add(sign.subList((i * 100), endPoint));
} }
// //发送短信 // //发送短信
for (int i = 0; i < mobileList.size(); i++) { for (int i = 0; i < mobileList.size(); i++) {
SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest() SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest()
.setPhoneNumberJson(JSONUtil.toJsonStr(mobileList.get(i))) .setPhoneNumberJson(JSONUtil.toJsonStr(mobileList.get(i)))
@ -356,11 +356,11 @@ public class SmsUtilAliImplService implements SmsUtil, AliSmsUtil {
SmsSetting smsSetting = new Gson().fromJson(setting.getSettingValue(), SmsSetting.class); SmsSetting smsSetting = new Gson().fromJson(setting.getSettingValue(), SmsSetting.class);
Config config = new Config(); Config config = new Config();
// 您的AccessKey ID //您的AccessKey ID
config.accessKeyId = smsSetting.getAccessKeyId(); config.accessKeyId = smsSetting.getAccessKeyId();
// 您的AccessKey Secret //您的AccessKey Secret
config.accessKeySecret = smsSetting.getAccessSecret(); config.accessKeySecret = smsSetting.getAccessSecret();
// 访问的域名 //访问的域名
config.endpoint = "dysmsapi.aliyuncs.com"; config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config); return new com.aliyun.dysmsapi20170525.Client(config);
} catch (Exception e) { } catch (Exception e) {

View File

@ -121,15 +121,15 @@ public class TokenUtil {
* @return * @return
*/ */
private String createToken(String username, Object claim, Long expirationTime) { private String createToken(String username, Object claim, Long expirationTime) {
// JWT 生成 //JWT 生成
return Jwts.builder() return Jwts.builder()
// jwt 私有声明 //jwt 私有声明
.claim(SecurityEnum.USER_CONTEXT.getValue(), new Gson().toJson(claim)) .claim(SecurityEnum.USER_CONTEXT.getValue(), new Gson().toJson(claim))
// JWT的主体 //JWT的主体
.setSubject(username) .setSubject(username)
// 失效时间 当前时间+过期分钟 //失效时间 当前时间+过期分钟
.setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000)) .setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000))
// 签名算法和密钥 //签名算法和密钥
.signWith(SecretKeyUtil.generalKey()) .signWith(SecretKeyUtil.generalKey())
.compact(); .compact();
} }

View File

@ -43,7 +43,7 @@ public class ManagerTokenGenerate extends AbstractTokenGenerate {
@Override @Override
public Token createToken(String username, Boolean longTerm) { public Token createToken(String username, Boolean longTerm) {
// 生成token //生成token
AdminUser adminUser = adminUserService.findByUsername(username); AdminUser adminUser = adminUserService.findByUsername(username);
AuthUser user = new AuthUser(adminUser.getUsername(), adminUser.getId(), UserEnums.MANAGER, adminUser.getNickName(), adminUser.getIsSuper()); AuthUser user = new AuthUser(adminUser.getUsername(), adminUser.getId(), UserEnums.MANAGER, adminUser.getNickName(), adminUser.getIsSuper());

View File

@ -54,7 +54,7 @@ public class MemberTokenGenerate extends AbstractTokenGenerate {
memberService.updateById(member); memberService.updateById(member);
AuthUser authUser = new AuthUser(member.getUsername(), member.getId(),member.getNickName(), UserEnums.MEMBER); AuthUser authUser = new AuthUser(member.getUsername(), member.getId(),member.getNickName(), UserEnums.MEMBER);
// 登陆成功生成token //登陆成功生成token
return tokenUtil.createToken(username, authUser, longTerm, UserEnums.MEMBER); return tokenUtil.createToken(username, authUser, longTerm, UserEnums.MEMBER);
} }

View File

@ -33,7 +33,7 @@ public class StoreTokenGenerate extends AbstractTokenGenerate {
@Override @Override
public Token createToken(String username, Boolean longTerm) { public Token createToken(String username, Boolean longTerm) {
// 生成token //生成token
Member member = memberService.findByUsername(username); Member member = memberService.findByUsername(username);
if (!member.getHaveStore()) { if (!member.getHaveStore()) {
throw new ServiceException("该会员未开通店铺"); throw new ServiceException("该会员未开通店铺");

View File

@ -101,7 +101,7 @@ public class Base64DecodeMultipartFile implements MultipartFile {
public static String inputStreamToStream(InputStream in) { public static String inputStreamToStream(InputStream in) {
byte[] data = null; byte[] data = null;
// 读取图片字节数组 //读取图片字节数组
try { try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100]; byte[] buff = new byte[100];

View File

@ -14,9 +14,9 @@ import java.util.regex.Pattern;
public class CheckMobileUtil { public class CheckMobileUtil {
// \b 是单词边界(连着的两个(字母字符 非字母字符) 之间的逻辑上的间隔), //\b 是单词边界(连着的两个(字母字符 非字母字符) 之间的逻辑上的间隔),
// 字符串在编译时会被转码一次,所以是 "\\b" //字符串在编译时会被转码一次,所以是 "\\b"
// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔) //\B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
+ "|windows (phone|ce)|blackberry" + "|windows (phone|ce)|blackberry"
+ "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
@ -41,7 +41,7 @@ public class CheckMobileUtil {
if (null == userAgent) { if (null == userAgent) {
userAgent = ""; userAgent = "";
} }
// 匹配 //匹配
Matcher matcherPhone = phonePat.matcher(userAgent); Matcher matcherPhone = phonePat.matcher(userAgent);
Matcher matcherTable = tablePat.matcher(userAgent); Matcher matcherTable = tablePat.matcher(userAgent);
if (matcherPhone.find() || matcherTable.find()) { if (matcherPhone.find() || matcherTable.find()) {

View File

@ -148,18 +148,18 @@ public class DateUtil {
* @return * @return
*/ */
public static Long[] getLastMonth() { public static Long[] getLastMonth() {
// 取得系统当前时间 //取得系统当前时间
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR); int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; int month = cal.get(Calendar.MONTH) + 1;
// 取得系统当前时间所在月第一天时间对象 //取得系统当前时间所在月第一天时间对象
cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.DAY_OF_MONTH, 1);
// 日期减一,取得上月最后一天时间对象 //日期减一,取得上月最后一天时间对象
cal.add(Calendar.DAY_OF_MONTH, -1); cal.add(Calendar.DAY_OF_MONTH, -1);
// 输出上月最后一天日期 //输出上月最后一天日期
int day = cal.get(Calendar.DAY_OF_MONTH); int day = cal.get(Calendar.DAY_OF_MONTH);
String months = ""; String months = "";
@ -355,7 +355,7 @@ public class DateUtil {
*/ */
public static Integer getDelayTime(Long startTime) { public static Integer getDelayTime(Long startTime) {
int time = Math.toIntExact((startTime - System.currentTimeMillis()) / 1000); int time = Math.toIntExact((startTime - System.currentTimeMillis()) / 1000);
// 如果时间为负数则改为一秒后执行 //如果时间为负数则改为一秒后执行
if (time <= 0) { if (time <= 0) {
time = 1; time = 1;
} }

View File

@ -43,14 +43,14 @@ public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {
out.nullValue(); out.nullValue();
return; return;
} }
// Retrieve the original (not proxy) class //Retrieve the original (not proxy) class
Class<?> baseType = Hibernate.getClass(value); Class<?> baseType = Hibernate.getClass(value);
// Get the TypeAdapter of the original class, to delegate the serialization //Get the TypeAdapter of the original class, to delegate the serialization
TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType)); TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
// Get a filled instance of the original class //Get a filled instance of the original class
Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer() Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
.getImplementation(); .getImplementation();
// Serialize the value //Serialize the value
delegate.write(out, unproxiedValue); delegate.write(out, unproxiedValue);
} }
} }

View File

@ -37,25 +37,25 @@ import java.util.Map;
@Slf4j @Slf4j
public class HttpClientUtils { public class HttpClientUtils {
// org.apache.http.impl.client.CloseableHttpClient //org.apache.http.impl.client.CloseableHttpClient
private static CloseableHttpClient httpClient = null; private static CloseableHttpClient httpClient = null;
// 这里就直接默认固定了,因为以下三个参数在新建的method中仍然可以重新配置并被覆盖. //这里就直接默认固定了,因为以下三个参数在新建的method中仍然可以重新配置并被覆盖.
static final int connectionRequestTimeout = 30000;// ms毫秒,从池中获取链接超时时间 static final int connectionRequestTimeout = 30000;//ms毫秒,从池中获取链接超时时间
static final int connectTimeout = 60000;// ms毫秒,建立链接超时时间 static final int connectTimeout = 60000;//ms毫秒,建立链接超时时间
static final int socketTimeout = 60000;// ms毫秒,读取超时时间 static final int socketTimeout = 60000;//ms毫秒,读取超时时间
// 总配置,主要涉及是以下两个参数,如果要作调整没有用到properties会比较后麻烦,但鉴于一经粘贴,随处可用的特点,就不再做依赖性配置化处理了. //总配置,主要涉及是以下两个参数,如果要作调整没有用到properties会比较后麻烦,但鉴于一经粘贴,随处可用的特点,就不再做依赖性配置化处理了.
// 而且这个参数同一家公司基本不会变动. //而且这个参数同一家公司基本不会变动.
static final int maxTotal = 500;// 最大总并发,很重要的参数 static final int maxTotal = 500;//最大总并发,很重要的参数
static final int maxPerRoute = 100;// 每路并发,很重要的参数 static final int maxPerRoute = 100;//每路并发,很重要的参数
// 正常情况这里应该配成MAP或LIST //正常情况这里应该配成MAP或LIST
// 细化配置参数,用来对每路参数做精细化处理,可以管控各ip的流量,比如默认配置请求baidu:80端口最大100个并发链接, //细化配置参数,用来对每路参数做精细化处理,可以管控各ip的流量,比如默认配置请求baidu:80端口最大100个并发链接,
static final String detailHostName = "http://www.baidu.com";// 每个细化配置之ip(不重要,在特殊场景很有用) static final String detailHostName = "http://www.baidu.com";//每个细化配置之ip(不重要,在特殊场景很有用)
// 每个细化配置之port(不重要,在特殊场景很有用) //每个细化配置之port(不重要,在特殊场景很有用)
static final int detailPort = 80; static final int detailPort = 80;
// 每个细化配置之最大并发数(不重要,在特殊场景很有用) //每个细化配置之最大并发数(不重要,在特殊场景很有用)
static final int detailMaxPerRoute = 100; static final int detailMaxPerRoute = 100;
private synchronized static CloseableHttpClient getHttpClient() { private synchronized static CloseableHttpClient getHttpClient() {
@ -72,51 +72,51 @@ public class HttpClientUtils {
private static CloseableHttpClient init() { private static CloseableHttpClient init() {
CloseableHttpClient newHotpoint; CloseableHttpClient newHotpoint;
// 设置连接池 //设置连接池
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register("https", sslsf).build(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// 将最大连接数增加 //将最大连接数增加
cm.setMaxTotal(maxTotal); cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加 //将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute); cm.setDefaultMaxPerRoute(maxPerRoute);
// 细化配置开始,其实这里用Map或List的for循环来配置每个链接,在特殊场景很有用. //细化配置开始,其实这里用Map或List的for循环来配置每个链接,在特殊场景很有用.
// 将每个路由基础的连接做特殊化配置,一般用不着 //将每个路由基础的连接做特殊化配置,一般用不着
HttpHost httpHost = new HttpHost(detailHostName, detailPort); HttpHost httpHost = new HttpHost(detailHostName, detailPort);
// 将目标主机的最大连接数增加 //将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), detailMaxPerRoute); cm.setMaxPerRoute(new HttpRoute(httpHost), detailMaxPerRoute);
// 细化配置结束 //细化配置结束
// 请求重试处理 //请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> {
if (executionCount >= 2) {// 如果已经重试了2次就放弃 if (executionCount >= 2) {//如果已经重试了2次就放弃
return false; return false;
} }
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接那么就重试 if (exception instanceof NoHttpResponseException) {//如果服务器丢掉了连接那么就重试
return true; return true;
} }
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 if (exception instanceof SSLHandshakeException) {//不要重试SSL握手异常
return false; return false;
} }
if (exception instanceof InterruptedIOException) {// 超时 if (exception instanceof InterruptedIOException) {//超时
return false; return false;
} }
if (exception instanceof UnknownHostException) {// 目标服务器不可达 if (exception instanceof UnknownHostException) {//目标服务器不可达
return false; return false;
} }
if (exception instanceof SSLException) {// SSL握手异常 if (exception instanceof SSLException) {//SSL握手异常
return false; return false;
} }
HttpClientContext clientContext = HttpClientContext.adapt(context); HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest(); HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的就再次尝试 //如果请求是幂等的就再次尝试
return !(request instanceof HttpEntityEnclosingRequest); return !(request instanceof HttpEntityEnclosingRequest);
}; };
// 配置请求的超时设置 //配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build(); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
newHotpoint = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setRetryHandler(httpRequestRetryHandler).build(); newHotpoint = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setRetryHandler(httpRequestRetryHandler).build();
return newHotpoint; return newHotpoint;
@ -124,13 +124,13 @@ public class HttpClientUtils {
public static String doGet(String url, Map<String, String> param) { public static String doGet(String url, Map<String, String> param) {
// httpClient //httpClient
CloseableHttpClient httpClient = getHttpClient(); CloseableHttpClient httpClient = getHttpClient();
String resultString = ""; String resultString = "";
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
// 创建uri //创建uri
URIBuilder builder = new URIBuilder(url); URIBuilder builder = new URIBuilder(url);
if (param != null) { if (param != null) {
for (String key : param.keySet()) { for (String key : param.keySet()) {
@ -139,12 +139,12 @@ public class HttpClientUtils {
} }
URI uri = builder.build(); URI uri = builder.build();
// 创建http GET请求 //创建http GET请求
HttpGet httpGet = new HttpGet(uri); HttpGet httpGet = new HttpGet(uri);
// 执行请求 //执行请求
response = httpClient.execute(httpGet); response = httpClient.execute(httpGet);
// 判断返回状态是否为200 //判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) { if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} }

View File

@ -90,7 +90,7 @@ public class PageUtil {
*/ */
public static <T> QueryWrapper<T> initWrapper(Object object, SearchVO searchVo) { public static <T> QueryWrapper<T> initWrapper(Object object, SearchVO searchVo) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>(); QueryWrapper<T> queryWrapper = new QueryWrapper<>();
// 创建时间区间判定 //创建时间区间判定
if (searchVo != null && StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) { if (searchVo != null && StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
Date start = cn.hutool.core.date.DateUtil.parse(searchVo.getStartDate()); Date start = cn.hutool.core.date.DateUtil.parse(searchVo.getStartDate());
Date end = cn.hutool.core.date.DateUtil.parse(searchVo.getEndDate()); Date end = cn.hutool.core.date.DateUtil.parse(searchVo.getEndDate());

View File

@ -50,11 +50,11 @@ public class PasswordUtil {
* @return Key PBE算法密钥 * @return Key PBE算法密钥
*/ */
private static Key getPBEKey(String password) throws Exception { private static Key getPBEKey(String password) throws Exception {
// 实例化使用的算法 //实例化使用的算法
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 设置PBE密钥参数 //设置PBE密钥参数
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
// 生成密钥 //生成密钥
SecretKey secretKey = keyFactory.generateSecret(keySpec); SecretKey secretKey = keyFactory.generateSecret(keySpec);
return secretKey; return secretKey;

View File

@ -17,10 +17,10 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SpelUtil { public class SpelUtil {
// spel表达式解析器 //spel表达式解析器
private static SpelExpressionParser spelExpressionParser = new SpelExpressionParser(); private static SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
// 参数名发现器 //参数名发现器
private static DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); private static DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/** /**
@ -30,8 +30,8 @@ public class SpelUtil {
* @param spel * @param spel
* @return * @return
*/ */
public static String compileParams(JoinPoint joinPoint, String spel) { // Spel表达式解析日志信息 public static String compileParams(JoinPoint joinPoint, String spel) { //Spel表达式解析日志信息
// 获得方法参数名数组 //获得方法参数名数组
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod()); String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod());
@ -41,7 +41,7 @@ public class SpelUtil {
//获取方法参数值 //获取方法参数值
Object[] args = joinPoint.getArgs(); Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
context.setVariable(parameterNames[i], args[i]); // 替换spel里的变量值为实际值 比如 #user --> user对象 context.setVariable(parameterNames[i], args[i]); //替换spel里的变量值为实际值 比如 #user --> user对象
} }
return spelExpressionParser.parseExpression(spel).getValue(context).toString(); return spelExpressionParser.parseExpression(spel).getValue(context).toString();
} }
@ -55,8 +55,8 @@ public class SpelUtil {
* @param spel * @param spel
* @return * @return
*/ */
public static String compileParams(JoinPoint joinPoint, Object rvt, String spel) { // Spel表达式解析日志信息 public static String compileParams(JoinPoint joinPoint, Object rvt, String spel) { //Spel表达式解析日志信息
// 获得方法参数名数组 //获得方法参数名数组
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod()); String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod());
@ -66,7 +66,7 @@ public class SpelUtil {
//获取方法参数值 //获取方法参数值
Object[] args = joinPoint.getArgs(); Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
context.setVariable(parameterNames[i], args[i]); // 替换spel里的变量值为实际值 比如 #user --> user对象 context.setVariable(parameterNames[i], args[i]); //替换spel里的变量值为实际值 比如 #user --> user对象
} }
context.setVariable("rvt", rvt); context.setVariable("rvt", rvt);
return spelExpressionParser.parseExpression(spel).getValue(context).toString(); return spelExpressionParser.parseExpression(spel).getValue(context).toString();

View File

@ -22,13 +22,13 @@ public class ImageUtil {
*/ */
public static void addWatermark(BufferedImage oriImage, String text) { public static void addWatermark(BufferedImage oriImage, String text) {
Graphics2D graphics2D = oriImage.createGraphics(); Graphics2D graphics2D = oriImage.createGraphics();
// 设置水印文字颜色 //设置水印文字颜色
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 设置水印文字Font //设置水印文字Font
graphics2D.setColor(Color.black); graphics2D.setColor(Color.black);
// 设置水印文字透明度 //设置水印文字透明度
graphics2D.setFont(new Font("宋体", Font.BOLD, 30)); graphics2D.setFont(new Font("宋体", Font.BOLD, 30));
// 第一参数->设置的内容后面两个参数->文字在图片上的坐标位置(x,y) //第一参数->设置的内容后面两个参数->文字在图片上的坐标位置(x,y)
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f)); graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
graphics2D.drawString(text, 10, 40); graphics2D.drawString(text, 10, 40);
graphics2D.dispose(); graphics2D.dispose();
@ -44,40 +44,40 @@ public class ImageUtil {
*/ */
public static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage, public static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage,
int x, int y) { int x, int y) {
// 临时数组遍历用于高斯模糊存周边像素值 //临时数组遍历用于高斯模糊存周边像素值
int[][] matrix = new int[3][3]; int[][] matrix = new int[3][3];
int[] values = new int[9]; int[] values = new int[9];
int xLength = templateImage.getWidth(); int xLength = templateImage.getWidth();
int yLength = templateImage.getHeight(); int yLength = templateImage.getHeight();
// 模板图像宽度 //模板图像宽度
for (int i = 0; i < xLength; i++) { for (int i = 0; i < xLength; i++) {
// 模板图片高度 //模板图片高度
for (int j = 0; j < yLength; j++) { for (int j = 0; j < yLength; j++) {
// 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中 //如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
int rgb = templateImage.getRGB(i, j); int rgb = templateImage.getRGB(i, j);
if (rgb < 0) { if (rgb < 0) {
newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j)); newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));
// 抠图区域高斯模糊 //抠图区域高斯模糊
readPixel(oriImage, x + i, y + j, values); readPixel(oriImage, x + i, y + j, values);
fillMatrix(matrix, values); fillMatrix(matrix, values);
oriImage.setRGB(x + i, y + j, avgMatrix(matrix)); oriImage.setRGB(x + i, y + j, avgMatrix(matrix));
} }
// 防止数组越界判断 //防止数组越界判断
if (i == (xLength - 1) || j == (yLength - 1)) { if (i == (xLength - 1) || j == (yLength - 1)) {
continue; continue;
} }
int rightRgb = templateImage.getRGB(i + 1, j); int rightRgb = templateImage.getRGB(i + 1, j);
int downRgb = templateImage.getRGB(i, j + 1); int downRgb = templateImage.getRGB(i, j + 1);
// 描边处理,取带像素和无像素的界点判断该点是不是临界轮廓点,如果是设置该坐标像素是白色 //描边处理,取带像素和无像素的界点判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0)
|| (rgb < 0 && downRgb >= 0)) { || (rgb < 0 && downRgb >= 0)) {
newImage.setRGB(i, j, Color.GRAY.getRGB()); newImage.setRGB(i, j, Color.GRAY.getRGB());
// oriImage.setRGB(x + i, y + j, Color.white.getRGB()); // oriImage.setRGB(x + i, y + j, Color.white.getRGB());
} }
} }
} }

View File

@ -44,34 +44,34 @@ public class SliderImageUtil {
Random random = new Random(); Random random = new Random();
Map<String, Object> pictureMap = new HashMap<>(); Map<String, Object> pictureMap = new HashMap<>();
// 拼图 //拼图
BufferedImage sliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(sliderFile.getBase64())); BufferedImage sliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(sliderFile.getBase64()));
int sliderWidth = sliderImage.getWidth(); int sliderWidth = sliderImage.getWidth();
int sliderHeight = sliderImage.getHeight(); int sliderHeight = sliderImage.getHeight();
// 原图 //原图
BufferedImage originalImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(originalFile.getBase64())); BufferedImage originalImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(originalFile.getBase64()));
int originalWidth = originalImage.getWidth(); int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight(); int originalHeight = originalImage.getHeight();
// 随机生成抠图坐标X,Y //随机生成抠图坐标X,Y
// X轴距离右端targetWidth Y轴距离底部targetHeight以上 //X轴距离右端targetWidth Y轴距离底部targetHeight以上
int randomX = random.nextInt(originalWidth - 3 * sliderWidth) + 2 * sliderWidth; int randomX = random.nextInt(originalWidth - 3 * sliderWidth) + 2 * sliderWidth;
int randomY = random.nextInt(originalHeight - sliderHeight); int randomY = random.nextInt(originalHeight - sliderHeight);
log.info("原图大小{} x {},随机生成的坐标 X,Y 为({}{}", originalWidth, originalHeight, randomX, randomY); log.info("原图大小{} x {},随机生成的坐标 X,Y 为({}{}", originalWidth, originalHeight, randomX, randomY);
// 新建一个和模板一样大小的图像TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像正常取imageTemplate.getType() //新建一个和模板一样大小的图像TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像正常取imageTemplate.getType()
BufferedImage newImage = new BufferedImage(sliderWidth, sliderHeight, sliderImage.getType()); BufferedImage newImage = new BufferedImage(sliderWidth, sliderHeight, sliderImage.getType());
// 得到画笔对象 //得到画笔对象
Graphics2D graphics = newImage.createGraphics(); Graphics2D graphics = newImage.createGraphics();
// 如果需要生成RGB格式需要做如下配置,Transparency 设置透明 //如果需要生成RGB格式需要做如下配置,Transparency 设置透明
newImage = graphics.getDeviceConfiguration().createCompatibleImage(sliderWidth, sliderHeight, newImage = graphics.getDeviceConfiguration().createCompatibleImage(sliderWidth, sliderHeight,
Transparency.TRANSLUCENT); Transparency.TRANSLUCENT);
// 新建的图像根据模板颜色赋值,源图生成遮罩 //新建的图像根据模板颜色赋值,源图生成遮罩
ImageUtil.cutByTemplate(originalImage, sliderImage, newImage, randomX, randomY); ImageUtil.cutByTemplate(originalImage, sliderImage, newImage, randomX, randomY);
// 设置抗锯齿的属性 //设置抗锯齿的属性
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
graphics.drawImage(newImage, 0, 0, null); graphics.drawImage(newImage, 0, 0, null);
@ -79,19 +79,19 @@ public class SliderImageUtil {
//添加水印 //添加水印
ImageUtil.addWatermark(originalImage, "请滑动拼图"); ImageUtil.addWatermark(originalImage, "请滑动拼图");
ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();// 新建流 ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();//新建流
ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);// 利用ImageIO类提供的write方法将bi以png图片的数据模式写入流 ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);//利用ImageIO类提供的write方法将bi以png图片的数据模式写入流
byte[] newImagery = newImageOs.toByteArray(); byte[] newImagery = newImageOs.toByteArray();
ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();// 新建流 ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();//新建流
ImageIO.write(originalImage, IMG_FILE_TYPE, oriImagesOs);// 利用ImageIO类提供的write方法将bi以jpg图片的数据模式写入流 ImageIO.write(originalImage, IMG_FILE_TYPE, oriImagesOs);//利用ImageIO类提供的write方法将bi以jpg图片的数据模式写入流
byte[] oriImageByte = oriImagesOs.toByteArray(); byte[] oriImageByte = oriImagesOs.toByteArray();
pictureMap.put("slidingImage", "data:image/png;base64," + Base64Utils.encodeToString(newImagery)); pictureMap.put("slidingImage", "data:image/png;base64," + Base64Utils.encodeToString(newImagery));
pictureMap.put("backImage", "data:image/png;base64," + Base64Utils.encodeToString(oriImageByte)); pictureMap.put("backImage", "data:image/png;base64," + Base64Utils.encodeToString(oriImageByte));
// x轴 // x轴
pictureMap.put("randomX", randomX); pictureMap.put("randomX", randomX);
// y轴 // y轴
pictureMap.put("randomY", randomY); pictureMap.put("randomY", randomY);
pictureMap.put("originalHeight", originalHeight); pictureMap.put("originalHeight", originalHeight);

View File

@ -58,14 +58,14 @@ public class VerificationServiceImpl implements VerificationService {
Random random = new Random(); Random random = new Random();
// 随机选择需要切的图下标 //随机选择需要切的图下标
int resourceNum = random.nextInt(verificationResources.size()); int resourceNum = random.nextInt(verificationResources.size());
// 随机选择剪切模版下标 //随机选择剪切模版下标
int sliderNum = random.nextInt(verificationSlider.size()); int sliderNum = random.nextInt(verificationSlider.size());
// 随机选择需要切的图片地址 //随机选择需要切的图片地址
String originalResource = verificationResources.get(resourceNum).getResource(); String originalResource = verificationResources.get(resourceNum).getResource();
// 随机选择剪切模版图片地址 //随机选择剪切模版图片地址
String sliderResource = verificationSlider.get(sliderNum).getResource(); String sliderResource = verificationSlider.get(sliderNum).getResource();
try { try {
@ -73,10 +73,10 @@ public class VerificationServiceImpl implements VerificationService {
SerializableStream originalFile = getInputStream(originalResource); SerializableStream originalFile = getInputStream(originalResource);
SerializableStream sliderFile = getInputStream(sliderResource); SerializableStream sliderFile = getInputStream(sliderResource);
Map<String, Object> resultMap = SliderImageUtil.pictureTemplatesCut(sliderFile, originalFile); Map<String, Object> resultMap = SliderImageUtil.pictureTemplatesCut(sliderFile, originalFile);
// 生成验证参数 120可以验证 无需手动清除120秒有效时间自动清除 //生成验证参数 120可以验证 无需手动清除120秒有效时间自动清除
cache.put(cacheKey(verificationEnums, uuid), resultMap.get("randomX"), 120L); cache.put(cacheKey(verificationEnums, uuid), resultMap.get("randomX"), 120L);
resultMap.put("key", cacheKey(verificationEnums, uuid)); resultMap.put("key", cacheKey(verificationEnums, uuid));
// 移除横坐标移动距离 //移除横坐标移动距离
resultMap.remove("randomX"); resultMap.remove("randomX");
return resultMap; return resultMap;
} catch (ServiceException e) { } catch (ServiceException e) {

View File

@ -83,10 +83,10 @@ public class RedisConfig extends CachingConfigurerSupport {
RedisTemplate<Object, Object> template = new RedisTemplate<>(); RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化 //使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class); FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// value值的序列化采用fastJsonRedisSerializer //value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer); template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer //key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer()); template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(lettuceConnectionFactory); template.setConnectionFactory(lettuceConnectionFactory);
@ -102,19 +102,19 @@ public class RedisConfig extends CachingConfigurerSupport {
return (target, method, params) -> { return (target, method, params) -> {
Map<String, Object> container = new HashMap<>(3); Map<String, Object> container = new HashMap<>(3);
Class<?> targetClassClass = target.getClass(); Class<?> targetClassClass = target.getClass();
// 类地址 //类地址
container.put("class", targetClassClass.toGenericString()); container.put("class", targetClassClass.toGenericString());
// 方法名称 //方法名称
container.put("methodName", method.getName()); container.put("methodName", method.getName());
// 包名称 //包名称
container.put("package", targetClassClass.getPackage()); container.put("package", targetClassClass.getPackage());
// 参数列表 //参数列表
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
container.put(String.valueOf(i), params[i]); container.put(String.valueOf(i), params[i]);
} }
// 转为JSON字符串 //转为JSON字符串
String jsonString = JSON.toJSONString(container); String jsonString = JSON.toJSONString(container);
// 做SHA256 Hash计算得到一个SHA256摘要作为Key //做SHA256 Hash计算得到一个SHA256摘要作为Key
return DigestUtils.sha256Hex(jsonString); return DigestUtils.sha256Hex(jsonString);
}; };
} }
@ -122,7 +122,7 @@ public class RedisConfig extends CachingConfigurerSupport {
@Bean @Bean
@Override @Override
public CacheErrorHandler errorHandler() { public CacheErrorHandler errorHandler() {
// 异常处理当Redis发生异常时打印日志但是程序正常走 //异常处理当Redis发生异常时打印日志但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
return new CacheErrorHandler() { return new CacheErrorHandler() {
@Override @Override

View File

@ -62,9 +62,9 @@ public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
} }
restBuilder.setRequestConfigCallback(requestConfigBuilder -> restBuilder.setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder.setConnectTimeout(1000) // time until a connection with the server is established. requestConfigBuilder.setConnectTimeout(1000) //time until a connection with the server is established.
.setSocketTimeout(12 * 1000) // time of inactivity to wait for packets[data] to receive. .setSocketTimeout(12 * 1000) //time of inactivity to wait for packets[data] to receive.
.setConnectionRequestTimeout(2 * 1000)); // time to fetch a connection from the connection pool 0 for infinite. .setConnectionRequestTimeout(2 * 1000)); //time to fetch a connection from the connection pool 0 for infinite.
client = new RestHighLevelClient(restBuilder); client = new RestHighLevelClient(restBuilder);
return client; return client;

View File

@ -23,11 +23,11 @@ public class UrlConfiguration implements WebMvcConfigurer {
@Override @Override
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器 //注册拦截器
InterceptorRegistration ir = registry.addInterceptor(requestInterceptorAdapter); InterceptorRegistration ir = registry.addInterceptor(requestInterceptorAdapter);
// 配置拦截的路径 //配置拦截的路径
ir.addPathPatterns("/**"); ir.addPathPatterns("/**");
// 配置不拦截的路径 //配置不拦截的路径
ir.excludePathPatterns(ignoredUrlsProperties.getUrls()); ir.excludePathPatterns(ignoredUrlsProperties.getUrls());
} }
@ -36,7 +36,7 @@ public class UrlConfiguration implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/"); registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// 解决 SWAGGER 404报错 //解决 SWAGGER 404报错
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
} }

View File

@ -37,9 +37,9 @@ public class CreateTimeShardingTableAlgorithmBak implements PreciseShardingAlgor
//循环增加区间的查询条件 //循环增加区间的查询条件
// 因为考虑到 假设2019-052020-05 //因为考虑到 假设2019-052020-05
// 这快是没办法处理的因为分库分表之后每个库都要进行查询如果操作为1-4月那么2020年数据查询正确了可是2019年到5-12月数据就查询不到了 //这快是没办法处理的因为分库分表之后每个库都要进行查询如果操作为1-4月那么2020年数据查询正确了可是2019年到5-12月数据就查询不到了
// 这里需要做一些性能的浪费现在看来是没办法处理到 //这里需要做一些性能的浪费现在看来是没办法处理到
for (Integer i = 1; i <= 12; i++) { for (Integer i = 1; i <= 12; i++) {
collect.add("li_order_" + i); collect.add("li_order_" + i);

View File

@ -73,8 +73,8 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("商品") .groupName("商品")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.goods")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.goods"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -87,7 +87,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("会员") .groupName("会员")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.member")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.member"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -100,7 +100,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("促销") .groupName("促销")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.promotion")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.promotion"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -113,7 +113,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("店铺") .groupName("店铺")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.store")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.store"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -126,7 +126,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("交易") .groupName("交易")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.trade")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.trade"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -140,7 +140,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("设置") .groupName("设置")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.setting")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.setting"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -153,7 +153,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("权限") .groupName("权限")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.permission")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.permission"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -166,7 +166,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("其他") .groupName("其他")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.other")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.other"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -179,7 +179,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("通用") .groupName("通用")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.common")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.common"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -191,7 +191,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("分销") .groupName("分销")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.distribution")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.distribution"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -204,7 +204,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("统计") .groupName("统计")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.statistics")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.statistics"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -217,7 +217,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("支付") .groupName("支付")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.payment")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.payment"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()
@ -230,7 +230,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.groupName("登录") .groupName("登录")
.apiInfo(apiInfo()).select() .apiInfo(apiInfo()).select()
// 扫描所有有注解的api用这种方式更灵活 //扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.basePackage("cn.lili.controller.passport")) .apis(RequestHandlerSelectors.basePackage("cn.lili.controller.passport"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build() .build()

View File

@ -27,15 +27,15 @@ public class ThreadConfig implements AsyncConfigurer {
@Override @Override
public Executor getAsyncExecutor() { public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数默认为5 // 核心线程数默认为5
executor.setCorePoolSize(threadProperties.getCorePoolSize()); executor.setCorePoolSize(threadProperties.getCorePoolSize());
// 最大线程数默认为10 // 最大线程数默认为10
executor.setMaxPoolSize(threadProperties.getMaxPoolSize()); executor.setMaxPoolSize(threadProperties.getMaxPoolSize());
// 队列最大长度一般需要设置值为足够大 // 队列最大长度一般需要设置值为足够大
executor.setQueueCapacity(threadProperties.getQueueCapacity()); executor.setQueueCapacity(threadProperties.getQueueCapacity());
// 线程池维护线程所允许的空闲时间默认为60s // 线程池维护线程所允许的空闲时间默认为60s
executor.setKeepAliveSeconds(threadProperties.getKeepAliveSeconds()); executor.setKeepAliveSeconds(threadProperties.getKeepAliveSeconds());
// 允许超时关闭 // 允许超时关闭
executor.setAllowCoreThreadTimeOut(threadProperties.getAllowCoreThreadTimeOut()); executor.setAllowCoreThreadTimeOut(threadProperties.getAllowCoreThreadTimeOut());
executor.initialize(); executor.initialize();
return executor; return executor;

View File

@ -20,7 +20,7 @@ public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { public void registerStompEndpoints(StompEndpointRegistry registry) {
// 允许使用socketJs方式访问 即可通过http://IP:PORT/manager/ws来和服务端websocket连接 //允许使用socketJs方式访问 即可通过http://IP:PORT/manager/ws来和服务端websocket连接
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
} }
@ -31,11 +31,11 @@ public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry registry) { public void configureMessageBroker(MessageBrokerRegistry registry) {
// 订阅Broker名称 user点对点 topic广播即群发 //订阅Broker名称 user点对点 topic广播即群发
registry.enableSimpleBroker("/user","/topic"); registry.enableSimpleBroker("/user","/topic");
// 全局(客户端)使用的消息前缀 //全局(客户端)使用的消息前缀
registry.setApplicationDestinationPrefixes("/app"); registry.setApplicationDestinationPrefixes("/app");
// 点对点使用的前缀 无需配置 默认/user //点对点使用的前缀 无需配置 默认/user
registry.setUserDestinationPrefix("/user"); registry.setUserDestinationPrefix("/user");
} }
} }

View File

@ -100,14 +100,14 @@ public class CodeGenerator {
* @throws IOException * @throws IOException
*/ */
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
// 模板路径 //模板路径
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/templates/"); ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/templates/");
Configuration cfg = Configuration.defaultConfiguration(); Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg); GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
// 生成代码 //生成代码
generateCode(gt); generateCode(gt);
//根据类名删除生成的代码 //根据类名删除生成的代码
// deleteCode(className); // deleteCode(className);
} }
/** /**
@ -152,7 +152,7 @@ public class CodeGenerator {
entityDir.mkdirs(); entityDir.mkdirs();
} }
if (!entityFile.exists()) { if (!entityFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
entityFile.createNewFile(); entityFile.createNewFile();
out = new FileOutputStream(entityFile); out = new FileOutputStream(entityFile);
entityTemplate.renderTo(out); entityTemplate.renderTo(out);
@ -170,7 +170,7 @@ public class CodeGenerator {
daoDir.mkdirs(); daoDir.mkdirs();
} }
if (!daoFile.exists()) { if (!daoFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
daoFile.createNewFile(); daoFile.createNewFile();
out = new FileOutputStream(daoFile); out = new FileOutputStream(daoFile);
daoTemplate.renderTo(out); daoTemplate.renderTo(out);
@ -188,7 +188,7 @@ public class CodeGenerator {
serviceDir.mkdirs(); serviceDir.mkdirs();
} }
if (!serviceFile.exists()) { if (!serviceFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
serviceFile.createNewFile(); serviceFile.createNewFile();
out = new FileOutputStream(serviceFile); out = new FileOutputStream(serviceFile);
serviceTemplate.renderTo(out); serviceTemplate.renderTo(out);
@ -207,7 +207,7 @@ public class CodeGenerator {
serviceImplDir.mkdirs(); serviceImplDir.mkdirs();
} }
if (!serviceImplFile.exists()) { if (!serviceImplFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
serviceImplFile.createNewFile(); serviceImplFile.createNewFile();
out = new FileOutputStream(serviceImplFile); out = new FileOutputStream(serviceImplFile);
serviceImplTemplate.renderTo(out); serviceImplTemplate.renderTo(out);
@ -225,7 +225,7 @@ public class CodeGenerator {
controllerDir.mkdirs(); controllerDir.mkdirs();
} }
if (!controllerFile.exists()) { if (!controllerFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
controllerFile.createNewFile(); controllerFile.createNewFile();
out = new FileOutputStream(controllerFile); out = new FileOutputStream(controllerFile);
controllerTemplate.renderTo(out); controllerTemplate.renderTo(out);
@ -243,7 +243,7 @@ public class CodeGenerator {
mapperXmlDir.mkdirs(); mapperXmlDir.mkdirs();
} }
if (!mapperXmlFile.exists()) { if (!mapperXmlFile.exists()) {
// 若文件存在则不重新生成 //若文件存在则不重新生成
mapperXmlFile.createNewFile(); mapperXmlFile.createNewFile();
out = new FileOutputStream(mapperXmlFile); out = new FileOutputStream(mapperXmlFile);
mapperXmlTemplate.renderTo(out); mapperXmlTemplate.renderTo(out);

View File

@ -141,25 +141,25 @@ public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> impleme
*/ */
private List<Region> initData(String jsonString) { private List<Region> initData(String jsonString) {
// 最终数据承载对象 //最终数据承载对象
List<Region> regions = new ArrayList<>(); List<Region> regions = new ArrayList<>();
JSONObject jsonObject = JSONObject.parseObject(jsonString); JSONObject jsonObject = JSONObject.parseObject(jsonString);
//获取到国家及下面所有的信息 开始循环插入这里可以写成递归调用但是不如这样方便查看理解 //获取到国家及下面所有的信息 开始循环插入这里可以写成递归调用但是不如这样方便查看理解
JSONArray countryAll = jsonObject.getJSONArray("districts"); JSONArray countryAll = jsonObject.getJSONArray("districts");
for (int i = 0; i < countryAll.size(); i++) { for (int i = 0; i < countryAll.size(); i++) {
JSONObject contry = countryAll.getJSONObject(i); JSONObject contry = countryAll.getJSONObject(i);
// String citycode0 = contry.getString("citycode"); // String citycode0 = contry.getString("citycode");
// String adcode0 = contry.getString("adcode"); // String adcode0 = contry.getString("adcode");
// String name0 = contry.getString("name"); // String name0 = contry.getString("name");
// String center0 = contry.getString("center"); // String center0 = contry.getString("center");
// String country = contry.getString("level"); // String country = contry.getString("level");
// int level = 0; // int level = 0;
// if (country.equals("country")) { // if (country.equals("country")) {
// level = 0; // level = 0;
// } // }
// 插入国家 // 插入国家
// Integer id1 = insert(0, adcode0, citycode0, name0, center0, level, name0); // Integer id1 = insert(0, adcode0, citycode0, name0, center0, level, name0);
// Integer id1 = insert(0, adcode0, citycode0, name0, center0, level); // Integer id1 = insert(0, adcode0, citycode0, name0, center0, level);
String id1 = "0"; String id1 = "0";
JSONArray provinceAll = contry.getJSONArray("districts"); JSONArray provinceAll = contry.getJSONArray("districts");
for (int j = 0; j < provinceAll.size(); j++) { for (int j = 0; j < provinceAll.size(); j++) {
@ -192,7 +192,7 @@ public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> impleme
String level3 = district.getString("level"); String level3 = district.getString("level");
//插入区县 //插入区县
String id4 = insert(regions, id3, citycode3, adcode3, name3, center3, level3, w, id1, id2, id3); String id4 = insert(regions, id3, citycode3, adcode3, name3, center3, level3, w, id1, id2, id3);
// JSONArray street = street3.getJSONArray("districts"); // JSONArray street = street3.getJSONArray("districts");
//有需要可以继续向下遍历 //有需要可以继续向下遍历
JSONArray streetAll = district.getJSONArray("districts"); JSONArray streetAll = district.getJSONArray("districts");
for (int r = 0; r < streetAll.size(); r++) { for (int r = 0; r < streetAll.size(); r++) {
@ -232,11 +232,11 @@ public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> impleme
* @return * @return
*/ */
public String insert(List<Region> regions, String parentId, String cityCode, String adCode, String name, String center, String level, Integer order, String... ids) { public String insert(List<Region> regions, String parentId, String cityCode, String adCode, String name, String center, String level, Integer order, String... ids) {
// \"citycode\": [],\n" + // \"citycode\": [],\n" +
// " \"adcode\": \"100000\",\n" + // " \"adcode\": \"100000\",\n" +
// " \"name\": \"中华人民共和国\",\n" + // " \"name\": \"中华人民共和国\",\n" +
// " \"center\": \"116.3683244,39.915085\",\n" + // " \"center\": \"116.3683244,39.915085\",\n" +
// " \"level\": \"country\",\n" + // " \"level\": \"country\",\n" +
Region record = new Region(); Region record = new Region();
if (!adCode.equals("[]")) { if (!adCode.equals("[]")) {
record.setAdCode(adCode); record.setAdCode(adCode);

View File

@ -29,8 +29,8 @@ public class Commodity extends BaseEntity {
private String name; private String name;
//1一口价只需要传入priceprice2不传 //1一口价只需要传入priceprice2不传
// 2价格区间price字段为左边界price2字段为右边界price和price2必传 //2价格区间price字段为左边界price2字段为右边界price和price2必传
// 3显示折扣价price字段为原价price2字段为现价 price和price2必传 //3显示折扣价price字段为原价price2字段为现价 price和price2必传
@ApiModelProperty(value = "价格类型") @ApiModelProperty(value = "价格类型")
private Integer priceType; private Integer priceType;

View File

@ -23,8 +23,8 @@ public class GoodsInfo {
private String name; private String name;
//1一口价只需要传入priceprice2不传 //1一口价只需要传入priceprice2不传
// 2价格区间price字段为左边界price2字段为右边界price和price2必传 //2价格区间price字段为左边界price2字段为右边界price和price2必传
// 3显示折扣价price字段为原价price2字段为现价 price和price2必传 //3显示折扣价price字段为原价price2字段为现价 price和price2必传
@ApiModelProperty(value = "价格类型") @ApiModelProperty(value = "价格类型")
private Integer priceType; private Integer priceType;

View File

@ -75,7 +75,7 @@ public class StudioServiceImpl extends ServiceImpl<StudioMapper, Studio> impleme
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.BROADCAST, studio.getId()), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.BROADCAST, studio.getId()),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
//直播结束延时任务 //直播结束延时任务
@ -84,7 +84,7 @@ public class StudioServiceImpl extends ServiceImpl<StudioMapper, Studio> impleme
Long.parseLong(studio.getEndTime()) * 1000L, broadcastMessage, Long.parseLong(studio.getEndTime()) * 1000L, broadcastMessage,
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.BROADCAST, studio.getId()), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.BROADCAST, studio.getId()),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
} }
return true; return true;
@ -100,7 +100,7 @@ public class StudioServiceImpl extends ServiceImpl<StudioMapper, Studio> impleme
Studio oldStudio = this.getById(studio.getId()); Studio oldStudio = this.getById(studio.getId());
wechatLivePlayerUtil.editRoom(studio); wechatLivePlayerUtil.editRoom(studio);
if (this.updateById(studio)) { if (this.updateById(studio)) {
// 发送更新延时任务 //发送更新延时任务
//直播间开始 //直播间开始
BroadcastMessage broadcastMessage = new BroadcastMessage(studio.getId(), StudioStatusEnum.START.name()); BroadcastMessage broadcastMessage = new BroadcastMessage(studio.getId(), StudioStatusEnum.START.name());
this.timeTrigger.edit( this.timeTrigger.edit(

View File

@ -93,13 +93,13 @@ public class WechatLivePlayerUtil {
//发送url //发送url
String url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + token; String url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + token;
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
// 获取回放 //获取回放
map.put("action", "get_replay"); map.put("action", "get_replay");
// 直播间ID //直播间ID
map.put("room_id", roomId); map.put("room_id", roomId);
// 起始拉取视频0表示从第一个视频片段开始拉取 //起始拉取视频0表示从第一个视频片段开始拉取
map.put("start", "0"); map.put("start", "0");
// 每次拉取的数量建议100以内 //每次拉取的数量建议100以内
map.put("limit", "1"); map.put("limit", "1");
String content = HttpUtils.doPostWithJson(url, map); String content = HttpUtils.doPostWithJson(url, map);
@ -122,10 +122,10 @@ public class WechatLivePlayerUtil {
//发送url //发送url
String url = "https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token=" + token; String url = "https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token=" + token;
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
// 直播间回放 //直播间回放
Integer[] ids = {goodsId}; Integer[] ids = {goodsId};
map.put("ids", ids); map.put("ids", ids);
// 商品ID //商品ID
map.put("roomId", roomId); map.put("roomId", roomId);
String content = HttpUtils.doPostWithJson(url, map); String content = HttpUtils.doPostWithJson(url, map);
JSONObject json = new JSONObject(content); JSONObject json = new JSONObject(content);
@ -149,9 +149,9 @@ public class WechatLivePlayerUtil {
//发送url //发送url
String url = "https://api.weixin.qq.com/wxaapi/broadcast/goods/deleteInRoom?access_token=" + token; String url = "https://api.weixin.qq.com/wxaapi/broadcast/goods/deleteInRoom?access_token=" + token;
Map<String, Integer> map = new HashMap<>(); Map<String, Integer> map = new HashMap<>();
// 直播间回放 //直播间回放
map.put("goodsId", goodsId); map.put("goodsId", goodsId);
// 商品ID //商品ID
map.put("roomId", roomId); map.put("roomId", roomId);
String content = HttpUtils.doPostWithJson(url, map); String content = HttpUtils.doPostWithJson(url, map);
JSONObject json = new JSONObject(content); JSONObject json = new JSONObject(content);
@ -229,31 +229,31 @@ public class WechatLivePlayerUtil {
private Map<String, String> mockRoom(String token, Studio studio) { private Map<String, String> mockRoom(String token, Studio studio) {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
// 背景图 //背景图
map.put("coverImg", wechatMediaUtil.uploadMedia(token, "image", studio.getCoverImg())); map.put("coverImg", wechatMediaUtil.uploadMedia(token, "image", studio.getCoverImg()));
// 分享图 //分享图
map.put("shareImg", wechatMediaUtil.uploadMedia(token, "image", studio.getShareImg())); map.put("shareImg", wechatMediaUtil.uploadMedia(token, "image", studio.getShareImg()));
// 购物直播频道封面图 //购物直播频道封面图
map.put("feedsImg", wechatMediaUtil.uploadMedia(token, "image", studio.getFeedsImg())); map.put("feedsImg", wechatMediaUtil.uploadMedia(token, "image", studio.getFeedsImg()));
// 直播间名字 //直播间名字
map.put("name", studio.getName()); map.put("name", studio.getName());
// 直播计划开始时间 //直播计划开始时间
map.put("startTime", studio.getStartTime()); map.put("startTime", studio.getStartTime());
// 直播计划结束时间 //直播计划结束时间
map.put("endTime", studio.getEndTime()); map.put("endTime", studio.getEndTime());
// 主播昵称 //主播昵称
map.put("anchorName", studio.getAnchorName()); map.put("anchorName", studio.getAnchorName());
// 主播微信号 //主播微信号
map.put("anchorWechat", studio.getAnchorWechat()); map.put("anchorWechat", studio.getAnchorWechat());
// 直播间类型 //直播间类型
map.put("type", "0"); map.put("type", "0");
// 是否关闭点赞 //是否关闭点赞
map.put("closeLike", "0"); map.put("closeLike", "0");
// 是否关闭货架 //是否关闭货架
map.put("closeGoods", "0"); map.put("closeGoods", "0");
// 是否关闭评论 //是否关闭评论
map.put("closeComment", "0"); map.put("closeComment", "0");
// 直播间名字 //直播间名字
map.put("closeReplay", "0"); map.put("closeReplay", "0");
return map; return map;

View File

@ -40,7 +40,7 @@ public abstract class AuthDefaultRequest implements AuthRequest {
if (!AuthChecker.isSupportedAuth(config, source)) { if (!AuthChecker.isSupportedAuth(config, source)) {
throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE, source); throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE, source);
} }
// 校验配置合法性 //校验配置合法性
AuthChecker.checkConfig(config, source); AuthChecker.checkConfig(config, source);
} }
@ -71,9 +71,9 @@ public abstract class AuthDefaultRequest implements AuthRequest {
public AuthResponse login(AuthCallback authCallback) { public AuthResponse login(AuthCallback authCallback) {
try { try {
AuthChecker.checkCode(source, authCallback); AuthChecker.checkCode(source, authCallback);
// if (!config.isIgnoreCheckState()) { // if (!config.isIgnoreCheckState()) {
// AuthChecker.checkState(authCallback.getState(), source, cache); // AuthChecker.checkState(authCallback.getState(), source, cache);
// } // }
AuthToken authToken = this.getAccessToken(authCallback); AuthToken authToken = this.getAccessToken(authCallback);
ConnectAuthUser user = this.getUserInfo(authToken); ConnectAuthUser user = this.getUserInfo(authToken);
@ -268,7 +268,7 @@ public abstract class AuthDefaultRequest implements AuthRequest {
scopes = defaultScopes; scopes = defaultScopes;
} }
if (null == separator) { if (null == separator) {
// 默认为空格 //默认为空格
separator = " "; separator = " ";
} }
String scopeStr = String.join(separator, scopes); String scopeStr = String.join(separator, scopes);

View File

@ -107,7 +107,7 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
.msg(object.getString("error")) .msg(object.getString("error"))
.build(); .build();
} }
// 返回 result = true 表示取消授权成功否则失败 //返回 result = true 表示取消授权成功否则失败
AuthResponseStatus status = object.getBooleanValue("result") ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE; AuthResponseStatus status = object.getBooleanValue("result") ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE;
return AuthResponse.builder().code(status.getCode()).msg(status.getMsg()).build(); return AuthResponse.builder().code(status.getCode()).msg(status.getMsg()).build();
} }

View File

@ -309,14 +309,14 @@ public class ConnectServiceImpl extends ServiceImpl<ConnectMapper, Connect> impl
* @return 用户信息 * @return 用户信息
*/ */
public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) { public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据 //被加密的数据
byte[] dataByte = Base64.getDecoder().decode(encryptedData); byte[] dataByte = Base64.getDecoder().decode(encryptedData);
// 加密秘钥 //加密秘钥
byte[] keyByte = Base64.getDecoder().decode(sessionKey); byte[] keyByte = Base64.getDecoder().decode(sessionKey);
// 偏移量 //偏移量
byte[] ivByte = Base64.getDecoder().decode(iv); byte[] ivByte = Base64.getDecoder().decode(iv);
try { try {
// 如果密钥不足16位那么就补足. 这个if 中的内容很重要 //如果密钥不足16位那么就补足. 这个if 中的内容很重要
int base = 16; int base = 16;
if (keyByte.length % base != 0) { if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0); int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
@ -325,13 +325,13 @@ public class ConnectServiceImpl extends ServiceImpl<ConnectMapper, Connect> impl
System.arraycopy(keyByte, 0, temp, 0, keyByte.length); System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp; keyByte = temp;
} }
// 初始化 //初始化
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte)); parameters.init(new IvParameterSpec(ivByte));
// 初始化 //初始化
cipher.init(Cipher.DECRYPT_MODE, spec, parameters); cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(dataByte); byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) { if (null != resultByte && resultByte.length > 0) {

View File

@ -47,9 +47,9 @@ public class AuthChecker {
if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) { if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) {
throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, connectAuth); throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, connectAuth);
} }
// 支付宝在创建回调地址时不允许使用localhost或者127.0.0.1 //支付宝在创建回调地址时不允许使用localhost或者127.0.0.1
if (ConnectAuthEnum.ALIPAY == connectAuth && GlobalAuthUtils.isLocalHost(redirectUri)) { if (ConnectAuthEnum.ALIPAY == connectAuth && GlobalAuthUtils.isLocalHost(redirectUri)) {
// The redirect uri of alipay is forbidden to use localhost or 127.0.0.1 //The redirect uri of alipay is forbidden to use localhost or 127.0.0.1
throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, connectAuth); throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, connectAuth);
} }
} }

View File

@ -43,7 +43,7 @@ public class Base64Utils {
'4', '5', '6', '7', '8', '9', '-', '_' // '4', '5', '6', '7', '8', '9', '-', '_' //
}; };
// -------------------------------------------------------------------- encode //-------------------------------------------------------------------- encode
/** /**
* 编码为Base64非URL安全的 * 编码为Base64非URL安全的
@ -174,7 +174,7 @@ public class Base64Utils {
} }
} }
int left = len - evenlen;// 剩余位数 int left = len - evenlen;//剩余位数
if (left > 0) { if (left > 0) {
int i = ((arr[evenlen] & 0xff) << 10) | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0); int i = ((arr[evenlen] & 0xff) << 10) | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);
@ -182,7 +182,7 @@ public class Base64Utils {
dest[destlen - 3] = encodeTable[(i >>> 6) & 0x3f]; dest[destlen - 3] = encodeTable[(i >>> 6) & 0x3f];
if (isUrlSafe) { if (isUrlSafe) {
// 在URL Safe模式下=为URL中的关键字符不需要补充空余的byte位要去掉 //在URL Safe模式下=为URL中的关键字符不需要补充空余的byte位要去掉
int urlSafeLen = destlen - 2; int urlSafeLen = destlen - 2;
if (2 == left) { if (2 == left) {
dest[destlen - 2] = encodeTable[i & 0x3f]; dest[destlen - 2] = encodeTable[i & 0x3f];

View File

@ -189,39 +189,39 @@ public class ConnectUtil {
} }
break; break;
// case ALIPAY: // case ALIPAY:
// // 支付宝在创建回调地址时不允许使用localhost或者127.0.0.1所以这儿的回调地址使用的局域网内的ip // //支付宝在创建回调地址时不允许使用localhost或者127.0.0.1所以这儿的回调地址使用的局域网内的ip
// authRequest = new AuthAlipayRequest(AuthConfig.builder() // authRequest = new AuthAlipayRequest(AuthConfig.builder()
// .clientId("") // .clientId("")
// .clientSecret("") // .clientSecret("")
// .alipayPublicKey("") // .alipayPublicKey("")
// .redirectUri(getRedirectUri(authInterface)) // .redirectUri(getRedirectUri(authInterface))
// .build(), cache); // .build(), cache);
// break; // break;
// case WEIBO: // case WEIBO:
// List<String> scopes = new ArrayList<>(); // List<String> scopes = new ArrayList<>();
// scopes.add("all"); // scopes.add("all");
// authRequest = new AuthWeiboRequest(AuthConfig.builder() // authRequest = new AuthWeiboRequest(AuthConfig.builder()
// .clientId("") // .clientId("")
// .clientSecret("") // .clientSecret("")
// .redirectUri(getRedirectUri(authInterface)) // .redirectUri(getRedirectUri(authInterface))
// .scopes(scopes) // .scopes(scopes)
// .build(), cache); // .build(), cache);
// break; // break;
// case "wechat_open": // case "wechat_open":
// authRequest = new AuthWeChatOpenRequest(AuthConfig.builder() // authRequest = new AuthWeChatOpenRequest(AuthConfig.builder()
// .clientId("") // .clientId("")
// .clientSecret("") // .clientSecret("")
// .redirectUri("https://z171l91606.51mypc.cn/callback/wechat") // .redirectUri("https://z171l91606.51mypc.cn/callback/wechat")
// .build()); // .build());
// break; // break;
// case "wechat_mp": // case "wechat_mp":
// authRequest = new AuthWeChatMpRequest(AuthConfig.builder() // authRequest = new AuthWeChatMpRequest(AuthConfig.builder()
// .clientId("") // .clientId("")
// .clientSecret("") // .clientSecret("")
// .redirectUri("") // .redirectUri("")
// .build()); // .build());
// break; // break;
default: default:
break; break;
} }
@ -231,9 +231,9 @@ public class ConnectUtil {
return authRequest; return authRequest;
} }
// \b 是单词边界(连着的两个(字母字符 非字母字符) 之间的逻辑上的间隔), //\b 是单词边界(连着的两个(字母字符 非字母字符) 之间的逻辑上的间隔),
// 字符串在编译时会被转码一次,所以是 "\\b" //字符串在编译时会被转码一次,所以是 "\\b"
// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔) //\B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
+ "|windows (phone|ce)|blackberry" + "|windows (phone|ce)|blackberry"
+ "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" + "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
@ -257,7 +257,7 @@ public class ConnectUtil {
if (null == userAgent) { if (null == userAgent) {
userAgent = ""; userAgent = "";
} }
// 匹配 //匹配
Matcher matcherPhone = phonePat.matcher(userAgent); Matcher matcherPhone = phonePat.matcher(userAgent);
Matcher matcherTable = tablePat.matcher(userAgent); Matcher matcherTable = tablePat.matcher(userAgent);
if (matcherPhone.find() || matcherTable.find()) { if (matcherPhone.find() || matcherTable.find()) {

View File

@ -48,7 +48,7 @@ public class IpUtils {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
// 对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割 //对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) { if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) { if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(",")); ip = ip.substring(0, ip.indexOf(","));

View File

@ -80,11 +80,11 @@ public class DistributionOrderServiceImpl extends ServiceImpl<DistributionOrderM
distributionOrder.setDistributionName(distribution.getMemberName()); distributionOrder.setDistributionName(distribution.getMemberName());
//设置结算天数(解冻日期) //设置结算天数(解冻日期)
// Setting setting = settingService.get(SettingEnum.DISTRIBUTION_SETTING.name()); // Setting setting = settingService.get(SettingEnum.DISTRIBUTION_SETTING.name());
// DistributionSetting distributionSetting = JSONUtil.toBean(setting.getSettingValue(), DistributionSetting.class); // DistributionSetting distributionSetting = JSONUtil.toBean(setting.getSettingValue(), DistributionSetting.class);
DateTime dateTime = new DateTime(); DateTime dateTime = new DateTime();
//默认解冻1天 //默认解冻1天
// dateTime.offsetNew(DateField.DAY_OF_MONTH,distributionSetting.getCashDay()); // dateTime.offsetNew(DateField.DAY_OF_MONTH,distributionSetting.getCashDay());
dateTime.offsetNew(DateField.DAY_OF_MONTH,1); dateTime.offsetNew(DateField.DAY_OF_MONTH,1);
distributionOrder.setSettleCycle(dateTime); distributionOrder.setSettleCycle(dateTime);
this.save(distributionOrder); this.save(distributionOrder);

View File

@ -186,8 +186,8 @@ public class AliFileManagerPlugin implements FileManagerPlugin {
@Override @Override
public String getUrl(String url, Integer width, Integer height) { public String getUrl(String url, Integer width, Integer height) {
// 缩略图全路径 //缩略图全路径
// 返回缩略图全路径 //返回缩略图全路径
return url + "?x-oss-process=style/" + width + "X" + height; return url + "?x-oss-process=style/" + width + "X" + height;
} }
} }

View File

@ -51,12 +51,12 @@ public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> i
return (List<CategoryVO>) cache.get(CachePrefix.CATEGORY.getPrefix() + "tree"); return (List<CategoryVO>) cache.get(CachePrefix.CATEGORY.getPrefix() + "tree");
} }
// 获取全部分类 //获取全部分类
LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Category::getDeleteFlag, false); queryWrapper.eq(Category::getDeleteFlag, false);
List<Category> list = this.list(queryWrapper); List<Category> list = this.list(queryWrapper);
// 构造分类树 //构造分类树
List<CategoryVO> categoryVOList = new ArrayList<>(); List<CategoryVO> categoryVOList = new ArrayList<>();
for (Category category : list) { for (Category category : list) {
if (category.getParentId().equals("0")) { if (category.getParentId().equals("0")) {
@ -112,10 +112,10 @@ public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> i
@Override @Override
public List<CategoryVO> listAllChildrenDB() { public List<CategoryVO> listAllChildrenDB() {
// 获取全部分类 //获取全部分类
List<Category> list = this.list(); List<Category> list = this.list();
// 构造分类树 //构造分类树
List<CategoryVO> categoryVOList = new ArrayList<>(); List<CategoryVO> categoryVOList = new ArrayList<>();
for (Category category : list) { for (Category category : list) {
if (category.getParentId().equals("0")) { if (category.getParentId().equals("0")) {
@ -197,7 +197,7 @@ public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> i
@Override @Override
public void updateCategoryStatus(String categoryId, Boolean enableOperations) { public void updateCategoryStatus(String categoryId, Boolean enableOperations) {
// 禁用子分类 //禁用子分类
CategoryVO categoryVO = new CategoryVO(this.getById(categoryId)); CategoryVO categoryVO = new CategoryVO(this.getById(categoryId));
List<String> ids = new ArrayList<>(); List<String> ids = new ArrayList<>();
ids.add(categoryVO.getId()); ids.add(categoryVO.getId());

View File

@ -45,10 +45,10 @@ public class GoodsGalleryServiceImpl extends ServiceImpl<GoodsGalleryMapper, Goo
//确定好图片选择器后进行处理 //确定好图片选择器后进行处理
int i = 0; int i = 0;
for (String origin : goodsGalleryList) { for (String origin : goodsGalleryList) {
// 获取带所有缩略的相册 //获取带所有缩略的相册
GoodsGallery galley = this.getGoodsGallery(origin); GoodsGallery galley = this.getGoodsGallery(origin);
galley.setGoodsId(goodsId); galley.setGoodsId(goodsId);
// 默认第一个为默认图片 //默认第一个为默认图片
galley.setIsDefault(i == 0 ? 1 : 0); galley.setIsDefault(i == 0 ? 1 : 0);
i++; i++;
this.baseMapper.insert(galley); this.baseMapper.insert(galley);

View File

@ -105,17 +105,17 @@ public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements
Goods goods = new Goods(goodsOperationDTO); Goods goods = new Goods(goodsOperationDTO);
//检查商品 //检查商品
this.checkGoods(goods); this.checkGoods(goods);
// 向goods加入图片 //向goods加入图片
this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0), goods); this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0), goods);
//添加商品 //添加商品
this.save(goods); this.save(goods);
// 添加商品参数 //添加商品参数
if (goodsOperationDTO.getGoodsParamsList() != null && !goodsOperationDTO.getGoodsParamsList().isEmpty()) { if (goodsOperationDTO.getGoodsParamsList() != null && !goodsOperationDTO.getGoodsParamsList().isEmpty()) {
this.goodsParamsService.addParams(goodsOperationDTO.getGoodsParamsList(), goods.getId()); this.goodsParamsService.addParams(goodsOperationDTO.getGoodsParamsList(), goods.getId());
} }
// 添加商品sku信息 //添加商品sku信息
this.goodsSkuService.add(goodsOperationDTO.getSkuList(), goods); this.goodsSkuService.add(goodsOperationDTO.getSkuList(), goods);
// 添加相册 //添加相册
if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) { if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) {
this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId()); this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId());
} }
@ -128,17 +128,17 @@ public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements
goods.setId(goodsId); goods.setId(goodsId);
//检查商品信息 //检查商品信息
this.checkGoods(goods); this.checkGoods(goods);
// 向goods加入图片 //向goods加入图片
this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0), goods); this.setGoodsGalleryParam(goodsOperationDTO.getGoodsGalleryList().get(0), goods);
//修改商品 //修改商品
this.updateById(goods); this.updateById(goods);
// 添加商品参数 //添加商品参数
if (goodsOperationDTO.getGoodsParamsList() != null && !goodsOperationDTO.getGoodsParamsList().isEmpty()) { if (goodsOperationDTO.getGoodsParamsList() != null && !goodsOperationDTO.getGoodsParamsList().isEmpty()) {
this.goodsParamsService.addParams(goodsOperationDTO.getGoodsParamsList(), goods.getId()); this.goodsParamsService.addParams(goodsOperationDTO.getGoodsParamsList(), goods.getId());
} }
//修改商品sku信息 //修改商品sku信息
this.goodsSkuService.update(goodsOperationDTO.getSkuList(), goods, goodsOperationDTO.getRegeneratorSkuFlag()); this.goodsSkuService.update(goodsOperationDTO.getSkuList(), goods, goodsOperationDTO.getRegeneratorSkuFlag());
// 添加相册 //添加相册
if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) { if (goodsOperationDTO.getGoodsGalleryList() != null && !goodsOperationDTO.getGoodsGalleryList().isEmpty()) {
this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId()); this.goodsGalleryService.add(goodsOperationDTO.getGoodsGalleryList(), goods.getId());
} }
@ -165,7 +165,7 @@ public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements
images.add(goodsGallery.getOriginal()); images.add(goodsGallery.getOriginal());
} }
goodsVO.setGoodsGalleryList(images); goodsVO.setGoodsGalleryList(images);
// 商品sku赋值 //商品sku赋值
List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsId); List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsId);
if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) { if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
goodsVO.setSkuList(goodsListByGoodsId); goodsVO.setSkuList(goodsListByGoodsId);
@ -300,9 +300,9 @@ public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements
LambdaQueryWrapper<MemberEvaluation> goodEvaluationQueryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<MemberEvaluation> goodEvaluationQueryWrapper = new LambdaQueryWrapper<>();
goodEvaluationQueryWrapper.eq(MemberEvaluation::getId, goodsId); goodEvaluationQueryWrapper.eq(MemberEvaluation::getId, goodsId);
goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name()); goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name());
// 好评数量 //好评数量
int highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper); int highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper);
// 好评率 //好评率
double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goods.getCommentNum().doubleValue(), 2), 100); double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goods.getCommentNum().doubleValue(), 2), 100);
goods.setGrade(grade); goods.setGrade(grade);
this.updateById(goods); this.updateById(goods);
@ -351,13 +351,13 @@ public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements
if (goods.getId() != null) { if (goods.getId() != null) {
this.checkExist(goods.getId()); this.checkExist(goods.getId());
} else { } else {
// 评论次数 //评论次数
goods.setCommentNum(0); goods.setCommentNum(0);
// 购买次数 //购买次数
goods.setBuyCount(0); goods.setBuyCount(0);
// 购买次数 //购买次数
goods.setQuantity(0); goods.setQuantity(0);
// 商品评分 //商品评分
goods.setGrade(100.0); goods.setGrade(100.0);
} }

View File

@ -88,12 +88,12 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
@Override @Override
public void add(List<Map<String, Object>> skuList, Goods goods) { public void add(List<Map<String, Object>> skuList, Goods goods) {
// 检查是否需要生成索引 //检查是否需要生成索引
boolean needIndex = checkNeedIndex(goods); boolean needIndex = checkNeedIndex(goods);
List<GoodsSku> newSkuList; List<GoodsSku> newSkuList;
// 如果有规格 //如果有规格
if (skuList != null && !skuList.isEmpty()) { if (skuList != null && !skuList.isEmpty()) {
// 添加商品sku //添加商品sku
newSkuList = this.addGoodsSku(skuList, goods, needIndex); newSkuList = this.addGoodsSku(skuList, goods, needIndex);
} else { } else {
throw new ServiceException("规格必须要有一个!"); throw new ServiceException("规格必须要有一个!");
@ -118,9 +118,9 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
@Override @Override
public void update(List<Map<String, Object>> skuList, Goods goods, Boolean regeneratorSkuFlag) { public void update(List<Map<String, Object>> skuList, Goods goods, Boolean regeneratorSkuFlag) {
// 检查是否需要生成索引 //检查是否需要生成索引
boolean needIndex = checkNeedIndex(goods); boolean needIndex = checkNeedIndex(goods);
// 是否存在规格 //是否存在规格
if (skuList == null || skuList.isEmpty()) { if (skuList == null || skuList.isEmpty()) {
throw new ServiceException("规格必须要有一个!"); throw new ServiceException("规格必须要有一个!");
} }
@ -138,7 +138,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
this.removeByIds(oldSkuIds); this.removeByIds(oldSkuIds);
//删除sku相册 //删除sku相册
goodsGalleryService.removeByIds(oldSkuIds); goodsGalleryService.removeByIds(oldSkuIds);
// 添加商品sku //添加商品sku
newSkuList = this.addGoodsSku(skuList, goods, needIndex); newSkuList = this.addGoodsSku(skuList, goods, needIndex);
//发送mq消息 //发送mq消息
@ -216,7 +216,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
throw new ServiceException("商品已下架"); throw new ServiceException("商品已下架");
} }
} }
// 获取当前商品的索引信息 //获取当前商品的索引信息
EsGoodsIndex goodsIndex = goodsIndexService.findById(skuId); EsGoodsIndex goodsIndex = goodsIndexService.findById(skuId);
if (goodsIndex == null) { if (goodsIndex == null) {
goodsIndex = new EsGoodsIndex(goodsSku); goodsIndex = new EsGoodsIndex(goodsSku);
@ -225,7 +225,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
//商品规格 //商品规格
GoodsSkuVO goodsSkuDetail = this.getGoodsSkuVO(goodsSku); GoodsSkuVO goodsSkuDetail = this.getGoodsSkuVO(goodsSku);
// 设置当前商品的促销价格 //设置当前商品的促销价格
if (goodsIndex.getPromotionMap() != null && !goodsIndex.getPromotionMap().isEmpty() && goodsIndex.getPromotionPrice() != null) { if (goodsIndex.getPromotionMap() != null && !goodsIndex.getPromotionMap().isEmpty() && goodsIndex.getPromotionPrice() != null) {
goodsSkuDetail.setPromotionPrice(goodsIndex.getPromotionPrice()); goodsSkuDetail.setPromotionPrice(goodsIndex.getPromotionPrice());
} }
@ -426,13 +426,13 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
goodEvaluationQueryWrapper.eq(MemberEvaluation::getSkuId, goodsSku.getId()); goodEvaluationQueryWrapper.eq(MemberEvaluation::getSkuId, goodsSku.getId());
goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name()); goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name());
// 好评数量 //好评数量
int highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper); int highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper);
// 更新商品评价数量 //更新商品评价数量
goodsSku.setCommentNum(goodsSku.getCommentNum() != null ? goodsSku.getCommentNum() + 1 : 1); goodsSku.setCommentNum(goodsSku.getCommentNum() != null ? goodsSku.getCommentNum() + 1 : 1);
// 好评率 //好评率
double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goodsSku.getCommentNum().doubleValue(), 2), 100); double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goodsSku.getCommentNum().doubleValue(), 2), 100);
goodsSku.setGrade(grade); goodsSku.setGrade(grade);
//修改规格 //修改规格

View File

@ -59,7 +59,7 @@ public class MemberNoticeSenterServiceImpl extends ServiceImpl<MemberNoticeSente
} else { } else {
return true; return true;
} }
} // 否则是全部会员发送 } //否则是全部会员发送
else { else {
List<Member> members = memberService.list(); List<Member> members = memberService.list();
MemberNotice memberNotice; MemberNotice memberNotice;

View File

@ -180,7 +180,7 @@ public class WechatMPMessageServiceImpl extends ServiceImpl<WechatMPMessageMappe
class WechatMPMessageData { class WechatMPMessageData {
/** /**
* 场景描述 // 等于本服务器模版名称 * 场景描述 // 等于本服务器模版名称
*/ */
String sceneDesc; String sceneDesc;

View File

@ -100,7 +100,7 @@ public class WechatMessageUtil {
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token; String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
// 用户id //用户id
map.put("touser", connect.getUnionId()); map.put("touser", connect.getUnionId());
//模版id //模版id
map.put("template_id", wechatMessage.getCode()); map.put("template_id", wechatMessage.getCode());
@ -157,7 +157,7 @@ public class WechatMessageUtil {
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token; String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
// 用户id //用户id
map.put("touser", connect.getUnionId()); map.put("touser", connect.getUnionId());
//模版id //模版id
map.put("template_id", wechatMPMessage.getCode()); map.put("template_id", wechatMPMessage.getCode());

View File

@ -60,26 +60,26 @@ public class WechatMpCodeUtil {
params.put("path", path); params.put("path", path);
params.put("width", "280"); params.put("width", "280");
// ======================================================================// //======================================================================//
// 执行URL Post调用 //执行URL Post调用
// ======================================================================// //======================================================================//
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(CREATE_QR_CODE + accessToken); HttpPost httpPost = new HttpPost(CREATE_QR_CODE + accessToken);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
// 必须是json模式的 post //必须是json模式的 post
String body = JSON.toJSONString(params); String body = JSON.toJSONString(params);
StringEntity entity = new StringEntity(body); StringEntity entity = new StringEntity(body);
entity.setContentType("image/png"); entity.setContentType("image/png");
httpPost.setEntity(entity); httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity(); HttpEntity httpEntity = httpResponse.getEntity();
// ======================================================================// //======================================================================//
// 处理HTTP返回结果 //处理HTTP返回结果
// ======================================================================// //======================================================================//
InputStream contentStream = httpEntity.getContent(); InputStream contentStream = httpEntity.getContent();
byte[] bytes = toByteArray(contentStream); byte[] bytes = toByteArray(contentStream);
contentStream.read(bytes); contentStream.read(bytes);
// 返回内容 //返回内容
return Base64.getEncoder().encodeToString(bytes); return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) { } catch (Exception e) {
log.error("生成二维码错误:", e); log.error("生成二维码错误:", e);
@ -117,26 +117,26 @@ public class WechatMpCodeUtil {
params.put("scene", shortLink.getId()); params.put("scene", shortLink.getId());
params.put("width", "280"); params.put("width", "280");
// ======================================================================// //======================================================================//
// 执行URL Post调用 //执行URL Post调用
// ======================================================================// //======================================================================//
CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(UN_LIMIT_API + accessToken); HttpPost httpPost = new HttpPost(UN_LIMIT_API + accessToken);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
// 必须是json模式的 post //必须是json模式的 post
String body = JSON.toJSONString(params); String body = JSON.toJSONString(params);
StringEntity entity = new StringEntity(body); StringEntity entity = new StringEntity(body);
entity.setContentType("image/png"); entity.setContentType("image/png");
httpPost.setEntity(entity); httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity(); HttpEntity httpEntity = httpResponse.getEntity();
// ======================================================================// //======================================================================//
// 处理HTTP返回结果 //处理HTTP返回结果
// ======================================================================// //======================================================================//
InputStream contentStream = httpEntity.getContent(); InputStream contentStream = httpEntity.getContent();
byte[] bytes = toByteArray(contentStream); byte[] bytes = toByteArray(contentStream);
contentStream.read(bytes); contentStream.read(bytes);
// 返回内容 //返回内容
return Base64.getEncoder().encodeToString(bytes); return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) { } catch (Exception e) {
log.error("生成二维码错误:", e); log.error("生成二维码错误:", e);

View File

@ -34,7 +34,7 @@ public class CartPriceRender implements CartRenderStep {
@Override @Override
public void render(TradeDTO tradeDTO) { public void render(TradeDTO tradeDTO) {
// 构造cartVO //构造cartVO
this.buildCart(tradeDTO); this.buildCart(tradeDTO);
this.buildCartPrice(tradeDTO); this.buildCartPrice(tradeDTO);
this.buildTradePrice(tradeDTO); this.buildTradePrice(tradeDTO);
@ -70,11 +70,11 @@ public class CartPriceRender implements CartRenderStep {
//购物车列表 //购物车列表
List<CartVO> cartVOS = tradeDTO.getCartList(); List<CartVO> cartVOS = tradeDTO.getCartList();
// key store id //key store id
// value 商品列表 //value 商品列表
Map<String, List<CartSkuVO>> map = new HashMap<>(); Map<String, List<CartSkuVO>> map = new HashMap<>();
for (CartSkuVO cartSkuVO : cartSkuVOList) { for (CartSkuVO cartSkuVO : cartSkuVOList) {
// 如果存在商家id //如果存在商家id
if (map.containsKey(cartSkuVO.getGoodsSku().getStoreId())) { if (map.containsKey(cartSkuVO.getGoodsSku().getStoreId())) {
List<CartSkuVO> list = map.get(cartSkuVO.getGoodsSku().getStoreId()); List<CartSkuVO> list = map.get(cartSkuVO.getGoodsSku().getStoreId());
list.add(cartSkuVO); list.add(cartSkuVO);
@ -94,15 +94,15 @@ public class CartPriceRender implements CartRenderStep {
for (CartSkuVO cartSkuVO : cartSkuVOS) { for (CartSkuVO cartSkuVO : cartSkuVOS) {
if (Boolean.TRUE.equals(cartSkuVO.getChecked())) { if (Boolean.TRUE.equals(cartSkuVO.getChecked())) {
PriceDetailDTO priceDetailDTO = cartSkuVO.getPriceDetailDTO(); PriceDetailDTO priceDetailDTO = cartSkuVO.getPriceDetailDTO();
// 流水金额(入账 出帐金额) = goodsPrice + freight - discountPrice - couponPrice //流水金额(入账 出帐金额) = goodsPrice + freight - discountPrice - couponPrice
double flowPrice = CurrencyUtil.sub(CurrencyUtil.add(priceDetailDTO.getGoodsPrice(), priceDetailDTO.getFreightPrice()), CurrencyUtil.add(priceDetailDTO.getDiscountPrice(), priceDetailDTO.getCouponPrice() != null ? priceDetailDTO.getCouponPrice() : 0)); double flowPrice = CurrencyUtil.sub(CurrencyUtil.add(priceDetailDTO.getGoodsPrice(), priceDetailDTO.getFreightPrice()), CurrencyUtil.add(priceDetailDTO.getDiscountPrice(), priceDetailDTO.getCouponPrice() != null ? priceDetailDTO.getCouponPrice() : 0));
priceDetailDTO.setFlowPrice(flowPrice); priceDetailDTO.setFlowPrice(flowPrice);
// 最终结算金额 = flowPrice - platFormCommission - distributionCommission //最终结算金额 = flowPrice - platFormCommission - distributionCommission
double billPrice = CurrencyUtil.sub(CurrencyUtil.sub(flowPrice, priceDetailDTO.getPlatFormCommission()), priceDetailDTO.getDistributionCommission()); double billPrice = CurrencyUtil.sub(CurrencyUtil.sub(flowPrice, priceDetailDTO.getPlatFormCommission()), priceDetailDTO.getDistributionCommission());
priceDetailDTO.setBillPrice(billPrice); priceDetailDTO.setBillPrice(billPrice);
// 平台佣金 //平台佣金
String categoryId = cartSkuVO.getGoodsSku().getCategoryPath().substring( String categoryId = cartSkuVO.getGoodsSku().getCategoryPath().substring(
cartSkuVO.getGoodsSku().getCategoryPath().lastIndexOf(",") + 1 cartSkuVO.getGoodsSku().getCategoryPath().lastIndexOf(",") + 1
); );

View File

@ -70,7 +70,7 @@ public class CheckDataRender implements CartRenderStep {
cartSkuVO.setErrorMessage("商品信息发生变化,已失效"); cartSkuVO.setErrorMessage("商品信息发生变化,已失效");
continue; continue;
} }
// 商品上架状态判定 //商品上架状态判定
if (!GoodsAuthEnum.PASS.name().equals(dataSku.getIsAuth()) || !GoodsStatusEnum.UPPER.name().equals(dataSku.getMarketEnable())) { if (!GoodsAuthEnum.PASS.name().equals(dataSku.getIsAuth()) || !GoodsStatusEnum.UPPER.name().equals(dataSku.getMarketEnable())) {
//设置购物车未选中 //设置购物车未选中
cartSkuVO.setChecked(false); cartSkuVO.setChecked(false);
@ -80,7 +80,7 @@ public class CheckDataRender implements CartRenderStep {
cartSkuVO.setErrorMessage("商品已下架"); cartSkuVO.setErrorMessage("商品已下架");
continue; continue;
} }
// 商品库存判定 //商品库存判定
if (dataSku.getQuantity() < cartSkuVO.getNum()) { if (dataSku.getQuantity() < cartSkuVO.getNum()) {
//设置购物车未选中 //设置购物车未选中
cartSkuVO.setChecked(false); cartSkuVO.setChecked(false);
@ -98,10 +98,10 @@ public class CheckDataRender implements CartRenderStep {
* @param tradeDTO * @param tradeDTO
*/ */
private void groupStore(TradeDTO tradeDTO) { private void groupStore(TradeDTO tradeDTO) {
// 渲染的购物车 //渲染的购物车
List<CartVO> cartList = new ArrayList<>(); List<CartVO> cartList = new ArrayList<>();
// 根据店铺分组 //根据店铺分组
Map<String, List<CartSkuVO>> storeCollect = tradeDTO.getSkuList().parallelStream().collect(Collectors.groupingBy(CartSkuVO::getStoreId)); Map<String, List<CartSkuVO>> storeCollect = tradeDTO.getSkuList().parallelStream().collect(Collectors.groupingBy(CartSkuVO::getStoreId));
for (Map.Entry<String, List<CartSkuVO>> storeCart : storeCollect.entrySet()) { for (Map.Entry<String, List<CartSkuVO>> storeCart : storeCollect.entrySet()) {
if (!storeCart.getValue().isEmpty()) { if (!storeCart.getValue().isEmpty()) {

View File

@ -25,7 +25,7 @@ public class CouponRender implements CartRenderStep {
public void render(TradeDTO tradeDTO) { public void render(TradeDTO tradeDTO) {
//主要渲染各个优惠的价格 //主要渲染各个优惠的价格
// this.renderCoupon(tradeDTO); //this.renderCoupon(tradeDTO);
} }

View File

@ -32,17 +32,17 @@ public class FullDiscountRender implements CartRenderStep {
@Override @Override
public void render(TradeDTO tradeDTO) { public void render(TradeDTO tradeDTO) {
// 获取购物车中所有的商品 //获取购物车中所有的商品
List<CartSkuVO> cartSkuList = tradeDTO.getSkuList(); List<CartSkuVO> cartSkuList = tradeDTO.getSkuList();
// 店铺id集合 //店铺id集合
List<String> storeIds = new ArrayList<>(); List<String> storeIds = new ArrayList<>();
// 店铺集合 //店铺集合
List<CartVO> cartList = tradeDTO.getCartList(); List<CartVO> cartList = tradeDTO.getCartList();
// 获取店铺id //获取店铺id
Map<String, List<CartSkuVO>> storeCollect = tradeDTO.getSkuList().parallelStream().collect(Collectors.groupingBy(CartSkuVO::getStoreId)); Map<String, List<CartSkuVO>> storeCollect = tradeDTO.getSkuList().parallelStream().collect(Collectors.groupingBy(CartSkuVO::getStoreId));
for (Map.Entry<String, List<CartSkuVO>> storeCart : storeCollect.entrySet()) { for (Map.Entry<String, List<CartSkuVO>> storeCart : storeCollect.entrySet()) {
if (!storeCart.getValue().isEmpty()) { if (!storeCart.getValue().isEmpty()) {
@ -50,7 +50,7 @@ public class FullDiscountRender implements CartRenderStep {
} }
} }
// 获取当前店铺进行到满减活动 //获取当前店铺进行到满减活动
List<FullDiscountVO> fullDiscounts = fullDiscountService.currentPromotion(storeIds); List<FullDiscountVO> fullDiscounts = fullDiscountService.currentPromotion(storeIds);
//循环满减信息 //循环满减信息
for (FullDiscountVO fullDiscount : fullDiscounts) { for (FullDiscountVO fullDiscount : fullDiscounts) {
@ -63,7 +63,7 @@ public class FullDiscountRender implements CartRenderStep {
//写入满减活动 //写入满减活动
cart.setFullDiscount(fullDiscount); cart.setFullDiscount(fullDiscount);
List<String> skuIds; List<String> skuIds;
// 参与活动的sku判定 //参与活动的sku判定
if (fullDiscount.getNumber() != -1) { if (fullDiscount.getNumber() != -1) {
skuIds = initFullDiscountGoods(fullDiscount, cartSkuList); skuIds = initFullDiscountGoods(fullDiscount, cartSkuList);
} else { } else {

View File

@ -118,7 +118,7 @@ public class SkuFreightRender implements CartRenderStep {
return finalFreight; return finalFreight;
} }
Double continuedCount = count - template.getFirstCompany(); Double continuedCount = count - template.getFirstCompany();
// 计算续重价格 //计算续重价格
return CurrencyUtil.add(finalFreight, return CurrencyUtil.add(finalFreight,
CurrencyUtil.mul(NumberUtil.parseInt(String.valueOf((continuedCount / template.getContinuedCompany()))), template.getContinuedPrice())); CurrencyUtil.mul(NumberUtil.parseInt(String.valueOf((continuedCount / template.getContinuedCompany()))), template.getContinuedPrice()));
} catch (Exception e) { } catch (Exception e) {

View File

@ -70,7 +70,7 @@ public class SkuPromotionRender implements CartRenderStep {
*/ */
private void renderSkuPromotion(TradeDTO tradeDTO) { private void renderSkuPromotion(TradeDTO tradeDTO) {
// 渲染促销价格 //渲染促销价格
this.renderPromotionPrice(tradeDTO); this.renderPromotionPrice(tradeDTO);
//拼团和积分购买需要特殊处理这里优先特殊处理 //拼团和积分购买需要特殊处理这里优先特殊处理
@ -110,12 +110,12 @@ public class SkuPromotionRender implements CartRenderStep {
for (CartVO cartVO : cartList) { for (CartVO cartVO : cartList) {
if (Boolean.TRUE.equals(cartVO.getChecked())) { if (Boolean.TRUE.equals(cartVO.getChecked())) {
for (CartSkuVO cartSkuVO : cartVO.getSkuList()) { for (CartSkuVO cartSkuVO : cartVO.getSkuList()) {
// 检查当前购物车商品是否有效且为选中 //检查当前购物车商品是否有效且为选中
if (Boolean.TRUE.equals(cartSkuVO.getChecked()) && Boolean.FALSE.equals(cartSkuVO.getInvalid())) { if (Boolean.TRUE.equals(cartSkuVO.getChecked()) && Boolean.FALSE.equals(cartSkuVO.getInvalid())) {
PromotionPriceParamDTO param = new PromotionPriceParamDTO(); PromotionPriceParamDTO param = new PromotionPriceParamDTO();
param.setSkuId(cartSkuVO.getGoodsSku().getId()); param.setSkuId(cartSkuVO.getGoodsSku().getId());
param.setNum(cartSkuVO.getNum()); param.setNum(cartSkuVO.getNum());
// 是否为拼团商品计算 //是否为拼团商品计算
if (cartSkuVO.getPintuanId() != null) { if (cartSkuVO.getPintuanId() != null) {
param.setPintuanId(cartSkuVO.getPintuanId()); param.setPintuanId(cartSkuVO.getPintuanId());
} }
@ -126,21 +126,21 @@ public class SkuPromotionRender implements CartRenderStep {
} }
//如果包含促销规则 //如果包含促销规则
if (!promotionPriceParamList.isEmpty()) { if (!promotionPriceParamList.isEmpty()) {
// 店铺优惠券集合 //店铺优惠券集合
List<MemberCoupon> memberCoupons = new ArrayList<>(); List<MemberCoupon> memberCoupons = new ArrayList<>();
if (tradeDTO.getStoreCoupons() != null) { if (tradeDTO.getStoreCoupons() != null) {
memberCoupons.addAll(tradeDTO.getStoreCoupons().values().parallelStream().map(MemberCouponDTO::getMemberCoupon).collect(Collectors.toList())); memberCoupons.addAll(tradeDTO.getStoreCoupons().values().parallelStream().map(MemberCouponDTO::getMemberCoupon).collect(Collectors.toList()));
} }
// 平台优惠券 //平台优惠券
if (tradeDTO.getPlatformCoupon() != null && tradeDTO.getPlatformCoupon().getMemberCoupon() != null) { if (tradeDTO.getPlatformCoupon() != null && tradeDTO.getPlatformCoupon().getMemberCoupon() != null) {
memberCoupons.add(tradeDTO.getPlatformCoupon().getMemberCoupon()); memberCoupons.add(tradeDTO.getPlatformCoupon().getMemberCoupon());
} }
// 检查优惠券集合中是否存在过期优惠券 //检查优惠券集合中是否存在过期优惠券
this.checkMemberCoupons(memberCoupons); this.checkMemberCoupons(memberCoupons);
// 调用价格计算模块返回价格计算结果 //调用价格计算模块返回价格计算结果
PromotionPriceDTO promotionPrice = promotionPriceService.calculationPromotionPrice(promotionPriceParamList, memberCoupons); PromotionPriceDTO promotionPrice = promotionPriceService.calculationPromotionPrice(promotionPriceParamList, memberCoupons);
// 分配计算后的促销 // 分配计算后的促销
this.distributionPromotionPrice(tradeDTO, promotionPrice); this.distributionPromotionPrice(tradeDTO, promotionPrice);
} }
} }
@ -159,11 +159,11 @@ public class SkuPromotionRender implements CartRenderStep {
private void distributionPromotionPrice(TradeDTO tradeDTO, PromotionPriceDTO promotionPrice) { private void distributionPromotionPrice(TradeDTO tradeDTO, PromotionPriceDTO promotionPrice) {
for (CartVO cartVO : tradeDTO.getCartList()) { for (CartVO cartVO : tradeDTO.getCartList()) {
// 根据店铺分配店铺价格计算结果 //根据店铺分配店铺价格计算结果
Optional<StorePromotionPriceDTO> storePromotionPriceDTOOptional = promotionPrice.getStorePromotionPriceList().parallelStream().filter(i -> i.getStoreId().equals(cartVO.getStoreId())).findAny(); Optional<StorePromotionPriceDTO> storePromotionPriceDTOOptional = promotionPrice.getStorePromotionPriceList().parallelStream().filter(i -> i.getStoreId().equals(cartVO.getStoreId())).findAny();
if (storePromotionPriceDTOOptional.isPresent()) { if (storePromotionPriceDTOOptional.isPresent()) {
StorePromotionPriceDTO storePromotionPriceDTO = storePromotionPriceDTOOptional.get(); StorePromotionPriceDTO storePromotionPriceDTO = storePromotionPriceDTOOptional.get();
// 根据商品分配商品结果计算结果 //根据商品分配商品结果计算结果
this.distributionSkuPromotionPrice(cartVO.getSkuList(), storePromotionPriceDTO); this.distributionSkuPromotionPrice(cartVO.getSkuList(), storePromotionPriceDTO);
PriceDetailDTO sSpd = new PriceDetailDTO(); PriceDetailDTO sSpd = new PriceDetailDTO();
@ -183,7 +183,7 @@ public class SkuPromotionRender implements CartRenderStep {
} }
} }
// 根据整个购物车分配价格计算结果 //根据整个购物车分配价格计算结果
PriceDetailDTO priceDetailDTO = new PriceDetailDTO(); PriceDetailDTO priceDetailDTO = new PriceDetailDTO();
priceDetailDTO.setDiscountPrice(promotionPrice.getTotalDiscountPrice()); priceDetailDTO.setDiscountPrice(promotionPrice.getTotalDiscountPrice());
@ -203,7 +203,7 @@ public class SkuPromotionRender implements CartRenderStep {
private void distributionSkuPromotionPrice(List<CartSkuVO> skuList, StorePromotionPriceDTO storePromotionPriceDTO) { private void distributionSkuPromotionPrice(List<CartSkuVO> skuList, StorePromotionPriceDTO storePromotionPriceDTO) {
if (storePromotionPriceDTO != null) { if (storePromotionPriceDTO != null) {
for (CartSkuVO cartSkuVO : skuList) { for (CartSkuVO cartSkuVO : skuList) {
// 获取当前购物车商品的商品计算结果 //获取当前购物车商品的商品计算结果
List<GoodsSkuPromotionPriceDTO> collect = storePromotionPriceDTO.getGoodsSkuPromotionPriceList().parallelStream().filter(i -> i.getSkuId().equals(cartSkuVO.getGoodsSku().getId())).collect(Collectors.toList()); List<GoodsSkuPromotionPriceDTO> collect = storePromotionPriceDTO.getGoodsSkuPromotionPriceList().parallelStream().filter(i -> i.getSkuId().equals(cartSkuVO.getGoodsSku().getId())).collect(Collectors.toList());
if (!collect.isEmpty()) { if (!collect.isEmpty()) {
GoodsSkuPromotionPriceDTO goodsSkuPromotionPriceDTO = collect.get(0); GoodsSkuPromotionPriceDTO goodsSkuPromotionPriceDTO = collect.get(0);
@ -235,11 +235,11 @@ public class SkuPromotionRender implements CartRenderStep {
private void renderPintuan(List<CartSkuVO> cartSkuList) { private void renderPintuan(List<CartSkuVO> cartSkuList) {
for (CartSkuVO cartSku : cartSkuList) { for (CartSkuVO cartSku : cartSkuList) {
PriceDetailDTO priceDetailDTO = cartSku.getPriceDetailDTO(); PriceDetailDTO priceDetailDTO = cartSku.getPriceDetailDTO();
// PromotionGoods promotionGoods = cartSku.getPromotion(); // PromotionGoods promotionGoods = cartSku.getPromotion();
//参与平台则以拼团价处理 //参与平台则以拼团价处理
if (StringUtils.isNotEmpty(cartSku.getPintuanId())) { if (StringUtils.isNotEmpty(cartSku.getPintuanId())) {
// Double discountPrice = CurrencyUtil.sub(cartSku.getGoodsSku().getPrice(), promotionGoods.getPrice()); // Double discountPrice = CurrencyUtil.sub(cartSku.getGoodsSku().getPrice(), promotionGoods.getPrice());
// priceDetailDTO.setDiscountPrice(discountPrice); // priceDetailDTO.setDiscountPrice(discountPrice);
} else { } else {
//否则代表单独购买则以原价购买 //否则代表单独购买则以原价购买
priceDetailDTO.setDiscountPrice(0d); priceDetailDTO.setDiscountPrice(0d);
@ -301,7 +301,7 @@ public class SkuPromotionRender implements CartRenderStep {
private void checkPromotionLimit(TradeDTO tradeDTO) { private void checkPromotionLimit(TradeDTO tradeDTO) {
if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.PINTUAN)) { if (tradeDTO.getCartTypeEnum().equals(CartTypeEnum.PINTUAN)) {
// 如果为拼团订单则获取拼团活动ID //如果为拼团订单则获取拼团活动ID
Optional<String> pintuanId = tradeDTO.getSkuList().get(0).getPromotions().stream().filter(i -> i.getPromotionType().equals(PromotionTypeEnum.PINTUAN.name())).map(PromotionGoods::getPromotionId).findFirst(); Optional<String> pintuanId = tradeDTO.getSkuList().get(0).getPromotions().stream().filter(i -> i.getPromotionType().equals(PromotionTypeEnum.PINTUAN.name())).map(PromotionGoods::getPromotionId).findFirst();
if (pintuanId.isPresent()) { if (pintuanId.isPresent()) {
Pintuan pintuan = pintuanService.getPintuanById(pintuanId.get()); Pintuan pintuan = pintuanService.getPintuanById(pintuanId.get());

View File

@ -145,7 +145,7 @@ public class CartServiceImpl implements CartService {
tradeDTO.setCartTypeEnum(cartTypeEnum); tradeDTO.setCartTypeEnum(cartTypeEnum);
// 如购物车发生更改则重置优惠券 //如购物车发生更改则重置优惠券
tradeDTO.setStoreCoupons(null); tradeDTO.setStoreCoupons(null);
tradeDTO.setPlatformCoupon(null); tradeDTO.setPlatformCoupon(null);
this.resetTradeDTO(tradeDTO); this.resetTradeDTO(tradeDTO);
@ -282,10 +282,10 @@ public class CartServiceImpl implements CartService {
} }
} }
cartSkuVOS.removeAll(deleteVos); cartSkuVOS.removeAll(deleteVos);
// 清除选择的优惠券 //清除选择的优惠券
tradeDTO.setPlatformCoupon(null); tradeDTO.setPlatformCoupon(null);
tradeDTO.setStoreCoupons(null); tradeDTO.setStoreCoupons(null);
// 清除添加过的备注 //清除添加过的备注
tradeDTO.setStoreRemark(null); tradeDTO.setStoreRemark(null);
cache.put(this.getOriginKey(tradeDTO.getCartTypeEnum()), tradeDTO); cache.put(this.getOriginKey(tradeDTO.getCartTypeEnum()), tradeDTO);
} }
@ -339,7 +339,7 @@ public class CartServiceImpl implements CartService {
} }
List<MemberCoupon> allScopeMemberCoupon = memberCouponService.getAllScopeMemberCoupon(tradeDTO.getMemberId(), storeIds); List<MemberCoupon> allScopeMemberCoupon = memberCouponService.getAllScopeMemberCoupon(tradeDTO.getMemberId(), storeIds);
if (allScopeMemberCoupon != null && !allScopeMemberCoupon.isEmpty()) { if (allScopeMemberCoupon != null && !allScopeMemberCoupon.isEmpty()) {
// 过滤满足消费门槛 //过滤满足消费门槛
count += allScopeMemberCoupon.stream().filter(i -> i.getConsumeThreshold() <= totalPrice).count(); count += allScopeMemberCoupon.stream().filter(i -> i.getConsumeThreshold() <= totalPrice).count();
} }
} }
@ -548,10 +548,10 @@ public class CartServiceImpl implements CartService {
private void useCoupon(TradeDTO tradeDTO, MemberCoupon memberCoupon, CartTypeEnum cartTypeEnum) { private void useCoupon(TradeDTO tradeDTO, MemberCoupon memberCoupon, CartTypeEnum cartTypeEnum) {
//如果是平台优惠券 //如果是平台优惠券
if (Boolean.TRUE.equals(memberCoupon.getIsPlatform())) { if (Boolean.TRUE.equals(memberCoupon.getIsPlatform())) {
// 购物车价格 //购物车价格
Double cartPrice = 0d; Double cartPrice = 0d;
for (CartSkuVO cartSkuVO : tradeDTO.getSkuList()) { for (CartSkuVO cartSkuVO : tradeDTO.getSkuList()) {
// 获取商品的促销信息 //获取商品的促销信息
Optional<PromotionGoods> promotionOptional = Optional<PromotionGoods> promotionOptional =
cartSkuVO.getPromotions().parallelStream().filter(promotionGoods -> cartSkuVO.getPromotions().parallelStream().filter(promotionGoods ->
(promotionGoods.getPromotionType().equals(PromotionTypeEnum.PINTUAN.name()) && (promotionGoods.getPromotionType().equals(PromotionTypeEnum.PINTUAN.name()) &&
@ -576,7 +576,7 @@ public class CartServiceImpl implements CartService {
else { else {
//过滤对应店铺购物车 //过滤对应店铺购物车
CartSkuVO cartVO = tradeDTO.getSkuList().stream().filter(i -> i.getStoreId().equals(memberCoupon.getStoreId())).findFirst().orElse(null); CartSkuVO cartVO = tradeDTO.getSkuList().stream().filter(i -> i.getStoreId().equals(memberCoupon.getStoreId())).findFirst().orElse(null);
// 优惠券消费门槛 <= 商品购买时的成交价单品 * 购买数量 //优惠券消费门槛 <= 商品购买时的成交价单品 * 购买数量
if (cartVO != null && memberCoupon.getConsumeThreshold() <= CurrencyUtil.mul(cartVO.getPurchasePrice(), cartVO.getNum())) { if (cartVO != null && memberCoupon.getConsumeThreshold() <= CurrencyUtil.mul(cartVO.getPurchasePrice(), cartVO.getNum())) {
tradeDTO.getStoreCoupons().put(memberCoupon.getStoreId(), new MemberCouponDTO(memberCoupon)); tradeDTO.getStoreCoupons().put(memberCoupon.getStoreId(), new MemberCouponDTO(memberCoupon));
//选择店铺优惠券则将品台优惠券清空 //选择店铺优惠券则将品台优惠券清空
@ -603,15 +603,15 @@ public class CartServiceImpl implements CartService {
cartSkuVOS = tradeDTO.getSkuList(); cartSkuVOS = tradeDTO.getSkuList();
} }
// 当初购物车商品中是否存在符合优惠券条件的商品sku //当初购物车商品中是否存在符合优惠券条件的商品sku
if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_GOODS_CATEGORY.name())) { if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_GOODS_CATEGORY.name())) {
// 分类路径是否包含 //分类路径是否包含
return cartSkuVOS.stream().anyMatch(i -> i.getGoodsSku().getCategoryPath().indexOf("," + memberCoupon.getScopeId() + ",") <= 0); return cartSkuVOS.stream().anyMatch(i -> i.getGoodsSku().getCategoryPath().indexOf("," + memberCoupon.getScopeId() + ",") <= 0);
} else if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_GOODS.name())) { } else if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_GOODS.name())) {
// 范围关联ID是否包含 //范围关联ID是否包含
return cartSkuVOS.stream().anyMatch(i -> memberCoupon.getScopeId().indexOf("," + i.getGoodsSku().getId() + ",") <= 0); return cartSkuVOS.stream().anyMatch(i -> memberCoupon.getScopeId().indexOf("," + i.getGoodsSku().getId() + ",") <= 0);
} else if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_SHOP_CATEGORY.name())) { } else if (memberCoupon.getScopeType().equals(CouponScopeTypeEnum.PORTION_SHOP_CATEGORY.name())) {
// 分类路径是否包含 //分类路径是否包含
return cartSkuVOS.stream().anyMatch(i -> i.getGoodsSku().getStoreCategoryPath().indexOf("," + memberCoupon.getScopeId() + ",") <= 0); return cartSkuVOS.stream().anyMatch(i -> i.getGoodsSku().getStoreCategoryPath().indexOf("," + memberCoupon.getScopeId() + ",") <= 0);
} }
return true; return true;

View File

@ -97,7 +97,7 @@ public class AfterSale extends BaseEntity {
@ApiModelProperty(value = "售后单状态", allowableValues = "APPLY,PASS,REFUSE,BUYER_RETURN,SELLER_RE_DELIVERY,BUYER_CONFIRM,SELLER_CONFIRM,COMPLETE") @ApiModelProperty(value = "售后单状态", allowableValues = "APPLY,PASS,REFUSE,BUYER_RETURN,SELLER_RE_DELIVERY,BUYER_CONFIRM,SELLER_CONFIRM,COMPLETE")
private String serviceStatus; private String serviceStatus;
// 退款信息 //退款信息
/** /**
* @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum * @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum
@ -135,7 +135,7 @@ public class AfterSale extends BaseEntity {
@ApiModelProperty(value = "退款时间") @ApiModelProperty(value = "退款时间")
private Date refundTime; private Date refundTime;
// 买家物流信息 //买家物流信息
@ApiModelProperty(value = "发货单号") @ApiModelProperty(value = "发货单号")
private String mLogisticsNo; private String mLogisticsNo;

View File

@ -101,7 +101,7 @@ public class OrderSearchParams extends PageVO {
wrapper.like("o.sn", keywords); wrapper.like("o.sn", keywords);
wrapper.like("oi.goods_name", keywords); wrapper.like("oi.goods_name", keywords);
} }
// 按卖家查询 //按卖家查询
if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.STORE.name())) { if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.STORE.name())) {
wrapper.eq("o.store_id", UserContext.getCurrentUser().getStoreId()); wrapper.eq("o.store_id", UserContext.getCurrentUser().getStoreId());
} }
@ -109,44 +109,44 @@ public class OrderSearchParams extends PageVO {
&& StringUtils.isNotEmpty(storeId)) { && StringUtils.isNotEmpty(storeId)) {
wrapper.eq("o.store_id", storeId); wrapper.eq("o.store_id", storeId);
} }
// 按买家查询 //按买家查询
if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MEMBER.name())) { if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MEMBER.name())) {
wrapper.eq("o.member_id", UserContext.getCurrentUser().getId()); wrapper.eq("o.member_id", UserContext.getCurrentUser().getId());
} }
// 按照买家查询 //按照买家查询
if (StringUtils.isNotEmpty(memberId)) { if (StringUtils.isNotEmpty(memberId)) {
wrapper.like("o.member_id", memberId); wrapper.like("o.member_id", memberId);
} }
// 按订单编号查询 //按订单编号查询
if (StringUtils.isNotEmpty(orderSn)) { if (StringUtils.isNotEmpty(orderSn)) {
wrapper.like("o.sn", orderSn); wrapper.like("o.sn", orderSn);
} }
// 按时间查询 //按时间查询
if (startDate != null) { if (startDate != null) {
wrapper.ge("o.create_time", startDate); wrapper.ge("o.create_time", startDate);
} }
if (endDate != null) { if (endDate != null) {
wrapper.le("o.create_time", DateUtil.endOfDate(endDate)); wrapper.le("o.create_time", DateUtil.endOfDate(endDate));
} }
// 按购买人用户名 //按购买人用户名
if (StringUtils.isNotEmpty(buyerName)) { if (StringUtils.isNotEmpty(buyerName)) {
wrapper.like("o.member_name", buyerName); wrapper.like("o.member_name", buyerName);
} }
// 按订单类型 //按订单类型
if (StringUtils.isNotEmpty(orderType)) { if (StringUtils.isNotEmpty(orderType)) {
wrapper.eq("o.order_type", orderType) wrapper.eq("o.order_type", orderType)
.or().eq("o.order_promotion_type", orderType); .or().eq("o.order_promotion_type", orderType);
} }
// 按支付方式 //按支付方式
if (StringUtils.isNotEmpty(paymentMethod)) { if (StringUtils.isNotEmpty(paymentMethod)) {
wrapper.eq("o.payment_method", paymentMethod); wrapper.eq("o.payment_method", paymentMethod);
} }
// 按标签查询 //按标签查询
if (StringUtils.isNotEmpty(tag)) { if (StringUtils.isNotEmpty(tag)) {
String orderStatusColumn = "o.order_status"; String orderStatusColumn = "o.order_status";
OrderTagEnum tagEnum = OrderTagEnum.valueOf(tag); OrderTagEnum tagEnum = OrderTagEnum.valueOf(tag);
@ -179,7 +179,7 @@ public class OrderSearchParams extends PageVO {
if (StringUtils.isNotEmpty(shipName)) { if (StringUtils.isNotEmpty(shipName)) {
wrapper.like("o.ship_name", shipName); wrapper.like("o.ship_name", shipName);
} }
// 按商品名称查询 //按商品名称查询
if (StringUtils.isNotEmpty(goodsName)) { if (StringUtils.isNotEmpty(goodsName)) {
wrapper.like("oi.goods_name", goodsName); wrapper.like("oi.goods_name", goodsName);
} }

View File

@ -72,11 +72,11 @@ public class AfterSaleSearchParams extends PageVO {
if (StringUtils.isNotEmpty(orderSn)) { if (StringUtils.isNotEmpty(orderSn)) {
queryWrapper.like("order_sn", orderSn); queryWrapper.like("order_sn", orderSn);
} }
// 按买家查询 //按买家查询
if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MEMBER.name())) { if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MEMBER.name())) {
queryWrapper.eq("member_id", UserContext.getCurrentUser().getId()); queryWrapper.eq("member_id", UserContext.getCurrentUser().getId());
} }
// 按卖家查询 //按卖家查询
if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.STORE.name())) { if (StringUtils.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.STORE.name())) {
queryWrapper.eq("store_id", UserContext.getCurrentUser().getStoreId()); queryWrapper.eq("store_id", UserContext.getCurrentUser().getStoreId());
} }
@ -96,7 +96,7 @@ public class AfterSaleSearchParams extends PageVO {
if (StringUtils.isNotEmpty(goodsName)) { if (StringUtils.isNotEmpty(goodsName)) {
queryWrapper.like("goods_name", goodsName); queryWrapper.like("goods_name", goodsName);
} }
// 按时间查询 //按时间查询
if (startDate != null) { if (startDate != null) {
queryWrapper.ge("create_time", startDate); queryWrapper.ge("create_time", startDate);
} }

View File

@ -151,7 +151,7 @@ public class OrderSimpleVO {
String[] complainStatus = groupComplainStatus.split(","); String[] complainStatus = groupComplainStatus.split(",");
String[] commentStatus = groupCommentStatus.split(","); String[] commentStatus = groupCommentStatus.split(",");
String[] goodsPrice = groupGoodsPrice.split(","); String[] goodsPrice = groupGoodsPrice.split(",");
// String goodsId, String skuId, Integer num, String image, String name, String afterSaleStatus // String goodsId, String skuId, Integer num, String image, String name, String afterSaleStatus
for (int i = 0; i < goodsId.length; i++) { for (int i = 0; i < goodsId.length; i++) {
orderItemVOS.add(new OrderItemVO(orderItemsSn[i], goodsId[i], skuId[i], num[i], image[i], name[i], afterSaleStatus[i], complainStatus[i], commentStatus[i], Double.parseDouble(goodsPrice[i]))); orderItemVOS.add(new OrderItemVO(orderItemsSn[i], goodsId[i], skuId[i], num[i], image[i], name[i], afterSaleStatus[i], complainStatus[i], commentStatus[i], Double.parseDouble(goodsPrice[i])));
} }

View File

@ -440,7 +440,7 @@ public class AfterSaleServiceImpl extends ServiceImpl<AfterSaleMapper, AfterSale
this.checkAfterSaleReturnMoneyParam(afterSaleDTO); this.checkAfterSaleReturnMoneyParam(afterSaleDTO);
break; break;
case RETURN_GOODS: case RETURN_GOODS:
// 是否为有效状态 //是否为有效状态
boolean availableStatus = StrUtil.equalsAny(order.getOrderStatus(), OrderStatusEnum.DELIVERED.name(), OrderStatusEnum.COMPLETED.name()); boolean availableStatus = StrUtil.equalsAny(order.getOrderStatus(), OrderStatusEnum.DELIVERED.name(), OrderStatusEnum.COMPLETED.name());
if (!PayStatusEnum.PAID.name().equals(order.getPayStatus()) && availableStatus) { if (!PayStatusEnum.PAID.name().equals(order.getPayStatus()) && availableStatus) {
throw new ServiceException(ResultCode.AFTER_SALES_BAN); throw new ServiceException(ResultCode.AFTER_SALES_BAN);

View File

@ -155,7 +155,7 @@ public class OrderPriceServiceImpl implements OrderPriceService {
//计算修改后的订单货物金额 //计算修改后的订单货物金额
double flowPrice = CurrencyUtil.mul(order.getFlowPrice(), priceFluctuationRatio); double flowPrice = CurrencyUtil.mul(order.getFlowPrice(), priceFluctuationRatio);
// 记录修改金额 //记录修改金额
priceDetailDTO.setUpdatePrice(CurrencyUtil.sub(priceDetailDTO.getOriginalPrice(), flowPrice)); priceDetailDTO.setUpdatePrice(CurrencyUtil.sub(priceDetailDTO.getOriginalPrice(), flowPrice));
priceDetailDTO.setFlowPrice(flowPrice); priceDetailDTO.setFlowPrice(flowPrice);
@ -163,7 +163,7 @@ public class OrderPriceServiceImpl implements OrderPriceService {
Double platFormCommission = CurrencyUtil.div(CurrencyUtil.mul(flowPrice, categoryService.getById(orderItem.getCategoryId()).getCommissionRate()), 100); Double platFormCommission = CurrencyUtil.div(CurrencyUtil.mul(flowPrice, categoryService.getById(orderItem.getCategoryId()).getCommissionRate()), 100);
priceDetailDTO.setPlatFormCommission(platFormCommission); priceDetailDTO.setPlatFormCommission(platFormCommission);
// 最终结算金额 = 流水金额-平台佣金-分销提佣 //最终结算金额 = 流水金额-平台佣金-分销提佣
double billPrice = CurrencyUtil.sub(CurrencyUtil.sub(priceDetailDTO.getFlowPrice(),priceDetailDTO.getPlatFormCommission()), double billPrice = CurrencyUtil.sub(CurrencyUtil.sub(priceDetailDTO.getFlowPrice(),priceDetailDTO.getPlatFormCommission()),
priceDetailDTO.getDistributionCommission()); priceDetailDTO.getDistributionCommission());
priceDetailDTO.setBillPrice(billPrice); priceDetailDTO.setBillPrice(billPrice);

View File

@ -161,9 +161,9 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
this.saveBatch(orders); this.saveBatch(orders);
//批量保存 子订单 //批量保存 子订单
orderItemService.saveBatch(orderItems); orderItemService.saveBatch(orderItems);
// 批量记录订单操作日志 //批量记录订单操作日志
orderLogService.saveBatch(orderLogs); orderLogService.saveBatch(orderLogs);
// 赠品根据店铺单独生成订单 //赠品根据店铺单独生成订单
this.generatorGiftOrder(tradeDTO); this.generatorGiftOrder(tradeDTO);
} }
@ -304,7 +304,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
//要记录之前的收货地址所以需要以代码方式进行调用 不采用注解 //要记录之前的收货地址所以需要以代码方式进行调用 不采用注解
String message = "订单[" + orderSn + "]收货信息修改,由[" + order.getConsigneeDetail() + "]修改为[" + memberAddressDTO.getConsigneeDetail() + "]"; String message = "订单[" + orderSn + "]收货信息修改,由[" + order.getConsigneeDetail() + "]修改为[" + memberAddressDTO.getConsigneeDetail() + "]";
BeanUtil.copyProperties(memberAddressDTO, order);// 记录订单操作日志 BeanUtil.copyProperties(memberAddressDTO, order);//记录订单操作日志
this.updateById(order); this.updateById(order);
OrderLog orderLog = new OrderLog(orderSn, UserContext.getCurrentUser().getId(), UserContext.getCurrentUser().getRole().getRole(), UserContext.getCurrentUser().getUsername(), message); OrderLog orderLog = new OrderLog(orderSn, UserContext.getCurrentUser().getId(), UserContext.getCurrentUser().getRole().getRole(), UserContext.getCurrentUser().getUsername(), message);
@ -401,7 +401,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
orderMessage.setOrderSn(order.getSn()); orderMessage.setOrderSn(order.getSn());
this.sendUpdateStatusMessage(orderMessage); this.sendUpdateStatusMessage(orderMessage);
// 发送当前商品购买完成的信息用于更新商品数据 //发送当前商品购买完成的信息用于更新商品数据
List<OrderItem> orderItems = orderItemService.getByOrderSn(orderSn); List<OrderItem> orderItems = orderItemService.getByOrderSn(orderSn);
List<GoodsCompleteMessage> goodsCompleteMessageList = new ArrayList<>(); List<GoodsCompleteMessage> goodsCompleteMessageList = new ArrayList<>();
for (OrderItem orderItem : orderItems) { for (OrderItem orderItem : orderItems) {
@ -488,10 +488,10 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
Pintuan pintuan = pintuanService.getPintuanById(pintuanId); Pintuan pintuan = pintuanService.getPintuanById(pintuanId);
List<Order> list = this.getPintuanOrder(pintuanId, parentOrderSn); List<Order> list = this.getPintuanOrder(pintuanId, parentOrderSn);
if (Boolean.TRUE.equals(pintuan.getFictitious()) && pintuan.getRequiredNum() > list.size()) { if (Boolean.TRUE.equals(pintuan.getFictitious()) && pintuan.getRequiredNum() > list.size()) {
// 如果开启虚拟成团且当前订单数量不足成团数量则认为拼团成功 //如果开启虚拟成团且当前订单数量不足成团数量则认为拼团成功
this.pintuanOrderSuccess(list); this.pintuanOrderSuccess(list);
} else if (Boolean.FALSE.equals(pintuan.getFictitious()) && pintuan.getRequiredNum() > list.size()) { } else if (Boolean.FALSE.equals(pintuan.getFictitious()) && pintuan.getRequiredNum() > list.size()) {
// 如果未开启虚拟成团且当前订单数量不足成团数量则认为拼团失败 //如果未开启虚拟成团且当前订单数量不足成团数量则认为拼团失败
this.pintuanOrderFailed(list); this.pintuanOrderFailed(list);
} }
} }
@ -534,10 +534,10 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
List<OrderBatchDeliverDTO> orderBatchDeliverDTOList = new ArrayList<>(); List<OrderBatchDeliverDTO> orderBatchDeliverDTOList = new ArrayList<>();
try { try {
inputStream = files.getInputStream(); inputStream = files.getInputStream();
// 2.应用HUtool ExcelUtil获取ExcelReader指定输入流和sheet //2.应用HUtool ExcelUtil获取ExcelReader指定输入流和sheet
ExcelReader excelReader = ExcelUtil.getReader(inputStream); ExcelReader excelReader = ExcelUtil.getReader(inputStream);
// 可以加上表头验证 //可以加上表头验证
// 3.读取第二行到最后一行数据 //3.读取第二行到最后一行数据
List<List<Object>> read = excelReader.read(1, excelReader.getRowCount()); List<List<Object>> read = excelReader.read(1, excelReader.getRowCount());
for (List<Object> objects : read) { for (List<Object> objects : read) {
OrderBatchDeliverDTO orderBatchDeliverDTO = new OrderBatchDeliverDTO(); OrderBatchDeliverDTO orderBatchDeliverDTO = new OrderBatchDeliverDTO();
@ -626,7 +626,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
List<Order> list = this.getPintuanOrder(pintuanId, parentOrderSn); List<Order> list = this.getPintuanOrder(pintuanId, parentOrderSn);
int count = list.size(); int count = list.size();
if (count == 1) { if (count == 1) {
// 如果为开团订单则发布一个一小时的延时任务时间到达后如果未成团则自动结束未开启虚拟成团的情况下 //如果为开团订单则发布一个一小时的延时任务时间到达后如果未成团则自动结束未开启虚拟成团的情况下
PintuanOrderMessage pintuanOrderMessage = new PintuanOrderMessage(); PintuanOrderMessage pintuanOrderMessage = new PintuanOrderMessage();
long startTime = DateUtil.offsetHour(new Date(), 1).getTime(); long startTime = DateUtil.offsetHour(new Date(), 1).getTime();
pintuanOrderMessage.setOrderSn(parentOrderSn); pintuanOrderMessage.setOrderSn(parentOrderSn);
@ -658,7 +658,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
queryWrapper.eq(Order::getPromotionId, pintuanId) queryWrapper.eq(Order::getPromotionId, pintuanId)
.eq(Order::getOrderPromotionType, OrderPromotionTypeEnum.PINTUAN.name()) .eq(Order::getOrderPromotionType, OrderPromotionTypeEnum.PINTUAN.name())
.eq(Order::getPayStatus, PayStatusEnum.PAID.name()); .eq(Order::getPayStatus, PayStatusEnum.PAID.name());
// 拼团sn=开团订单sn 或者 参团订单的开团订单sn //拼团sn=开团订单sn 或者 参团订单的开团订单sn
queryWrapper.and(i -> i.eq(Order::getSn, parentOrderSn) queryWrapper.and(i -> i.eq(Order::getSn, parentOrderSn)
.or(j -> j.eq(Order::getParentOrderSn, parentOrderSn))); .or(j -> j.eq(Order::getParentOrderSn, parentOrderSn)));
//参团后的订单数人数 //参团后的订单数人数

View File

@ -48,7 +48,7 @@ public class ArticleCategoryServiceImpl extends ServiceImpl<ArticleCategoryMappe
if (StringUtils.isNotEmpty(list)) { if (StringUtils.isNotEmpty(list)) {
throw new ServiceException(ResultCode.SUCCESS.ARTICLE_CATEGORY_NAME_EXIST); throw new ServiceException(ResultCode.SUCCESS.ARTICLE_CATEGORY_NAME_EXIST);
} }
// 非顶级分类 //非顶级分类
if (articleCategory.getParentId() != null && !articleCategory.getParentId().equals("0")) { if (articleCategory.getParentId() != null && !articleCategory.getParentId().equals("0")) {
ArticleCategory parent = this.getById(articleCategory.getParentId()); ArticleCategory parent = this.getById(articleCategory.getParentId());
if (parent == null) { if (parent == null) {
@ -68,13 +68,13 @@ public class ArticleCategoryServiceImpl extends ServiceImpl<ArticleCategoryMappe
@Override @Override
public ArticleCategory updateArticleCategory(ArticleCategory articleCategory) { public ArticleCategory updateArticleCategory(ArticleCategory articleCategory) {
// 非顶级分类校验是否存在 //非顶级分类校验是否存在
if (!articleCategory.getParentId().equals("0")) { if (!articleCategory.getParentId().equals("0")) {
ArticleCategory parent = this.getById(articleCategory.getParentId()); ArticleCategory parent = this.getById(articleCategory.getParentId());
if (parent == null) { if (parent == null) {
throw new ServiceException(ResultCode.ARTICLE_CATEGORY_PARENT_NOT_EXIST); throw new ServiceException(ResultCode.ARTICLE_CATEGORY_PARENT_NOT_EXIST);
} }
// 替换catPath 根据path规则来匹配级别 //替换catPath 根据path规则来匹配级别
if (articleCategory.getLevel() >= 2) { if (articleCategory.getLevel() >= 2) {
throw new ServiceException(ResultCode.ARTICLE_CATEGORY_BEYOND_TWO); throw new ServiceException(ResultCode.ARTICLE_CATEGORY_BEYOND_TWO);
} }
@ -123,11 +123,11 @@ public class ArticleCategoryServiceImpl extends ServiceImpl<ArticleCategoryMappe
@Override @Override
public List<ArticleCategoryVO> allChildren() { public List<ArticleCategoryVO> allChildren() {
// 从缓存取所有的分类 //从缓存取所有的分类
Object all = cache.get(CachePrefix.ARTICLE_CATEGORY.getPrefix()); Object all = cache.get(CachePrefix.ARTICLE_CATEGORY.getPrefix());
List<ArticleCategoryVO> articleCategories; List<ArticleCategoryVO> articleCategories;
if (all == null) { if (all == null) {
// 调用初始化分类缓存方法 //调用初始化分类缓存方法
articleCategories = initCategory(); articleCategories = initCategory();
} else { } else {
articleCategories = (List<ArticleCategoryVO>) all; articleCategories = (List<ArticleCategoryVO>) all;

View File

@ -37,32 +37,32 @@ public class XmlHelper {
private XmlHelper(InputSource inputSource) throws ParserConfigurationException, SAXException, IOException { private XmlHelper(InputSource inputSource) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = getDocumentBuilderFactory(); DocumentBuilderFactory dbf = getDocumentBuilderFactory();
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all //This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all
// XML entity attacks are prevented //XML entity attacks are prevented
// Xerces 2 only - //Xerces 2 only -
// http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl //http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// If you can't completely disable DTDs, then at least do the following: //If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - //Xerces 1 -
// http://xerces.apache.org/xerces-j/features.html#external-general-entities //http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - //Xerces 2 -
// http://xerces.apache.org/xerces2-j/features.html#external-general-entities //http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities //JDK7+ - http://xml.org/sax/features/external-general-entities
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
// Xerces 1 - //Xerces 1 -
// http://xerces.apache.org/xerces-j/features.html#external-parameter-entities //http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - //Xerces 2 -
// http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities //http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities //JDK7+ - http://xml.org/sax/features/external-parameter-entities
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Disable external DTDs as well //Disable external DTDs as well
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and //and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and
// Entity Attacks" //Entity Attacks"
dbf.setXIncludeAware(false); dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false); dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
@ -218,14 +218,14 @@ public class XmlHelper {
public Map<String, String> toMap() { public Map<String, String> toMap() {
Element root = doc.getDocumentElement(); Element root = doc.getDocumentElement();
// 将节点封装成map形式 //将节点封装成map形式
NodeList list = root.getChildNodes(); NodeList list = root.getChildNodes();
Map<String, String> params = new HashMap<String, String>(list.getLength()); Map<String, String> params = new HashMap<String, String>(list.getLength());
for (int i = 0; i < list.getLength(); i++) { for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i); Node node = list.item(i);
params.put(node.getNodeName(), node.getTextContent()); params.put(node.getNodeName(), node.getTextContent());
} }
// 含有空白符会生成一个#text参数 //含有空白符会生成一个#text参数
params.remove("#text"); params.remove("#text");
return params; return params;
} }

View File

@ -1,7 +1,7 @@
package cn.lili.modules.payment.kit.core.kit; package cn.lili.modules.payment.kit.core.kit;
// //
// Source code recreated from a .class file by IntelliJ IDEA //Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler) //(powered by Fernflower decompiler)
// //
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -29,13 +29,13 @@ public class IpKit {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
// 对于通过多个代理的情况第一个 IP 为客户端真实 IP多个IP按照','分割 //对于通过多个代理的情况第一个 IP 为客户端真实 IP多个IP按照','分割
if (ip != null && ip.length() > 15) { if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) { if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(",")); ip = ip.substring(0, ip.indexOf(","));
} }
} }
// return ip; // return ip;
return "27.189.225.9"; return "27.189.225.9";
} }
} }

View File

@ -146,7 +146,7 @@ public class PayKit {
for (int i = 0; i < keys.size(); i++) { for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i); String key = keys.get(i);
String value = params.get(key); String value = params.get(key);
// 拼接时不包括最后一个&字符 //拼接时不包括最后一个&字符
if (i == keys.size() - 1) { if (i == keys.size() - 1) {
if (quotes) { if (quotes) {
content.append(key).append("=").append('"').append(encode ? urlEncode(value) : value).append('"'); content.append(key).append("=").append('"').append(encode ? urlEncode(value) : value).append('"');
@ -196,7 +196,7 @@ public class PayKit {
for (Map.Entry<String, String> entry : params.entrySet()) { for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
String value = entry.getValue(); String value = entry.getValue();
// 略过空值 //略过空值
if (StrUtil.isEmpty(value)) { if (StrUtil.isEmpty(value)) {
continue; continue;
} }
@ -322,9 +322,9 @@ public class PayKit {
if (StrUtil.isEmpty(signMessage)) { if (StrUtil.isEmpty(signMessage)) {
return null; return null;
} }
// 获取商户私钥 //获取商户私钥
PrivateKey privateKey = PayKit.getPrivateKey(keyPath); PrivateKey privateKey = PayKit.getPrivateKey(keyPath);
// 生成签名 //生成签名
return RsaKit.encryptByPrivateKey(signMessage, privateKey); return RsaKit.encryptByPrivateKey(signMessage, privateKey);
} }
@ -340,7 +340,7 @@ public class PayKit {
if (StrUtil.isEmpty(signMessage)) { if (StrUtil.isEmpty(signMessage)) {
return null; return null;
} }
// 生成签名 //生成签名
return RsaKit.encryptByPrivateKey(signMessage, privateKey); return RsaKit.encryptByPrivateKey(signMessage, privateKey);
} }

View File

@ -40,7 +40,7 @@ public class QrCodeKit {
boolean bool = false; boolean bool = false;
BufferedImage bufImg; BufferedImage bufImg;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3); Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3);
// 指定纠错等级 //指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel); hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin); hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

View File

@ -123,7 +123,7 @@ public class RsaKit {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key key = keyFactory.generatePublic(x509KeySpec); Key key = keyFactory.generatePublic(x509KeySpec);
// 对数据加密 //对数据加密
Cipher cipher = Cipher.getInstance(fillMode); Cipher cipher = Cipher.getInstance(fillMode);
cipher.init(Cipher.ENCRYPT_MODE, key); cipher.init(Cipher.ENCRYPT_MODE, key);
int inputLen = dataByte.length; int inputLen = dataByte.length;
@ -131,7 +131,7 @@ public class RsaKit {
int offSet = 0; int offSet = 0;
byte[] cache; byte[] cache;
int i = 0; int i = 0;
// 对数据分段加密 //对数据分段加密
while (inputLen - offSet > 0) { while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK); cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
@ -265,7 +265,7 @@ public class RsaKit {
int offSet = 0; int offSet = 0;
byte[] cache; byte[] cache;
int i = 0; int i = 0;
// 对数据分段解密 //对数据分段解密
while (inputLen - offSet > 0) { while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);

View File

@ -103,7 +103,7 @@ public class WxPayKit {
if (signType == null) { if (signType == null) {
signType = SignType.MD5; signType = SignType.MD5;
} }
// 生成签名前先去除sign //生成签名前先去除sign
params.remove(FIELD_SIGN); params.remove(FIELD_SIGN);
String tempStr = PayKit.createLinkString(params); String tempStr = PayKit.createLinkString(params);
String stringSignTemp = tempStr + "&key=" + partnerKey; String stringSignTemp = tempStr + "&key=" + partnerKey;
@ -122,7 +122,7 @@ public class WxPayKit {
* @return 签名后的数据 * @return 签名后的数据
*/ */
public static String createSign(Map<String, String> params, String secret) { public static String createSign(Map<String, String> params, String secret) {
// 生成签名前先去除sign //生成签名前先去除sign
params.remove(FIELD_SIGN); params.remove(FIELD_SIGN);
String tempStr = PayKit.createLinkString(params); String tempStr = PayKit.createLinkString(params);
String stringSignTemp = tempStr + "&secret=" + secret; String stringSignTemp = tempStr + "&secret=" + secret;
@ -432,10 +432,10 @@ public class WxPayKit {
public static String buildAuthorization(RequestMethodEnums method, String urlSuffix, String mchId, public static String buildAuthorization(RequestMethodEnums method, String urlSuffix, String mchId,
String serialNo, String keyPath, String body, String nonceStr, String serialNo, String keyPath, String body, String nonceStr,
long timestamp, String authType) throws Exception { long timestamp, String authType) throws Exception {
// 构建签名参数 //构建签名参数
String buildSignMessage = PayKit.buildSignMessage(method, urlSuffix, timestamp, nonceStr, body); String buildSignMessage = PayKit.buildSignMessage(method, urlSuffix, timestamp, nonceStr, body);
String signature = PayKit.createSign(buildSignMessage, keyPath); String signature = PayKit.createSign(buildSignMessage, keyPath);
// 根据平台规则生成请求头 authorization //根据平台规则生成请求头 authorization
return PayKit.getAuthorization(mchId, serialNo, nonceStr, String.valueOf(timestamp), signature, authType); return PayKit.getAuthorization(mchId, serialNo, nonceStr, String.valueOf(timestamp), signature, authType);
} }
@ -457,10 +457,10 @@ public class WxPayKit {
public static String buildAuthorization(RequestMethodEnums method, String urlSuffix, String mchId, public static String buildAuthorization(RequestMethodEnums method, String urlSuffix, String mchId,
String serialNo, PrivateKey privateKey, String body, String nonceStr, String serialNo, PrivateKey privateKey, String body, String nonceStr,
long timestamp, String authType) throws Exception { long timestamp, String authType) throws Exception {
// 构建签名参数 //构建签名参数
String buildSignMessage = PayKit.buildSignMessage(method, urlSuffix, timestamp, nonceStr, body); String buildSignMessage = PayKit.buildSignMessage(method, urlSuffix, timestamp, nonceStr, body);
String signature = PayKit.createSign(buildSignMessage, privateKey); String signature = PayKit.createSign(buildSignMessage, privateKey);
// 根据平台规则生成请求头 authorization //根据平台规则生成请求头 authorization
return PayKit.getAuthorization(mchId, serialNo, nonceStr, String.valueOf(timestamp), signature, authType); return PayKit.getAuthorization(mchId, serialNo, nonceStr, String.valueOf(timestamp), signature, authType);
} }
@ -585,7 +585,7 @@ public class WxPayKit {
*/ */
public static boolean verifySignature(String signature, String body, String nonce, String timestamp, InputStream certInputStream) throws Exception { public static boolean verifySignature(String signature, String body, String nonce, String timestamp, InputStream certInputStream) throws Exception {
String buildSignMessage = PayKit.buildSignMessage(timestamp, nonce, body); String buildSignMessage = PayKit.buildSignMessage(timestamp, nonce, body);
// 获取证书 //获取证书
X509Certificate certificate = PayKit.getCertificate(certInputStream); X509Certificate certificate = PayKit.getCertificate(certInputStream);
PublicKey publicKey = certificate.getPublicKey(); PublicKey publicKey = certificate.getPublicKey();
return RsaKit.checkByPublicKey(buildSignMessage, signature, publicKey); return RsaKit.checkByPublicKey(buildSignMessage, signature, publicKey);
@ -624,11 +624,11 @@ public class WxPayKit {
public static String verifyNotify(String serialNo, String body, String signature, String nonce, public static String verifyNotify(String serialNo, String body, String signature, String nonce,
String timestamp, String key, String certPath) throws Exception { String timestamp, String key, String certPath) throws Exception {
BufferedInputStream inputStream = FileUtil.getInputStream(certPath); BufferedInputStream inputStream = FileUtil.getInputStream(certPath);
// 获取平台证书序列号 //获取平台证书序列号
X509Certificate certificate = PayKit.getCertificate(inputStream); X509Certificate certificate = PayKit.getCertificate(inputStream);
String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase(); String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase();
System.out.println(serialNumber); System.out.println(serialNumber);
// 验证证书序列号 //验证证书序列号
if (serialNumber.equals(serialNo)) { if (serialNumber.equals(serialNo)) {
boolean verifySignature = WxPayKit.verifySignature(signature, body, nonce, timestamp, certificate.getPublicKey()); boolean verifySignature = WxPayKit.verifySignature(signature, body, nonce, timestamp, certificate.getPublicKey());
if (verifySignature) { if (verifySignature) {
@ -639,7 +639,7 @@ public class WxPayKit {
String associatedData = resource.getStr("associated_data"); String associatedData = resource.getStr("associated_data");
AesUtil aesUtil = new AesUtil(key.getBytes(StandardCharsets.UTF_8)); AesUtil aesUtil = new AesUtil(key.getBytes(StandardCharsets.UTF_8));
// 密文解密 //密文解密
return aesUtil.decryptToString( return aesUtil.decryptToString(
associatedData.getBytes(StandardCharsets.UTF_8), associatedData.getBytes(StandardCharsets.UTF_8),
nonceStr.getBytes(StandardCharsets.UTF_8), nonceStr.getBytes(StandardCharsets.UTF_8),
@ -665,7 +665,7 @@ public class WxPayKit {
public static String verifyNotify(String serialNo, String body, String signature, String nonce, public static String verifyNotify(String serialNo, String body, String signature, String nonce,
String timestamp, String key, X509Certificate certificate) throws Exception { String timestamp, String key, X509Certificate certificate) throws Exception {
String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase(); String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase();
// 验证证书序列号 //验证证书序列号
if (serialNumber.equals(serialNo)) { if (serialNumber.equals(serialNo)) {
boolean verifySignature = WxPayKit.verifySignature(signature, body, nonce, timestamp, certificate.getPublicKey()); boolean verifySignature = WxPayKit.verifySignature(signature, body, nonce, timestamp, certificate.getPublicKey());
if (verifySignature) { if (verifySignature) {
@ -676,7 +676,7 @@ public class WxPayKit {
String associatedData = resource.getStr("associated_data"); String associatedData = resource.getStr("associated_data");
AesUtil aesUtil = new AesUtil(key.getBytes(StandardCharsets.UTF_8)); AesUtil aesUtil = new AesUtil(key.getBytes(StandardCharsets.UTF_8));
// 密文解密 //密文解密
return aesUtil.decryptToString( return aesUtil.decryptToString(
associatedData.getBytes(StandardCharsets.UTF_8), associatedData.getBytes(StandardCharsets.UTF_8),
nonceStr.getBytes(StandardCharsets.UTF_8), nonceStr.getBytes(StandardCharsets.UTF_8),

View File

@ -244,7 +244,7 @@ public class AliPayApi {
*/ */
public static AlipayTradePayResponse tradePayToResponse(AlipayTradePayModel model, String notifyUrl) throws AlipayApiException { public static AlipayTradePayResponse tradePayToResponse(AlipayTradePayModel model, String notifyUrl) throws AlipayApiException {
AlipayTradePayRequest request = new AlipayTradePayRequest(); AlipayTradePayRequest request = new AlipayTradePayRequest();
// 填充业务参数 //填充业务参数
request.setBizModel(model); request.setBizModel(model);
request.setNotifyUrl(notifyUrl); request.setNotifyUrl(notifyUrl);
return doExecute(request); return doExecute(request);
@ -316,7 +316,7 @@ public class AliPayApi {
if (response.isSuccess()) { if (response.isSuccess()) {
return true; return true;
} else { } else {
// 调用查询接口查询数据 //调用查询接口查询数据
JSONObject jsonObject = JSONObject.parseObject(result); JSONObject jsonObject = JSONObject.parseObject(result);
String outBizNo = jsonObject.getJSONObject("alipay_fund_trans_toaccount_transfer_response").getString("out_biz_no"); String outBizNo = jsonObject.getJSONObject("alipay_fund_trans_toaccount_transfer_response").getString("out_biz_no");
AlipayFundTransOrderQueryModel queryModel = new AlipayFundTransOrderQueryModel(); AlipayFundTransOrderQueryModel queryModel = new AlipayFundTransOrderQueryModel();

View File

@ -149,7 +149,7 @@ public class AliPayPlugin implements Payment {
//回传数据 //回传数据
payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8)); payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(payParam), StandardCharsets.UTF_8));
// payModel.setStoreId("store_id"); // payModel.setStoreId("store_id");
payModel.setTimeoutExpress("3m"); payModel.setTimeoutExpress("3m");
payModel.setOutTradeNo(outTradeNo); payModel.setOutTradeNo(outTradeNo);
log.info("支付宝扫码:{}", payModel); log.info("支付宝扫码:{}", payModel);
@ -245,7 +245,7 @@ public class AliPayPlugin implements Payment {
private void verifyNotify(HttpServletRequest request) { private void verifyNotify(HttpServletRequest request) {
try { try {
AlipayPaymentSetting alipayPaymentSetting = alipayPaymentSetting(); AlipayPaymentSetting alipayPaymentSetting = alipayPaymentSetting();
// 获取支付宝反馈信息 //获取支付宝反馈信息
Map<String, String> map = AliPayApi.toMap(request); Map<String, String> map = AliPayApi.toMap(request);
log.info("支付回调响应:{}", JSONUtil.toJsonStr(map)); log.info("支付回调响应:{}", JSONUtil.toJsonStr(map));
boolean verifyResult = AlipaySignature.rsaCertCheckV1(map, alipayPaymentSetting.getAlipayPublicCertPath(), "UTF-8", boolean verifyResult = AlipaySignature.rsaCertCheckV1(map, alipayPaymentSetting.getAlipayPublicCertPath(), "UTF-8",

View File

@ -177,7 +177,7 @@ public class WechatApi {
String mchId, String serialNo, String platSerialNo, String keyPath, String mchId, String serialNo, String platSerialNo, String keyPath,
String body, String nonceStr, long timestamp, String authType, String body, String nonceStr, long timestamp, String authType,
File file) throws Exception { File file) throws Exception {
// 构建 Authorization //构建 Authorization
String authorization = WxPayKit.buildAuthorization(method, urlSuffix, mchId, serialNo, String authorization = WxPayKit.buildAuthorization(method, urlSuffix, mchId, serialNo,
keyPath, body, nonceStr, timestamp, authType); keyPath, body, nonceStr, timestamp, authType);
@ -220,7 +220,7 @@ public class WechatApi {
String mchId, String serialNo, String platSerialNo, PrivateKey privateKey, String mchId, String serialNo, String platSerialNo, PrivateKey privateKey,
String body, String nonceStr, long timestamp, String authType, String body, String nonceStr, long timestamp, String authType,
File file) throws Exception { File file) throws Exception {
// 构建 Authorization //构建 Authorization
String authorization = WxPayKit.buildAuthorization(method, urlSuffix, mchId, serialNo, String authorization = WxPayKit.buildAuthorization(method, urlSuffix, mchId, serialNo,
privateKey, body, nonceStr, timestamp, authType); privateKey, body, nonceStr, timestamp, authType);

View File

@ -191,7 +191,7 @@ public class WechatPlugin implements Payment {
setting.getApiclient_key(), setting.getApiclient_key(),
JSONUtil.toJsonStr(unifiedOrderModel) JSONUtil.toJsonStr(unifiedOrderModel)
); );
// 根据证书序列号查询对应的证书来验证签名结果 //根据证书序列号查询对应的证书来验证签名结果
boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert()); boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert());
log.info("verifySignature: {}", verifySignature); log.info("verifySignature: {}", verifySignature);
log.info("统一下单响应 {}", response); log.info("统一下单响应 {}", response);
@ -252,7 +252,7 @@ public class WechatPlugin implements Payment {
setting.getApiclient_key(), setting.getApiclient_key(),
JSONUtil.toJsonStr(unifiedOrderModel) JSONUtil.toJsonStr(unifiedOrderModel)
); );
// 根据证书序列号查询对应的证书来验证签名结果 //根据证书序列号查询对应的证书来验证签名结果
boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert()); boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert());
log.info("verifySignature: {}", verifySignature); log.info("verifySignature: {}", verifySignature);
log.info("统一下单响应 {}", response); log.info("统一下单响应 {}", response);
@ -316,7 +316,7 @@ public class WechatPlugin implements Payment {
JSONUtil.toJsonStr(unifiedOrderModel) JSONUtil.toJsonStr(unifiedOrderModel)
); );
log.info("统一下单响应 {}", response); log.info("统一下单响应 {}", response);
// 根据证书序列号查询对应的证书来验证签名结果 //根据证书序列号查询对应的证书来验证签名结果
boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert()); boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert());
log.info("verifySignature: {}", verifySignature); log.info("verifySignature: {}", verifySignature);
@ -392,7 +392,7 @@ public class WechatPlugin implements Payment {
setting.getApiclient_key(), setting.getApiclient_key(),
JSONUtil.toJsonStr(unifiedOrderModel) JSONUtil.toJsonStr(unifiedOrderModel)
); );
// 根据证书序列号查询对应的证书来验证签名结果 //根据证书序列号查询对应的证书来验证签名结果
boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert()); boolean verifySignature = WxPayKit.verifySignature(response, getPlatformCert());
log.info("verifySignature: {}", verifySignature); log.info("verifySignature: {}", verifySignature);
log.info("统一下单响应 {}", response); log.info("统一下单响应 {}", response);
@ -451,7 +451,7 @@ public class WechatPlugin implements Payment {
log.info("微信支付通知密文 {}", result); log.info("微信支付通知密文 {}", result);
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
// 校验服务器端响应¬ //校验服务器端响应¬
String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp, String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp,
setting.getApiKey3(), Objects.requireNonNull(getPlatformCert())); setting.getApiKey3(), Objects.requireNonNull(getPlatformCert()));
@ -486,7 +486,7 @@ public class WechatPlugin implements Payment {
Amount amount = new Amount().setRefund(CurrencyUtil.fen(refundLog.getTotalAmount())) Amount amount = new Amount().setRefund(CurrencyUtil.fen(refundLog.getTotalAmount()))
.setTotal(CurrencyUtil.fen(refundLog.getPayPrice())); .setTotal(CurrencyUtil.fen(refundLog.getPayPrice()));
// 退款参数准备 //退款参数准备
RefundModel refundModel = new RefundModel() RefundModel refundModel = new RefundModel()
.setTransaction_id(refundLog.getPaymentReceivableNo()) .setTransaction_id(refundLog.getPaymentReceivableNo())
.setOut_refund_no(refundLog.getOutOrderNo()) .setOut_refund_no(refundLog.getOutOrderNo())
@ -508,11 +508,11 @@ public class WechatPlugin implements Payment {
JSONUtil.toJsonStr(refundModel) JSONUtil.toJsonStr(refundModel)
); );
log.info("微信退款响应 {}", response); log.info("微信退款响应 {}", response);
// 退款申请成功 //退款申请成功
if (response.getStatus() == 200) { if (response.getStatus() == 200) {
refundLogService.save(refundLog); refundLogService.save(refundLog);
} else { } else {
// 退款申请失败 //退款申请失败
refundLog.setErrorMessage(response.getBody()); refundLog.setErrorMessage(response.getBody());
refundLogService.save(refundLog); refundLogService.save(refundLog);
} }
@ -543,7 +543,7 @@ public class WechatPlugin implements Payment {
return; return;
} }
try { try {
// 校验服务器端响应¬ //校验服务器端响应¬
String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp, String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp,
wechatPaymentSetting().getApiKey3(), Objects.requireNonNull(getPlatformCert())); wechatPaymentSetting().getApiKey3(), Objects.requireNonNull(getPlatformCert()));
log.info("微信退款通知明文 {}", plainText); log.info("微信退款通知明文 {}", plainText);
@ -589,7 +589,7 @@ public class WechatPlugin implements Payment {
if (!StringUtils.isEmpty(publicCert)) { if (!StringUtils.isEmpty(publicCert)) {
return PayKit.getCertificate(publicCert); return PayKit.getCertificate(publicCert);
} }
// 获取平台证书列表 //获取平台证书列表
try { try {
WechatPaymentSetting setting = wechatPaymentSetting(); WechatPaymentSetting setting = wechatPaymentSetting();
@ -609,7 +609,7 @@ public class WechatPlugin implements Payment {
if (response.getStatus() == 200) { if (response.getStatus() == 200) {
JSONObject jsonObject = JSONUtil.parseObj(body); JSONObject jsonObject = JSONUtil.parseObj(body);
JSONArray dataArray = jsonObject.getJSONArray("data"); JSONArray dataArray = jsonObject.getJSONArray("data");
// 默认认为只有一个平台证书 //默认认为只有一个平台证书
JSONObject encryptObject = dataArray.getJSONObject(0); JSONObject encryptObject = dataArray.getJSONObject(0);
JSONObject encryptCertificate = encryptObject.getJSONObject("encrypt_certificate"); JSONObject encryptCertificate = encryptObject.getJSONObject("encrypt_certificate");
String associatedData = encryptCertificate.getStr("associated_data"); String associatedData = encryptCertificate.getStr("associated_data");
@ -643,8 +643,8 @@ public class WechatPlugin implements Payment {
AesUtil aesUtil = new AesUtil(wechatPaymentSetting().getApiKey3().getBytes(StandardCharsets.UTF_8)); AesUtil aesUtil = new AesUtil(wechatPaymentSetting().getApiKey3().getBytes(StandardCharsets.UTF_8));
// 平台证书密文解密 //平台证书密文解密
// encrypt_certificate 中的 associated_data nonce ciphertext //encrypt_certificate 中的 associated_data nonce ciphertext
return aesUtil.decryptToString( return aesUtil.decryptToString(
associatedData.getBytes(StandardCharsets.UTF_8), associatedData.getBytes(StandardCharsets.UTF_8),
nonce.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8),

View File

@ -138,7 +138,7 @@ public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser
return null; return null;
} }
AdminUserVO adminUserVO = new AdminUserVO(user); AdminUserVO adminUserVO = new AdminUserVO(user);
// 关联部门 //关联部门
if (user.getDepartmentId() != null) { if (user.getDepartmentId() != null) {
Department department = departmentService.getById(user.getDepartmentId()); Department department = departmentService.getById(user.getDepartmentId());
if (department != null) { if (department != null) {

View File

@ -79,15 +79,15 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
@Override @Override
public CouponVO add(CouponVO coupon) { public CouponVO add(CouponVO coupon) {
// 检查参数 //检查参数
this.checkParam(coupon); this.checkParam(coupon);
coupon.setUsedNum(0); coupon.setUsedNum(0);
coupon.setReceivedNum(0); coupon.setReceivedNum(0);
// 保存到MYSQL中 //保存到MYSQL中
this.save(coupon); this.save(coupon);
// 如果优惠券类型为部分商品则将促销活动商品更新 //如果优惠券类型为部分商品则将促销活动商品更新
this.updateScopePromotionGoods(coupon); this.updateScopePromotionGoods(coupon);
// 保存到MONGO中 //保存到MONGO中
this.mongoTemplate.save(coupon); this.mongoTemplate.save(coupon);
//如果优惠券是固定时间则添加延时任务 //如果优惠券是固定时间则添加延时任务
if (coupon.getRangeDayType().equals(CouponRangeDayEnum.FIXEDTIME.name())) { if (coupon.getRangeDayType().equals(CouponRangeDayEnum.FIXEDTIME.name())) {
@ -97,7 +97,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
promotionMessage, promotionMessage,
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
} }
@ -107,16 +107,16 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
@Override @Override
public CouponVO updateCoupon(CouponVO couponVO) { public CouponVO updateCoupon(CouponVO couponVO) {
CouponVO coupon = checkStatus(couponVO.getId()); CouponVO coupon = checkStatus(couponVO.getId());
// 检查参数 //检查参数
this.checkParam(couponVO); this.checkParam(couponVO);
// 更新到MYSQL中 //更新到MYSQL中
this.updateById(couponVO); this.updateById(couponVO);
// 如果优惠券类型为部分商品则将促销活动商品更新 //如果优惠券类型为部分商品则将促销活动商品更新
this.updateScopePromotionGoods(couponVO); this.updateScopePromotionGoods(couponVO);
// 保存到MONGO中 //保存到MONGO中
this.mongoTemplate.save(couponVO); this.mongoTemplate.save(couponVO);
PromotionMessage promotionMessage = new PromotionMessage(couponVO.getId(), PromotionTypeEnum.COUPON.name(), PromotionStatusEnum.START.name(), coupon.getStartTime(), coupon.getEndTime()); PromotionMessage promotionMessage = new PromotionMessage(couponVO.getId(), PromotionTypeEnum.COUPON.name(), PromotionStatusEnum.START.name(), coupon.getStartTime(), coupon.getEndTime());
// 更新延时任务 //更新延时任务
this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR,
promotionMessage, promotionMessage,
coupon.getStartTime().getTime(), couponVO.getStartTime().getTime(), coupon.getStartTime().getTime(), couponVO.getStartTime().getTime(),
@ -144,7 +144,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
this.mongoTemplate.save(couponVO); this.mongoTemplate.save(couponVO);
if (promotionStatus.name().equals(PromotionStatusEnum.START.name())) { if (promotionStatus.name().equals(PromotionStatusEnum.START.name())) {
PromotionMessage promotionMessage = new PromotionMessage(couponVO.getId(), PromotionTypeEnum.COUPON.name(), PromotionStatusEnum.START.name(), couponVO.getStartTime(), couponVO.getEndTime()); PromotionMessage promotionMessage = new PromotionMessage(couponVO.getId(), PromotionTypeEnum.COUPON.name(), PromotionStatusEnum.START.name(), couponVO.getStartTime(), couponVO.getEndTime());
// 更新延时任务 //更新延时任务
this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR,
promotionMessage, promotionMessage,
couponVO.getStartTime().getTime(), couponVO.getStartTime().getTime(), couponVO.getStartTime().getTime(), couponVO.getStartTime().getTime(),
@ -160,10 +160,10 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
public boolean deleteCoupon(String id) { public boolean deleteCoupon(String id) {
CouponVO couponVO = checkStatus(id); CouponVO couponVO = checkStatus(id);
LambdaUpdateWrapper<Coupon> couponUpdateWrapper = new LambdaUpdateWrapper<Coupon>().eq(Coupon::getId, id).set(Coupon::getPromotionStatus, PromotionStatusEnum.CLOSE.name()).set(Coupon::getDeleteFlag, true); LambdaUpdateWrapper<Coupon> couponUpdateWrapper = new LambdaUpdateWrapper<Coupon>().eq(Coupon::getId, id).set(Coupon::getPromotionStatus, PromotionStatusEnum.CLOSE.name()).set(Coupon::getDeleteFlag, true);
// 更新优惠券状态为关闭标示删除标志 //更新优惠券状态为关闭标示删除标志
boolean result = this.update(couponUpdateWrapper); boolean result = this.update(couponUpdateWrapper);
LambdaUpdateWrapper<PromotionGoods> updateWrapper = new LambdaUpdateWrapper<PromotionGoods>().eq(PromotionGoods::getPromotionId, id).set(PromotionGoods::getPromotionStatus, PromotionStatusEnum.CLOSE.name()).set(PromotionGoods::getDeleteFlag, true); LambdaUpdateWrapper<PromotionGoods> updateWrapper = new LambdaUpdateWrapper<PromotionGoods>().eq(PromotionGoods::getPromotionId, id).set(PromotionGoods::getPromotionStatus, PromotionStatusEnum.CLOSE.name()).set(PromotionGoods::getDeleteFlag, true);
// 更新促销商品记录信息为删除 //更新促销商品记录信息为删除
this.promotionGoodsService.update(updateWrapper); this.promotionGoodsService.update(updateWrapper);
LambdaUpdateWrapper<MemberCoupon> memberCouponLambdaUpdateWrapper = new LambdaUpdateWrapper<MemberCoupon>().eq(MemberCoupon::getCouponId, id).set(MemberCoupon::getMemberCouponStatus, MemberCouponStatusEnum.CLOSED.name()); LambdaUpdateWrapper<MemberCoupon> memberCouponLambdaUpdateWrapper = new LambdaUpdateWrapper<MemberCoupon>().eq(MemberCoupon::getCouponId, id).set(MemberCoupon::getMemberCouponStatus, MemberCouponStatusEnum.CLOSED.name());
memberCouponService.update(memberCouponLambdaUpdateWrapper); memberCouponService.update(memberCouponLambdaUpdateWrapper);
@ -373,7 +373,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
} }
private void updateScopePromotionGoods(CouponVO couponVO) { private void updateScopePromotionGoods(CouponVO couponVO) {
// 如果优惠券类型为部分商品则将促销活动更新至ES中 //如果优惠券类型为部分商品则将促销活动更新至ES中
if (CouponScopeTypeEnum.PORTION_GOODS.name().equals(couponVO.getScopeType()) && !couponVO.getPromotionGoodsList().isEmpty()) { if (CouponScopeTypeEnum.PORTION_GOODS.name().equals(couponVO.getScopeType()) && !couponVO.getPromotionGoodsList().isEmpty()) {
PromotionTools.promotionGoodsInit(couponVO.getPromotionGoodsList(), couponVO, PromotionTypeEnum.COUPON); PromotionTools.promotionGoodsInit(couponVO.getPromotionGoodsList(), couponVO, PromotionTypeEnum.COUPON);
} }

View File

@ -82,20 +82,20 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
@Override @Override
public FullDiscount addFullDiscount(FullDiscountVO fullDiscountVO) { public FullDiscount addFullDiscount(FullDiscountVO fullDiscountVO) {
// 验证是否是有效参数 //验证是否是有效参数
PromotionTools.paramValid(fullDiscountVO.getStartTime().getTime(), fullDiscountVO.getEndTime().getTime(), fullDiscountVO.getNumber(), fullDiscountVO.getPromotionGoodsList()); PromotionTools.paramValid(fullDiscountVO.getStartTime().getTime(), fullDiscountVO.getEndTime().getTime(), fullDiscountVO.getNumber(), fullDiscountVO.getPromotionGoodsList());
// 当前时间段是否存在同类活动 //当前时间段是否存在同类活动
this.checkSameActiveExist(fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime(), fullDiscountVO.getStoreId(), null); this.checkSameActiveExist(fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime(), fullDiscountVO.getStoreId(), null);
// 检查满减参数 //检查满减参数
this.checkFullDiscount(fullDiscountVO); this.checkFullDiscount(fullDiscountVO);
// 保存到MYSQL中 //保存到MYSQL中
this.save(fullDiscountVO); this.save(fullDiscountVO);
if (fullDiscountVO.getPromotionGoodsList() != null) { if (fullDiscountVO.getPromotionGoodsList() != null) {
List<PromotionGoods> promotionGoodsList = PromotionTools.promotionGoodsInit(fullDiscountVO.getPromotionGoodsList(), fullDiscountVO, PromotionTypeEnum.FULL_DISCOUNT); List<PromotionGoods> promotionGoodsList = PromotionTools.promotionGoodsInit(fullDiscountVO.getPromotionGoodsList(), fullDiscountVO, PromotionTypeEnum.FULL_DISCOUNT);
// 促销活动商品更新 //促销活动商品更新
this.promotionGoodsService.saveOrUpdateBatch(promotionGoodsList); this.promotionGoodsService.saveOrUpdateBatch(promotionGoodsList);
} }
// 保存到MONGO中 //保存到MONGO中
this.mongoTemplate.save(fullDiscountVO); this.mongoTemplate.save(fullDiscountVO);
PromotionMessage promotionMessage = new PromotionMessage(fullDiscountVO.getId(), PromotionTypeEnum.FULL_DISCOUNT.name(), PromotionMessage promotionMessage = new PromotionMessage(fullDiscountVO.getId(), PromotionTypeEnum.FULL_DISCOUNT.name(),
PromotionStatusEnum.START.name(), PromotionStatusEnum.START.name(),
@ -105,7 +105,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
fullDiscountVO.getStartTime().getTime(), promotionMessage, fullDiscountVO.getStartTime().getTime(), promotionMessage,
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
return fullDiscountVO; return fullDiscountVO;
} }
@ -132,31 +132,31 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
@Override @Override
public FullDiscountVO modifyFullDiscount(FullDiscountVO fullDiscountVO) { public FullDiscountVO modifyFullDiscount(FullDiscountVO fullDiscountVO) {
// 检查满优惠活动是否存在 //检查满优惠活动是否存在
FullDiscountVO fullDiscount = this.checkFullDiscountExist(fullDiscountVO.getId()); FullDiscountVO fullDiscount = this.checkFullDiscountExist(fullDiscountVO.getId());
if (!fullDiscount.getPromotionStatus().equals(PromotionStatusEnum.NEW.name())) { if (!fullDiscount.getPromotionStatus().equals(PromotionStatusEnum.NEW.name())) {
throw new ServiceException("当前编辑的满优惠活动已经开始或者已经结束,无法修改"); throw new ServiceException("当前编辑的满优惠活动已经开始或者已经结束,无法修改");
} }
// 检查活动是否已经开始 //检查活动是否已经开始
PromotionTools.checkPromotionTime(fullDiscountVO.getStartTime().getTime(), fullDiscountVO.getEndTime().getTime()); PromotionTools.checkPromotionTime(fullDiscountVO.getStartTime().getTime(), fullDiscountVO.getEndTime().getTime());
// 检查满减参数 //检查满减参数
this.checkFullDiscount(fullDiscountVO); this.checkFullDiscount(fullDiscountVO);
// 时间发生变化 //时间发生变化
if (!fullDiscount.getStartTime().equals(fullDiscountVO.getStartTime()) && fullDiscount.getEndTime().equals(fullDiscountVO.getEndTime())) { if (!fullDiscount.getStartTime().equals(fullDiscountVO.getStartTime()) && fullDiscount.getEndTime().equals(fullDiscountVO.getEndTime())) {
// 检查当前时间段是否存在同类活动 //检查当前时间段是否存在同类活动
this.checkSameActiveExist(fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime(), fullDiscountVO.getStoreId(), fullDiscount.getId()); this.checkSameActiveExist(fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime(), fullDiscountVO.getStoreId(), fullDiscount.getId());
} }
// 更新到MYSQL中 //更新到MYSQL中
this.updateById(fullDiscountVO); this.updateById(fullDiscountVO);
if (fullDiscountVO.getPromotionGoodsList() != null) { if (fullDiscountVO.getPromotionGoodsList() != null) {
// 促销活动商品更新 //促销活动商品更新
this.promotionGoodsService.updateBatchById(PromotionTools.promotionGoodsInit(fullDiscountVO.getPromotionGoodsList(), fullDiscountVO, PromotionTypeEnum.FULL_DISCOUNT)); this.promotionGoodsService.updateBatchById(PromotionTools.promotionGoodsInit(fullDiscountVO.getPromotionGoodsList(), fullDiscountVO, PromotionTypeEnum.FULL_DISCOUNT));
} }
// 保存到MONGO中 //保存到MONGO中
this.mongoTemplate.save(fullDiscountVO); this.mongoTemplate.save(fullDiscountVO);
PromotionMessage promotionMessage = new PromotionMessage(fullDiscountVO.getId(), PromotionTypeEnum.FULL_DISCOUNT.name(), PromotionStatusEnum.START.name(), fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime()); PromotionMessage promotionMessage = new PromotionMessage(fullDiscountVO.getId(), PromotionTypeEnum.FULL_DISCOUNT.name(), PromotionStatusEnum.START.name(), fullDiscountVO.getStartTime(), fullDiscountVO.getEndTime());
// 发送更新延时任务 //发送更新延时任务
this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, promotionMessage, this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, promotionMessage,
fullDiscount.getStartTime().getTime(), fullDiscountVO.getStartTime().getTime(), fullDiscount.getStartTime().getTime(), fullDiscountVO.getStartTime().getTime(),
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())),
@ -179,7 +179,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
@Override @Override
public boolean deleteFullDiscount(String id) { public boolean deleteFullDiscount(String id) {
FullDiscountVO fullDiscount = this.checkFullDiscountExist(id); FullDiscountVO fullDiscount = this.checkFullDiscountExist(id);
// 检查活动是否已经开始 //检查活动是否已经开始
boolean result = this.removeById(id); boolean result = this.removeById(id);
this.mongoTemplate.remove(new Query().addCriteria(Criteria.where("id").is(id)), FullDiscountVO.class); this.mongoTemplate.remove(new Query().addCriteria(Criteria.where("id").is(id)), FullDiscountVO.class);
if (fullDiscount.getPromotionGoodsList() != null && !fullDiscount.getPromotionGoodsList().isEmpty()) { if (fullDiscount.getPromotionGoodsList() != null && !fullDiscount.getPromotionGoodsList().isEmpty()) {
@ -214,24 +214,24 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
if (fullDiscountVO.getIsFullMinus() == null && fullDiscountVO.getIsCoupon() == null && fullDiscountVO.getIsGift() == null && fullDiscountVO.getIsPoint() == null && fullDiscountVO.getIsFullRate() == null) { if (fullDiscountVO.getIsFullMinus() == null && fullDiscountVO.getIsCoupon() == null && fullDiscountVO.getIsGift() == null && fullDiscountVO.getIsPoint() == null && fullDiscountVO.getIsFullRate() == null) {
throw new ServiceException("请选择一种优惠方式"); throw new ServiceException("请选择一种优惠方式");
} }
// 如果优惠方式是满减 //如果优惠方式是满减
if (Boolean.TRUE.equals(fullDiscountVO.getIsFullMinus())) { if (Boolean.TRUE.equals(fullDiscountVO.getIsFullMinus())) {
this.checkFullMinus(fullDiscountVO.getFullMinus(), fullDiscountVO.getFullMoney()); this.checkFullMinus(fullDiscountVO.getFullMinus(), fullDiscountVO.getFullMoney());
fullDiscountVO.setTitle("" + fullDiscountVO.getFullMoney() + "" + fullDiscountVO.getFullMinus()); fullDiscountVO.setTitle("" + fullDiscountVO.getFullMoney() + "" + fullDiscountVO.getFullMinus());
} }
// 如果优惠方式是赠品 //如果优惠方式是赠品
if (Boolean.TRUE.equals(fullDiscountVO.getIsGift())) { if (Boolean.TRUE.equals(fullDiscountVO.getIsGift())) {
// 是否没有选择赠品 //是否没有选择赠品
boolean noGiftSelected = fullDiscountVO.getGiftId() == null; boolean noGiftSelected = fullDiscountVO.getGiftId() == null;
if (noGiftSelected) { if (noGiftSelected) {
throw new ServiceException("请选择赠品"); throw new ServiceException("请选择赠品");
} }
} }
// 如果优惠方式是赠优惠券 //如果优惠方式是赠优惠券
if (Boolean.TRUE.equals(fullDiscountVO.getIsCoupon())) { if (Boolean.TRUE.equals(fullDiscountVO.getIsCoupon())) {
this.checkCoupon(fullDiscountVO.getCouponId(), fullDiscountVO.getEndTime().getTime()); this.checkCoupon(fullDiscountVO.getCouponId(), fullDiscountVO.getEndTime().getTime());
} }
// 如果优惠方式是折扣 //如果优惠方式是折扣
if (Boolean.TRUE.equals(fullDiscountVO.getIsFullRate())) { if (Boolean.TRUE.equals(fullDiscountVO.getIsFullRate())) {
this.checkFullRate(fullDiscountVO.getFullRate()); this.checkFullRate(fullDiscountVO.getFullRate());
fullDiscountVO.setTitle("" + fullDiscountVO.getFullMoney() + "" + fullDiscountVO.getFullRate() + ""); fullDiscountVO.setTitle("" + fullDiscountVO.getFullMoney() + "" + fullDiscountVO.getFullRate() + "");
@ -248,7 +248,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
* @param id 满优惠活动ID * @param id 满优惠活动ID
*/ */
private void checkSameActiveExist(Date statTime, Date endTime, String storeId, String id) { private void checkSameActiveExist(Date statTime, Date endTime, String storeId, String id) {
// 同一时间段内相同的活动 //同一时间段内相同的活动
QueryWrapper<FullDiscount> queryWrapper = PromotionTools.checkActiveTime(statTime, endTime, PromotionTypeEnum.FULL_DISCOUNT, storeId, id); QueryWrapper<FullDiscount> queryWrapper = PromotionTools.checkActiveTime(statTime, endTime, PromotionTypeEnum.FULL_DISCOUNT, storeId, id);
Integer sameNum = this.count(queryWrapper); Integer sameNum = this.count(queryWrapper);
if (sameNum > 0) { if (sameNum > 0) {
@ -263,7 +263,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
* @param endTime 活动结束时间 * @param endTime 活动结束时间
*/ */
private void checkCoupon(String couponId, long endTime) { private void checkCoupon(String couponId, long endTime) {
// 是否没有选择优惠券 //是否没有选择优惠券
boolean noCouponSelected = couponId == null; boolean noCouponSelected = couponId == null;
if (noCouponSelected) { if (noCouponSelected) {
throw new ServiceException("请选择优惠券"); throw new ServiceException("请选择优惠券");
@ -281,7 +281,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
* @param fullMoney 优惠门槛 * @param fullMoney 优惠门槛
*/ */
private void checkFullMinus(Double fullMinus, Double fullMoney) { private void checkFullMinus(Double fullMinus, Double fullMoney) {
// 是否没有填写满减金额 //是否没有填写满减金额
boolean noFullMinusInput = fullMinus == null || fullMinus == 0; boolean noFullMinusInput = fullMinus == null || fullMinus == 0;
if (noFullMinusInput) { if (noFullMinusInput) {
throw new ServiceException("请填写满减金额"); throw new ServiceException("请填写满减金额");
@ -297,7 +297,7 @@ public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountMapper, Ful
* @param fullRate 打折数值 * @param fullRate 打折数值
*/ */
private void checkFullRate(Double fullRate) { private void checkFullRate(Double fullRate) {
// 是否没有填写打折数值 //是否没有填写打折数值
boolean noFullRateInput = fullRate == null || fullRate == 0; boolean noFullRateInput = fullRate == null || fullRate == 0;
if (noFullRateInput) { if (noFullRateInput) {
throw new ServiceException("请填写打折数值"); throw new ServiceException("请填写打折数值");

View File

@ -107,16 +107,16 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
.eq(Order::getOrderStatus, OrderStatusEnum.PAID.name()) .eq(Order::getOrderStatus, OrderStatusEnum.PAID.name())
.eq(Order::getParentOrderSn, ""); .eq(Order::getParentOrderSn, "");
List<Order> orders = orderService.list(queryWrapper); List<Order> orders = orderService.list(queryWrapper);
// 遍历订单状态为已支付为团长的拼团订单 //遍历订单状态为已支付为团长的拼团订单
for (Order order : orders) { for (Order order : orders) {
Member member = memberService.getById(order.getMemberId()); Member member = memberService.getById(order.getMemberId());
PintuanMemberVO memberVO = new PintuanMemberVO(member); PintuanMemberVO memberVO = new PintuanMemberVO(member);
LambdaQueryWrapper<Order> countQueryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> countQueryWrapper = new LambdaQueryWrapper<>();
countQueryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.PAID.name()); countQueryWrapper.eq(Order::getOrderStatus, OrderStatusEnum.PAID.name());
countQueryWrapper.and(i -> i.eq(Order::getSn, order.getSn()).or(j -> j.eq(Order::getParentOrderSn, order.getSn()))); countQueryWrapper.and(i -> i.eq(Order::getSn, order.getSn()).or(j -> j.eq(Order::getParentOrderSn, order.getSn())));
// 获取已参团人数 //获取已参团人数
int count = orderService.count(countQueryWrapper); int count = orderService.count(countQueryWrapper);
// 获取待参团人数 //获取待参团人数
int toBoGrouped = pintuan.getRequiredNum() - count; int toBoGrouped = pintuan.getRequiredNum() - count;
memberVO.setGroupNum(pintuan.getRequiredNum()); memberVO.setGroupNum(pintuan.getRequiredNum());
memberVO.setGroupedNum(count); memberVO.setGroupedNum(count);
@ -192,7 +192,7 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
PromotionTools.checkPromotionTime(pintuan.getStartTime().getTime(), pintuan.getEndTime().getTime()); PromotionTools.checkPromotionTime(pintuan.getStartTime().getTime(), pintuan.getEndTime().getTime());
this.checkSamePromotion(pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getStoreId(), null); this.checkSamePromotion(pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getStoreId(), null);
pintuan.setPromotionStatus(PromotionStatusEnum.NEW.name()); pintuan.setPromotionStatus(PromotionStatusEnum.NEW.name());
// 保存到MYSQL中 //保存到MYSQL中
boolean result = this.save(pintuan); boolean result = this.save(pintuan);
this.updatePintuanPromotionGoods(pintuan); this.updatePintuanPromotionGoods(pintuan);
this.mongoTemplate.save(pintuan); this.mongoTemplate.save(pintuan);
@ -206,19 +206,19 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
if (!pintuan.getPromotionStatus().equals(PromotionStatusEnum.NEW.name())) { if (!pintuan.getPromotionStatus().equals(PromotionStatusEnum.NEW.name())) {
throw new ServiceException("只有活动状态为新活动时(活动未开始)才可编辑!"); throw new ServiceException("只有活动状态为新活动时(活动未开始)才可编辑!");
} }
// 检查促销时间 //检查促销时间
PromotionTools.checkPromotionTime(pintuan.getStartTime().getTime(), pintuan.getEndTime().getTime()); PromotionTools.checkPromotionTime(pintuan.getStartTime().getTime(), pintuan.getEndTime().getTime());
// 检查同一时间同一店铺同一类型的促销活动 //检查同一时间同一店铺同一类型的促销活动
this.checkSamePromotion(pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getStoreId(), pintuan.getId()); this.checkSamePromotion(pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getStoreId(), pintuan.getId());
boolean result = this.updateById(pintuan); boolean result = this.updateById(pintuan);
if (pintuan.getPromotionGoodsList() != null) { if (pintuan.getPromotionGoodsList() != null) {
this.updatePintuanPromotionGoods(pintuan); this.updatePintuanPromotionGoods(pintuan);
} }
this.mongoTemplate.save(pintuan); this.mongoTemplate.save(pintuan);
// 时间发生变化 //时间发生变化
if (pintuan.getStartTime().getTime() != pintuanVO.getStartTime().getTime()) { if (pintuan.getStartTime().getTime() != pintuanVO.getStartTime().getTime()) {
PromotionMessage promotionMessage = new PromotionMessage(pintuan.getId(), PromotionTypeEnum.PINTUAN.name(), PromotionStatusEnum.START.name(), pintuan.getStartTime(), pintuan.getEndTime()); PromotionMessage promotionMessage = new PromotionMessage(pintuan.getId(), PromotionTypeEnum.PINTUAN.name(), PromotionStatusEnum.START.name(), pintuan.getStartTime(), pintuan.getEndTime());
// 更新延时任务 //更新延时任务
this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR,
promotionMessage, promotionMessage,
pintuanVO.getStartTime().getTime(), pintuanVO.getStartTime().getTime(),
@ -269,7 +269,7 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
queryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name()); queryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name());
queryWrapper.eq(Order::getPromotionId, pintuanId); queryWrapper.eq(Order::getPromotionId, pintuanId);
queryWrapper.nested(i -> i.eq(Order::getPayStatus, PayStatusEnum.PAID.name()).or().eq(Order::getOrderStatus, OrderStatusEnum.PAID.name())); queryWrapper.nested(i -> i.eq(Order::getPayStatus, PayStatusEnum.PAID.name()).or().eq(Order::getOrderStatus, OrderStatusEnum.PAID.name()));
// 过滤父级拼团订单根据父级拼团订单分组 //过滤父级拼团订单根据父级拼团订单分组
Map<String, List<Order>> collect = orderService.list(queryWrapper).stream().filter(i -> !i.getParentOrderSn().equals("")).collect(Collectors.groupingBy(Order::getParentOrderSn)); Map<String, List<Order>> collect = orderService.list(queryWrapper).stream().filter(i -> !i.getParentOrderSn().equals("")).collect(Collectors.groupingBy(Order::getParentOrderSn));
this.isOpenFictitiousPintuan(pintuan, collect); this.isOpenFictitiousPintuan(pintuan, collect);
@ -322,16 +322,16 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
PintuanShareVO pintuanShareVO = new PintuanShareVO(); PintuanShareVO pintuanShareVO = new PintuanShareVO();
pintuanShareVO.setPintuanMemberVOS(new ArrayList<>()); pintuanShareVO.setPintuanMemberVOS(new ArrayList<>());
LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
// 查找团长订单和已和当前拼团订单拼团的订单 //查找团长订单和已和当前拼团订单拼团的订单
queryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name()) queryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name())
.eq(Order::getPayStatus, OrderStatusEnum.PAID.name()) .eq(Order::getPayStatus, OrderStatusEnum.PAID.name())
.and(i -> i.eq(Order::getParentOrderSn, parentOrderSn).or(j -> j.eq(Order::getSn, parentOrderSn))); .and(i -> i.eq(Order::getParentOrderSn, parentOrderSn).or(j -> j.eq(Order::getSn, parentOrderSn)));
List<Order> orders = orderService.list(queryWrapper); List<Order> orders = orderService.list(queryWrapper);
this.setPintuanOrderInfo(orders, pintuanShareVO, skuId); this.setPintuanOrderInfo(orders, pintuanShareVO, skuId);
// 如果为根据团员订单sn查询拼团订单信息时找到团长订单sn然后找到所有参与到同一拼团的订单信息 //如果为根据团员订单sn查询拼团订单信息时找到团长订单sn然后找到所有参与到同一拼团的订单信息
if (!orders.isEmpty() && pintuanShareVO.getPromotionGoods() == null) { if (!orders.isEmpty() && pintuanShareVO.getPromotionGoods() == null) {
LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
// 查找团长订单和已和当前拼团订单拼团的订单 //查找团长订单和已和当前拼团订单拼团的订单
orderLambdaQueryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name()) orderLambdaQueryWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name())
.eq(Order::getPayStatus, OrderStatusEnum.PAID.name()) .eq(Order::getPayStatus, OrderStatusEnum.PAID.name())
.ne(Order::getSn, parentOrderSn) .ne(Order::getSn, parentOrderSn)
@ -365,9 +365,9 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
LambdaQueryWrapper<Order> countQueryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Order> countQueryWrapper = new LambdaQueryWrapper<>();
countQueryWrapper.eq(Order::getPayStatus, PayStatusEnum.PAID.name()); countQueryWrapper.eq(Order::getPayStatus, PayStatusEnum.PAID.name());
countQueryWrapper.and(i -> i.eq(Order::getSn, order.getSn()).or(j -> j.eq(Order::getParentOrderSn, order.getSn()))); countQueryWrapper.and(i -> i.eq(Order::getSn, order.getSn()).or(j -> j.eq(Order::getParentOrderSn, order.getSn())));
// 获取已参团人数 //获取已参团人数
int count = orderService.count(countQueryWrapper); int count = orderService.count(countQueryWrapper);
// 获取待参团人数 //获取待参团人数
int toBoGrouped = pintuanById.getRequiredNum() - count; int toBoGrouped = pintuanById.getRequiredNum() - count;
memberVO.setGroupNum(pintuanById.getRequiredNum()); memberVO.setGroupNum(pintuanById.getRequiredNum());
memberVO.setGroupedNum(count); memberVO.setGroupedNum(count);
@ -392,7 +392,7 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
promotionMessage, promotionMessage,
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
} }
@ -416,13 +416,13 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
* @param collect 检查的订单列表 * @param collect 检查的订单列表
*/ */
private void isOpenFictitiousPintuan(PintuanVO pintuan, Map<String, List<Order>> collect) { private void isOpenFictitiousPintuan(PintuanVO pintuan, Map<String, List<Order>> collect) {
// 成团人数 //成团人数
Integer requiredNum = pintuan.getRequiredNum(); Integer requiredNum = pintuan.getRequiredNum();
for (Map.Entry<String, List<Order>> entry : collect.entrySet()) { for (Map.Entry<String, List<Order>> entry : collect.entrySet()) {
// 是否开启虚拟成团 //是否开启虚拟成团
if (Boolean.FALSE.equals(pintuan.getFictitious()) && entry.getValue().size() < requiredNum) { if (Boolean.FALSE.equals(pintuan.getFictitious()) && entry.getValue().size() < requiredNum) {
// 如果未开启虚拟成团且已参团人数小于成团人数则自动取消订单 //如果未开启虚拟成团且已参团人数小于成团人数则自动取消订单
LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>(); LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name()); updateWrapper.eq(Order::getOrderPromotionType, PromotionTypeEnum.PINTUAN.name());
updateWrapper.eq(Order::getPromotionId, pintuan.getId()); updateWrapper.eq(Order::getPromotionId, pintuan.getId());
@ -444,9 +444,9 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
*/ */
private void fictitiousPintuan(Map.Entry<String, List<Order>> entry, Integer requiredNum) { private void fictitiousPintuan(Map.Entry<String, List<Order>> entry, Integer requiredNum) {
Map<String, List<Order>> listMap = entry.getValue().stream().collect(Collectors.groupingBy(Order::getPayStatus)); Map<String, List<Order>> listMap = entry.getValue().stream().collect(Collectors.groupingBy(Order::getPayStatus));
// 未付款订单 //未付款订单
List<Order> unpaidOrders = listMap.get(PayStatusEnum.UNPAID.name()); List<Order> unpaidOrders = listMap.get(PayStatusEnum.UNPAID.name());
// 未付款订单自动取消 //未付款订单自动取消
if (unpaidOrders != null && !unpaidOrders.isEmpty()) { if (unpaidOrders != null && !unpaidOrders.isEmpty()) {
for (Order unpaidOrder : unpaidOrders) { for (Order unpaidOrder : unpaidOrders) {
unpaidOrder.setOrderStatus(OrderStatusEnum.CANCELLED.name()); unpaidOrder.setOrderStatus(OrderStatusEnum.CANCELLED.name());
@ -455,11 +455,11 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
orderService.updateBatchById(unpaidOrders); orderService.updateBatchById(unpaidOrders);
} }
List<Order> paidOrders = listMap.get(PayStatusEnum.PAID.name()); List<Order> paidOrders = listMap.get(PayStatusEnum.PAID.name());
// 如待参团人数大于0并已开启虚拟成团 //如待参团人数大于0并已开启虚拟成团
if (!paidOrders.isEmpty()) { if (!paidOrders.isEmpty()) {
// 待参团人数 //待参团人数
int waitNum = requiredNum - paidOrders.size(); int waitNum = requiredNum - paidOrders.size();
// 添加虚拟成团 //添加虚拟成团
for (int i = 0; i < waitNum; i++) { for (int i = 0; i < waitNum; i++) {
Order order = new Order(); Order order = new Order();
BeanUtil.copyProperties(paidOrders.get(0), order); BeanUtil.copyProperties(paidOrders.get(0), order);
@ -503,9 +503,9 @@ public class PintuanServiceImpl extends ServiceImpl<PintuanMapper, Pintuan> impl
log.error("商品[" + promotionGood.getGoodsName() + "]不存在或处于不可售卖状态!"); log.error("商品[" + promotionGood.getGoodsName() + "]不存在或处于不可售卖状态!");
throw new ServiceException(); throw new ServiceException();
} }
// 查询是否在同一时间段参与了拼团活动 //查询是否在同一时间段参与了拼团活动
Integer count = promotionGoodsService.findInnerOverlapPromotionGoods(PromotionTypeEnum.SECKILL.name(), promotionGood.getSkuId(), pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getId()); Integer count = promotionGoodsService.findInnerOverlapPromotionGoods(PromotionTypeEnum.SECKILL.name(), promotionGood.getSkuId(), pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getId());
// 查询是否在同一时间段参与了限时抢购活动 //查询是否在同一时间段参与了限时抢购活动
count += promotionGoodsService.findInnerOverlapPromotionGoods(PromotionTypeEnum.PINTUAN.name(), promotionGood.getSkuId(), pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getId()); count += promotionGoodsService.findInnerOverlapPromotionGoods(PromotionTypeEnum.PINTUAN.name(), promotionGood.getSkuId(), pintuan.getStartTime(), pintuan.getEndTime(), pintuan.getId());
if (count > 0) { if (count > 0) {
log.error("商品[" + promotionGood.getGoodsName() + "]已经在重叠的时间段参加了秒杀活动或拼团活动,不能参加拼团活动"); log.error("商品[" + promotionGood.getGoodsName() + "]已经在重叠的时间段参加了秒杀活动或拼团活动,不能参加拼团活动");

View File

@ -115,7 +115,7 @@ public class PointsGoodsServiceImpl extends ServiceImpl<PointsGoodsMapper, Point
this.mongoTemplate.save(pointsGoods); this.mongoTemplate.save(pointsGoods);
if (pointsGoods.getStartTime().getTime() != pointsGoodsVO.getStartTime().getTime()) { if (pointsGoods.getStartTime().getTime() != pointsGoodsVO.getStartTime().getTime()) {
PromotionMessage promotionMessage = new PromotionMessage(pointsGoods.getId(), PromotionTypeEnum.POINTS_GOODS.name(), PromotionStatusEnum.START.name(), pointsGoods.getStartTime(), pointsGoods.getEndTime()); PromotionMessage promotionMessage = new PromotionMessage(pointsGoods.getId(), PromotionTypeEnum.POINTS_GOODS.name(), PromotionStatusEnum.START.name(), pointsGoods.getStartTime(), pointsGoods.getEndTime());
// 更新延时任务 //更新延时任务
this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR, this.timeTrigger.edit(TimeExecuteConstant.PROMOTION_EXECUTOR,
promotionMessage, promotionMessage,
pointsGoodsVO.getStartTime().getTime(), pointsGoodsVO.getStartTime().getTime(),
@ -245,7 +245,7 @@ public class PointsGoodsServiceImpl extends ServiceImpl<PointsGoodsMapper, Point
promotionMessage, promotionMessage,
DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())), DelayQueueTools.wrapperUniqueKey(DelayTypeEnums.PROMOTION, (promotionMessage.getPromotionType() + promotionMessage.getPromotionId())),
rocketmqCustomProperties.getPromotionTopic()); rocketmqCustomProperties.getPromotionTopic());
// 发送促销活动开始的延时任务 //发送促销活动开始的延时任务
this.timeTrigger.addDelay(timeTriggerMsg); this.timeTrigger.addDelay(timeTriggerMsg);
} }

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