admin
2019-11-03 788deca1b4a24f8a24e49c24f7d89975a1d74bbe
fanli/src/main/java/com/yeshi/fanli/service/impl/user/UserSystemCouponServiceImpl.java
@@ -12,21 +12,25 @@
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.yeshi.utils.DateUtil;
import org.yeshi.utils.entity.DateInfo;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionExecuter;
import com.aliyun.openservices.ons.api.transaction.TransactionProducer;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;
import com.google.gson.Gson;
import com.yeshi.fanli.dao.mybatis.user.UserSystemCouponMapper;
import com.yeshi.fanli.dto.mq.user.UserTopicTagEnum;
import com.yeshi.fanli.dto.mq.user.body.UserSystemCouponUseMQMsg;
import com.yeshi.fanli.dto.msg.MsgOtherCouponActivateDTO;
import com.yeshi.fanli.dto.msg.MsgOtherGiveContentDTO;
import com.yeshi.fanli.dto.user.coupon.UserSystemCouponUseMQMsgDTO;
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.entity.bus.msg.MsgOtherDetail.MsgTypeOtherTypeEnum;
import com.yeshi.fanli.entity.bus.user.HongBaoV2;
@@ -36,6 +40,7 @@
import com.yeshi.fanli.entity.bus.user.UserInfo;
import com.yeshi.fanli.entity.bus.user.UserInfoExtra;
import com.yeshi.fanli.entity.bus.user.UserSystemCoupon;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponActivate;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponGiveRecord;
import com.yeshi.fanli.entity.bus.user.UserSystemCouponRecord;
import com.yeshi.fanli.entity.common.JumpDetailV2;
@@ -44,7 +49,6 @@
import com.yeshi.fanli.entity.system.SystemCoupon;
import com.yeshi.fanli.entity.system.SystemCoupon.CouponTypeEnum;
import com.yeshi.fanli.entity.taobao.TaoBaoGoodsBrief;
import com.yeshi.fanli.exception.money.UserMoneyDetailException;
import com.yeshi.fanli.exception.user.UserInfoExtraException;
import com.yeshi.fanli.exception.user.UserSystemCouponException;
import com.yeshi.fanli.log.LogHelper;
@@ -76,6 +80,7 @@
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.TokenUtil;
import com.yeshi.fanli.util.VersionUtil;
import com.yeshi.fanli.util.annotation.RequestSerializableByKeyService;
import com.yeshi.fanli.util.factory.UserMoneyDetailFactory;
import com.yeshi.fanli.util.factory.msg.MsgOtherSystemGiveDTOFactory;
import com.yeshi.fanli.util.rocketmq.MQTopicName;
@@ -161,12 +166,14 @@
   @Resource
   private TokenRecordService tokenRecordService;
   @Resource(name = "transactionManager")
   private DataSourceTransactionManager transactionManager;
   @Resource(name = "orderTransactionProducer")
   private TransactionProducer orderTransactionProducer;
   @Resource
   private UserSystemCouponActivateService userSystemCouponActivateService;
   @Override
   public int insertSelective(UserSystemCoupon record) {
@@ -877,81 +884,95 @@
         // 提成金额
         BigDecimal money = MoneyBigDecimalUtil.mul(hongBao, percent);
         UserSystemCouponUseMQMsgDTO mqMsg = new UserSystemCouponUseMQMsgDTO(userSystemCoupon.getId(),
               order.getOrderId(), sourceType);
         UserSystemCouponUseMQMsg mqMsg = new UserSystemCouponUseMQMsg(userSystemCoupon.getId(), order.getOrderId(),
               sourceType, systemCoupon.getType().name());
         // 事务消息
         Message msg = new Message(MQTopicName.TOPIC_SYSTEM_COUPON_USE.name(),systemCoupon.getType().name(),
         Message msg = new Message(MQTopicName.TOPIC_USER.name(), UserTopicTagEnum.useSystemCoupon.name(),
               new Gson().toJson(mqMsg).getBytes());
         orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
            @Override
            public TransactionStatus execute(Message arg0, Object arg1) {
               try {
                  useRewardCouponCore(userSystemCoupon, money, hongBao, uid, order);
                  return TransactionStatus.CommitTransaction;
               } catch (UserMoneyDetailException e) {
                  return TransactionStatus.RollbackTransaction;
         try {
            SendResult result = orderTransactionProducer.send(msg, new LocalTransactionExecuter() {
               @Override
               public TransactionStatus execute(Message arg0, Object arg1) {
                  try {
                     useRewardCouponCore(userSystemCoupon, money, hongBao, uid, order);
                     return TransactionStatus.CommitTransaction;
                  } catch (Exception e) {
                     return TransactionStatus.RollbackTransaction;
                  }
               }
            }
         }, null);
            }, null);
            System.out.println(result);
         } catch (Exception e) {
            throw new Exception();
         }
      }
   }
   @Transactional
   private void useRewardCouponCore(UserSystemCoupon userSystemCoupon, BigDecimal money, BigDecimal hongBao, Long uid,
         Order order) throws UserMoneyDetailException {
      // 1、插入红包数据
      HongBaoV2 hongBaoV2 = new HongBaoV2();
      hongBaoV2.setMoney(money);
      hongBaoV2.setType(HongBaoV2.TYPE_COUPON);
      hongBaoV2.setState(HongBaoV2.STATE_YILINGQU);
      hongBaoV2.setVersion(2);
      hongBaoV2.setCreateTime(new Date());
      hongBaoV2.setUpdateTime(new Date());
      hongBaoV2.setUserInfo(new UserInfo(uid));
      hongBaoV2.setPreGetTime(new Date());
      hongBaoV2.setGetTime(new Date());
      hongBaoV2Service.insertSelective(hongBaoV2);
      // 2.插入关联
      orderHongBaoMapService.addOrderHongBaoMap(hongBaoV2, order);
      // 3.插入资金明细,用户余额
      UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createOrderReward(order.getOrderId(),
            order.getOrderType(), money, new UserInfo(uid));
      userMoneyDetailService.addUserMoneyDetail(userMoneyDetail);
      userInfoService.addMoney(new UserInfo(uid), money);
      // 插入资金通知
      userMoneyMsgNotificationService.orderReward(uid, order.getOrderId(), order.getOrderType(), money,
            userInfoService.selectByPKey(uid).getMyHongBao());
      /* 用户券信息状态及记录处理 */
      Date date = new Date();
      // 更新券状态:已使用
      userSystemCoupon.setState(UserSystemCoupon.STATE_END_USE);
      userSystemCoupon.setUseTime(date);
      userSystemCoupon.setUpdateTime(date);
      userSystemCouponMapper.updateByPrimaryKeySelective(userSystemCoupon);
      // 插入使用券记录
      UserSystemCouponRecord couponRecord = new UserSystemCouponRecord();
      couponRecord.setState(UserSystemCouponRecord.STATE_SUCCESS);
      couponRecord.setGoodSource(order.getOrderType());
      couponRecord.setOrderNo(order.getOrderId());
      couponRecord.setUserSystemCoupon(userSystemCoupon);
      couponRecord.setCouponType(userSystemCoupon.getSystemCoupon().getType().name());
      couponRecord.setCreateTime(date);
      couponRecord.setUpdateTime(date);
      userSystemCouponRecordService.insertSelective(couponRecord);
      // 消息推送
   public void useRewardCouponCore(UserSystemCoupon userSystemCoupon, BigDecimal money, BigDecimal hongBao, Long uid,
         Order order) throws Exception {
      org.springframework.transaction.TransactionStatus transactionStatus = transactionManager
            .getTransaction(new DefaultTransactionDefinition());
      try {
         userOtherMsgNotificationService.rewardCouponUsed(userSystemCoupon, hongBao, money, order.getOrderId());
         // 1、插入红包数据
         HongBaoV2 hongBaoV2 = new HongBaoV2();
         hongBaoV2.setMoney(money);
         hongBaoV2.setType(HongBaoV2.TYPE_COUPON);
         hongBaoV2.setState(HongBaoV2.STATE_YILINGQU);
         hongBaoV2.setVersion(2);
         hongBaoV2.setCreateTime(new Date());
         hongBaoV2.setUpdateTime(new Date());
         hongBaoV2.setUserInfo(new UserInfo(uid));
         hongBaoV2.setPreGetTime(new Date());
         hongBaoV2.setGetTime(new Date());
         hongBaoV2Service.insertSelective(hongBaoV2);
         // 2.插入关联
         orderHongBaoMapService.addOrderHongBaoMap(hongBaoV2, order);
         // 3.插入资金明细,用户余额
         UserMoneyDetail userMoneyDetail = UserMoneyDetailFactory.createOrderReward(order.getOrderId(),
               order.getOrderType(), money, new UserInfo(uid));
         userMoneyDetailService.addUserMoneyDetail(userMoneyDetail);
         userInfoService.addMoney(new UserInfo(uid), money);
         /* 用户券信息状态及记录处理 */
         Date date = new Date();
         // 更新券状态:已使用
         userSystemCoupon.setState(UserSystemCoupon.STATE_END_USE);
         userSystemCoupon.setUseTime(date);
         userSystemCoupon.setUpdateTime(date);
         userSystemCouponMapper.updateByPrimaryKeySelective(userSystemCoupon);
         SystemCoupon coupon = systemCouponService.selectByPrimaryKey(userSystemCoupon.getSystemCoupon().getId());
         // 插入使用券记录
         UserSystemCouponRecord couponRecord = new UserSystemCouponRecord();
         couponRecord.setState(UserSystemCouponRecord.STATE_SUCCESS);
         couponRecord.setGoodSource(order.getOrderType());
         couponRecord.setOrderNo(order.getOrderId());
         couponRecord.setUserSystemCoupon(userSystemCoupon);
         couponRecord.setCouponType(coupon.getType().name());
         couponRecord.setCreateTime(date);
         couponRecord.setUpdateTime(date);
         userSystemCouponRecordService.insertSelective(couponRecord);
         // 插入资金通知
         userMoneyMsgNotificationService.orderReward(uid, order.getOrderId(), order.getOrderType(), money,
               userInfoService.selectByPKey(uid).getMyHongBao());
         // 消息推送
         try {
            userOtherMsgNotificationService.rewardCouponUsed(userSystemCoupon, hongBao, money, order.getOrderId());
         } catch (Exception e) {
            LogHelper.errorDetailInfo(e);
         }
         transactionManager.commit(transactionStatus);
      } catch (Exception e) {
         LogHelper.errorDetailInfo(e);
         e.printStackTrace();
         transactionManager.rollback(transactionStatus);
         throw new Exception();
      }
   }
@@ -1803,7 +1824,8 @@
                  if (VersionUtil.greaterThan_2_0_2(acceptData.getPlatform(), acceptData.getVersion())) {
                     int activateCount = userSystemCouponActivateService.getActivateCount(userCouponVO.getId());
                     String activateNum = configService.get("free_coupon_activate_num");
                     userCouponVO.setCouponEffect("(" + activateCount + "/"+ Integer.parseInt(activateNum) +")待激活");
                     userCouponVO.setCouponEffect(
                           "(" + activateCount + "/" + Integer.parseInt(activateNum) + ")待激活");
                  }
               } else if (CouponTypeEnum.welfareFreeCoupon == type) {
                  jumpBtn = new HashMap<String, Object>();
@@ -2078,7 +2100,6 @@
      return userCouponVO;
   }
   @Transactional
   @Override
