KKSU
2025-01-23 20e0c1036ebc6d558e57644b770b9c9de8bcf383
src/main/java/cc/mrbird/febs/mall/service/impl/ApiMallOrderInfoServiceImpl.java
@@ -42,6 +42,7 @@
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
@@ -86,17 +87,13 @@
    private final CouponGoodsMapper couponGoodsMapper;
    private final IMallVipConfigService mallVipConfigService;
    private final MallActivityMapper mallActivityMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(AddOrderDto addOrderDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        MallMember member = mallMemberMapper.selectById(memberId);
                //验证用户的等级
//        if(AgentLevelEnum.ZERO_LEVEL.name().equals(member.getLevel())){
//            throw new FebsException("请先申请成为代理人");
//        }
        //订单范围内才允许下单
        MallAddressInfo address = mallAddressInfoMapper.selectAddressInfoByMemberIdAndId(member.getId(), addOrderDto.getAddressId());
@@ -126,14 +123,9 @@
        MallMemberCoupon mallMemberCoupon = new MallMemberCoupon();
        if(ObjectUtil.isNotEmpty(addOrderDto.getMemberCouponId())){
            Long memberCouponId = addOrderDto.getMemberCouponId();
            mallMemberCoupon = mallMemberCouponMapper.selectById(memberCouponId);
            if(ObjectUtil.isEmpty(mallMemberCoupon)){
                throw new FebsException(mallMemberCoupon.getCouponName()+"无法使用");
            }
            Integer state = mallMemberCoupon.getState();
            if(1 != state){
                throw new FebsException(mallMemberCoupon.getCouponName()+"无法使用");
            }
            mallMemberCoupon = ValidateEntityUtils.ensureColumnReturnEntity(memberCouponId, MallMemberCoupon::getId, mallMemberCouponMapper::selectOne, "优惠券不存在");
            ValidateEntityUtils.ensureEqual(mallMemberCoupon.getState(),1, "优惠券状态异常");
            List<AddOrderItemDto> items = addOrderDto.getItems();
            couponAmountMap = getCouponAmountMap(memberCouponId, items);
        }
@@ -146,10 +138,10 @@
                    if (mallGoods.getStock() < item.getCnt()) {
                        throw new FebsException(mallGoods.getGoodsName() + "库存不足");
                    }
                    if (MallGoods.ISSALE_STATUS_DISABLED.equals(mallGoods.getIsSale())) {
                        throw new FebsException(mallGoods.getGoodsName() + "已下架");
                    }
                    ValidateEntityUtils.ensureNotEqual(mallGoods.getIsSale(),MallGoods.ISSALE_STATUS_DISABLED, "商品已下架");
//                    if (MallGoods.ISSALE_STATUS_DISABLED.equals(mallGoods.getIsSale())) {
//                        throw new FebsException(mallGoods.getGoodsName() + "已下架");
//                    }
                    BigDecimal amount = mallGoods.getScore().multiply(BigDecimal.valueOf(item.getCnt()));
                    orderItem.setAmount(amount);
@@ -201,9 +193,7 @@
                        }
                    }
                    if (MallGoods.ISSALE_STATUS_DISABLED.equals(mallGoods.getIsSale())) {
                        throw new FebsException(mallGoods.getGoodsName() + "已下架");
                    }
                    ValidateEntityUtils.ensureNotEqual(mallGoods.getIsSale(),MallGoods.ISSALE_STATUS_DISABLED, "商品已下架");
                    //商品库存销量计算
                    Integer goodsResult = mallGoodsMapper.upDateStockAndVolumeByGoodsId(mallGoods.getId(), item.getCnt());
                    if(1 != goodsResult){
@@ -288,81 +278,101 @@
     * @return Map<Long,BigDecimal> skuId,实际支付金额
     */
    @Override
    public Map<Long,BigDecimal> getCouponAmountMap(Long memberCouponId,List<AddOrderItemDto> items){
        HashMap<Long,BigDecimal> couponAmountMap = new HashMap<>();
        MallMemberCoupon mallMemberCoupon = mallMemberCouponMapper.selectById(memberCouponId);
        if(ObjectUtil.isEmpty(mallMemberCoupon)){
            return couponAmountMap;
        }
        Integer state = mallMemberCoupon.getState();
        if(1 != state){
            return couponAmountMap;
        }
        Long couponId = mallMemberCoupon.getCouponId();//优惠卷ID
        List<Long> goodsIdsAll = couponGoodsMapper.selectByCouponId(couponId);
        List<MallGoodsSku> skusAll = mallGoodsSkuMapper.selectSkuIdsByGoodsId(goodsIdsAll);//获取该优惠卷绑定的全部商品sku
        List<Long> skuIdsAll = skusAll.stream().map(MallGoodsSku::getId).collect(Collectors.toList());//获取该优惠卷绑定的全部商品skuIDS
        List<Long> skuIds = items.stream().map(AddOrderItemDto::getSkuId).collect(Collectors.toList());//订单中的全部skuIds
    public Map<Long, BigDecimal> getCouponAmountMap(Long memberCouponId, List<AddOrderItemDto> items) {
        HashMap<Long, BigDecimal> couponAmountMap = new HashMap<>();
        // 获取优惠券信息
        Optional<MallMemberCoupon> optionalMallMemberCoupon = Optional.ofNullable(mallMemberCouponMapper.selectById(memberCouponId));
        MallMemberCoupon mallMemberCoupon = optionalMallMemberCoupon.orElse(null);
        /**
         * 获取这张优惠卷生效的skuIds
         */
        Set<Long> intersection = skuIdsAll.stream()
                .filter(item -> skuIds.contains(item))
                .collect(Collectors.toSet());//获取两个集合的交集
        if(CollUtil.isEmpty(intersection)){
        if (mallMemberCoupon == null || mallMemberCoupon.getState() != 1) {
            return couponAmountMap;
        }
        HashMap<Long,BigDecimal> skuMap = new HashMap<>();//每个订单详情的ID和amount的map
        List<MallGoodsSku> skus = mallGoodsSkuMapper.selectByIds(new ArrayList<>(intersection));
        BigDecimal totalAmount = BigDecimal.ZERO;//订单中的总金额
        Map<Long, AddOrderItemDto> itemMap = new HashMap<>();// 预先将items转换为Map,以skuId作为键
        for (AddOrderItemDto addOrderItemDto : items) {
            itemMap.put(addOrderItemDto.getSkuId(), addOrderItemDto);
        Set<Long> intersection = items.stream().map(AddOrderItemDto::getSkuId).collect(Collectors.toSet()); // 订单中的全部skuIds
        if (intersection.isEmpty()) {
            return couponAmountMap;
        }
        for(MallGoodsSku mallGoodsSku : skus){
        // 获取订单详情的ID和amount的map
        Map<Long, AddOrderItemDto> itemMap = items.stream()
                .collect(Collectors.toMap(AddOrderItemDto::getSkuId, item -> item));
        List<MallGoodsSku> skus = mallGoodsSkuMapper.selectList(
                new LambdaQueryWrapper<MallGoodsSku>()
                        .select(MallGoodsSku::getId, MallGoodsSku::getPresentPrice)
                        .in(MallGoodsSku::getId, intersection)
        );
        BigDecimal totalAmount = BigDecimal.ZERO;
        Map<Long, BigDecimal> skuMap = new HashMap<>();
        for (MallGoodsSku mallGoodsSku : skus) {
            Long id = mallGoodsSku.getId();
            BigDecimal presentPrice = mallGoodsSku.getPresentPrice();
            // 检查itemMap中是否存在该商品
            AddOrderItemDto addOrderItemDto = itemMap.get(id);
            if (addOrderItemDto != null) {
                BigDecimal skuAmount = presentPrice.multiply(BigDecimal.valueOf(addOrderItemDto.getCnt()));
                totalAmount = totalAmount.add(skuAmount);
                skuMap.put(id,skuAmount);
                skuMap.put(id, skuAmount);
            }
        }
        /**
         * 计算每个商品利用优惠卷打折的具体金额
         */
        MallGoodsCoupon mallGoodsCoupon = mallGoodsCouponMapper.selectById(mallMemberCoupon.getCouponId());
        BigDecimal costAmount = mallGoodsCoupon.getCostAmount();
        BigDecimal realAmount = mallGoodsCoupon.getRealAmount();
        if(totalAmount.compareTo(costAmount) < 0){
        // 计算每个商品利用优惠卷打折的具体金额
        Optional<MallGoodsCoupon> optionalMallGoodsCoupon = Optional.ofNullable(mallGoodsCouponMapper.selectById(mallMemberCoupon.getCouponId()));
        MallGoodsCoupon mallGoodsCoupon = optionalMallGoodsCoupon.orElse(null);
        if (mallGoodsCoupon == null) {
            return couponAmountMap;
        }
        HashMap<Long,BigDecimal> skuMapPercent = new HashMap<>();//每个订单详情的ID和amount的map
        for (Map.Entry<Long,BigDecimal> entry : skuMap.entrySet()) {
        BigDecimal costAmount = mallGoodsCoupon.getCostAmount();
        BigDecimal realAmount = mallGoodsCoupon.getRealAmount();
        Integer type = mallGoodsCoupon.getType();
        if (MallGoodsCoupon.TYPE_ONE == type) {
            realAmount = mallGoodsCoupon.getRealAmount();
        } else if (MallGoodsCoupon.TYPE_TWO == type) {
            BigDecimal divideTime = totalAmount.divide(costAmount, 0, RoundingMode.DOWN); // 累计减免次数
            realAmount = divideTime.multiply(realAmount); // 实际减免金额
        }
        if (totalAmount.compareTo(costAmount) < 0) {
            return couponAmountMap;
        }
        BigDecimal totalDiscount = BigDecimal.ZERO;
        for (Map.Entry<Long, BigDecimal> entry : skuMap.entrySet()) {
            Long keySkuId = entry.getKey();
            BigDecimal valueSkuAmount = entry.getValue();
            BigDecimal divide = valueSkuAmount.divide(totalAmount, 4, BigDecimal.ROUND_DOWN);//每个商品占符合满减的总额的比例
            skuMapPercent.put(keySkuId,divide);
            Integer type = mallGoodsCoupon.getType();
            if(MallGoodsCoupon.TYPE_ONE == type){
                BigDecimal bigDecimal = realAmount.multiply(divide).setScale(0, BigDecimal.ROUND_DOWN);//每个SKU的减免金额(比例*减免金额)
                BigDecimal skuRealAmount = valueSkuAmount.subtract(bigDecimal.compareTo(BigDecimal.ZERO) > 0 ? bigDecimal : BigDecimal.ZERO);//实际支付金额
                couponAmountMap.put(keySkuId,skuRealAmount);
            BigDecimal divide = valueSkuAmount.divide(totalAmount, 4, RoundingMode.DOWN); // 每个商品占符合满减的总额的比例
            BigDecimal skuRealAmount = BigDecimal.ZERO;
            if (MallGoodsCoupon.TYPE_ONE == type) {
                BigDecimal bigDecimalOne = realAmount.multiply(divide).setScale(2, RoundingMode.DOWN); // 每个SKU的减免金额(比例*减免金额)
                skuRealAmount = valueSkuAmount.subtract(bigDecimalOne.max(BigDecimal.ZERO)).setScale(2, RoundingMode.DOWN);
                totalDiscount = totalDiscount.add(bigDecimalOne);
            } else if (MallGoodsCoupon.TYPE_TWO == type) {
                BigDecimal divideTime = totalAmount.divide(costAmount, 0, RoundingMode.DOWN); // 累计减免次数
                BigDecimal multiply = divideTime.multiply(realAmount); // 实际减免金额
                BigDecimal bigDecimalTwo = multiply.multiply(divide).setScale(2, RoundingMode.DOWN); // 每个SKU的减免金额(比例*实际减免金额)
                skuRealAmount = valueSkuAmount.subtract(bigDecimalTwo.max(BigDecimal.ZERO)).setScale(2, RoundingMode.DOWN);
                totalDiscount = totalDiscount.add(bigDecimalTwo);
            }
            if(MallGoodsCoupon.TYPE_TWO == type){
                BigDecimal divideTime = totalAmount.divide(costAmount, 0, BigDecimal.ROUND_DOWN);//累计减免次数
                BigDecimal multiply = divideTime.multiply(realAmount);//实际减免金额
                BigDecimal bigDecimal = multiply.multiply(divide).setScale(0, BigDecimal.ROUND_DOWN);//每个SKU的减免金额(比例*实际减免金额)
                BigDecimal skuRealAmount = valueSkuAmount.subtract(bigDecimal.compareTo(BigDecimal.ZERO) > 0 ? bigDecimal : BigDecimal.ZERO);//实际支付金额
                couponAmountMap.put(keySkuId,skuRealAmount);
            couponAmountMap.put(keySkuId, skuRealAmount);
        }
        // 调整最后一个商品的减免金额以确保总减免金额达到预期
        if (totalDiscount.compareTo(realAmount) < 0) {
            BigDecimal difference = realAmount.subtract(totalDiscount);
            for (Map.Entry<Long, BigDecimal> entry : couponAmountMap.entrySet()) {
                Long keySkuId = entry.getKey();
                BigDecimal skuRealAmount = entry.getValue();
                BigDecimal newSkuRealAmount = skuRealAmount.subtract(difference).setScale(2, RoundingMode.DOWN);
                couponAmountMap.put(keySkuId, newSkuRealAmount);
                break; // 调整最后一个商品的减免金额
            }
        }
        return couponAmountMap;
    }
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>();
@@ -391,14 +401,13 @@
    public void cancelOrder(Long id) {
        MallMember member = LoginUserUtil.getLoginUser();
        MallOrderInfo orderInfo = this.baseMapper.selectOrderByMemberIdAndId(member.getId(), id);
        if (orderInfo == null || AppContants.DEL_FLAG_Y == orderInfo.getDelFlag()) {
            throw new FebsException("订单不存在");
        }
        ValidateEntityUtils.ensureNotEqual(orderInfo,null, "订单不存在");
        ValidateEntityUtils.ensureNotEqual(orderInfo.getDelFlag(),AppContants.DEL_FLAG_Y, "订单已删除");
        if (OrderStatusEnum.WAIT_PAY.getValue() != orderInfo.getStatus()) {
            throw new FebsException("订单不是待付款, 无法取消");
        if (OrderStatusEnum.WAIT_PAY.getValue() != orderInfo.getStatus()
                && OrderStatusEnum.WAIT_SHIPPING.getValue() != orderInfo.getStatus() ) {
            throw new FebsException("订单不是待付款或者待收货, 无法取消");
        }
        orderInfo.setStatus(OrderStatusEnum.CANCEL.getValue());
        orderInfo.setCancelType(MallOrderInfo.CANCEL_BY_SELF);
        this.baseMapper.updateById(orderInfo);
@@ -530,7 +539,7 @@
                mallMoneyFlowService.addMoneyFlow(member.getId(), orderInfo.getAmount().negate(), MoneyFlowTypeEnum.PAY.getValue(), orderInfo.getOrderNo(), FlowTypeEnum.BALANCE.getValue(),"余额支付",2);
                agentProducer.sendOrderCoupon(orderInfo.getId());
//                agentProducer.sendOrderCoupon(orderInfo.getId());
                break;
            case "4":
                if (orderInfo.getOrderType() != 2) {
@@ -574,14 +583,12 @@
            throw new FebsException("未设置支付密码");
        }
        if (!SecureUtil.md5(tradePwd).equals(mallMember.getTradePassword())) {
            throw new FebsException("支付密码错误");
        }
        ValidateEntityUtils.ensureEqual(SecureUtil.md5(tradePwd),mallMember.getTradePassword(),"支付密码错误");
        int reduce = memberWalletService.reduce(orderInfo.getAmount(), mallMember.getId(), field);
        if (reduce == 2) {
            throw new FebsException("余额不足");
        }
//        int reduce = memberWalletService.reduce(orderInfo.getAmount(), mallMember.getId(), field);
//        if (reduce == 2) {
//            throw new FebsException("余额不足");
//        }
        return orderInfo.getOrderNo();
    }
@@ -644,15 +651,10 @@
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(Long id) {
        MallMember member = LoginUserUtil.getLoginUser();
        MallOrderInfo orderInfo = this.baseMapper.selectOrderByMemberIdAndId(member.getId(), id);
        if (orderInfo == null || AppContants.DEL_FLAG_Y == orderInfo.getDelFlag()) {
            throw new FebsException("订单不存在");
        }
        if (orderInfo.getStatus() != OrderStatusEnum.WAIT_FINISH.getValue()) {
            throw new FebsException("该状态不能确认收货");
        }
        MallOrderInfo orderInfo = ValidateEntityUtils.ensureColumnReturnEntity(id,MallOrderInfo::getId,this.baseMapper::selectOne,"订单不存在");
        ValidateEntityUtils.ensureEqual(member.getId(), orderInfo.getMemberId(), "订单数据异常");
        ValidateEntityUtils.ensureEqual(orderInfo.getStatus(), OrderStatusEnum.WAIT_FINISH.getValue(), "该状态不能确认收货");
//        if (orderInfo.getDeliveryState() != OrderDeliveryStateEnum.DELIVERY_FINISH.getValue()) {
//            throw new FebsException("还未送至自提点");
//        }
@@ -666,9 +668,9 @@
        orderInfo.setReceivingTime(new Date());
        this.baseMapper.updateById(orderInfo);
        //普通订单才产生积分,积分订单不产生积分
        if(1 == orderInfo.getOrderType()){
            agentProducer.sendGetScoreMsg(orderInfo.getId());
        }
//        if(1 == orderInfo.getOrderType()){
//            agentProducer.sendGetScoreMsg(orderInfo.getId());
//        }
        //生成一条团长提成记录
//        Long orderInfoId = orderInfo.getId();
//        List<MallOrderItem> mallOrderItemList = mallOrderItemMapper.selectListByOrderId(orderInfoId);
@@ -702,11 +704,8 @@
    @Override
    public void delOrder(Long id) {
        MallMember member = LoginUserUtil.getLoginUser();
        MallOrderInfo orderInfo = this.baseMapper.selectOrderByMemberIdAndId(member.getId(), id);
        if (orderInfo == null || AppContants.DEL_FLAG_Y == orderInfo.getDelFlag()) {
            throw new FebsException("订单不存在");
        }
        MallOrderInfo orderInfo = ValidateEntityUtils.ensureColumnReturnEntity(id,MallOrderInfo::getId,this.baseMapper::selectOne,"订单不存在");
        ValidateEntityUtils.ensureNotEqual(orderInfo.getDelFlag(),AppContants.DEL_FLAG_Y,"订单已删除");
        orderInfo.setDelFlag(AppContants.DEL_FLAG_Y);
        this.baseMapper.updateById(orderInfo);
    }
@@ -1012,22 +1011,6 @@
            if (sku == null) {
                return new FebsResponse().fail().message("购买商品或sku不存在");
            }
//            if("样品".equals(sku.getSample())){
//                List<MallOrderItem> mallOrderItems = mallOrderItemMapper.selectItemBySkuIdUnCancel(sku.getId(), member.getId());
//                if (CollUtil.isNotEmpty(mallOrderItems)) {
//                    return new FebsResponse().fail().message("样品只能购买一次");
//                }
//                Integer cnt = item.getCnt();
//                if(1 < cnt){
//                    return new FebsResponse().fail().message("样品只能购买一件");
//                }
//            }else{
//                //验证用户的等级
//                if(AgentLevelEnum.ZERO_LEVEL.name().equals(member.getLevel())){
//                    return new FebsResponse().fail().message("请先申请成为合伙人");
//                }
//            }
            if (sku.getStock() < item.getCnt()) {
                return new FebsResponse().fail().message(sku.getSkuName() + "库存不足");
            }
@@ -1036,6 +1019,14 @@
            if (MallGoods.ISSALE_STATUS_DISABLED.equals(mallGoods.getIsSale())) {
                return new FebsResponse().fail().message(mallGoods.getGoodsName() + "已下架");
            }
            if(GoodsTypeEnum.HUO_DONG.getValue() == mallGoods.getIsNormal()){
                //活动商品判断是否在活动进行中
                MallActivity mallActivity = mallActivityMapper.selectById(mallGoods.getActivityId());
                if(mallActivity == null || mallActivity.getState() != 2){
                    return new FebsResponse().fail().message("活动不在进行中");
                }
            }
        }
        return new FebsResponse().success();