| package com.mzl.flower.service.payment; | 
|   | 
| import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; | 
| import com.alibaba.fastjson.JSONObject; | 
| import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; | 
| import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; | 
| import com.baomidou.mybatisplus.core.metadata.IPage; | 
| import com.baomidou.mybatisplus.extension.plugins.pagination.Page; | 
| import com.mzl.flower.component.SequenceNo; | 
| import com.mzl.flower.config.PyamentV3Configurer; | 
| import com.mzl.flower.config.exception.ValidationException; | 
| import com.mzl.flower.config.security.SecurityUtils; | 
| import com.mzl.flower.constant.Constants; | 
| import com.mzl.flower.dto.PriceDTO; | 
| import com.mzl.flower.dto.request.menber.MemberGrowthRecordDTO; | 
| import com.mzl.flower.dto.request.payment.*; | 
| import com.mzl.flower.dto.response.coupon.CouponRecordVO; | 
| import com.mzl.flower.dto.response.flower.FlowerCartListDTO; | 
| import com.mzl.flower.dto.response.flower.FlowerCartListWrapDTO; | 
| import com.mzl.flower.dto.response.flower.FlowerDTO; | 
| import com.mzl.flower.dto.response.flower.ParamItemDTO; | 
| import com.mzl.flower.dto.response.partner.PartnerOrderDTO; | 
| import com.mzl.flower.dto.response.payment.*; | 
| import com.mzl.flower.dto.response.system.CodeValueDTO; | 
| import com.mzl.flower.dto.response.transport.TransportOrderDTO; | 
| import com.mzl.flower.dto.response.warehouse.WarehouseLocationDTO; | 
| import com.mzl.flower.entity.coupon.CouponRecordDO; | 
| import com.mzl.flower.entity.customer.Address; | 
| import com.mzl.flower.entity.customer.Customer; | 
| import com.mzl.flower.entity.flower.Flower; | 
| import com.mzl.flower.entity.flower.FlowerSupplierSaleNum; | 
| import com.mzl.flower.entity.menber.Member; | 
| import com.mzl.flower.entity.partner.Partner; | 
| import com.mzl.flower.entity.payment.*; | 
| import com.mzl.flower.entity.supplier.Station; | 
| import com.mzl.flower.entity.supplier.Supplier; | 
| import com.mzl.flower.entity.system.User; | 
| import com.mzl.flower.mapper.customer.AddressMapper; | 
| import com.mzl.flower.mapper.flower.FlowerMapper; | 
| import com.mzl.flower.mapper.flower.FlowerSupplierSaleNumMapper; | 
| import com.mzl.flower.mapper.payment.*; | 
| import com.mzl.flower.mapper.supplier.StationMapper; | 
| import com.mzl.flower.mapper.system.UserWechatMapper; | 
| import com.mzl.flower.mapper.warehouse.WarehouseLocationMapper; | 
| import com.mzl.flower.service.BaseService; | 
| import com.mzl.flower.service.coupon.CouponRecordService; | 
| import com.mzl.flower.service.flower.FlowerService; | 
| import com.mzl.flower.service.menber.MemberGrowthRecordService; | 
| import com.mzl.flower.service.point.CustomerPointService; | 
| import com.mzl.flower.service.point.PointGoodsService; | 
| import com.mzl.flower.service.system.CodeService; | 
| import com.mzl.flower.service.system.WeChatService; | 
| import com.mzl.flower.service.transport.TransportService; | 
| import com.mzl.flower.utils.UUIDGenerator; | 
| import com.wechat.pay.java.core.util.GsonUtil; | 
| import io.micrometer.core.instrument.util.StringUtils; | 
| import lombok.extern.slf4j.Slf4j; | 
| import me.chanjar.weixin.common.error.WxErrorException; | 
| import org.springframework.beans.BeanUtils; | 
| import org.springframework.beans.factory.annotation.Autowired; | 
| import org.springframework.context.annotation.Lazy; | 
| import org.springframework.stereotype.Service; | 
| import org.springframework.transaction.annotation.Transactional; | 
| import org.springframework.util.ObjectUtils; | 
|   | 
| import java.math.BigDecimal; | 
| import java.math.RoundingMode; | 
| import java.time.LocalDate; | 
| import java.time.LocalDateTime; | 
| import java.time.LocalTime; | 
| import java.util.*; | 
| import java.util.stream.Collectors; | 
|   | 
| @Service | 
| @Transactional | 
| @Slf4j | 
| public class OrderService extends BaseService { | 
|   | 
|     @Autowired | 
|     private CartMapper cartMapper; | 
|   | 
|     @Autowired | 
|     private FlowerMapper flowerMapper; | 
|   | 
|     @Autowired | 
|     private FlowerService flowerService; | 
|   | 
|     @Autowired | 
|     private TransportService transportService; | 
|   | 
|     @Autowired | 
|     private AddressMapper addressMapper; | 
|   | 
|     @Autowired | 
|     private UserPaymentV3Service paymentV3Service; | 
|   | 
|     @Autowired | 
|     private SequenceNo sequenceNo; | 
|   | 
|     @Autowired | 
|     private OrderMapper orderMapper; | 
|   | 
|     @Autowired | 
|     private OrderItemMapper orderItemMapper; | 
|   | 
|     @Autowired | 
|     private DeliveryOrderService deliveryOrderService; | 
|   | 
|     @Autowired | 
|     private WarehouseLocationMapper warehouseLocationMapper; | 
|   | 
|     @Autowired | 
|     private FlowerSupplierSaleNumMapper saleNumMapper; | 
|   | 
|     @Autowired | 
|     private UserWechatMapper wechatMapper; | 
|   | 
|     @Autowired | 
|     private OrderSettlementMapper settlementMapper; | 
|   | 
|     @Autowired | 
|     private OrderItemSalesMapper orderItemSalesMapper; | 
|   | 
|     @Autowired | 
|     private WeChatService weChatService; | 
|   | 
|     @Autowired | 
|     private OrderRefundMapper orderRefundMapper; | 
|   | 
|     @Autowired | 
|     private StationMapper stationMapper; | 
|   | 
|     @Autowired | 
|     private CodeService codeService; | 
|   | 
|     @Autowired | 
|     private FeeServiceMapper feeServiceMapper; | 
|   | 
|     @Autowired | 
|     private WxDeliveryGoodService wxDeliveryGoodService; | 
|   | 
|     @Autowired | 
|     private OrderItemCheckMapper orderItemCheckMapper; | 
|   | 
|     @Autowired | 
|     private OrderPointGoodsMapper pointGoodsMapper; | 
|   | 
|     @Autowired | 
|     @Lazy | 
|     private MemberGrowthRecordService memberGrowthRecordService; | 
|   | 
|     @Autowired | 
|     private CustomerPointService customerPointService; | 
|   | 
|     @Autowired | 
|     private PointGoodsService pointGoodsService; | 
|   | 
|     @Autowired | 
|     private RedisLockService lockService; | 
|   | 
|     @Autowired | 
|     private CouponRecordService couponRecordService; | 
|   | 
|   | 
|     public void changeFlower2Cart(CartSaveDTO dto) { | 
|         String userId = SecurityUtils.getUserId(); | 
|         String key = userId + "_" + dto.getId(); | 
|         boolean lock = lockService.getObjectLock(RedisLockService.LOCK_KEY_CART_, key); | 
|         if(!lock){ | 
|             return; | 
|         } | 
|   | 
|         try { | 
|             Cart c = cartMapper.selectOne(new QueryWrapper<Cart>() | 
|                     .eq("create_by", userId).eq("flower_id", dto.getId())); | 
|             if (c == null) { | 
|                 if (dto.getNum() <= 0) { | 
|                     throw new ValidationException("数量不能小于等于0,请刷新页面重试"); | 
|                 } | 
|                 c = new Cart(); | 
|                 c.setFlowerId(dto.getId()); | 
|                 c.setNum(dto.getNum()); | 
|                 c.create(userId); | 
|   | 
|                 // 限购  1.首先查看购物车中的数量是否已经超过限售数量 | 
|                 final FlowerDTO flowerDetail = flowerService.getFlowerDetail(c.getFlowerId()); | 
|                 if(null!=c.getNum() && null!=flowerDetail.getLimited() | 
|                         && c.getNum().compareTo(flowerDetail.getLimited())>0){ | 
|                     throw new ValidationException("数量不能超过限售数量!"); | 
|                 } | 
|   | 
|                 // 限购  2.查看已结单的订单的当前花朵已经购买的数量,加当前购物车的加入的数量是否超过限购的数量,查看当前5点前到昨天五点前 | 
|                 Integer completeNumToday=getFlowerCompleteNumToday(userId,c.getFlowerId()); | 
|                 Integer tmp=completeNumToday+c.getNum(); | 
|                 if(null!=tmp && null!=flowerDetail.getLimited() | 
|                       &&  tmp.compareTo(flowerDetail.getLimited())>0){ | 
|                     throw new ValidationException("当天的订单的花数量加上购物车的数量不能超过限售数量!"); | 
|                 } | 
|   | 
|                 cartMapper.insert(c); | 
|             } else { | 
|                 // 查看是否已经超过当前商品的限购数量 | 
|                 final FlowerDTO flowerDetail = flowerService.getFlowerDetail(c.getFlowerId()); | 
|                 c.setNum((c.getNum()==null?0:c.getNum()) + dto.getNum()); | 
|   | 
|                 // 限购  1.首先查看购物车中的数量是否已经超过限售数量 | 
|                 if(null!=c.getNum() && null!=flowerDetail.getLimited() | 
|                       && c.getNum().compareTo(flowerDetail.getLimited())>0){ | 
|                     throw new ValidationException("数量不能超过限售数量!"); | 
|                 } | 
|   | 
|                 // 限购  2.查看已结单的订单的当前花朵已经购买的数量,加当前购物车的加入的数量是否超过限购的数量,查看当前5点前到昨天五点前 | 
|                 Integer completeNumToday=getFlowerCompleteNumToday(userId,c.getFlowerId()); | 
|                 Integer tmp=completeNumToday+c.getNum(); | 
|                 if(null!=tmp && null!=flowerDetail.getLimited() | 
|                        && tmp.compareTo(flowerDetail.getLimited())>0){ | 
|                     throw new ValidationException("当天的订单的花数量加上购物车的数量不能超过限售数量!"); | 
|                 } | 
|   | 
|                 c.update(userId); | 
|                 if (c.getNum() <= 0) { | 
|                     cartMapper.deleteById(c.getId()); | 
|                 } else { | 
|                     cartMapper.updateById(c); | 
|                 } | 
|             } | 
|         } finally { | 
|             lockService.releaseObjectLock(RedisLockService.LOCK_KEY_CART_, key); | 
|         } | 
|     } | 
|   | 
|     public void saveFlower2Cart(CartSaveDTO dto) { | 
|         String userId = SecurityUtils.getUserId(); | 
|   | 
|         String key = userId + "_" + dto.getId(); | 
|         boolean lock = lockService.getObjectLock(RedisLockService.LOCK_KEY_CART_, key); | 
|         if(!lock){ | 
|             return; | 
|         } | 
|   | 
|         try { | 
|             Cart c = cartMapper.selectOne(new QueryWrapper<Cart>() | 
|                     .eq("create_by", userId).eq("flower_id", dto.getId())); | 
|             if (c == null) { | 
|                 c = new Cart(); | 
|                 c.setFlowerId(dto.getId()); | 
|                 c.setNum(dto.getNum()); | 
|                 c.create(userId); | 
|   | 
|                 cartMapper.insert(c); | 
|             } else { | 
|                 c.setNum(dto.getNum()); | 
|                 c.update(userId); | 
|   | 
|                 cartMapper.updateById(c); | 
|             } | 
|         } finally { | 
|             lockService.releaseObjectLock(RedisLockService.LOCK_KEY_CART_, key); | 
|         } | 
|     } | 
|   | 
|     public void deleteFlower4Cart(Long flowerId) { | 
|         String userId = SecurityUtils.getUserId(); | 
|         cartMapper.delete(new QueryWrapper<Cart>() | 
|                 .eq("create_by", userId).eq("flower_id", flowerId)); | 
|     } | 
|   | 
|     public void deleteBatchFlower4Cart(List<Long> flowerIds) { | 
|         String userId = SecurityUtils.getUserId(); | 
|         cartMapper.delete(new QueryWrapper<Cart>() | 
|                 .eq("create_by", userId).in("flower_id", flowerIds)); | 
|     } | 
|   | 
|   | 
|     public int getCartFlowerCount(String flowerId) { | 
|         String userId = SecurityUtils.getUserId(); | 
|         /*QueryWrapper<Cart> qw = new QueryWrapper<Cart>().eq("create_by", userId); | 
|         if(StringUtils.isNotEmpty(flowerId)){ | 
|             qw = qw.eq("flower_id", Long.parseLong(flowerId)); | 
|         } | 
|         return cartMapper.selectCount(qw);*/ | 
|         Long fId = null; | 
|         if (StringUtils.isNotEmpty(flowerId)) { | 
|             fId = Long.parseLong(flowerId); | 
|         } | 
|         Integer num = cartMapper.getCartFlowerCount(userId, fId); | 
|         return num == null ? 0 : num; | 
|     } | 
|   | 
|     public List<FlowerCartListWrapDTO> getFlowerCartList() { | 
|         String userId = SecurityUtils.getUserId(); | 
|         List<FlowerCartListDTO> ls = flowerMapper.selectFlowerCartList(userId); | 
|   | 
|         List<FlowerCartListWrapDTO> result = new ArrayList<>(); | 
|         if (ls != null && ls.size() > 0) { | 
|             Customer customer = getCurrentCustomer(); | 
|             Long partnerId = customer.getPartnerId(); | 
|             Long levelId = customer.getLevelId(); | 
|             Member member = getMember(levelId); | 
|   | 
|             Map<Long, FlowerCartListWrapDTO> map = new HashMap<>(); | 
|             for (FlowerCartListDTO c : ls) { | 
|                 BigDecimal price = getFinalPrice(partnerId, c.getCategory() | 
|                         , c.getId(), c.getPrice(), c.getLevel()); | 
|                 c.setPrice(price); | 
|                 c.setPriceMember(calculateMemberPrice(price, member)); | 
|   | 
|                 c.setTotal(price.multiply(new BigDecimal(c.getNum()))); | 
|                 c.setTotalMember(c.getPriceMember().multiply(new BigDecimal(c.getNum()))); | 
|   | 
|                 if (c.getSales() != null && c.getRealSales() != null) { | 
|                     c.setSales(c.getSales() + c.getRealSales()); | 
|                 } | 
|   | 
|                 Long supplierId = c.getSupplierId(); | 
|                 FlowerCartListWrapDTO w = map.get(supplierId); | 
|                 if (w == null) { | 
|                     w = new FlowerCartListWrapDTO(); | 
|                     w.setSupplierId(supplierId); | 
|                     w.setSupplierName(c.getSupplierName()); | 
|                     w.setFlowerList(new ArrayList<>()); | 
|                     map.put(supplierId, w); | 
|                     result.add(w); | 
|                 } | 
|                 w.getFlowerList().add(c); | 
|             } | 
|         } | 
|   | 
|         return result; | 
|     } | 
|   | 
|     public PreOrderDTO getPreOrderInfo(List<CartSaveDTO> flowers) { | 
|         return getPreOrderInfo(flowers, null); | 
|     } | 
|   | 
|     public PreOrderDTO getPreOrderInfo(List<CartSaveDTO> flowers, Map<Long, PriceDTO> priceMap) { | 
|         String userId = SecurityUtils.getUserId(); | 
|   | 
|         if (flowers == null || flowers.size() == 0) { | 
|             throw new ValidationException("请选择商品"); | 
|         } | 
|   | 
|         List<Long> ids = new ArrayList<>(); | 
|         Map<Long, Integer> idNumMap = new HashMap<>(); | 
|         for (CartSaveDTO c : flowers) { | 
|             Long id = c.getId(); | 
|             Integer num = c.getNum(); | 
|             ids.add(id); | 
|             if (num == null || num <= 0) { | 
|                 throw new ValidationException("商品的数量不能为零"); | 
|             } | 
|             idNumMap.put(id, num); | 
|         } | 
|   | 
|         // 限购数量校验 鲜花数量校验 | 
|         flowers.forEach(cartSaveDTO -> { | 
|             // 限购数量 鲜花数量校验 | 
|             Integer completeNumToday=getFlowerCompleteNumToday(userId,cartSaveDTO.getId()); | 
|             Integer tmp=completeNumToday+cartSaveDTO.getNum(); | 
|             Flower flower=flowerMapper.selectById(cartSaveDTO.getId()); | 
|             if(null!=flower.getLimited() && tmp.compareTo(flower.getLimited())>0){ | 
|                 throw new ValidationException("商品:'"+flower.getName()+"' 昨天17:00到今天17:00 超过限售数量:"+flower.getLimited()+"!"); | 
|             } | 
|         }); | 
|   | 
|         PreOrderDTO result = new PreOrderDTO(); | 
|   | 
|         List<FlowerCartListDTO> ls = flowerMapper.selectFlowerOrderList(ids); | 
|         Customer customer = getCurrentCustomer(); | 
|         Long partnerId = customer.getPartnerId(); | 
|         Long levelId = customer.getLevelId(); | 
|         Member member = getMember(levelId); | 
|         if (member != null) { | 
|             result.setMemberId(levelId); | 
|             result.setMemberName(member.getName()); | 
|             result.setMemberDiscountType(member.getDiscountType()); | 
|             result.setMemberDiscountRatio(member.getDiscountRatio()); | 
|             result.setMemberDiscountAmount(member.getDiscountAmount()); | 
|         } | 
|   | 
|         double totalWeight = 0D; | 
|         int num = 0; | 
|         BigDecimal totalAmount = new BigDecimal(0); | 
|         BigDecimal totalMemberAmount = new BigDecimal(0); | 
|         for (FlowerCartListDTO c : ls) { | 
|             if (!Constants.FLOWER_STATUS.UP.name().equals(c.getStatus())) { | 
|                 throw new ValidationException("商品" + c.getName() + "已下架,请重新提交"); | 
|             } | 
|   | 
|             if (c.getWeight() == null) { | 
|                 throw new ValidationException("商品" + c.getName() + "无法预估重量,请联系管理员"); | 
|             } | 
|   | 
|             c.setNum(idNumMap.get(c.getId())); | 
|   | 
|             if (c.getStock() == null || c.getStock() < c.getNum()) { | 
|                 throw new ValidationException("商品" + c.getName() + "库存不足"); | 
|             } | 
|   | 
|             PriceDTO priceDTO = getFinalPriceDTO(partnerId, c.getCategory() | 
|                     , c.getId(), c.getPrice(), c.getLevel()); | 
|             BigDecimal price = priceDTO.getPrice(); | 
|             c.setPrice(price); | 
|             c.setPriceMember(calculateMemberPrice(price, member)); | 
|   | 
|             c.setTotal(price.multiply(new BigDecimal(c.getNum()))); | 
|             c.setTotalMember(c.getPriceMember().multiply(new BigDecimal(c.getNum())));//使用会员价计算总价 | 
|   | 
|             if (priceMap != null) { | 
|                 priceMap.put(c.getId(), priceDTO); | 
|             } | 
|   | 
|             totalWeight += c.getWeight() * c.getNum(); | 
|             totalAmount = totalAmount.add(c.getTotal()); | 
|             totalMemberAmount = totalMemberAmount.add(c.getTotalMember()); | 
|             num += c.getNum(); | 
|         } | 
|   | 
|         BigDecimal packing = new BigDecimal(8); | 
|         if (partnerId != null || num >= 20) { | 
|             packing = new BigDecimal(0); | 
|         } | 
|         result.setFlowers(ls); | 
|         result.setPacking(packing); | 
|         result.setTotalAmount(totalAmount); | 
|         result.setTotalMemberAmount(totalMemberAmount); | 
|         result.setTotalWeight(totalWeight); | 
|   | 
|         return result; | 
|     } | 
|   | 
|     public synchronized PreOrderDTO processPreOrderInfo(List<CartSaveDTO> flowers, Map<Long, PriceDTO> priceMap) { | 
|         PreOrderDTO p = getPreOrderInfo(flowers, priceMap); | 
|         for (CartSaveDTO c : flowers) { | 
|             flowerMapper.addFlowerStock(c.getId(), -c.getNum()); | 
|         } | 
|   | 
|         return p; | 
|     } | 
|   | 
|     public synchronized void revertFlowerStock(List<CartSaveDTO> flowers) { | 
|         for (CartSaveDTO c : flowers) { | 
|             flowerMapper.addFlowerStock(c.getId(), c.getNum()); | 
|         } | 
|     } | 
|   | 
|     public Map commitOrder(OrderCommitDTO dto, PreOrderDTO p, Map<Long, PriceDTO> priceMap) { | 
|         String userId = SecurityUtils.getUserId(); | 
|         p.getFlowers().forEach(flower -> { | 
|             // 限购数量 鲜花数量校验 | 
|             Integer completeNumToday=getFlowerCompleteNumToday(userId,flower.getId()); | 
|             Integer tmp=completeNumToday+flower.getNum(); | 
|             if(null!=tmp && null!=flower.getLimited() | 
|                     && tmp.compareTo(flower.getLimited())>0){ | 
|                 throw new ValidationException("商品:'"+flower.getName()+"' 昨天17:00到今天17:00 超过限售数量:"+flower.getLimited()+"!"); | 
|             } | 
|         }); | 
|   | 
|         WxMaJscode2SessionResult session = null; | 
|         try { | 
|             session = weChatService.getWxMaSessionInfo(dto.getWxcode()); | 
|         } catch (WxErrorException e) { | 
|             throw new ValidationException("微信登录失败"); | 
|         } | 
|         String openId = session.getOpenid(); | 
|         if (StringUtils.isBlank(openId)) { | 
|             throw new ValidationException("微信登录失败"); | 
|         } | 
|   | 
|         Address address = addressMapper.selectById(dto.getAddressId()); | 
|         List<TransportOrderDTO> tLs = transportService.getPreOrderTransportList(address | 
|                 , p.getTotalWeight(), dto.getTransportId()); | 
|         BigDecimal transportFee = new BigDecimal(0); | 
|         String deliveryName = ""; | 
|         if (tLs != null && tLs.size() > 0) { | 
|             TransportOrderDTO d = tLs.get(0); | 
|             transportFee = d.getFee(); | 
|             deliveryName = d.getName(); | 
|         } | 
|   | 
|   | 
|         Order order = new Order(); | 
|         order.setId(UUIDGenerator.getUUID()); | 
|   | 
|         final List<Long> goodsRecordIdList = dto.getGoodsRecordIdList(); | 
|         usePointGoods(order.getId(), goodsRecordIdList);//使用积分商品兑换券 | 
|   | 
|         order.create(userId); | 
|         order.setRemarks(dto.getRemarks()); | 
|         order.setSpecialNeeds(dto.getSpecialNeeds()); | 
|         order.setStatusBackend(Constants.ORDER_STATUS_BACKEND.PENDING.name()); | 
|         order.setStatus(Constants.ORDER_STATUS.PENDING.name()); | 
|   | 
|         //设置下单时的会员信息 | 
|         order.setMemberId(p.getMemberId()); | 
|         order.setMemberName(p.getMemberName()); | 
|         order.setMemberDiscountType(p.getMemberDiscountType()); | 
|         order.setMemberDiscountRatio(p.getMemberDiscountRatio()); | 
|         order.setMemberCouponAmount(p.getMemberDiscountAmount()); | 
|   | 
|         order.setFlowerAmount(p.getTotalMemberAmount());//使用会员价总价 | 
|         order.setPackingFee(p.getPacking()); | 
|         order.setTransportFee(transportFee); | 
|         order.setDeliveryName(deliveryName); | 
|   | 
|         BigDecimal totalAmount = order.getFlowerAmount();//使用优惠券之前的总价,使用商品价格 | 
|         CouponRecordDO coupon = useCouponRecord(order.getId(), totalAmount, dto.getCouponRecordId()); | 
|         log.info("用户优惠券: " + coupon); | 
|         if(coupon != null){ | 
|             order.setMemberCouponId(coupon.getId()); | 
|             order.setMemberCouponCode(coupon.getCouponCode()); | 
|             order.setMemberCouponName(coupon.getCouponName()); | 
|             order.setMemberCouponAmount(coupon.getCouponDiscountValue()); | 
|   | 
|             totalAmount = totalAmount.subtract(order.getMemberCouponAmount());//满足条件需要减去优惠券金额 | 
|         } | 
|         if(totalAmount.doubleValue() < 0){//假如扣除优惠券后金额小于0,则按0计算 | 
|             totalAmount = new BigDecimal(0); | 
|         } | 
|         totalAmount = totalAmount.add(p.getPacking()).add(transportFee); | 
|         if(totalAmount.doubleValue() <= 0){//假如总价小于等于0,则支付0.01元 | 
|             totalAmount = new BigDecimal(0.01); | 
|         } | 
|         order.setTotalAmount(totalAmount); | 
|   | 
|         order.setCustomer(address.getName()); | 
|         order.setCustomerTel(address.getTel()); | 
|         order.setCustomerProvince(address.getProvince()); | 
|         order.setCustomerCity(address.getCity()); | 
|         order.setCustomerRegion(address.getRegion()); | 
|         order.setCustomerAddress(address.getAddress()); | 
|   | 
|         Customer customer = getCurrentCustomer(); | 
|         Long partnerId = customer.getPartnerId(); | 
|         order.setPartnerId(partnerId); | 
|         if (partnerId != null) { | 
|             Partner pp = partnerMapper.selectById(partnerId); | 
|             order.setPartnerName(pp == null ? "" : pp.getName()); | 
|         } | 
|   | 
|         //商品列表处理 | 
|         List<FlowerCartListDTO> flowers = p.getFlowers(); | 
|         Map<Long, List<ParamItemDTO>> paramMap = new HashMap<>(); | 
|         final BigDecimal flowerAmount = order.getFlowerAmount();//订单商品总价 | 
|         final BigDecimal memberCouponAmount = getAmount(order.getMemberCouponAmount());//使用优惠券面值 | 
|         BigDecimal usedCouponAmount = new BigDecimal(0); | 
|         for (int i = 0; i < flowers.size(); i++) { | 
|             FlowerCartListDTO f = flowers.get(i); | 
|   | 
|             OrderItem t = new OrderItem(); | 
|             t.setId(UUIDGenerator.getUUID()); | 
|             t.setOrderId(order.getId()); | 
|             t.setFlowerId(f.getId()); | 
|             t.setFlowerCover(f.getCover()); | 
|             t.setFlowerName(f.getName()); | 
|             t.setFlowerUnit(f.getUnit()); | 
|             t.setFlowerColor(f.getColor()); | 
|             t.setFlowerLevel(f.getLevel()); | 
|             t.setFlowerCategory(f.getCategoryStr()); | 
|   | 
|             List<ParamItemDTO> params = flowerService.getFlowerParams(f.getParamId(), f.getId(), paramMap); | 
|             t.setFlowerParams(toJSONString(params)); | 
|   | 
|             t.setNum(f.getNum()); | 
|             t.setSupplierId(f.getSupplierId()); | 
|             t.setSupplierName(f.getSupplierName()); | 
|             t.setStationId(f.getStationId()); | 
|   | 
|             PriceDTO pp = priceMap.get(t.getFlowerId()); | 
|             t.setSupplierPrice(pp.getOrgPrice()); | 
|             t.setMarkupOne(pp.getFirstFee()); | 
|             t.setMarkupTwo(pp.getSecondFee()); | 
|             t.setMarkupPartner(pp.getPartnerFee()); | 
|             t.setPrice(f.getPriceMember());//使用会员单价 | 
|             t.setTotal(f.getTotalMember());//使用会员总价 | 
|   | 
|             t.setOriginalPrice(pp.getPrice());//非会员售价 | 
|             boolean isLastOne = i == (flowers.size() - 1); | 
|             BigDecimal couponAmount = calculateCoupon(memberCouponAmount, t.getTotal() | 
|                     , flowerAmount, t.getNum(), t.getPrice(), isLastOne, usedCouponAmount); | 
|             t.setCouponAmount(couponAmount);//每扎平摊的优惠券面值 | 
|             t.setRealPrice(t.getPrice().subtract(couponAmount));//退款时使用的真实成交单价 | 
|   | 
|             t.setCouponAmountTotal(couponAmount.multiply(BigDecimal.valueOf(t.getNum()))); | 
|             if(isLastOne){ | 
|                 t.setCouponAmountTotal(memberCouponAmount.subtract(usedCouponAmount)); | 
|             } else { | 
|                 usedCouponAmount = usedCouponAmount.add(t.getCouponAmountTotal()); | 
|             } | 
|             t.setRealTotal(t.getTotal().subtract(t.getCouponAmountTotal())); | 
|   | 
|             t.create(userId); | 
|             orderItemMapper.insert(t); | 
|   | 
|             deleteFlower4Cart(f.getId()); | 
|         } | 
|   | 
|         order.setOrderNo(getOrderNo()); | 
|         order.setPayOpenid(openId); | 
|         orderMapper.insert(order); | 
|   | 
|         //处理积分商品兑换券 | 
|         if(goodsRecordIdList != null && goodsRecordIdList.size() > 0){ | 
|             for(Long goodsRecordId : goodsRecordIdList){ | 
|                 OrderPointGoods g = new OrderPointGoods(); | 
|                 g.setId(UUIDGenerator.getUUID()); | 
|                 g.setOrderId(order.getId()); | 
|                 g.setGoodsRecordId(goodsRecordId); | 
|                 g.create(userId); | 
|                 pointGoodsMapper.insert(g); | 
|             } | 
|         } | 
|   | 
|         Map map = paymentV3Service.wxPrepay(order); | 
|         map.put("_testV2OrderId", order.getId()); | 
|         return map; | 
|     } | 
|   | 
|     private void usePointGoods(String orderId, List<Long> goodsRecordIdList){ | 
|         //使用积分商品兑换券 | 
|         if(goodsRecordIdList != null && goodsRecordIdList.size() > 0){ | 
|             for(Long grId : goodsRecordIdList){ | 
|                 pointGoodsService.useExchangeGoods(grId, orderId); | 
|             } | 
|         } | 
|     } | 
|   | 
|     /** | 
|      * 计算订单中每种商品每扎平摊的优惠券面值,保留2位小数 | 
|      * | 
|      * @param couponAmount | 
|      * @param itemTotalAmount | 
|      * @param totalAmount | 
|      * @param num | 
|      * @param price | 
|      * @return | 
|      */ | 
|     private BigDecimal calculateCoupon(BigDecimal couponAmount, BigDecimal itemTotalAmount | 
|             , BigDecimal totalAmount, Integer num, BigDecimal price | 
|             , boolean isLastOne, BigDecimal usedCouponAmount){ | 
|         if(couponAmount == null || couponAmount.doubleValue() == 0){ | 
|             return new BigDecimal(0); | 
|         } | 
|   | 
|         if(couponAmount.doubleValue() >= totalAmount.doubleValue()){ | 
|             return price; | 
|         } | 
|         if(isLastOne){//最后的商品使用优惠券剩下的面值 | 
|             BigDecimal subCoupon = couponAmount.subtract(usedCouponAmount);//占有的优惠券面值 | 
|             return subCoupon.divide(BigDecimal.valueOf(num), 2, RoundingMode.HALF_UP); | 
|         } | 
|   | 
|         /*BigDecimal radio = itemTotalAmount.divide(totalAmount, 2, RoundingMode.HALF_UP);//计算该商品总价在订单中的占比 | 
|         BigDecimal subCoupon = couponAmount.multiply(radio);//占有的优惠券面值 | 
|         return subCoupon.divide(BigDecimal.valueOf(num), 2, RoundingMode.HALF_UP);*/ | 
|   | 
|         //不能分步计算,分步计算会有精度问题 | 
|         return couponAmount.multiply(itemTotalAmount).divide(totalAmount.multiply(BigDecimal.valueOf(num)), 2, RoundingMode.HALF_UP); | 
|     } | 
|   | 
|     private CouponRecordDO useCouponRecord(String orderId, BigDecimal amount, String couponRecordId){ | 
|         log.info("使用用户优惠券id: " + couponRecordId + "; 订单id: " + orderId); | 
|         if(StringUtils.isNotEmpty(couponRecordId)){ | 
|             //优惠券使用和验证,如果不符合使用条件需要抛出异常。需调用优惠券使用方法 | 
|             couponRecordService.useCoupon(couponRecordId, orderId, amount); | 
|             return couponRecordService.getCouponRecordById(couponRecordId); | 
|         } | 
|   | 
|         return null; | 
|     } | 
|   | 
|     private String getOrderNo() { | 
|         String seq = sequenceNo.getSeqNo(SequenceNo.ORDER_FLOWER); | 
|         return "XH" + format(LocalDateTime.now(), "yyyyMMdd") + seq; | 
|     } | 
|   | 
|     public IPage<Order> unAllocatedWarehouseLocationOrder(String orderNo, Long partnerId, Page page) { | 
|         // 获取当前日期和时间 | 
|         LocalDateTime currentDateTime = LocalDateTime.now(); | 
|         // 获取当前的小时 | 
|         int currentHour = currentDateTime.getHour(); | 
|         LocalDateTime start = null; | 
|         LocalDateTime end = null; | 
|         if (currentHour >= 2 && currentHour <= 23) { //没有跨天 | 
|             start = LocalDate.now().plusDays(-1).atTime(17, 0, 0); | 
|             end = LocalDate.now().atTime(16, 59, 59); | 
|         } else { //跨天 | 
|             start = LocalDate.now().plusDays(-2).atTime(17, 0, 0); | 
|             end = LocalDate.now().plusDays(-1).atTime(16, 59, 59); | 
|         } | 
|         QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<Order>().eq("deleted", 0) | 
|                 .eq("status_backend", Constants.ORDER_STATUS_BACKEND.PAYMENT.name()) | 
|                 .gt("payment_time", start).le("payment_time", end) | 
|                 .isNull("warehouse_location_id").orderByDesc("partner_id").orderByAsc("payment_time"); | 
|         if (StringUtils.isNotBlank(orderNo)) { | 
|             orderQueryWrapper.like("order_no", orderNo); | 
|         } | 
|         if (partnerId != null) { | 
|             orderQueryWrapper.eq("partner_id", partnerId); | 
|         } | 
|         IPage iPage = orderMapper.selectPage(page, orderQueryWrapper); | 
|         return iPage; | 
|     } | 
|   | 
|   | 
|     /** | 
|      * 查询待分配库位的订单 | 
|      * | 
|      * @return | 
|      */ | 
|     public List<Order> selectPaymentOrderList() { | 
|         LocalDateTime start = LocalDate.now().plusDays(-1).atTime(17, 0, 0); | 
|         LocalDateTime end = LocalDate.now().atTime(16, 59, 59); | 
|         List<Order> orders = orderMapper.selectList(new QueryWrapper<Order>().eq("deleted", 0) | 
|                 .eq("status_backend", Constants.ORDER_STATUS_BACKEND.PAYMENT.name()) | 
|                 .gt("payment_time", start).le("payment_time", end) | 
|                 .isNull("warehouse_location_id").orderByAsc("payment_time") | 
|         ); | 
|   | 
|         return orders; | 
|     } | 
|   | 
|     /** | 
|      * 分配订单库位 | 
|      */ | 
|     public void allocatedWarehouseLocation(String orderId | 
|             , Long warehouseId, String warehouseName | 
|             , Long warehouseLocationId, String warehouseLocationCode) { | 
|         //修改后台状态 | 
|         Order order = orderMapper.selectById(orderId); | 
|         order.setWarehouseId(warehouseId); | 
|         order.setWarehouseName(warehouseName); | 
|         order.setWarehouseLocationId(warehouseLocationId); | 
|         order.setWarehouseLocationCode(warehouseLocationCode); | 
|         order.setStatusBackend(Constants.ORDER_STATUS_BACKEND.COLLECTION.name()); | 
|         order.setWarehouseTime(LocalDateTime.now()); | 
|         order.update("sys"); | 
|         orderMapper.updateById(order); | 
|   | 
|         //更新配库状态 | 
|         deliveryOrderService.setDeliveryOrderPending(orderId); | 
|     } | 
|   | 
|   | 
|     public void addOrder(Long warehouseLocationId, String orderId) { | 
|         WarehouseLocationDTO location = warehouseLocationMapper.findById(warehouseLocationId); | 
|         if (location == null) { | 
|             throw new ValidationException("库位不存在"); | 
|         } | 
|         if (!"手动分配区".equalsIgnoreCase(location.getWarehouseName())) {//非手动分配区,限制17点之后手动添加订单 | 
|             LocalDateTime currentDateTime = LocalDateTime.now(); | 
|             // 获取当前的小时 | 
|             int currentHour = currentDateTime.getHour(); | 
|             if (currentHour >= 2 && currentHour < 17) { //没有跨天 | 
|                 throw new ValidationException("非手动分配区,当前时间不能添加订单,请17点后分配订单"); | 
|             } | 
|         } | 
|         allocatedWarehouseLocation(orderId, location.getWarehouseId(), location.getWarehouseName(), warehouseLocationId, location.getCode()); | 
|     } | 
|   | 
|     /** | 
|      * 合伙人订单定时发货 | 
|      */ | 
|     public void setPartnerOrderSend() { | 
|         List<Order> orders = orderMapper.getPartnerOrderReceive(); | 
|         if(orders == null || orders.size() == 0){ | 
|             return; | 
|         } | 
|         for (Order o : orders) { | 
|             //set status_backend = 'RECEIVE', status = 'RECEIVE' | 
|             o.setStatusBackend("RECEIVE"); | 
|             o.setStatus("RECEIVE"); | 
|             //发送微信发货请求 | 
|             JSONObject jsonObject = sendWxDeliveryGood(o); | 
|             if (jsonObject != null && (int) jsonObject.get("errcode") == 0) { | 
|                 o.setWxDeliveryGood(true); | 
|                 o.setWxDeliveryMsg(GsonUtil.toJson(jsonObject)); | 
|             } else { | 
|                 o.setWxDeliveryGood(false); | 
|                 o.setWxDeliveryMsg(GsonUtil.toJson(jsonObject)); | 
|             } | 
|   | 
|             orderMapper.updateById(o); | 
|         } | 
|         //orderMapper.setPartnerOrderReceive(); | 
|     } | 
|   | 
|     /** | 
|      * 没有合伙人的花店上传快递号发货 | 
|      * | 
|      * @param dto | 
|      */ | 
|     public void saveDeliveryNo(OrderDeliveryNoDTO dto) { | 
|         if (StringUtils.isEmpty(dto.getDeliveryNo())) { | 
|             throw new ValidationException("快递号不能为空"); | 
|         } | 
|         Order o = orderMapper.selectById(dto.getId()); | 
|         if (!Constants.ORDER_STATUS_BACKEND.SEND.name().equals(o.getStatusBackend())) { | 
|             throw new ValidationException("请先完成质检"); | 
|         } | 
|         o.setDeliveryNo(dto.getDeliveryNo()); | 
|         o.setStatus(Constants.ORDER_STATUS.RECEIVE.name()); | 
|         o.setStatusBackend(Constants.ORDER_STATUS_BACKEND.RECEIVE.name()); | 
|         o.update(SecurityUtils.getUserId()); | 
|   | 
|         //发送微信发货请求 | 
|         JSONObject jsonObject = sendWxDeliveryGood(o); | 
|         if (jsonObject != null && (int) jsonObject.get("errcode") == 0) { | 
|             o.setWxDeliveryGood(true); | 
|             o.setWxDeliveryMsg(GsonUtil.toJson(jsonObject)); | 
|         } else { | 
|             o.setWxDeliveryGood(false); | 
|             o.setWxDeliveryMsg(GsonUtil.toJson(jsonObject)); | 
|         } | 
|   | 
|         orderMapper.updateById(o); | 
|     } | 
|   | 
|     public Page<OrderListDTO> selectOrderList(Page page, OrderQueryDTO dto) { | 
|         List<OrderListDTO> ls = getOrderList(page, dto); | 
|   | 
|         page.setRecords(ls); | 
|         return page; | 
|     } | 
|   | 
|     private List<OrderListDTO> getOrderListBase(Page page, OrderQueryDTO dto) { | 
|         dto.setStartDate(parseLocalDateTime(dto.getStartDateStr(), true)); | 
|         dto.setEndDate(parseLocalDateTime(dto.getEndDateStr(), false)); | 
|   | 
|         dto.setCreateStartDate(parseLocalDateTime(dto.getCreateStartDateStr(), 17, 0, 0, -1)); | 
|         dto.setCreateEndDate(parseLocalDateTime(dto.getCreateEndDateStr(), 17, 0, 0, 0)); | 
|   | 
|         List<OrderListDTO> ls = orderMapper.selectOrderList(page, dto); | 
|   | 
|         return ls; | 
|     } | 
|   | 
|     public List<OrderStatusCountDTO> getOrderStatusCount(OrderQueryDTO dto) { | 
|         dto.setStartDate(parseLocalDateTime(dto.getStartDateStr(), true)); | 
|         dto.setEndDate(parseLocalDateTime(dto.getEndDateStr(), false)); | 
|   | 
|         dto.setCreateStartDate(parseLocalDateTime(dto.getCreateStartDateStr(), 17, 0, 0, -1)); | 
|         dto.setCreateEndDate(parseLocalDateTime(dto.getCreateEndDateStr(), 17, 0, 0, 0)); | 
|   | 
|         List<CodeValueDTO> ls = codeService.searchValue("ORDER_STATUS_BACKEND"); | 
|         List<OrderStatusCountDTO> ll = orderMapper.getOrderStatusCount(dto); | 
|         Map<String, Integer> llMap = new HashMap<>(); | 
|         if (ll != null && ll.size() > 0) { | 
|             for (OrderStatusCountDTO c : ll) { | 
|                 llMap.put(c.getValue(), c.getOrderCount()); | 
|             } | 
|         } | 
|   | 
|         List<OrderStatusCountDTO> rr = new ArrayList<>(); | 
|         for (CodeValueDTO c : ls) { | 
|             OrderStatusCountDTO r = new OrderStatusCountDTO(); | 
|             r.setValue(c.getValue()); | 
|             r.setLabel(c.getLabel()); | 
|             Integer count = llMap.get(r.getValue()); | 
|             r.setOrderCount(count == null ? 0 : count); | 
|   | 
|             rr.add(r); | 
|         } | 
|   | 
|         return rr; | 
|     } | 
|   | 
|     public List<OrderListDTO> getOrderList(Page page, OrderQueryDTO dto) { | 
|         List<OrderListDTO> ls = getOrderListBase(page, dto); | 
|         if (ls != null && ls.size() > 0) { | 
|             List<String> orderIds = new ArrayList<>(); | 
|             Map<String, OrderListDTO> orderMap = new HashMap<>(); | 
|             for (OrderListDTO o : ls) { | 
|                 o.setCouldRefund(couldRefund(o.getStatusBackend(), o.getPaymentTime())); | 
|                 orderIds.add(o.getId()); | 
|                 orderMap.put(o.getId(), o); | 
|             } | 
|   | 
|             List<OrderItemListDTO> itemList = orderItemMapper.getOrderItems(orderIds); | 
|             Map<String, List<OrderItemListDTO>> map = new HashMap<>(); | 
|             for (OrderItemListDTO oi : itemList) { | 
|                 String orderId = oi.getOrderId(); | 
|                 List<OrderItemListDTO> ll = map.computeIfAbsent(orderId, k -> new ArrayList<>()); | 
|                 OrderItemListDTO d = new OrderItemListDTO(); | 
|                 BeanUtils.copyProperties(oi, d); | 
|   | 
|                 OrderListDTO o = orderMap.get(orderId); | 
|                 if(dto.isCustomerQuery() && o != null && StringUtils.isEmpty(o.getTransferId())){ | 
|                     d.setReduceNum(0); | 
|                     d.setLackNum(0); | 
|                     d.setReplaceNum(0); | 
|                 } | 
|   | 
|                 ll.add(d); | 
|             } | 
|   | 
|             for (OrderListDTO o : ls) { | 
|                 o.setItems(map.get(o.getId())); | 
|             } | 
|         } | 
|   | 
|         return ls; | 
|     } | 
|   | 
|     public Page<OrderPlatformListDTO> selectOrderPlatformList(Page page, OrderQueryDTO dto) { | 
|         List<OrderPlatformListDTO> result = new ArrayList<>(); | 
|         List<OrderListDTO> ls = getOrderListBase(page, dto); | 
|         if (ls != null && ls.size() > 0) { | 
|             List<String> orderIds = new ArrayList<>(); | 
|             for (OrderListDTO o : ls) { | 
|                 o.setCouldRefund(couldRefund(o.getStatusBackend(), o.getPaymentTime())); | 
|                 orderIds.add(o.getId()); | 
|   | 
|                 OrderPlatformListDTO p = new OrderPlatformListDTO(); | 
|                 BeanUtils.copyProperties(o, p); | 
|                 result.add(p); | 
|             } | 
|   | 
|             List<OrderItem> itemList = orderItemMapper.selectList( | 
|                     new QueryWrapper<OrderItem>().in("order_id", orderIds)); | 
|             Map<String, List<OrderItemPlatformListDTO>> map = new HashMap<>(); | 
|             for (OrderItem oi : itemList) { | 
|                 String orderId = oi.getOrderId(); | 
|                 List<OrderItemPlatformListDTO> ll = map.computeIfAbsent(orderId, k -> new ArrayList<>()); | 
|                 OrderItemPlatformListDTO d = new OrderItemPlatformListDTO(); | 
|                 BeanUtils.copyProperties(oi, d); | 
|                 ll.add(d); | 
|             } | 
|   | 
|             for (OrderPlatformListDTO o : result) { | 
|                 List<OrderItemPlatformListDTO> items = map.get(o.getId()); | 
|                 o.setItems(items); | 
|                 BigDecimal supplierAmount = new BigDecimal(0); | 
|                 if (items != null && items.size() > 0) { | 
|                     for (OrderItemPlatformListDTO it : items) { | 
|                         BigDecimal sp = it.getSupplierPrice() == null ? new BigDecimal(0) : it.getSupplierPrice(); | 
|                         int num = it.getNum() == null ? 0 : it.getNum(); | 
|                         supplierAmount = supplierAmount.add(sp.multiply(new BigDecimal(num))); | 
|                     } | 
|                 } | 
|                 o.setSupplierAmount(supplierAmount); | 
|             } | 
|         } | 
|   | 
|         page.setRecords(result); | 
|         return page; | 
|     } | 
|   | 
|     public List<OrderCheckListDTO> selectOrderCheckList(OrderQueryDTO dto) { | 
|         dto.setIdList(splitParam(dto.getIds())); | 
|         dto.setStartDate(parseLocalDateTime(dto.getStartDateStr(), true)); | 
|         dto.setEndDate(parseLocalDateTime(dto.getEndDateStr(), false)); | 
|   | 
|         dto.setCreateStartDate(parseLocalDateTime(dto.getCreateStartDateStr(), 17, 0, 0, -1)); | 
|         dto.setCreateEndDate(parseLocalDateTime(dto.getCreateEndDateStr(), 17, 0, 0, 0)); | 
|   | 
|         List<OrderCheckListDTO> ls = orderMapper.selectOrderCheckList(dto); | 
|         if (ls != null && ls.size() > 0) { | 
|             List<String> orderIds = new ArrayList<>(); | 
|             for (OrderCheckListDTO c : ls) { | 
|                 orderIds.add(c.getId()); | 
|             } | 
|   | 
|             Map<Long, String> stationMap = prepareStationMap(); | 
|   | 
|             List<OrderItem> itemList = orderItemMapper.selectList( | 
|                     new QueryWrapper<OrderItem>().in("order_id", orderIds)); | 
|             Map<String, List<OrderItemListDTO>> map = new HashMap<>(); | 
|             for (OrderItem oi : itemList) { | 
|                 String orderId = oi.getOrderId(); | 
|                 List<OrderItemListDTO> ll = map.computeIfAbsent(orderId, k -> new ArrayList<>()); | 
|                 OrderItemListDTO d = new OrderItemListDTO(); | 
|                 BeanUtils.copyProperties(oi, d); | 
|                 d.setStationName(stationMap.get(oi.getStationId())); | 
|   | 
|                 ll.add(d); | 
|             } | 
|   | 
|             for (OrderCheckListDTO c : ls) { | 
|                 c.setItems(map.get(c.getId())); | 
|             } | 
|         } | 
|   | 
|         return ls; | 
|     } | 
|   | 
|     public List<OrderCheckLocationListDTO> selectOrderCheckLocationList(OrderQueryDTO dto) { | 
|         dto.setIdList(splitParam(dto.getIds())); | 
|         dto.setStartDate(parseLocalDateTime(dto.getStartDateStr(), true)); | 
|         dto.setEndDate(parseLocalDateTime(dto.getEndDateStr(), false)); | 
|   | 
|         dto.setCreateStartDate(parseLocalDateTime(dto.getCreateStartDateStr(), 17, 0, 0, -1)); | 
|         dto.setCreateEndDate(parseLocalDateTime(dto.getCreateEndDateStr(), 17, 0, 0, 0)); | 
|   | 
|         List<OrderCheckListDTO> ls = orderMapper.selectOrderCheckList(dto); | 
|   | 
|         List<OrderCheckLocationListDTO> result = new ArrayList<>(); | 
|   | 
|         if (ls != null && ls.size() > 0) { | 
|             List<String> orderIds = new ArrayList<>(); | 
|             Map<Long, OrderCheckLocationListDTO> rMap = new HashMap<>(); | 
|             Map<String, OrderCheckListDTO> orderMap = new HashMap<>(); | 
|             for (OrderCheckListDTO c : ls) { | 
|                 orderIds.add(c.getId()); | 
|   | 
|                 orderMap.put(c.getId(), c); | 
|   | 
|                 Long locationId = c.getWarehouseLocationId(); | 
|                 OrderCheckLocationListDTO llc = rMap.get(locationId); | 
|                 if(llc == null){ | 
|                     llc = new OrderCheckLocationListDTO(); | 
|                     BeanUtils.copyProperties(c, llc); | 
|                     llc.setTotalAmount(new BigDecimal(0)); | 
|   | 
|                     rMap.put(locationId, llc); | 
|                     result.add(llc); | 
|                 } | 
|   | 
|                 BigDecimal t = llc.getTotalAmount(); | 
|                 if(t == null){ | 
|                     t = new BigDecimal(0); | 
|                 } | 
|                 t = t.add(c.getTotalAmount()); | 
|                 llc.setTotalAmount(t); | 
|             } | 
|   | 
|             Map<Long, String> stationMap = prepareStationMap(); | 
|   | 
|             List<OrderItem> itemList = orderItemMapper.selectList(new QueryWrapper<OrderItem>() | 
|                     .in("order_id", orderIds)); | 
|             Map<String, List<OrderItemLocationListDTO>> map = new HashMap<>(); | 
|   | 
|             for (OrderItem oi : itemList) { | 
|                 String orderId = oi.getOrderId(); | 
|                 List<OrderItemLocationListDTO> ll = map.computeIfAbsent(orderId, k -> new ArrayList<>()); | 
|                 OrderItemLocationListDTO d = new OrderItemLocationListDTO(); | 
|                 BeanUtils.copyProperties(oi, d); | 
|                 d.setStationName(stationMap.get(oi.getStationId())); | 
|   | 
|                 OrderCheckListDTO c = orderMap.get(oi.getOrderId()); | 
|                 d.setOrderNo(c.getOrderNo()); | 
|                 d.setOrderId(c.getId()); | 
|   | 
|                 ll.add(d); | 
|             } | 
|   | 
|             for (OrderCheckListDTO c : ls) { | 
|                 String orderId = c.getId(); | 
|                 Long locationId = c.getWarehouseLocationId(); | 
|                 OrderCheckLocationListDTO r = rMap.get(locationId); | 
|                 List<OrderItemLocationListDTO> items = r.getItems(); | 
|                 if(items == null){ | 
|                     items = new ArrayList<>(); | 
|                     r.setItems(items); | 
|                 } | 
|                 items.addAll(map.get(orderId)); | 
|             } | 
|         } | 
|   | 
|         return result; | 
|     } | 
|   | 
|     public Page<OrderListDTO> selectPartnerOrderList(Page page, OrderQueryDTO dto) { | 
|         Partner p = getCurrentPartner(); | 
|         dto.setPartnerId(p.getId()); | 
|   | 
|         return selectOrderList(page, dto); | 
|     } | 
|   | 
|     public Page<OrderListDTO> selectCustomerOrderList(Page page, OrderQueryDTO dto) { | 
|         dto.setCreateBy(SecurityUtils.getUserId()); | 
|         dto.setCustomerQuery(true); | 
|   | 
|         return selectOrderList(page, dto); | 
|     } | 
|   | 
|     public OrderDTO getOrderInfo(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         OrderDTO dto = new OrderDTO(); | 
|         BeanUtils.copyProperties(o, dto); | 
|         dto.setCouldRefund(couldRefund(o.getStatusBackend(), o.getPaymentTime())); | 
|   | 
|         User u = userMapper.selectById(o.getCreateBy()); | 
|         dto.setCreateName(u != null ? u.getNickName() : o.getCreateBy()); | 
|   | 
|         //是否可质检退款 | 
|         String transferId = o.getTransferId(); | 
|         int count = orderItemMapper.selectCount(new QueryWrapper<OrderItem>() | 
|                 .eq("order_id", id) | 
|                 .isNull("status") | 
|         ); | 
|         int cc = orderItemCheckMapper.selectCount(new QueryWrapper<OrderItemCheck>() | 
|                 .eq("order_id", id) | 
|                 .isNull("audit_status") | 
|         ); | 
|         boolean couldCheckRefund = StringUtils.isEmpty(transferId) && count == 0 && cc == 0; | 
|         dto.setCouldCheckRefund(couldCheckRefund); | 
|   | 
|         List<OrderPointGoodsListDTO> pointGoodsList = orderMapper.getPointGoodsList(id); | 
|         dto.setPointGoodsList(pointGoodsList); | 
|   | 
|         //判断优惠券ID是否为空 用户优惠券id | 
|         if(StringUtils.isNotBlank(o.getMemberCouponId())){ | 
|             CouponRecordVO couponRecordVO = couponRecordService.getCouponRecordById(o.getMemberCouponId()); | 
|             if(!ObjectUtils.isEmpty(couponRecordVO)){ | 
|                 dto.setCouponDiscountType(couponRecordVO.getCouponDiscountType()); | 
|                 dto.setMinOrderAmount("满"+couponRecordVO.getMinOrderAmount()); | 
|             } | 
|         } | 
|   | 
|         return dto; | 
|     } | 
|   | 
|     public List<OrderItemPlatformListDTO> getPlatformOrderItems(String id) { | 
|         return orderItemMapper.getPlatformOrderItems(id); | 
|     } | 
|   | 
|     private Map<Long, String> prepareStationMap() { | 
|         List<Station> sLs = stationMapper.selectList(new QueryWrapper<>()); | 
|         Map<Long, String> stationMap = new HashMap<>(); | 
|         if (sLs != null && sLs.size() > 0) { | 
|             for (Station s : sLs) { | 
|                 stationMap.put(s.getId(), s.getName()); | 
|             } | 
|         } | 
|   | 
|         return stationMap; | 
|     } | 
|   | 
|     public List<OrderItemListDTO> getPtCuOrderItems(String id) { | 
|         List<OrderItem> ls = orderItemMapper.selectList( | 
|                 new QueryWrapper<OrderItem>().eq("order_id", id)); | 
|   | 
|         Map<Long, String> stationMap = prepareStationMap(); | 
|   | 
|         List<OrderItemListDTO> result = new ArrayList<>(); | 
|         for (OrderItem oi : ls) { | 
|             OrderItemListDTO dto = new OrderItemListDTO(); | 
|             BeanUtils.copyProperties(oi, dto); | 
|   | 
|             dto.setStationName(stationMap.get(oi.getStationId())); | 
|   | 
|             result.add(dto); | 
|         } | 
|   | 
|         return result; | 
|     } | 
|   | 
|     public List<Order> autoReceive() { | 
|         int days = -5; //5天前的订单自动收货 | 
|         LocalDateTime endTime = LocalDateTime.now().plusDays(days); | 
|         List<Order> ls = orderMapper.getOrderForAutoReceive(endTime); | 
|         if (ls == null || ls.size() == 0) { | 
|             return ls; | 
|         } | 
|   | 
|         for (Order o : ls) { | 
|             o.setStatus(Constants.ORDER_STATUS.EVALUATE.name()); | 
|             o.setStatusBackend(Constants.ORDER_STATUS_BACKEND.EVALUATE.name()); | 
|             o.setReceiveTime(LocalDateTime.now()); | 
|             o.update("sys"); | 
|             orderMapper.updateById(o); | 
|         } | 
|   | 
|         return ls; | 
|     } | 
|   | 
|     public void processAfterReceive(Order o){ | 
|         String status = o.getStatus(); | 
|         if(!Constants.ORDER_STATUS.EVALUATE.name().equals(status)){ | 
|             log.warn("订单未确认收货,无法处理积分和成长值"); | 
|             return; | 
|         } | 
|   | 
|         BigDecimal totalAmount = o.getTotalAmount(); | 
|         List<OrderItemCheck> checkList = orderItemCheckMapper.selectList(new QueryWrapper<OrderItemCheck>() | 
|                 .eq("order_id", o.getId()) | 
|                 .eq("audit_status", Constants.CHECK_AUDIT_STATUS.AGREED.name()) | 
|         ); | 
|   | 
|         if(checkList != null && checkList.size() > 0){ | 
|             for(OrderItemCheck c : checkList){ | 
|                 if(Constants.CHECK_TYPE.replace.name().equals(c.getType())){ | 
|                     continue; | 
|                 } | 
|                 totalAmount = totalAmount.subtract(getAmount(c.getDeductAmount())); | 
|             } | 
|         } | 
|   | 
|         //成长值计算 | 
|         MemberGrowthRecordDTO mDto = new MemberGrowthRecordDTO(); | 
|         mDto.setTotalAmount(totalAmount); | 
|         mDto.setUserId(o.getCreateBy()); | 
|         mDto.setSource(Constants.GROWTH_SOURCE.consume.name()); | 
|         mDto.setType(Constants.GROWTH_TYPE.add.name()); | 
|         mDto.setRemarks("订单: " + o.getOrderNo()); | 
|         memberGrowthRecordService.saveMemberGrowthRecord(mDto); | 
|   | 
|         //积分计算 | 
|         customerPointService.consumptionPoint(totalAmount, o.getOrderNo(), o.getCreateBy()); | 
|     } | 
|   | 
|     public JSONObject sendWxDeliveryGood(Order o) { | 
|         JSONObject json = new JSONObject(); | 
|         List<OrderItem> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>() | 
|                 .eq(OrderItem::getOrderId, o.getId()) | 
|                 .eq(OrderItem::getDeleted, false)); | 
|         String accessToken = weChatService.getAccessToken(PyamentV3Configurer.customer_app_id, PyamentV3Configurer.customer_app_secret); | 
|         if (items == null || items.size() == 0) { | 
|             log.error("订单" + o.getOrderNo() + "没有商品记录"); | 
|             json.put("errcode", -1); | 
|             json.put("errmsg", "订单" + o.getOrderNo() + "没有商品记录"); | 
|             return json; | 
|         } else if (StringUtils.isBlank(accessToken)) { | 
|             log.error("订单" + o.getOrderNo() + "发货,获取微信access_token失败"); | 
|             json.put("errcode", -1); | 
|             json.put("errmsg", "订单" + o.getOrderNo() + "发货,获取微信access_token失败"); | 
|             return json; | 
|         } else { | 
|             StringBuffer sb = new StringBuffer(); | 
|             for (OrderItem item : items) { | 
|                 sb.append(item.getFlowerName() + "*" + item.getNum() + "扎、");//商品信息 | 
|             } | 
|             try { | 
|                 json = wxDeliveryGoodService.wxDeliveryGood( | 
|                         o.getId(), | 
|                         o.getPayOpenid(), | 
|                         o.getPaymentTrId(), | 
|                         sb.toString(), | 
|                         PyamentV3Configurer.merchantId, | 
|                         accessToken); | 
|             } catch (Exception e) { | 
|                 log.error("订单" + o.getOrderNo() + "发货,调用微信发货接口失败", e); | 
|                 json.put("errcode", -1); | 
|                 json.put("errmsg", "订单" + o.getOrderNo() + "发货,调用微信发货接口失败"); | 
|                 return json; | 
|             } | 
|             return json; | 
|         } | 
|     } | 
|   | 
|     public Order confirmOrderReceive(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         String userId = SecurityUtils.getUserId(); | 
|         if (!userId.equals(o.getCreateBy())) { | 
|             throw new ValidationException("无权操作"); | 
|         } | 
|   | 
|         int count = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("order_id", id) | 
|                 .eq("status", Constants.ORDER_SALES_STATUS.PENDING.name())); | 
|         if (count > 0) { | 
|             throw new ValidationException("有未完成理赔申请"); | 
|         } | 
|   | 
|         o.setStatus(Constants.ORDER_STATUS.EVALUATE.name()); | 
|         o.setStatusBackend(Constants.ORDER_STATUS_BACKEND.EVALUATE.name()); | 
|         o.setReceiveTime(LocalDateTime.now()); | 
|         o.update(userId); | 
|         orderMapper.updateById(o); | 
|   | 
|         return o; | 
|     } | 
|   | 
|     public Integer getMyOrderStatusCount(String status) { | 
|         return orderMapper.selectCount(new QueryWrapper<Order>() | 
|                 .eq("status", status) | 
|                 .eq("deleted", 0) | 
|                 .eq("create_by", SecurityUtils.getUserId()) | 
|         ); | 
|     } | 
|   | 
|     public CustomerOrderCountDTO getCustomerOrderCount() { | 
|         String userId = SecurityUtils.getUserId(); | 
|         CustomerOrderCountDTO dto = new CustomerOrderCountDTO(); | 
|         int pendingCount = getMyOrderStatusCount(Constants.ORDER_STATUS.PENDING.name()); | 
|         int sendCount = getMyOrderStatusCount(Constants.ORDER_STATUS.SEND.name()); | 
|         int receiveCount = getMyOrderStatusCount(Constants.ORDER_STATUS.RECEIVE.name()); | 
|         int evaluateCount = getMyOrderStatusCount(Constants.ORDER_STATUS.EVALUATE.name()); | 
|   | 
|         int salesCount = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("create_by", userId)); | 
|         int salesPendingCount = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("create_by", userId).eq("status", Constants.ORDER_SALES_STATUS.PENDING.name())); | 
|         int salesRejectCount = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("create_by", userId).eq("status", Constants.ORDER_SALES_STATUS.REJECTED.name())); | 
|         int salesAgreeCount = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("create_by", userId).eq("status", Constants.ORDER_SALES_STATUS.AGREED.name())); | 
|         int salesCancelCount = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>() | 
|                 .eq("create_by", userId).eq("status", Constants.ORDER_SALES_STATUS.CANCEL.name())); | 
|   | 
|         dto.setPendingCount(pendingCount); | 
|         dto.setSendCount(sendCount); | 
|         dto.setReceiveCount(receiveCount); | 
|         dto.setEvaluateCount(evaluateCount); | 
|         dto.setSalesCount(salesCount); | 
|         dto.setSalesPendingCount(salesPendingCount); | 
|         dto.setSalesCompletedCount(salesRejectCount + salesAgreeCount); | 
|         dto.setSalesCancelCount(salesCancelCount); | 
|   | 
|         return dto; | 
|     } | 
|   | 
|     public boolean couldRefund(String statusBackend, LocalDateTime pTime) { | 
|         boolean r = true; | 
|         if (pTime == null || LocalDateTime.now().plusMinutes(-10).isAfter(pTime) | 
|                 || !Constants.ORDER_STATUS_BACKEND.PAYMENT.name().equals(statusBackend)) { | 
|             r = false; | 
|         } | 
|   | 
|         return r; | 
|     } | 
|   | 
|     public void refundCheck(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         String status = o.getStatusBackend(); | 
|         LocalDateTime pTime = o.getPaymentTime(); | 
|   | 
|         if (!couldRefund(status, pTime)) { | 
|             throw new ValidationException("无效退款"); | 
|         } | 
|     } | 
|   | 
|     public void refundCheckAdmin(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         if (o.getPaymentTime() == null) { | 
|             throw new ValidationException("未支付订单不可退款"); | 
|         } | 
|   | 
|         if (o.getRefundTime() != null) { | 
|             throw new ValidationException("已退款订单不可退款"); | 
|         } | 
|   | 
|         if (o.getReceiveTime() != null) { | 
|             throw new ValidationException("已收货订单不可退款,请走售后"); | 
|         } | 
|   | 
|         int count = orderRefundMapper.selectCount(new QueryWrapper<OrderRefund>() | 
|                 .eq("order_id", id)); | 
|         if (count > 0) { | 
|             throw new ValidationException("已部分退款订单不可退款"); | 
|         } | 
|     } | 
|   | 
|     public void calculateSupplierSaleNum() { | 
|         LocalDate start = LocalDate.now().plusMonths(-1).withDayOfMonth(1); | 
|         LocalDate end = LocalDate.now().withDayOfMonth(1); | 
|         LocalDateTime startTime = start.atTime(0, 0, 0); | 
|         LocalDateTime endTime = end.atTime(0, 0, 0); | 
|         List<SupplierNumDTO> sLs = orderMapper.getSupplierSaleNum(startTime, endTime); | 
|         if (sLs != null && sLs.size() > 0) { | 
|             List<FeeService> fees = feeServiceMapper.selectList(new QueryWrapper<>()); | 
|   | 
|             Map<Long, Integer> snMap = new HashMap<>(); | 
|             for (SupplierNumDTO s : sLs) { | 
|                 snMap.put(s.getSupplierId(), s.getNum()); | 
|             } | 
|             String yearMonth = format(startTime, "yyyy-MM"); | 
|             List<Supplier> ls = supplierMapper.selectList(new QueryWrapper<>()); | 
|             for (Supplier s : ls) { | 
|                 FlowerSupplierSaleNum n = new FlowerSupplierSaleNum(); | 
|                 n.setSupplierId(s.getId()); | 
|                 n.setYearMonth(yearMonth); | 
|                 Integer num = snMap.get(s.getId()); | 
|                 n.setSaleNum(num == null ? 0 : num); | 
|                 n.setServiceFeeRate(getServiceFeeRate(fees, n.getSaleNum())); | 
|                 saleNumMapper.insert(n); | 
|             } | 
|         } | 
|     } | 
|   | 
|     public AbnormalOrderDTO getAbnormalOrderDetails(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         if (o == null) { | 
|             throw new ValidationException("订单不存在"); | 
|         } | 
|         AbnormalOrderDTO dto = new AbnormalOrderDTO(); | 
|         dto.setId(id); | 
|         dto.setTransferId(o.getTransferId()); | 
|         dto.setTransferTime(o.getTransferTime()); | 
|   | 
|         BigDecimal deductAmount = new BigDecimal(0); | 
|         List<AbnormalOrderItemDTO> items = orderItemMapper.getAbnormalItems(id); | 
|         if (items != null && items.size() > 0) { | 
|             for (AbnormalOrderItemDTO a : items) { | 
|                 deductAmount = deductAmount.add(a.getDeductAmount()); | 
|             } | 
|         } | 
|         dto.setDeductAmount(deductAmount); | 
|         dto.setItems(items); | 
|   | 
|         return dto; | 
|     } | 
|   | 
|     public void processAbnormalOrder(String id) { | 
|         Order o = orderMapper.selectById(id); | 
|         String transferId = o.getTransferId(); | 
|         if (StringUtils.isNotEmpty(transferId)) { | 
|             throw new ValidationException("已处理,不用重复处理"); | 
|         } | 
|   | 
|         int count = orderItemMapper.selectCount(new QueryWrapper<OrderItem>() | 
|                 .eq("order_id", id) | 
|                 .isNull("status") | 
|         ); | 
|         if(count > 0){ | 
|             throw new ValidationException("有未质检商品,不可处理"); | 
|         } | 
|   | 
|         int cc = orderItemCheckMapper.selectCount(new QueryWrapper<OrderItemCheck>() | 
|                 .eq("order_id", id) | 
|                 .isNull("audit_status") | 
|         ); | 
|         if(cc > 0){ | 
|             throw new ValidationException("有未审核质检,不可操作"); | 
|         } | 
|   | 
|         BigDecimal deductAmount = new BigDecimal(0); | 
|         List<AbnormalOrderItemDTO> items = orderItemMapper.getAbnormalItems(id); | 
|   | 
|         if (items == null || items.size() == 0) { | 
|             throw new ValidationException("非异常订单不用处理"); | 
|         } | 
|   | 
|         for (AbnormalOrderItemDTO a : items) { | 
|             deductAmount = deductAmount.add(a.getDeductAmount()); | 
|         } | 
|   | 
|         transferId = "NoNeedRefund"; | 
|         if (deductAmount.doubleValue() > 0) { | 
|             transferId = paymentV3Service.refundOrderSub(o, deductAmount); | 
|         } | 
|         o.setTransferId(transferId); | 
|         o.setTransferTime(LocalDateTime.now()); | 
|         o.update(SecurityUtils.getUserId()); | 
|         orderMapper.updateById(o); | 
|   | 
|     } | 
|   | 
|     public void processLevelDown(OrderReduceDTO dto) { | 
|         Order o = orderMapper.selectById(dto.getId()); | 
|         String transferId = o.getTransferId(); | 
|         if (StringUtils.isNotEmpty(transferId)) { | 
|             throw new ValidationException("已处理,不用重复处理"); | 
|         } | 
|   | 
|         int count = orderItemMapper.selectCount(new QueryWrapper<OrderItem>() | 
|                 .eq("order_id", o.getId()) | 
|                 .eq("status", Constants.CHECK_OPERATE.reduce.name())); | 
|         if (count == 0) { | 
|             throw new ValidationException("非降级原因不用处理"); | 
|         } | 
|   | 
|         BigDecimal amount = dto.getAmount(); | 
|         transferId = paymentV3Service.refundOrderSub(o, amount); | 
|         o.setTransferId(transferId); | 
|         o.setTransferTime(LocalDateTime.now()); | 
|         o.update(SecurityUtils.getUserId()); | 
|         orderMapper.updateById(o); | 
|   | 
|         /*if (amount == null || amount.doubleValue() == 0) { | 
|             throw new ValidationException("打款金额不能为空"); | 
|         } | 
|   | 
|         if(amount.doubleValue() > o.getTotalAmount().doubleValue()){ | 
|             throw new ValidationException("金额不能大于订单金额"); | 
|         } | 
|   | 
|         String remarks = "降级打款"; | 
|         String openId = o.getPayOpenid(); | 
|   | 
|         List<TransferDetailReqDTO> details = new ArrayList<>(); | 
|         TransferDetailReqDTO dr = new TransferDetailReqDTO(); | 
|         dr.setAmount(amount.multiply(new BigDecimal(100)).longValue()); | 
|         dr.setOpenId(openId); | 
|         dr.setRemarks(remarks); | 
|         if (amount.doubleValue() >= 2000) { | 
|             // 现在支付的人不一定是注册的客户,所以付款的人真实姓名不一定是注册客户,可能会打款不成功 | 
|             Customer p = customerMapper.selectOne(new QueryWrapper<Customer>() | 
|                     .eq("user_id", o.getCreateBy())); | 
|             dr.setUserName(p.getName()); | 
|         } | 
|         details.add(dr); | 
|   | 
|         TransferReqDTO transferReqDTO = new TransferReqDTO(); | 
|         transferReqDTO.setDetails(details); | 
|         transferReqDTO.setAppId(PyamentV3Configurer.customer_app_id); | 
|         transferReqDTO.setName(o.getOrderNo()); | 
|         transferReqDTO.setRemarks(remarks); | 
|   | 
|         transferId = paymentV3Service.doBatchTransfer(transferReqDTO, SecurityUtils.getUserId()); //发起转账 | 
|         o.setTransferId(transferId); | 
|         o.setTransferTime(LocalDateTime.now()); | 
|         o.update(SecurityUtils.getUserId()); | 
|         orderMapper.updateById(o);*/ | 
|     } | 
|   | 
|     public void evaluateOrder(OrderEvaluateDTO dto) { | 
|         Order o = orderMapper.selectById(dto.getId()); | 
|         o.setEvaluate(dto.getEvaluate()); | 
|         o.setEvaluateTime(LocalDateTime.now()); | 
|         o.update(SecurityUtils.getUserId()); | 
|         orderMapper.updateById(o); | 
|     } | 
|   | 
|     public PartnerOrderDTO getCurrentPartnerOrderStatistics() { | 
|         Partner partner = getCurrentPartner(); | 
|         PartnerOrderDTO dto = new PartnerOrderDTO(); | 
|         if (partner != null) { | 
|             String userId = SecurityUtils.getUserId(); | 
|             BigDecimal income = settlementMapper.getUserIncome(userId); | 
|             dto.setIncome(income == null ? new BigDecimal(0) : income); | 
|   | 
|             LocalDateTime now = LocalDateTime.now(); | 
|             LocalDateTime towAm = LocalDate.now().atTime(2, 0, 0); | 
|             LocalDateTime fivePm = LocalDate.now().atTime(17, 0, 0); | 
|             LocalDateTime startDate; | 
|             LocalDateTime endDate; | 
|             if (now.isAfter(towAm)) { | 
|                 startDate = fivePm.plusDays(-1); | 
|                 endDate = fivePm; | 
|             } else { | 
|                 startDate = fivePm.plusDays(-2); | 
|                 endDate = fivePm.plusDays(-1); | 
|             } | 
|   | 
|             Long partnerId = partner.getId(); | 
|             Integer orderCountToday = orderMapper.selectCount(new QueryWrapper<Order>() | 
|                     .eq("partner_id", partnerId) | 
|                     .gt("payment_time", startDate) | 
|                     .le("payment_time", endDate) | 
|                     .isNull("refund_time") | 
|             ); | 
|             dto.setOrderCountToday(orderCountToday == null ? 0 : orderCountToday); | 
|   | 
|             Integer orderCountYesterday = orderMapper.selectCount(new QueryWrapper<Order>() | 
|                     .eq("partner_id", partnerId) | 
|                     .gt("payment_time", startDate.plusDays(-1)) | 
|                     .le("payment_time", endDate.plusDays(-1)) | 
|                     .isNull("refund_time") | 
|             ); | 
|             dto.setOrderCountYesterday(orderCountYesterday == null ? 0 : orderCountYesterday); | 
|   | 
|             LocalDateTime ffPm = LocalDate.now().withDayOfMonth(1).atTime(17, 0, 0).plusDays(-1); | 
|             Integer orderCountMonth = orderMapper.selectCount(new QueryWrapper<Order>() | 
|                     .eq("partner_id", partnerId) | 
|                     .gt("payment_time", ffPm) | 
|                     .isNull("refund_time") | 
|             ); | 
|             dto.setOrderCountMonth(orderCountMonth == null ? 0 : orderCountMonth); | 
|   | 
|             Double salesRate = 0d; | 
|             Integer orderTotal = orderMapper.selectCount(new QueryWrapper<Order>() | 
|                     .eq("partner_id", partnerId).isNull("refund_time")); | 
|             Integer salesCount = orderItemSalesMapper.getPartnerSalesCount(partnerId); | 
|             if (orderTotal != null && orderTotal > 0) { | 
|                 BigDecimal rate = new BigDecimal(salesCount).divide(new BigDecimal(orderTotal), 2, RoundingMode.HALF_UP); | 
|                 salesRate = rate.doubleValue(); | 
|             } | 
|             dto.setSalesRate(salesRate); | 
|         } | 
|   | 
|         return dto; | 
|     } | 
|   | 
|     public void deleteOrder(String id) { | 
|         Order order = orderMapper.selectById(id); | 
|         String status = order.getStatus(); | 
|         if (!Constants.ORDER_STATUS.CANCEL.name().equals(status)) { | 
|             throw new ValidationException("非取消订单不可删除"); | 
|         } | 
|         order.setDeleted(true); | 
|         order.update(SecurityUtils.getUserId()); | 
|         orderMapper.updateById(order); | 
|     } | 
|   | 
|     /** | 
|      * 获取用户最后收货时间 | 
|      * @param userId | 
|      * @return | 
|      */ | 
|     public LocalDateTime getUserLastOrderTime(String userId){ | 
|         Order o = orderMapper.getUserLastOrder(userId); | 
|         return o.getReceiveTime(); | 
|     } | 
|   | 
|     public Integer getFlowerCompleteNumToday(String userId,Long flowerId){ | 
|   | 
|         int completeNum = 0; | 
|         // 获取当前时间 | 
|         LocalDateTime now = LocalDateTime.now(); | 
|         // 构造今天的17:00 | 
|         LocalDateTime todayAtFivePM = LocalDateTime.of(LocalDate.now(), LocalTime.of(17, 0)); | 
|         // 定义时间区间的开始和结束时间 | 
|         LocalDateTime startTime; | 
|         LocalDateTime endTime; | 
|   | 
|         if (now.isAfter(todayAtFivePM)) { | 
|             // 当前时间大于今天的17:00,取今天17:00到明天17:00的区间 | 
|             startTime = todayAtFivePM; | 
|             endTime = todayAtFivePM.plusDays(1);  // 明天的17:00 | 
|         } else { | 
|             // 当前时间小于今天的17:00,取昨天17:00到今天17:00的区间 | 
|             startTime = todayAtFivePM.minusDays(1);  // 昨天的17:00 | 
|             endTime = todayAtFivePM;  // 今天的17:00 | 
|         } | 
|   | 
|         // 调用Mapper方法,传递开始时间和结束时间 | 
|         completeNum = orderMapper.getFlowerCompleteNumWithinTimeRange(userId, flowerId, startTime, endTime); | 
|   | 
|         return completeNum; | 
|   | 
|   | 
|     } | 
|   | 
|     @Transactional | 
|     public String copyOrder(String id) { | 
|         List<OrderItem> ls = orderItemMapper.selectList( | 
|                 new QueryWrapper<OrderItem>().eq("order_id", id)); | 
|         StringBuilder sb=new StringBuilder(); | 
|         ls.stream().forEach(orderItem -> { | 
|             Cart cart = null; | 
|             final Long flowerId = orderItem.getFlowerId(); | 
|             final Integer num = orderItem.getNum(); | 
|             final String userId=orderItem.getCreateBy(); | 
|             // 查看当前的花是否已经下架 | 
|             Flower flower = flowerMapper.selectById(flowerId); | 
|             // 查看当前的花的限购 | 
|             final Integer limited = flower.getLimited(); | 
|   | 
|             // 查看当前购物车里面是否已经存在当前花 | 
|             cart = cartMapper.selectOne(new QueryWrapper<Cart>() | 
|                     .eq("create_by", orderItem.getCreateBy()).eq("flower_id",flowerId)); | 
|   | 
|             if(null==cart){ | 
|                 cart = new Cart(); | 
|                 cart.setFlowerId(flowerId); | 
|                 cart.setNum(0); | 
|                 cart.create(orderItem.getCreateBy()); | 
|             } | 
|   | 
|             if (!flower.getStatus().equals(Constants.FLOWER_STATUS.UP.name())) { | 
|                 sb.append(flower.getName() + "已下架"); | 
|             }else if(flower.getStatus().equals(Constants.FLOWER_STATUS.UP.name())){ | 
|                 // 未下架库存逻辑控制 | 
|                 Integer tmpNum=cart.getNum()+num; | 
|                 //查看当前的库存 | 
|                 if (null!=flower.getStock() && flower.getStock() > 0 && flower.getStock().compareTo(tmpNum) >= 0) { | 
|                     // 库存充足 | 
|                     cart.setNum(tmpNum); | 
|                 } else if (null!=flower.getStock() && flower.getStock() > 0 && flower.getStock().compareTo(tmpNum) < 0) { | 
|                     // 库存不足,剩多少给多少 | 
|                     cart.setNum(flower.getStock()); | 
|                     sb.append(flower.getName() + "购物车的总数超过库存,已调整成库存数!"); | 
|                 }else { | 
|                     sb.append(flower.getName() + "已无库存"); | 
|                 } | 
|   | 
|                 // 限购控制,如果当前的购物车的数量大于限购的话,则需要控制 | 
|                 if(null!=limited && limited>0){ | 
|                     Integer buyedNum= getFlowerCompleteNumToday(userId,flowerId); | 
|                     Integer todayNum=cart.getNum()+buyedNum; | 
|                     // | 
|                     if(todayNum>limited){ | 
|                         cart.setNum(limited-buyedNum<=0?0:limited-buyedNum); | 
|                         sb.append(flower.getName() + "购物车的总数超过限购,已调整成未限购数!"); | 
|                     } | 
|                 } | 
|   | 
|             } | 
|   | 
|             if(null!=cart){ | 
|                 // 插入购物车 | 
|                 if(null!=cart.getId()){ | 
|                     // 新增 | 
|                     cartMapper.updateById(cart); | 
|                 }else{ | 
|                    // 更新 | 
|                     cartMapper.insert(cart); | 
|                 } | 
|             } | 
|   | 
|         }); | 
|   | 
|         return sb.toString(); | 
|   | 
|     } | 
| } |