| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270 |
- package com.cyksj.service.coupon.impl;
- import cn.hutool.core.date.DateTime;
- import cn.hutool.core.date.DateUtil;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.cyksj.common.exception.BusinessRuntimeException;
- import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
- import com.cyksj.common.util.Jsons;
- import com.cyksj.mapper.manage.coupon.*;
- import com.cyksj.model.entity.Coupon;
- import com.cyksj.model.entity.CouponActive;
- import com.cyksj.model.entity.CouponUser;
- import com.cyksj.model.request.CouponCollectReq;
- import com.cyksj.model.views.*;
- import com.cyksj.service.coupon.CouponFontService;
- import com.ejlchina.searcher.BeanSearcher;
- import com.ejlchina.searcher.param.Operator;
- import com.ejlchina.searcher.util.MapUtils;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.dao.DuplicateKeyException;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Optional;
- /*
- *项目名: netflix
- *文件名: CouponFontServiceImpl
- *创建者: JavaZou
- *创建时间:2022/11/18 13:34
- */
- @Service
- @RequiredArgsConstructor
- @Slf4j
- public class CouponFontServiceImpl implements CouponFontService {
- private final CouponMapper couponMapper;
- private final CouponActiveMapper couponActiveMapper;
- private final CouponUserMapper couponUserMapper;
- private final BeanSearcher beanSearcher;
- private final CouponSkuMapper couponSkuMapper;
- private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
- private final CouponRecommendMapper recommendMapper;
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public void collectCoupon(CouponCollectReq couponCollectReq, Long userId) {
- collectCommonCheck(couponCollectReq, userId);
- CouponActive couponActive = couponActiveMapper.selectById(couponCollectReq.getCouponActiveId());
- if (couponActive == null) {
- throw BusinessRuntimeException.getInstance("该发放优惠券不存在");
- }
- if (couponActive.getRemainNum() <= 0) {
- throw BusinessRuntimeException.getInstance("该优惠券已领取完");
- }
- CouponUser couponUser = new CouponUser();
- couponUser.setUserId(userId);
- couponUser.setCouponId(couponCollectReq.getCouponId());
- //领券中心
- couponUser.setChannel(CouponUser.Channel.center);
- couponUser.setStatus(CouponUser.Status.unused);
- couponUser.setCouponActiveId(couponCollectReq.getCouponActiveId());
- //优惠券有效时间
- this.updateCouponUserValidTime(couponActive.getCouponId(), couponUser);
- try {
- couponUserMapper.insert(couponUser);
- } catch (DuplicateKeyException e) {
- log.info("用户:{}重复领取优惠券{}插入数据错误", userId, couponCollectReq.getCouponId());
- throw BusinessRuntimeException.getInstance("已领取成功");
- }
- if (couponActive != null) {
- //发放优惠券记录剩余数量
- Integer remainNum = couponActive.getRemainNum();
- Integer update = couponActiveMapper.subRemainNum(couponActive.getId(), remainNum);
- if (update != 1) {
- throw BusinessRuntimeException.getInstance("系统繁忙,请稍后再试..");
- }
- }
- }
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public void collectRecommendCoupon(CouponCollectReq couponCollectReq, Long userId) {
- collectCommonCheck(couponCollectReq, userId);
- CouponUser couponUser = new CouponUser();
- couponUser.setUserId(userId);
- couponUser.setCouponId(couponCollectReq.getCouponId());
- //推荐渠道
- couponUser.setChannel(CouponUser.Channel.recommend);
- couponUser.setStatus(CouponUser.Status.unused);
- couponUser.setRecommendId(couponCollectReq.getCouponRecommendId());
- //优惠券有效时间
- this.updateCouponUserValidTime(couponCollectReq.getCouponId(), couponUser);
- try {
- couponUserMapper.insert(couponUser);
- } catch (DuplicateKeyException e) {
- log.info("用户:{}重复领取推荐优惠券{}插入数据错误", userId, couponCollectReq.getCouponId());
- throw BusinessRuntimeException.getInstance("已领取成功");
- }
- }
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public void collectWholeRecommendCoupon(Long userId) {
- CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
- Boolean isNewUser = true;
- if (couponNewUserView != null) {
- isNewUser = false;
- }
- //查询所有可领取的推荐优惠券
- List<CouponAvailableRecommendView> couponAvailableRecommendViews = recommendMapper.getRecommendCouponList(userId, isNewUser);
- couponAvailableRecommendViews.stream().forEach(data -> {
- //领取优惠券
- CouponUser couponUser = new CouponUser();
- couponUser.setUserId(userId);
- couponUser.setCouponId(data.getCouponId());
- //推荐渠道
- couponUser.setChannel(CouponUser.Channel.recommend);
- couponUser.setStatus(CouponUser.Status.unused);
- couponUser.setRecommendId(data.getRecommendId());
- //优惠券有效时间
- this.updateCouponUserValidTime(data.getCouponId(), couponUser);
- try {
- couponUserMapper.insert(couponUser);
- } catch (DuplicateKeyException e) {
- //插入失败继续插入 不影响
- log.info("用户:{}一键领取推荐优惠券{}插入数据错误", userId, data.getCouponId());
- }
- });
- }
- @Override
- public Page<CouponUserView> getAvailableCouponList(Long skuId, Long couponId, Long userId, Boolean isRenew, Long start, Long limit) {
- DateTime now = DateTime.now();
- Long goodsId = null;
- //实物还是虚物
- GoodsDonSkuView goodsDonSkuView = beanSearcher.searchFirst(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getSkuId, skuId).op(Operator.Equal).build());
- BigDecimal skuMoney = goodsDonSkuView.getMoney();
- if (goodsDonSkuView.getType() == 2) {
- goodsId = goodsDonSkuView.getGoodsId();
- }
- Page<CouponUserView> availableCouponList = couponUserMapper.getAvailableCouponList(skuId, couponId, goodsId, userId, isRenew, new Page<>(start, limit));
- Optional.ofNullable(availableCouponList).ifPresent(page->{
- page.getRecords().stream().forEach(data->{
- String str = couponSkuMapper.selectGoodsSkuStr(data.getCouponId());
- data.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
- List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(data.getCouponId());
- try {
- data.setGoodsSkuIds(Jsons.toJson(couponSkus));
- } catch (Exception e) {
- }
- if (!data.getIsAvailable()) {
- data.setReason(String.format("仅限%s", data.getGoodsSkuStr()));
- if (isRenew != null && isRenew && data.getIsRenew()) {
- data.setReason(String.format("%s续费时可使用", data.getReason()));
- }
- }
- if (goodsDonSkuView.getType() == 2 && data.getType() == Coupon.Type.reduce) {
- if (data.getIsAvailable() && skuMoney.compareTo(data.getReduceCondition()) < 0) {
- data.setIsAvailable(false);
- data.setReason(String.format("满%s可用", data.getReduceCondition().divide(BigDecimal.valueOf(100))));
- }
- }
- if (isRenew != null && isRenew && !data.getIsRenew()) {
- data.setReason(String.format("续费时,不可使用"));
- }
- //为了重新校验
- data.setCouponUserStatus(CouponUser.Status.unused);
- this.setCouponUserStatus(data, now);
- });
- });
- if (goodsDonSkuView.getType() == 2) {
- availableCouponList.getRecords().sort(Comparator.comparing(CouponUserView::getIsAvailable).reversed());
- }
- return availableCouponList;
- }
- /**
- * 设置用户优惠券状态
- */
- @Override
- public void setCouponUserStatus(CouponUserView data, DateTime now) {
- Boolean isFlag = false;
- if (data.getCouponUserStatus() == CouponUser.Status.unused) {
- if (data.getExpiryStatus() != null && !data.getExpiryStatus()) {
- data.setCouponUserStatus(CouponUser.Status.invalid);
- data.setIsAvailable(false);
- data.setReason("该优惠券已失效");
- isFlag = true;
- } else if (now.isAfter(data.getValidEndTime())) {
- data.setCouponUserStatus(CouponUser.Status.expired);
- data.setIsAvailable(false);
- data.setReason("该优惠券已过期");
- isFlag = true;
- } else if (now.isBefore(data.getValidStartTime())) {
- data.setCouponUserStatus(CouponUser.Status.notEffective);
- data.setIsAvailable(false);
- data.setReason("该优惠券未生效");
- isFlag = true;
- }
- }
- if (isFlag) {
- TASK_EXECUTOR.execute(() -> {
- if (data.getCouponUserStatus() != CouponUser.Status.notEffective) {
- CouponUser couponUser = new CouponUser();
- couponUser.setId(data.getId());
- couponUser.setStatus(data.getCouponUserStatus());
- couponUserMapper.updateById(couponUser);
- }
- });
- }
- }
- @Override
- public Integer collectRecommendCouponNum(Long userId, Boolean isNewUser) {
- List<CouponAvailableRecommendView> recommendCouponList = Optional.ofNullable(recommendMapper.getRecommendCouponList(userId, isNewUser)).orElse(new ArrayList<>());
- return recommendCouponList.size();
- }
- public void collectCommonCheck(CouponCollectReq couponCollectReq, Long userId) {
- Coupon coupon = couponMapper.selectById(couponCollectReq.getCouponId());
- if (coupon == null || !coupon.getDeleted()) {
- throw BusinessRuntimeException.getInstance("该优惠券不存在");
- }
- //是否可领取
- if (coupon.getScope() == Coupon.Scope.newUser) {
- //注册后从没产生过虚拟订单的用户,产生过退款后也不是新用户
- CouponNewUserView couponNewUserView = beanSearcher.searchFirst(CouponNewUserView.class, MapUtils.builder().field(CouponNewUserView::getUserId, userId).op(Operator.Equal).build());
- if (couponNewUserView != null) {
- throw BusinessRuntimeException.getInstance("该优惠券只能新用户才能领取");
- }
- }
- CouponUser couponUser = couponUserMapper.selectOne(Wrappers.lambdaQuery(CouponUser.class).eq(CouponUser::getUserId, userId).eq(CouponUser::getCouponId, couponCollectReq.getCouponId()));
- if (couponUser != null) {
- if (couponUser.getChannel() == CouponUser.Channel.exCode) {
- throw BusinessRuntimeException.getInstance("您已兑换过该优惠券..");
- }
- throw BusinessRuntimeException.getInstance("您已领取该优惠券..");
- }
- }
- @Override
- public void updateCouponUserValidTime(Long couponId, CouponUser couponUser) {
- Coupon entity = couponMapper.getCouponById(couponId);
- Optional.ofNullable(entity).ifPresent(coupon->{
- if (coupon.getIsValidTime()) {
- couponUser.setValidStartTime(coupon.getValidStartTime());
- couponUser.setValidEndTime(coupon.getValidEndTime());
- } else {
- couponUser.setValidStartTime(DateTime.now());
- couponUser.setValidEndTime(DateUtil.offsetDay(couponUser.getValidStartTime(), coupon.getValidDays()));
- }
- });
- }
- }
|