Merge branch 'master' of gitee.com:beijing_hongye_huicheng/lilishop into feature/pg

This commit is contained in:
OceansDeep 2021-06-21 16:10:06 +00:00 committed by Gitee
commit 54408db0f0
157 changed files with 1383 additions and 1137 deletions

View File

@ -37,11 +37,11 @@ public class AdminApplication {
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeRequests().antMatchers("/instances**").permitAll();
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() //其他所有请求都必须经过验证
).formLogin(
(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注册所必需的
(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注册所必需的
.csrf().disable()
.rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
}

View File

@ -4,9 +4,9 @@ import cn.lili.common.enums.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.message.entity.enums.MessageStatusEnum;
import cn.lili.modules.member.entity.dos.MemberMessage;
import cn.lili.modules.member.entity.vo.MemberMessageQueryVO;
import cn.lili.modules.member.service.MemberMessageService;
import cn.lili.modules.message.entity.dos.MemberMessage;
import cn.lili.modules.message.entity.vos.MemberMessageQueryVO;
import cn.lili.modules.message.service.MemberMessageService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
package cn.lili.controller.common;
import cn.lili.common.aop.limiter.annotation.LimitPoint;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.verification.enums.VerificationEnums;
@ -37,8 +38,8 @@ public class SliderImageController {
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
log.error("获取校验接口错误",e);
return null;
log.error("获取校验接口错误", e);
throw new ServiceException(ResultCode.VERIFICATION_EXIST);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,18 +1,27 @@
package cn.lili.listener;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.SwitchEnum;
import cn.lili.common.rocketmq.tags.OtherTagsEnum;
import cn.lili.common.sms.SmsUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.vo.MemberSearchVO;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.message.entity.dos.MemberMessage;
import cn.lili.modules.message.entity.dos.Message;
import cn.lili.modules.message.entity.dos.StoreMessage;
import cn.lili.modules.message.entity.dto.SmsReachDTO;
import cn.lili.modules.message.entity.enums.MessageSendClient;
import cn.lili.modules.message.entity.enums.MessageStatusEnum;
import cn.lili.modules.message.entity.enums.RangeEnum;
import cn.lili.modules.message.service.MemberMessageService;
import cn.lili.modules.message.service.StoreMessageService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.service.StoreService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
@ -41,9 +50,15 @@ public class NoticeSendMessageListener implements RocketMQListener<MessageExt> {
//店铺消息
@Autowired
private StoreMessageService storeMessageService;
//会员消息
@Autowired
private MemberMessageService memberMessageService;
//店铺
@Autowired
private StoreService storeService;
//会员
@Autowired
private MemberService memberService;
@Override
public void onMessage(MessageExt messageExt) {
@ -51,7 +66,6 @@ public class NoticeSendMessageListener implements RocketMQListener<MessageExt> {
case SMS:
String smsJsonStr = new String(messageExt.getBody());
SmsReachDTO smsReachDTO = JSONUtil.toBean(smsJsonStr, SmsReachDTO.class);
//发送全部会员
if (smsReachDTO.getSmsRange().equals(RangeEnum.ALL.name())) {
//获取所有会员的手机号
@ -65,38 +79,118 @@ public class NoticeSendMessageListener implements RocketMQListener<MessageExt> {
//管理员发送站内信
case MESSAGE:
Message message = JSONUtil.toBean(new String(messageExt.getBody()), Message.class);
List<StoreMessage> list = new ArrayList<>();
//保存商家记录
if (message.getMessageRange().equals("ALL")) {
List<Store> storeList = storeService.list(new QueryWrapper<Store>().eq("store_disable", "OPEN"));
storeList.forEach(item -> {
StoreMessage storeMessage = new StoreMessage();
storeMessage.setMessageId(message.getId());
storeMessage.setStoreName(item.getStoreName());
storeMessage.setStoreId(item.getId());
storeMessage.setStatus(MessageStatusEnum.UN_READY.name());
storeMessage.setTitle(message.getTitle());
storeMessage.setContent(message.getContent());
list.add(storeMessage);
});
// 管理端发送给商家的站内信
if (message.getMessageClient().equals(MessageSendClient.STORE.name().toLowerCase())) {
saveStoreMessage(message);
} else {
int i = 0;
for (String str : message.getUserIds()) {
StoreMessage storeMessage = new StoreMessage();
storeMessage.setMessageId(message.getId());
storeMessage.setStoreId(str);
storeMessage.setStoreName(message.getUserNames()[i]);
storeMessage.setStatus(MessageStatusEnum.UN_READY.name());
storeMessage.setTitle(message.getTitle());
storeMessage.setContent(message.getContent());
list.add(storeMessage);
i++;
}
//管理员发送给会员的站内信
saveMemberMessage(message);
}
storeMessageService.save(list);
break;
default:
break;
}
}
/**
* 保存店铺消息
*
* @param message 消息
*/
private void saveStoreMessage(Message message) {
List<StoreMessage> list = new ArrayList<>();
//发送全部商家情况
if (message.getMessageRange().equals("ALL")) {
List<Store> storeList = storeService.list(new QueryWrapper<Store>().eq("store_disable", "OPEN"));
storeList.forEach(item -> {
StoreMessage storeMessage = new StoreMessage();
storeMessage.setMessageId(message.getId());
storeMessage.setStoreName(item.getStoreName());
storeMessage.setStoreId(item.getId());
storeMessage.setStatus(MessageStatusEnum.UN_READY.name());
storeMessage.setTitle(message.getTitle());
storeMessage.setContent(message.getContent());
list.add(storeMessage);
});
} else {
//发送给指定商家情况
int i = 0;
for (String str : message.getUserIds()) {
StoreMessage storeMessage = new StoreMessage();
storeMessage.setMessageId(message.getId());
storeMessage.setStoreId(str);
storeMessage.setStoreName(message.getUserNames()[i]);
storeMessage.setStatus(MessageStatusEnum.UN_READY.name());
storeMessage.setTitle(message.getTitle());
storeMessage.setContent(message.getContent());
list.add(storeMessage);
i++;
}
}
if (list.size() > 0) {
//执行保存
storeMessageService.save(list);
}
}
/**
* 保存会员消息
*
* @param message 消息
*/
private void saveMemberMessage(Message message) {
List<MemberMessage> list = new ArrayList<>();
//如果是给所有会员发送消息
if (message.getMessageRange().equals("ALL")) {
//查询所有会员总数因为会员总数比较大 如果一次性查出来会占用数据库资源所以要分页查询
MemberSearchVO memberSearchVO = new MemberSearchVO();
memberSearchVO.setDisabled(SwitchEnum.OPEN.name());
Integer memberNum = memberService.getMemberNum(memberSearchVO);
//构建分页查询参数
//100条查一次
Integer pageSize = 200;
Integer pageCount = 0;
pageCount = memberNum / pageSize;
pageCount = memberNum % pageSize > 0 ? pageCount + 1 : pageCount;
for (int i = 1; i <= pageCount; i++) {
PageVO pageVO = new PageVO();
pageVO.setPageSize(pageSize);
pageVO.setPageNumber(i);
IPage<Member> page = memberService.getMemberPage(memberSearchVO, pageVO);
//循环要保存的信息
page.getRecords().forEach(item -> {
MemberMessage memberMessage = new MemberMessage();
memberMessage.setContent(message.getContent());
memberMessage.setTitle(message.getTitle());
memberMessage.setMessageId(message.getId());
memberMessage.setMemberId(item.getId());
memberMessage.setMemberName(item.getUsername());
memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
list.add(memberMessage);
});
}
} else {
//如果是给指定会员发送消息
int i = 0;
for (String str : message.getUserIds()) {
MemberMessage memberMessage = new MemberMessage();
memberMessage.setMessageId(message.getId());
memberMessage.setMemberId(str);
memberMessage.setMemberName(message.getUserNames()[i]);
memberMessage.setStatus(MessageStatusEnum.UN_READY.name());
memberMessage.setTitle(message.getTitle());
memberMessage.setContent(message.getContent());
list.add(memberMessage);
i++;
}
}
if (list.size() > 0) {
//执行保存
memberMessageService.save(list);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,10 +5,8 @@ import cn.lili.common.exception.ServiceException;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
@ -18,7 +16,6 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* 流量拦截
@ -43,40 +40,34 @@ public class LimitInterceptor {
this.limitScript = limitScript;
}
@Around("execution(public * *(..)) && @annotation(cn.lili.common.aop.limiter.annotation.LimitPoint)")
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
LimitPoint limitPointAnnotation = method.getAnnotation(LimitPoint.class);
@Before("@annotation(limitPointAnnotation)")
public void interceptor(LimitPoint limitPointAnnotation) {
LimitType limitType = limitPointAnnotation.limitType();
String name = limitPointAnnotation.name();
String key;
int limitPeriod = limitPointAnnotation.period();
int limitCount = limitPointAnnotation.limit();
switch (limitType) {
case IP:
key = limitPointAnnotation.key() + getIpAddress();
break;
case CUSTOMER:
key = limitPointAnnotation.key();
break;
default:
key = StringUtils.upperCase(method.getName());
key = limitPointAnnotation.key() + getIpAddress();
}
ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitPointAnnotation.prefix(), key));
try {
Number count = redisTemplate.execute(limitScript, keys, limitCount, limitPeriod);
log.info("Access try count is {} for name={} and key = {}", count, name, key);
// 如果缓存里没有值或者他的值小于限制频率
if (count.intValue() <= limitCount) {
return pjp.proceed();
} else {
log.info("限制请求{}, 当前请求{},缓存key{}", limitCount, count.intValue(), key);
//如果缓存里没有值或者他的值小于限制频率
if (count.intValue() >= limitCount) {
throw new ServiceException("访问过于频繁,请稍后再试");
}
}
//如果从redis中执行都值判定为空则这里跳过
catch (NullPointerException e) {
return pjp.proceed();
return;
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("服务器异常,请稍后再试");
}

View File

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

View File

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

View File

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

View File

@ -34,6 +34,7 @@ public enum ResultCode {
*/
WECHAT_CONNECT_NOT_EXIST(1001, "微信联合登录未配置"),
VERIFICATION_EXIST(1002, "验证码服务异常"),
/**
* 分类
*/
@ -56,77 +57,119 @@ public enum ResultCode {
GOODS_UPPER_ERROR(11004, "商品上架失败"),
GOODS_AUTH_ERROR(11005, "商品审核失败"),
POINT_GOODS_ERROR(11006, "积分商品业务异常,请稍后重试"),
GOODS_SKU_SN_ERROR(11007, "商品SKU编号不能为空"),
GOODS_SKU_PRICE_ERROR(11008, "商品SKU价格不能小于等于0"),
GOODS_SKU_COST_ERROR(11009, "商品SKU成本价不能小于等于0"),
GOODS_SKU_WEIGHT_ERROR(11010, "商品重量不能为负数"),
GOODS_SKU_QUANTITY_ERROR(11011, "商品库存数量不能为负数"),
/**
* 参数
*/
PARAMETER_SAVE_ERROR(12001, "参数添加失败"),
PARAMETER_UPDATE_ERROR(12002, "参数编辑失败"),
/**
* 规格
*/
SPEC_SAVE_ERROR(13001, "规格修改失败"),
SPEC_UPDATE_ERROR(13002, "规格修改失败"),
SPEC_DELETE_ERROR(13003, "此规格已绑定分类不允许删除"),
/**
* 品牌
*/
BRAND_SAVE_ERROR(14001, "品牌添加失败"),
BRAND_UPDATE_ERROR(14002, "品牌修改失败"),
BRAND_DISABLE_ERROR(14003, "品牌禁用失败"),
BRAND_DELETE_ERROR(14004, "品牌删除失败"),
/**
* 用户
*/
USER_EDIT_SUCCESS(20001, "用户修改成功"),
USER_NOT_EXIST(20002, "用户不存在"),
USER_NOT_LOGIN(20003, "用户未登录"),
USER_AUTH_EXPIRED(20004, "用户已退出,请重新登录"),
USER_AUTHORITY_ERROR(20005, "权限不足"),
USER_CONNECT_LOGIN_ERROR(20006, "未找到登录信息"),
USER_NAME_EXIST(20007, "该用户名已被注册"),
USER_PHONE_EXIST(20008, "该手机号已被注册"),
USER_PHONE_NOT_EXIST(20009, "手机号不存在"),
USER_PASSWORD_ERROR(20010, "密码不正确"),
USER_NOT_PHONE(20011, "非当前用户的手机号"),
USER_CONNECT_ERROR(20012, "联合第三方登录,授权信息错误"),
USER_RECEIPT_REPEAT_ERROR(20013, "会员发票信息重复"),
USER_RECEIPT_NOT_EXIST(20014, "会员发票信息不存在"),
USER_EDIT_ERROR(20015, "用户修改失败"),
USER_OLD_PASSWORD_ERROR(20016, "旧密码不正确"),
USER_COLLECTION_EXIST(20017, "无法重复收藏"),
USER_GRADE_IS_DEFAULT(20018, "会员等级为默认会员等级"),
DELETE_EXIST(2001, "无法重复收藏"),
/**
* 权限
*/
PERMISSION_DEPARTMENT_ROLE_ERROR(21001, "角色已绑定部门,请逐个删除"),
PERMISSION_USER_ROLE_ERROR(21002, "角色已绑定管理员,请逐个删除"),
PERMISSION_MENU_ROLE_ERROR(21003, "菜单已绑定角色,请先删除或编辑角色"),
PERMISSION_DEPARTMENT_DELETE_ERROR(21004, "部门已经绑定管理员,请先删除或编辑管理员"),
PERMISSION_BEYOND_TEN(21005, "最多可以设置10个角色"),
/**
* 分销
*/
DISTRIBUTION_CLOSE(22000, "分销功能关闭"),
DISTRIBUTION_NOT_EXIST(22001, "分销员不存在"),
DISTRIBUTION_IS_APPLY(22002, "分销员已申请,无需重复提交"),
DISTRIBUTION_AUDIT_ERROR(22003, "审核分销员失败"),
DISTRIBUTION_RETREAT_ERROR(22004, "分销员清退失败"),
DISTRIBUTION_CASH_NOT_EXIST(22005, "分销员提现记录不存在"),
DISTRIBUTION_GOODS_DOUBLE(22006, "不能重复添加分销商品"),
/**
* 购物车
*/
CART_ERROR(30001, "读取结算页的购物车异常"),
CART_PINTUAN_NOT_EXIST_ERROR(30002, "拼团活动不存在错误"),
CART_PINTUAN_LIMIT_ERROR(30003, "购买数量超过拼团活动限制数量"),
SHIPPING_NOT_APPLY(30005, "购物商品不支持当前收货地址配送"),
/**

View File

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

View File

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

View File

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

View File

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

View File

@ -43,7 +43,7 @@ public class ManagerTokenGenerate extends AbstractTokenGenerate {
@Override
public Token createToken(String username, Boolean longTerm) {
// 生成token
//生成token
AdminUser adminUser = adminUserService.findByUsername(username);
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);
AuthUser authUser = new AuthUser(member.getUsername(), member.getId(),member.getNickName(), UserEnums.MEMBER);
// 登陆成功生成token
//登陆成功生成token
return tokenUtil.createToken(username, authUser, longTerm, UserEnums.MEMBER);
}

View File

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

View File

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

View File

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

View File

@ -87,6 +87,9 @@ public class DateUtil {
* @return
*/
public static Date endOfDate(Date date) {
if (date == null) {
date = new Date();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
@ -148,18 +151,18 @@ public class DateUtil {
* @return
*/
public static Long[] getLastMonth() {
// 取得系统当前时间
//取得系统当前时间
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
// 取得系统当前时间所在月第一天时间对象
//取得系统当前时间所在月第一天时间对象
cal.set(Calendar.DAY_OF_MONTH, 1);
// 日期减一,取得上月最后一天时间对象
//日期减一,取得上月最后一天时间对象
cal.add(Calendar.DAY_OF_MONTH, -1);
// 输出上月最后一天日期
//输出上月最后一天日期
int day = cal.get(Calendar.DAY_OF_MONTH);
String months = "";
@ -194,21 +197,23 @@ public class DateUtil {
/**
* 把日期转换成字符串型
*
* @param date 日期
* @param date 日期
* @return
*/
public static String toString(Date date) {
return toString(date,STANDARD_FORMAT);
return toString(date, STANDARD_FORMAT);
}
/**
* 把日期转换成字符串型
*
* @param Long 日期
* @param Long 日期
* @return
*/
public static String toString(Long date) {
return toString(date,STANDARD_FORMAT);
return toString(date, STANDARD_FORMAT);
}
/**
* 把日期转换成字符串型
*
@ -355,7 +360,7 @@ public class DateUtil {
*/
public static Integer getDelayTime(Long startTime) {
int time = Math.toIntExact((startTime - System.currentTimeMillis()) / 1000);
// 如果时间为负数则改为一秒后执行
//如果时间为负数则改为一秒后执行
if (time <= 0) {
time = 1;
}

View File

@ -43,14 +43,14 @@ public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {
out.nullValue();
return;
}
// Retrieve the original (not proxy) class
//Retrieve the original (not proxy) class
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));
// Get a filled instance of the original class
//Get a filled instance of the original class
Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
.getImplementation();
// Serialize the value
//Serialize the value
delegate.write(out, unproxiedValue);
}
}

View File

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

View File

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

View File

@ -17,10 +17,10 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SpelUtil {
// spel表达式解析器
//spel表达式解析器
private static SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
// 参数名发现器
//参数名发现器
private static DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/**
@ -30,8 +30,8 @@ public class SpelUtil {
* @param spel
* @return
*/
public static String compileParams(JoinPoint joinPoint, String spel) { // Spel表达式解析日志信息
// 获得方法参数名数组
public static String compileParams(JoinPoint joinPoint, String spel) { //Spel表达式解析日志信息
//获得方法参数名数组
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod());
@ -41,7 +41,7 @@ public class SpelUtil {
//获取方法参数值
Object[] args = joinPoint.getArgs();
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();
}
@ -55,8 +55,8 @@ public class SpelUtil {
* @param spel
* @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();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(signature.getMethod());
@ -66,7 +66,7 @@ public class SpelUtil {
//获取方法参数值
Object[] args = joinPoint.getArgs();
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);
return spelExpressionParser.parseExpression(spel).getValue(context).toString();

View File

@ -22,13 +22,13 @@ public class ImageUtil {
*/
public static void addWatermark(BufferedImage oriImage, String text) {
Graphics2D graphics2D = oriImage.createGraphics();
// 设置水印文字颜色
//设置水印文字颜色
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 设置水印文字Font
//设置水印文字Font
graphics2D.setColor(Color.black);
// 设置水印文字透明度
//设置水印文字透明度
graphics2D.setFont(new Font("宋体", Font.BOLD, 30));
// 第一参数->设置的内容后面两个参数->文字在图片上的坐标位置(x,y)
//第一参数->设置的内容后面两个参数->文字在图片上的坐标位置(x,y)
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
graphics2D.drawString(text, 10, 40);
graphics2D.dispose();
@ -44,40 +44,40 @@ public class ImageUtil {
*/
public static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage,
int x, int y) {
// 临时数组遍历用于高斯模糊存周边像素值
//临时数组遍历用于高斯模糊存周边像素值
int[][] matrix = new int[3][3];
int[] values = new int[9];
int xLength = templateImage.getWidth();
int yLength = templateImage.getHeight();
// 模板图像宽度
//模板图像宽度
for (int i = 0; i < xLength; i++) {
// 模板图片高度
//模板图片高度
for (int j = 0; j < yLength; j++) {
// 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
//如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
int rgb = templateImage.getRGB(i, j);
if (rgb < 0) {
newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));
// 抠图区域高斯模糊
//抠图区域高斯模糊
readPixel(oriImage, x + i, y + j, values);
fillMatrix(matrix, values);
oriImage.setRGB(x + i, y + j, avgMatrix(matrix));
}
// 防止数组越界判断
//防止数组越界判断
if (i == (xLength - 1) || j == (yLength - 1)) {
continue;
}
int rightRgb = templateImage.getRGB(i + 1, j);
int downRgb = templateImage.getRGB(i, j + 1);
// 描边处理,取带像素和无像素的界点判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
//描边处理,取带像素和无像素的界点判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0)
|| (rgb < 0 && downRgb >= 0)) {
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();
Map<String, Object> pictureMap = new HashMap<>();
// 拼图
//拼图
BufferedImage sliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(sliderFile.getBase64()));
int sliderWidth = sliderImage.getWidth();
int sliderHeight = sliderImage.getHeight();
// 原图
//原图
BufferedImage originalImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(originalFile.getBase64()));
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
// 随机生成抠图坐标X,Y
// X轴距离右端targetWidth Y轴距离底部targetHeight以上
//随机生成抠图坐标X,Y
//X轴距离右端targetWidth Y轴距离底部targetHeight以上
int randomX = random.nextInt(originalWidth - 3 * sliderWidth) + 2 * sliderWidth;
int randomY = random.nextInt(originalHeight - sliderHeight);
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());
// 得到画笔对象
//得到画笔对象
Graphics2D graphics = newImage.createGraphics();
// 如果需要生成RGB格式需要做如下配置,Transparency 设置透明
//如果需要生成RGB格式需要做如下配置,Transparency 设置透明
newImage = graphics.getDeviceConfiguration().createCompatibleImage(sliderWidth, sliderHeight,
Transparency.TRANSLUCENT);
// 新建的图像根据模板颜色赋值,源图生成遮罩
//新建的图像根据模板颜色赋值,源图生成遮罩
ImageUtil.cutByTemplate(originalImage, sliderImage, newImage, randomX, randomY);
// 设置抗锯齿的属性
//设置抗锯齿的属性
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
graphics.drawImage(newImage, 0, 0, null);
@ -79,19 +79,19 @@ public class SliderImageUtil {
//添加水印
ImageUtil.addWatermark(originalImage, "请滑动拼图");
ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();// 新建流
ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);// 利用ImageIO类提供的write方法将bi以png图片的数据模式写入流
ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();//新建流
ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);//利用ImageIO类提供的write方法将bi以png图片的数据模式写入流
byte[] newImagery = newImageOs.toByteArray();
ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();// 新建流
ImageIO.write(originalImage, IMG_FILE_TYPE, oriImagesOs);// 利用ImageIO类提供的write方法将bi以jpg图片的数据模式写入流
ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();//新建流
ImageIO.write(originalImage, IMG_FILE_TYPE, oriImagesOs);//利用ImageIO类提供的write方法将bi以jpg图片的数据模式写入流
byte[] oriImageByte = oriImagesOs.toByteArray();
pictureMap.put("slidingImage", "data:image/png;base64," + Base64Utils.encodeToString(newImagery));
pictureMap.put("backImage", "data:image/png;base64," + Base64Utils.encodeToString(oriImageByte));
// x轴
// x轴
pictureMap.put("randomX", randomX);
// y轴
// y轴
pictureMap.put("randomY", randomY);
pictureMap.put("originalHeight", originalHeight);

View File

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

View File

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

View File

@ -62,9 +62,9 @@ public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
}
restBuilder.setRequestConfigCallback(requestConfigBuilder ->
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.
.setConnectionRequestTimeout(2 * 1000)); // time to fetch a connection from the connection pool 0 for infinite.
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.
.setConnectionRequestTimeout(2 * 1000)); //time to fetch a connection from the connection pool 0 for infinite.
client = new RestHighLevelClient(restBuilder);
return client;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -107,7 +107,7 @@ public class AuthWeiboRequest extends AuthDefaultRequest {
.msg(object.getString("error"))
.build();
}
// 返回 result = true 表示取消授权成功否则失败
//返回 result = true 表示取消授权成功否则失败
AuthResponseStatus status = object.getBooleanValue("result") ? AuthResponseStatus.SUCCESS : AuthResponseStatus.FAILURE;
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 用户信息
*/
public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据
//被加密的数据
byte[] dataByte = Base64.getDecoder().decode(encryptedData);
// 加密秘钥
//加密秘钥
byte[] keyByte = Base64.getDecoder().decode(sessionKey);
// 偏移量
//偏移量
byte[] ivByte = Base64.getDecoder().decode(iv);
try {
// 如果密钥不足16位那么就补足. 这个if 中的内容很重要
//如果密钥不足16位那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 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);
keyByte = temp;
}
// 初始化
//初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
// 初始化
//初始化
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {

View File

@ -47,9 +47,9 @@ public class AuthChecker {
if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) {
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)) {
// 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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,11 +2,14 @@ package cn.lili.modules.goods.entity.dos;
import cn.hutool.json.JSONUtil;
import cn.lili.base.BaseEntity;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.modules.goods.entity.dto.GoodsOperationDTO;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsStatusEnum;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xkcoding.http.util.StringUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@ -16,6 +19,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import java.util.Map;
/**
* 商品
@ -222,6 +226,27 @@ public class Goods extends BaseEntity {
}
//如果立即上架则
this.marketEnable = goodsOperationDTO.isRelease() ? GoodsStatusEnum.UPPER.name() : GoodsStatusEnum.DOWN.name();
this.goodsType=goodsOperationDTO.getGoodsType();
this.goodsType = goodsOperationDTO.getGoodsType();
//循环sku判定sku是否有效
for (Map<String, Object> sku : goodsOperationDTO.getSkuList()) {
//判定参数不能为空
if (sku.get("sn") == null) {
throw new ServiceException(ResultCode.GOODS_SKU_SN_ERROR);
}
if (StringUtil.isEmpty(sku.get("price").toString()) || Integer.parseInt( sku.get("price").toString()) <= 0) {
throw new ServiceException(ResultCode.GOODS_SKU_PRICE_ERROR);
}
if (StringUtil.isEmpty(sku.get("cost").toString()) || Integer.parseInt( sku.get("cost").toString()) <= 0) {
throw new ServiceException(ResultCode.GOODS_SKU_COST_ERROR);
}
if (StringUtil.isEmpty(sku.get("weight").toString()) || Integer.parseInt( sku.get("weight").toString()) < 0) {
throw new ServiceException(ResultCode.GOODS_SKU_WEIGHT_ERROR);
}
if (StringUtil.isEmpty(sku.get("quantity").toString()) || Integer.parseInt( sku.get("quantity").toString()) < 0) {
throw new ServiceException(ResultCode.GOODS_SKU_QUANTITY_ERROR);
}
}
}
}

View File

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

View File

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

View File

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

View File

@ -90,7 +90,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
public void add(List<Map<String, Object>> skuList, Goods goods) {
// 检查是否需要生成索引
List<GoodsSku> newSkuList;
// 如果有规格
//如果有规格
if (skuList != null && !skuList.isEmpty()) {
// 添加商品sku
newSkuList = this.addGoodsSku(skuList, goods);
@ -198,7 +198,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
throw new ServiceException("商品已下架");
}
}
// 获取当前商品的索引信息
//获取当前商品的索引信息
EsGoodsIndex goodsIndex = goodsIndexService.findById(skuId);
if (goodsIndex == null) {
goodsIndex = goodsIndexService.resetEsGoodsIndex(goodsSku, goodsVO.getGoodsParamsList());
@ -206,7 +206,7 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
//商品规格
GoodsSkuVO goodsSkuDetail = this.getGoodsSkuVO(goodsSku);
// 设置当前商品的促销价格
//设置当前商品的促销价格
if (goodsIndex.getPromotionMap() != null && !goodsIndex.getPromotionMap().isEmpty() && goodsIndex.getPromotionPrice() != null) {
goodsSkuDetail.setPromotionPrice(goodsIndex.getPromotionPrice());
}
@ -407,13 +407,13 @@ public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> i
goodEvaluationQueryWrapper.eq(MemberEvaluation::getSkuId, goodsSku.getId());
goodEvaluationQueryWrapper.eq(MemberEvaluation::getGrade, EvaluationGradeEnum.GOOD.name());
// 好评数量
//好评数量
int highPraiseNum = memberEvaluationService.count(goodEvaluationQueryWrapper);
// 更新商品评价数量
//更新商品评价数量
goodsSku.setCommentNum(goodsSku.getCommentNum() != null ? goodsSku.getCommentNum() + 1 : 1);
// 好评率
//好评率
double grade = NumberUtil.mul(NumberUtil.div(highPraiseNum, goodsSku.getCommentNum().doubleValue(), 2), 100);
goodsSku.setGrade(grade);
//修改规格

View File

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

View File

@ -557,9 +557,9 @@ public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> impleme
queryWrapper.like(StringUtils.isNotBlank(memberSearchVO.getUsername()), "username", memberSearchVO.getUsername());
//按照电话号码查询
queryWrapper.like(StringUtils.isNotBlank(memberSearchVO.getMobile()), "mobile", memberSearchVO.getMobile());
//按照电话号码查询
queryWrapper.like(StringUtils.isNotBlank(memberSearchVO.getDisabled()), "disabled", memberSearchVO.getDisabled());
queryWrapper.orderByDesc("create_time");
//按照状态查询
queryWrapper.eq(StringUtils.isNotBlank(memberSearchVO.getDisabled()), "disabled",
memberSearchVO.getDisabled().equals(SwitchEnum.OPEN.name()) ? 1 : 0); queryWrapper.orderByDesc("create_time");
return this.count(queryWrapper);
}

View File

@ -1,4 +1,4 @@
package cn.lili.modules.member.entity.dos;
package cn.lili.modules.message.entity.dos;
import cn.lili.base.BaseEntity;
import cn.lili.modules.message.entity.enums.MessageStatusEnum;
@ -11,7 +11,7 @@ import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 会员消息
* 会员接受消息对象
*
* @author Chopper
* @date 2020-02-25 14:10:16
@ -37,6 +37,9 @@ public class MemberMessage extends BaseEntity {
@ApiModelProperty(value = "消息内容")
private String content;
@ApiModelProperty(value = "关联消息id")
private String messageId;
/**
* @see MessageStatusEnum
*/

View File

@ -2,6 +2,7 @@ package cn.lili.modules.message.entity.dos;
import cn.lili.base.BaseEntity;
import cn.lili.modules.message.entity.enums.RangeEnum;
import cn.lili.modules.message.entity.enums.MessageSendClient;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
@ -13,6 +14,8 @@ import javax.persistence.Table;
import javax.persistence.Transient;
/**
* 管理段发送消息对象
*
* @author lili
*/
@ -37,7 +40,10 @@ public class Message extends BaseEntity {
@ApiModelProperty(value = "发送范围")
private String messageRange;
@ApiModelProperty(value = "发送客户端 商家和会员")
/**
* @see MessageSendClient
*/
@ApiModelProperty(value = "发送客户端 商家或者会员")
private String messageClient;
@Transient

View File

@ -10,7 +10,7 @@ import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 站内消息模板设置
* 通知类站内信模版对象
*
* @author Bulbasaur
* @version v4.1
@ -20,7 +20,7 @@ import javax.persistence.Table;
@Entity
@Table(name = "li_notice_message")
@TableName("li_notice_message")
@ApiModel(value = "站内消息模板")
@ApiModel(value = "通知类消息模板")
public class NoticeMessage extends BaseEntity {
private static final long serialVersionUID = 1L;

View File

@ -17,7 +17,7 @@ import javax.persistence.*;
import java.util.Date;
/**
* 店铺消息
* 店铺接收消息对象
* @author Chopper
* @date 2021/1/30 4:13 下午
*/

View File

@ -0,0 +1,27 @@
package cn.lili.modules.message.entity.enums;
/**
* 消息发送客户端
*
* @author pikachu
* @date 2020/12/8 9:46
*/
public enum MessageSendClient {
//全部用户
MEMBER("会员"),
//指定用户
STORE("店铺");
private final String description;
MessageSendClient(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}

View File

@ -1,17 +1,19 @@
package cn.lili.modules.member.entity.vo;
package cn.lili.modules.message.entity.vos;
import cn.lili.modules.message.entity.enums.MessageStatusEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 会员消息查询
* 会员接收消息查询vo
*
* @author Chopper
* @date 2020-02-25 14:10:16
* @date 2020/12/2 17:50
*/
@Data
@ApiModel(value = "会员接收消息查询vo")
public class MemberMessageQueryVO {
private static final long serialVersionUID = 1L;
@ -22,6 +24,9 @@ public class MemberMessageQueryVO {
@ApiModelProperty(value = "状态")
private String status;
@ApiModelProperty(value = "消息id")
private String messageId;
@ApiModelProperty(value = "消息标题")
private String title;

View File

@ -1,12 +1,12 @@
package cn.lili.modules.member.mapper;
package cn.lili.modules.message.mapper;
import cn.lili.modules.member.entity.dos.MemberMessage;
import cn.lili.modules.message.entity.dos.MemberMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 会员消息数据处理层
* 会员接收到消息数据处理层
*
* @author lili
* @date 2020-02-25 14:10:16

View File

@ -4,7 +4,7 @@ import cn.lili.modules.message.entity.dos.Message;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 消息内容数据处理层
* 管理端发送消息内容数据处理层
* @author Chopper
* @date 2020/12/2 17:50
*/

View File

@ -4,7 +4,7 @@ import cn.lili.modules.message.entity.dos.NoticeMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 消息模板数据处理层
* 通知类消息模板数据处理层
*
* @author Bulbasaur
* @date 2020/12/8 9:46

View File

@ -9,7 +9,7 @@ import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* 消息发送数据处理层
* 店铺接收到消息发送数据处理层
*
* @author Chopper
* @date 2021/1/30 4:17 下午

View File

@ -1,13 +1,15 @@
package cn.lili.modules.member.service;
package cn.lili.modules.message.service;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.MemberMessage;
import cn.lili.modules.member.entity.vo.MemberMessageQueryVO;
import cn.lili.modules.message.entity.dos.MemberMessage;
import cn.lili.modules.message.entity.vos.MemberMessageQueryVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* 消息发送业务层
* 会员消息发送业务层
*
* @author Chopper
* @date 2020/11/17 3:44 下午
@ -41,4 +43,13 @@ public interface MemberMessageService extends IService<MemberMessage> {
Boolean deleteMessage(String messageId);
/**
* 保存消息信息
*
* @param messages 消息
* @return
*/
boolean save(List<MemberMessage> messages);
}

View File

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* 消息内容业务层
* 管理端发送消息内容业务层
*
* @author Chopper
* @date 2020/11/17 3:44 下午

View File

@ -7,7 +7,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* 消息模板业务层
* 通知类消息模板业务层
*
* @author Bulbasaur
* @date 2020/12/8 9:47

View File

@ -9,7 +9,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* 消息发送业务层
* 店铺接收消息业务层
*
* @author Chopper
* @date 2020/11/17 3:44 下午
@ -34,7 +34,7 @@ public interface StoreMessageService extends IService<StoreMessage> {
IPage<StoreMessage> getPage(StoreMessageQueryVO storeMessageQueryVO, PageVO pageVO);
/**
* 保存消息信息
* 保存店铺消息信息
*
* @param messages 消息
* @return

View File

@ -1,21 +1,23 @@
package cn.lili.modules.member.serviceimpl;
package cn.lili.modules.message.serviceimpl;
import cn.lili.common.utils.PageUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.MemberMessage;
import cn.lili.modules.member.entity.vo.MemberMessageQueryVO;
import cn.lili.modules.member.mapper.MemberMessageMapper;
import cn.lili.modules.member.service.MemberMessageService;
import cn.lili.modules.message.entity.dos.MemberMessage;
import cn.lili.modules.message.mapper.MemberMessageMapper;
import cn.lili.modules.message.service.MemberMessageService;
import cn.lili.modules.message.entity.vos.MemberMessageQueryVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 会员消息业务层实现
* 会员接收消息业务层实现
*
* @author Chopper
* @date 2020/11/17 3:48 下午
@ -28,6 +30,8 @@ public class MemberMessageServiceImpl extends ServiceImpl<MemberMessageMapper, M
@Override
public IPage<MemberMessage> getPage(MemberMessageQueryVO memberMessageQueryVO, PageVO pageVO) {
QueryWrapper<MemberMessage> queryWrapper = new QueryWrapper<>();
//消息id
queryWrapper.like(StringUtils.isNotEmpty(memberMessageQueryVO.getMessageId()), "message_id", memberMessageQueryVO.getMessageId());
//消息标题
queryWrapper.like(StringUtils.isNotEmpty(memberMessageQueryVO.getTitle()), "title", memberMessageQueryVO.getTitle());
//会员id
@ -61,4 +65,9 @@ public class MemberMessageServiceImpl extends ServiceImpl<MemberMessageMapper, M
}
return false;
}
@Override
public boolean save(List<MemberMessage> messages) {
return saveBatch(messages);
}
}

View File

@ -17,7 +17,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 消息内容业务层实现
* 管理端发送消息内容业务层实现
*
* @author Chopper
* @date 2020/11/17 3:48 下午

View File

@ -22,7 +22,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
/**
* 消息模板业务层实现
* 通知类消息模板业务层实现
*
* @author Bulbasaur
* @date 2020/12/8 9:48

View File

@ -180,7 +180,7 @@ public class WechatMPMessageServiceImpl extends ServiceImpl<WechatMPMessageMappe
class WechatMPMessageData {
/**
* 场景描述 // 等于本服务器模版名称
* 场景描述 // 等于本服务器模版名称
*/
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;
Map<String, String> map = new HashMap<>();
// 用户id
//用户id
map.put("touser", connect.getUnionId());
//模版id
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;
Map<String, Object> map = new HashMap<>();
// 用户id
//用户id
map.put("touser", connect.getUnionId());
//模版id
map.put("template_id", wechatMPMessage.getCode());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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