OrderServiceImpl.java 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. package com.kmall.admin.service.impl;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.common.collect.ImmutableBiMap;
  4. import com.google.common.collect.Maps;
  5. import com.kmall.admin.dao.*;
  6. import com.kmall.admin.dao.mk.Mk2GoodsTopicPriceDao;
  7. import com.kmall.admin.dao.mk.Mk2MemberBirthdayDao;
  8. import com.kmall.admin.dao.mk.store.MkStorePromOrderRealDao;
  9. import com.kmall.admin.dao.mk.store.MkStorePromTypeDao;
  10. import com.kmall.admin.dao.mk.store.StoreTopicDao;
  11. import com.kmall.admin.dao.vip.Mall2MemberConsumptionRecordsDao;
  12. import com.kmall.admin.dao.vip.Mall2MemberPointsDao;
  13. import com.kmall.admin.dao.vip.Mall2PointsRulesDao;
  14. import com.kmall.admin.dto.OrderExpressDto;
  15. import com.kmall.admin.dto.OrderRecognitionDto;
  16. import com.kmall.admin.entity.*;
  17. import com.kmall.admin.entity.OrderProcessRecordEntity;
  18. import com.kmall.admin.entity.mk.Mk2GoodsTopicPriceEntity;
  19. import com.kmall.admin.entity.mk.store.*;
  20. import com.kmall.admin.entity.vip.Mall2MemberConsumptionRecordsEntity;
  21. import com.kmall.admin.entity.vip.Mall2MemberPointsEntity;
  22. import com.kmall.admin.entity.vip.Mall2PointsRulesEntity;
  23. import com.kmall.admin.fromcomm.dao.SysConfigDao;
  24. import com.kmall.admin.service.*;
  25. import com.kmall.admin.service.mk.store.MkStoreCampMinusService;
  26. import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
  27. import com.kmall.admin.websocket.WebSocketServer;
  28. import com.kmall.api.entity.*;
  29. import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
  30. import com.kmall.common.utils.ResponseData;
  31. import com.kmall.common.utils.wechat.WechatMicropayApiResult;
  32. import com.kmall.common.utils.wechat.WechatReverseApiResult;
  33. import com.kmall.manager.manager.alipay.AliPayMicropayApiResult;
  34. import com.kmall.manager.manager.alipay.AliPayRequestParams;
  35. import com.kmall.manager.manager.alipay.AliPayUtil;
  36. import com.kmall.manager.manager.express.sf.properties.SFPropertiesBuilder;
  37. import com.kmall.manager.manager.express.sf.properties.SFUtil;
  38. import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity;
  39. import com.kmall.manager.manager.express.sf.entity.RouteEntity;
  40. import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity;
  41. import com.kmall.manager.manager.print.ticket.TicketPrintUtil;
  42. import com.kmall.manager.manager.wechat.WechatUtil;
  43. import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
  44. import com.kmall.admin.utils.ShiroUtils;
  45. import com.kmall.common.constant.Dict;
  46. import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
  47. import com.kmall.api.util.CommonUtil;
  48. import com.kmall.admin.fromcomm.entity.SysUserEntity;
  49. import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder;
  50. import com.kmall.common.utils.*;
  51. import com.kmall.common.utils.print.ticket.item.*;
  52. import com.kmall.manager.manager.express.kdn.KdniaoUtil;
  53. import com.kmall.common.utils.wechat.WechatRefundApiResult;
  54. import org.slf4j.Logger;
  55. import org.slf4j.LoggerFactory;
  56. import org.springframework.beans.factory.annotation.Autowired;
  57. import org.springframework.stereotype.Service;
  58. import org.springframework.transaction.annotation.Transactional;
  59. import java.io.IOException;
  60. import java.math.BigDecimal;
  61. import java.math.RoundingMode;
  62. import java.text.ParseException;
  63. import java.text.SimpleDateFormat;
  64. import java.util.*;
  65. @Service("orderService")
  66. public class OrderServiceImpl implements OrderService {
  67. private final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
  68. @Autowired
  69. private OrderDao orderDao;
  70. @Autowired
  71. private ShippingDao shippingDao;
  72. @Autowired
  73. private OrderGoodsDao orderGoodsDao;
  74. @Autowired
  75. private SysPrinterDao printerDao;
  76. @Autowired
  77. private UserDao userDao;
  78. @Autowired
  79. private UserCouponDao userCouponDao;
  80. @Autowired
  81. private ProductStoreRelaDao productStoreRelaDao;
  82. @Autowired
  83. private OrderProcessRecordDao orderProcessRecordDao;
  84. @Autowired
  85. private OrderRefundDao orderRefundDao;
  86. @Autowired
  87. private StoreDao storeDao;
  88. @Autowired
  89. private OfflineCartDao offlineCartDao;
  90. @Autowired
  91. private GoodsDao goodsDao;
  92. @Autowired
  93. private MerchDao merchDao;
  94. @Autowired
  95. private MngChangeDao mngChangeDao;
  96. @Autowired
  97. private StoreMngChangeDao storeMngChangeDao;
  98. @Autowired
  99. private ThirdMerchExpressDao thirdMerchExpressDao;
  100. @Autowired
  101. private MkStorePromOrderRealDao mkStorePromOrderRealDao;
  102. @Autowired
  103. private UserCampMinusDao userCampMinusDao;
  104. @Autowired
  105. private UserService userService;
  106. @Autowired
  107. private SysConfigDao sysConfigDao;
  108. @Autowired
  109. private ProductDao productDao;
  110. @Autowired
  111. private OrderWXPayRecordService orderWXPayRecordService;
  112. @Autowired
  113. private StoreService storeService;
  114. @Autowired
  115. private PickUpCodeService pickUpCodeService;
  116. @Autowired
  117. private MkStoreCampMinusService mkStoreCampMinusService;
  118. @Autowired
  119. private MkStoreTicketDiscountService mkStoreTicketDiscountService;
  120. @Autowired
  121. private CashierDao cashierDao; // 收银机查询
  122. @Autowired
  123. private CashierLoginRecordDao cashierLoginRecordDao; // 收银员登录记录
  124. @Autowired
  125. private SaleRecordDao saleRecordDao; // 销售记录
  126. @Autowired
  127. private StoreTopicDao storeTopicDao; // 查询是否有门店活动
  128. @Autowired
  129. private Mk2GoodsTopicPriceDao mk2GoodsTopicPriceDao; // 门店商品价格
  130. @Autowired
  131. private Mall2PointsRulesDao pointsRulesDao; // 积分规则
  132. @Autowired
  133. private Mall2MemberPointsDao memberPointsDao; // 用户积分
  134. @Autowired
  135. private Mall2MemberConsumptionRecordsDao memberConsumptionRecordsDao; // 会员消费记录
  136. @Autowired
  137. private MkStorePromTypeDao storePromTypeDao; // 优惠类型
  138. @Autowired
  139. private Mk2MemberBirthdayDao memberBirthdayDao; // 生日优惠
  140. @Override
  141. public OrderEntity queryObject(Long id) {
  142. return orderDao.queryObject(id);
  143. }
  144. @Override
  145. public Double getTotalActualPrice(String merchOrderSn) {
  146. return orderDao.getTotalActualPrice(merchOrderSn);
  147. }
  148. @Override
  149. public List<OrderEntity> queryList(Map<String, Object> map) {
  150. return orderDao.queryList(map);
  151. }
  152. @Override
  153. public int queryTotal(Map<String, Object> map) {
  154. return orderDao.queryTotal(map);
  155. }
  156. @Override
  157. public int save(OrderEntity order) {
  158. return orderDao.save(order);
  159. }
  160. @Override
  161. public int update(OrderEntity order) {
  162. return orderDao.update(order);
  163. }
  164. /**
  165. * 取消订单
  166. *
  167. * @param order
  168. */
  169. @Override
  170. public void cancelOrder(OrderEntity order) {
  171. boolean needUpdateStock = true;
  172. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  173. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
  174. }
  175. orderDao.update(order);
  176. if (!needUpdateStock) {
  177. return;
  178. }
  179. // 更新库存
  180. updateStock(order, "管理后台取消订单");
  181. // 释放优惠券
  182. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  183. if (null != couponVo) {
  184. userCouponDao.cancelOrder(couponVo);
  185. }
  186. //释放促销满减券
  187. UserCampMinusEntity userCampMinusVo = userCampMinusDao.queryUserCampByOrderId(order.getId());
  188. if (null != userCampMinusVo) {
  189. userCampMinusDao.cancelUserCampOrder(userCampMinusVo);
  190. }
  191. }
  192. @Override
  193. public int delete(Long id) {
  194. return orderDao.delete(id);
  195. }
  196. @Override
  197. public int deleteBatch(Long[] ids) {
  198. return orderDao.deleteBatch(ids);
  199. }
  200. @Override
  201. public int confirm(Long id) {
  202. OrderEntity orderEntity = queryObject(id);
  203. Integer shippingStatus = orderEntity.getShippingStatus();//发货状态
  204. Integer payStatus = orderEntity.getPayStatus();//付款状态
  205. if (2 != payStatus) {
  206. throw new RRException("此订单未付款,不能确认收货!");
  207. }
  208. if (4 == shippingStatus) {
  209. throw new RRException("此订单处于退货状态,不能确认收货!");
  210. }
  211. if (0 == shippingStatus) {
  212. throw new RRException("此订单未发货,不能确认收货!");
  213. }
  214. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
  215. throw new RRException("此订单已完成!");
  216. }
  217. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  218. throw new RRException("此订单待付款!");
  219. }
  220. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
  221. throw new RRException("此订单付款中!");
  222. }
  223. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  224. throw new RRException("此订单已取消!");
  225. }
  226. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  227. throw new RRException("此订单已删除!");
  228. }
  229. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  230. throw new RRException("此订单还未发货!");
  231. }
  232. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())) {
  233. throw new RRException("此订单已退款!");
  234. }
  235. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
  236. throw new RRException("此订单已退款!");
  237. }
  238. orderEntity.setShippingStatus(2);
  239. orderEntity.setOrderStatus(301);
  240. orderEntity.setConfirmTime(new Date());
  241. orderDao.update(orderEntity);
  242. return 0;
  243. }
  244. @Override
  245. public int sendGoods(OrderEntity order) {
  246. Integer payStatus = order.getPayStatus();//付款状态
  247. if (2 != payStatus) {
  248. throw new RRException("此订单未付款!");
  249. }
  250. ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId());
  251. if (null != shippingEntity) {
  252. order.setShippingName(shippingEntity.getName());
  253. }
  254. order.setOrderStatus(300);//订单已发货
  255. order.setShippingStatus(1);//已发货
  256. return orderDao.update(order);
  257. }
  258. @Override
  259. public Ticket printMsg(Long id) {
  260. OrderEntity orderEntity = queryInfos(id);
  261. List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
  262. // 获取门店
  263. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  264. // 获取清关信息
  265. OrderProcessRecordEntity orderProcessRecordEntity =
  266. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  267. // 小票头
  268. TicketHead head = new TicketHead();
  269. head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
  270. // head.setMemberId(orderEntity.getUserName().toString());
  271. head.setOrderId(orderEntity.getOrderSn());
  272. head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date()));
  273. // 商品信息
  274. Integer goodsTotal = 0; // 商品总个数
  275. BigDecimal total = Constant.ZERO; // 商品总计
  276. List<Goods> goodsList = new ArrayList<>();
  277. for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
  278. goodsTotal += orderGoods.getNumber();
  279. total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  280. .setScale(2, BigDecimal.ROUND_HALF_UP);
  281. Goods goods = new Goods(orderGoods.getGoodsName(), orderGoods.getRetailPrice().toString(),
  282. orderGoods.getNumber().toString(),
  283. orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber()))
  284. .setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  285. goodsList.add(goods);
  286. }
  287. // 收银信息
  288. CashInfo cashInfo = new CashInfo();
  289. cashInfo.setGoodsTotal(goodsTotal.toString());
  290. cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  291. cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  292. cashInfo.setOddChange("0.00");
  293. cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  294. cashInfo.setFreight(
  295. new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  296. cashInfo.setPaymentMode("微信支付");
  297. // 海关清单
  298. CusListing cusListing = new CusListing();
  299. cusListing.setOrderId(orderEntity.getOrderSn());
  300. if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
  301. cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
  302. cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
  303. cusListing.setConsignee(orderEntity.getConsignee());
  304. cusListing.setConsigneeTel(orderEntity.getMobile());
  305. }
  306. cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
  307. cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
  308. return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing);
  309. }
  310. @Override
  311. public Ticket printMsg(Long id, String sessionId) {
  312. OrderEntity orderEntity = queryInfos(id);
  313. List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
  314. // 获取门店
  315. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  316. // 获取清关信息
  317. OrderProcessRecordEntity orderProcessRecordEntity =
  318. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  319. // 小票头
  320. TicketHead head = new TicketHead();
  321. head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
  322. // head.setMemberId(orderEntity.getUserName().toString());
  323. head.setOrderId(orderEntity.getOrderSn());
  324. head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date()));
  325. // 商品信息
  326. Integer goodsTotal = 0; // 商品总个数
  327. BigDecimal total = Constant.ZERO; // 商品总计
  328. List<Goods> goodsList = new ArrayList<>();
  329. for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
  330. goodsTotal += orderGoods.getNumber();
  331. total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
  332. .setScale(2, BigDecimal.ROUND_HALF_UP);
  333. Goods goods = new Goods(orderGoods.getGoodsName(), orderGoods.getRetailPrice().toString(),
  334. orderGoods.getNumber().toString(),
  335. orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber()))
  336. .setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  337. goodsList.add(goods);
  338. }
  339. // 收银信息
  340. CashInfo cashInfo = new CashInfo();
  341. cashInfo.setGoodsTotal(goodsTotal.toString());
  342. cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  343. cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  344. cashInfo.setOddChange("0.00");
  345. cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  346. cashInfo.setFreight(
  347. new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
  348. cashInfo.setPaymentMode("微信支付");
  349. // 海关清单
  350. CusListing cusListing = new CusListing();
  351. cusListing.setOrderId(orderEntity.getOrderSn());
  352. if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
  353. cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
  354. cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
  355. cusListing.setConsignee(orderEntity.getConsignee());
  356. cusListing.setConsigneeTel(orderEntity.getMobile());
  357. }
  358. cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
  359. cusListing.setDeliveryAddress(storeEntity.getStoreAddress());
  360. // 尝试在取货码表中查询数据,如果有的话就改变状态
  361. String orderSn = orderEntity.getOrderSn();
  362. PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(orderSn);
  363. if(pickUpCodeEntity != null){
  364. pickUpCodeEntity.setPickUpCodeStatus("1");
  365. pickUpCodeService.update(pickUpCodeEntity);
  366. // try {
  367. // WebSocketServer.delete(sessionId,orderEntity.getStoreId(),pickUpCodeEntity);
  368. // } catch (IOException e) {
  369. // e.printStackTrace();
  370. // }
  371. }
  372. return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing);
  373. }
  374. /**
  375. * 退款
  376. */
  377. @Transactional
  378. public void refund(OrderEntity order) {
  379. boolean needUpdateStock = true;
  380. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  381. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  382. }
  383. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  384. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  385. }
  386. orderDao.update(order);//修改为退款中
  387. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  388. /*// 判断是否有优惠券
  389. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  390. if (null != couponVo) {
  391. userCouponDao.cancelOrder(couponVo);
  392. }
  393. if (!needUpdateStock) {
  394. return;
  395. }
  396. // 更新库存
  397. updateStock(order, "管理后台订单退款");*/
  398. // updateStock(order, "管理后台订单退款");
  399. queryStorePromRealUpdateIsScan(order);
  400. }
  401. /**
  402. * 退款
  403. */
  404. @Transactional
  405. public void refund(OrderEntity order, WechatRefundApiResult result) {
  406. boolean needUpdateStock = true;
  407. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  408. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  409. }
  410. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  411. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  412. }else{
  413. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  414. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  415. OrderRefundEntity orderRefund = new OrderRefundEntity();
  416. orderRefund.setRefundId(result.getRefund_id());
  417. orderRefund.setOutRefundNo(result.getOut_refund_no());
  418. orderRefund
  419. .setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
  420. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  421. orderRefund.setModTime(new Date());
  422. if (mallOrderRefund != null) {
  423. orderRefund.setId(mallOrderRefund.getId());
  424. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  425. orderRefundDao.update(orderRefund);
  426. } else {
  427. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  428. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  429. orderRefund.setCreateTime(new Date());
  430. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  431. if(list.size()>1){//多条订单
  432. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  433. }else{
  434. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  435. }
  436. orderRefundDao.save(orderRefund);//退款记录
  437. }
  438. }
  439. orderDao.update(order);//修改为退款中
  440. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  441. /*// 判断是否有优惠券
  442. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  443. if (null != couponVo) {
  444. userCouponDao.cancelOrder(couponVo);
  445. }
  446. if (!needUpdateStock) {
  447. return;
  448. }
  449. // 更新库存
  450. updateStock(order, "管理后台订单退款");*/
  451. // updateStock(order, "管理后台订单退款");
  452. queryStorePromRealUpdateIsScan(order);
  453. }
  454. @Transactional
  455. public void refund(OrderEntity order, AliPayMicropayApiResult result) {
  456. boolean needUpdateStock = true;
  457. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  458. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  459. }
  460. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  461. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  462. }else{
  463. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  464. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  465. OrderRefundEntity orderRefund = new OrderRefundEntity();
  466. orderRefund.setRefundId(result.getTradeNo());
  467. orderRefund.setOutRefundNo(result.getOutTradeNo());
  468. orderRefund
  469. .setRefundMoney(new BigDecimal(result.getRefundFee()).divide(Constant.ONE_HUNDRED));
  470. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款处理中
  471. orderRefund.setModTime(new Date());
  472. if (mallOrderRefund != null) {
  473. orderRefund.setId(mallOrderRefund.getId());
  474. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  475. orderRefundDao.update(orderRefund);
  476. } else {
  477. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  478. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  479. orderRefund.setCreateTime(new Date());
  480. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  481. if(list.size()>1){//多条订单
  482. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  483. }else{
  484. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  485. }
  486. orderRefundDao.save(orderRefund);//退款记录
  487. }
  488. }
  489. orderDao.update(order);//修改为退款中
  490. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  491. /*// 判断是否有优惠券
  492. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  493. if (null != couponVo) {
  494. userCouponDao.cancelOrder(couponVo);
  495. }
  496. if (!needUpdateStock) {
  497. return;
  498. }
  499. // 更新库存
  500. updateStock(order, "管理后台订单退款");*/
  501. // updateStock(order, "管理后台订单退款");
  502. // queryStorePromRealUpdateIsScan(order);
  503. }
  504. /**
  505. * 平安退款逻辑处理
  506. * @param order
  507. * @param result
  508. */
  509. @Transactional
  510. public void pinganRefund(OrderEntity order, net.sf.json.JSONObject result, String refundId) {
  511. boolean needUpdateStock = true;
  512. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  513. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  514. }
  515. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  516. OrderRefundEntity orderRefund = new OrderRefundEntity();
  517. orderRefund.setRefundId(refundId);
  518. orderRefund.setOutRefundNo(result.getString("ord_no"));
  519. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  520. orderRefund.setModTime(new Date());
  521. orderRefund.setRefundMoney(BigDecimal.valueOf(result.getInt("trade_amount")).divide(Constant.ONE_HUNDRED));
  522. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  523. if (mallOrderRefund != null) {
  524. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  525. orderRefund.setId(mallOrderRefund.getId());
  526. orderRefundDao.update(orderRefund);
  527. } else {//退款记录不存在
  528. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  529. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  530. orderRefund.setCreateTime(new Date());
  531. orderRefundDao.save(orderRefund);//退款记录
  532. }
  533. orderDao.update(order);//修改为退款中
  534. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  535. /*// 判断是否有优惠券
  536. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  537. if (null != couponVo) {
  538. userCouponDao.cancelOrder(couponVo);
  539. }
  540. if (!needUpdateStock) {
  541. return;
  542. }
  543. // 更新库存
  544. updateStock(order, "管理后台平安退款订单");*/
  545. queryStorePromRealUpdateIsScan(order);
  546. }
  547. /**
  548. * 微信国际退款逻辑处理
  549. * @param order
  550. * @param result
  551. */
  552. @Transactional
  553. public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) {
  554. boolean needUpdateStock = true;
  555. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  556. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  557. }
  558. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  559. OrderRefundEntity orderRefund = new OrderRefundEntity();
  560. orderRefund.setRefundId(result.getRefund_id());
  561. orderRefund.setOutRefundNo(result.getOut_refund_no());
  562. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
  563. orderRefund.setModTime(new Date());
  564. orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
  565. orderRefund.setRefundFeeType(result.getRefund_fee_type());
  566. if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) {
  567. orderRefund.setTotalFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getTotal_fee())).divide(Constant.ONE_HUNDRED).toString()));
  568. }
  569. orderRefund.setFeeType(result.getFee_type());
  570. if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) {
  571. orderRefund.setCashFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_fee())).divide(Constant.ONE_HUNDRED).toString()));
  572. }
  573. orderRefund.setCashFeeType(result.getCash_fee_type());
  574. if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_refund_fee())) {
  575. orderRefund.setCashRefundFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_refund_fee())).divide(Constant.ONE_HUNDRED).toString()));
  576. }
  577. orderRefund.setCashRefundFeeType(result.getCash_refund_fee_type());
  578. OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
  579. if (mallOrderRefund != null) {
  580. orderRefund.setRefundType(mallOrderRefund.getRefundType());
  581. orderRefund.setId(mallOrderRefund.getId());
  582. orderRefundDao.update(orderRefund);
  583. } else {//退款记录不存在
  584. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  585. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  586. orderRefund.setCreateTime(new Date());
  587. orderRefundDao.save(orderRefund);//退款记录
  588. }
  589. orderDao.update(order);//修改为退款中
  590. // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
  591. /*// 判断是否有优惠券
  592. UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
  593. if (null != couponVo) {
  594. userCouponDao.cancelOrder(couponVo);
  595. }
  596. if (!needUpdateStock) {
  597. return;
  598. }
  599. // 更新库存
  600. updateStock(order, "管理后台微信国际退款订单");*/
  601. queryStorePromRealUpdateIsScan(order);
  602. }
  603. private void updateStock(OrderEntity order, String changeReason){
  604. Map<String, Object> map = new HashMap();
  605. SysUserEntity user = ShiroUtils.getUserEntity();
  606. map.put("orderId", order.getId());
  607. List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
  608. for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
  609. ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
  610. .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),Long.valueOf(orderGoodsEntity.getProductId()));
  611. if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
  612. storeRelaEntity.setSellVolume(0);
  613. }
  614. BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
  615. if (sellVolume.compareTo(Constant.ZERO) < 0) {
  616. sellVolume = Constant.ZERO;
  617. }
  618. Integer stockNum = 0;
  619. GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
  620. if(goodsEntity != null){
  621. stockNum = goodsEntity.getGoodsNumber();
  622. //还原商户商品库存
  623. resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
  624. }
  625. if (null != storeRelaEntity.getStockNum()) {
  626. stockNum = storeRelaEntity.getStockNum();
  627. //普通商品不受共享库存影响,直接取门店配置库存
  628. //该商品所属第三方商户不是共享库存
  629. if(goodsEntity.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
  630. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
  631. }else{
  632. //该商品所属第三方商户是共享库存,但商品业务类型不是00保税备货
  633. if(!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
  634. resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
  635. }
  636. }
  637. }
  638. //该商品所属第三方商户为共享库存,且是保税备货商品,取消订单时改变
  639. updateGoodsByIsShareStock(goodsEntity);
  640. }
  641. }
  642. /**
  643. * 更新商品库存数量变化后是否已共享为0“未共享”
  644. * @param goodsInfo
  645. */
  646. private void updateGoodsByIsShareStock(GoodsEntity goodsInfo){
  647. //该商品所属第三方商户为共享库存,且是保税备货商品
  648. if(goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
  649. && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
  650. GoodsEntity goodsVo = new GoodsEntity();
  651. goodsVo.setId(goodsInfo.getId());
  652. //商品库存数量变化后是否已共享,0:否,1:是(下单、退款、取消订单触发)
  653. goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem());
  654. goodsDao.update(goodsVo);
  655. }
  656. }
  657. /**
  658. * 还原商品总库存
  659. * @param stockNum
  660. * @param storeRelaEntity
  661. * @param orderGoodsEntity
  662. * @param sellVolume
  663. * @param changeReason
  664. * @param user
  665. */
  666. private void resetGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
  667. OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){
  668. GoodsEntity goodsEntity = goodsDao.queryObject(storeRelaEntity.getGoodsId());
  669. if(goodsEntity!=null){
  670. goodsEntity.setGoodsNumber(stockNum + orderGoodsEntity.getNumber());
  671. // goodsEntity.setSellVolume(Integer.parseInt(goodsSellVolume.toString()));
  672. goodsDao.update(goodsEntity);
  673. // storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString()));
  674. // productStoreRelaDao.update(storeRelaEntity);
  675. MngChangeEntity mngChangeEntity = new MngChangeEntity();
  676. mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
  677. mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
  678. mngChangeEntity.setChangeReason(changeReason);
  679. mngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
  680. mngChangeEntity.setChangeNum(orderGoodsEntity.getNumber());//变化数
  681. mngChangeEntity.setOriginalNum(stockNum);//原库存数
  682. mngChangeEntity.setValidNum(stockNum + orderGoodsEntity.getNumber());//可用数
  683. mngChangeEntity.setCreateTime(new Date());
  684. mngChangeEntity.setModTime(new Date());
  685. mngChangeEntity.setCreaterSn(user.getUsername());
  686. mngChangeEntity.setModerSn(user.getUsername());
  687. mngChangeEntity.setIsValid(0);
  688. mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
  689. mngChangeDao.save(mngChangeEntity);
  690. }
  691. }
  692. /**
  693. * 还原门店商品库存
  694. * @param stockNum
  695. * @param storeRelaEntity
  696. * @param orderGoodsEntity
  697. * @param sellVolume
  698. * @param changeReason
  699. * @param user
  700. */
  701. private void resetStoreGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
  702. OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){
  703. storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString()));
  704. storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量
  705. productStoreRelaDao.update(storeRelaEntity);
  706. StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
  707. storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
  708. storeMngChangeEntity.setChangeReason(changeReason);
  709. storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(storeRelaEntity.getGoodsId())));
  710. storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(storeRelaEntity.getStoreId())));
  711. storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn());
  712. storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber());
  713. storeMngChangeEntity.setStoreOriginalNum(stockNum);
  714. storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber());
  715. storeMngChangeEntity.setCreateTime(new Date());
  716. storeMngChangeEntity.setModTime(new Date());
  717. storeMngChangeEntity.setCreaterSn(user.getUsername());
  718. storeMngChangeEntity.setModerSn(user.getUsername());
  719. storeMngChangeEntity.setIsValid(0);
  720. storeMngChangeDao.save(storeMngChangeEntity);
  721. }
  722. /**
  723. * 查询该退款订单编号是否是推广渠道订单,是则修改渠道定时扫描状态
  724. * @param orderInfo
  725. */
  726. private void queryStorePromRealUpdateIsScan(OrderEntity orderInfo){
  727. Map map = new HashMap();
  728. map.put("orderId", orderInfo.getId());
  729. List<MkStorePromOrderRealEntity> list = mkStorePromOrderRealDao.queryPromRealListByMap(map);
  730. if(list.size() > 0) {
  731. for (MkStorePromOrderRealEntity mkStorePromOrderRealEntity : list) {
  732. mkStorePromOrderRealEntity.setIsPromStatScan(Dict.isDistSellScan.item_0.getItem());
  733. mkStorePromOrderRealDao.update(mkStorePromOrderRealEntity);
  734. }
  735. }
  736. }
  737. /**
  738. * 处理用户退款申请
  739. *
  740. * @param orderInfo
  741. */
  742. @Transactional
  743. public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) {
  744. refundEntity.setApprovalTime(new Date());
  745. // refundEntity.setApprover(ShiroUtils.getUserId());
  746. // 退积分
  747. try {
  748. Integer integral = 1;
  749. if (orderInfo.getActualPrice().intValue() > 0) {
  750. integral = orderInfo.getActualPrice().intValue();
  751. }
  752. if (refundEntity.getRefundStatus() == 2) {
  753. orderInfo.setOrderStatus(401);
  754. // UserEntity entity = userDao.queryObject(orderInfo.getUserId());
  755. } else {
  756. orderInfo.setOrderStatus(201);
  757. }
  758. } catch (Exception e) {
  759. e.printStackTrace();
  760. }
  761. orderRefundDao.update(refundEntity);
  762. orderDao.update(orderInfo);
  763. }
  764. @Override
  765. public OrderRefundEntity queryRefundObject(Long refundId) {
  766. return orderRefundDao.queryObject(refundId);
  767. }
  768. @Override
  769. public List<OrderRefundEntity> queryRefundList(Map<String, Object> map) {
  770. return orderRefundDao.queryList(map);
  771. }
  772. @Override
  773. public int queryRefundTotal(Map<String, Object> map) {
  774. return orderRefundDao.queryTotal(map);
  775. }
  776. @Override
  777. public int getUserOrderInfo(Map<String, Object> map) {
  778. int result = 0;
  779. String type = (String) map.get("type");
  780. if ("yfkOrderUserSum".equals(type)) {
  781. result = orderDao.getYfkOrderUserSum(map);
  782. } else if ("oderUserSum".equals(type)) {
  783. result = orderDao.getOderUserSum(map);
  784. } else if ("todayUserOrder".equals(type)) {
  785. result = orderDao.getTodayUserOrder(map);
  786. } else if ("todayUserSales".equals(type)) {
  787. result = orderDao.getTodayUserSales(map);
  788. } else if ("incomeSum".equals(type)) {
  789. result = orderDao.getIncomeSum(map);
  790. } else if ("payedOrderCount".equals(type)) {
  791. result = orderDao.getPayedOrderCount(map);
  792. }
  793. return result;
  794. }
  795. @Override
  796. public Map getLogistics(Long id) {
  797. OrderEntity orderEntity = queryObject(id);
  798. if (orderEntity == null) {
  799. throw new RRException("此订单不存在!");
  800. }
  801. if (orderEntity.getShippingStatus() == 0) {
  802. if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) ||
  803. orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) {
  804. throw new RRException("此订单还未发货!");
  805. } else {
  806. if (StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) {
  807. throw new RRException("此订单还未发货!");
  808. }
  809. }
  810. }
  811. Map logisticsInfo = Maps.newHashMap();
  812. List<WuliuEntity> wuliuEntityList = new ArrayList<>();
  813. OrderProcessRecordEntity orderProcessRecordEntity =
  814. orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
  815. if (orderProcessRecordEntity != null) {
  816. if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) ||
  817. orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) {
  818. WuliuEntity wuliuEntity = new WuliuEntity();
  819. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  820. .format(orderProcessRecordEntity.getCustomsSuccTime()));
  821. wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" +
  822. storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() +
  823. ";交易完成,用户已提走");
  824. wuliuEntityList.add(wuliuEntity);
  825. }
  826. if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) &&
  827. StringUtils.isNotEmpty(orderEntity.getShippingNo()) &&
  828. orderProcessRecordEntity.getShipmentStartTime() != null) {
  829. if(orderEntity.getShippingCode().equalsIgnoreCase("SF")){
  830. StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
  831. if(storeEntity == null){
  832. throw new RRException("查询顺丰订单异常,订单的门店信息不存在");
  833. }
  834. ThirdMerchExpressEntity thirdMerchExpressEntity = thirdMerchExpressDao.getThirdMerchExpressByThirdCode(storeEntity.getThirdPartyMerchCode());
  835. if(thirdMerchExpressEntity == null){
  836. throw new RRException("查询顺丰订单异常,缺失商户快递账号信息");
  837. }
  838. SfRouteServiceResponseEntity entity = SFUtil.routeService(orderEntity.getShippingNo(), thirdMerchExpressEntity.getExpressAccount(),
  839. thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());
  840. // SfRouteServiceResponseEntity entity = SFUtil.routeService("254355029325", thirdMerchExpressEntity.getExpressAccount(),
  841. // thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());//444072971585
  842. if(entity.getHead().equalsIgnoreCase("OK")){
  843. if(entity.getBody() == null){
  844. WuliuEntity wuliuEntity = new WuliuEntity();
  845. wuliuEntity.setAcceptStation("暂无物流轨迹");
  846. wuliuEntityList.add(wuliuEntity);
  847. }else{
  848. if(entity.getBody().getRouteResponse() == null){
  849. WuliuEntity wuliuEntity = new WuliuEntity();
  850. wuliuEntity.setAcceptStation("暂无物流轨迹");
  851. wuliuEntityList.add(wuliuEntity);
  852. }else{
  853. RouteResponseEntity routeResponseEntity = entity.getBody().getRouteResponse().get(0);
  854. if(routeResponseEntity != null){
  855. List<RouteEntity> entityList = routeResponseEntity.getRouteResponse();
  856. for (RouteEntity route : entityList) {
  857. WuliuEntity wuliuEntity = new WuliuEntity();
  858. wuliuEntity.setAcceptTime(route.getAccept_time());
  859. wuliuEntity.setAcceptStation(route.getAccept_address() + route.getRemark());
  860. wuliuEntityList.add(wuliuEntity);
  861. }
  862. }
  863. }
  864. }
  865. }else{
  866. throw new RRException("查询顺丰订单异常,"+entity.getErrors());
  867. }
  868. }else{
  869. JSONObject traces =
  870. KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
  871. List<Map> mapList = (List<Map>) traces.get("Traces");
  872. if (mapList != null && mapList.size() > 0) {
  873. for (Map map : mapList) {
  874. WuliuEntity wuliuEntity = new WuliuEntity();
  875. wuliuEntity.setAcceptTime(map.get("AcceptTime").toString());
  876. wuliuEntity.setAcceptStation(map.get("AcceptStation").toString());
  877. wuliuEntityList.add(wuliuEntity);
  878. }
  879. }
  880. String state = traces.get("State") + "";
  881. if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
  882. String reason = traces.get("Reason") + "";
  883. WuliuEntity wuliuEntity = new WuliuEntity();
  884. wuliuEntity.setAcceptStation(reason);
  885. wuliuEntityList.add(wuliuEntity);
  886. }
  887. }
  888. }
  889. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) &&
  890. orderProcessRecordEntity.getShipmentStartTime() != null) {
  891. WuliuEntity wuliuEntity = new WuliuEntity();
  892. wuliuEntity.setAcceptStation("订单已出库");
  893. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  894. .format(orderProcessRecordEntity.getShipmentStartTime()));
  895. wuliuEntityList.add(wuliuEntity);
  896. }
  897. if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) {
  898. WuliuEntity wuliuEntity = new WuliuEntity();
  899. wuliuEntity.setAcceptStation("订单清关完成,等待仓库发货");
  900. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  901. .format(orderProcessRecordEntity.getCustomsSuccTime()));
  902. wuliuEntityList.add(wuliuEntity);
  903. }
  904. if (Dict.isSend.item_0.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend())) {
  905. WuliuEntity wuliuEntity = new WuliuEntity();
  906. wuliuEntity.setAcceptStation("订单清关失败");
  907. wuliuEntityList.add(wuliuEntity);
  908. }
  909. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsEleOrderSend()) &&
  910. orderProcessRecordEntity.getWaybillSuccTime() != null) {
  911. WuliuEntity wuliuEntity = new WuliuEntity();
  912. wuliuEntity.setAcceptStation("海关三单发送成功");
  913. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  914. .format(orderProcessRecordEntity.getWaybillSuccTime()));
  915. wuliuEntityList.add(wuliuEntity);
  916. }
  917. if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsPaymentSend())) {
  918. WuliuEntity wuliuEntity = new WuliuEntity();
  919. wuliuEntity.setAcceptStation("订单支付成功");
  920. wuliuEntity.setAcceptTime(
  921. new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderProcessRecordEntity.getPaySuccTime()));
  922. wuliuEntityList.add(wuliuEntity);
  923. }
  924. if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsAddOrderSend())) {
  925. WuliuEntity wuliuEntity = new WuliuEntity();
  926. wuliuEntity.setAcceptStation("订单下单成功");
  927. wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  928. .format(orderProcessRecordEntity.getAddOrderSuccTime()));
  929. wuliuEntityList.add(wuliuEntity);
  930. }
  931. }
  932. logisticsInfo.put("tracesList", wuliuEntityList);
  933. logisticsInfo.put("logisticCode", orderEntity.getShippingNo());
  934. logisticsInfo.put("shipperCode", orderEntity.getShippingCode());
  935. return logisticsInfo;
  936. }
  937. @Override
  938. public OrderEntity queryInfos(Long id) {
  939. OrderEntity orderEntity = orderDao.queryObject(id);
  940. Map<String, Object> map = new HashMap<String, Object>();
  941. map.put("orderId", id);
  942. List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
  943. orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
  944. return orderEntity;
  945. }
  946. /**
  947. * 普货商品生成线下订单
  948. * @param offlineCartList
  949. * @param user
  950. * @return
  951. */
  952. @Transactional
  953. @Override
  954. public Map orderSubmit(List<OfflineCartEntity> offlineCartList, SysUserEntity user) {
  955. Map resultObj = Maps.newHashMap();
  956. try {
  957. if (user == null) {
  958. resultObj.put("errno", 400);
  959. resultObj.put("errmsg", "用户登录超时,请重新登录");
  960. return resultObj;
  961. }
  962. if (!user.getRoleType().equalsIgnoreCase("2")) {
  963. resultObj.put("errno", 400);
  964. resultObj.put("errmsg", "该操作只允许店员账户操作");
  965. return resultObj;
  966. }
  967. if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
  968. resultObj.put("errno", 400);
  969. resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
  970. return resultObj;
  971. }
  972. Long userId = user.getUserId();
  973. Integer storeId = user.getStoreId();
  974. //获取要购买的商品
  975. Map param = Maps.newHashMap();
  976. param.put("userId", userId);
  977. param.put("storeId", storeId);
  978. if (null == offlineCartList && offlineCartList.size() == 0) {
  979. resultObj.put("errno", 400);
  980. resultObj.put("errmsg", "购买商品数据为空");
  981. return resultObj;
  982. }
  983. List<OfflineCartEntity> offlineCartEntityList = offlineCartDao.queryOfflineCartByBizType(param);
  984. if (offlineCartEntityList.size() == 0 && offlineCartList.size() > 0) {
  985. resultObj.put("errno", 0);
  986. resultObj.put("errmsg", "该单已下单成功,请重新扫描商品进行购买");
  987. return resultObj;
  988. }
  989. // 检查库存和更新库存
  990. for (OfflineCartEntity cartEntity : offlineCartEntityList) {
  991. GoodsEntity goodsEntity = goodsDao.queryObject(cartEntity.getGoodsId());
  992. if (goodsEntity == null) {
  993. resultObj.put("errno", 400);
  994. resultObj.put("errmsg", "订单提交失败:商品不存在");
  995. return resultObj;
  996. }
  997. //取得规格的信息,判断规格库存
  998. ProductStoreRelaEntity productInfo = productStoreRelaDao
  999. .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(cartEntity.getGoodsId()));
  1000. synchronized (productInfo) {
  1001. if (null == productInfo || null == productInfo.getStockNum() ||
  1002. productInfo.getStockNum() < cartEntity.getNumber()) {
  1003. resultObj.put("errno", 400);
  1004. resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum());
  1005. return resultObj;
  1006. } else {
  1007. productInfo.setStockNum(productInfo.getStockNum() - cartEntity.getNumber());
  1008. productInfo.setStoreId(Long.valueOf(storeId));
  1009. productInfo.addSellVolume();
  1010. productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
  1011. if(goodsEntity != null) {
  1012. goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - cartEntity.getNumber());
  1013. goodsDao.update(goodsEntity);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
  1019. OrderEntity order = setOrderVo(user, offlineCartEntityList, user.getMerchSn());
  1020. order.setStoreId(storeId);
  1021. order.setMerchOrderSn(merchOrderSn);
  1022. //开启事务,插入订单信息和订单商品
  1023. if (order != null) {
  1024. orderDao.save(order);
  1025. if (null == order.getId()) {
  1026. resultObj.put("errno", 400);
  1027. resultObj.put("errmsg", "订单提交失败");
  1028. return resultObj;
  1029. }
  1030. for (OfflineCartEntity cartEntity : offlineCartEntityList) {
  1031. OrderGoodsEntity orderGoodsEntity = setOrderGoodsVo(order, cartEntity);
  1032. //新增订单详情
  1033. orderGoodsDao.save(orderGoodsEntity);
  1034. }
  1035. //清空预订单商品临时表
  1036. offlineCartDao.deleteByUserId(userId);
  1037. Map orderInfoMap = Maps.newHashMap();
  1038. orderInfoMap.put("orderInfo", order);
  1039. resultObj.put("errno", 0);
  1040. resultObj.put("errmsg", "订单提交成功");
  1041. resultObj.put("data", orderInfoMap);
  1042. }
  1043. } catch (Exception e) {
  1044. e.printStackTrace();
  1045. resultObj.put("errno", 400);
  1046. resultObj.put("errmsg", "订单异常");
  1047. return resultObj;
  1048. }
  1049. return resultObj;
  1050. }
  1051. /**
  1052. * 设置订单数据
  1053. *
  1054. * @param loginUser
  1055. * @return
  1056. */
  1057. public OrderEntity setOrderVo(SysUserEntity loginUser, List<OfflineCartEntity> offlineCartEntityList,
  1058. String merchSn) {
  1059. OrderEntity orderInfo = new OrderEntity();
  1060. BigDecimal freightPrice = new BigDecimal(0.00);
  1061. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  1062. for (OfflineCartEntity offlineCartEntity : offlineCartEntityList) {
  1063. goodsTotalPrice = goodsTotalPrice
  1064. .add(offlineCartEntity.getRetailPrice().multiply(new BigDecimal(offlineCartEntity.getNumber())));
  1065. }
  1066. //订单价格计算:订单的总价+运费
  1067. BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
  1068. //查询未使用的优惠券
  1069. /*String couponName = "";
  1070. BigDecimal fullCutCouponDec = Constant.ZERO;
  1071. UserCouponVo couponVo = null;*/
  1072. BigDecimal couponPrice = new BigDecimal(0.00);
  1073. //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
  1074. BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
  1075. //商户(拼音首字母)+业务类型+编号
  1076. // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
  1077. // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
  1078. MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
  1079. String merchShortName = "";
  1080. if (merchEntity != null) {
  1081. merchShortName = merchEntity.getMerchShortName();
  1082. }
  1083. String orderSn = merchShortName + Dict.orderBizType.item_11.getItem() + CommonUtil.generateOrderNumber();
  1084. orderInfo.setOrderSn(orderSn);
  1085. orderInfo.setMerchSn(merchSn);
  1086. orderInfo.setUserId(Integer.parseInt(loginUser.getUserId() + ""));
  1087. orderInfo.setFreightPrice(freightPrice.intValue());
  1088. orderInfo.setOrderBizType(Dict.orderBizType.item_11.getItem());
  1089. /*orderInfo.setCoupon_id(userCouponId);
  1090. orderInfo.setCoupon_name(couponName);*/
  1091. // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
  1092. orderInfo.setCouponPrice(couponPrice);
  1093. orderInfo.setPostscript("");//留言
  1094. orderInfo.setAddTime(new Date());
  1095. orderInfo.setGoodsPrice(goodsTotalPrice);
  1096. orderInfo.setOrderPrice(orderTotalPrice);
  1097. orderInfo.setActualPrice(actualPrice);
  1098. orderInfo.setOrderType("1");
  1099. orderInfo.setOrderStatus(0);// 待付款
  1100. orderInfo.setShippingStatus(0);
  1101. orderInfo.setPayStatus(0);
  1102. orderInfo.setShippingId(0L);
  1103. orderInfo.setShippingFee(Constant.ZERO);
  1104. orderInfo.setIntegral(0);
  1105. orderInfo.setIntegralMoney(Constant.ZERO);
  1106. orderInfo.setCreateTime(new Date());
  1107. orderInfo.setModTime(new Date());
  1108. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
  1109. /*//标记该订单已使用优惠券
  1110. if(couponVo != null){
  1111. couponVo.setUsed_time(new Date());
  1112. couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
  1113. apiUserCouponMapper.update(couponVo);
  1114. }*/
  1115. return orderInfo;
  1116. }
  1117. /**
  1118. * 设置订单数据
  1119. *
  1120. * @param
  1121. * @return
  1122. */
  1123. public OrderEntity setOrder(Integer userId, List<LinkedHashMap> goodsList,
  1124. String merchSn) {
  1125. OrderEntity orderInfo = new OrderEntity();
  1126. BigDecimal freightPrice = new BigDecimal(0.00);
  1127. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  1128. for (LinkedHashMap goods : goodsList) {
  1129. goodsTotalPrice = goodsTotalPrice
  1130. .add(new BigDecimal( goods.get("retailPrice").toString()).multiply(new BigDecimal( goods.get("sellVolume").toString())));
  1131. }
  1132. //订单价格计算:订单的总价+运费
  1133. BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
  1134. //查询未使用的优惠券
  1135. /*String couponName = "";
  1136. BigDecimal fullCutCouponDec = Constant.ZERO;
  1137. UserCouponVo couponVo = null;*/
  1138. BigDecimal couponPrice = new BigDecimal(0.00);
  1139. //减去其它支付的金额后,要实际支付的金额 订单的总价+运费-优惠券金额
  1140. BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
  1141. //商户(拼音首字母)+业务类型+编号
  1142. // String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
  1143. // String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
  1144. MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
  1145. String merchShortName = "";
  1146. if (merchEntity != null) {
  1147. merchShortName = merchEntity.getMerchShortName();
  1148. }
  1149. String orderSn = merchShortName + Dict.orderBizType.item_10.getItem() + CommonUtil.generateOrderNumber();
  1150. orderInfo.setOrderSn(orderSn);
  1151. orderInfo.setMerchSn(merchSn);
  1152. orderInfo.setUserId(userId);
  1153. orderInfo.setFreightPrice(freightPrice.intValue());
  1154. orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  1155. /*orderInfo.setCoupon_id(userCouponId);
  1156. orderInfo.setCoupon_name(couponName);*/
  1157. // orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
  1158. orderInfo.setCouponPrice(couponPrice);
  1159. orderInfo.setPostscript("");//留言
  1160. orderInfo.setAddTime(new Date());
  1161. orderInfo.setGoodsPrice(goodsTotalPrice);
  1162. orderInfo.setOrderPrice(orderTotalPrice);
  1163. orderInfo.setActualPrice(actualPrice);
  1164. orderInfo.setOrderType("1");
  1165. orderInfo.setOrderStatus(0);// 待付款
  1166. orderInfo.setShippingStatus(0);
  1167. orderInfo.setPayStatus(0);
  1168. orderInfo.setShippingId(0L);
  1169. orderInfo.setShippingFee(Constant.ZERO);
  1170. orderInfo.setIntegral(0);
  1171. orderInfo.setIntegralMoney(Constant.ZERO);
  1172. orderInfo.setCreateTime(new Date());
  1173. orderInfo.setModTime(new Date());
  1174. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
  1175. // orderInfo.setIsScan("0");//默认未扫描
  1176. /*//标记该订单已使用优惠券
  1177. if(couponVo != null){
  1178. couponVo.setUsed_time(new Date());
  1179. couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
  1180. apiUserCouponMapper.update(couponVo);
  1181. }*/
  1182. return orderInfo;
  1183. }
  1184. public OrderGoodsEntity setOrderGoodsVo(OrderEntity orderInfo, OfflineCartEntity goodsItem) {
  1185. GoodsEntity goodsVo = goodsDao.queryObject(goodsItem.getGoodsId());
  1186. OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
  1187. orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
  1188. orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
  1189. orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
  1190. orderGoodsVo.setProductId(goodsItem.getProductId());
  1191. orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
  1192. orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
  1193. orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
  1194. orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
  1195. orderGoodsVo.setNumber(goodsItem.getNumber());
  1196. orderGoodsVo.setOrderBizType(Dict.orderBizType.item_11.getItem());
  1197. orderGoodsVo.setCreateTime(new Date());
  1198. orderGoodsVo.setModTime(new Date());
  1199. orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
  1200. orderGoodsVo.setSku(goodsVo.getSku());
  1201. return orderGoodsVo;
  1202. }
  1203. // public OrderGoodsEntity setOrderGoods(OrderEntity orderInfo, LinkedHashMap goods) {
  1204. // GoodsEntity goodsVo = goodsDao.queryObject(goods.get("goodsId"));
  1205. // ProductEntity productEntity = productDao.queryObjectByGoodsIdAndStoreId(goodsVo.getId() + "", null);
  1206. // OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
  1207. // orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
  1208. // orderGoodsVo.setGoodsId(goodsVo.getId().intValue());
  1209. // orderGoodsVo.setGoodsSn(goodsVo.getGoodsSn());
  1210. // orderGoodsVo.setProductId(productEntity.getId().intValue());
  1211. // orderGoodsVo.setGoodsName(goodsVo.getName());
  1212. // orderGoodsVo.setListPicUrl(goodsVo.getListPicUrl());
  1213. //
  1214. //
  1215. // orderGoodsVo.setMarketPrice((BigDecimal) goods.get("storeMarketPrice"));
  1216. // orderGoodsVo.setRetailPrice((BigDecimal) goods.get("storeRetailPrice"));
  1217. // orderGoodsVo.setNumber((Integer) goods.get("sellVolume"));
  1218. // orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  1219. // orderGoodsVo.setCreateTime(new Date());
  1220. // orderGoodsVo.setModTime(new Date());
  1221. // orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
  1222. // orderGoodsVo.setSku(goodsVo.getSku());
  1223. //
  1224. //
  1225. // BigDecimal number = new BigDecimal(Long.valueOf(goodsItem.getNumber()));
  1226. // BigDecimal goodsTotal = goodsItem.getRetail_price().multiply(number);//单商品总价
  1227. // BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
  1228. // BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
  1229. // BigDecimal settlePrice = Constant.ZERO;
  1230. // if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  1231. // //运费-优惠券
  1232. // BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
  1233. // //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
  1234. // settlePrice = goodsTotal.add(rate.multiply(rateTotal));
  1235. // }else{
  1236. // if(orderInfo.getFreight_price()!=0){
  1237. // //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
  1238. // BigDecimal freightRate = rate.multiply(freightPrice);
  1239. // //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
  1240. // settlePrice = goodsTotal.add(freightRate);
  1241. // }
  1242. // if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  1243. // //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
  1244. // BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
  1245. // //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
  1246. // settlePrice = goodsTotal.subtract(couponRate);
  1247. // }
  1248. // }
  1249. // if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
  1250. // orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
  1251. // }else{
  1252. // orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
  1253. // }
  1254. //
  1255. // return orderGoodsVo;
  1256. // }
  1257. @Override
  1258. public OrderEntity queryObjectBySysUser(Long id) {
  1259. OrderEntity orderEntity = orderDao.queryObjectBySysUser(id);
  1260. Map<String, Object> map = new HashMap<String, Object>();
  1261. map.put("orderId", id);
  1262. List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
  1263. orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
  1264. return orderEntity;
  1265. }
  1266. @Override
  1267. public int confirmPay(Long id, String payFlag,String orderSnWx) {
  1268. SysUserEntity user = ShiroUtils.getUserEntity();
  1269. if (user == null) {
  1270. throw new RRException("用户登录超时,请重新登录");
  1271. }
  1272. if (!user.getRoleType().equalsIgnoreCase("2")) {
  1273. throw new RRException("该操作只允许店员账户操作");
  1274. }
  1275. OrderEntity orderEntity = queryObject(id);
  1276. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  1277. throw new RRException("此订单已付款!");
  1278. }
  1279. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
  1280. throw new RRException("此订单已完成!");
  1281. }
  1282. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  1283. throw new RRException("此订单已取消!");
  1284. }
  1285. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  1286. throw new RRException("此订单已删除!");
  1287. }
  1288. orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
  1289. orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
  1290. orderEntity.setPayFlag(payFlag);
  1291. orderEntity.setPayTime(new Date());
  1292. if(Dict.payFlag.item_alipay.getItem().equalsIgnoreCase(payFlag)){
  1293. orderEntity.setAliTradeNo(orderSnWx);
  1294. }else {
  1295. if (orderSnWx != null) {
  1296. orderEntity.setOrderSnWx(orderSnWx);
  1297. }
  1298. }
  1299. orderDao.update(orderEntity);
  1300. return 0;
  1301. }
  1302. @Override
  1303. public List<OrderEntity> queryExportList(Map<String, Object> map) {
  1304. List<OrderEntity> list = orderDao.queryExportList(map);
  1305. for (OrderEntity order : list) {
  1306. OrderProcessRecordEntity orderProcessRecord = orderProcessRecordDao.queryObjectByOrderSn(order.getOrderSn());
  1307. order.setOrderProcessRecord(orderProcessRecord);
  1308. }
  1309. return list;
  1310. }
  1311. @Override
  1312. public List<OrderEntity> queryOffilineOrderList(Map<String, Object> map) {
  1313. return orderDao.queryOffilineOrderList(map);
  1314. }
  1315. @Override
  1316. public int uploadExcel(List<OrderExpressDto> orderExpressDtoList) {
  1317. SysUserEntity user = ShiroUtils.getUserEntity();
  1318. boolean isFail = false;
  1319. List<String> failShippingNameList = new ArrayList<>();
  1320. List<String> failOrderSnList = new ArrayList<>();
  1321. List<String> failShippingCodeList = new ArrayList<>();
  1322. List<String> failCodeSnList = new ArrayList<>();
  1323. List<String> failNameSnList = new ArrayList<>();
  1324. List<String> failStatusOrderSnList = new ArrayList<>();
  1325. if (orderExpressDtoList != null && orderExpressDtoList.size() > 0) {
  1326. for (int i = 0; i < orderExpressDtoList.size(); i++) {
  1327. OrderExpressDto orderExpressDto = orderExpressDtoList.get(i);
  1328. OrderEntity orderEntity = new OrderEntity();
  1329. Map<String, Object> valideDate = MapBeanUtil.fromObject(orderExpressDto);
  1330. ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
  1331. builder.put("orderSn", "订单编号");
  1332. builder.put("shippingNo", "快递单号");
  1333. builder.put("shippingName", "快递公司");
  1334. builder.put("shippingCode", "快递简写");
  1335. R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
  1336. if (Integer.valueOf(r.get("code").toString()) != 0) {
  1337. throw new RRException(r.get("msg").toString());
  1338. } else {
  1339. r = ValidatorUtil.isEmpty(builder.build(), valideDate);
  1340. if (Integer.valueOf(r.get("code").toString()) != 0) {
  1341. throw new RRException(r.get("msg").toString());
  1342. }
  1343. }
  1344. OrderEntity order = orderDao.queryObjectByOrderSn(orderExpressDto.getOrderSn());
  1345. if(order == null){
  1346. isFail = true;
  1347. failOrderSnList.add(orderExpressDto.getOrderSn());
  1348. }else{
  1349. if(!(order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())
  1350. && order.getPayStatus() == Integer.parseInt(Dict.payStatus.item_2.getItem()))){
  1351. isFail = true;
  1352. failStatusOrderSnList.add(orderExpressDto.getOrderSn());
  1353. }
  1354. }
  1355. ShippingEntity shippingEntity = shippingDao.queryObjectByCode(orderExpressDto.getShippingCode());
  1356. if(shippingEntity == null){
  1357. isFail = true;
  1358. failShippingCodeList.add(orderExpressDto.getShippingCode());
  1359. failCodeSnList.add(orderExpressDto.getOrderSn());
  1360. }else{
  1361. if(!orderExpressDto.getShippingName().equalsIgnoreCase(shippingEntity.getName())){
  1362. isFail = true;
  1363. failShippingNameList.add(orderExpressDto.getShippingName());
  1364. failNameSnList.add(orderExpressDto.getOrderSn());
  1365. }
  1366. }
  1367. if(!isFail){//false则有错误的数据
  1368. if(order != null) {// 修改商品
  1369. // orderEntity.setOrderSn(orderExpressDto.getOrderSn());
  1370. orderEntity.setShippingNo(orderExpressDto.getShippingNo());
  1371. orderEntity.setShippingCode(orderExpressDto.getShippingCode());
  1372. orderEntity.setShippingName(orderExpressDto.getShippingName());
  1373. orderEntity.setShippingStatus(Integer.parseInt(Dict.shippingStatus.item_1.getItem()));
  1374. orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_300.getItem()));
  1375. orderEntity.setModerSn(user.getUsername());
  1376. orderEntity.setCreateTime(new Date());
  1377. orderEntity.setModTime(new Date());
  1378. orderEntity.setId(order.getId());
  1379. orderDao.update(orderEntity);
  1380. }
  1381. }
  1382. }
  1383. if(failOrderSnList != null && failOrderSnList.size() > 0){
  1384. throw new RRException("导入数据异常,订单编号不存在,不存在的订单编号【"+failOrderSnList+"】,请删除掉再继续操作");
  1385. }
  1386. if(failStatusOrderSnList != null && failStatusOrderSnList.size() > 0){
  1387. throw new RRException("导入数据异常,修改订单快递功能只支持已付款未发货的订单,以下订单编号无效【"+failStatusOrderSnList+"】,请删除掉再继续操作");
  1388. }
  1389. if(failShippingCodeList != null && failShippingCodeList.size() > 0){
  1390. throw new RRException("导入数据异常,快递简写不在可支持的范围中,简写错误的订单编号【"+failCodeSnList+"】,错误的快递简写【"+failShippingCodeList+"】," +
  1391. "正确数据可下载订单页面的快递公司简写Excel中查看");
  1392. }
  1393. if(failShippingNameList != null && failShippingNameList.size() > 0){
  1394. throw new RRException("导入数据异常,快递简写对应的快递公司不一致,快递公司错误的订单编号【"+failNameSnList+"】,请修改Excel数据中订单编号对应的快递公司错误信息," +
  1395. "正确数据可下载订单页面的快递公司简写Excel中查看");
  1396. }
  1397. // if(failFreightGoodsSnList != null && failFreightGoodsSnList.size() > 0){
  1398. // exportExceptionDataEntity.setExportExceptionData("运费信息请在商城配置》运费模板中维护,运费与商户信息对应,请检查该商品商户信息下的运费是否维护,不存在的商品编码【"+failFreightGoodsSnList+"】,运费【"+failFreightList+"】");
  1399. // exportExceptionDataDao.save(exportExceptionDataEntity);
  1400. // throw new RRException("导入数据异常,异常信息请在商品管理》》商品导入异常数据中查看检查");
  1401. // }
  1402. }else{
  1403. throw new RRException("导入数据为空,或者检查商品编码数据是否为空");
  1404. }
  1405. return 1;
  1406. }
  1407. @Override
  1408. public List<OrderEntity> promOrderList(Map<String, Object> map) {
  1409. Integer[] statusList = {201};
  1410. List<OrderEntity> list = orderDao.promOrderList(map);
  1411. for (OrderEntity orderEntity: list) {
  1412. Map<String, Object> queryMap = new HashMap<>();
  1413. queryMap.put("goodsId", orderEntity.getGoodsId());
  1414. queryMap.put("statusList", statusList);
  1415. queryMap.put("orderId", orderEntity.getId());
  1416. Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
  1417. if(promActualPrice == null){
  1418. promActualPrice = 0d;
  1419. }
  1420. orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
  1421. }
  1422. return list;
  1423. }
  1424. @Override
  1425. public int queryPromOrderTotal(Map<String, Object> map) {
  1426. return orderDao.queryPromOrderTotal(map);
  1427. }
  1428. @Override
  1429. public List<OrderEntity> promOrderListExport(Map<String, Object> map){
  1430. Integer[] statusList = {201};
  1431. List<OrderEntity> list = orderDao.promOrderListExport(map);
  1432. for (OrderEntity orderEntity: list) {
  1433. Map<String, Object> queryMap = new HashMap<>();
  1434. queryMap.put("goodsId", orderEntity.getGoodsId());
  1435. queryMap.put("orderId", orderEntity.getId());
  1436. queryMap.put("statusList", statusList);
  1437. Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
  1438. if(promActualPrice == null){
  1439. promActualPrice = 0d;
  1440. }
  1441. orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
  1442. }
  1443. return list;
  1444. }
  1445. @Override
  1446. public List<OrderEntity> storeTopicOrderList(Map<String, Object> map) {
  1447. List<OrderEntity> list = orderDao.storeTopicOrderList(map);
  1448. return list;
  1449. }
  1450. @Override
  1451. public int queryStoreTopicOrderTotal(Map<String, Object> map) {
  1452. return orderDao.queryStoreTopicOrderTotal(map);
  1453. }
  1454. @Override
  1455. public List<WxOrderEntity> wxOrderResendQueryAllList(Map<String, Object> map){
  1456. // String requestData = JacksonUtil.toJson(map);
  1457. String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl();
  1458. // 同步访问,返回结果字符串
  1459. String response = OkHttpUtils.post(map, url, "SSL");
  1460. ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
  1461. if(responseData.getCode().equalsIgnoreCase("0")){
  1462. List<WxOrderEntity> list = responseData.getData().getRows();
  1463. return list;
  1464. }
  1465. return null;
  1466. }
  1467. @Override
  1468. public List<OrderRecognitionDto> queryOrderListByRecognition(Map<String, Object> map){
  1469. String value = sysConfigDao.queryByKey("FACE_COLLECT_FREQUENCY_TIME");
  1470. if(value==null){
  1471. throw new RRException("请联系管理员配系统参数置FACE_COLLECT_FREQUENCY_TIME信息!");
  1472. }
  1473. List<OrderRecognitionDto> list = orderDao.queryOrderListByRecognition(map);
  1474. for (OrderRecognitionDto orderRecognitionDto: list){
  1475. Integer frequencySecondTime = Integer.parseInt(value);
  1476. String lastFaceTime = orderRecognitionDto.getLastFaceTime();
  1477. if(StringUtils.isNotEmpty(lastFaceTime)) {
  1478. Date lastFaceDate = DateUtils.convertStringToDate(lastFaceTime, DateUtils.DATE_TIME_PATTERN);
  1479. Calendar calendar = Calendar.getInstance();
  1480. calendar.setTime(lastFaceDate);
  1481. calendar.add(Calendar.SECOND, frequencySecondTime);
  1482. Date addSecondTime = calendar.getTime();
  1483. Date nowDate = new Date();
  1484. if (addSecondTime.getTime() > nowDate.getTime()) {
  1485. orderRecognitionDto.setAddSecondTime(DateUtils.format(addSecondTime,DateUtils.DATE_TIME_PATTERN));
  1486. orderRecognitionDto.setIsDateLast("false");
  1487. } else {
  1488. //可调用身份验证范围内
  1489. orderRecognitionDto.setIsDateLast("true");
  1490. }
  1491. }else{//可调用身份验证范围内
  1492. orderRecognitionDto.setIsDateLast("true");
  1493. }
  1494. }
  1495. return list;
  1496. }
  1497. @Override
  1498. public int queryOrderListByRecognitionTotal(Map<String, Object> map){
  1499. return orderDao.queryOrderListByRecognitionTotal(map);
  1500. }
  1501. /**
  1502. * 提交订单并付款
  1503. *
  1504. * @param param
  1505. * @param user
  1506. * @return
  1507. */
  1508. @Override
  1509. @Transactional
  1510. public Map offlineRetailSubmit(Map param, SysUserEntity user) {
  1511. // 解析订单数据 List
  1512. List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
  1513. // 解析用户信息 LinkedHashMap
  1514. Map userInfo = (Map) param.get("userInfo");
  1515. // 解析支付码 String
  1516. String parCode = (String) param.get("payCode");
  1517. // 解析sessionId(WebSocket) String
  1518. String sessionId = (String) param.get("sessionId");
  1519. // machineCode
  1520. String machineCode = (String) param.get("machineCode");
  1521. Map resultObj = Maps.newHashMap();
  1522. try {
  1523. if (user == null) {
  1524. resultObj.put("errno", 400);
  1525. resultObj.put("errmsg", "用户登录超时,请重新登录");
  1526. return resultObj;
  1527. }
  1528. if (!user.getRoleType().equalsIgnoreCase("2")) {
  1529. resultObj.put("errno", 400);
  1530. resultObj.put("errmsg", "该操作只允许店员账户操作");
  1531. return resultObj;
  1532. }
  1533. if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
  1534. resultObj.put("errno", 400);
  1535. resultObj.put("errmsg", "操作用户的商户编号为空,请先维护用户商户编号信息再来操作");
  1536. return resultObj;
  1537. }
  1538. Long userId = user.getUserId();
  1539. Integer storeId = user.getStoreId();
  1540. List<GoodsEntity> goodsEntities = new ArrayList<>();
  1541. // 检查库存和更新库存
  1542. for (LinkedHashMap goodsDto : goodsList) {
  1543. //
  1544. GoodsEntity goodsEntity = goodsDao.queryObjectByProdBarcodeAndStore((String) goodsDto.get("prodBarcode"),storeId);
  1545. if (goodsEntity == null) {
  1546. resultObj.put("errno", 400);
  1547. resultObj.put("errmsg", "订单提交失败:商品不存在");
  1548. return resultObj;
  1549. }
  1550. Integer sellVolume = (Integer)goodsDto.get("sellVolume");
  1551. goodsDto.put("goodsId",goodsEntity.getId());
  1552. goodsDto.put("goodsSn",goodsEntity.getGoodsSn());
  1553. goodsDto.put("productId",goodsEntity.getProductId());
  1554. goodsDto.put("storeMarketPrice",goodsEntity.getStoreMarketPrice());
  1555. goodsDto.put("storeRetailPrice",goodsEntity.getStoreRetailPrice());
  1556. //取得规格的信息,判断规格库存
  1557. ProductStoreRelaEntity productInfo = productStoreRelaDao
  1558. .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsEntity.getId()));
  1559. synchronized (productInfo) {
  1560. if (null == productInfo || null == productInfo.getStockNum() ||
  1561. productInfo.getStockNum() < (sellVolume)) {
  1562. resultObj.put("errno", 400);
  1563. resultObj.put("errmsg", "库存不足,仅剩余" + productInfo.getStockNum());
  1564. return resultObj;
  1565. } else {
  1566. // TODO 判断销售价是否低于底线价
  1567. productInfo.setStockNum(productInfo.getStockNum() - sellVolume);
  1568. productInfo.setStoreId(Long.valueOf(storeId));
  1569. productInfo.addSellVolume();
  1570. productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存
  1571. if(goodsEntity != null) {
  1572. goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - sellVolume);
  1573. goodsDao.update(goodsEntity);
  1574. }
  1575. }
  1576. // 借用这个字段来存储购买数
  1577. goodsEntity.setGoodsNumber(sellVolume);
  1578. goodsEntities.add(goodsEntity);
  1579. }
  1580. }
  1581. UserEntity userEntity = userDao.queryByMobile((String) userInfo.get("customPhone"));
  1582. if(userEntity == null) {
  1583. // 保存用户信息
  1584. userEntity = new UserEntity();
  1585. userEntity.setUsername((String) userInfo.get("customName"));
  1586. userEntity.setPassword("");
  1587. userEntity.setIdNo((String) userInfo.get("customIDCard"));
  1588. userEntity.setMobile((String) userInfo.get("customPhone"));
  1589. userEntity.setGender(1);
  1590. userEntity.setRegisterTime(new Date());
  1591. userEntity.setLastLoginTime(new Date());
  1592. userEntity.setIdNo((String) userInfo.get("customIDCard"));
  1593. userDao.save(userEntity);
  1594. }
  1595. // 优惠金额
  1596. BigDecimal disCountAmount = new BigDecimal(0);
  1597. // 活动id
  1598. Integer topicId = 0;
  1599. // 查询活动类别id
  1600. MkStorePromTypeEntity mkStorePromEntity = storePromTypeDao.queryByName("周活动");
  1601. // 根据门店id和活动类别查询该门店是否有活动
  1602. StoreTopicEntity storeTopic = storeTopicDao.queryByStoreIdAndType(storeId,mkStorePromEntity.getPromTypeId());
  1603. // 判断是否启用了活动,如果启用了活动。则去查询活动价
  1604. if(storeTopic != null){
  1605. for(GoodsEntity goodsEntity :goodsEntities){
  1606. // 根据活动id跟商品id,查询该商品的价格
  1607. Mk2GoodsTopicPriceEntity goodsTopicPriceEntity =
  1608. mk2GoodsTopicPriceDao.queryByTopicIdAndGoodsId(storeTopic.getId(),goodsEntity.getSku());
  1609. if (goodsEntity.getStoreRetailPrice().compareTo(goodsTopicPriceEntity.getTopicPrice()) <= -1) {
  1610. LOGGER.error("销售价格小于活动价格");
  1611. throw new RuntimeException("商品"+goodsEntity.getName()+"的销售价格小于活动价格");
  1612. }
  1613. goodsEntity.setStoreRetailPrice(goodsTopicPriceEntity.getTopicPrice());
  1614. }
  1615. }else{
  1616. disCountAmount = getDisCountAmout(goodsEntities);
  1617. }
  1618. // 判断该用户是否是生日
  1619. Boolean isBirth = false;
  1620. String birthday = "";
  1621. if(userEntity.getIdNo().length() == 15){
  1622. birthday = userEntity.getIdNo().substring(8,10) + "-" + userEntity.getIdNo().substring(10,12);
  1623. }else if(userEntity.getIdNo().length() == 18){
  1624. birthday = userEntity.getIdNo().substring(10,12) + "-" + userEntity.getIdNo().substring(12,14);
  1625. }
  1626. SimpleDateFormat format = new SimpleDateFormat("MM-dd");
  1627. String today = format.format(new Date());
  1628. if(birthday.equalsIgnoreCase(today)){
  1629. isBirth = true;
  1630. }
  1631. // 生成订单
  1632. String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
  1633. OrderVo order = setOrderVo(goodsEntities, userEntity,storeId.longValue(), user.getMerchSn(),disCountAmount);
  1634. order.setStore_id(storeId.longValue());
  1635. if(storeTopic != null){
  1636. order.setActivity_id(storeTopic.getId().longValue());
  1637. }
  1638. order.setMerchOrderSn(merchOrderSn);
  1639. //插入订单信息和订单商品
  1640. orderDao.saveOrderVo(order);
  1641. // TODO 订单流转表
  1642. OrderProcessRecordEntity processRecordEntity = new OrderProcessRecordEntity();
  1643. processRecordEntity.setOrderSn(order.getOrder_sn());
  1644. processRecordEntity.setUserId(Integer.valueOf(userEntity.getId()+""));
  1645. processRecordEntity.setAddOrderStartTime(order.getCreateTime());
  1646. processRecordEntity.setIsAddOrderSend(Dict.isSend.item_1.getItem());
  1647. processRecordEntity.setOrderBizType(Dict.orderBizType.item_10.getItem());
  1648. if (null == order.getId()) {
  1649. resultObj.put("errno", 400);
  1650. resultObj.put("errmsg", "订单提交失败");
  1651. return resultObj;
  1652. }
  1653. for (GoodsEntity goodsDto : goodsEntities) {
  1654. OrderGoodsVo orderGoodsVo = setOrderGoodsVo(order,goodsDto);
  1655. //新增订单详情
  1656. orderGoodsDao.saveOrderGoodsVo(orderGoodsVo);
  1657. }
  1658. //清空预订单商品临时表
  1659. Map orderInfoMap = Maps.newHashMap();
  1660. orderInfoMap.put("orderInfo", order);
  1661. resultObj.put("errno", 0);
  1662. resultObj.put("errmsg", "订单提交成功");
  1663. resultObj.put("data", orderInfoMap);
  1664. //判断支付类型,并支付订单
  1665. R r = null;
  1666. //保存支付记录
  1667. OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecordVo(order);
  1668. StoreEntity store = storeService.queryObject(order.getStore_id().intValue());
  1669. // 设置支付单开始时间
  1670. processRecordEntity.setPaymentStartTime(new Date());
  1671. // 微信支付
  1672. // wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
  1673. // 支付宝支付
  1674. // AliPay(user, parCode , order, processRecordEntity, orderWXPayRecordCurrent, store);
  1675. resultObj.put("shopName",store.getStoreName()); // 根据门店编号查询
  1676. resultObj.put("userName",user.getUsername());
  1677. // 保存订单流转表
  1678. // 设置下单完成时间
  1679. processRecordEntity.setAddOrderSuccTime(order.getPay_time());
  1680. orderProcessRecordDao.save(processRecordEntity);
  1681. // 生成取票码
  1682. PickUpCodeEntity pickUpCodeEntity = new PickUpCodeEntity();
  1683. pickUpCodeEntity.setOrderSn(order.getOrder_sn());
  1684. pickUpCodeService.save(pickUpCodeEntity);
  1685. // 生成销售记录
  1686. SaleRecordEntity saleRecordEntity = new SaleRecordEntity();
  1687. // 根据收银机机器码,查询收银机
  1688. CashierEntity cashierEntity = cashierDao.queryByMachineCode(machineCode);
  1689. if(cashierEntity != null){
  1690. saleRecordEntity.setCashierSn(cashierEntity.getCashierSn());
  1691. saleRecordEntity.setOrderSn(order.getOrder_sn());
  1692. saleRecordEntity.setSallerId(userId+"");
  1693. saleRecordEntity.setSalesTime(new Date());
  1694. saleRecordEntity.setDiscountId(topicId + "");
  1695. saleRecordEntity.setCreateTime(new Date());
  1696. saleRecordDao.save(saleRecordEntity);
  1697. }
  1698. // 查询积分规则 ,默认先按消费金额1:1积分
  1699. Mall2PointsRulesEntity pointsRules = null;
  1700. // 增加该会员的积分
  1701. Mall2MemberPointsEntity memberPointsEntity = memberPointsDao.queryByUserId(userEntity.getId());
  1702. if(memberPointsEntity == null){
  1703. memberPointsEntity = new Mall2MemberPointsEntity();
  1704. memberPointsEntity.setUserId(userEntity.getId()+"");
  1705. memberPointsEntity.setPoints(order.getActual_price().intValue());
  1706. memberPointsEntity.setCreaterSn(userId+"");
  1707. memberPointsEntity.setCreateTime(new Date());
  1708. memberPointsDao.save(memberPointsEntity);
  1709. }else{
  1710. memberPointsEntity.setPoints(order.getActual_price().add(new BigDecimal(memberPointsEntity.getPoints())).intValue());
  1711. memberPointsEntity.setModerSn(userId+"");
  1712. memberPointsEntity.setModTime(new Date());
  1713. memberPointsDao.update(memberPointsEntity);
  1714. }
  1715. // 增加该会员的消费记录
  1716. Mall2MemberConsumptionRecordsEntity consumptionRecords = new Mall2MemberConsumptionRecordsEntity();
  1717. consumptionRecords.setUserId(userEntity.getId()+"");
  1718. consumptionRecords.setOrderSn(order.getOrder_sn());
  1719. consumptionRecords.setConsumptionTime(new Date());
  1720. consumptionRecords.setShopSn(storeId+"");
  1721. // TODO 判断是否有使用生日优惠
  1722. if(isBirth){
  1723. consumptionRecords.setIsUseBirthdayOffer("0"); // 使用生日优惠
  1724. }else{
  1725. consumptionRecords.setIsUseBirthdayOffer("1"); // 没使用生日优惠
  1726. }
  1727. consumptionRecords.setCreaterSn(userId+"");
  1728. consumptionRecords.setCreateTime(new Date());
  1729. memberConsumptionRecordsDao.save(consumptionRecords);
  1730. resultObj.put("code",pickUpCodeEntity.getPickUpCodeSn()); // 系统中累加
  1731. resultObj.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  1732. resultObj.put("orderNo",order.getOrder_sn()); //
  1733. // 通知WebSocket
  1734. WebSocketServer.sendMessage(sessionId,order.getOrder_sn(),order.getStore_id()
  1735. +"");
  1736. } catch (Exception e) {
  1737. e.printStackTrace();
  1738. resultObj.put("errno", 400);
  1739. resultObj.put("errmsg", "订单异常------"+e.getMessage());
  1740. throw new RuntimeException(e);
  1741. }
  1742. return resultObj;
  1743. }
  1744. private BigDecimal getDisCountAmout(List<GoodsEntity> goodsEntities) {
  1745. BigDecimal disCountAmount;
  1746. // TODO 生成订单之前,先查询是否有优惠券或者满减
  1747. // TODO 20200610 要修改成全部商品
  1748. // 优惠券的集合
  1749. List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntities = new ArrayList<>();
  1750. // 满减的集合
  1751. List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntities = new ArrayList<>();
  1752. // 存商品跟金额的关系
  1753. Map<Long,BigDecimal> moneyMap = new HashMap<>();
  1754. // 商品总价
  1755. BigDecimal totalPrice = new BigDecimal(0);
  1756. for(GoodsEntity goodsEntity : goodsEntities){
  1757. Long goodsId = goodsEntity.getId();
  1758. // 计算该商品的价格
  1759. BigDecimal goodsPrice = goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber())).setScale(2, RoundingMode.HALF_UP);
  1760. moneyMap.put(goodsId,goodsPrice);
  1761. totalPrice = totalPrice.add(goodsPrice);
  1762. // 查询该商品id是否有优惠券
  1763. List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountEntity = mkStoreTicketDiscountService.queryByGoodsId(goodsId);
  1764. if(mkStoreTicketDiscountEntity != null) {
  1765. mkStoreTicketDiscountEntities.addAll(mkStoreTicketDiscountEntity);
  1766. }
  1767. // 查询该商品id是否有满减
  1768. List<MkStoreCampMinusLevelEntity> mkStoreCampMinusEntity = mkStoreCampMinusService.queryByGoodsId(goodsId);
  1769. if(mkStoreCampMinusEntity != null) {
  1770. mkStoreCampMinusEntities.addAll(mkStoreCampMinusEntity);
  1771. }
  1772. }
  1773. // 满减优惠的金额
  1774. BigDecimal campDisCountAmount = new BigDecimal(0);
  1775. if(mkStoreCampMinusEntities.size() > 0){
  1776. // 上一次所需金额,用于取最大的优惠力度
  1777. BigDecimal lastAmount = new BigDecimal(0);
  1778. for (int i = 0 ; i < mkStoreCampMinusEntities.size() ; i++){
  1779. MkStoreCampMinusLevelEntity mkStoreCampMinusLevelEntity = mkStoreCampMinusEntities.get(i);
  1780. // TODO 20200610还有满多少件,跟满多少元打折的,逻辑复杂,下次开发
  1781. BigDecimal discCond = mkStoreCampMinusLevelEntity.getYuanMinusCond();
  1782. // 判断这次金额是否大于上次金额,如果不大于,直接continue
  1783. if(discCond.compareTo(lastAmount) > 0){
  1784. // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
  1785. if(totalPrice.compareTo(discCond) > 0){
  1786. // 记录上一次金额
  1787. lastAmount = discCond;
  1788. campDisCountAmount = mkStoreCampMinusLevelEntity.getYuanMinusPref();
  1789. }
  1790. }
  1791. }
  1792. }
  1793. // 优惠券优惠的金额
  1794. BigDecimal ticketDisCountAmount = new BigDecimal(0);
  1795. if(mkStoreTicketDiscountEntities.size() > 0){
  1796. // 上一次所需金额,用于取最大的优惠力度
  1797. BigDecimal lastAmount = new BigDecimal(0);
  1798. for (int i = 0 ; i < mkStoreTicketDiscountEntities.size() ; i++){
  1799. MkStoreTicketDiscountEntity mkStoreTicketDiscountEntity = mkStoreTicketDiscountEntities.get(i);
  1800. // 代金券所需金额
  1801. // TODO 20200610还有折扣券的,逻辑较为复杂,下次在开发
  1802. BigDecimal discCond = mkStoreTicketDiscountEntity.getVoucherCond();
  1803. // 判断这次金额是否大于上次金额,如果不大于,直接continue
  1804. if(discCond.compareTo(lastAmount) > 0){
  1805. // 如果总金额大于所需金额,则可以使用该优惠券,记录该优惠券的角标,金额跟优惠的钱
  1806. if(totalPrice.compareTo(discCond) > 0){
  1807. // 记录上一次金额
  1808. lastAmount = discCond;
  1809. ticketDisCountAmount = mkStoreTicketDiscountEntity.getVoucherMoney();
  1810. }
  1811. }
  1812. }
  1813. }
  1814. disCountAmount = ticketDisCountAmount.compareTo(campDisCountAmount) > 0 ? ticketDisCountAmount : campDisCountAmount;
  1815. return disCountAmount;
  1816. }
  1817. private void AliPay(SysUserEntity user, String parCode, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws Exception {
  1818. AliPayRequestParams params = new AliPayRequestParams();
  1819. params.setAuthCode(parCode);
  1820. params.setBody(order.getApprovalRemark());
  1821. params.setOutTradeNo(order.getOrder_sn());
  1822. params.setSubject("CW下单");
  1823. params.setStoreId(store.getId()+"");
  1824. params.setTotalAmount(order.getActual_price().setScale(2,BigDecimal.ROUND_HALF_UP)+"");
  1825. LOGGER.info("调用阿里支付接口的请求参数:"+JacksonUtils.toJson(params));
  1826. AliPayMicropayApiResult aliPayMicropayApiResult = AliPayUtil.aliTradePay(params);
  1827. orderWXPayRecordService.updateRecordByAli(orderWXPayRecordCurrent.getId(), aliPayMicropayApiResult);
  1828. LOGGER.info("调用阿里支付接口的同步返回结果:"+JacksonUtils.toJson(aliPayMicropayApiResult));
  1829. // 修改订单状态
  1830. //当支付成功时,修改订单,并把其他支付记录撤销
  1831. if (AliPayUtil.AliPayTradeState.SUCC.getCode().equals(aliPayMicropayApiResult.getCode())) {
  1832. // //查询当前订单所有的支付记录
  1833. // List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
  1834. // orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
  1835. this.confirmPay(order.getId(), Dict.payFlag.item_alipay.getItem(), aliPayMicropayApiResult.getTradeNo());
  1836. // 设置支付单完成时间
  1837. processRecordEntity.setPaymentSuccTime(aliPayMicropayApiResult.getGmtPayment());
  1838. processRecordEntity.setPayTransactionId(aliPayMicropayApiResult.getTradeNo());
  1839. // 系统繁忙
  1840. } else if(AliPayUtil.AliPayTradeState.SERVER_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())){
  1841. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1842. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请稍后再试");
  1843. // 支付失败
  1844. }else if(AliPayUtil.AliPayTradeState.BUSINESS_FAIL.getCode().equals(aliPayMicropayApiResult.getCode())){
  1845. // 系统异常
  1846. if(AliPayUtil.BusinessFailState.SYSTEM_ERROR.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1847. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1848. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请稍后再试");
  1849. // 订单总额超过限额
  1850. }else if(AliPayUtil.BusinessFailState.TOTAL_FEE_EXCEED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1851. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1852. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请告知顾客");
  1853. // 授权码无效
  1854. }else if(AliPayUtil.BusinessFailState.PAYMENT_AUTH_CODE_INVALID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1855. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1856. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请顾客刷新条码后,重新支付");
  1857. // 交易信息被篡改
  1858. }else if(AliPayUtil.BusinessFailState.CONTEXT_INCONSISTENT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1859. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1860. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试");
  1861. // 余额支付功能关闭
  1862. }else if(AliPayUtil.BusinessFailState.ERROR_BALANCE_PAYMENT_DISABLE.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1863. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1864. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户打开余额支付");
  1865. // 交易买家不匹配
  1866. }else if(AliPayUtil.BusinessFailState.TRADE_BUYER_NOT_MATCH.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1867. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1868. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试");
  1869. // 买家状态非法
  1870. }else if(AliPayUtil.BusinessFailState.BUYER_ENABLE_STATUS_FORBID.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1871. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1872. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家联系支付宝小二,确认为什么非法");
  1873. // 唤起移动收银台失败
  1874. }else if(AliPayUtil.BusinessFailState.PULL_MOBILE_CASHIER_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1875. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1876. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户刷新条码后,重新支付");
  1877. // 用户的无限支付开关关闭
  1878. }else if(AliPayUtil.BusinessFailState.MOBILE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1879. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1880. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请用户在PC上打开无线支付开关后,在发起支付");
  1881. // 支付失败
  1882. }else if(AliPayUtil.BusinessFailState.PAYMENT_FAIL.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1883. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1884. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请重试");
  1885. // 商户账号被冻结
  1886. }else if(AliPayUtil.BusinessFailState.SELLER_BEEN_BLOCKED.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1887. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1888. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请联系支付宝小二解冻");
  1889. // 买家未通过人行认证
  1890. }else if(AliPayUtil.BusinessFailState.ERROR_BUYER_CERTIFY_LEVEL_LIMIT.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1891. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1892. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家联系支付宝小二");
  1893. // 用户当面付付款开关管壁
  1894. }else if(AliPayUtil.BusinessFailState.USER_FACE_PAYMENT_SWITCH_OFF.getCode().equalsIgnoreCase(aliPayMicropayApiResult.getSubCode())){
  1895. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1896. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+",请买家打开当面付付款开关");
  1897. }else{
  1898. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1899. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg());
  1900. }
  1901. // 其他支付异常状态
  1902. } else {
  1903. LOGGER.info(aliPayMicropayApiResult.getSubMsg());
  1904. throw new RuntimeException(aliPayMicropayApiResult.getSubMsg()+"...........请联系管理员");
  1905. }
  1906. }
  1907. private void wxPay(SysUserEntity user, String parCode, Map resultObj, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws ParseException {
  1908. R r;
  1909. WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
  1910. .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), order.getOrderBizType(), null,
  1911. orderWXPayRecordCurrent.getOutTradeNoWX(), order.getActual_price().doubleValue(),
  1912. "127.0.0.1", parCode);
  1913. orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);
  1914. resultObj.put("shopName",store.getStoreName()); // 根据门店编号查询
  1915. resultObj.put("userName",user.getUsername());
  1916. // 修改订单状态
  1917. //当支付成功时,修改订单,并把其他支付记录撤销
  1918. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  1919. //查询当前订单所有的支付记录
  1920. List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
  1921. orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
  1922. for (OrderWXPayRecordEntity orderWXPayRecordTemp : orderWXPayRecordEntitys) {
  1923. //查询出来的记录排除当前已支付成功的记录,对其他记录交易状态为未撤销,未关闭的订单,调用撤销订单
  1924. if (orderWXPayRecordTemp.getId() != orderWXPayRecordCurrent.getId() &&
  1925. (!WechatUtil.WXTradeState.REVOKED.getCode().equals(orderWXPayRecordTemp.getTradeState()) ||
  1926. !WechatUtil.WXTradeState.CLOSED.getCode().equals(orderWXPayRecordTemp.getTradeState()))) {
  1927. WechatReverseApiResult wechatReverseApiResult =
  1928. WechatUtil.wxReverse(orderWXPayRecordTemp.getOutTradeNoWX());
  1929. //撤销订单成功
  1930. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
  1931. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
  1932. //调用订单查询接口
  1933. WechatRefundApiResult wechatRefundApiResult =
  1934. WechatUtil.wxOrderQuery(orderWXPayRecordTemp.getOutTradeNoWX());
  1935. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
  1936. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
  1937. // 修改订单支付记录
  1938. orderWXPayRecordService
  1939. .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
  1940. }
  1941. }
  1942. }
  1943. }
  1944. this.confirmPay(order.getId(), Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());
  1945. // 设置支付单完成时间
  1946. processRecordEntity.setPaymentSuccTimeStr(wechatMicropayApiResult.getTime_end());
  1947. processRecordEntity.setPaymentSuccTime(
  1948. new SimpleDateFormat("yyyyMMddHHmmss").parse(wechatMicropayApiResult.getTime_end()));
  1949. processRecordEntity.setPayTransactionId(wechatMicropayApiResult.getTransaction_id());
  1950. //用户支付中
  1951. } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  1952. r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
  1953. //用户支付失败
  1954. } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  1955. WechatReverseApiResult wechatReverseApiResult =
  1956. WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
  1957. //撤销订单成功
  1958. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
  1959. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
  1960. //调用订单查询接口
  1961. WechatRefundApiResult wechatRefundApiResult =
  1962. WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
  1963. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
  1964. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
  1965. // 修改订单支付记录
  1966. orderWXPayRecordService
  1967. .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
  1968. }
  1969. r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
  1970. } else {
  1971. r = R.error(wechatReverseApiResult.getErr_code_des());
  1972. }
  1973. }
  1974. }
  1975. @Override
  1976. public OrderEntity queryObjectByOrderSn(String orderSn) {
  1977. return orderDao.queryObjectByOrderSn(orderSn);
  1978. }
  1979. @Override
  1980. public void orderRefund(OrderEntity order, String sessionId) throws Exception {
  1981. boolean needUpdateStock = true;
  1982. if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  1983. order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
  1984. }
  1985. if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
  1986. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
  1987. }else{
  1988. AliPayMicropayApiResult userRefund = AliPayUtil.aliTradeRefund(order.getMerchOrderSn(), "38.81",
  1989. "用户退款", order.getStoreId() + "");
  1990. LOGGER.info(userRefund.getSubMsg());
  1991. order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
  1992. OrderRefundEntity orderRefund = new OrderRefundEntity();
  1993. orderRefund.setRefundId(userRefund.getTradeNo());
  1994. orderRefund.setOutRefundNo(userRefund.getOutTradeNo());
  1995. orderRefund
  1996. .setRefundMoney(new BigDecimal(userRefund.getRefundFee()));
  1997. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));//退款成功
  1998. orderRefund.setModTime(new Date());
  1999. orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
  2000. orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
  2001. orderRefund.setCreateTime(new Date());
  2002. List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
  2003. if(list.size()>1){//多条订单
  2004. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
  2005. }else{
  2006. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
  2007. }
  2008. orderRefundDao.save(orderRefund);//退款记录
  2009. }
  2010. orderDao.update(order);//修改为退款成功
  2011. // 修改取货码
  2012. PickUpCodeEntity pickUpCodeEntity = pickUpCodeService.queryObject(order.getOrderSn());
  2013. pickUpCodeEntity.setPickUpCodeStatus("3");
  2014. pickUpCodeService.update(pickUpCodeEntity);
  2015. // WebSocketServer.delete(sessionId,order.getStoreId(),pickUpCodeEntity);
  2016. updateStock(order, "收银端退款");
  2017. }
  2018. /**
  2019. * 设置订单数据
  2020. * @return
  2021. */
  2022. public OrderVo setOrderVo(List<GoodsEntity> goodsList, UserEntity loginUser,Long storeId, String merchSn, BigDecimal disCountAmount){
  2023. OrderVo orderInfo = new OrderVo();
  2024. BigDecimal goodsTotalPrice = new BigDecimal(0.00);
  2025. BigDecimal freightPrice = Constant.ZERO;
  2026. for (GoodsEntity goodsEntity : goodsList) {
  2027. goodsTotalPrice = goodsTotalPrice
  2028. .add(goodsEntity.getStoreRetailPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber())));
  2029. }
  2030. //订单价格计算:订单的总价+运费
  2031. BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
  2032. BigDecimal fullCutCouponDec = Constant.ZERO;
  2033. BigDecimal couponPrice = disCountAmount;
  2034. BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
  2035. String orderSn = "CW" + CommonUtil.generateOrderNumber();
  2036. orderInfo.setOrder_sn(orderSn);
  2037. orderInfo.setMerchSn(merchSn);
  2038. orderInfo.setUser_id(loginUser.getId().longValue());
  2039. StoreEntity storeEntity = storeDao.queryObject(storeId);
  2040. //收货地址和运费
  2041. orderInfo.setConsignee(loginUser.getUsername());
  2042. orderInfo.setMobile(loginUser.getMobile());
  2043. orderInfo.setCountry("");
  2044. orderInfo.setProvince(storeEntity.getProvinceName());
  2045. orderInfo.setCity(storeEntity.getCityName());
  2046. orderInfo.setDistrict(storeEntity.getCountyName());
  2047. orderInfo.setAddress(storeEntity.getStoreName());
  2048. orderInfo.setAddress_id(1L);
  2049. orderInfo.setDelivery_date(new Date());
  2050. orderInfo.setDelivery_remark("无");
  2051. orderInfo.setStore_id(storeId);
  2052. orderInfo.setFreight_price(freightPrice.intValue());
  2053. orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
  2054. orderInfo.setCoupon_price(couponPrice);
  2055. orderInfo.setCoupon_name("无");
  2056. orderInfo.setActivity_id(0L);
  2057. //使用的促销费用
  2058. orderInfo.setFull_cut_price(fullCutCouponDec);
  2059. orderInfo.setCampMinusId(0);
  2060. orderInfo.setCampName("");
  2061. //留言
  2062. orderInfo.setPostscript("无");
  2063. orderInfo.setAdd_time(new Date());
  2064. orderInfo.setGoods_price(goodsTotalPrice);
  2065. orderInfo.setOrder_price(orderTotalPrice);
  2066. orderInfo.setActual_price(actualPrice);
  2067. orderInfo.setOrder_type("1");
  2068. orderInfo.setOrder_status(0);
  2069. orderInfo.setShipping_status(0);
  2070. orderInfo.setPay_status(0);
  2071. orderInfo.setShipping_id(0L);
  2072. orderInfo.setShipping_fee(Constant.ZERO);
  2073. orderInfo.setIntegral(0);
  2074. orderInfo.setIntegral_money(Constant.ZERO);
  2075. orderInfo.setCreateTime(new Date());
  2076. orderInfo.setModTime(new Date());
  2077. orderInfo.setPayMobile(loginUser.getMobile());
  2078. orderInfo.setPayTransactionId("");
  2079. orderInfo.setIsScan("0");//默认未扫描
  2080. orderInfo.setPayMobile(loginUser.getMobile());
  2081. orderInfo.setPay_name(loginUser.getUsername());
  2082. orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
  2083. orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  2084. return orderInfo;
  2085. }
  2086. public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo,GoodsEntity goodsDto){
  2087. OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
  2088. orderGoodsVo.setOrder_id(orderInfo.getId());
  2089. orderGoodsVo.setGoods_id(goodsDto.getId());
  2090. orderGoodsVo.setGoods_sn(goodsDto.getGoodsSn());
  2091. orderGoodsVo.setProduct_id(Long.valueOf(goodsDto.getProductId()));
  2092. orderGoodsVo.setGoods_name(goodsDto.getName());
  2093. orderGoodsVo.setList_pic_url(goodsDto.getListPicUrl());
  2094. orderGoodsVo.setMarket_price(goodsDto.getStoreMarketPrice());
  2095. orderGoodsVo.setRetail_price(goodsDto.getStoreRetailPrice());
  2096. orderGoodsVo.setNumber(goodsDto.getGoodsNumber());
  2097. // orderGoodsVo.setGoods_specification_name_value(goodsDto.get);
  2098. // orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids());
  2099. orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
  2100. orderGoodsVo.setCreateTime(new Date());
  2101. orderGoodsVo.setModTime(new Date());
  2102. orderGoodsVo.setGoodsRate(goodsDto.getGoodsRate());
  2103. orderGoodsVo.setSku(goodsDto.getSku());
  2104. BigDecimal number = new BigDecimal(Long.valueOf(goodsDto.getGoodsNumber()));
  2105. BigDecimal goodsTotal = goodsDto.getStoreRetailPrice().multiply(number);//单商品总价
  2106. BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价(不含运费、不含优惠券)
  2107. BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
  2108. BigDecimal settlePrice = Constant.ZERO;
  2109. if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  2110. //运费-优惠券
  2111. BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
  2112. //商品结算平摊价格(含优惠券、运费金额) = 单商品总价 + 当前商品总价/订单总价(不含运费、不含优惠券) * 运费与优惠券合计税率
  2113. settlePrice = goodsTotal.add(rate.multiply(rateTotal));
  2114. }else{
  2115. if(orderInfo.getFreight_price()!=0){
  2116. //运费税率 = 单商品总价/订单总价(不含运费)* 运费金额
  2117. BigDecimal freightRate = rate.multiply(freightPrice);
  2118. //商品结算平摊价格(含运费金额) = 单商品总价+运费税率
  2119. settlePrice = goodsTotal.add(freightRate);
  2120. }
  2121. if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
  2122. //优惠券税率 = 单商品总价/订单总价(不含优惠券)* 优惠券金额
  2123. BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
  2124. //商品结算平摊价格(含优惠券金额) = 单商品总价-优惠券税率
  2125. settlePrice = goodsTotal.subtract(couponRate);
  2126. }
  2127. }
  2128. if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
  2129. orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
  2130. }else{
  2131. orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
  2132. }
  2133. return orderGoodsVo;
  2134. }
  2135. }