@@ -2422,78 +2443,100 @@
      return userSystemCouponMapper.getFreeCouponByType(uid, type);
   }
   @RequestSerializableByKeyService(key = "#uid")
   @Override
   @Transactional
   public void activateFreeCoupon(Long uid) {
      List<UserSystemCoupon> list = userSystemCouponMapper.getNeedActivateFreeCouponByType(uid, CouponTypeEnum.freeCoupon.name());
      if (list == null || list.size() == 0)
   @Transactional(rollbackFor = Exception.class)
   public void triggerFreeCouponActivate(Long uid) {
      UserSystemCoupon coupon = userSystemCouponMapper.getNeedActivateCouponByType(uid,
            CouponTypeEnum.freeCoupon.name());
      if (coupon == null)
         return;
      UserSystemCoupon coupon = list.get(0);
      Date nowDate = new Date();
      Date endTime2 = coupon.getEndTime();
      if (endTime2 != null && endTime2.getTime() <= nowDate.getTime())
         return; // 已失效
      SystemCoupon systemCoupon = coupon.getSystemCoupon();
      if (systemCoupon == null)
         return; // 券已不存在
      Long id = coupon.getId();
      UserSystemCouponActivate couponActivate = userSystemCouponActivateService.selectForUpdate(id);
      systemCoupon = systemCouponService.selectByPrimaryKey(systemCoupon.getId());
      if (systemCoupon == null || systemCoupon.getType() != CouponTypeEnum.freeCoupon)
         return; // 券类型不匹配
      // 激活数量
      boolean result = false;
      int limitNum = Integer.parseInt(configService.get("free_coupon_activate_num"));
      // 添加激活数量
      String activateNum = configService.get("free_coupon_activate_num");
      boolean activate = userSystemCouponActivateService.addActivateCount(coupon.getId(), Integer.parseInt(activateNum));
      // 激活券
      if (activate) {
         try {
            Integer expiryDay = systemCoupon.getExpiryDay();
            String endDay = DateUtil.plusDay(expiryDay - 1, nowDate);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (endDay != null && endDay.trim().length() > 0) {
               endDay += " 23:59:59";
            }
            Date endTime = format.parse(endDay);
      Integer state = couponActivate.getState();
      int count = couponActivate.getCount();
      count++;
      if (count >= limitNum) {
         result = true;
         state = UserSystemCouponActivate.STATE_END;
      }
            UserSystemCoupon userCoupon = new UserSystemCoupon();
            userCoupon.setId(coupon.getId());
            userCoupon.setStateActivated(1);
            userCoupon.setEndTime(endTime);
            userCoupon.setStartTime(nowDate);
            userCoupon.setUpdateTime(new Date());
            userSystemCouponMapper.updateByPrimaryKeySelective(userCoupon);
      UserSystemCouponActivate updateActivate = new UserSystemCouponActivate();
      updateActivate.setId(id);
      updateActivate.setState(state);
      updateActivate.setCount(count);
      updateActivate.setUpdateTime(new Date());
      userSystemCouponActivateService.updateByPrimaryKeySelective(updateActivate);
            // 赠送记录
            UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService.getByReceiveId(coupon.getId());
            if (giveRecord == null)
               return;
      // 激活奖励券
      if (result) {
         activateFreeCoupon(coupon, limitNum);
      }
   }
            Long giveUid = giveRecord.getGiveUid();
            UserInfo userInfo = userInfoService.selectByPKey(giveUid);
            if (userInfo == null)
               return;
   /**
    * 激活券
    *
    * @param coupon
    * @param activateNum
    */
   @Transactional
   private void activateFreeCoupon(UserSystemCoupon coupon, int limitNum) {
      try {
         Date nowDate = new Date();
         SystemCoupon systemCoupon = coupon.getSystemCoupon();
            String beiZhu = "请到我的-福利中心中查看";
            SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm");
            MsgOtherCouponActivateDTO msgOther = new MsgOtherCouponActivateDTO();
            msgOther.setTitle("免单券激活");
            msgOther.setType("免单券系统已自动激活");
            msgOther.setExplain("满足" + systemCoupon.getActivateDay() + "天内产生" + activateNum + "笔已到账返利订单");
            msgOther.setGiveUser("昵称:" + userInfo.getNickName() + " ID:" + giveUid);
            msgOther.setReceiveTime(sd.format(giveRecord.getReceiveTime()));
            msgOther.setValidityTime(expiryDay + "天");
            userOtherMsgNotificationService.giveCouponActivateMsg(uid, beiZhu, msgOther);
         } catch (Exception e) {
            e.printStackTrace();
            LogHelper.errorDetailInfo(e);
         Integer expiryDay = systemCoupon.getExpiryDay();
         String endDay = DateUtil.plusDay(expiryDay - 1, nowDate);
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         if (endDay != null && endDay.trim().length() > 0) {
            endDay += " 23:59:59";
         }
         Date endTime = format.parse(endDay);
         UserSystemCoupon userCoupon = new UserSystemCoupon();
         userCoupon.setId(coupon.getId());
         userCoupon.setStateActivated(1);
         userCoupon.setEndTime(endTime);
         userCoupon.setStartTime(nowDate);
         userCoupon.setUpdateTime(new Date());
         userSystemCouponMapper.updateByPrimaryKeySelective(userCoupon);
         // 消息
         executor.execute(new Runnable() {
            @Override
            public void run() {
               UserSystemCouponGiveRecord giveRecord = userSystemCouponGiveRecordService
                     .getByReceiveId(coupon.getId());
               if (giveRecord == null)
                  return;
               Long giveUid = giveRecord.getGiveUid();
               UserInfo userInfo = userInfoService.selectByPKey(giveUid);
               if (userInfo == null)
                  return;
               String beiZhu = "请到我的-福利中心中查看";
               SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm");
               MsgOtherCouponActivateDTO msgOther = new MsgOtherCouponActivateDTO();
               msgOther.setTitle("免单券激活");
               msgOther.setType("免单券系统已自动激活");
               msgOther.setExplain("满足" + systemCoupon.getActivateDay() + "天内产生" + limitNum + "笔已到账返利订单");
               msgOther.setGiveUser("昵称:" + userInfo.getNickName() + " ID:" + giveUid);
               msgOther.setReceiveTime(sd.format(giveRecord.getReceiveTime()));
               msgOther.setValidityTime(expiryDay + "天");
               userOtherMsgNotificationService.giveCouponActivateMsg(coupon.getUid(), beiZhu, msgOther);
            }
         });
      } catch (Exception e) {
         e.printStackTrace();
         LogHelper.errorDetailInfo(e);
      }
   }
}