package com.kmall.admin.service.impl; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.Maps; import com.kmall.admin.dao.*; import com.kmall.admin.dao.alarm.Mall2LowPriceWarningDao; import com.kmall.admin.dao.mk.Mk2GoodsTopicPriceDao; import com.kmall.admin.dao.mk.Mk2MemberBirthdayDao; import com.kmall.admin.dao.mk.store.MkStorePromOrderRealDao; import com.kmall.admin.dao.mk.store.MkStorePromTypeDao; import com.kmall.admin.dao.mk.store.StoreTopicDao; import com.kmall.admin.dao.vip.Mall2MemberConsumptionRecordsDao; import com.kmall.admin.dao.vip.Mall2MemberPointsDao; import com.kmall.admin.dao.vip.Mall2PointsRulesDao; import com.kmall.admin.dto.OrderExpressDto; import com.kmall.admin.dto.OrderRecognitionDto; import com.kmall.admin.entity.*; import com.kmall.admin.entity.OrderProcessRecordEntity; import com.kmall.admin.entity.alarm.Mall2LowPriceWarningEntity; import com.kmall.admin.entity.mk.Mk2GoodsTopicPriceEntity; import com.kmall.admin.entity.mk.store.*; import com.kmall.admin.entity.vip.Mall2MemberConsumptionRecordsEntity; import com.kmall.admin.entity.vip.Mall2MemberPointsEntity; import com.kmall.admin.entity.vip.Mall2PointsRulesEntity; import com.kmall.admin.fromcomm.dao.SysConfigDao; import com.kmall.admin.service.*; import com.kmall.admin.service.mk.store.MkStoreCampMinusService; import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService; import com.kmall.admin.websocket.WebSocketServer; import com.kmall.api.entity.*; import com.kmall.api.entity.mk.MkStoreTicketDiscountVo; import com.kmall.common.utils.ResponseData; import com.kmall.common.utils.wechat.WechatMicropayApiResult; import com.kmall.common.utils.wechat.WechatReverseApiResult; import com.kmall.manager.manager.alipay.AliPayMicropayApiResult; import com.kmall.manager.manager.alipay.AliPayRequestParams; import com.kmall.manager.manager.alipay.AliPayUtil; import com.kmall.manager.manager.express.sf.properties.SFPropertiesBuilder; import com.kmall.manager.manager.express.sf.properties.SFUtil; import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity; import com.kmall.manager.manager.express.sf.entity.RouteEntity; import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity; import com.kmall.manager.manager.print.ticket.TicketPrintUtil; import com.kmall.manager.manager.wechat.WechatUtil; import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult; import com.kmall.admin.utils.ShiroUtils; import com.kmall.common.constant.Dict; import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder; import com.kmall.api.util.CommonUtil; import com.kmall.admin.fromcomm.entity.SysUserEntity; import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder; import com.kmall.common.utils.*; import com.kmall.common.utils.print.ticket.item.*; import com.kmall.manager.manager.express.kdn.KdniaoUtil; import com.kmall.common.utils.wechat.WechatRefundApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Service("orderService") public class OrderServiceImpl implements OrderService { private final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class); @Autowired private OrderDao orderDao; @Autowired private ShippingDao shippingDao; @Autowired private OrderGoodsDao orderGoodsDao; @Autowired private SysPrinterDao printerDao; @Autowired private UserDao userDao; @Autowired private UserCouponDao userCouponDao; @Autowired private ProductStoreRelaDao productStoreRelaDao; @Autowired private OrderProcessRecordDao orderProcessRecordDao; @Autowired private OrderRefundDao orderRefundDao; @Autowired private StoreDao storeDao; @Autowired private OfflineCartDao offlineCartDao; @Autowired private GoodsDao goodsDao; @Autowired private MerchDao merchDao; @Autowired private MngChangeDao mngChangeDao; @Autowired private StoreMngChangeDao storeMngChangeDao; @Autowired private ThirdMerchExpressDao thirdMerchExpressDao; @Autowired private MkStorePromOrderRealDao mkStorePromOrderRealDao; @Autowired private UserCampMinusDao userCampMinusDao; @Autowired private UserService userService; @Autowired private SysConfigDao sysConfigDao; @Autowired private ProductDao productDao; @Autowired private OrderWXPayRecordService orderWXPayRecordService; @Autowired private StoreService storeService; @Autowired private PickUpCodeService pickUpCodeService; @Autowired private MkStoreCampMinusService mkStoreCampMinusService; @Autowired private MkStoreTicketDiscountService mkStoreTicketDiscountService; @Autowired private CashierDao cashierDao; // 收银机查询 @Autowired private CashierLoginRecordDao cashierLoginRecordDao; // 收银员登录记录 @Autowired private SaleRecordDao saleRecordDao; // 销售记录 @Autowired private StoreTopicDao storeTopicDao; // 查询是否有门店活动 @Autowired private Mk2GoodsTopicPriceDao mk2GoodsTopicPriceDao; // 门店商品价格 @Autowired private Mall2PointsRulesDao pointsRulesDao; // 积分规则 @Autowired private Mall2MemberPointsDao memberPointsDao; // 用户积分 @Autowired private Mall2MemberConsumptionRecordsDao memberConsumptionRecordsDao; // 会员消费记录 @Autowired private MkStorePromTypeDao storePromTypeDao; // 优惠类型 @Autowired private Mk2MemberBirthdayDao memberBirthdayDao; // 生日优惠 @Autowired private MerchUserDao merchUserDao; @Autowired private Mall2LowPriceWarningDao lowPriceWarningDao; @Override public OrderEntity queryObject(Long id) { return orderDao.queryObject(id); } @Override public Double getTotalActualPrice(String merchOrderSn) { return orderDao.getTotalActualPrice(merchOrderSn); } @Override public List queryList(Map map) { return orderDao.queryList(map); } @Override public int queryTotal(Map map) { return orderDao.queryTotal(map); } @Override public int save(OrderEntity order) { return orderDao.save(order); } @Override public int update(OrderEntity order) { return orderDao.update(order); } /** * 取消订单 * * @param order */ @Override public void cancelOrder(OrderEntity order) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem())); } orderDao.update(order); if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台取消订单"); // 释放优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } //释放促销满减券 UserCampMinusEntity userCampMinusVo = userCampMinusDao.queryUserCampByOrderId(order.getId()); if (null != userCampMinusVo) { userCampMinusDao.cancelUserCampOrder(userCampMinusVo); } } @Override public int delete(Long id) { return orderDao.delete(id); } @Override public int deleteBatch(Long[] ids) { return orderDao.deleteBatch(ids); } @Override public int confirm(Long id) { OrderEntity orderEntity = queryObject(id); Integer shippingStatus = orderEntity.getShippingStatus();//发货状态 Integer payStatus = orderEntity.getPayStatus();//付款状态 if (2 != payStatus) { throw new RRException("此订单未付款,不能确认收货!"); } if (4 == shippingStatus) { throw new RRException("此订单处于退货状态,不能确认收货!"); } if (0 == shippingStatus) { throw new RRException("此订单未发货,不能确认收货!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) { throw new RRException("此订单已完成!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) { throw new RRException("此订单待付款!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) { throw new RRException("此订单付款中!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) { throw new RRException("此订单已取消!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) { throw new RRException("此订单已删除!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { throw new RRException("此订单还未发货!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())) { throw new RRException("此订单已退款!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) { throw new RRException("此订单已退款!"); } orderEntity.setShippingStatus(2); orderEntity.setOrderStatus(301); orderEntity.setConfirmTime(new Date()); orderDao.update(orderEntity); return 0; } @Override public int sendGoods(OrderEntity order) { Integer payStatus = order.getPayStatus();//付款状态 if (2 != payStatus) { throw new RRException("此订单未付款!"); } ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId()); if (null != shippingEntity) { order.setShippingName(shippingEntity.getName()); } order.setOrderStatus(300);//订单已发货 order.setShippingStatus(1);//已发货 return orderDao.update(order); } @Override public Ticket printMsg(Long id) { OrderEntity orderEntity = queryInfos(id); List orderGoodsEntityList = orderEntity.getOrderGoodsEntityList(); // 获取门店 StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId()); // 获取清关信息 OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn()); // 小票头 TicketHead head = new TicketHead(); head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName()); // head.setMemberId(orderEntity.getUserName().toString()); head.setOrderId(orderEntity.getOrderSn()); head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date())); // 商品信息 Integer goodsTotal = 0; // 商品总个数 BigDecimal total = Constant.ZERO; // 商品总计 List goodsList = new ArrayList<>(); for (OrderGoodsEntity orderGoods : orderGoodsEntityList) { goodsTotal += orderGoods.getNumber(); total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber()))) .setScale(2, BigDecimal.ROUND_HALF_UP); Goods goods = new Goods(orderGoods.getGoodsName(), orderGoods.getRetailPrice().toString(), orderGoods.getNumber().toString(), orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())) .setScale(2, BigDecimal.ROUND_HALF_UP).toString()); goodsList.add(goods); } // 收银信息 CashInfo cashInfo = new CashInfo(); cashInfo.setGoodsTotal(goodsTotal.toString()); cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setOddChange("0.00"); cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setFreight( new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setPaymentMode("微信支付"); // 海关清单 CusListing cusListing = new CusListing(); cusListing.setOrderId(orderEntity.getOrderSn()); if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) { cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo()); cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo()); cusListing.setConsignee(orderEntity.getConsignee()); cusListing.setConsigneeTel(orderEntity.getMobile()); } cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress()); cusListing.setDeliveryAddress(storeEntity.getStoreAddress()); return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing); } @Override public Ticket printMsg(Long id, String sessionId) { OrderEntity orderEntity = queryInfos(id); List orderGoodsEntityList = orderEntity.getOrderGoodsEntityList(); // 获取门店 StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId()); // 获取清关信息 OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn()); // 小票头 TicketHead head = new TicketHead(); head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName()); // head.setMemberId(orderEntity.getUserName().toString()); head.setOrderId(orderEntity.getOrderSn()); head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date())); // 商品信息 Integer goodsTotal = 0; // 商品总个数 BigDecimal total = Constant.ZERO; // 商品总计 List goodsList = new ArrayList<>(); for (OrderGoodsEntity orderGoods : orderGoodsEntityList) { goodsTotal += orderGoods.getNumber(); total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber()))) .setScale(2, BigDecimal.ROUND_HALF_UP); Goods goods = new Goods(orderGoods.getGoodsName(), orderGoods.getRetailPrice().toString(), orderGoods.getNumber().toString(), orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())) .setScale(2, BigDecimal.ROUND_HALF_UP).toString()); goodsList.add(goods); } // 收银信息 CashInfo cashInfo = new CashInfo(); cashInfo.setGoodsTotal(goodsTotal.toString()); cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setOddChange("0.00"); cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setFreight( new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()); cashInfo.setPaymentMode("微信支付"); // 海关清单 CusListing cusListing = new CusListing(); cusListing.setOrderId(orderEntity.getOrderSn()); if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) { cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo()); cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo()); cusListing.setConsignee(orderEntity.getConsignee()); cusListing.setConsigneeTel(orderEntity.getMobile()); } cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress()); cusListing.setDeliveryAddress(storeEntity.getStoreAddress()); // 尝试在取货码表中查询数据,如果有的话就改变状态 String orderSn = orderEntity.getOrderSn(); PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn); if(pickUpCodeEntity != null){ pickUpCodeEntity.setPickUpCodeStatus("1"); pickUpCodeService.update(pickUpCodeEntity); // try { // WebSocketServer.delete(sessionId,orderEntity.getStoreId(),pickUpCodeEntity); // } catch (IOException e) { // e.printStackTrace(); // } } return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing); } /** * 退款 */ @Transactional public void refund(OrderEntity order) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) { order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem())); } orderDao.update(order);//修改为退款中 // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券 /*// 判断是否有优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台订单退款");*/ // updateStock(order, "管理后台订单退款"); queryStorePromRealUpdateIsScan(order); } /** * 退款 */ @Transactional public void refund(OrderEntity order, WechatRefundApiResult result) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) { order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem())); }else{ order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem())); OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId()); OrderRefundEntity orderRefund = new OrderRefundEntity(); orderRefund.setRefundId(result.getRefund_id()); orderRefund.setOutRefundNo(result.getOut_refund_no()); orderRefund .setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED)); orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中 orderRefund.setModTime(new Date()); if (mallOrderRefund != null) { orderRefund.setId(mallOrderRefund.getId()); orderRefund.setRefundType(mallOrderRefund.getRefundType()); orderRefundDao.update(orderRefund); } else { orderRefund.setOrderId(Integer.parseInt(order.getId() + "")); orderRefund.setUserId(Integer.parseInt(order.getUserId() + "")); orderRefund.setCreateTime(new Date()); List list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn()); if(list.size()>1){//多条订单 orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款 }else{ orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款 } orderRefundDao.save(orderRefund);//退款记录 } } orderDao.update(order);//修改为退款中 // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券 /*// 判断是否有优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台订单退款");*/ // updateStock(order, "管理后台订单退款"); queryStorePromRealUpdateIsScan(order); } @Transactional public void refund(OrderEntity order, AliPayMicropayApiResult result) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) { order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem())); }else{ order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem())); OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId()); OrderRefundEntity orderRefund = new OrderRefundEntity(); orderRefund.setRefundId(result.getTradeNo()); orderRefund.setOutRefundNo(result.getOutTradeNo()); orderRefund .setRefundMoney(new BigDecimal(result.getRefundFee()).divide(Constant.ONE_HUNDRED)); orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中 orderRefund.setModTime(new Date()); if (mallOrderRefund != null) { orderRefund.setId(mallOrderRefund.getId()); orderRefund.setRefundType(mallOrderRefund.getRefundType()); orderRefundDao.update(orderRefund); } else { orderRefund.setOrderId(Integer.parseInt(order.getId() + "")); orderRefund.setUserId(Integer.parseInt(order.getUserId() + "")); orderRefund.setCreateTime(new Date()); List list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn()); if(list.size()>1){//多条订单 orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款 }else{ orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款 } orderRefundDao.save(orderRefund);//退款记录 } } orderDao.update(order);//修改为退款中 // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券 /*// 判断是否有优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台订单退款");*/ // updateStock(order, "管理后台订单退款"); // queryStorePromRealUpdateIsScan(order); } /** * 平安退款逻辑处理 * @param order * @param result */ @Transactional public void pinganRefund(OrderEntity order, net.sf.json.JSONObject result, String refundId) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem())); OrderRefundEntity orderRefund = new OrderRefundEntity(); orderRefund.setRefundId(refundId); orderRefund.setOutRefundNo(result.getString("ord_no")); orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中 orderRefund.setModTime(new Date()); orderRefund.setRefundMoney(BigDecimal.valueOf(result.getInt("trade_amount")).divide(Constant.ONE_HUNDRED)); OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId()); if (mallOrderRefund != null) { orderRefund.setRefundType(mallOrderRefund.getRefundType()); orderRefund.setId(mallOrderRefund.getId()); orderRefundDao.update(orderRefund); } else {//退款记录不存在 orderRefund.setOrderId(Integer.parseInt(order.getId() + "")); orderRefund.setUserId(Integer.parseInt(order.getUserId() + "")); orderRefund.setCreateTime(new Date()); orderRefundDao.save(orderRefund);//退款记录 } orderDao.update(order);//修改为退款中 // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券 /*// 判断是否有优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台平安退款订单");*/ queryStorePromRealUpdateIsScan(order); } /** * 微信国际退款逻辑处理 * @param order * @param result */ @Transactional public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem())); OrderRefundEntity orderRefund = new OrderRefundEntity(); orderRefund.setRefundId(result.getRefund_id()); orderRefund.setOutRefundNo(result.getOut_refund_no()); orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中 orderRefund.setModTime(new Date()); orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED)); orderRefund.setRefundFeeType(result.getRefund_fee_type()); if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) { orderRefund.setTotalFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getTotal_fee())).divide(Constant.ONE_HUNDRED).toString())); } orderRefund.setFeeType(result.getFee_type()); if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) { orderRefund.setCashFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_fee())).divide(Constant.ONE_HUNDRED).toString())); } orderRefund.setCashFeeType(result.getCash_fee_type()); if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_refund_fee())) { orderRefund.setCashRefundFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_refund_fee())).divide(Constant.ONE_HUNDRED).toString())); } orderRefund.setCashRefundFeeType(result.getCash_refund_fee_type()); OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId()); if (mallOrderRefund != null) { orderRefund.setRefundType(mallOrderRefund.getRefundType()); orderRefund.setId(mallOrderRefund.getId()); orderRefundDao.update(orderRefund); } else {//退款记录不存在 orderRefund.setOrderId(Integer.parseInt(order.getId() + "")); orderRefund.setUserId(Integer.parseInt(order.getUserId() + "")); orderRefund.setCreateTime(new Date()); orderRefundDao.save(orderRefund);//退款记录 } orderDao.update(order);//修改为退款中 // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券 /*// 判断是否有优惠券 UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId()); if (null != couponVo) { userCouponDao.cancelOrder(couponVo); } if (!needUpdateStock) { return; } // 更新库存 updateStock(order, "管理后台微信国际退款订单");*/ queryStorePromRealUpdateIsScan(order); } private void updateStock(OrderEntity order, String changeReason){ Map map = new HashMap(); SysUserEntity user = ShiroUtils.getUserEntity(); map.put("orderId", order.getId()); List orderGoodsVoList = orderGoodsDao.queryList(map); for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) { ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),Long.valueOf(orderGoodsEntity.getProductId())); if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) { storeRelaEntity.setSellVolume(0); } BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量 if (sellVolume.compareTo(Constant.ZERO) < 0) { sellVolume = Constant.ZERO; } Integer stockNum = 0; GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId()); if(goodsEntity != null){ stockNum = goodsEntity.getGoodsNumber(); //还原商户商品库存 resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user); } if (null != storeRelaEntity.getStockNum()) { stockNum = storeRelaEntity.getStockNum(); //普通商品不受共享库存影响,直接取门店配置库存 //该商品所属第三方商户不是共享库存 if(goodsEntity.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) { resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存 }else{ //该商品所属第三方商户是共享库存,但商品业务类型不是00保税备货 if(!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){ resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存 } } } //该商品所属第三方商户为共享库存,且是保税备货商品,取消订单时改变 updateGoodsByIsShareStock(goodsEntity); } } /** * 更新商品库存数量变化后是否已共享为0“未共享” * @param goodsInfo */ private void updateGoodsByIsShareStock(GoodsEntity goodsInfo){ //该商品所属第三方商户为共享库存,且是保税备货商品 if(goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem()) && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) { GoodsEntity goodsVo = new GoodsEntity(); goodsVo.setId(goodsInfo.getId()); //商品库存数量变化后是否已共享,0:否,1:是(下单、退款、取消订单触发) goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem()); goodsDao.update(goodsVo); } } /** * 还原商品总库存 * @param stockNum * @param storeRelaEntity * @param orderGoodsEntity * @param sellVolume * @param changeReason * @param user */ private void resetGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity, OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){ GoodsEntity goodsEntity = goodsDao.queryObject(storeRelaEntity.getGoodsId()); if(goodsEntity!=null){ goodsEntity.setGoodsNumber(stockNum + orderGoodsEntity.getNumber()); // goodsEntity.setSellVolume(Integer.parseInt(goodsSellVolume.toString())); goodsDao.update(goodsEntity); // storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString())); // productStoreRelaDao.update(storeRelaEntity); MngChangeEntity mngChangeEntity = new MngChangeEntity(); mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId()))); mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode()); mngChangeEntity.setChangeReason(changeReason); mngChangeEntity.setChangeType(Dict.changeType.item_0.getItem()); mngChangeEntity.setChangeNum(orderGoodsEntity.getNumber());//变化数 mngChangeEntity.setOriginalNum(stockNum);//原库存数 mngChangeEntity.setValidNum(stockNum + orderGoodsEntity.getNumber());//可用数 mngChangeEntity.setCreateTime(new Date()); mngChangeEntity.setModTime(new Date()); mngChangeEntity.setCreaterSn(user.getUsername()); mngChangeEntity.setModerSn(user.getUsername()); mngChangeEntity.setIsValid(0); mngChangeEntity.setMerchSn(goodsEntity.getMerchSn()); mngChangeDao.save(mngChangeEntity); } } /** * 还原门店商品库存 * @param stockNum * @param storeRelaEntity * @param orderGoodsEntity * @param sellVolume * @param changeReason * @param user */ private void resetStoreGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity, OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){ storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString())); storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量 productStoreRelaDao.update(storeRelaEntity); StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity(); storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem()); storeMngChangeEntity.setChangeReason(changeReason); storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(storeRelaEntity.getGoodsId()))); storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(storeRelaEntity.getStoreId()))); storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn()); storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber()); storeMngChangeEntity.setStoreOriginalNum(stockNum); storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber()); storeMngChangeEntity.setCreateTime(new Date()); storeMngChangeEntity.setModTime(new Date()); storeMngChangeEntity.setCreaterSn(user.getUsername()); storeMngChangeEntity.setModerSn(user.getUsername()); storeMngChangeEntity.setIsValid(0); storeMngChangeDao.save(storeMngChangeEntity); } /** * 查询该退款订单编号是否是推广渠道订单,是则修改渠道定时扫描状态 * @param orderInfo */ private void queryStorePromRealUpdateIsScan(OrderEntity orderInfo){ Map map = new HashMap(); map.put("orderId", orderInfo.getId()); List list = mkStorePromOrderRealDao.queryPromRealListByMap(map); if(list.size() > 0) { for (MkStorePromOrderRealEntity mkStorePromOrderRealEntity : list) { mkStorePromOrderRealEntity.setIsPromStatScan(Dict.isDistSellScan.item_0.getItem()); mkStorePromOrderRealDao.update(mkStorePromOrderRealEntity); } } } /** * 处理用户退款申请 * * @param orderInfo */ @Transactional public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) { refundEntity.setApprovalTime(new Date()); // refundEntity.setApprover(ShiroUtils.getUserId()); // 退积分 try { Integer integral = 1; if (orderInfo.getActualPrice().intValue() > 0) { integral = orderInfo.getActualPrice().intValue(); } if (refundEntity.getRefundStatus() == 2) { orderInfo.setOrderStatus(401); // UserEntity entity = userDao.queryObject(orderInfo.getUserId()); } else { orderInfo.setOrderStatus(201); } } catch (Exception e) { e.printStackTrace(); } orderRefundDao.update(refundEntity); orderDao.update(orderInfo); } @Override public OrderRefundEntity queryRefundObject(Long refundId) { return orderRefundDao.queryObject(refundId); } @Override public List queryRefundList(Map map) { return orderRefundDao.queryList(map); } @Override public int queryRefundTotal(Map map) { return orderRefundDao.queryTotal(map); } @Override public int getUserOrderInfo(Map map) { int result = 0; String type = (String) map.get("type"); if ("yfkOrderUserSum".equals(type)) { result = orderDao.getYfkOrderUserSum(map); } else if ("oderUserSum".equals(type)) { result = orderDao.getOderUserSum(map); } else if ("todayUserOrder".equals(type)) { result = orderDao.getTodayUserOrder(map); } else if ("todayUserSales".equals(type)) { result = orderDao.getTodayUserSales(map); } else if ("incomeSum".equals(type)) { result = orderDao.getIncomeSum(map); } else if ("payedOrderCount".equals(type)) { result = orderDao.getPayedOrderCount(map); } return result; } @Override public Map getLogistics(Long id) { OrderEntity orderEntity = queryObject(id); if (orderEntity == null) { throw new RRException("此订单不存在!"); } if (orderEntity.getShippingStatus() == 0) { if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) || orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) { throw new RRException("此订单还未发货!"); } else { if (StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) { throw new RRException("此订单还未发货!"); } } } Map logisticsInfo = Maps.newHashMap(); List wuliuEntityList = new ArrayList<>(); OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn()); if (orderProcessRecordEntity != null) { if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) || orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(orderProcessRecordEntity.getCustomsSuccTime())); wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" + storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() + ";交易完成,用户已提走"); wuliuEntityList.add(wuliuEntity); } if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) && StringUtils.isNotEmpty(orderEntity.getShippingNo()) && orderProcessRecordEntity.getShipmentStartTime() != null) { if(orderEntity.getShippingCode().equalsIgnoreCase("SF")){ StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId()); if(storeEntity == null){ throw new RRException("查询顺丰订单异常,订单的门店信息不存在"); } ThirdMerchExpressEntity thirdMerchExpressEntity = thirdMerchExpressDao.getThirdMerchExpressByThirdCode(storeEntity.getThirdPartyMerchCode()); if(thirdMerchExpressEntity == null){ throw new RRException("查询顺丰订单异常,缺失商户快递账号信息"); } SfRouteServiceResponseEntity entity = SFUtil.routeService(orderEntity.getShippingNo(), thirdMerchExpressEntity.getExpressAccount(), thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl()); // SfRouteServiceResponseEntity entity = SFUtil.routeService("254355029325", thirdMerchExpressEntity.getExpressAccount(), // thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());//444072971585 if(entity.getHead().equalsIgnoreCase("OK")){ if(entity.getBody() == null){ WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("暂无物流轨迹"); wuliuEntityList.add(wuliuEntity); }else{ if(entity.getBody().getRouteResponse() == null){ WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("暂无物流轨迹"); wuliuEntityList.add(wuliuEntity); }else{ RouteResponseEntity routeResponseEntity = entity.getBody().getRouteResponse().get(0); if(routeResponseEntity != null){ List entityList = routeResponseEntity.getRouteResponse(); for (RouteEntity route : entityList) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptTime(route.getAccept_time()); wuliuEntity.setAcceptStation(route.getAccept_address() + route.getRemark()); wuliuEntityList.add(wuliuEntity); } } } } }else{ throw new RRException("查询顺丰订单异常,"+entity.getErrors()); } }else{ JSONObject traces = KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo()); List mapList = (List) traces.get("Traces"); if (mapList != null && mapList.size() > 0) { for (Map map : mapList) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptTime(map.get("AcceptTime").toString()); wuliuEntity.setAcceptStation(map.get("AcceptStation").toString()); wuliuEntityList.add(wuliuEntity); } } String state = traces.get("State") + ""; if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) { String reason = traces.get("Reason") + ""; WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation(reason); wuliuEntityList.add(wuliuEntity); } } } if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) && orderProcessRecordEntity.getShipmentStartTime() != null) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("订单已出库"); wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(orderProcessRecordEntity.getShipmentStartTime())); wuliuEntityList.add(wuliuEntity); } if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("订单清关完成,等待仓库发货"); wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(orderProcessRecordEntity.getCustomsSuccTime())); wuliuEntityList.add(wuliuEntity); } if (Dict.isSend.item_0.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend())) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("订单清关失败"); wuliuEntityList.add(wuliuEntity); } if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsEleOrderSend()) && orderProcessRecordEntity.getWaybillSuccTime() != null) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("海关三单发送成功"); wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(orderProcessRecordEntity.getWaybillSuccTime())); wuliuEntityList.add(wuliuEntity); } if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsPaymentSend())) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("订单支付成功"); wuliuEntity.setAcceptTime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderProcessRecordEntity.getPaySuccTime())); wuliuEntityList.add(wuliuEntity); } if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsAddOrderSend())) { WuliuEntity wuliuEntity = new WuliuEntity(); wuliuEntity.setAcceptStation("订单下单成功"); wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(orderProcessRecordEntity.getAddOrderSuccTime())); wuliuEntityList.add(wuliuEntity); } } logisticsInfo.put("tracesList", wuliuEntityList); logisticsInfo.put("logisticCode", orderEntity.getShippingNo()); logisticsInfo.put("shipperCode", orderEntity.getShippingCode()); return logisticsInfo; } @Override public OrderEntity queryInfos(Long id) { OrderEntity orderEntity = orderDao.queryObject(id); Map map = new HashMap(); map.put("orderId", id); List orderGoodsEntityList = orderGoodsDao.queryList(map); orderEntity.setOrderGoodsEntityList(orderGoodsEntityList); return orderEntity; } /** * 普货商品生成线下订单 * @param offlineCartList * @param user * @return */ @Transactional @Override public Map orderSubmit(List offlineCartList, SysUserEntity user) { Map resultObj = Maps.newHashMap(); try { if (user == null) { resultObj.put("errno", 400); resultObj.put("errmsg", "用户登录超时,请重新登录"); return resultObj; } if (!user.getRoleType().equalsIgnoreCase("2")) { resultObj.put("errno", 400); resultObj.put("errmsg", "该操作只允许店员账户操作"); return resultObj; } if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) { resultObj.put("errno", 400); resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作"); return resultObj; } Long userId = user.getUserId(); Integer storeId = user.getStoreId(); //获取要购买的商品 Map param = Maps.newHashMap(); param.put("userId", userId); param.put("storeId", storeId); if (null == offlineCartList && offlineCartList.size() == 0) { resultObj.put("errno", 400); resultObj.put("errmsg", "购买商品数据为空"); return resultObj; } List offlineCartEntityList = offlineCartDao.queryOfflineCartByBizType(param); if (offlineCartEntityList.size() == 0 && offlineCartList.size() > 0) { resultObj.put("errno", 0); resultObj.put("errmsg", "该单已下单成功,请重新扫描商品进行购买"); return resultObj; } // 检查库存和更新库存 for (OfflineCartEntity cartEntity : offlineCartEntityList) { GoodsEntity goodsEntity = goodsDao.queryObject(cartEntity.getGoodsId()); if (goodsEntity == null) { resultObj.put("errno", 400); resultObj.put("errmsg", "订单提交失败:商品不存在"); return resultObj; } //取得规格的信息,判断规格库存 ProductStoreRelaEntity productInfo = productStoreRelaDao .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(cartEntity.getGoodsId())); synchronized (productInfo) { if (null == productInfo || null == productInfo.getStockNum() || productInfo.getStockNum() < cartEntity.getNumber()) { resultObj.put("errno", 400); resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum()); return resultObj; } else { productInfo.setStockNum(productInfo.getStockNum() - cartEntity.getNumber()); productInfo.setStoreId(Long.valueOf(storeId)); productInfo.addSellVolume(); productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存 if(goodsEntity != null) { goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - cartEntity.getNumber()); goodsDao.update(goodsEntity); } } } } String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber(); OrderEntity order = setOrderVo(user, offlineCartEntityList, user.getMerchSn()); order.setStoreId(storeId); order.setMerchOrderSn(merchOrderSn); //开启事务,插入订单信息和订单商品 if (order != null) { orderDao.save(order); if (null == order.getId()) { resultObj.put("errno", 400); resultObj.put("errmsg", "订单提交失败"); return resultObj; } for (OfflineCartEntity cartEntity : offlineCartEntityList) { OrderGoodsEntity orderGoodsEntity = setOrderGoodsVo(order, cartEntity); //新增订单详情 orderGoodsDao.save(orderGoodsEntity); } //清空预订单商品临时表 offlineCartDao.deleteByUserId(userId); Map orderInfoMap = Maps.newHashMap(); orderInfoMap.put("orderInfo", order); resultObj.put("errno", 0); resultObj.put("errmsg", "订单提交成功"); resultObj.put("data", orderInfoMap); } } catch (Exception e) { e.printStackTrace(); resultObj.put("errno", 400); resultObj.put("errmsg", "订单异常"); return resultObj; } return resultObj; } /** * 设置订单数据 * * @param loginUser * @return */ public OrderEntity setOrderVo(SysUserEntity loginUser, List offlineCartEntityList, String merchSn) { OrderEntity orderInfo = new OrderEntity(); BigDecimal freightPrice = new BigDecimal(0.00); BigDecimal goodsTotalPrice = new BigDecimal(0.00); for (OfflineCartEntity offlineCartEntity : offlineCartEntityList) { goodsTotalPrice = goodsTotalPrice .add(offlineCartEntity.getRetailPrice().multiply(new BigDecimal(offlineCartEntity.getNumber()))); } //订单价格计算:订单的总价+运费 BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); //查询未使用的优惠券 /*String couponName = ""; BigDecimal fullCutCouponDec = Constant.ZERO; UserCouponVo couponVo = null;*/ BigDecimal couponPrice = new BigDecimal(0.00); //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额 BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice); //商户(拼音首字母)+业务类型+编号 // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn(); // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName(); MerchEntity merchEntity = merchDao.findByMerchSn(merchSn); String merchShortName = ""; if (merchEntity != null) { merchShortName = merchEntity.getMerchShortName(); } String orderSn = merchShortName + Dict.orderBizType.item_11.getItem() + CommonUtil.generateOrderNumber(); orderInfo.setOrderSn(orderSn); orderInfo.setMerchSn(merchSn); orderInfo.setUserId(Integer.parseInt(loginUser.getUserId() + "")); orderInfo.setFreightPrice(freightPrice.intValue()); orderInfo.setOrderBizType(Dict.orderBizType.item_11.getItem()); /*orderInfo.setCoupon_id(userCouponId); orderInfo.setCoupon_name(couponName);*/ // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券 orderInfo.setCouponPrice(couponPrice); orderInfo.setPostscript("");//留言 orderInfo.setAddTime(new Date()); orderInfo.setGoodsPrice(goodsTotalPrice); orderInfo.setOrderPrice(orderTotalPrice); orderInfo.setActualPrice(actualPrice); orderInfo.setOrderType("1"); orderInfo.setOrderStatus(0);// 待付款 orderInfo.setShippingStatus(0); orderInfo.setPayStatus(0); orderInfo.setShippingId(0L); orderInfo.setShippingFee(Constant.ZERO); orderInfo.setIntegral(0); orderInfo.setIntegralMoney(Constant.ZERO); orderInfo.setCreateTime(new Date()); orderInfo.setModTime(new Date()); orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买 /*//标记该订单已使用优惠券 if(couponVo != null){ couponVo.setUsed_time(new Date()); couponVo.setIsUsed(Dict.isUsed.item_1.getItem()); apiUserCouponMapper.update(couponVo); }*/ return orderInfo; } /** * 设置订单数据 * * @param * @return */ public OrderEntity setOrder(Integer userId, List goodsList, String merchSn) { OrderEntity orderInfo = new OrderEntity(); BigDecimal freightPrice = new BigDecimal(0.00); BigDecimal goodsTotalPrice = new BigDecimal(0.00); for (LinkedHashMap goods : goodsList) { goodsTotalPrice = goodsTotalPrice .add(new BigDecimal( goods.get("retailPrice").toString()).multiply(new BigDecimal( goods.get("sellVolume").toString()))); } //订单价格计算:订单的总价+运费 BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); //查询未使用的优惠券 /*String couponName = ""; BigDecimal fullCutCouponDec = Constant.ZERO; UserCouponVo couponVo = null;*/ BigDecimal couponPrice = new BigDecimal(0.00); //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额 BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice); //商户(拼音首字母)+业务类型+编号 // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn(); // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName(); MerchEntity merchEntity = merchDao.findByMerchSn(merchSn); String merchShortName = ""; if (merchEntity != null) { merchShortName = merchEntity.getMerchShortName(); } String orderSn = merchShortName + Dict.orderBizType.item_10.getItem() + CommonUtil.generateOrderNumber(); orderInfo.setOrderSn(orderSn); orderInfo.setMerchSn(merchSn); orderInfo.setUserId(userId); orderInfo.setFreightPrice(freightPrice.intValue()); orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem()); /*orderInfo.setCoupon_id(userCouponId); orderInfo.setCoupon_name(couponName);*/ // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券 orderInfo.setCouponPrice(couponPrice); orderInfo.setPostscript("");//留言 orderInfo.setAddTime(new Date()); orderInfo.setGoodsPrice(goodsTotalPrice); orderInfo.setOrderPrice(orderTotalPrice); orderInfo.setActualPrice(actualPrice); orderInfo.setOrderType("1"); orderInfo.setOrderStatus(0);// 待付款 orderInfo.setShippingStatus(0); orderInfo.setPayStatus(0); orderInfo.setShippingId(0L); orderInfo.setShippingFee(Constant.ZERO); orderInfo.setIntegral(0); orderInfo.setIntegralMoney(Constant.ZERO); orderInfo.setCreateTime(new Date()); orderInfo.setModTime(new Date()); orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买 // orderInfo.setIsScan("0");//默认未扫描 /*//标记该订单已使用优惠券 if(couponVo != null){ couponVo.setUsed_time(new Date()); couponVo.setIsUsed(Dict.isUsed.item_1.getItem()); apiUserCouponMapper.update(couponVo); }*/ return orderInfo; } public OrderGoodsEntity setOrderGoodsVo(OrderEntity orderInfo, OfflineCartEntity goodsItem) { GoodsEntity goodsVo = goodsDao.queryObject(goodsItem.getGoodsId()); OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity(); orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + "")); orderGoodsVo.setGoodsId(goodsItem.getGoodsId()); orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn()); orderGoodsVo.setProductId(goodsItem.getProductId()); orderGoodsVo.setGoodsName(goodsItem.getGoodsName()); orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl()); orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice()); orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice()); orderGoodsVo.setNumber(goodsItem.getNumber()); orderGoodsVo.setOrderBizType(Dict.orderBizType.item_11.getItem()); orderGoodsVo.setCreateTime(new Date()); orderGoodsVo.setModTime(new Date()); orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate()); orderGoodsVo.setSku(goodsVo.getSku()); return orderGoodsVo; } // public OrderGoodsEntity setOrderGoods(OrderEntity orderInfo, LinkedHashMap goods) { // GoodsEntity goodsVo = goodsDao.queryObject(goods.get("goodsId")); // ProductEntity productEntity = productDao.queryObjectByGoodsIdAndStoreId(goodsVo.getId() + "", null); // OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity(); // orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + "")); // orderGoodsVo.setGoodsId(goodsVo.getId().intValue()); // orderGoodsVo.setGoodsSn(goodsVo.getGoodsSn()); // orderGoodsVo.setProductId(productEntity.getId().intValue()); // orderGoodsVo.setGoodsName(goodsVo.getName()); // orderGoodsVo.setListPicUrl(goodsVo.getListPicUrl()); // // // orderGoodsVo.setMarketPrice((BigDecimal) goods.get("storeMarketPrice")); // orderGoodsVo.setRetailPrice((BigDecimal) goods.get("storeRetailPrice")); // orderGoodsVo.setNumber((Integer) goods.get("sellVolume")); // orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem()); // orderGoodsVo.setCreateTime(new Date()); // orderGoodsVo.setModTime(new Date()); // orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate()); // orderGoodsVo.setSku(goodsVo.getSku()); // // // BigDecimal number = new BigDecimal(Long.valueOf(goodsItem.getNumber())); // BigDecimal goodsTotal = goodsItem.getRetail_price().multiply(number);//单商品总价 // BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券) // BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price()); // BigDecimal settlePrice = Constant.ZERO; // if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){ // //运费-优惠券 // BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price()); // //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率 // settlePrice = goodsTotal.add(rate.multiply(rateTotal)); // }else{ // if(orderInfo.getFreight_price()!=0){ // //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额 // BigDecimal freightRate = rate.multiply(freightPrice); // //商品结算平摊价格(含运费金额) = 单商品总价+运费税率 // settlePrice = goodsTotal.add(freightRate); // } // if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){ // //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额 // BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price()); // //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率 // settlePrice = goodsTotal.subtract(couponRate); // } // } // if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){ // orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格 // }else{ // orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格 // } // // return orderGoodsVo; // } @Override public OrderEntity queryObjectBySysUser(Long id) { OrderEntity orderEntity = orderDao.queryObjectBySysUser(id); Map map = new HashMap(); map.put("orderId", id); List orderGoodsEntityList = orderGoodsDao.queryList(map); orderEntity.setOrderGoodsEntityList(orderGoodsEntityList); return orderEntity; } @Override public int confirmPay(Long id, String payFlag,String orderSnWx) { SysUserEntity user = ShiroUtils.getUserEntity(); if (user == null) { throw new RRException("用户登录超时,请重新登录"); } if (!user.getRoleType().equalsIgnoreCase("2")) { throw new RRException("该操作只允许店员账户操作"); } OrderEntity orderEntity = queryObject(id); if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { throw new RRException("此订单已付款!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) { throw new RRException("此订单已完成!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) { throw new RRException("此订单已取消!"); } if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) { throw new RRException("此订单已删除!"); } orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem())); orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem())); orderEntity.setPayFlag(payFlag); orderEntity.setPayTime(new Date()); if(Dict.payFlag.item_alipay.getItem().equalsIgnoreCase(payFlag)){ orderEntity.setAliTradeNo(orderSnWx); }else { if (orderSnWx != null) { orderEntity.setOrderSnWx(orderSnWx); } } // Date now = new Date(); // Integer storeId = orderEntity.getStoreId(); // Map queryParams = new HashMap(); // queryParams.put("orderId", orderEntity.getId()); // List orderGoodsList = orderGoodsDao.queryList(queryParams); // // 遍历订单下的详情商品,修改商品的最后销售时间 // if (orderGoodsList!=null && orderGoodsList.size()>0){ // orderGoodsList.forEach(orderGoods ->{ // Integer goodsId = orderGoods.getGoodsId(); // GoodsEntity goodsEntity = goodsDao.queryObject(goodsId); // if (Objects.nonNull(goodsEntity)){ // goodsEntity.setLastSaleTime(now); // goodsDao.update(goodsEntity); // } // if (Objects.nonNull(storeId)){ // ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaDao.queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsId)); // if (Objects.nonNull(productStoreRelaEntity)){ // productStoreRelaEntity.setLastSaleTime(now); // productStoreRelaDao.update(productStoreRelaEntity); // } // } // }); // } orderDao.update(orderEntity); return 0; } @Override public List queryExportList(Map map) { List list = orderDao.queryExportList(map); for (OrderEntity order : list) { OrderProcessRecordEntity orderProcessRecord = orderProcessRecordDao.queryObjectByOrderSn(order.getOrderSn()); order.setOrderProcessRecord(orderProcessRecord); // 查询活动价 BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(order.getOrderSn(),order.getSku()); order.setTopicPrice(topicPrice); } return list; } @Override public List queryOffilineOrderList(Map map) { return orderDao.queryOffilineOrderList(map); } @Override public int uploadExcel(List orderExpressDtoList) { SysUserEntity user = ShiroUtils.getUserEntity(); boolean isFail = false; List failShippingNameList = new ArrayList<>(); List failOrderSnList = new ArrayList<>(); List failShippingCodeList = new ArrayList<>(); List failCodeSnList = new ArrayList<>(); List failNameSnList = new ArrayList<>(); List failStatusOrderSnList = new ArrayList<>(); if (orderExpressDtoList != null && orderExpressDtoList.size() > 0) { for (int i = 0; i < orderExpressDtoList.size(); i++) { OrderExpressDto orderExpressDto = orderExpressDtoList.get(i); OrderEntity orderEntity = new OrderEntity(); Map valideDate = MapBeanUtil.fromObject(orderExpressDto); ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder(); builder.put("orderSn", "订单编号"); builder.put("shippingNo", "快递单号"); builder.put("shippingName", "快递公司"); builder.put("shippingCode", "快递简写"); R r = ValidatorUtil.isEmpty(builder.build(), valideDate); if (Integer.valueOf(r.get("code").toString()) != 0) { throw new RRException(r.get("msg").toString()); } else { r = ValidatorUtil.isEmpty(builder.build(), valideDate); if (Integer.valueOf(r.get("code").toString()) != 0) { throw new RRException(r.get("msg").toString()); } } OrderEntity order = orderDao.queryObjectByOrderSn(orderExpressDto.getOrderSn()); if(order == null){ isFail = true; failOrderSnList.add(orderExpressDto.getOrderSn()); }else{ if(!(order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem()) && order.getPayStatus() == Integer.parseInt(Dict.payStatus.item_2.getItem()))){ isFail = true; failStatusOrderSnList.add(orderExpressDto.getOrderSn()); } } ShippingEntity shippingEntity = shippingDao.queryObjectByCode(orderExpressDto.getShippingCode()); if(shippingEntity == null){ isFail = true; failShippingCodeList.add(orderExpressDto.getShippingCode()); failCodeSnList.add(orderExpressDto.getOrderSn()); }else{ if(!orderExpressDto.getShippingName().equalsIgnoreCase(shippingEntity.getName())){ isFail = true; failShippingNameList.add(orderExpressDto.getShippingName()); failNameSnList.add(orderExpressDto.getOrderSn()); } } if(!isFail){//false则有错误的数据 if(order != null) {// 修改商品 // orderEntity.setOrderSn(orderExpressDto.getOrderSn()); orderEntity.setShippingNo(orderExpressDto.getShippingNo()); orderEntity.setShippingCode(orderExpressDto.getShippingCode()); orderEntity.setShippingName(orderExpressDto.getShippingName()); orderEntity.setShippingStatus(Integer.parseInt(Dict.shippingStatus.item_1.getItem())); orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_300.getItem())); orderEntity.setModerSn(user.getUsername()); orderEntity.setCreateTime(new Date()); orderEntity.setModTime(new Date()); orderEntity.setId(order.getId()); orderDao.update(orderEntity); } } } if(failOrderSnList != null && failOrderSnList.size() > 0){ throw new RRException("导入数据异常,订单编号不存在,不存在的订单编号【"+failOrderSnList+"】,请删除掉再继续操作"); } if(failStatusOrderSnList != null && failStatusOrderSnList.size() > 0){ throw new RRException("导入数据异常,修改订单快递功能只支持已付款未发货的订单,以下订单编号无效【"+failStatusOrderSnList+"】,请删除掉再继续操作"); } if(failShippingCodeList != null && failShippingCodeList.size() > 0){ throw new RRException("导入数据异常,快递简写不在可支持的范围中,简写错误的订单编号【"+failCodeSnList+"】,错误的快递简写【"+failShippingCodeList+"】," + "正确数据可下载订单页面的快递公司简写Excel中查看"); } if(failShippingNameList != null && failShippingNameList.size() > 0){ throw new RRException("导入数据异常,快递简写对应的快递公司不一致,快递公司错误的订单编号【"+failNameSnList+"】,请修改Excel数据中订单编号对应的快递公司错误信息," + "正确数据可下载订单页面的快递公司简写Excel中查看"); } // if(failFreightGoodsSnList != null && failFreightGoodsSnList.size() > 0){ // exportExceptionDataEntity.setExportExceptionData("运费信息请在商城配置》运费模板中维护,运费与商户信息对应,请检查该商品商户信息下的运费是否维护,不存在的商品编码【"+failFreightGoodsSnList+"】,运费【"+failFreightList+"】"); // exportExceptionDataDao.save(exportExceptionDataEntity); // throw new RRException("导入数据异常,异常信息请在商品管理》》商品导入异常数据中查看检查"); // } }else{ throw new RRException("导入数据为空,或者检查商品编码数据是否为空"); } return 1; } @Override public List promOrderList(Map map) { Integer[] statusList = {201}; List list = orderDao.promOrderList(map); for (OrderEntity orderEntity: list) { Map queryMap = new HashMap<>(); queryMap.put("goodsId", orderEntity.getGoodsId()); queryMap.put("statusList", statusList); queryMap.put("orderId", orderEntity.getId()); Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap); if(promActualPrice == null){ promActualPrice = 0d; } orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice)); } return list; } @Override public int queryPromOrderTotal(Map map) { return orderDao.queryPromOrderTotal(map); } @Override public List promOrderListExport(Map map){ Integer[] statusList = {201}; List list = orderDao.promOrderListExport(map); for (OrderEntity orderEntity: list) { Map queryMap = new HashMap<>(); queryMap.put("goodsId", orderEntity.getGoodsId()); queryMap.put("orderId", orderEntity.getId()); queryMap.put("statusList", statusList); Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap); if(promActualPrice == null){ promActualPrice = 0d; } orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice)); } return list; } @Override public List storeTopicOrderList(Map map) { List list = orderDao.storeTopicOrderList(map); return list; } @Override public int queryStoreTopicOrderTotal(Map map) { return orderDao.queryStoreTopicOrderTotal(map); } @Override public List wxOrderResendQueryAllList(Map map){ // String requestData = JacksonUtil.toJson(map); String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl(); // 同步访问,返回结果字符串 String response = OkHttpUtils.post(map, url, "SSL"); ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class); if(responseData.getCode().equalsIgnoreCase("0")){ List list = responseData.getData().getRows(); return list; } return null; } @Override public List queryOrderListByRecognition(Map map){ String value = sysConfigDao.queryByKey("FACE_COLLECT_FREQUENCY_TIME"); if(value==null){ throw new RRException("请联系管理员配系统参数置FACE_COLLECT_FREQUENCY_TIME信息!"); } List list = orderDao.queryOrderListByRecognition(map); for (OrderRecognitionDto orderRecognitionDto: list){ Integer frequencySecondTime = Integer.parseInt(value); String lastFaceTime = orderRecognitionDto.getLastFaceTime(); if(StringUtils.isNotEmpty(lastFaceTime)) { Date lastFaceDate = DateUtils.convertStringToDate(lastFaceTime, DateUtils.DATE_TIME_PATTERN); Calendar calendar = Calendar.getInstance(); calendar.setTime(lastFaceDate); calendar.add(Calendar.SECOND, frequencySecondTime); Date addSecondTime = calendar.getTime(); Date nowDate = new Date(); if (addSecondTime.getTime() > nowDate.getTime()) { orderRecognitionDto.setAddSecondTime(DateUtils.format(addSecondTime,DateUtils.DATE_TIME_PATTERN)); orderRecognitionDto.setIsDateLast("false"); } else { //可调用身份验证范围内 orderRecognitionDto.setIsDateLast("true"); } }else{//可调用身份验证范围内 orderRecognitionDto.setIsDateLast("true"); } } return list; } @Override public int queryOrderListByRecognitionTotal(Map map){ return orderDao.queryOrderListByRecognitionTotal(map); } /** * 提交订单并付款 * * @param param * @param user * @return */ @Override @Transactional public Map offlineRetailSubmit(Map param, SysUserEntity user) { // 解析订单数据 List List goodsList = (List) param.get("goodsList"); // 解析用户信息 LinkedHashMap Map userInfo = (Map) param.get("userInfo"); // 解析支付码 String String parCode = (String) param.get("payCode"); // 解析sessionId(WebSocket) String String sessionId = (String) param.get("sessionId"); // machineCode String machineCode = (String) param.get("machineCode"); try { machineCode = URLDecoder.decode(machineCode,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Map resultObj = Maps.newHashMap(); try { if (user == null) { resultObj.put("errno", 400); resultObj.put("errmsg", "用户登录超时,请重新登录"); return resultObj; } if (!user.getRoleType().equalsIgnoreCase("2")) { resultObj.put("errno", 400); resultObj.put("errmsg", "该操作只允许店员账户操作"); return resultObj; } if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) { resultObj.put("errno", 400); resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作"); return resultObj; } Long userId = user.getUserId(); Integer storeId = user.getStoreId(); List goodsEntities = new ArrayList<>(); // 检查库存和更新库存 for (LinkedHashMap goodsDto : goodsList) { // GoodsEntity goodsEntity = goodsDao.queryObjectByProdBarcodeAndStore((String) goodsDto.get("prodBarcode"),storeId); if (goodsEntity == null) { resultObj.put("errno", 400); resultObj.put("errmsg", "订单提交失败:商品不存在"); return resultObj; } Integer sellVolume = (Integer)goodsDto.get("sellVolume"); goodsDto.put("goodsId",goodsEntity.getId()); goodsDto.put("goodsSn",goodsEntity.getGoodsSn()); goodsDto.put("productId",goodsEntity.getProductId()); goodsDto.put("storeMarketPrice",goodsEntity.getStoreMarketPrice()); goodsDto.put("storeRetailPrice",goodsEntity.getStoreRetailPrice()); //取得规格的信息,判断规格库存 ProductStoreRelaEntity productInfo = productStoreRelaDao .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsEntity.getId())); synchronized (productInfo) { if (null == productInfo || null == productInfo.getStockNum() || productInfo.getStockNum() < (sellVolume)) { resultObj.put("errno", 400); resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum()); return resultObj; } else { // 判断销售价是否低于底线价 BigDecimal bottomLinePrice = new BigDecimal(productInfo.getBottomLinePrice()); if (goodsEntity.getStoreRetailPrice().compareTo(bottomLinePrice) <= -1) { LOGGER.error("销售价格小于底线价格"); // 记录该信息,到价格过低日志表中,这里没有活动id Mall2LowPriceWarningEntity lowPriceWarningEntity = new Mall2LowPriceWarningEntity(); lowPriceWarningEntity.setSalePrice(goodsEntity.getStoreRetailPrice()); lowPriceWarningEntity.setWarningPrice(bottomLinePrice); lowPriceWarningEntity.setSku(goodsEntity.getGoodsSn()); lowPriceWarningEntity.setWarningType("00"); lowPriceWarningEntity.setStoreId(storeId+""); lowPriceWarningEntity.setCreateTime(new Date()); lowPriceWarningDao.save(lowPriceWarningEntity); resultObj.put("errno", 400); resultObj.put("errmsg", "商品"+goodsEntity.getName()+"的销售价格小于底线价格"); return resultObj; } productInfo.setStockNum(productInfo.getStockNum() - sellVolume); productInfo.setStoreId(Long.valueOf(storeId)); productInfo.addSellVolume(); productInfo.setLastSaleTime(new Date()); productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存 if(goodsEntity != null) { goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - sellVolume); goodsEntity.setLastSaleTime(new Date()); goodsDao.update(goodsEntity); } } // 实际取的是门店商品的价格,所以借这个字段来存储销售价 goodsEntity.setStoreRetailPrice(productInfo.getRetailPrice()); // 借用这个字段来存储购买数 goodsEntity.setGoodsNumber(sellVolume); goodsEntities.add(goodsEntity); } } UserEntity userEntity = userDao.queryByMobile((String) userInfo.get("customPhone")); if(userEntity == null) { // 保存用户信息 userEntity = new UserEntity(); userEntity.setUsername((String) userInfo.get("customName")); userEntity.setPassword(""); userEntity.setIdNo((String) userInfo.get("customIDCard")); userEntity.setMobile((String) userInfo.get("customPhone")); userEntity.setGender(1); userEntity.setRegisterTime(new Date()); userEntity.setLastLoginTime(new Date()); userEntity.setIdNo((String) userInfo.get("customIDCard")); userDao.save(userEntity); MerchUserEntity merchUserEntity = new MerchUserEntity(); merchUserEntity.setMerchSn(user.getMerchSn()); merchUserEntity.setStoreId(storeId); merchUserEntity.setUserId(userEntity.getId()); merchUserEntity.setCreateTime(new Date()); merchUserEntity.setIsLoadGoods("0"); merchUserDao.save(merchUserEntity); } // 根据活动形式来查询 // 优惠金额 BigDecimal disCountAmount = new BigDecimal(0); // 活动id Integer topicId = 0; // 查询活动类别id MkStorePromTypeEntity mkStorePromEntity = storePromTypeDao.queryByName("周活动"); // 根据门店id和活动类别查询该门店是否有活动 StoreTopicEntity storeTopic = storeTopicDao.queryByStoreIdAndType(storeId,mkStorePromEntity.getPromTypeId()); // 判断是否启用了活动,如果启用了活动。则去查询活动价 if(storeTopic != null){ for(GoodsEntity goodsEntity :goodsEntities){ // 根据活动id跟商品id,查询该商品的价格 Mk2GoodsTopicPriceEntity goodsTopicPriceEntity = mk2GoodsTopicPriceDao.queryByTopicIdAndGoodsId(storeTopic.getId(),goodsEntity.getSku()); if (goodsEntity.getStoreRetailPrice().compareTo(goodsTopicPriceEntity.getTopicPrice()) <= -1) { LOGGER.error("销售价格小于活动价格"); // 记录该信息,到价格过低日志表中,这里有活动id Mall2LowPriceWarningEntity lowPriceWarningEntity = new Mall2LowPriceWarningEntity(); lowPriceWarningEntity.setSalePrice(goodsEntity.getStoreRetailPrice()); lowPriceWarningEntity.setWarningPrice(goodsTopicPriceEntity.getTopicPrice()); lowPriceWarningEntity.setActivityId(goodsTopicPriceEntity.getTopicId()); lowPriceWarningEntity.setSku(goodsEntity.getGoodsSn()); lowPriceWarningEntity.setWarningType("00"); lowPriceWarningEntity.setStoreId(storeId+""); lowPriceWarningEntity.setCreateTime(new Date()); lowPriceWarningDao.save(lowPriceWarningEntity); resultObj.put("errno", 400); resultObj.put("errmsg", "商品"+goodsEntity.getName()+"的销售价格小于活动价格"); return resultObj; } goodsEntity.setStoreRetailPrice(goodsTopicPriceEntity.getTopicPrice()); } topicId = storeTopic.getId(); }else{ disCountAmount = getDisCountAmout(goodsEntities); } // 判断该用户是否是生日 Boolean isBirth = false; String birthday = ""; if(userEntity.getIdNo().length() == 15){ birthday = userEntity.getIdNo().substring(8,10) + "-" + userEntity.getIdNo().substring(10,12); }else if(userEntity.getIdNo().length() == 18){ birthday = userEntity.getIdNo().substring(10,12) + "-" + userEntity.getIdNo().substring(12,14); } SimpleDateFormat format = new SimpleDateFormat("MM-dd"); String today = format.format(new Date()); if(birthday.equalsIgnoreCase(today)){ isBirth = true; } // 生成订单 String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber(); OrderVo order = setOrderVo(goodsEntities, userEntity,storeId.longValue(), user.getMerchSn(),disCountAmount); order.setStore_id(storeId.longValue()); if(storeTopic != null){ order.setActivity_id(storeTopic.getId().longValue()); } order.setMerchOrderSn(merchOrderSn); //插入订单信息和订单商品 orderDao.saveOrderVo(order); // TODO 订单流转表 OrderProcessRecordEntity processRecordEntity = new OrderProcessRecordEntity(); processRecordEntity.setOrderSn(order.getOrder_sn()); processRecordEntity.setUserId(Integer.valueOf(userEntity.getId()+"")); processRecordEntity.setAddOrderStartTime(order.getCreateTime()); processRecordEntity.setIsAddOrderSend(Dict.isSend.item_1.getItem()); processRecordEntity.setOrderBizType(Dict.orderBizType.item_10.getItem()); if (null == order.getId()) { resultObj.put("errno", 400); resultObj.put("errmsg", "订单提交失败"); return resultObj; } for (GoodsEntity goodsDto : goodsEntities) { OrderGoodsVo orderGoodsVo = setOrderGoodsVo(order,goodsDto); //新增订单详情 orderGoodsDao.saveOrderGoodsVo(orderGoodsVo); } //清空预订单商品临时表 Map orderInfoMap = Maps.newHashMap(); orderInfoMap.put("orderInfo", order); resultObj.put("errno", 0); resultObj.put("errmsg", "订单提交成功"); resultObj.put("data", orderInfoMap); //判断支付类型,并支付订单 R r = null; //保存支付记录 OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecordVo(order); StoreEntity store = storeService.queryObject(order.getStore_id().intValue()); // 设置支付单开始时间 processRecordEntity.setPaymentStartTime(new Date()); // 微信支付 // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store); // 支付宝支付 AliPay(user, parCode , order, processRecordEntity, orderWXPayRecordCurrent, store); resultObj.put("shopName",store.getStoreName()); // 根据门店编号查询 resultObj.put("userName",user.getUsername()); // 保存订单流转表 // 设置下单完成时间 processRecordEntity.setAddOrderSuccTime(order.getPay_time()); orderProcessRecordDao.save(processRecordEntity); // 生成取票码 PickUpCodeEntity pickUpCodeEntity = new PickUpCodeEntity(); pickUpCodeEntity.setOrderSn(order.getOrder_sn()); pickUpCodeService.save(pickUpCodeEntity); // 生成销售记录 SaleRecordEntity saleRecordEntity = new SaleRecordEntity(); // 根据收银机机器码,查询收银机 CashierEntity cashierEntity = cashierDao.queryByMachineCode(machineCode,storeId+""); if(cashierEntity != null){ saleRecordEntity.setCashierSn(cashierEntity.getCashierSn()); saleRecordEntity.setOrderSn(order.getOrder_sn()); saleRecordEntity.setSallerId(userId+""); saleRecordEntity.setSalesTime(new Date()); saleRecordEntity.setDiscountId(topicId + ""); saleRecordEntity.setCreateTime(new Date()); saleRecordDao.save(saleRecordEntity); } // 查询积分规则 ,默认先按消费金额1:1积分 Mall2PointsRulesEntity pointsRules = null; // 增加该会员的积分 Mall2MemberPointsEntity memberPointsEntity = memberPointsDao.queryByUserId(userEntity.getId()); if(memberPointsEntity == null){ memberPointsEntity = new Mall2MemberPointsEntity(); memberPointsEntity.setUserId(userEntity.getId()+""); memberPointsEntity.setPoints(order.getActual_price().intValue()); memberPointsEntity.setCreaterSn(userId+""); memberPointsEntity.setCreateTime(new Date()); memberPointsDao.save(memberPointsEntity); }else{ memberPointsEntity.setPoints(order.getActual_price().add(new BigDecimal(memberPointsEntity.getPoints())).intValue()); memberPointsEntity.setModerSn(userId+""); memberPointsEntity.setModTime(new Date()); memberPointsDao.update(memberPointsEntity); } // 增加该会员的消费记录 Mall2MemberConsumptionRecordsEntity consumptionRecords = new Mall2MemberConsumptionRecordsEntity(); consumptionRecords.setUserId(userEntity.getId()+""); consumptionRecords.setOrderSn(order.getOrder_sn()); consumptionRecords.setConsumptionTime(new Date()); consumptionRecords.setShopSn(storeId+""); // TODO 判断是否有使用生日优惠 if(isBirth){ consumptionRecords.setIsUseBirthdayOffer("0"); // 使用生日优惠 }else{ consumptionRecords.setIsUseBirthdayOffer("1"); // 没使用生日优惠 } consumptionRecords.setCreaterSn(userId+""); consumptionRecords.setCreateTime(new Date()); memberConsumptionRecordsDao.save(consumptionRecords); resultObj.put("code",pickUpCodeEntity.getPickUpCodeSn()); // 系统中累加 resultObj.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); resultObj.put("orderNo",order.getOrder_sn()); // // 通知WebSocket WebSocketServer.sendMessage(sessionId,order.getOrder_sn(),order.getStore_id() +""); } catch (Exception e) { e.printStackTrace(); resultObj.put("errno", 400); resultObj.put("errmsg", "订单异常------"+e.getMessage()); throw new RuntimeException(e); } return resultObj; } private BigDecimal getDisCountAmout(List goodsEntities) { BigDecimal disCountAmount; // TODO 生成订单之前,先查询是否有优惠券或者满减 // TODO 20200610 要修改成全部商品 // 优惠券的集合 List mkStoreTicketDiscountEntities = new ArrayList<>(); // 满减的集合 List mkStoreCampMinusEntities = new ArrayList<>(); // 存商品跟金额的关系 Map moneyMap = new HashMap<>(); // 商品总价 BigDecimal totalPrice = new BigDecimal(0); for(GoodsEntity goodsEntity : goodsEntities){ Long goodsId = goodsEntity.getId(); // 计算该商品的价格 BigDecimal goodsPrice = goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber())).setScale(2, RoundingMode.HALF_UP); moneyMap.put(goodsId,goodsPrice); totalPrice = totalPrice.add(goodsPrice); // 查询该商品id是否有优惠券 List mkStoreTicketDiscountEntity = mkStoreTicketDiscountService.queryByGoodsId(goodsId); if(mkStoreTicketDiscountEntity != null) { mkStoreTicketDiscountEntities.addAll(mkStoreTicketDiscountEntity); } // 查询该商品id是否有满减 List mkStoreCampMinusEntity = mkStoreCampMinusService.queryByGoodsId(goodsId); if(mkStoreCampMinusEntity != null) { mkStoreCampMinusEntities.addAll(mkStoreCampMinusEntity); } } // 满减优惠的金额 BigDecimal campDisCountAmount = new BigDecimal(0); if(mkStoreCampMinusEntities.size() > 0){ // 上一次所需金额,用于取最大的优惠力度 BigDecimal lastAmount = new BigDecimal(0); for (int i = 0 ; i < mkStoreCampMinusEntities.size() ; i++){ MkStoreCampMinusLevelEntity mkStoreCampMinusLevelEntity = mkStoreCampMinusEntities.get(i); // TODO 20200610还有满多少件,跟满多少元打折的,逻辑复杂,下次开发 BigDecimal discCond = mkStoreCampMinusLevelEntity.getYuanMinusCond(); // 判断这次金额是否大于上次金额,如果不大于,直接continue if(discCond.compareTo(lastAmount) > 0){ // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱 if(totalPrice.compareTo(discCond) > 0){ // 记录上一次金额 lastAmount = discCond; campDisCountAmount = mkStoreCampMinusLevelEntity.getYuanMinusPref(); } } } } // 优惠券优惠的金额 BigDecimal ticketDisCountAmount = new BigDecimal(0); if(mkStoreTicketDiscountEntities.size() > 0){ // 上一次所需金额,用于取最大的优惠力度 BigDecimal lastAmount = new BigDecimal(0); BigDecimal lastRadio = new BigDecimal(0); for (int i = 0 ; i < mkStoreTicketDiscountEntities.size() ; i++){ MkStoreTicketDiscountEntity mkStoreTicketDiscountEntity = mkStoreTicketDiscountEntities.get(i); // 代金券所需金额 // TODO 20200610还有折扣券的,逻辑较为复杂,下次在开发 if("00".equals(mkStoreTicketDiscountEntity.getApplyType())){ BigDecimal discCond = mkStoreTicketDiscountEntity.getVoucherCond(); // 判断这次金额是否大于上次金额,如果不大于,直接continue if(discCond.compareTo(lastAmount) > 0){ // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱 if(totalPrice.compareTo(discCond) > 0){ // 记录上一次金额 lastAmount = discCond; ticketDisCountAmount = mkStoreTicketDiscountEntity.getVoucherMoney(); } } }else if("01".equals(mkStoreTicketDiscountEntity.getApplyType())){ BigDecimal discCond = mkStoreTicketDiscountEntity.getDiscCond(); if(totalPrice.compareTo(discCond) > 0){ // 打的折扣 lastRadio = mkStoreTicketDiscountEntity.getDiscRatio(); } } } } disCountAmount = ticketDisCountAmount.compareTo(campDisCountAmount) > 0 ? ticketDisCountAmount : campDisCountAmount; return disCountAmount; } private void AliPay(SysUserEntity user, String parCode, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws Exception { AliPayRequestParams params = new AliPayRequestParams(); params.setAuthCode(parCode); params.setBody(order.getApprovalRemark()); params.setOutTradeNo(order.getOrder_sn()); params.setSubject("CW下单"); params.setStoreId(store.getId()+""); params.setTotalAmount(order.getActual_price().setScale(2,BigDecimal.ROUND_HALF_UP)+""); LOGGER.info("调用阿里支付接口的请求参数:"+JacksonUtils.toJson(params)); AliPayMicropayApiResult aliPayMicropayApiResult = AliPayUtil.aliTradePay(params); orderWXPayRecordService.updateRecordByAli(orderWXPayRecordCurrent.getId(), aliPayMicropayApiResult); LOGGER.info("调用阿里支付接口的同步返回结果:"+JacksonUtils.toJson(aliPayMicropayApiResult)); // 修改订单状态 //当支付成功时,修改订单,并把其他支付记录撤销 if (AliPayUtil.AliPayTradeState.SUCC.getCode().equals(aliPayMicropayApiResult.getCode())) { // //查询当前订单所有的支付记录 // List orderWXPayRecordEntitys = // orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn()); this.confirmPay(order.getId(), Dict.payFlag.item_alipay.getItem(), aliPayMicropayApiResult.getTradeNo()); // 设置支付单完成时间 processRecordEntity.setPaymentSuccTime(aliPayMicropayApiResult.getGmtPayment()); processRecordEntity.setPayTransactionId(aliPayMicropayApiResult.getTradeNo()); // 系统繁忙 } else if(AliPayUtil.AliPayTradeState.SERVER_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请稍后再试"); // 支付失败 }else if(AliPayUtil.AliPayTradeState.BUSINESS_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())){ // 系统异常 if(AliPayUtil.BusinessFailState.SYSTEM_ERROR.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请稍后再试"); // 订单总额超过限额 }else if(AliPayUtil.BusinessFailState.TOTAL_FEE_EXCEED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请告知顾客"); // 授权码无效 }else if(AliPayUtil.BusinessFailState.PAYMENT_AUTH_CODE_INVALID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请顾客刷新条码后,重新支付"); // 交易信息被篡改 }else if(AliPayUtil.BusinessFailState.CONTEXT_INCONSISTENT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试"); // 余额支付功能关闭 }else if(AliPayUtil.BusinessFailState.ERROR_BALANCE_PAYMENT_DISABLE.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户打开余额支付"); // 交易买家不匹配 }else if(AliPayUtil.BusinessFailState.TRADE_BUYER_NOT_MATCH.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试"); // 买家状态非法 }else if(AliPayUtil.BusinessFailState.BUYER_ENABLE_STATUS_FORBID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家联系支付宝小二,确认为什么非法"); // 唤起移动收银台失败 }else if(AliPayUtil.BusinessFailState.PULL_MOBILE_CASHIER_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户刷新条码后,重新支付"); // 用户的无限支付开关关闭 }else if(AliPayUtil.BusinessFailState.MOBILE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户在PC上打开无线支付开关后,在发起支付"); // 支付失败 }else if(AliPayUtil.BusinessFailState.PAYMENT_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试"); // 商户账号被冻结 }else if(AliPayUtil.BusinessFailState.SELLER_BEEN_BLOCKED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请联系支付宝小二解冻"); // 买家未通过人行认证 }else if(AliPayUtil.BusinessFailState.ERROR_BUYER_CERTIFY_LEVEL_LIMIT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家联系支付宝小二"); // 用户当面付付款开关管壁 }else if(AliPayUtil.BusinessFailState.USER_FACE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家打开当面付付款开关"); }else{ LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()); } // 其他支付异常状态 } else { LOGGER.info(aliPayMicropayApiResult.getSubMsg()); throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+"...........请联系管理员"); } } private void wxPay(SysUserEntity user, String parCode, Map resultObj, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws ParseException { R r; WechatMicropayApiResult wechatMicropayApiResult = WechatUtil .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), order.getOrderBizType(), null, orderWXPayRecordCurrent.getOutTradeNoWX(), order.getActual_price().doubleValue(), "127.0.0.1", parCode); orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult); resultObj.put("shopName",store.getStoreName()); // 根据门店编号查询 resultObj.put("userName",user.getUsername()); // 修改订单状态 //当支付成功时,修改订单,并把其他支付记录撤销 if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) { //查询当前订单所有的支付记录 List orderWXPayRecordEntitys = orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn()); for (OrderWXPayRecordEntity orderWXPayRecordTemp : orderWXPayRecordEntitys) { //查询出来的记录排除当前已支付成功的记录,对其他记录交易状态为未撤销,未关闭的订单,调用撤销订单 if (orderWXPayRecordTemp.getId() != orderWXPayRecordCurrent.getId() && (!WechatUtil.WXTradeState.REVOKED.getCode().equals(orderWXPayRecordTemp.getTradeState()) || !WechatUtil.WXTradeState.CLOSED.getCode().equals(orderWXPayRecordTemp.getTradeState()))) { WechatReverseApiResult wechatReverseApiResult = WechatUtil.wxReverse(orderWXPayRecordTemp.getOutTradeNoWX()); //撤销订单成功 if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) && WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) { //调用订单查询接口 WechatRefundApiResult wechatRefundApiResult = WechatUtil.wxOrderQuery(orderWXPayRecordTemp.getOutTradeNoWX()); if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) && WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) { // 修改订单支付记录 orderWXPayRecordService .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult); } } } } this.confirmPay(order.getId(), Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX()); // 设置支付单完成时间 processRecordEntity.setPaymentSuccTimeStr(wechatMicropayApiResult.getTime_end()); processRecordEntity.setPaymentSuccTime( new SimpleDateFormat("yyyyMMddHHmmss").parse(wechatMicropayApiResult.getTime_end())); processRecordEntity.setPayTransactionId(wechatMicropayApiResult.getTransaction_id()); //用户支付中 } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) { r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态"); //用户支付失败 } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) { WechatReverseApiResult wechatReverseApiResult = WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX()); //撤销订单成功 if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) && WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) { //调用订单查询接口 WechatRefundApiResult wechatRefundApiResult = WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX()); if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) && WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) { // 修改订单支付记录 orderWXPayRecordService .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult); } r = R.error(orderWXPayRecordCurrent.getErrCodeDes()); } else { r = R.error(wechatReverseApiResult.getErr_code_des()); } } } @Override public OrderEntity queryObjectByOrderSn(String orderSn) { return orderDao.queryObjectByOrderSn(orderSn); } @Override public void orderRefund(OrderEntity order, String sessionId) throws Exception { boolean needUpdateStock = true; if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) { order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem())); } if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) { order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem())); }else{ AliPayMicropayApiResult userRefund = AliPayUtil.aliTradeRefund(order.getMerchOrderSn(), "38.81", "用户退款", order.getStoreId() + ""); LOGGER.info(userRefund.getSubMsg()); order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem())); OrderRefundEntity orderRefund = new OrderRefundEntity(); orderRefund.setRefundId(userRefund.getTradeNo()); orderRefund.setOutRefundNo(userRefund.getOutTradeNo()); orderRefund .setRefundMoney(new BigDecimal(userRefund.getRefundFee())); orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款成功 orderRefund.setModTime(new Date()); orderRefund.setOrderId(Integer.parseInt(order.getId() + "")); orderRefund.setUserId(Integer.parseInt(order.getUserId() + "")); orderRefund.setCreateTime(new Date()); List list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn()); if(list.size()>1){//多条订单 orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款 }else{ orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款 } orderRefundDao.save(orderRefund);//退款记录 } orderDao.update(order);//修改为退款成功 // 修改取货码 PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn()); pickUpCodeEntity.setPickUpCodeStatus("3"); pickUpCodeService.update(pickUpCodeEntity); // WebSocketServer.delete(sessionId,order.getStoreId(),pickUpCodeEntity); updateStock(order, "收银端退款"); } @Override public int queryOffilineOrderTotal(Query query) { return orderDao.queryOffilineOrderTotal(query); } @Override public List purchaseSalesInStockDetailList(Query query) { return orderDao.purchaseSalesInStockDetailList(query); } @Override public int purchaseSalesInStockDetailTotal(Query query) { return orderDao.purchaseSalesInStockDetailTotal(query); } @Override public List queryExportOffilineOrderList(Map params) { List orderEntityList = orderDao.queryExportOffilineOrderList(params); if (orderEntityList!=null && orderEntityList.size()>0){ for (OrderEntity orderEntity : orderEntityList) { // 查询活动价 BigDecimal topicPrice = orderDao.queryTopicPriceByOrderSnAndSku(orderEntity.getOrderSn(),orderEntity.getSku()); orderEntity.setTopicPrice(topicPrice); } } return orderEntityList; } @Override public List queryMasterExportOffilineOrderList(Map params) { return orderDao.queryMasterExportOffilineOrderList(params); } @Override public List queryMasterExportList(Map params) { return orderDao.queryMasterExportList(params); } /** * 设置订单数据 * @return */ public OrderVo setOrderVo(List goodsList, UserEntity loginUser,Long storeId, String merchSn, BigDecimal disCountAmount){ OrderVo orderInfo = new OrderVo(); BigDecimal goodsTotalPrice = new BigDecimal(0.00); BigDecimal freightPrice = Constant.ZERO; for (GoodsEntity goodsEntity : goodsList) { goodsTotalPrice = goodsTotalPrice .add(goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()))); } //订单价格计算:订单的总价+运费 BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0)); BigDecimal fullCutCouponDec = Constant.ZERO; BigDecimal couponPrice = disCountAmount; BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice); String orderSn = "CW" + CommonUtil.generateOrderNumber(); orderInfo.setOrder_sn(orderSn); orderInfo.setMerchSn(merchSn); orderInfo.setUser_id(loginUser.getId().longValue()); StoreEntity storeEntity = storeDao.queryObject(storeId); //收货地址和运费 orderInfo.setConsignee(loginUser.getUsername()); orderInfo.setMobile(loginUser.getMobile()); orderInfo.setCountry(""); orderInfo.setProvince(storeEntity.getProvinceName()); orderInfo.setCity(storeEntity.getCityName()); orderInfo.setDistrict(storeEntity.getCountyName()); orderInfo.setAddress(storeEntity.getStoreName()); orderInfo.setAddress_id(1L); orderInfo.setDelivery_date(new Date()); orderInfo.setDelivery_remark("无"); orderInfo.setStore_id(storeId); orderInfo.setFreight_price(freightPrice.intValue()); orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L))); orderInfo.setCoupon_price(couponPrice); orderInfo.setCoupon_name("无"); orderInfo.setActivity_id(0L); //使用的促销费用 orderInfo.setFull_cut_price(fullCutCouponDec); orderInfo.setCampMinusId(0); orderInfo.setCampName(""); //留言 orderInfo.setPostscript("无"); orderInfo.setAdd_time(new Date()); orderInfo.setGoods_price(goodsTotalPrice); orderInfo.setOrder_price(orderTotalPrice); orderInfo.setActual_price(actualPrice); orderInfo.setOrder_type("1"); orderInfo.setOrder_status(0); orderInfo.setShipping_status(0); orderInfo.setPay_status(0); orderInfo.setShipping_id(0L); orderInfo.setShipping_fee(Constant.ZERO); orderInfo.setIntegral(0); orderInfo.setIntegral_money(Constant.ZERO); orderInfo.setCreateTime(new Date()); orderInfo.setModTime(new Date()); orderInfo.setPayMobile(loginUser.getMobile()); orderInfo.setPayTransactionId(""); orderInfo.setIsScan("0");//默认未扫描 orderInfo.setPayMobile(loginUser.getMobile()); orderInfo.setPay_name(loginUser.getUsername()); orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem()); orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem()); return orderInfo; } public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo,GoodsEntity goodsDto){ OrderGoodsVo orderGoodsVo = new OrderGoodsVo(); orderGoodsVo.setOrder_id(orderInfo.getId()); orderGoodsVo.setGoods_id(goodsDto.getId()); orderGoodsVo.setGoods_sn(goodsDto.getGoodsSn()); orderGoodsVo.setProduct_id(Long.valueOf(goodsDto.getProductId())); orderGoodsVo.setGoods_name(goodsDto.getName()); orderGoodsVo.setList_pic_url(goodsDto.getListPicUrl()); orderGoodsVo.setMarket_price(goodsDto.getStoreMarketPrice()); orderGoodsVo.setRetail_price(goodsDto.getStoreRetailPrice()); orderGoodsVo.setNumber(goodsDto.getGoodsNumber()); // orderGoodsVo.setGoods_specification_name_value(goodsDto.get); // orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids()); orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem()); orderGoodsVo.setCreateTime(new Date()); orderGoodsVo.setModTime(new Date()); orderGoodsVo.setGoodsRate(goodsDto.getGoodsRate()); orderGoodsVo.setSku(goodsDto.getSku()); BigDecimal number = new BigDecimal(Long.valueOf(goodsDto.getGoodsNumber())); BigDecimal goodsTotal = goodsDto.getStoreRetailPrice().multiply(number);//单商品总价 BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券) BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price()); BigDecimal settlePrice = Constant.ZERO; if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){ //运费-优惠券 BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price()); //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率 settlePrice = goodsTotal.add(rate.multiply(rateTotal)); }else{ if(orderInfo.getFreight_price()!=0){ //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额 BigDecimal freightRate = rate.multiply(freightPrice); //商品结算平摊价格(含运费金额) = 单商品总价+运费税率 settlePrice = goodsTotal.add(freightRate); } if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){ //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额 BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price()); //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率 settlePrice = goodsTotal.subtract(couponRate); } } if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){ orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格 }else{ orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格 } return orderGoodsVo; } }