package com.ydd.app.service.impl; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.ydd.api.*; import com.ydd.app.service.ApiOrderCancelService; import com.ydd.app.service.ApiWaimaiPrintService; import com.ydd.app.service.ApiWaimaiService; import com.ydd.app.task.TriggerProcessTask; import com.ydd.common.core.redis.RedisCache; import com.ydd.common.enums.WaimaiTypeEnums; import com.ydd.common.utils.DateUtils; import com.ydd.common.utils.SnCodeUtils; import com.ydd.common.utils.StringUtils; import com.ydd.ecloud.core.utils.JsonMapper; import com.ydd.module.domain.*; import com.ydd.module.dto.OrderDetailDto; import com.ydd.module.dto.WaimaiListDto; import com.ydd.module.enums.*; import com.ydd.module.expection.CustomAppException; import com.ydd.module.push.MessagePushService; import com.ydd.module.service.*; import com.ydd.third.common.config.WaimaiConfig; import com.ydd.third.common.vo.ResObject; import com.ydd.third.common.vo.waimai.*; import com.ydd.third.common.vo.waimai.eleme.api.entity.order.OGoodsItem; import com.ydd.third.common.vo.waimai.eleme.api.entity.order.OOrder; import com.ydd.third.common.vo.waimai.eleme.api.entity.order.OrderList; import com.ydd.third.common.vo.waimai.eleme.api.entity.order.UserExtraInfo; import com.ydd.third.common.vo.waimai.jdHome.vo.JdHomeOrderResultVo; import com.ydd.third.common.vo.waimai.meituan.OrderDetailVo; import com.ydd.third.print.request.PrintOrderDto; import com.ydd.third.waimai.eleRetai.param.*; import com.ydd.third.waimai.eleRetai.vo.OrderEBaiInfo; import com.ydd.third.waimai.eleRetai.vo.OrderEBaiList; import com.ydd.third.waimai.jdHome.dto.OrderInfoDTO; import com.ydd.third.waimai.jdHome.dto.OrderInvoiceDTO; import com.ydd.third.waimai.jdHome.dto.OrderProductDTO; import com.ydd.third.waimai.jdHome.dto.StoreInfo; import com.ydd.third.waimai.jdHome.vo.JdHomeParamJsonVo; import com.ydd.third.waimai.meituanSg.vo.SgOrderDetailVo; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.math.BigDecimal; import java.net.URLDecoder; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Project:lb-server * Class:ApiWaimaiServiceImpl * Description:TODO * Time:2021/3/2 17:16 * * @author zoe */ @Slf4j @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class ApiWaimaiServiceImpl implements ApiWaimaiService { public static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); private final IShopWaimaiService iShopWaimaiService; private final IShopService iShopService; private final IMemberConfigService iMemberConfigService; private final IDspWaimaiService iDspWaimaiService; private final MeiTuanApi meituanClient; private final MeiTuanSgApi meituanSgClient; private final JdHomeApi jdHomeClient; private final IWaimaiOrderService iWaimaiOrderService; private final IMemberService iMemberService; private final IMerchantService iMerchantService; private final IDadaDspService iDadaDspService; private final IOrderService iOrderService; private final IWaimaiOrderDetailService iWaimaiOrderDetailService; // private final IShopDeviceService iShopDeviceService; // private final ApiProductService apiProductService; // // private final UnifiedPrintService unifiedPrintService; private final MessagePushService messagePushService; private final ElemeApi elemeClient; private final ApplicationContext applicationContext; // private final Client client; // // private final IDspDeliveryService iDspDeliveryService; // // private final IMemberBalanceLogService iMemberBalanceLogService; private final RedisCache redisCache; private final ApiOrderCancelService apiOrderCancelService; private final EleRetailApi eleRetaiClient; private final IAgentService iAgentService; // private final IShopUserService iShopUserService; private final IMerchantCategoryService iMerchantCategoryService; private final WaimaiConfig waimaiConfig; private final ApiWaimaiPrintService apiWaimaiPrintService; private final IOrderDeliveryService iOrderDeliveryService; private final IWaimaiFoodImgService iWaimaiFoodImgService; private final IShopJdHomeService iShopJdHomeService; private final IShopJdHomeCodeService iShopJdHomeCodeService; // // /** // * 绑定外卖平台 // * // * @param loginId // * @param waimaiId // * @param shopId // * @param isNew 是否是新版本,有值是新版本 // * @param mtBindType 美团外卖绑定类型:1->冲突模式,2->非冲突模式 // * @return // */ // @Override // public String bind(Long loginId, Long waimaiId, Long shopId, Integer isNew,Integer mtBindType) { // Shop shop = iShopService.getById(shopId); // if (isNew != null) { // // 判断门店是否有员工账号,没有提示 //// List shopUsers = iShopUserService.queryByShopId(shopId); //// if (shopUsers == null || shopUsers.size() == 0){ //// throw new CustomAppException("请先添加该门店账号",201); //// } // ShopWaimai shopWaimai = iShopWaimaiService.findById(shopId, waimaiId); // if (shopWaimai != null) { // throw new CustomAppException("已绑定成功!"); // } // } // DspWaimai waimai = iDspWaimaiService.getById(waimaiId); // String url = null; // if (waimai.getType().equals(WaimaiTypeEnums.MEI_TUAN.getType())) { // url = meituanClient.storeMapUrl(shop.getCode(), shop.getName(),mtBindType); // } else if (waimai.getType().equals(WaimaiTypeEnums.E_LE_ME.getType())) { // url = elemeAuthClient.getOAuthUrl(shop.getCode()); // } else if (waimai.getType().equals(WaimaiTypeEnums.E_LE_ME_RETAIL.getType())) { // url = waimaiConfig.getEleRetailUrl(); // } else if (waimai.getType().equals(WaimaiTypeEnums.MEI_TUAN_SG.getType())) { // url = waimaiConfig.getMeituansgUrl(); // } // return url; // } @Override @Transactional @Async public void doNewOrder(MeituanOrderResultVo orderVo) { DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN.getType()); // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", orderVo.getEPoiId())); ShopWaimai shopWaimai =iShopWaimaiService.getOne(new QueryWrapper().eq("epoid", orderVo.getEPoiId()) .eq("deleted",IsDeleteEnum.NORMAL.status) .eq("waimai_id",waimai.getId()) .eq("bind_status",BindStatusEnum.BIND.status)); Long memberId = null; List memberIds = iMemberService.selectByShopId(shopWaimai.getShopId()); if(CollectionUtils.isNotEmpty(memberIds)){ memberId = memberIds.get(0); }else{ Member member = iMemberService.findOne(shopWaimai.getMerchantId()); memberId = member.getId(); } MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id",memberId)); // ShopWaimai shopWaimai = iShopWaimaiService.findById(shop.getId(), waimai.getId()); if (config != null && StatusEnum.SHOW.status.equals(config.getOpenAutoorder())) { ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo(); confirmOrderVo.setLbClient(WaimaiTypeEnums.MEI_TUAN.getName()); confirmOrderVo.setOrderId(orderVo.getOrderId()); confirmOrderVo.setAppAuthToken(shopWaimai.getAuthToken()); ResObject resObject = meituanClient.confirmOrder(confirmOrderVo); log.info("=======美团订单确认结果=====" + JsonMapper.nonEmptyMapper().toJson(resObject)); } } @Override @Transactional @Async public void sgDoNewOrder(MeituanSgOrderResultVo orderVo) { DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN_SG.getType()); // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", orderVo.getAppPoiCode())); ShopWaimai shopWaimai =iShopWaimaiService.getOne(new QueryWrapper().eq("epoid", orderVo.getAppPoiCode()) .eq("deleted",IsDeleteEnum.NORMAL.status) .eq("waimai_id",waimai.getId()) .eq("bind_status",BindStatusEnum.BIND.status)); Long memberId = null; List memberIds = iMemberService.selectByShopId(shopWaimai.getShopId()); if(CollectionUtils.isNotEmpty(memberIds)){ memberId = memberIds.get(0); }else{ Member member = iMemberService.findOne(shopWaimai.getMerchantId()); memberId = member.getId(); } MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id",memberId)); // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN_SG.getType()); // ShopWaimai shopWaimai = iShopWaimaiService.findById(shop.getId(), waimai.getId()); if (config != null && StatusEnum.SHOW.status.equals(config.getOpenAutoorder())) { ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo(); confirmOrderVo.setLbClient(WaimaiTypeEnums.MEI_TUAN_SG.getName()); confirmOrderVo.setOrderId(orderVo.getOrderId()); confirmOrderVo.setAppAuthToken(shopWaimai.getAuthToken()); ResObject resObject = meituanSgClient.confirmOrder(confirmOrderVo); log.info("=======美团闪购订单确认结果=====" + JsonMapper.nonEmptyMapper().toJson(resObject)); } } @Override @Async public void doCancelOrder(MeituanOrderCancelResultVo orderCancelVo) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderCancelVo.getOrderId())); if (waimaiOrder != null) { String title = "您有一个外卖订单被顾客取消,请及时查看"; String content = "您有一个外卖订单被顾客取消,请及时查看"; redisCache.redisTemplate.opsForValue().set(orderCancelVo.getOrderId()+ "_lock", "1", 60, TimeUnit.MINUTES); messagePushService.userCancelOrderMessage(waimaiOrder.getShopId(), title, content, waimaiOrder.getId()); log.info("------->取消订单" + orderCancelVo.getOrderId()); cancelOrder(waimaiOrder); try { String json = redisCache.redisTemplate.opsForValue().get("mt-order:"+orderCancelVo.getOrderId()) + ""; if (StringUtils.isNotBlank(json)){ MeituanOrderResultVo meiTuanOrderResultVo = JSONObject.parseObject(json, MeituanOrderResultVo.class); PrintOrderDto printOrderDto = MeiTuanConvertPrint.convert(meiTuanOrderResultVo); printOrderDto.setOrderStatus(OrderStatusEnum.CANCEL.status); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, waimaiOrder.getShopId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印异常!", e); } } } @Override @Async public void sgDoCancelOrder(MeituanSgOrderCancelResultVo orderCancelVo) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderCancelVo.getOrderId())); if (waimaiOrder != null) { String title = "您有一个外卖订单被顾客取消,请及时查看"; String content = "您有一个外卖订单被顾客取消,请及时查看"; redisCache.redisTemplate.opsForValue().set(orderCancelVo.getOrderId()+ "_lock", "1", 60, TimeUnit.MINUTES); messagePushService.userCancelOrderMessage(waimaiOrder.getShopId(), title, content,waimaiOrder.getId()); log.info("------->闪购取消订单" + orderCancelVo.getOrderId()); cancelOrder(waimaiOrder); try { String json = redisCache.redisTemplate.opsForValue().get("mtsg-order:"+orderCancelVo.getOrderId()) + ""; if (StringUtils.isNotBlank(json)){ MeituanSgOrderResultVo vo = JSONObject.parseObject(json, MeituanSgOrderResultVo.class); PrintOrderDto printOrderDto = MeiTuanSgConvertPrint.convert(vo); printOrderDto.setOrderStatus(OrderStatusEnum.CANCEL.status); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, waimaiOrder.getShopId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印异常!", e); } } } // @Override @Async @Transactional public void doConfirmOrder(MeituanOrderResultVo orderVo) { // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", orderVo.getEPoiId())); DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN.getType()); ShopWaimai shopWaimai =iShopWaimaiService.getOne(new QueryWrapper().eq("epoid", orderVo.getEPoiId()) .eq("deleted",IsDeleteEnum.NORMAL.status) .eq("waimai_id",waimai.getId()) .eq("bind_status",BindStatusEnum.BIND.status)); Shop shop = iShopService.getById(shopWaimai.getShopId()); WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderVo.getOrderId())); if (waimaiOrder == null) { waimaiOrder = new WaimaiOrder(); BeanUtils.copyProperties(orderVo, waimaiOrder); ResObject res = meituanClient.getRealRecipientAddress(shopWaimai.getAuthToken(),orderVo.getOrderId()); String recipientAddress = orderVo.getRecipientAddress(); if(res.getCode()==0){ recipientAddress = res.getData(); } String recipientAddressDesensitization = orderVo.getRecipientAddressDesensitization(); if (recipientAddress.contains("@#")) { recipientAddress = recipientAddress.substring(0,recipientAddress.indexOf("@#")); } waimaiOrder.setRecipientAddress(recipientAddress); waimaiOrder.setRecipientAddressDesensitization(recipientAddressDesensitization); waimaiOrder.setLogisticsCode(orderVo.getLogisticsCode()); String remark = orderVo.getCaution(); if(StringUtils.isNotBlank(remark)&&remark.contains("[预")){ remark = remark.substring(remark.indexOf("[预"),remark.indexOf("[预")+8)+"****"+remark.substring(remark.indexOf("[预")+12,remark.length()); } waimaiOrder.setCaution(remark); // Map map = AddressLngLatExchanger.addressToLngAndLag(recipientAddress); // // if (map != null) { // waimaiOrder.setReceiptLat(map.get("lat") + ""); // waimaiOrder.setReceiptLng(map.get("lng") + ""); // } // todo: 美团收货人隐私号 waimaiOrder.setReceiptPrivacyPhone(null); waimaiOrder.setReceiptLat(orderVo.getLatitude().toString()); waimaiOrder.setReceiptLng(orderVo.getLongitude().toString()); waimaiOrder.setExtras(JSONObject.toJSONString(orderVo.getExtras())); waimaiOrder.setStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); waimaiOrder.setShopId(shop.getId()); waimaiOrder.setWaimaiId(waimai.getId()); waimaiOrder.setOrderidView(orderVo.getOrderIdView()); waimaiOrder.setOutOrderId(orderVo.getOrderId()); waimaiOrder.setOrderType(WaimaiOrderTypeEnum.MEI_TUAN.getType()); waimaiOrder.setTotalPrice(orderVo.getTotal()); waimaiOrder.setCreateTime(new Date()); long createTime = orderVo.getCtime() * 1000L; waimaiOrder.setOrderTime(new Date(createTime)); BigDecimal boxFee = BigDecimal.ZERO; if (CollectionUtils.isNotEmpty(orderVo.getDetail())) { for (OrderDetailVo vo : orderVo.getDetail()) { boxFee = vo.getBoxPrice().multiply(new BigDecimal(vo.getBoxNum())); } } waimaiOrder.setBoxFee(boxFee); waimaiOrder.setThirdShopId(shopWaimai.getThirdShopId()); iWaimaiOrderService.save(waimaiOrder); //消息推送 // messagePushService.waimaiMessage(shop.getId(), waimaiOrder); //记录商品详情 List detailList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(orderVo.getDetail())) { for (OrderDetailVo vo : orderVo.getDetail()) { WaimaiOrderDetail detail = new WaimaiOrderDetail(); BeanUtils.copyProperties(vo, detail); if(vo.getActualPrice()!=null){ detail.setPrice(vo.getActualPrice()); } detail.setQuantity(Long.valueOf(vo.getQuantity())); detail.setWaimaiOrderId(waimaiOrder.getId()); detail.setSkuId(vo.getMtSpuId()+""); detailList.add(detail); //iWaimaiOrderDetailService.save(detail); } iWaimaiOrderDetailService.saveBatch(detailList); } //自动打印外卖单 redisCache.redisTemplate.opsForValue().set("mt-order:"+orderVo.getOrderId() + "", JSONObject.toJSONString(orderVo),2,TimeUnit.DAYS); try { // redisCache.setNumber(shop.getId(),Integer.parseInt(orderVo.getDaySeq())); // autoPrintWaimai(waimaiOrder, detailList); PrintOrderDto printOrderDto = MeiTuanConvertPrint.convert(orderVo); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, shop.getId(),waimaiOrder); } catch (Exception e) { log.error("自动打印异常!", e); } try { //推送外卖新消息 messagePushService.waimaiMessage(shop.getId(), waimaiOrder); } catch (Exception e) { log.error("推送外卖订单消息异常,订单号:" + waimaiOrder.getOutOrderId()); } //产生配送订单 addOrder(shop, waimaiOrder,waimai,SnCodeUtils.createSn()); } } @SneakyThrows @Override @Async @Transactional public void sgConfirmOrder(MeituanSgOrderResultVo orderVo) { DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN_SG.getType()); ShopWaimai shopWaimai =iShopWaimaiService.getOne(new QueryWrapper() .eq("epoid", orderVo.getAppPoiCode()) .eq("deleted",IsDeleteEnum.NORMAL.status) .eq("waimai_id",waimai.getId()) .eq("bind_status",BindStatusEnum.BIND.status)); Shop shop = iShopService.getById(shopWaimai.getShopId()); WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderVo.getOrderId())); if (waimaiOrder == null) { waimaiOrder = new WaimaiOrder(); BeanUtils.copyProperties(orderVo, waimaiOrder); String recipientAddress = URLDecoder.decode(orderVo.getRecipientAddress(), "utf-8"); // String recipientAddressDesensitization = orderVo.getRecipientAddressDesensitization(); if (recipientAddress.contains("@#")) { recipientAddress = recipientAddress.substring(0,recipientAddress.indexOf("@#")); waimaiOrder.setRecipientAddress(recipientAddress); } waimaiOrder.setRecipientAddressDesensitization(recipientAddress); waimaiOrder.setLogisticsCode(orderVo.getLogisticsCode()); String remark = URLDecoder.decode(orderVo.getCaution(), "utf-8"); if(StringUtils.isNotBlank(remark)&&remark.contains("[预")){ remark = remark.substring(remark.indexOf("[预"),remark.indexOf("[预")+8)+"****"+remark.substring(remark.indexOf("[预")+12,remark.length()); } waimaiOrder.setCaution(remark); // Map map = AddressLngLatExchanger.addressToLngAndLag(recipientAddress); // // if (map != null) { // waimaiOrder.setReceiptLat(map.get("lat") + ""); // waimaiOrder.setReceiptLng(map.get("lng") + ""); // } // todo: 美团收货人隐私号 waimaiOrder.setWaimaiId(waimai.getId()); waimaiOrder.setShopId(shop.getId()); waimaiOrder.setCityId(orderVo.getCityId()); waimaiOrder.setOutOrderId(orderVo.getOrderId()); waimaiOrder.setOrderidView(orderVo.getWmOrderIdView()); long createTime = orderVo.getCtime() * 1000L; waimaiOrder.setOrderTime(new Date(createTime)); orderVo.setRecipientName(URLDecoder.decode(orderVo.getRecipientName(), "utf-8")); waimaiOrder.setRecipientName(orderVo.getRecipientName()); waimaiOrder.setDaySeq(orderVo.getDaySeq().toString()); orderVo.setDetail(URLDecoder.decode(orderVo.getDetail(), "utf-8")); waimaiOrder.setDetail(orderVo.getDetail()); orderVo.setExtras(URLDecoder.decode(orderVo.getExtras(), "utf-8")); waimaiOrder.setExtras(orderVo.getExtras()); waimaiOrder.setIsThirdShipping(orderVo.getIsThirdShipping()); waimaiOrder.setReceiptLat(orderVo.getLatitude().toString()); waimaiOrder.setReceiptLng(orderVo.getLongitude().toString()); orderVo.setWmPoiAddress(URLDecoder.decode(orderVo.getWmPoiAddress(), "utf-8")); waimaiOrder.setPoiAddress(orderVo.getWmPoiAddress()); orderVo.setWmPoiName(URLDecoder.decode(orderVo.getWmPoiName(), "utf-8")); waimaiOrder.setPoiName(orderVo.getWmPoiName()); waimaiOrder.setPoiPhone(orderVo.getWmPoiPhone()); waimaiOrder.setPoiReceiveDetail(null); waimaiOrder.setReceiptPrivacyPhone(null); waimaiOrder.setStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); waimaiOrder.setOrderType(WaimaiOrderTypeEnum.MEI_TUAN_SG.getType()); waimaiOrder.setTotalPrice(orderVo.getTotal()); waimaiOrder.setCreateTime(new Date()); BigDecimal boxFee = BigDecimal.ZERO; if (CollectionUtils.isNotEmpty(orderVo.getDetailList())) { for (SgOrderDetailVo vo : orderVo.getDetailList()) { boxFee = vo.getBoxPrice().multiply(vo.getBoxNum()); } } waimaiOrder.setBoxFee(boxFee); waimaiOrder.setThirdShopId(shopWaimai.getThirdShopId()); iWaimaiOrderService.save(waimaiOrder); //消息推送 // messagePushService.waimaiMessage(shop.getId(), waimaiOrder); //记录商品详情 List detailList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(orderVo.getDetailList())) { for (SgOrderDetailVo vo : orderVo.getDetailList()) { WaimaiOrderDetail detail = new WaimaiOrderDetail(); BeanUtils.copyProperties(vo, detail); detail.setQuantity(Long.valueOf(vo.getQuantity())); detail.setWaimaiOrderId(waimaiOrder.getId()); detail.setBoxNum(vo.getBoxNum().toString()); detailList.add(detail); //iWaimaiOrderDetailService.save(detail); } iWaimaiOrderDetailService.saveBatch(detailList); } //自动打印外卖单 redisCache.redisTemplate.opsForValue().set("mtsg-order:"+orderVo.getOrderId() + "", JSONObject.toJSONString(orderVo),2,TimeUnit.DAYS); try { // redisCache.setNumber(shop.getId(),Integer.parseInt(orderVo.getDaySeq())); // autoPrintWaimai(waimaiOrder, detailList); PrintOrderDto printOrderDto = MeiTuanSgConvertPrint.convert(orderVo); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, shop.getId(),waimaiOrder); } catch (Exception e) { log.error("自动打印异常!", e); } try { //推送外卖新消息 messagePushService.waimaiMessage(shop.getId(), waimaiOrder); } catch (Exception e) { log.error("推送外卖订单消息异常,订单号:" + waimaiOrder.getOutOrderId()); } //产生配送订单 addOrder(shop, waimaiOrder,waimai,SnCodeUtils.createSn()); } } @Override @Transactional public void addOrder(Shop shop, WaimaiOrder waimaiOrder,DspWaimai waimai,String orderSn) { // Order order = iOrderService.getOne(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId()).ne("delivery_status",DeliveryStatusEnum.CANCEL.status)); Order order = iOrderService.getOne(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId()).eq("deleted",0)); // Member member = iMemberService.findOne(shop.getMerchantId()); Member member = new Member(); List memberList = iMemberService.list(new QueryWrapper().eq("shop_id", shop.getId()).eq("status", StatusEnum.SHOW.status).eq("deleted", 0)); if (CollectionUtils.isNotEmpty(memberList)) { member = memberList.get(0); } else { member = iMemberService.findOne(shop.getMerchantId()); } if (order == null) { order = new Order(); if (waimaiOrder.getDeliveryTime().intValue() == 0) { order.setTakeTime(DateUtils.getNowDate()); order.setTakeType(TakeTypeEnum.NOW.type); } else { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //预计送达时间 减一小时 转换预计取件时间 order.setTakeTime( DateUtils.addHours(new Date(Long.valueOf(waimaiOrder.getDeliveryTime() + "000")),-1)); order.setTakeType(TakeTypeEnum.APPOINTMENT.type); } order.setSendLng(shop.getLng()); order.setSendLat(shop.getLat()); order.setPaymentType(PaymentTypeEnum.BALANCE.type); order.setOrderSn(orderSn); order.setDeliveryStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); order.setStatus(OrderStatusEnum.NO_PAYED.status); if (waimaiOrder.getStatus() != null && waimaiOrder.getStatus().equals(DeliveryStatusEnum.CANCEL.status)){ order.setDeliveryStatus(DeliveryStatusEnum.CANCEL.status); order.setCancelReason("用户取消"); order.setStatus(DeliveryStatusEnum.CANCEL.status); } order.setMemberId(member.getId()); order.setReceiptAddress(waimaiOrder.getRecipientAddress()); order.setReceiptContactName(waimaiOrder.getRecipientName()); order.setReceiptPhone(waimaiOrder.getRecipientPhone()); order.setReceiptPrivacyPhone(waimaiOrder.getReceiptPrivacyPhone()); order.setReceiptLng(waimaiOrder.getReceiptLng()); order.setReceiptLat(waimaiOrder.getReceiptLat()); order.setReceiptCityName(shop.getCityName()); order.setReceiptCityCode(shop.getCityCode()); order.setReceiptDistrictName(shop.getDistrictName()); // if (shop.getStreet() != null) { // order.setSendStreet(shop.getStreet()); // } if (shop.getStreet() != null) { order.setSendStreet(shop.getStreet()); order.setSendAddress(shop.getAddress() + shop.getStreet()); } else { order.setSendAddress(shop.getAddress()); } order.setSendCityName(shop.getCityName()); order.setSendContactName(shop.getContactName()); order.setSendDistrictName(shop.getDistrictName()); order.setSendPhone(shop.getMobile()); order.setSendProvinceName(shop.getProvinceName()); order.setSendCityCode(shop.getCityCode()); order.setSendLat(shop.getLat()); order.setSendLng(shop.getLng()); order.setShopName(shop.getName()); order.setWaimaiOrderId(waimaiOrder.getId()); order.setShopId(waimaiOrder.getShopId()); order.setMerchantId(shop.getMerchantId()); order.setProductId(shop.getCategoryId()); MerchantCategory category = iMerchantCategoryService.getById(shop.getCategoryId()); if (category != null) { order.setProductName(category.getName()); } else { order.setProductName("其他"); } order.setWeight(1); order.setDeleted(0); Member member1 = iMemberService.findOne(shop.getMerchantId()); if (member1.getAgentId() != null) { order.setAgentId(member1.getAgentId()); order.setAgentIdSource(member1.getAgentSource()); if (member1.getPersonnelId() != null){ order.setPersonnelId(member1.getPersonnelId()); } } else { // 判断区域,只给一级代理商 Agent agent = iAgentService.findByArea(order.getSendCityName(), order.getSendDistrictName()); if (agent != null) { order.setAgentId(agent.getId()); order.setAgentIdSource(AgentSourceEnum.QU_YU.status); } } iOrderService.save(order); //新订单轮询用 OrderDetailDto dto = new OrderDetailDto(); BeanUtils.copyProperties(order,dto); dto.setCaution(waimaiOrder.getCaution()); dto.setOutOrderId(waimaiOrder.getOutOrderId()); dto.setDaySeq(waimaiOrder.getDaySeq()); dto.setOrderType(waimaiOrder.getOrderType()); dto.setUpdateTime(new Date()); dto.setWaimaiLogo(waimai.getLogo()); dto.setExceptTime(waimaiOrder.getDeliveryTime()); dto.setOrderTime(waimaiOrder.getOrderTime()); redisCache.redisTemplate.opsForList().leftPush("shop"+shop.getId() + "", dto); redisCache.redisTemplate.expire("shop"+shop.getId(),30,TimeUnit.MINUTES); redisCache.redisTemplate.opsForList().leftPush("merchant"+shop.getMerchantId() + "", dto); redisCache.redisTemplate.expire("merchant"+shop.getMerchantId(),30,TimeUnit.MINUTES); // Product product = apiProductService.findById(order.getProductId().intValue()); // order.setProduct(product); } if (StringUtils.isNotBlank(waimaiOrder.getTakeRemark())){ order.setTakeRemark(waimaiOrder.getTakeRemark()); } Merchant merchant = iMerchantService.getById(shop.getMerchantId()); if (merchant != null && merchant.getDadaDspId() != null) { DadaDsp dadaDsp = iDadaDspService.getById(merchant.getDadaDspId()); if (dadaDsp != null) { order.setDadaDspId(dadaDsp.getId()); order.setDadaDspType(DadaDspRoleEnum.SELF_DELIVERY.type.equals(dadaDsp.getDspRole()) ? OrderDadaDspTypeEnum.DELIVERY.type : OrderDadaDspTypeEnum.DELIVERY_RAP.type); } } MemberConfig config = iMemberConfigService.getShopMemberConfig(shop.getId(), null); // 非自动拉取、非撤回的预约单, 设置预约单提前发单时间快照 if (waimaiOrder.getAutoOrder() == null && order.getTakeType() > 0 && config != null && StatusEnum.SHOW.status.equals(config.getOpenBookingAutodelivery()) && config.getBookingAutodeliveryOrderTime() != null) { order.setAutoDeliveryMinutes(config.getBookingAutodeliveryOrderTime() / 60); } iOrderService.updateById(order); log.info("自动配送外卖信息==="+JSONObject.toJSONString(waimaiOrder)); if (waimaiOrder.getAutoOrder() == null) { // 自动配送,并且是非自动拉取的订单, 非撤回订单 log.info("自动配送用户信息==="+JSONObject.toJSONString(config)); // 即时单发单配置 if (config != null && order.getTakeType() == 0) { if (StatusEnum.SHOW.status.equals(config.getOpenAutodelivery())) { final Long deliver = config.getAutodeliveryOrderTime(); log.info("立即单,订单号 {}触发自动配送, 预计{} 秒后发起" + order.getOrderSn(), deliver); try { autoDelivery(order, config, deliver); } catch (Exception e) { log.error("自动配送异常", e); } } } // 预约单发单配置 if (config != null && order.getTakeType() > 0) { if (StatusEnum.SHOW.status.equals(config.getOpenBookingAutodelivery())) { long diff = waimaiOrder.getDeliveryTime() - config.getBookingAutodeliveryOrderTime(); final Long deliver = diff - (new Date().getTime() / 1000); log.info("预约单,订单号 {}触发自动配送, 预计{} 秒后发起", order.getOrderSn(), deliver); try { autoDelivery(order, config, deliver); } catch (Exception e) { log.error("自动配送异常", e); } } } } } public void autoDelivery(final Order order, MemberConfig config, Long deliver) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { scheduledExecutorService.schedule(new TriggerProcessTask(order, config.getAutodeliveryIds(), applicationContext), deliver, TimeUnit.SECONDS); } }); } // @Override // @Transactional(rollbackFor = Exception.class) // public void doOAuth(ElemeMerchantResultVo resultVo) { // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME.getType()); // if (waimai != null) { // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", resultVo.getState())); // //先解除其他绑定 // iShopWaimaiService.updateStatus(String.valueOf(resultVo.getShopList().get(0).getId())); // ShopWaimai shopWaimai = new ShopWaimai(); // shopWaimai.setWaimaiId(waimai.getId()); // shopWaimai.setShopId(shop.getId()); // shopWaimai.setMerchantId(shop.getMerchantId()); // shopWaimai.setThirdShopId(String.valueOf(resultVo.getShopList().get(0).getId())); // shopWaimai.setThirdShopName(resultVo.getShopList().get(0).getName()); // shopWaimai.setAuthToken(resultVo.getToken().getAccessToken()); // shopWaimai.setBindStatus(BindStatusEnum.BIND.status); // shopWaimai.setExpiresIn(resultVo.getToken().getExpiresIn()); // shopWaimai.setRefreshToken(resultVo.getToken().getRefreshToken()); // iShopWaimaiService.save(shopWaimai); // // 拉取当天订单 //// getEleOrders(shopWaimai.getAuthToken(),Long.valueOf(shopWaimai.getThirdShopId()),DateUtils.parseDateToStr("yyyy-MM-dd",new Date())); // } // } public void getEleOrders(String token,Long shopId,String date){ Integer i = 1; Integer pageNo = 1; Integer pages = 0; Integer pageSize = 50; while (i>0){ ResObject resObject = elemeClient.getAllOrders(token,shopId,pageNo,pageSize,date); if (resObject.getCode() == 0){ OrderList listList = resObject.getData(); List oOrders = listList.getList(); // 保存数据 for (OOrder o : oOrders){ ElemeOrderResultVo v = new ElemeOrderResultVo(); BeanUtils.copyProperties(o,v); if (!v.getStatus().name().equals("valid") && !v.getStatus().name().equals("refunding") && !v.getStatus().name().equals("settled")){ return; } ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", String.valueOf(v.getShopId())).eq("deleted", IsDeleteEnum.NORMAL.status)); Shop shop = iShopService.getById(shopWaimai.getShopId()); DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME.getType()); WaimaiOrder waimaiOrder = createWaimaiOrder(v,shop, waimai.getId()); waimaiOrder.setAutoOrder(1); if (v.getStatus().name().equals("settled")){ waimaiOrder.setStatus(DeliveryStatusEnum.FINISH.status); iWaimaiOrderService.updateById(waimaiOrder); } if (v.getStatus().name().equals("refunding")){ waimaiOrder.setStatus(DeliveryStatusEnum.CANCEL.status); iWaimaiOrderService.updateById(waimaiOrder); } addOrder(shop, waimaiOrder,waimai,SnCodeUtils.createSn()); } Integer total = listList.getTotal(); if (total <= oOrders.size()){ i = 0; } if (total > oOrders.size() && pageNo == 1){ // 还需要拉取的次数 pages = (total - oOrders.size())/pageSize; Integer a = (total - oOrders.size())%pageSize; if (a > 0){ pages = pages +1 ; } i = pages; } if (pageNo > 1 && pages>0){ i--; } pageNo++; }else { log.info("拉取饿了么订单失败==="+resObject.getMsg()); i = 0; } } } /** * 饿了么新订单处理 */ @Override @Transactional @Async public void doElmNewOrder(ElemeOrderResultVo orderVo) { // log.info("=====饿了么新订单参数====" + JsonMapper.nonEmptyMapper().toJson(orderVo)); // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME.getType()); ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", String.valueOf(orderVo.getShopId())).eq("deleted", IsDeleteEnum.NORMAL.status)); if (shopWaimai != null) { Shop shop = iShopService.getById(shopWaimai.getShopId()); Long memberId = null; List memberIds = iMemberService.selectByShopId(shop.getId()); if(CollectionUtils.isNotEmpty(memberIds)){ memberId = memberIds.get(0); }else{ Member member = iMemberService.findOne(shop.getMerchantId()); memberId = member.getId(); } MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id",memberId)); //产生外卖订单 // WaimaiOrder waimaiOrder = createWaimaiOrder(orderVo, shop, waimai.getId()); redisCache.redisTemplate.opsForValue().set("ele-order:"+orderVo.getId() + "", JSONObject.toJSONString(orderVo),2,TimeUnit.DAYS); WaimaiOrder waimaiOrder = new WaimaiOrder(); waimaiOrder.setOutOrderId(orderVo.getId()); waimaiOrder.setTotalPrice(new BigDecimal(orderVo.getTotalPrice() + "")); // messagePushService.waimaiMessage(shop.getId(), waimaiOrder); if (config!=null&&StatusEnum.SHOW.status.equals(config.getOpenAutoorder())) { ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo(); confirmOrderVo.setLbClient(WaimaiTypeEnums.E_LE_ME.getName()); confirmOrderVo.setOrderId(orderVo.getId()); confirmOrderVo.setAppAuthToken(shopWaimai.getAuthToken()); ResObject resObject = elemeClient.confirmOrder(confirmOrderVo); log.info("=======饿了么订单确认结果=====" + JsonMapper.nonEmptyMapper().toJson(resObject)); } } } @Override public WaimaiOrder createWaimaiOrder(ElemeOrderResultVo orderVo, Shop shop, Long waimaiId) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderVo.getId()).eq("deleted",0)); if (waimaiOrder == null) { waimaiOrder = new WaimaiOrder(); waimaiOrder.setShopId(shop.getId()); waimaiOrder.setWaimaiId(waimaiId); // waimaiOrder.setOrderidView(String.valueOf(orderVo.getPickUpNumber())); waimaiOrder.setOrderidView(orderVo.getId()); waimaiOrder.setOutOrderId(orderVo.getId()); UserExtraInfo userExtraInfo = orderVo.getUserExtraInfo(); waimaiOrder.setCaution(orderVo.getDescription()); if(userExtraInfo!=null&&StringUtils.isNotBlank(userExtraInfo.getGreeting())){ waimaiOrder.setCaution("[祝福语]:"+userExtraInfo.getGreeting()+orderVo.getDescription()); } waimaiOrder.setOrderTime(orderVo.getCreatedAt()); waimaiOrder.setDaySeq(String.valueOf(orderVo.getDaySn())); waimaiOrder.setInvoiceTitle(orderVo.getInvoice()); waimaiOrder.setTaxpayerId(orderVo.getTaxpayerId()); waimaiOrder.setHasInvoiced(orderVo.getInvoiced() ? 1 : 0); waimaiOrder.setIsThirdShipping(1); waimaiOrder.setOriginalPrice(new BigDecimal(orderVo.getTotalPrice())); waimaiOrder.setPayType(orderVo.getOnlinePaid() ? 1 : 0); waimaiOrder.setPoiAddress(shop.getAddress()); waimaiOrder.setPoiName(shop.getName()); waimaiOrder.setOrderType(WaimaiOrderTypeEnum.E_LE_ME.getType()); waimaiOrder.setPoiPhone(shop.getMobile()); waimaiOrder.setRecipientAddress(orderVo.getDeliveryPoiAddress()); waimaiOrder.setRecipientName(orderVo.getConsignee()); String phone = orderVo.getPhoneList().get(0); phone = phone.replace(",", "_"); waimaiOrder.setRecipientPhone(phone); waimaiOrder.setReceiptPrivacyPhone(CollectionUtils.isEmpty(orderVo.getConsigneePhones()) ? null : orderVo.getConsigneePhones().get(0)); waimaiOrder.setReceiptLat(orderVo.getDeliveryGeo().split(",")[1]); waimaiOrder.setReceiptLng(orderVo.getDeliveryGeo().split(",")[0]); waimaiOrder.setTotalPrice(new BigDecimal(orderVo.getTotalPrice() + "")); waimaiOrder.setExtras(JSONObject.toJSONString(orderVo.getOrderActivities())); waimaiOrder.setBoxFee(new BigDecimal(orderVo.getPackageFee() + "")); if (orderVo.getBook()) { waimaiOrder.setDeliveryTime(orderVo.getDeliverTime().getTime() / 1000); } else { waimaiOrder.setDeliveryTime(0l); } waimaiOrder.setThirdShopId(orderVo.getShopId()+""); iWaimaiOrderService.save(waimaiOrder); //记录商品详情 List detailList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(orderVo.getGroups())) { List items = orderVo.getGroups().get(0).getItems(); for (OGoodsItem item : items) { WaimaiOrderDetail detail = new WaimaiOrderDetail(); // List specs = item.getNewSpecs(); // List attributeList = item.getAttributes(); // if(CollectionUtils.isNotEmpty(specs)){ // StringBuilder sb = new StringBuilder(); // for(OGroupItemSpec spec:specs){ // sb.append(spec.getValue()).append(","); // } // if(sb.length()>0){ // detail.setSpec(sb.toString().substring(0,sb.length()-1)); // } // } // if(CollectionUtils.isNotEmpty(attributeList)){ // StringBuilder sb = new StringBuilder(); // for(OGroupItemAttribute attr:attributeList){ // sb.append(attr.getValue()).append(","); // } // if(sb.length()>0){ // detail.setFoodProperty(sb.toString().substring(0,sb.length()-1)); // } // // } detail.setWaimaiOrderId(waimaiOrder.getId()); detail.setSkuId(item.getId() + ""); detail.setFoodName(item.getName()); detail.setPrice(new BigDecimal(item.getPrice())); detail.setQuantity((long) item.getQuantity()); detail.setUnit(item.getWeight().toString()); detailList.add(detail); // iWaimaiOrderDetailService.save(detail); } iWaimaiOrderDetailService.saveBatch(detailList); } } return waimaiOrder; } @Override @Transactional @Async public void doStateNewOrder(ElemeOrderStateResultVo orderVo, Integer type) { String json = redisCache.redisTemplate.opsForValue().get("ele-order:"+orderVo.getOrderId()) + ""; ElemeOrderResultVo elemeOrderResultVo = JSONObject.parseObject(json, ElemeOrderResultVo.class); DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME.getType()); ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", String.valueOf(orderVo.getShopId())).eq("deleted", IsDeleteEnum.NORMAL.status)); if (shopWaimai != null) { Shop shop = iShopService.getById(shopWaimai.getShopId()); WaimaiOrder waimaiOrder = createWaimaiOrder(elemeOrderResultVo, shop, waimai.getId()); // WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderVo.getOrderId())); if (waimaiOrder != null) { // Shop shop = iShopService.getById(waimaiOrder.getShopId()); //自动打印外卖单 //List detailList = iWaimaiOrderDetailService.findList(waimaiOrder.getId()); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); try { if (type.intValue() == 12) { // redisCache.setNumber(shop.getId(),elemeOrderResultVo.getDaySn()); // autoPrintWaimai(waimaiOrder, detailList); PrintOrderDto printOrderDto = EleConvertPrint.convert(elemeOrderResultVo); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, shop.getId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印异常!", e); } try { //推送外卖新消息 if (type.intValue() == 12) { messagePushService.waimaiMessage(shop.getId(), waimaiOrder); } } catch (Exception e) { log.error("推送外卖订单消息异常,订单号:" + waimaiOrder.getOutOrderId()); } //产生配送订单 if (type.intValue() == 12) { addOrder(shop, waimaiOrder,waimai,SnCodeUtils.createSn()); } if (type.intValue() == 14 || type.intValue() == 15 || type.intValue() == 17) { doEleCancelOrder(orderVo.getOrderId(), type); } } } } @Override @Async public void doEleCancelOrder(String orderId, int type) { if (type == 14 || type == 17 || type == 23) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderId)); if (waimaiOrder != null) { //用户取消取消订单 String title = "您有一个外卖订单被顾客取消,请及时查看"; String content = "您有一个外卖订单被顾客取消,请及时查看"; log.info("------->取消订单" + orderId); cancelOrder(waimaiOrder); if (type == 23 || type == 17) { redisCache.redisTemplate.opsForValue().set(orderId+ "_lock", "1", 60, TimeUnit.MINUTES); messagePushService.userCancelOrderMessage(waimaiOrder.getShopId(), title, content, waimaiOrder.getId()); // 打印取消订单 try { String json = redisCache.redisTemplate.opsForValue().get("ele-order:"+orderId) + ""; if (StringUtils.isNotBlank(json)){ ElemeOrderResultVo elemeOrderResultVo = JSONObject.parseObject(json, ElemeOrderResultVo.class); PrintOrderDto printOrderDto = EleConvertPrint.convert(elemeOrderResultVo); printOrderDto.setOrderStatus(OrderStatusEnum.CANCEL.status); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, waimaiOrder.getShopId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印取消订单异常!", e); } } } } } // @Override // public void saveShop(ElemeRetailMerchantResultVo shopMappingVo) { // log.info("饿百绑定门店回调"); // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME_RETAIL.getType()); // if (waimai != null) { // for (BindShop bindShop : shopMappingVo.getShopList()) { // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", bindShop.getShopId())); // if (shop == null) { // log.error("门店未找到,门店code" + bindShop.getShopId()); // return; // } // //先解除其他绑定 // ShopWaimai waimai1 = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", bindShop.getBaiduShopId()).eq("bind_status", BindStatusEnum.BIND.status).eq("shop_id", bindShop.getShopId()).eq("deleted", 0)); // if (waimai1 != null) { // return; // } // ShopWaimai shopWaimai = new ShopWaimai(); // shopWaimai.setWaimaiId(waimai.getId()); // shopWaimai.setShopId(shop.getId()); // shopWaimai.setMerchantId(shop.getMerchantId()); // shopWaimai.setThirdShopId(String.valueOf(bindShop.getBaiduShopId())); // shopWaimai.setThirdShopName(bindShop.getName()); // //shopWaimai.setAuthToken(resultVo.getToken().getAccessToken()); // shopWaimai.setBindStatus(BindStatusEnum.BIND.status); //// shopWaimai.setExpiresIn(bindShop.getExpiresIn()); //// shopWaimai.setRefreshToken(bindShop.getRefreshToken()); // iShopWaimaiService.save(shopWaimai); // // 拉取当天订单 //// log.info("拉取数据"); //// pullOrders(String.valueOf(bindShop.getBaiduShopId())); // } // } // } public void pullOrders(String thirdShopId){ log.info("开始拉取数据"); Integer i = 1; Integer pageNo = 1; Integer pages = 0; Integer pageSize = 100; long startTime = (com.ydd.third.common.utils.DateUtils.getAutoTime(new Date(),0,0,0))/1000; long endTime = System.currentTimeMillis()/1000; while (i>0){ ResObject resObject = eleRetaiClient.getOrderList(thirdShopId,pageNo,pageSize,String.valueOf(startTime),String.valueOf(endTime),""); OrderEBaiList listList = resObject.getData(); List oOrders = listList.getList(); // 保存数据 for (OrderEBaiInfo o : oOrders){ // 待确认订单不要 if (o.getOrder_status().equals("1")){ continue; } // 查询订单详情 OrderGetResult orderGetResult = eleRetaiClient.getOrder(o.getOrder_id()); if (orderGetResult.getData().getOrder().getDown_flag() == 1) { orderGetResult = eleRetaiClient.getOrder(o.getOrder_id()); } if (o.getOrder_status().equals("9")){ orderGetResult.setOrderStatus(DeliveryStatusEnum.FINISH.status); } if (o.getOrder_status().equals("10") || o.getOrder_status().equals("15")){ orderGetResult.setOrderStatus(DeliveryStatusEnum.CANCEL.status); } orderGetResult.setAutoOrder(1); redisCache.redisTemplate.opsForValue().set("ebai.order:"+o.getOrder_id() + "", SnCodeUtils.createSn(),30,TimeUnit.MINUTES); String orderId = createOrder(orderGetResult); } Integer total = listList.getTotal(); if (total <= oOrders.size()){ i = 0; } if (total > oOrders.size() && pageNo == 1){ // 还需要拉取的次数 pages = (total - oOrders.size())/pageSize; Integer a = (total - oOrders.size())%pageSize; if (a > 0){ pages = pages +1 ; } i = pages; } if (pageNo > 1 && pages>0){ i--; } pageNo++; } } // @Override // public void updateShop(ElemeRetailMerchantResultVo shopMappingVo) { // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME_RETAIL.getType()); // if (waimai != null) { // for (BindShop bindShop : shopMappingVo.getShopList()) { // // Shop shop = iShopService.getOne(new QueryWrapper().eq("code", bindShop.getShopId())); // //先解除其他绑定 // iShopWaimaiService.updateStatus(String.valueOf(bindShop.getBaiduShopId())); // } // } // } @Override @Transactional public void updateOrderStatus(JSONObject jsonObject) { String orderId = jsonObject.getString("order_id"); // WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderId)); // Order order = iOrderService.getOne(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); //1、待确认;5、订单已确认; 7、骑士已接单开始取餐(此时可通过订单详情接口获取骑士手机号); 8、骑士已取餐正在配送; 9、订单完成; 10、订单取消。推送地址和创建订单地址相同。 if (jsonObject.getString("status").equals("5")) { OrderGetResult result = eleRetaiClient.getOrder(orderId); String order1 = createOrder(result); // messagePushService.riderReceiveOrderMessage(order.getMemberId(), "您的订单已被骑手接单,请及时备货", "您的订单编号" + order.getOrderSn() + "已被骑手接单,配送平台:" + order.getDeliveryName() + ",请留意订单状态"); } else if ("9".equals(jsonObject.getString("status"))) { updateWaimaiOrderStatus(orderId, DeliveryStatusEnum.FINISH.status); } // else if ("10".equals(jsonObject.getString("status"))) { // updateWaimaiOrderStatus(orderId, DeliveryStatusEnum.CANCEL.status); // } } /** * 饿百新订单 * * @param orderGetResult */ @Override @Transactional public String createOrder(OrderGetResult orderGetResult) { try { //String orderSn = redisCache.redisTemplate.opsForValue().get("ebai.order:"+orderGetResult.getData().getOrder().getOrder_id() + "")+""; String shop_id = orderGetResult.getData().getShop().getBaidu_shop_id(); ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", String.valueOf(shop_id)).eq("deleted", IsDeleteEnum.NORMAL.status)); if (shopWaimai == null) { log.error("未找到饿百绑定的商户,商户id为---" + shop_id); return ""; } Shop shop = iShopService.getById(shopWaimai.getShopId()); Member member = iMemberService.findOne(shop.getMerchantId()); MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id", member.getId())); //redisCache.redisTemplate.opsForValue().set(orderGetResult.getData().getOrder().getOrder_id() + "", JSONObject.toJSONString(orderGetResult.getData().getOrder())); DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.E_LE_ME_RETAIL.getType()); WaimaiOrder order = transform(orderGetResult.getData(), waimai.getId(), shop); if (orderGetResult.getOrderStatus() != null){ if (orderGetResult.getOrderStatus().equals(DeliveryStatusEnum.FINISH.status)){ order.setStatus(DeliveryStatusEnum.FINISH.status); }else if (orderGetResult.getOrderStatus().equals(DeliveryStatusEnum.CANCEL.status)){ order.setStatus(DeliveryStatusEnum.CANCEL.status); } iWaimaiOrderService.updateById(order); } order.setAutoOrder(orderGetResult.getOrderStatus()); //推送外卖新消息 if(orderGetResult.getData().getOrder().getStatus().intValue()==5){//新订单 messagePushService.waimaiMessage(shop.getId(), order); } // Integer status = DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status; // if (config != null) { // if (config.getOpenAutoorder().equals(StatusEnum.SHOW.status)) { // boolean flat = eleRetaiClient.confirm(orderGetResult.getData().getOrder().getOrder_id()); // if (flat) { // status = DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status; // order.setStatus(OrderStatusEnum.TO_BE_DELIVERED.status); // iWaimaiOrderService.updateById(order); // } // } // } // addRetaiOrder(shop, order, status); // if(StringUtils.isBlank(orderSn)){ String orderSn = SnCodeUtils.createSn(); //} addOrder(shop, order,waimai,orderSn); return order.getId().toString(); } catch (Exception e) { log.error("饿百订单出现异常"); e.printStackTrace(); return ""; } } @Override public void doEleRetaiCancel(String orderId, int type) { if (type == 40 || type == 60) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderId)); if (waimaiOrder != null&&!redisCache.redisTemplate.hasKey(orderId+ "_lock")) { //用户取消取消订单 String title = "您有一个外卖订单被顾客取消,请及时查看"; String content = "您有一个外卖订单被顾客取消,请及时查看"; log.info("------->取消订单" + orderId); cancelOrder(waimaiOrder); redisCache.redisTemplate.opsForValue().set(orderId+ "_lock", "1", 60, TimeUnit.MINUTES); messagePushService.userCancelOrderMessage(waimaiOrder.getShopId(), title, content, waimaiOrder.getId()); try { String json = redisCache.redisTemplate.opsForValue().get("ebai.order.print:"+orderId) + ""; if (StringUtils.isNotBlank(json)){ OrderGetDataResultDataDto data = JSONObject.parseObject(json, OrderGetDataResultDataDto.class); PrintOrderDto printOrderDto = EleRetailConvertPrint.convert(data); printOrderDto.setOrderStatus(OrderStatusEnum.CANCEL.status); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList,waimaiOrder.getShopId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印异常!", e); } } } } private WaimaiOrder transform(OrderGetDataResultDataDto data, Long waimaiId, Shop shop) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", data.getOrder().getOrder_id())); if (waimaiOrder == null) { waimaiOrder = new WaimaiOrder(); DecimalFormat df = new DecimalFormat("#.00"); waimaiOrder.setShopId(shop.getId()); waimaiOrder.setWaimaiId(waimaiId); waimaiOrder.setOrderidView(data.getOrder().getEleme_order_id()); waimaiOrder.setOutOrderId(data.getOrder().getOrder_id()); String remark = "0".equals(data.getOrder().getRemark()) ? "" : data.getOrder().getRemark(); String greeting =""; if(data.getOrder().getExt()!=null){ greeting = data.getOrder().getExt().getGreeting(); if(StringUtils.isNotBlank(greeting)){ greeting ="[祝福语]"+greeting+" "; } } if(StringUtils.isNotBlank(greeting)){ remark = greeting+remark; } waimaiOrder.setCaution(remark); long createTime = Long.parseLong(data.getOrder().getCreate_time()) * 1000L; waimaiOrder.setOrderTime(new Date(createTime)); waimaiOrder.setDaySeq(String.valueOf(data.getOrder().getOrder_index())); waimaiOrder.setInvoiceTitle(data.getOrder().getInvoice_title()); waimaiOrder.setTaxpayerId(data.getOrder().getTaxer_id()); waimaiOrder.setHasInvoiced(data.getOrder().getNeed_invoice() == 1 ? 1 : 0); waimaiOrder.setIsThirdShipping(1); String format1 = df.format((double) data.getOrder().getTotal_fee() / 100); waimaiOrder.setOriginalPrice(new BigDecimal(format1)); waimaiOrder.setPayType(data.getOrder().getPay_type() == 2 ? 2 : 1); waimaiOrder.setPoiAddress(shop.getAddress()); waimaiOrder.setPoiName(shop.getName()); waimaiOrder.setOrderType(WaimaiOrderTypeEnum.E_LE_ME_RETAIL.getType()); waimaiOrder.setPoiPhone(shop.getMobile()); waimaiOrder.setRecipientAddress(data.getUser().getAddress()); waimaiOrder.setRecipientName(data.getUser().getName()); waimaiOrder.setRecipientPhone(data.getUser().getPhone()); waimaiOrder.setReceiptPrivacyPhone(data.getUser().getPrivacy_phone()); waimaiOrder.setReceiptLat(data.getUser().getCoord_amap().getLatitude().toString()); waimaiOrder.setReceiptLng(data.getUser().getCoord_amap().getLongitude().toString()); String format2 = df.format((double) data.getOrder().getUser_fee() / 100); waimaiOrder.setTotalPrice(new BigDecimal(format2)); waimaiOrder.setStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); waimaiOrder.setExtras(JSONObject.toJSONString(data.getDiscount())); waimaiOrder.setThirdShopId(data.getShop().getBaidu_shop_id()); if (data.getOrder().getSend_immediately() == 2) { waimaiOrder.setDeliveryTime(data.getOrder().getSend_time()); } else { waimaiOrder.setDeliveryTime(0L); } iWaimaiOrderService.save(waimaiOrder); //记录商品详情 List detailList = new ArrayList<>(); if (data.getProducts() != null && data.getProducts().length > 0) { OrderGetProduct[][] products = data.getProducts(); HashMap map = new HashMap<>(); for (int i = 0; i < products.length; i++) { for (int j = 0; j < products[i].length; j++) { OrderGetProduct[] product = products[i]; WaimaiOrderDetail detail = new WaimaiOrderDetail(); detail.setWaimaiOrderId(waimaiOrder.getId()); detail.setSkuId(product[j].getBaidu_product_id()); detail.setFoodName(product[j].getProduct_name()); String format = df.format((double) product[j].getProduct_price() / 100); detail.setPrice(new BigDecimal(product[j].getProduct_price() > 0 ? format : "0")); OrderGetProductFeatures[] product_features = product[j].getProduct_features(); OrderGetProductAttr[] attrs = product[j].getProduct_attr(); OrderGetProductProperties[] properties = product[j].getProperties(); if (product_features != null && product_features.length > 0) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < product_features.length; k++) { OrderGetProductFeatures features = product_features[k]; sb.append(features.getOption()).append(","); } if (sb.length() > 0) { detail.setSpec(sb.toString().substring(0, sb.length() - 1)); } } // if (attrs != null && attrs.length > 0) { // StringBuilder sb = new StringBuilder(); // for (int k = 0; k < attrs.length; k++) { // OrderGetProductAttr attr = attrs[k]; // sb.append(attr.getOption()).append(","); // } // if (sb.length() > 0) { // detail.setFoodProperty(sb.toString().substring(0, sb.length() - 1)); // } // // } if (properties != null && properties.length > 0) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < properties.length; k++) { OrderGetProductProperties attr = properties[k]; sb.append(attr.getName()).append(":").append(attr.getValue()).append(","); } if (sb.length() > 0) { detail.setFoodProperty(sb.toString().substring(0, sb.length() - 1)); } } //detail.setFoodProperty(JSON.toJSONString(product_features)); detail.setQuantity((long) product[j].getProduct_amount()); detail.setBoxNum(product[j].getPackage_amount().toString()); detail.setBoxPrice(new BigDecimal(product[j].getPackage_fee() > 0 ? (double) product[j].getPackage_fee() / 100 : 0)); detailList.add(detail); // iWaimaiOrderDetailService.save(detail); } iWaimaiOrderDetailService.saveBatch(detailList); } } // redisCache.setNumber(shop.getId(),data.getOrder().getOrder_index()); /**打印外卖单*/ //autoPrintWaimai(waimaiOrder, detailList); redisCache.redisTemplate.opsForValue().set("ebai.order.print:"+data.getOrder().getOrder_id() + "",JSONObject.toJSONString(data),2,TimeUnit.DAYS); PrintOrderDto printOrderDto = EleRetailConvertPrint.convert(data); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, shop.getId(),waimaiOrder); } return waimaiOrder; } private void cancelOrder(WaimaiOrder waimaiOrder) { String cancelReason = "用户取消"; waimaiOrder.setStatus(OrderStatusEnum.CANCEL.status); iWaimaiOrderService.updateById(waimaiOrder); Order order = iOrderService.getOne(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); if (order != null && !DeliveryStatusEnum.CANCEL.status.equals(order.getDeliveryStatus())) { apiOrderCancelService.cancel(order.getMemberId(), order.getId().intValue(), cancelReason,DeliveryStatusEnum.CANCEL.status,OrderCancelTypeEnum.USER_CANCEL.type); } } @Override public void updateWaimaiOrderStatus(String orderId, int status) { WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderId)); if (waimaiOrder != null) { waimaiOrder.setStatus(status); if(DeliveryStatusEnum.FINISH.status.intValue() == status){ waimaiOrder.setFinishTime(new Date()); } if(DeliveryStatusEnum.CANCEL.status.intValue() == status){ return; } iWaimaiOrderService.updateById(waimaiOrder); } } /** * 异常单撤回 * * @param loginId * @param orderId */ @Override @Transactional(rollbackFor = Exception.class) public void rollOrder(Long loginId, Integer orderId) { Order order = iOrderService.getById(orderId); if (order == null){ throw new CustomAppException("该订单已撤回"); } if (!order.getDeliveryStatus().equals(DeliveryStatusEnum.ABNORMAL.status) || order.getWaimaiOrderId() == null){ throw new CustomAppException("该订单不允许撤回"); } List deliverys = iOrderDeliveryService.getByOrderSn(order.getOrderSn()); boolean checkCancel = true; for (OrderDelivery delivery : deliverys){ if (StringUtils.isNotBlank(delivery.getOutTradeNo()) && !delivery.getOutTradeNo().equals(-1) && delivery.getDeliveryStatus() != -1){ checkCancel = false; break; } } if (!checkCancel){ throw new CustomAppException("操作太频繁,请稍后再试"); } // 将原始订单删除-逻辑删除 iOrderService.removeById(order); WaimaiOrder waimaiOrder = iWaimaiOrderService.getById(order.getWaimaiOrderId()); if (waimaiOrder.getStatus().equals(DeliveryStatusEnum.CANCEL.status)){ waimaiOrder.setStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); } waimaiOrder.setTakeRemark(order.getTakeRemark()); // 预约单撤回后, 不支持设置自动发单 if (waimaiOrder.getDeliveryTime() != null && waimaiOrder.getDeliveryTime() > 0) { waimaiOrder.setAutoOrder(0); } iWaimaiOrderService.updateById(waimaiOrder); Shop shop = iShopService.getById(order.getShopId()); DspWaimai waiMai = iDspWaimaiService.findOne(waimaiOrder.getOrderType()); addOrder(shop,waimaiOrder,waiMai,SnCodeUtils.createSn()); } @Override public String newEBaiOrder(String orderId,String shopId) { ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper().eq("third_shop_id", shopId).eq("deleted", IsDeleteEnum.NORMAL.status)); if (shopWaimai == null) { log.error("未找到饿百绑定的商户,商户id为---" + shopId); return null; } Shop shop = iShopService.getById(shopWaimai.getShopId()); Long memberId = null; List memberIds = iMemberService.selectByShopId(shop.getId()); if(CollectionUtils.isNotEmpty(memberIds)){ memberId = memberIds.get(0); }else{ Member member = iMemberService.findOne(shop.getMerchantId()); memberId = member.getId(); } MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id",memberId)); if (config != null) { if (config.getOpenAutoorder().equals(StatusEnum.SHOW.status)) { boolean flat = eleRetaiClient.confirm(orderId); log.info("饿百自动接单返回"+flat); } } String orderSn=SnCodeUtils.createSn(); redisCache.redisTemplate.opsForValue().set("ebai.order:"+orderId + "",orderSn,2,TimeUnit.DAYS); return orderSn; } // public static void main(String[] args) { // String remark="[预定人]18669794657 [蛋糕祝语]祝妮可生日快乐 [其他备注]两个1的数字蜡烛 收餐人隐私号 15192663044_7856,手机号 186****4657"; // if(remark.contains("[预")){ // remark = remark.substring(remark.indexOf("[预"),remark.indexOf("[预")+8)+"****"+remark.substring(remark.indexOf("[预")+12,remark.length()); // } // System.out.println( // remark // ); // } @Override public void syncFoodImg(Long loginId) { Member member = iMemberService.getById(loginId); List shopList = iShopWaimaiService.findWMList(member.getShopId()); if(CollectionUtils.isNotEmpty(shopList)){ for(WaimaiListDto shopWaimai:shopList){ if(WaimaiTypeEnums.E_LE_ME.getType().equals(shopWaimai.getType())){ log.info("shopId: {} 同步饿了么菜品图片开始", member.getShopId()); iWaimaiFoodImgService.syncEleFoodImgByShop(shopWaimai.getAuthToken(), shopWaimai.getThirdShopId(), shopWaimai.getShopId().intValue()); } if(WaimaiTypeEnums.MEI_TUAN.getType().equals(shopWaimai.getType())&&(shopWaimai.getBusinessId().intValue()!=16)){ log.info("shopId: {} 同步美团菜品图片开始", member.getShopId()); iWaimaiFoodImgService.syncMeituanFoodImgByShop(shopWaimai.getAuthToken(), shopWaimai.getShopId().intValue(),shopWaimai.getThirdShopId()); } if(WaimaiTypeEnums.E_LE_ME_RETAIL.getType().equals(shopWaimai.getType())){ log.info("shopId: {} 同步饿百菜品图片开始", member.getShopId()); iWaimaiFoodImgService.syncEleRetailFoodImgByShop(shopWaimai.getEpoid(), shopWaimai.getShopId().intValue(),shopWaimai.getThirdShopId()); } if(WaimaiTypeEnums.MEI_TUAN_SG.getType().equals(shopWaimai.getType())){ // 同步美团闪购图片 log.info("shopId: {} 同步美团闪购菜品图片开始", member.getShopId()); iWaimaiFoodImgService.syncMeituanSgFoodImgByShop(shopWaimai.getAuthToken(), shopWaimai.getShopId().intValue(), shopWaimai.getThirdShopId()); } if(WaimaiTypeEnums.MEI_TUAN.getType().equals(shopWaimai.getType())&&shopWaimai.getBusinessId().intValue()==16){ log.info("shopId: {} 同步美团非冲突菜品图片开始", member.getShopId()); iWaimaiFoodImgService.syncMeituanNgFoodImgByShop(shopWaimai.getAuthToken(), shopWaimai.getShopId().intValue(),shopWaimai.getThirdShopId()); } } } } /** * 处理京东到家新订单 * * @param orderResultVo */ @Override @Transactional @Async public void jdHomeNewOrder(JdHomeOrderResultVo orderResultVo) { ShopJdHomeCode shopJdHomeCode = iShopJdHomeCodeService.getOne(new QueryWrapper().eq("deleted", 0).eq("app_key", orderResultVo.getAppKey())); List shopWaimais = iShopWaimaiService.list(new QueryWrapper().eq("bind_status", 1).eq("business_id", shopJdHomeCode.getId())); Long memberId = null; ShopWaimai shopWaimai = new ShopWaimai(); if (CollectionUtils.isNotEmpty(shopWaimais)) { shopWaimai = shopWaimais.get(0); } List memberIds = iMemberService.selectByShopId(shopWaimai.getShopId()); if(CollectionUtils.isNotEmpty(memberIds)){ memberId = memberIds.get(0); }else{ Member member = iMemberService.findOne(shopWaimai.getMerchantId()); memberId = member.getId(); } MemberConfig config = iMemberConfigService.getOne(new QueryWrapper().eq("member_id",memberId)); // DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.MEI_TUAN_SG.getType()); // ShopWaimai shopWaimai = iShopWaimaiService.findById(shop.getId(), waimai.getId()); if (config != null && StatusEnum.SHOW.status.equals(config.getOpenAutoorder())) { ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo(); confirmOrderVo.setOrderId(orderResultVo.getBillId()); confirmOrderVo.setAppAuthToken(shopJdHomeCode.getToken()); ResObject resObject = jdHomeClient.confirmOrder(confirmOrderVo, shopJdHomeCode.getAppKey(), shopJdHomeCode.getAppSecret()); log.info("=======京东到家订单确认结果=====" + JsonMapper.nonEmptyMapper().toJson(resObject)); } } /** * 处理京东到家商家已接单 * * @param orderVo */ @SneakyThrows @Override @Async @Transactional public void jdHomeConfirmOrder(JdHomeOrderResultVo orderVo) { DspWaimai waimai = iDspWaimaiService.findOne(WaimaiTypeEnums.JD_HOME.getType()); ShopJdHomeCode shopJdHomeCode = iShopJdHomeCodeService.getOne(new QueryWrapper().eq("deleted", 0).eq("app_key", orderVo.getAppKey())); WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderVo.getBillId())); JdHomeParamJsonVo jsonVo = new JdHomeParamJsonVo(); jsonVo.setAppAuthToken(shopJdHomeCode.getToken()); jsonVo.setOrderId(orderVo.getBillId()); List orderInfoDTOList = jdHomeClient.selectJdHomeOrder(jsonVo, shopJdHomeCode.getAppKey(), shopJdHomeCode.getAppSecret()); OrderInfoDTO orderInfoDTO = new OrderInfoDTO(); if (orderInfoDTOList != null && orderInfoDTOList.size() > 0) { orderInfoDTO = orderInfoDTOList.get(0); } ShopWaimai shopWaimai = iShopWaimaiService.getOne(new QueryWrapper() .eq("business_id", shopJdHomeCode.getId()) .eq("deleted", IsDeleteEnum.NORMAL.status) .eq("waimai_id", waimai.getId()) .eq("bind_status", BindStatusEnum.BIND.status) .eq("third_shop_id", orderInfoDTO.getDeliveryStationNo())); Shop shop = iShopService.getById(shopWaimai.getShopId()); if (waimaiOrder == null && shopWaimai != null) { waimaiOrder = new WaimaiOrder(); BeanUtils.copyProperties(orderInfoDTO, waimaiOrder); String recipientAddress = orderInfoDTO.getBuyerFullAddress(); waimaiOrder.setRecipientAddress(recipientAddress); waimaiOrder.setRecipientAddressDesensitization(recipientAddress); waimaiOrder.setLogisticsCode(orderInfoDTO.getDeliveryCarrierNo()); String remark = orderInfoDTO.getOrderBuyerRemark(); if (StringUtils.isNotBlank(remark) && remark.contains("\n")) { remark = remark.replace("\n", ""); } if (StringUtils.isNotBlank(remark) && remark.contains("[预")) { remark = remark.substring(remark.indexOf("[预"), remark.indexOf("[预") + 8) + "****" + remark.substring(remark.indexOf("[预") + 12, remark.length()); } waimaiOrder.setCaution(remark); waimaiOrder.setWaimaiId(waimai.getId()); waimaiOrder.setShopId(shop.getId()); waimaiOrder.setCityId(Long.valueOf(orderInfoDTO.getBuyerCity())); waimaiOrder.setOutOrderId(orderInfoDTO.getOrderId().toString()); waimaiOrder.setOrderidView(orderInfoDTO.getOrderId().toString()); waimaiOrder.setOrderTime(orderInfoDTO.getOrderStartTime()); waimaiOrder.setRecipientName(orderInfoDTO.getBuyerFullName()); waimaiOrder.setRecipientPhone(orderInfoDTO.getBuyerMobile()); waimaiOrder.setDaySeq(orderInfoDTO.getOrderNum().toString()); Long deliveryTime = orderInfoDTO.getOrderPreStartDeliveryTime().getTime(); String businessTag = orderInfoDTO.getBusinessTag(); String[] reTag = businessTag.split(";"); List tagList = Arrays.asList(reTag); // 预计送达时间,如果立即达set 0 if (tagList.contains("one_dingshida") || tagList.contains("dj_aging_nextday")) { waimaiOrder.setDeliveryTime(deliveryTime/1000); }else if (tagList.contains("dj_aging_immediately")) { waimaiOrder.setDeliveryTime(0L); } waimaiOrder.setHasInvoiced(orderInfoDTO.getOrderInvoiceOpenMark() == 1 ? 1 : 0); // waimaiOrder.setLatitude(orderInfoDTO.getBuyerLng(); // waimaiOrder.setLongitude(orderInfoDTO.getBuyerLat()); // 发票具体信息 OrderInvoiceDTO orderInvoiceDTO = orderInfoDTO.getOrderInvoice(); if (orderInvoiceDTO != null) { waimaiOrder.setInvoiceTitle(orderInvoiceDTO.getInvoiceTitle()); waimaiOrder.setTaxpayerId(orderInvoiceDTO.getInvoiceDutyNo()); } // waimaiOrder.setExtras(orderInfoDTO.getDiscount().toString()); // waimaiOrder.setIsThirdShipping(orderVo.getIsThirdShipping()); waimaiOrder.setReceiptLat(orderInfoDTO.getBuyerLat().toString()); waimaiOrder.setReceiptLng(orderInfoDTO.getBuyerLng().toString()); BigDecimal originalPrice = new BigDecimal(String.valueOf(orderInfoDTO.getOrderTotalMoney())); waimaiOrder.setOriginalPrice(originalPrice.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)); waimaiOrder.setPayType(orderInfoDTO.getOrderPayType()); // waimaiOrder.setPickType(Integer.valueOf(orderInfoDTO.getDeliveryCarrierNo())); // orderVo.setWmPoiAddress(URLDecoder.decode(orderVo.getWmPoiAddress(), "utf-8")); waimaiOrder.setPoiName(orderInfoDTO.getDeliveryStationName()); BigDecimal orderReceivableFreight = new BigDecimal(String.valueOf(orderInfoDTO.getOrderReceivableFreight())); waimaiOrder.setShippingFee(orderReceivableFreight.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)); // 门店具体信息 jsonVo.setStoreNo(orderInfoDTO.getDeliveryStationNo()); StoreInfo storeInfo = jdHomeClient.selectJdHomeShop(jsonVo, shopJdHomeCode.getAppKey(), shopJdHomeCode.getAppSecret()); waimaiOrder.setPoiAddress(storeInfo.getStationAddress()); waimaiOrder.setPoiPhone(storeInfo.getPhone()); waimaiOrder.setPoiReceiveDetail(null); waimaiOrder.setReceiptPrivacyPhone(null); waimaiOrder.setStatus(DeliveryStatusEnum.ORDERS_TO_BE_BILLED.status); waimaiOrder.setOrderType(WaimaiOrderTypeEnum.JD_HOME.getType()); BigDecimal totalPrice = new BigDecimal(String.valueOf(orderInfoDTO.getOrderBuyerPayableMoney())); waimaiOrder.setTotalPrice(totalPrice.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)); waimaiOrder.setCreateTime(new Date()); BigDecimal boxFee = BigDecimal.ZERO; List orderProductDTOS = orderInfoDTO.getProduct(); for (OrderProductDTO dto : orderProductDTOS) { boxFee = boxFee.add(BigDecimal.valueOf(dto.getCanteenMoney())); } waimaiOrder.setBoxFee(boxFee); waimaiOrder.setThirdShopId(shopWaimai.getThirdShopId()); iWaimaiOrderService.save(waimaiOrder); //消息推送 // messagePushService.waimaiMessage(shop.getId(), waimaiOrder); //记录商品详情 List detailList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(orderInfoDTO.getProduct())) { for (OrderProductDTO vo : orderInfoDTO.getProduct()) { WaimaiOrderDetail detail = new WaimaiOrderDetail(); BeanUtils.copyProperties(vo, detail); detail.setAppFoodCode(vo.getSkuIdIsv()); detail.setSkuId(vo.getSkuId().toString()); detail.setQuantity(Long.valueOf(vo.getSkuCount())); detail.setWaimaiOrderId(waimaiOrder.getId()); detail.setFoodName(vo.getSkuName()); detail.setPrice(new BigDecimal(String.valueOf(vo.getSkuStorePrice())).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)); detail.setSpec(vo.getSkuCostumeProperty()); // detail.setBoxNum(vo.getBoxNum().toString()); detailList.add(detail); //iWaimaiOrderDetailService.save(detail); } iWaimaiOrderDetailService.saveBatch(detailList); } //自动打印外卖单 redisCache.redisTemplate.opsForValue().set("jd-order:" + orderInfoDTO.getOrderId() + "", JSONObject.toJSONString(orderInfoDTO), 2, TimeUnit.DAYS); try { // redisCache.setNumber(shop.getId(),Integer.parseInt(orderVo.getDaySeq())); // autoPrintWaimai(waimaiOrder, detailList); PrintOrderDto printOrderDto = JdHomeConvertPrint.convert(orderInfoDTO); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, shop.getId(), waimaiOrder); } catch (Exception e) { log.error("自动打印异常!", e); } try { //推送外卖新消息 messagePushService.waimaiMessage(shop.getId(), waimaiOrder); } catch (Exception e) { log.error("推送外卖订单消息异常,订单号:" + waimaiOrder.getOutOrderId()); } //产生配送订单 addOrder(shop, waimaiOrder, waimai, SnCodeUtils.createSn()); } } @Override @Async public void jdHomeDoCancelOrder(JdHomeOrderResultVo orderCancelVo) { if (!redisCache.redisTemplate.hasKey(orderCancelVo.getBillId()+ "_lock")){ WaimaiOrder waimaiOrder = iWaimaiOrderService.getOne(new QueryWrapper().eq("out_order_id", orderCancelVo.getBillId())); if (waimaiOrder != null) { String title = "您有一个外卖订单被顾客取消,请及时查看"; String content = "您有一个外卖订单被顾客取消,请及时查看"; redisCache.redisTemplate.opsForValue().set(orderCancelVo.getBillId()+ "_lock", "1", 60, TimeUnit.MINUTES); messagePushService.userCancelOrderMessage(waimaiOrder.getShopId(), title, content,waimaiOrder.getId()); log.info("------->京东到家取消订单" + orderCancelVo.getBillId()); cancelOrder(waimaiOrder); try { String json = redisCache.redisTemplate.opsForValue().get("jd-order:"+orderCancelVo.getBillId()) + ""; if (StringUtils.isNotBlank(json)){ OrderInfoDTO vo = JSONObject.parseObject(json, OrderInfoDTO .class); PrintOrderDto printOrderDto = JdHomeConvertPrint.convert(vo); printOrderDto.setOrderStatus(OrderStatusEnum.CANCEL.status); List detailList = iWaimaiOrderDetailService.list(new QueryWrapper().eq("waimai_order_id", waimaiOrder.getId())); apiWaimaiPrintService.autoPrintWaimaiNew(printOrderDto, detailList, waimaiOrder.getShopId(),waimaiOrder); } } catch (Exception e) { log.error("自动打印异常!", e); } } } } }