package com.cyksj.service.distribute.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.cyksj.common.constant.Constant; import com.cyksj.common.exception.BusinessRuntimeException; import com.cyksj.common.util.Jsons; import com.cyksj.mapper.GoodsDonMapper; import com.cyksj.mapper.UserDistributeSharedRelateUnbindMapper; import com.cyksj.mapper.UserMapper; import com.cyksj.mapper.manage.coupon.CouponDistributePopularizeMapper; import com.cyksj.mapper.manage.coupon.CouponMapper; import com.cyksj.mapper.manage.distribute.*; import com.cyksj.model.entity.*; import com.cyksj.model.request.UserDistributeReq; import com.cyksj.redis.RedisService; import com.cyksj.service.distribute.DistributeService; 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.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /* *项目名: netflix *文件名: DistributeServiceImpl *创建者: JavaZou *创建时间:2022/11/14 12:21 */ @Service @RequiredArgsConstructor @Slf4j public class DistributeServiceImpl implements DistributeService { private final UserDistributeMapper userDistributeMapper; private final UserPlatDistributeRateMapper userPlatDistributeRateMapper; private final GoodsDonMapper goodsDonMapper; private final UserDistributeSharedMapper userDistributeSharedMapper; private final UserBusinessDefaultRateConfigMapper defaultRateConfigMapper; private final RedisService redisService; private final CouponMapper couponMapper; private final CouponDistributePopularizeMapper couponDistributePopularizeMapper; private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper; private final UserDistributeTargetAlertMapper targetAlertMapper; private final UserDistributeSharedRelateUnbindMapper userDistributeSharedRelateUnbindMapper; private final DistributeGeneralSkuRateMapper generalSkuRateMapper; private final UserMapper userMapper; @Override @Transactional(rollbackFor = Throwable.class) public void insertDistribute(UserDistributeReq userDistributeReq) { if (!redisService.setNx(RedisService.key.USER_DISTRIBUTE_ADD_KEY.getNameFormat(userDistributeReq.getUserId()), userDistributeReq.getUserId(), 2 * 5l)) { return; } UserDistribute exists = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class).eq(UserDistribute::getUserId, userDistributeReq.getUserId()).eq(UserDistribute::getDeleted, true).last("limit 1")); if (exists != null) { throw BusinessRuntimeException.getInstance("该推广者已添加"); } Long businessId = userDistributeReq.getBusinessId(); UserDistribute userDistribute = new UserDistribute(); userDistribute.setUserId(userDistributeReq.getUserId()); userDistribute.setRemark(userDistributeReq.getRemark()); userDistribute.setType(userDistributeReq.getType()); userDistribute.setBusinessId(businessId); if (businessId != null && businessId != 0) { userDistribute.setBusinessBindTime(DateTime.now()); } userDistributeMapper.insert(userDistribute); for (UserPlatDistributeRate rate : userDistributeReq.getRates()) { if (rate.getRate() == null) { rate.setRate(0); } if (rate.getSecondRate() == null) { rate.setSecondRate(0); } if (rate.getRate() < 0 || rate.getRate() > 100) { throw new BusinessRuntimeException("比例错误"); } GoodsDon goodsDon = goodsDonMapper.selectById(rate.getGoodsId()); if (goodsDon == null || !goodsDon.getDeleted() || goodsDon.getType() == 3) { throw new BusinessRuntimeException("平台错误"); } //分销者虚物分销比例且配置商务 if (businessId != null && goodsDon.getType() == 1) { checkDistributorAndBusinessRate(rate.getRate(), goodsDon.getId(), goodsDon.getTitle()); } rate.setDistributeId(userDistribute.getId()); userPlatDistributeRateMapper.insert(rate); } List skuRates = userDistributeReq.getSkuRates(); if (CollUtil.isNotEmpty(skuRates)) { Map map = new ConcurrentHashMap<>(); for (UserPlatSkuDistributeRate skuRate : skuRates) { if (skuRate.getRate() == null) { skuRate.setRate(0); } if (skuRate.getSecondRate() == null) { skuRate.setSecondRate(0); } if (skuRate.getRate() < 0 || skuRate.getRate() > 100) { throw new BusinessRuntimeException("比例错误"); } GoodsDon goodsDon = map.get(skuRate.getGoodsId()); if (goodsDon == null) { goodsDon = goodsDonMapper.selectById(skuRate.getGoodsId()); map.putIfAbsent(skuRate.getSkuId(), goodsDon); } try { skuRate.setDistributeId(userDistribute.getId()); if (businessId != null && goodsDon.getType() == 1) { checkDistributorAndBusinessRate(skuRate.getRate(), skuRate.getGoodsId(), goodsDon.getTitle()); } userPlatSkuDistributeRateMapper.insert(skuRate); } catch (DuplicateKeyException e) { } } } //渠道附加功能 handlerDistributeOtherFunc(userDistribute, userDistributeReq); //设置过个人专属推广码 升级为渠道专属优惠码 setDistributePopularizeCode(userDistribute.getId(), userDistribute.getUserId()); } @Override @Transactional(rollbackFor = Throwable.class) public void editDistribute(UserDistributeReq userDistributeReq) { if (userDistributeReq.getId() == null || userDistributeReq.getId() < 1) { throw BusinessRuntimeException.getInstance("id错误"); } Long id = userDistributeReq.getId(); UserDistribute userDistribute = userDistributeMapper.selectById(id); if (userDistribute == null || !userDistribute.getDeleted()) { return; } userDistribute.setId(userDistributeReq.getId()); userDistribute.setRemark(userDistributeReq.getRemark()); Long businessId = userDistributeReq.getBusinessId(); if (businessId == null) { userDistribute.setBusinessId(0l); } else { if (userDistribute.getBusinessId() != null && !userDistribute.getBusinessId().equals(businessId)) { userDistribute.setBusinessBindTime(DateTime.now()); } userDistribute.setBusinessId(businessId); } userDistribute.setType(userDistributeReq.getType()); userDistributeMapper.updateById(userDistribute); for (UserPlatDistributeRate rate : userDistributeReq.getRates()) { if (rate.getRate() == null) { rate.setRate(0); } if (rate.getSecondRate() == null) { rate.setSecondRate(0); } if (rate.getRate() < 0 || rate.getRate() > 100) { throw new BusinessRuntimeException("比例错误"); } GoodsDon goodsDon = goodsDonMapper.selectById(rate.getGoodsId()); if (rate.getId() != null && (goodsDon == null || !goodsDon.getDeleted())) { userPlatDistributeRateMapper.deleteById(rate.getId()); continue; } if (goodsDon == null || !goodsDon.getDeleted() || goodsDon.getType() == 3) { throw new BusinessRuntimeException("平台错误"); } //分销者虚物分销比例且配置商务 if (businessId != null && goodsDon.getType() == 1) { checkDistributorAndBusinessRate(rate.getRate(), goodsDon.getId(), goodsDon.getTitle()); } rate.setDistributeId(userDistribute.getId()); if (rate.getId() == null) { try { userPlatDistributeRateMapper.insert(rate); } catch (DuplicateKeyException e) { userPlatDistributeRateMapper.update(null, Wrappers.lambdaUpdate(UserPlatDistributeRate.class) .eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId()) .eq(UserPlatDistributeRate::getGoodsId, rate.getGoodsId()) .set(UserPlatDistributeRate::getRate, rate.getRate())); } } else { UserPlatDistributeRate dbPlateRate = userPlatDistributeRateMapper.selectById(rate.getId()); if (dbPlateRate == null) { continue; } if (dbPlateRate.getRate() != rate.getRate() || dbPlateRate.getSecondRate() != rate.getSecondRate()) { userPlatDistributeRateMapper.updateById(rate); } } } //特殊平台 按规格分销比例 List skuRates = userDistributeReq.getSkuRates(); if (CollUtil.isNotEmpty(skuRates)) { Map map = new ConcurrentHashMap<>(); for (UserPlatSkuDistributeRate skuRate : skuRates) { if (skuRate.getRate() == null) { skuRate.setRate(0); } if (skuRate.getSecondRate() == null) { skuRate.setSecondRate(0); } if (skuRate.getRate() < 0 || skuRate.getRate() > 100) { throw new BusinessRuntimeException("比例错误"); } GoodsDon goodsDon = map.get(skuRate.getGoodsId()); if (goodsDon == null) { goodsDon = goodsDonMapper.selectById(skuRate.getGoodsId()); map.putIfAbsent(skuRate.getSkuId(), goodsDon); } if (businessId != null && goodsDon.getType() == 1) { checkDistributorAndBusinessRate(skuRate.getRate(), goodsDon.getId(), goodsDon.getTitle()); } if (skuRate.getId() != null) { userPlatSkuDistributeRateMapper.updateById(skuRate); continue; } try { skuRate.setDistributeId(userDistribute.getId()); userPlatSkuDistributeRateMapper.insert(skuRate); } catch (DuplicateKeyException e) { } } } handlerDistributeOtherFunc(userDistribute, userDistributeReq); } /** * 渠道附加功能 */ public void handlerDistributeOtherFunc(UserDistribute userDistribute, UserDistributeReq userDistributeReq) { //处理优惠券关联 handlerDistributeCouponRelate(userDistribute.getId(), userDistribute.getUserId(), userDistributeReq.getCouponRelates()); // //渠道目标额配置 // handlerDistributeTargetAlert(userDistribute.getId(), userDistributeReq.getTargets()); } @Override public void saveDistributionInvitation(Long sharedId, Long userId, Long dsPopularizeId) { if (sharedId == 0l || sharedId.equals(userId)) { return; } User user = userMapper.selectById(sharedId); if (user == null) { return; } UserDistributeShared userDistributeShared = new UserDistributeShared(); userDistributeShared.setSharedId(sharedId); //存在分销 userDistributeShared.setUserId(userId); userDistributeShared.setDsPopularizeId(dsPopularizeId); try { userDistributeSharedMapper.insert(userDistributeShared); } catch (DuplicateKeyException e) { log.info("分销被邀请人重复插入"); } } @Override @Transactional(rollbackFor = Throwable.class) public void bindPopularizeCode(Long userId, String code) { Coupon coupon = couponMapper.getCouponById(Constant.GENERAL_POPULARIZE_COUPON_ID); if (!redisService.setNx(RedisService.key.GENERAL_POPULARIZE_CODE.getName() + code, userId, RedisService.key.GENERAL_POPULARIZE_CODE.getTimeout())) { throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置"); } UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class) .eq(UserDistribute::getUserId, userId) .eq(UserDistribute::getDeleted, true) .last("limit 1")); if (userDistribute != null) throw BusinessRuntimeException.getInstance("只适用于普通用户进行专属推广"); CouponDistributePopularize is_exists = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class) .eq(CouponDistributePopularize::getUserId, userId) .last("limit 1")); if (is_exists != null) throw BusinessRuntimeException.getInstance("你已设置专属推广优惠码"); CouponDistributePopularize couponDistributePopularize = new CouponDistributePopularize(); couponDistributePopularize.setCouponId(coupon.getId()); couponDistributePopularize.setUserId(userId); couponDistributePopularize.setIsGeneral(true); CouponDistributePopularize exists = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class) .eq(CouponDistributePopularize::getExCode, code) .eq(CouponDistributePopularize::getDeleted, true) .ne(CouponDistributePopularize::getUserId, userId) .select(CouponDistributePopularize::getId) .last("limit 1")); if (exists != null) { throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置"); } else { Coupon existsCoupon = couponMapper.selectOne(Wrappers.lambdaQuery(Coupon.class) .eq(Coupon::getExCode, code) .eq(Coupon::getDeleted, true) .select(Coupon::getId) .last("limit 1")); if (existsCoupon != null) { throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置"); } } couponDistributePopularize.setExCode(code); couponDistributePopularizeMapper.insert(couponDistributePopularize); } @Override public void unbindUserDistributeShared(List userBind) throws Exception { List save_userIds = new ArrayList<>(500); userBind.forEach(e -> { Map map = Jsons.toMap(e); Object value0 = map.get("0"); if (value0 != null) { Long userId = Long.parseLong(value0.toString()); save_userIds.add(userId); if (save_userIds.size() == 500) { userDistributeSharedRelateUnbindMapper.batchInsert(save_userIds); save_userIds.clear(); } } }); if (save_userIds.size() > 0) { userDistributeSharedRelateUnbindMapper.batchInsert(save_userIds); save_userIds.clear(); } } @Override public void setDistributeCommonSkuRate(List skuRates) { List collect = skuRates.stream().map(DistributeGeneralSkuRate::getSkuId).collect(Collectors.toList()); if (CollUtil.isNotEmpty(collect)) { generalSkuRateMapper.delete(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class) .notIn(DistributeGeneralSkuRate::getSkuId, collect)); } skuRates.forEach(e -> { Integer rate = e.getRate(); if (rate == null || rate < 0 || rate > 100) { throw BusinessRuntimeException.getInstance("请输入正确的比例"); } if (e.getId() == null) { try { generalSkuRateMapper.insert(e); } catch (DuplicateKeyException ex) { } } else { generalSkuRateMapper.updateById(e); } }); } public void checkDistributorAndBusinessRate(Integer distributeGoodsRate, Long goodsId, String goodsName) { UserBusinessDefaultRateConfig defaultGoodsRateConfig = defaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(UserBusinessDefaultRateConfig.class) .eq(UserBusinessDefaultRateConfig::getGoodsId, goodsId) .last("limit 1")); Optional.ofNullable(defaultGoodsRateConfig).ifPresent(config -> { if (distributeGoodsRate > config.getMaxRate()) { throw BusinessRuntimeException.getInstance(String.format("该%s平台最高可配置分销比例为%s", goodsName, config.getMaxRate())); } }); } private void handlerDistributeCouponRelate(Long distributeId, Long userId, List couponRelates) { Map map = new ConcurrentHashMap<>(); couponRelates.forEach(data -> { data.setDistributeId(distributeId); if (data.getCouponId() == null) { throw BusinessRuntimeException.getInstance("优惠券不存在"); } Integer exists = couponMapper.selectCount(Wrappers.lambdaQuery(Coupon.class).eq(Coupon::getId, data.getCouponId()).eq(Coupon::getDeleted, 1)); if (exists == 0) { throw BusinessRuntimeException.getInstance("id为{0}的优惠券不存在", data.getCouponId()); } String exCode = data.getExCode(); if (StrUtil.isEmpty(exCode)) { throw BusinessRuntimeException.getInstance("优惠码为空"); } List popularizeList = couponDistributePopularizeMapper.selectList(Wrappers.lambdaQuery(CouponDistributePopularize.class) .eq(CouponDistributePopularize::getDeleted, 1) .eq(CouponDistributePopularize::getExCode, exCode)); //个人渠道 for (CouponDistributePopularize couponDistributePopularize : popularizeList) { Long disId = couponDistributePopularize.getDistributeId(); if (disId != null && !ObjectUtil.equal(disId, distributeId)) { throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode); } Long uid = couponDistributePopularize.getUserId(); if (uid != null && !ObjectUtil.equal(uid, userId)) { throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode); } } Integer count = couponMapper.selectCount(Wrappers.lambdaQuery(Coupon.class).eq(Coupon::getExCode, exCode).eq(Coupon::getDeleted, true)); if (count > 0) { throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode); } if (data.getId() != null) { couponDistributePopularizeMapper.updateById(data); } else { couponDistributePopularizeMapper.insert(data); } map.put(data.getId(), data); }); List dbCouponPopularizes = couponDistributePopularizeMapper.selectList(Wrappers.lambdaQuery(CouponDistributePopularize.class) .eq(CouponDistributePopularize::getDistributeId, distributeId) .eq(CouponDistributePopularize::getDeleted, 1)); //不存在的删除 List delDbCouponPids = new ArrayList<>(); dbCouponPopularizes.forEach(db -> { if (map.get(db.getId()) == null) { delDbCouponPids.add(db.getId()); } }); if (CollUtil.isNotEmpty(delDbCouponPids)) { couponDistributePopularizeMapper.update(null, Wrappers.lambdaUpdate(CouponDistributePopularize.class) .set(CouponDistributePopularize::getDeleted, 0) .in(CouponDistributePopularize::getId, delDbCouponPids) .eq(CouponDistributePopularize::getDeleted, 1)); } } /** * 渠道目标额 设置 */ private void handlerDistributeTargetAlert(Long distributeId, List targets) { Map map = new ConcurrentHashMap<>(); for (UserDistributeTargetAlert targetAlert : targets) { targetAlert.setDistributeId(distributeId); Integer type = targetAlert.getType(); BigDecimal target = targetAlert.getTarget(); Assert.notNull(type, "请选择对应目标类型"); Assert.notNull(target, "请输入对应目标额"); if (type < 1 || type > 3) { throw BusinessRuntimeException.getInstance("请选择正确的目标类型"); } if (target.compareTo(BigDecimal.ZERO) <= 0) { throw BusinessRuntimeException.getInstance("请输入正确的目标额值"); } if ((type == 2 || type == 3) && target.compareTo(BigDecimal.ZERO) < 0) { throw BusinessRuntimeException.getInstance("请输入正确的变化比例"); } Long id = targetAlert.getId(); try { if (id != null) { UserDistributeTargetAlert dbAlert = targetAlertMapper.selectById(id); if (dbAlert != null) { //目标额 变化 去掉下次提醒时间 if (dbAlert.getTarget().compareTo(targetAlert.getTarget()) != 0) { targetAlert.setNextAlertTime(null); } //关闭一周内提醒 去掉下次提醒时间 if (!targetAlert.getIsWeek()) { targetAlert.setNextAlertTime(null); } targetAlertMapper.updateById(targetAlert); } } else { targetAlertMapper.insert(targetAlert); } map.put(targetAlert.getId(), targetAlert); } catch (DuplicateKeyException e) { } } List dbTargetAlert = targetAlertMapper.selectList(Wrappers.lambdaQuery(UserDistributeTargetAlert.class) .eq(UserDistributeTargetAlert::getDistributeId, distributeId)); //不存在的删除 List delDbTargetAlert = new ArrayList<>(); dbTargetAlert.forEach(db -> { if (map.get(db.getId()) == null) { delDbTargetAlert.add(db.getId()); } }); if (CollUtil.isNotEmpty(delDbTargetAlert)) { targetAlertMapper.deleteBatchIds(delDbTargetAlert); } } private void setDistributePopularizeCode(Long distributeId, Long userId) { CouponDistributePopularize couponDistributePopularize = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class) .eq(CouponDistributePopularize::getCouponId, Constant.GENERAL_POPULARIZE_COUPON_ID) .eq(CouponDistributePopularize::getUserId, userId) .eq(CouponDistributePopularize::getDeleted, 1) .eq(CouponDistributePopularize::getIsGeneral, 1) .last("limit 1")); if (couponDistributePopularize != null) { //先删除 couponDistributePopularize.setDeleted(false); couponDistributePopularizeMapper.updateById(couponDistributePopularize); //后升级 CouponDistributePopularize newPopularizeCode = new CouponDistributePopularize(); newPopularizeCode.setDistributeId(distributeId); newPopularizeCode.setExCode(couponDistributePopularize.getExCode()); newPopularizeCode.setCouponId(Constant.DISTRIBUTE_POPULARIZE_COUPON_ID); couponDistributePopularizeMapper.insert(newPopularizeCode); } } }