CouponFontServiceImpl.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package com.cyksj.service.coupon.impl;
  2. import cn.hutool.core.date.DateTime;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.lang.Assert;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  8. import com.cyksj.common.exception.BusinessRuntimeException;
  9. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  10. import com.cyksj.common.util.Jsons;
  11. import com.cyksj.mapper.channel.ChannelPopularizeMapper;
  12. import com.cyksj.mapper.manage.coupon.*;
  13. import com.cyksj.model.entity.*;
  14. import com.cyksj.model.request.ChannelPopularizeCouponReq;
  15. import com.cyksj.model.request.CouponCollectReq;
  16. import com.cyksj.model.views.*;
  17. import com.cyksj.service.coupon.CouponFontService;
  18. import com.ejlchina.searcher.BeanSearcher;
  19. import com.ejlchina.searcher.param.Operator;
  20. import com.ejlchina.searcher.util.MapUtils;
  21. import lombok.RequiredArgsConstructor;
  22. import lombok.extern.slf4j.Slf4j;
  23. import org.springframework.dao.DuplicateKeyException;
  24. import org.springframework.stereotype.Service;
  25. import org.springframework.transaction.annotation.Transactional;
  26. import java.math.BigDecimal;
  27. import java.util.ArrayList;
  28. import java.util.Comparator;
  29. import java.util.List;
  30. import java.util.Optional;
  31. /*
  32. *项目名: netflix
  33. *文件名: CouponFontServiceImpl
  34. *创建者: JavaZou
  35. *创建时间:2022/11/18 13:34
  36. */
  37. @Service
  38. @RequiredArgsConstructor
  39. @Slf4j
  40. public class CouponFontServiceImpl implements CouponFontService {
  41. private final CouponMapper couponMapper;
  42. private final CouponActiveMapper couponActiveMapper;
  43. private final CouponUserMapper couponUserMapper;
  44. private final BeanSearcher beanSearcher;
  45. private final CouponSkuMapper couponSkuMapper;
  46. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  47. private final CouponRecommendMapper recommendMapper;
  48. private final ChannelPopularizeMapper channelPopularizeMapper;
  49. @Override
  50. @Transactional(rollbackFor = Throwable.class)
  51. public void collectCoupon(CouponCollectReq couponCollectReq, Long userId) {
  52. collectCommonCheck(couponCollectReq.getCouponId(), userId);
  53. CouponActive couponActive = couponActiveMapper.selectById(couponCollectReq.getCouponActiveId());
  54. if (couponActive == null) {
  55. throw BusinessRuntimeException.getInstance("该发放优惠券不存在");
  56. }
  57. if (couponActive.getRemainNum() <= 0) {
  58. throw BusinessRuntimeException.getInstance("该优惠券已领取完");
  59. }
  60. receiveCouponUser(couponCollectReq.getCouponId(), userId, CouponUser.Channel.center);
  61. if (couponActive != null) {
  62. //发放优惠券记录剩余数量
  63. Integer remainNum = couponActive.getRemainNum();
  64. Integer update = couponActiveMapper.subRemainNum(couponActive.getId(), remainNum);
  65. if (update != 1) {
  66. throw BusinessRuntimeException.getInstance("系统繁忙,请稍后再试..");
  67. }
  68. }
  69. }
  70. @Override
  71. @Transactional(rollbackFor = Throwable.class)
  72. public void collectRecommendCoupon(CouponCollectReq couponCollectReq, Long userId) {
  73. collectCommonCheck(couponCollectReq.getCouponId(), userId);
  74. receiveCouponUser(couponCollectReq.getCouponId(), userId, CouponUser.Channel.recommend);
  75. }
  76. @Override
  77. @Transactional(rollbackFor = Throwable.class)
  78. public void collectWholeRecommendCoupon(Long userId) {
  79. CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
  80. Boolean isNewUser = true;
  81. if (couponNewUserView != null) {
  82. isNewUser = false;
  83. }
  84. //查询所有可领取的推荐优惠券
  85. List<CouponAvailableRecommendView> couponAvailableRecommendViews = recommendMapper.getRecommendCouponList(userId, isNewUser);
  86. couponAvailableRecommendViews.stream().forEach(data -> {
  87. //领取优惠券
  88. CouponUser couponUser = new CouponUser();
  89. couponUser.setUserId(userId);
  90. couponUser.setCouponId(data.getCouponId());
  91. //推荐渠道
  92. couponUser.setChannel(CouponUser.Channel.recommend);
  93. couponUser.setStatus(CouponUser.Status.unused);
  94. couponUser.setRecommendId(data.getRecommendId());
  95. //优惠券有效时间
  96. this.updateCouponUserValidTime(data.getCouponId(), couponUser);
  97. try {
  98. couponUserMapper.insert(couponUser);
  99. } catch (DuplicateKeyException e) {
  100. //插入失败继续插入 不影响
  101. log.info("用户:{}一键领取推荐优惠券{}插入数据错误", userId, data.getCouponId());
  102. }
  103. });
  104. }
  105. @Override
  106. public Page<CouponUserView> getAvailableCouponList(Long skuId, Long couponId, Long userId, Boolean isRenew, Long start, Long limit) {
  107. DateTime now = DateTime.now();
  108. Long goodsId = null;
  109. //实物还是虚物
  110. GoodsDonSkuView goodsDonSkuView = beanSearcher.searchFirst(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuId).op(Operator.Equal).build());
  111. BigDecimal skuMoney = goodsDonSkuView.getMoney();
  112. if (goodsDonSkuView.getType() == 2) {
  113. goodsId = goodsDonSkuView.getGoodsId();
  114. }
  115. Page<CouponUserView> availableCouponList = couponUserMapper.getAvailableCouponList(skuId, couponId, goodsId, userId, isRenew, new Page<>(start, limit));
  116. Optional.ofNullable(availableCouponList).ifPresent(page->{
  117. page.getRecords().stream().forEach(data->{
  118. String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
  119. data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
  120. List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(data.getCouponId());
  121. try {
  122. data.setGoodsSkuIds(Jsons.toJson(couponSkus));
  123. } catch (Exception e) {
  124. }
  125. if (!data.getIsAvailable()) {
  126. data.setReason(String.format("仅限%s", data.getGoodsSkuStr()));
  127. if (data.getUseScope() == Coupon.UseScope.renew) {
  128. data.setReason(String.format("%s续费时可使用", data.getReason()));
  129. } else if (data.getUseScope() == Coupon.UseScope.orders) {
  130. data.setReason(String.format("%s下单时可使用", data.getReason()));
  131. }
  132. }
  133. if (goodsDonSkuView.getType() == 2 && data.getType() == Coupon.Type.reduce) {
  134. if (data.getIsAvailable() && skuMoney.compareTo(data.getReduceCondition()) < 0) {
  135. data.setIsAvailable(false);
  136. data.setReason(String.format("满%s可用", data.getReduceCondition().divide(BigDecimal.valueOf(100))));
  137. }
  138. }
  139. if (isRenew != null && isRenew && data.getUseScope() == Coupon.UseScope.orders) {
  140. data.setReason("仅下单可使用");
  141. }
  142. //为了重新校验
  143. data.setCouponUserStatus(CouponUser.Status.unused);
  144. this.setCouponUserStatus(data, now);
  145. });
  146. });
  147. if (goodsDonSkuView.getType() == 2) {
  148. availableCouponList.getRecords().sort(Comparator.comparing(CouponUserView::getIsAvailable).reversed());
  149. }
  150. return availableCouponList;
  151. }
  152. /**
  153. * 设置用户优惠券状态
  154. */
  155. @Override
  156. public void setCouponUserStatus(CouponUserView data, DateTime now) {
  157. Boolean isFlag = false;
  158. if (data.getCouponUserStatus() == CouponUser.Status.unused) {
  159. if (data.getExpiryStatus() != null && !data.getExpiryStatus()) {
  160. data.setCouponUserStatus(CouponUser.Status.invalid);
  161. data.setIsAvailable(false);
  162. data.setReason("该优惠券已失效");
  163. isFlag = true;
  164. } else if (now.isAfter(data.getValidEndTime())) {
  165. data.setCouponUserStatus(CouponUser.Status.expired);
  166. data.setIsAvailable(false);
  167. data.setReason("该优惠券已过期");
  168. isFlag = true;
  169. } else if (now.isBefore(data.getValidStartTime())) {
  170. data.setCouponUserStatus(CouponUser.Status.notEffective);
  171. data.setIsAvailable(false);
  172. data.setReason("该优惠券未生效");
  173. isFlag = true;
  174. }
  175. }
  176. if (isFlag) {
  177. TASK_EXECUTOR.execute(() -> {
  178. if (data.getCouponUserStatus() != CouponUser.Status.notEffective) {
  179. CouponUser couponUser = new CouponUser();
  180. couponUser.setId(data.getId());
  181. couponUser.setStatus(data.getCouponUserStatus());
  182. couponUserMapper.updateById(couponUser);
  183. }
  184. });
  185. }
  186. }
  187. @Override
  188. public Integer collectRecommendCouponNum(Long userId, Boolean isNewUser) {
  189. List<CouponAvailableRecommendView> recommendCouponList = Optional.ofNullable(recommendMapper.getRecommendCouponList(userId, isNewUser)).orElse(new ArrayList<>());
  190. return recommendCouponList.size();
  191. }
  192. public void collectCommonCheck(Long couponId, Long userId) {
  193. Coupon coupon = couponMapper.selectById(couponId);
  194. if (coupon == null || !coupon.getDeleted()) {
  195. throw BusinessRuntimeException.getInstance("该优惠券不存在");
  196. }
  197. //是否可领取
  198. if (coupon.getScope() == Coupon.Scope.newUser) {
  199. //注册后从没产生过虚拟订单的用户,产生过退款后也不是新用户
  200. CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
  201. if (couponNewUserView != null) {
  202. throw BusinessRuntimeException.getInstance("该优惠券只能新用户才能领取");
  203. }
  204. }
  205. CouponUser couponUser = couponUserMapper.selectOne(Wrappers.lambdaQuery(CouponUser.class).eq(CouponUser::getUserId, userId).eq(CouponUser::getCouponId, couponId));
  206. if (couponUser != null) {
  207. if (couponUser.getChannel() == CouponUser.Channel.exCode) {
  208. throw BusinessRuntimeException.getInstance("您已兑换过该优惠券..");
  209. }
  210. throw BusinessRuntimeException.getInstance("您已领取该优惠券..");
  211. }
  212. }
  213. @Override
  214. public void updateCouponUserValidTime(Long couponId, CouponUser couponUser) {
  215. Coupon entity = couponMapper.getCouponById(couponId);
  216. Optional.ofNullable(entity).ifPresent(coupon->{
  217. if (coupon.getIsValidTime()) {
  218. couponUser.setValidStartTime(coupon.getValidStartTime());
  219. couponUser.setValidEndTime(coupon.getValidEndTime());
  220. } else {
  221. couponUser.setValidStartTime(DateTime.now());
  222. couponUser.setValidEndTime(DateUtil.offsetDay(couponUser.getValidStartTime(), coupon.getValidDays()));
  223. }
  224. });
  225. }
  226. @Override
  227. public void updateOrderDonCouponStatus(OrderDon orderDon) {
  228. log.info("订单:{}退款,优惠券返还start...", orderDon.getId());
  229. CouponUser couponUser = couponUserMapper.selectById(orderDon.getCouponUserId());
  230. if (CouponUser.Channel.exCode == couponUser.getChannel()) {
  231. //兑换码兑换的优惠券退款时,直接删除
  232. couponUserMapper.deleteById(couponUser.getId());
  233. } else {
  234. CouponUserView couponUserView = beanSearcher.searchFirst(CouponUserView.class, MapUtils.builder()
  235. .field(CouponUserView::getCouponId, couponUser.getCouponId()).op(Operator.Equal)
  236. .field(CouponUserView::getUserId, orderDon.getUserId()).op(Operator.Equal)
  237. .build());
  238. couponUserView.setCouponUserStatus(CouponUser.Status.unused);
  239. this.setCouponUserStatus(couponUserView, DateTime.now());
  240. couponUser.setStatus(couponUserView.getCouponUserStatus());
  241. couponUserMapper.updateById(couponUser);
  242. }
  243. log.info("订单:{}退款,优惠券返还end...", orderDon.getId());
  244. }
  245. @Override
  246. public void receiveChannelPopularizeCoupon(ChannelPopularizeCouponReq req) {
  247. Long userId = req.getUserId();
  248. Long popularizeId = req.getPopularizeId();
  249. Long couponId = req.getCouponId();
  250. //渠道链接是否存在
  251. ChannelPopularize channelPopularize = channelPopularizeMapper.selectById(popularizeId);
  252. Assert.notNull(channelPopularize, "链接不存在");
  253. //是否关联该优惠券
  254. String couponIds = channelPopularize.getCouponIds();
  255. if (StrUtil.isEmpty(couponIds)) {
  256. throw BusinessRuntimeException.getInstance("链接未关联该优惠券");
  257. }
  258. List<Long> couponIdList = null;
  259. try {
  260. couponIdList = Jsons.parseList(couponIds, Long.class);
  261. if (!couponIdList.contains(couponId)) {
  262. throw BusinessRuntimeException.getInstance("链接未关联该优惠券");
  263. }
  264. //优惠券领取状态校验
  265. collectCommonCheck(couponId, userId);
  266. //领取优惠券
  267. receiveCouponUser(couponId, userId, CouponUser.Channel.channel_popularize);
  268. } catch (Exception e) {
  269. throw BusinessRuntimeException.getInstance("链接未关联该优惠券");
  270. }
  271. }
  272. /**
  273. * 领取优惠券
  274. */
  275. public void receiveCouponUser(Long couponId, Long userId, CouponUser.Channel channel) {
  276. CouponUser couponUser = new CouponUser();
  277. couponUser.setUserId(userId);
  278. couponUser.setCouponId(couponId);
  279. couponUser.setChannel(channel);
  280. couponUser.setStatus(CouponUser.Status.unused);
  281. //优惠券有效时间
  282. this.updateCouponUserValidTime(couponId, couponUser);
  283. try {
  284. couponUserMapper.insert(couponUser);
  285. } catch (DuplicateKeyException e) {
  286. log.info("用户:{}重复领取优惠券{}插入数据错误", userId, couponId);
  287. throw BusinessRuntimeException.getInstance("已领取成功");
  288. }
  289. }
  290. }