CouponFontServiceImpl.java 15 KB

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