OrderController.java 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. package com.kmall.admin.controller;
  2. import com.kmall.admin.dto.OrderExpressDto;
  3. import com.kmall.admin.dto.SystemFormatDto;
  4. import com.kmall.admin.entity.*;
  5. import com.kmall.admin.fromcomm.entity.SysUserEntity;
  6. import com.kmall.admin.haikong.vo.CalculateOrderDiscountPriceResponseVO;
  7. import com.kmall.admin.service.*;
  8. import com.kmall.admin.utils.CalculateTax;
  9. import com.kmall.admin.utils.ParamUtils;
  10. import com.kmall.admin.utils.ShiroUtils;
  11. import com.kmall.admin.haikong.vo.CalculateOrderDiscountPriceVO;
  12. import com.kmall.common.constant.Dict;
  13. import com.kmall.common.constant.JxlsXmlTemplateName;
  14. import com.kmall.common.utils.*;
  15. import com.kmall.common.utils.excel.Entry;
  16. import com.kmall.common.utils.excel.ExcelExport;
  17. import com.kmall.common.utils.excel.ExcelUtil;
  18. import com.kmall.common.utils.print.ticket.item.Ticket;
  19. import com.kmall.common.utils.wechat.WechatMicropayApiResult;
  20. import com.kmall.common.utils.wechat.WechatRefundApiResult;
  21. import com.kmall.common.utils.wechat.WechatReverseApiResult;
  22. import com.kmall.manager.manager.alipay.AliPayMicropayApiResult;
  23. import com.kmall.manager.manager.alipay.AliPayUtil;
  24. import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
  25. import com.kmall.manager.manager.pingan.PinganUtil;
  26. import com.kmall.manager.manager.pingan.dto.PinganResponseDto;
  27. import com.kmall.manager.manager.wechat.WechatGlobalUtil;
  28. import com.kmall.manager.manager.wechat.WechatUtil;
  29. import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
  30. import net.sf.json.JSONObject;
  31. import org.apache.commons.lang3.StringUtils;
  32. import org.apache.commons.logging.Log;
  33. import org.apache.commons.logging.LogFactory;
  34. import org.apache.shiro.authz.annotation.RequiresPermissions;
  35. import org.springframework.beans.factory.annotation.Autowired;
  36. import org.springframework.web.bind.annotation.*;
  37. import org.springframework.web.multipart.MultipartFile;
  38. import javax.servlet.http.HttpServletRequest;
  39. import javax.servlet.http.HttpServletResponse;
  40. import java.io.IOException;
  41. import java.math.BigDecimal;
  42. import java.math.RoundingMode;
  43. import java.text.ParseException;
  44. import java.text.SimpleDateFormat;
  45. import java.util.*;
  46. /**
  47. * @author Scott
  48. * @email
  49. * @date 2017-08-13 10:41:09
  50. */
  51. @RestController
  52. @RequestMapping("order")
  53. public class OrderController {
  54. private Log logger = LogFactory.getLog(OrderController.class);
  55. @Autowired
  56. private OrderService orderService;
  57. @Autowired
  58. private OrderGoodsService orderGoodsService;
  59. @Autowired
  60. private OrderProcessRecordService orderProcessRecordService;
  61. @Autowired
  62. private OrderRefundService orderRefundService;
  63. @Autowired
  64. private OrderExceptionRecordService orderExceptionRecordService;
  65. @Autowired
  66. private StoreService storeService;
  67. @Autowired
  68. private OrderWXPayRecordService orderWXPayRecordService;
  69. @Autowired
  70. private PinganResponseService pinganResponseService;
  71. @Autowired
  72. private ExcelUtil excelUtil;
  73. @Autowired
  74. private ShippingService shippingService;
  75. private volatile Integer code = 1;
  76. @Autowired
  77. private UserService userService;
  78. @Autowired
  79. private GoodsService goodsService;
  80. /**
  81. * 列表
  82. */
  83. @RequestMapping("/list")
  84. @RequiresPermissions("order:list")
  85. public R list(@RequestParam Map<String, Object> params) {
  86. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  87. params = ParamUtils.setTimeMap(params);
  88. //查询列表数据
  89. Query query = new Query(params);
  90. query.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_0.getItem());
  91. List<OrderEntity> orderList = orderService.queryList(query);
  92. int total = orderService.queryTotal(query);
  93. PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
  94. return R.ok().put("page", pageUtil);
  95. }
  96. /**
  97. * 信息
  98. */
  99. @RequestMapping("/info/{id}")
  100. @RequiresPermissions("order:info")
  101. public R info(@PathVariable("id") Long id) {
  102. OrderEntity order = orderService.queryObject(id);
  103. return R.ok().put("order", order);
  104. }
  105. /**
  106. * 信息
  107. */
  108. @RequestMapping("/infos/{id}")
  109. @RequiresPermissions("order:infos")
  110. public R infos(@PathVariable("id") Long id) {
  111. OrderEntity order = orderService.queryInfos(id);
  112. return R.ok().put("order", order);
  113. }
  114. /**
  115. * 保存
  116. */
  117. @RequestMapping("/save")
  118. @RequiresPermissions("order:save")
  119. public R save(@RequestBody OrderEntity order) {
  120. orderService.save(order);
  121. return R.ok();
  122. }
  123. /**
  124. * 修改
  125. */
  126. @RequestMapping("/update")
  127. @RequiresPermissions("order:update")
  128. public R update(@RequestBody OrderEntity order) {
  129. orderService.update(order);
  130. return R.ok();
  131. }
  132. /**
  133. * 删除
  134. */
  135. @RequestMapping("/delete")
  136. @RequiresPermissions("order:delete")
  137. public R delete(@RequestBody Long[] ids) {
  138. orderService.deleteBatch(ids);
  139. return R.ok();
  140. }
  141. /**
  142. * 查看所有列表
  143. */
  144. @RequestMapping("/queryAll")
  145. public R queryAll(@RequestParam Map<String, Object> params) {
  146. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  147. List<OrderEntity> list = orderService.queryList(params);
  148. return R.ok().put("list", list);
  149. }
  150. /**
  151. * 总计
  152. */
  153. @RequestMapping("/queryTotal")
  154. public R queryTotal(@RequestParam Map<String, Object> params) {
  155. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  156. int sum = orderService.queryTotal(params);
  157. return R.ok().put("sum", sum);
  158. }
  159. /**
  160. * 确定收货
  161. *
  162. * @param id
  163. * @return
  164. */
  165. @RequestMapping("/confirm")
  166. @RequiresPermissions("order:confirm")
  167. public R confirm(@RequestBody Long id) {
  168. orderService.confirm(id);
  169. return R.ok();
  170. }
  171. /**
  172. * 发货
  173. *
  174. * @param order
  175. * @return
  176. */
  177. @RequestMapping("/sendGoods")
  178. @RequiresPermissions("order:sendGoods")
  179. public R sendGoods(@RequestBody OrderEntity order) {
  180. orderService.sendGoods(order);
  181. return R.ok();
  182. }
  183. /**
  184. * 跟踪快递轨迹
  185. *
  186. * @param id
  187. * @return
  188. */
  189. @RequestMapping("/getLogistics/{id}")
  190. @RequiresPermissions("order:getLogistics")
  191. public R getLogistics(@PathVariable("id") Long id) {
  192. Map result = orderService.getLogistics(id);
  193. return R.ok().put("result", result);
  194. }
  195. /**
  196. * 获取订单清关信息
  197. *
  198. * @param orderSn
  199. * @return
  200. */
  201. @RequestMapping("/getProcess/{orderSn}")
  202. @RequiresPermissions("order:getProcess")
  203. public R getProcess(@PathVariable("orderSn") String orderSn) {
  204. OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordService.queryObjectByOrderSn(orderSn);
  205. if (orderProcessRecordEntity != null) {
  206. if (orderProcessRecordEntity.getShipmentStartTime() != null) {
  207. orderProcessRecordEntity.setShipmentStartTimeStr(
  208. DateUtils.format(orderProcessRecordEntity.getShipmentStartTime(), DateUtils.DATE_TIME_PATTERN));
  209. }
  210. if (orderProcessRecordEntity.getShipmentSuccTime() != null) {
  211. orderProcessRecordEntity.setShipmentSuccTimeStr(
  212. DateUtils.format(orderProcessRecordEntity.getShipmentSuccTime(), DateUtils.DATE_TIME_PATTERN));
  213. }
  214. if (orderProcessRecordEntity.getCustomsStartTime() != null) {
  215. orderProcessRecordEntity.setCustomsStartTimeStr(
  216. DateUtils.format(orderProcessRecordEntity.getCustomsStartTime(), DateUtils.DATE_TIME_PATTERN));
  217. }
  218. if (orderProcessRecordEntity.getCustomsSuccTime() != null) {
  219. orderProcessRecordEntity.setCustomsSuccTimeStr(
  220. DateUtils.format(orderProcessRecordEntity.getCustomsSuccTime(), DateUtils.DATE_TIME_PATTERN));
  221. }
  222. if (orderProcessRecordEntity.getWaybillStartTime() != null) {
  223. orderProcessRecordEntity.setWaybillStartTimeStr(
  224. DateUtils.format(orderProcessRecordEntity.getWaybillStartTime(), DateUtils.DATE_TIME_PATTERN));
  225. }
  226. if (orderProcessRecordEntity.getWaybillSuccTime() != null) {
  227. orderProcessRecordEntity.setWaybillSuccTimeStr(
  228. DateUtils.format(orderProcessRecordEntity.getWaybillSuccTime(), DateUtils.DATE_TIME_PATTERN));
  229. }
  230. if (orderProcessRecordEntity.getEleOrderStartTime() != null) {
  231. orderProcessRecordEntity.setEleOrderStartTimeStr(
  232. DateUtils.format(orderProcessRecordEntity.getEleOrderStartTime(), DateUtils.DATE_TIME_PATTERN));
  233. }
  234. if (orderProcessRecordEntity.getEleOrderSuccTime() != null) {
  235. orderProcessRecordEntity.setEleOrderSuccTimeStr(
  236. DateUtils.format(orderProcessRecordEntity.getEleOrderSuccTime(), DateUtils.DATE_TIME_PATTERN));
  237. }
  238. if (orderProcessRecordEntity.getAddOrderStartTime() != null) {
  239. orderProcessRecordEntity.setAddOrderStartTimeStr(
  240. DateUtils.format(orderProcessRecordEntity.getAddOrderStartTime(), DateUtils.DATE_TIME_PATTERN));
  241. }
  242. if (orderProcessRecordEntity.getAddOrderSuccTime() != null) {
  243. orderProcessRecordEntity.setAddOrderSuccTimeStr(
  244. DateUtils.format(orderProcessRecordEntity.getAddOrderSuccTime(), DateUtils.DATE_TIME_PATTERN));
  245. }
  246. if (orderProcessRecordEntity.getPaySuccTime() != null) {
  247. orderProcessRecordEntity.setPaySuccTimeStr(
  248. DateUtils.format(orderProcessRecordEntity.getPaySuccTime(), DateUtils.DATE_TIME_PATTERN));
  249. }
  250. if (orderProcessRecordEntity.getPayStartTime() != null) {
  251. orderProcessRecordEntity.setPayStartTimeStr(
  252. DateUtils.format(orderProcessRecordEntity.getPayStartTime(), DateUtils.DATE_TIME_PATTERN));
  253. }
  254. if (orderProcessRecordEntity.getPaymentStartTime() != null) {
  255. orderProcessRecordEntity.setPaymentStartTimeStr(
  256. DateUtils.format(orderProcessRecordEntity.getPaymentStartTime(), DateUtils.DATE_TIME_PATTERN));
  257. }
  258. if (orderProcessRecordEntity.getPaymentSuccTime() != null) {
  259. orderProcessRecordEntity.setPaymentSuccTimeStr(
  260. DateUtils.format(orderProcessRecordEntity.getPaymentSuccTime(), DateUtils.DATE_TIME_PATTERN));
  261. }
  262. }
  263. return R.ok().put("orderProcessRecordEntity", orderProcessRecordEntity);
  264. }
  265. /**
  266. * 打印小票
  267. *
  268. * @param id
  269. * @return
  270. */
  271. @RequestMapping("/printMsg")
  272. public R printMsg(@RequestBody Long id) {
  273. Ticket ticket = orderService.printMsg(id);
  274. return R.ok().put("ticket", ticket);
  275. }
  276. @RequestMapping("/printMsgAndChangeCode")
  277. public R printMsgAndChangeCode(@RequestBody Map param) {
  278. Ticket ticket = null;
  279. try{
  280. Integer id = (Integer) param.get("id");
  281. String sessionId = (String) param.get("sessionId");
  282. ticket = orderService.printMsg(id.longValue(),sessionId);
  283. return R.ok().put("ticket", ticket);
  284. }catch (Exception e){
  285. logger.error("[printMsgAndChangeCode-----核销小票打印失败]",e);
  286. }
  287. return R.ok().put("ticket", ticket);
  288. }
  289. /**
  290. * 打印快递面单
  291. * @param param
  292. * @return
  293. */
  294. @RequestMapping("/printMsgChangeEwb")
  295. public R printMsgChangeEwb(@RequestBody Map param) {
  296. Integer id = (Integer) param.get("id");
  297. String sessionId = (String) param.get("sessionId");
  298. Ticket ticket = orderService.printMsgEwb(id.longValue(),sessionId);
  299. return R.ok().put("ticket", ticket);
  300. }
  301. @RequestMapping("/printCode")
  302. public R printMsg(){
  303. Map map = new HashMap();
  304. map.put("code",code++); // 系统中累加
  305. map.put("shopName","深圳xxxxxxCW店"); // 根据门店编号查询
  306. map.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  307. map.put("orderNo",UUID.randomUUID().toString().replace("//-","")); //
  308. return R.ok().put("ticket", map);
  309. }
  310. /**
  311. * 订单取消请求
  312. */
  313. @RequiresPermissions(value = {"order:refund"})
  314. @RequestMapping(value = "cancel", method = RequestMethod.POST)
  315. public Object cancel(Long orderId) {
  316. OrderEntity orderInfo = orderService.queryObject(orderId);
  317. if (null == orderInfo) {
  318. return R.error("订单不存在");
  319. }
  320. if (orderInfo.getOrderStatus() != 0) {
  321. return R.error("订单状态不支持取消");
  322. }
  323. orderService.cancelOrder(orderInfo);
  324. return R.ok();
  325. }
  326. /**
  327. * 订单退款请求
  328. */
  329. @RequiresPermissions(value = {"order:refund"})
  330. @RequestMapping(value = "refund", method = RequestMethod.POST)
  331. public Object refund(Long orderId, String refundId, BigDecimal refundMoney) {
  332. OrderEntity orderInfo = orderService.queryObject(orderId);
  333. if (null == orderInfo) {
  334. return R.error("订单不存在");
  335. }
  336. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem()) ||
  337. orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
  338. return R.error("订单已退款");
  339. }
  340. Double totalActualPrice = orderService.getTotalActualPrice(orderInfo.getMerchOrderSn());
  341. if (totalActualPrice == null) {
  342. totalActualPrice = 0d;
  343. }
  344. OrderProcessRecordEntity processRecordEntity = orderProcessRecordService.queryObjectByOrderSn(orderInfo.getOrderSn());
  345. if(org.apache.commons.lang.StringUtils.isNotEmpty(processRecordEntity.getIsCustomsSend())) {
  346. if (processRecordEntity.getIsCustomsSend().equalsIgnoreCase("2")) {
  347. return R.error("订单正在清关中,不能退款");
  348. }
  349. if (processRecordEntity.getIsCustomsSend().equalsIgnoreCase("1")) {
  350. return R.error("订单已清关完成,不能退款");
  351. }
  352. }
  353. String refundResult = "";
  354. if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  355. if (orderInfo.getPayFlag().equalsIgnoreCase(Dict.payFlag.item_wxglobalpay.getItem())) {
  356. refundResult = wxGlobalRefund(orderInfo, totalActualPrice);
  357. if (StringUtils.isNotBlank(refundResult)) {
  358. return R.error(refundResult);
  359. }
  360. } else if (orderInfo.getPayFlag().equalsIgnoreCase(Dict.payFlag.item_pingan.getItem())) {
  361. refundResult = pinganRefund(orderInfo, refundId);
  362. if (StringUtils.isNotBlank(refundResult)) {
  363. return R.error(refundResult);
  364. }
  365. } else{
  366. refundResult = wxRefund(orderInfo,totalActualPrice);
  367. if(StringUtils.isNotBlank(refundResult)){
  368. return R.error(refundResult);
  369. }
  370. }
  371. }
  372. return R.ok("退款成功");
  373. }
  374. /**
  375. * 平安申请退款
  376. * @param orderInfo
  377. * @return
  378. */
  379. private String pinganRefund(OrderEntity orderInfo, String refundId){
  380. Integer refundAmount = orderInfo.getActualPrice().multiply(new BigDecimal(100)).intValue();
  381. PinganResponseDto responseDto = PinganUtil.pinganPayRefund(orderInfo.getMerchOrderSn(), refundId, refundAmount, null);
  382. if (!Objects.isNull(responseDto)) {
  383. responseDto.setOutNo(orderInfo.getMerchOrderSn());
  384. responseDto.setCreateTime(new Date());
  385. pinganResponseService.save(responseDto);
  386. if ("0".equals(responseDto.getErrcode())) {
  387. JSONObject tradeResult = JSONObject.fromObject(responseDto.getDatajson());
  388. if (Dict.pinganRefundStatus.item_1.getItem().equals(tradeResult.getString("status"))) {
  389. orderService.pinganRefund(orderInfo, tradeResult, refundId);
  390. } else {
  391. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  392. OrderRefundEntity orderRefund = new OrderRefundEntity();
  393. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  394. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  395. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  396. SysUserEntity user = ShiroUtils.getUserEntity();
  397. orderRefund.setModerSn(user.getUsername());
  398. orderRefund.setModTime(new Date());
  399. orderRefund.setOutRefundNo(tradeResult.getString("ord_no"));
  400. if (mallOrderRefund != null) {
  401. orderRefund.setId(mallOrderRefund.getId());
  402. orderRefundService.update(orderRefund);//退款记录
  403. }
  404. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  405. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  406. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  407. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  408. mallOrderExceptionRecord.setExceptionContent("退款失败");
  409. mallOrderExceptionRecord.setCreateTime(new Date());
  410. orderExceptionRecordService.save(mallOrderExceptionRecord);
  411. return "发起平安支付退款失败!";
  412. }
  413. } else {
  414. return responseDto.getMsg();
  415. }
  416. }
  417. return "";
  418. }
  419. /**
  420. * 微信申请退款
  421. * @param orderInfo
  422. * @param totalActualPrice
  423. * @return
  424. */
  425. private String wxRefund(OrderEntity orderInfo,Double totalActualPrice){
  426. WechatRefundApiResult result = WechatUtil.wxRefund(orderInfo.getMerchOrderSn().toString(), totalActualPrice,
  427. orderInfo.getActualPrice().doubleValue());
  428. if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  429. orderService.refund(orderInfo, result);
  430. } else {
  431. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  432. OrderRefundEntity orderRefund = new OrderRefundEntity();
  433. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  434. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  435. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  436. SysUserEntity user = ShiroUtils.getUserEntity();
  437. orderRefund.setModerSn(user.getUsername());
  438. orderRefund.setModTime(new Date());
  439. // orderRefund.setOutRefundNo(result.getOut_refund_no());
  440. if (mallOrderRefund != null) {
  441. orderRefund.setId(mallOrderRefund.getId());
  442. orderRefundService.update(orderRefund);//退款记录
  443. }
  444. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  445. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  446. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  447. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  448. mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
  449. mallOrderExceptionRecord.setCreateTime(new Date());
  450. orderExceptionRecordService.save(mallOrderExceptionRecord);
  451. return result.getErr_code_des();
  452. }
  453. return "";
  454. }
  455. /**
  456. * 微信国际申请退款
  457. * @param orderInfo
  458. * @param totalActualPrice
  459. * @return
  460. */
  461. private String wxGlobalRefund(OrderEntity orderInfo,Double totalActualPrice){
  462. WechatGlobalRefundApiResult result = WechatGlobalUtil.wxRefund(orderInfo.getMerchOrderSn().toString(), totalActualPrice,
  463. orderInfo.getActualPrice().doubleValue());
  464. if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  465. orderService.globalRefund(orderInfo, result);
  466. } else {
  467. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  468. OrderRefundEntity orderRefund = new OrderRefundEntity();
  469. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  470. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  471. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  472. // orderRefund.setOutRefundNo(result.getOut_refund_no());
  473. orderRefund.setModTime(new Date());
  474. if (mallOrderRefund != null) {
  475. orderRefund.setId(mallOrderRefund.getId());
  476. orderRefundService.update(orderRefund);//退款记录
  477. }
  478. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  479. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  480. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  481. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  482. mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
  483. mallOrderExceptionRecord.setCreateTime(new Date());
  484. orderExceptionRecordService.save(mallOrderExceptionRecord);
  485. return result.getErr_code_des();
  486. }
  487. return "";
  488. }
  489. /**
  490. * 订单退款请求
  491. */
  492. @RequiresPermissions(value = {"order:offilineRefund"})
  493. @RequestMapping(value = "offilineRefund", method = RequestMethod.POST)
  494. public Object offilineRefund(Long orderId) {
  495. OrderEntity orderInfo = orderService.queryObject(orderId);
  496. if (null == orderInfo) {
  497. return R.error("订单不存在");
  498. }
  499. if (orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem()) ||
  500. orderInfo.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
  501. return R.error("订单已退款");
  502. }
  503. if (orderInfo.getOrderStatus() != Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
  504. if (Dict.payFlag.item_cash.getItem().equals(orderInfo.getPayFlag())) {
  505. //现金支付,直接修改订单状态
  506. orderService.refund(orderInfo);
  507. } else if (Dict.payFlag.item_weixin.getItem().equals(orderInfo.getPayFlag())) {
  508. //微信线下扫码支付
  509. WechatRefundApiResult result = WechatUtil
  510. .wxRefund(orderInfo.getOrderSnWx(), orderInfo.getActualPrice().doubleValue(),
  511. orderInfo.getActualPrice().doubleValue());
  512. if (result.getResult_code().equals(WechatUtil.WXTradeState.SUCCESS.getCode())) {
  513. orderService.refund(orderInfo, result);
  514. } else {
  515. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  516. OrderRefundEntity orderRefund = new OrderRefundEntity();
  517. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  518. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  519. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  520. // orderRefund.setOutRefundNo(result.getOut_refund_no());
  521. SysUserEntity user = ShiroUtils.getUserEntity();
  522. orderRefund.setModerSn(user.getUsername());
  523. orderRefund.setModTime(new Date());
  524. if (mallOrderRefund != null) {
  525. orderRefund.setId(mallOrderRefund.getId());
  526. orderRefundService.update(orderRefund);//退款记录
  527. }
  528. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  529. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  530. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  531. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  532. mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getErr_code_des());
  533. mallOrderExceptionRecord.setCreateTime(new Date());
  534. orderExceptionRecordService.save(mallOrderExceptionRecord);
  535. return R.error(result.getErr_code_des());
  536. }
  537. }else if(Dict.payFlag.item_alipay.getItem().equals(orderInfo.getPayFlag())){
  538. // 支付宝线下扫码支付
  539. AliPayMicropayApiResult result = null;
  540. try {
  541. result = AliPayUtil.aliTradeRefund(orderInfo.getOrderSn(),orderInfo.getActualPrice()+"",
  542. "顾客退款",orderInfo.getStoreId().toString());
  543. } catch (Exception e) {
  544. e.printStackTrace();
  545. }
  546. if (result.getCode().equals(AliPayUtil.AliPayTradeState.SUCC.getCode())) {
  547. orderService.refund(orderInfo, result);
  548. } else {
  549. OrderRefundEntity mallOrderRefund = orderRefundService.queryObjectByOrderId(orderInfo.getId());
  550. OrderRefundEntity orderRefund = new OrderRefundEntity();
  551. orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
  552. orderRefund.setRefundMoney(BigDecimal.valueOf(orderInfo.getActualPrice().doubleValue()));
  553. orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
  554. // orderRefund.setOutRefundNo(result.getOut_refund_no());
  555. SysUserEntity user = ShiroUtils.getUserEntity();
  556. orderRefund.setModerSn(user.getUsername());
  557. orderRefund.setModTime(new Date());
  558. if (mallOrderRefund != null) {
  559. orderRefund.setId(mallOrderRefund.getId());
  560. orderRefundService.update(orderRefund);//退款记录
  561. }
  562. OrderExceptionRecordEntity mallOrderExceptionRecord = new OrderExceptionRecordEntity();
  563. mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUserId() + ""));
  564. mallOrderExceptionRecord.setOrderSn(orderInfo.getOrderSn());
  565. mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_03.getItem());
  566. mallOrderExceptionRecord.setExceptionContent("退款失败" + result.getSubMsg());
  567. mallOrderExceptionRecord.setCreateTime(new Date());
  568. orderExceptionRecordService.save(mallOrderExceptionRecord);
  569. return R.error(result.getSubMsg());
  570. }
  571. } else{
  572. return R.ok("退款成功");
  573. }
  574. }
  575. return R.ok("退款成功");
  576. }
  577. /**
  578. * 获取首页展示信息--会员购买率相关
  579. *
  580. * @param params
  581. * @return
  582. */
  583. @RequestMapping("/getUserOrderInfo")
  584. public R getUserOrderInfo(@RequestParam Map<String, Object> params) {
  585. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  586. int result = orderService.getUserOrderInfo(params);
  587. return R.ok().put("result", result);
  588. }
  589. @RequiresPermissions(value = {"order:orderSubmit"})
  590. @RequestMapping(value = "orderSubmit", method = RequestMethod.POST)
  591. @ResponseBody
  592. public R orderSubmit(@RequestBody List<OfflineCartEntity> offlineCartEntityList) {
  593. Map resultObj = null;
  594. try {
  595. SysUserEntity user = ShiroUtils.getUserEntity();
  596. resultObj = orderService.orderSubmit(offlineCartEntityList, user);
  597. if (((Integer) resultObj.get("errno")) != 0) {
  598. return R.error((String) resultObj.get("errmsg"));
  599. }
  600. } catch (Exception e) {
  601. e.printStackTrace();
  602. }
  603. return R.ok("订单提交成功");
  604. }
  605. /**
  606. * 确认付款
  607. *
  608. * @param id
  609. * @return
  610. */
  611. @RequestMapping("/confirmPay")
  612. @RequiresPermissions("order:confirmPay")
  613. public R confirmPay(@RequestBody Long id) {
  614. orderService.confirmPay(id, Dict.payFlag.item_cash.getItem(), null);
  615. return R.ok();
  616. }
  617. @RequestMapping("/offilineOrderList")
  618. @RequiresPermissions("order:offilineOrderList")
  619. public R offilineOrderList(@RequestParam Map<String, Object> params) {
  620. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  621. params = ParamUtils.setTimeMap(params);
  622. //查询列表数据
  623. Query query = new Query(params);
  624. query.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_1.getItem());
  625. List<OrderEntity> orderList = orderService.queryOffilineOrderList(query);
  626. int total = orderService.queryOffilineOrderTotal(query);
  627. for(OrderEntity orderEntity : orderList) {
  628. BigDecimal tax = new BigDecimal(0);
  629. Map map = new HashMap();
  630. map.put("orderId", orderEntity.getId());
  631. List<OrderGoodsEntity> goodsList = orderGoodsService.queryList(map);
  632. for (OrderGoodsEntity orderGoodsEntity : goodsList) {
  633. GoodsEntity goodsEntity = goodsService.queryObject(orderGoodsEntity.getGoodsId());
  634. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity,orderGoodsEntity.getMarketPrice(),goodsService).setScale(3,RoundingMode.HALF_UP);
  635. goodsTax = goodsTax.multiply(new BigDecimal(orderGoodsEntity.getNumber())).setScale(2,RoundingMode.HALF_UP);
  636. orderGoodsEntity.setTax(goodsTax);
  637. tax = tax.add(goodsTax).setScale(2,RoundingMode.HALF_UP);
  638. // BigDecimal goodsTax = orderGoodsEntity.getMarketPrice().divide(new BigDecimal(1).add(orderGoodsEntity.getGoodsRate()),2,RoundingMode.HALF_DOWN).multiply(orderGoodsEntity.getGoodsRate())
  639. // .multiply(new BigDecimal(orderGoodsEntity.getNumber())).setScale(2,RoundingMode.HALF_DOWN);
  640. // tax = tax.add(goodsTax).setScale(2,RoundingMode.HALF_UP);
  641. }
  642. orderEntity.setTax(tax);
  643. }
  644. // 遍历循环订单是哪个店员销售的,根据订单号查询
  645. PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
  646. return R.ok().put("page", pageUtil);
  647. }
  648. /**
  649. * 当查验单从保税仓发货时, 会导致门店库存不还原
  650. * 还原查验单库存
  651. * @param orderSns 查验单单号
  652. * @return 请求结果
  653. */
  654. @RequestMapping(value = "/restore", method = RequestMethod.POST)
  655. public R restore (@RequestBody String orderSns) {
  656. if (StringUtils.isEmpty(orderSns)) {
  657. return R.error("订单编号不能为空!");
  658. }
  659. try {
  660. Boolean restore = orderService.restore(orderSns);
  661. if (restore) {
  662. return R.ok("恢复【" + orderSns + "】这些查验订单的库存成功");
  663. }
  664. } catch (RRException e) {
  665. return R.error(e.getMsg());
  666. } catch (Exception e) {
  667. return R.error("恢复【 " + orderSns + " 】这些查验订单的库存失败!");
  668. }
  669. return R.error("恢复【 " + orderSns + " 】这些查验订单的库存失败!");
  670. }
  671. @RequestMapping("/offlineInfos/{id}")
  672. @RequiresPermissions("order:offlineInfos")
  673. public R queryObjectBySysUser(@PathVariable("id") Long id) {
  674. OrderEntity order = orderService.queryObjectBySysUser(id);
  675. List<OrderWXPayRecordEntity> payRecords = orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrderSn());
  676. BigDecimal tax = new BigDecimal(0);
  677. List<OrderGoodsEntity> goodsList = order.getOrderGoodsEntityList();
  678. for (OrderGoodsEntity orderGoodsEntity : goodsList) {
  679. GoodsEntity goodsEntity = goodsService.queryObject(orderGoodsEntity.getGoodsId());
  680. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity,orderGoodsEntity.getMarketPrice(),goodsService).setScale(3,RoundingMode.HALF_UP);
  681. goodsTax = goodsTax.multiply(new BigDecimal(orderGoodsEntity.getNumber())).setScale(2,RoundingMode.HALF_UP);
  682. orderGoodsEntity.setTax(goodsTax);
  683. tax = tax.add(goodsTax).setScale(2,RoundingMode.HALF_UP);
  684. // BigDecimal goodsTax = orderGoodsEntity.getMarketPrice().divide(new BigDecimal(1).add(orderGoodsEntity.getGoodsRate()),2,RoundingMode.HALF_DOWN).multiply(orderGoodsEntity.getGoodsRate())
  685. // .multiply(new BigDecimal(orderGoodsEntity.getNumber())).setScale(2,RoundingMode.HALF_DOWN);
  686. // orderGoodsEntity.setTax(goodsTax);
  687. //
  688. // tax = tax.add(goodsTax).setScale(2,RoundingMode.HALF_UP);
  689. }
  690. order.setTax(tax);
  691. order.setPayRecordList(payRecords);
  692. return R.ok().put("order", order);
  693. }
  694. @RequestMapping("/pickUpCodeList")
  695. public R pickUpCodeList(@RequestBody Map<String, Object> params) {
  696. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  697. //查询列表数据
  698. params.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_1.getItem());
  699. List<OrderEntity> orderList = orderService.queryPickUpCodeList(params);
  700. return R.ok().put("list", orderList);
  701. }
  702. @RequestMapping("/wxMicropayPay")
  703. @RequiresPermissions("order:wxMicropayPay")
  704. public R wxMicropayPay(Long id, String auth_code) {
  705. R r = null;
  706. SysUserEntity user = ShiroUtils.getUserEntity();
  707. if (user == null) {
  708. throw new RRException("用户登录超时,请重新登录");
  709. }
  710. if (!user.getRoleType().equalsIgnoreCase("2")) {
  711. throw new RRException("该操作只允许店员账户操作");
  712. }
  713. OrderEntity orderEntity = orderService.queryObject(id);
  714. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
  715. throw new RRException("此订单已付款!");
  716. }
  717. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
  718. throw new RRException("此订单已完成!");
  719. }
  720. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
  721. throw new RRException("此订单已取消!");
  722. }
  723. if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
  724. throw new RRException("此订单已删除!");
  725. }
  726. //保存支付记录
  727. OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecord(orderEntity);
  728. StoreEntity store = storeService.queryObject(orderEntity.getStoreId());
  729. WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
  730. .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), orderEntity.getOrderBizType(), null,
  731. orderWXPayRecordCurrent.getOutTradeNoWX(), orderEntity.getActualPrice().doubleValue(),
  732. "127.0.0.1", auth_code);
  733. orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);
  734. //当支付成功时,修改订单,并把其他支付记录撤销
  735. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  736. //查询当前订单所有的支付记录
  737. List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
  738. orderWXPayRecordService.getRecordsByOutTradeNo(orderEntity.getOrderSn());
  739. for (OrderWXPayRecordEntity orderWXPayRecordTemp : orderWXPayRecordEntitys) {
  740. //查询出来的记录排除当前已支付成功的记录,对其他记录交易状态为未撤销,未关闭的订单,调用撤销订单
  741. if (!orderWXPayRecordTemp.getId().equals(orderWXPayRecordCurrent.getId()) &&
  742. (!WechatUtil.WXTradeState.REVOKED.getCode().equals(orderWXPayRecordTemp.getTradeState()) ||
  743. !WechatUtil.WXTradeState.CLOSED.getCode().equals(orderWXPayRecordTemp.getTradeState()))) {
  744. WechatReverseApiResult wechatReverseApiResult =
  745. WechatUtil.wxReverse(orderWXPayRecordTemp.getOutTradeNoWX());
  746. //撤销订单成功
  747. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
  748. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
  749. //调用订单查询接口
  750. WechatRefundApiResult wechatRefundApiResult =
  751. WechatUtil.wxOrderQuery(orderWXPayRecordTemp.getOutTradeNoWX());
  752. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
  753. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
  754. // 修改订单支付记录
  755. orderWXPayRecordService
  756. .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
  757. }
  758. }
  759. }
  760. }
  761. orderService.confirmPay(id, Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());
  762. r = R.ok();
  763. //用户支付中
  764. } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  765. r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
  766. //用户支付失败
  767. } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
  768. WechatReverseApiResult wechatReverseApiResult =
  769. WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
  770. //撤销订单成功
  771. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
  772. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
  773. //调用订单查询接口
  774. WechatRefundApiResult wechatRefundApiResult =
  775. WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
  776. if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
  777. WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
  778. // 修改订单支付记录
  779. orderWXPayRecordService
  780. .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
  781. }
  782. r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
  783. } else {
  784. r = R.error(wechatReverseApiResult.getErr_code_des());
  785. }
  786. }
  787. return r;
  788. }
  789. /**
  790. * 线上订单导出请求
  791. */
  792. @RequiresPermissions(value = {"order:export"})
  793. @RequestMapping(value = "export")
  794. public Object export(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
  795. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  796. params = ParamUtils.setTimeMap(params);
  797. //查询列表数据
  798. params.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_0.getItem());
  799. ExcelExport ee = new ExcelExport("线上订单信息");
  800. // =================================================线上订单明细导出开始=====================================
  801. List<OrderEntity> orderList = orderService.queryExportList(params);
  802. String[] header = new String[]{"订单编号", "商户订单编号", "所属门店", "供应商", "供应商第三方商户代码", "订单状态", "SKU", "商品名称", "数量",
  803. "销售价", "促销价", "实际支付金额", "保税模式", "快递公司", "配送单号", "快递费用", "发货状态", "修改人",
  804. "海关清单编号", "收货人姓名", "收件人手机", "收件人省份", "收件人城市", "收件人区县", "收件人地址", "下单时间", "支付流水号", "身份证号"
  805. , "原产国", "规格型号", "品牌", "单位", "毛重(kg)", "净重"};
  806. List<Map<String, Object>> list = new ArrayList<>();
  807. if (orderList != null && orderList.size() != 0) {
  808. for (OrderEntity orderEntity : orderList) {
  809. LinkedHashMap<String, Object> map = new LinkedHashMap<>();
  810. Integer orderStatus = orderEntity.getOrderStatus();
  811. String orderBizType = orderEntity.getOrderBizType();
  812. Integer shippingStatus = orderEntity.getShippingStatus();
  813. map.put("OrderSn", orderEntity.getOrderSn());
  814. map.put("MerchOrderSn", orderEntity.getMerchOrderSn());
  815. map.put("StoreName", orderEntity.getStoreName());
  816. map.put("SupplierThirdPartyMerchName", orderEntity.getSupplierThirdPartyMerchName());
  817. map.put("SupplierThirdPartyMerchCode", orderEntity.getSupplierThirdPartyMerchCode());
  818. map.put("OrderStatus", StringUtils.isEmpty(orderStatus.toString())? "":Dict.orderStatus.valueOf("item_"+ orderStatus).getItemName());
  819. map.put("SKU", orderEntity.getSku());
  820. map.put("GoodsName", orderEntity.getGoodsName());
  821. map.put("Number", orderEntity.getNumber());
  822. map.put("RetailPrice", orderEntity.getRetailPrice());
  823. map.put("TopicPrice", orderEntity.getTopicPrice());
  824. map.put("ActualPrice", orderEntity.getActualPrice());
  825. map.put("OrderBizType", StringUtils.isEmpty(orderBizType)? "":Dict.orderBizType.valueOf("item_"+orderBizType).getItemName());
  826. map.put("ShippingName", orderEntity.getShippingName());
  827. map.put("ShippingNo", orderEntity.getShippingNo());
  828. map.put("ShippingFee", orderEntity.getShippingFee());
  829. map.put("ShippingStatus", Dict.shippingStatus.valueOf("item_"+shippingStatus).getItemName());
  830. map.put("ModerSn", orderEntity.getModerSn());
  831. map.put("InvtNo", orderEntity.getOrderProcessRecord()==null?"":orderEntity.getOrderProcessRecord().getInvtNo());
  832. map.put("Consignee", orderEntity.getConsignee());
  833. map.put("Mobile", orderEntity.getMobile());
  834. map.put("Province", orderEntity.getProvince());
  835. map.put("City", orderEntity.getCity());
  836. map.put("District", orderEntity.getDistrict());
  837. map.put("Address", orderEntity.getAddress());
  838. map.put("OrderStartTime", orderEntity.getOrderProcessRecord()==null?"":DateUtils.format(orderEntity.getOrderProcessRecord().getAddOrderStartTime(),"yyyy-MM-dd HH:mm:ss"));
  839. map.put("PayId", orderEntity.getPayTransactionId());
  840. map.put("IdNo", orderEntity.getIdNo());
  841. map.put("OriCntCode", orderEntity.getOriCntCode());
  842. map.put("CiqProdModel", orderEntity.getCiqProdModel());
  843. map.put("Brand", orderEntity.getBrand());
  844. map.put("UnitCode", orderEntity.getUnitCode());
  845. map.put("GrossWeight", orderEntity.getGrossWeight());
  846. map.put("NetWeight", orderEntity.getNetWeight());
  847. // 零售价\促销价\成交价
  848. // map.put("SellPrice",orderEntity.getRetailPrice());
  849. //
  850. // map.put("FinalPrice",orderEntity.getActualPrice());
  851. list.add(map);
  852. }
  853. }
  854. // =================================================线上订单明细导出开始=====================================
  855. // =================================================线上订单导出开始=====================================
  856. List<OrderEntity> masterOrderList = orderService.queryMasterExportList(params);
  857. String[] headerMatser = new String[]{"所属门店", "订单号", "会员", "支付类型", "商户订单号", "订单业务类型", "订单状态", "订付人核验", "付款状态",
  858. "实际支付", "订单总价", "下单时间", "快递公司", "配送单号", "快递费用", "发货状态", "修改人",};
  859. List<Map<String, Object>> listMaster = new ArrayList<>();
  860. if (masterOrderList != null && masterOrderList.size() > 0) {
  861. for (OrderEntity orderEntity : masterOrderList) {
  862. LinkedHashMap<String, Object> map = new LinkedHashMap<>();
  863. String orderBizType = orderEntity.getOrderBizType();
  864. Integer orderStatus = orderEntity.getOrderStatus();
  865. String isMergePay = orderEntity.getIsMergePay();
  866. String buyerPayCheck = orderEntity.getBuyerPayCheck();
  867. map.put("StoreName",orderEntity.getStoreName());
  868. map.put("OrderSn",orderEntity.getOrderSn());
  869. map.put("UserName",orderEntity.getUserName());
  870. map.put("IsMergePay",StringUtils.isEmpty(isMergePay)?"-":Dict.isMergePay.valueOf("item_"+isMergePay).getItemName());
  871. map.put("MerchOrderSn",orderEntity.getMerchOrderSn());
  872. map.put("OrderBizType",StringUtils.isEmpty(orderBizType)? "":Dict.orderBizType.valueOf("item_"+orderBizType).getItemName());
  873. map.put("OrderStatus",Dict.orderStatus.valueOf("item_"+ orderStatus).getItemName());
  874. map.put("BuyerPayCheck",StringUtils.isEmpty(buyerPayCheck)?"":Dict.merchReturnSubjectChecked.valueOf("item_"+buyerPayCheck).getItemName());
  875. map.put("PayStatus",Dict.payStatus.valueOf("item_"+orderEntity.getPayStatus()).getItemName());
  876. map.put("ActualPrice",orderEntity.getActualPrice());
  877. map.put("OrderPrice",orderEntity.getOrderPrice());
  878. map.put("AddTime",orderEntity.getAddTime());
  879. map.put("ShippingName",orderEntity.getShippingName());
  880. map.put("ShippingNo",orderEntity.getShippingNo());
  881. map.put("ShippingFee",orderEntity.getShippingFee());
  882. map.put("ShippingStatus",Dict.shippingStatus.valueOf("item_"+orderEntity.getShippingStatus()).getItemName());
  883. map.put("ModerSn",orderEntity.getModerSn());
  884. listMaster.add(map);
  885. }
  886. }
  887. // =================================================线上订单导出结束=====================================
  888. ee.addSheetByMap("线上订单信息", listMaster, headerMatser);
  889. ee.addSheetByMap("线上订单明细信息", list, header);
  890. ee.export(response);
  891. return R.ok();
  892. }
  893. /**
  894. * 订单修改已发货的快递信息
  895. */
  896. @RequestMapping("/updateExpressInfo")
  897. @RequiresPermissions("order:updateExpressInfo")
  898. public Object updateExpressInfo(@RequestBody OrderEntity orderEntity) {
  899. OrderEntity orderInfo = orderService.queryObject(orderEntity.getId());
  900. if (orderInfo != null){
  901. if(orderInfo.getShippingStatus() == Integer.parseInt(Dict.shippingStatus.item_1.getItem())) {
  902. OrderEntity order = new OrderEntity();
  903. order.setId(orderInfo.getId());
  904. order.setShippingCode(orderEntity.getShippingCode());
  905. Map map = new HashMap();
  906. map.put("code", orderEntity.getShippingCode());
  907. ShippingEntity shippingEntity = shippingService.queryObjectByCode(orderEntity.getShippingCode());
  908. if(shippingEntity != null) {
  909. order.setShippingName(shippingEntity.getName());
  910. }else{
  911. throw new RRException("此订单修改的快递公司信息不存在!不能操作");
  912. }
  913. order.setShippingNo(orderEntity.getShippingNo());
  914. order.setModerSn(ShiroUtils.getUserEntity().getUsername());
  915. order.setModTime(new Date());
  916. orderService.update(order);
  917. }else{
  918. throw new RRException("此订单"+Dict.shippingStatus.valueOf("item_"+orderInfo.getShippingStatus()).getItemName()+"!不能操作");
  919. }
  920. }
  921. return R.ok();
  922. }
  923. /**
  924. * 上传文件
  925. */
  926. @RequestMapping("/expressUpload")
  927. @ResponseBody
  928. public R expressUpload(@RequestParam("file") MultipartFile file) {
  929. List<OrderExpressDto> orderExpressList = new ArrayList<>();//快递信息
  930. try {
  931. Map<String, Object> beans = new HashMap<String, Object>();
  932. beans.put("OrderExpressList", orderExpressList);
  933. if (file.isEmpty()) {
  934. return R.error("文件不能为空!");
  935. }
  936. excelUtil.readExcel(JxlsXmlTemplateName.ORDER_EXPRESS_LIST, beans, file.getInputStream());
  937. } catch (Exception e) {
  938. e.printStackTrace();
  939. return R.error("导入失败!");
  940. }
  941. orderService.uploadExcel(orderExpressList);
  942. //上传文件
  943. return R.ok();
  944. }
  945. /**
  946. * 获取ccnet需要重发的订单数据
  947. */
  948. @RequestMapping("/wxOrderResendQueryAllList")
  949. public R wxOrderResendQueryAllList(@RequestParam Map<String, Object> params) {
  950. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  951. //查询列表数据
  952. Query query = new Query(params);
  953. List<WxOrderEntity> orderList = orderService.wxOrderResendQueryAllList(query);
  954. PageUtils pageUtil = new PageUtils(orderList, orderList.size(), query.getLimit(), query.getPage());
  955. return R.ok().put("page", pageUtil);
  956. }
  957. /**
  958. * 收银端支付
  959. * @param param
  960. * @return
  961. * @throws IOException
  962. */
  963. @RequestMapping("/orderConfirm")
  964. public R orderConfirm(@RequestBody Map param) throws IOException {
  965. SysUserEntity user = ShiroUtils.getUserEntity();
  966. Map resultObj = null;
  967. try {
  968. // throw new RuntimeException("系统异常");
  969. resultObj = orderService.offlineRetailSubmit(param,user);
  970. if(resultObj.get("errno") != null && ((Integer)resultObj.get("errno")) == 400){
  971. return R.error((String) resultObj.get("errmsg"));
  972. }
  973. return R.ok().put("resultObj", resultObj);
  974. } catch (Exception e) {
  975. if (e.getMessage().contains("java.lang.IllegalStateException: invalid auth_code!")){
  976. return R.error("付款码异常,请重新输入!");
  977. }
  978. return R.error(e.getMessage());
  979. }
  980. }
  981. /**
  982. * 海控退款
  983. * @param param
  984. * @return
  985. * @throws IOException
  986. */
  987. @RequestMapping("/orderHkRefund")
  988. public R orderRefund( @RequestBody Map param) {
  989. SysUserEntity user = ShiroUtils.getUserEntity();
  990. Integer orderId = (Integer) param.get("orderId");
  991. OrderEntity orderInfo = orderService.queryObject(orderId.longValue());
  992. String sessionId = (String) param.get("sessionId");
  993. try {
  994. return orderService.orderRefund(orderInfo,sessionId,user);
  995. } catch (Exception e) {
  996. e.printStackTrace();
  997. logger.error("[orderHkRefund-----海控退款异常]"+orderInfo.getOrderSn(),e);
  998. return R.error(500,"退款失败");
  999. }
  1000. }
  1001. @RequestMapping("/resendOrderToCCNET/{orderSn}/{resendType}")
  1002. public R resendWayBill(@PathVariable("orderSn") String orderSn, @PathVariable("resendType") String resendType){
  1003. String response = null;
  1004. Map map = new HashMap();
  1005. map.put("orderSn",orderSn);
  1006. try {
  1007. String url = "";
  1008. if("waybill".equals(resendType)){
  1009. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/resendWaybill/"+orderSn;
  1010. }else if("payment".equals(resendType)){
  1011. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/resendPayment/"+orderSn;
  1012. }else if("notice".equals(resendType)){
  1013. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/notice/"+orderSn;
  1014. }else if("clsOrder".equals(resendType)){
  1015. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/clsOrder/"+orderSn;
  1016. }else if("forceSend".equals(resendType)){
  1017. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/forceSend/"+orderSn;
  1018. }else if("resendOrder".equals(resendType)){
  1019. url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/resendOrder/"+orderSn;
  1020. }
  1021. // 同步访问,返回结果字符串
  1022. response = OkHttpUtils.post(map, url, "SSL");
  1023. ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
  1024. if(responseData.getCode().equalsIgnoreCase("0")){
  1025. List<WxOrderEntity> list = responseData.getData().getRows();
  1026. }
  1027. } catch (Exception e) {
  1028. logger.error("查询失败。"+e.getMessage());
  1029. }
  1030. return R.ok(response);
  1031. }
  1032. @RequestMapping("/orderDetail/{orderSn}")
  1033. public R orderDetail(@PathVariable("orderSn") String orderSn) throws IOException {
  1034. OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordService.queryObjectByOrderSn(orderSn);
  1035. OrderEntity orderEntity = orderService.queryObjectByOrderSn(orderSn);
  1036. Map map = new HashMap();
  1037. map.put("orderId",orderEntity.getId());
  1038. List<OrderGoodsEntity> goodsList = orderGoodsService.queryList(map);
  1039. BigDecimal tax = new BigDecimal(0);
  1040. for(OrderGoodsEntity orderGoodsEntity : goodsList){
  1041. BigDecimal retailPrice = orderGoodsEntity.getRetailPrice();
  1042. BigDecimal goodsRate = orderGoodsEntity.getGoodsRate();
  1043. Integer number = orderGoodsEntity.getNumber();
  1044. GoodsEntity goodsEntity = goodsService.queryObject(orderGoodsEntity.getGoodsId());
  1045. BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity,retailPrice,goodsService).setScale(3,RoundingMode.HALF_UP);
  1046. goodsTax = goodsTax.multiply(new BigDecimal(number)).setScale(2,RoundingMode.HALF_UP);
  1047. orderGoodsEntity.setTax(goodsTax);
  1048. tax = tax.add(goodsTax).setScale(2,RoundingMode.HALF_UP);
  1049. // BigDecimal goodsTax = retailPrice.divide(new BigDecimal(1).add(goodsRate),2,RoundingMode.HALF_DOWN).multiply(goodsRate).multiply(new BigDecimal(number)).setScale(0,RoundingMode.HALF_DOWN);
  1050. }
  1051. String response = null;
  1052. try {
  1053. // 查询失败原因
  1054. String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl() + "/"+orderSn;
  1055. // 同步访问,返回结果字符串
  1056. response = OkHttpUtils.post(map, url, "SSL");
  1057. } catch (Exception e) {
  1058. logger.error("查询失败。"+e.getMessage());
  1059. }
  1060. Map<String,Object> result = new HashMap<>();
  1061. result.put("orderProcessRecordEntity",orderProcessRecordEntity);
  1062. result.put("orderEntity",orderEntity);
  1063. result.put("goodsList",goodsList);
  1064. result.put("tax",tax.setScale(2, RoundingMode.HALF_DOWN).toString());
  1065. result.put("response",response);
  1066. return R.ok().put("resultObj", result);
  1067. }
  1068. @RequestMapping("/queryIDCardInfo/{mobile}")
  1069. public R queryIDCardInfo(@PathVariable("mobile")String mobile) throws IOException {
  1070. UserEntity userEntity = userService.queryByMobile(mobile);
  1071. if (userEntity == null) {
  1072. return R.error("该手机号未找到对应信息");
  1073. }
  1074. return R.ok().put("userEntity",userEntity);
  1075. }
  1076. @RequestMapping("/purchaseSalesInStockDetail")
  1077. // @RequiresPermissions("order:offilineOrderList")
  1078. public R purchaseSalesInStockDetail(@RequestParam Map<String, Object> params) {
  1079. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  1080. //查询列表数据
  1081. Query query = new Query(params);
  1082. List<PurchaseSalesInStockDetail> orderList = orderService.purchaseSalesInStockDetailList(query);
  1083. int total = orderService.purchaseSalesInStockDetailTotal(query);
  1084. // 遍历循环订单是哪个店员销售的,根据订单号查询
  1085. PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
  1086. return R.ok().put("page", pageUtil);
  1087. }
  1088. /**
  1089. * 线下订单导出请求
  1090. */
  1091. @RequiresPermissions("order:exportOffilineOrder")
  1092. @RequestMapping(value = "exportOffilineOrder")
  1093. public R exportOffilineOrder(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
  1094. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  1095. params = ParamUtils.setTimeMap(params);
  1096. params.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_1.getItem());
  1097. ExcelExport ee = new ExcelExport("线下订单信息");
  1098. //查询列表数据
  1099. // =================================================线下订单明细导出开始=====================================
  1100. List<OrderEntity> orderEntityList = orderService.queryExportOffilineOrderList(params);
  1101. String[] header = new String[]{"订单号", "操作店员", "购买类型", "订单业务类型", "订单状态",
  1102. "付款状态", "sku", "商品名称", "数量", "实际支付", /*"订单总价",*/ "下单时间", "付款时间", "零售价", "优惠金额", "成交价"};
  1103. List<Map<String, Object>> list = new LinkedList<>();
  1104. if (orderEntityList != null && orderEntityList.size() > 0) {
  1105. for (OrderEntity orderEntity : orderEntityList) {
  1106. LinkedHashMap<String, Object> map = new LinkedHashMap<>();
  1107. // 订单业务类型
  1108. String orderBizType = orderEntity.getOrderBizType();
  1109. // 订单状态
  1110. Integer orderStatus = orderEntity.getOrderStatus();
  1111. // 付款状态
  1112. Integer payStatus = orderEntity.getPayStatus();
  1113. map.put("OrderSn", orderEntity.getOrderSn());
  1114. map.put("UserName", orderEntity.getUserName());
  1115. map.put("IsOnfflineOrder", Dict.isOnfflineOrder.item_1.getItem().equals(orderEntity.getIsOnfflineOrder()) ? "线下购买" : "线上购买");
  1116. map.put("OrderBizType", StringUtils.isEmpty(orderBizType)?"":Dict.orderBizType.valueOf("item_"+orderBizType).getItemName());
  1117. map.put("OrderStatus", Dict.orderStatus.valueOf("item_"+orderStatus).getItemName());
  1118. map.put("PayStatus", Dict.payStatus.valueOf("item_"+payStatus).getItemName());
  1119. map.put("Sku", orderEntity.getSku());
  1120. map.put("GoodsName", orderEntity.getGoodsName());
  1121. map.put("Number", orderEntity.getNumber());
  1122. map.put("ActualPrice", orderEntity.getActualPrice()); // 实际支付价
  1123. // map.put("OrderPrice", orderEntity.getOrderPrice()); // 订单总价
  1124. map.put("AddTime", orderEntity.getAddTime());
  1125. map.put("PayTime", orderEntity.getPayTime());
  1126. map.put("SellPrice", orderEntity.getRetailPrice()); // 零售价
  1127. map.put("CouponPrice", orderEntity.getCouponPrice()); // 促销价
  1128. map.put("FinalPrice", orderEntity.getActualPrice()); // 成交价
  1129. list.add(map);
  1130. }
  1131. }
  1132. // =================================================线下订单明细导出结束=====================================
  1133. // =================================================线下订单导出开始=====================================
  1134. List<OrderEntity> masterOrderEntityList = orderService.queryMasterExportOffilineOrderList(params);
  1135. String[] headerMaster = new String[]{"订单号", "操作店员", "购买类型", "订单业务类型", "订单状态",
  1136. "付款状态", "实际支付", "订单总价", "下单时间", "付款时间"};
  1137. List<Map<String, Object>> listMaster = new LinkedList<>();
  1138. if (masterOrderEntityList != null && masterOrderEntityList.size() > 0) {
  1139. for (OrderEntity orderEntity : masterOrderEntityList) {
  1140. LinkedHashMap<String, Object> map = new LinkedHashMap<>();
  1141. // 订单业务类型
  1142. String orderBizType = orderEntity.getOrderBizType();
  1143. // 订单状态
  1144. Integer orderStatus = orderEntity.getOrderStatus();
  1145. // 付款状态
  1146. Integer payStatus = orderEntity.getPayStatus();
  1147. map.put("OrderSn", orderEntity.getOrderSn());
  1148. map.put("UserName", orderEntity.getUserName());
  1149. map.put("IsOnfflineOrder", Dict.isOnfflineOrder.item_1.getItem().equals(orderEntity.getIsOnfflineOrder()) ? "线下购买" : "线上购买");
  1150. map.put("OrderBizType", StringUtils.isEmpty(orderBizType)?"":Dict.orderBizType.valueOf("item_"+orderBizType).getItemName());
  1151. map.put("OrderStatus", Dict.orderStatus.valueOf("item_"+orderStatus).getItemName());
  1152. map.put("PayStatus", Dict.payStatus.valueOf("item_"+payStatus).getItemName());
  1153. map.put("ActualPrice", orderEntity.getActualPrice());
  1154. map.put("OrderPrice", orderEntity.getOrderPrice());
  1155. map.put("AddTime", orderEntity.getAddTime());
  1156. map.put("PayTime", orderEntity.getPayTime());
  1157. listMaster.add(map);
  1158. }
  1159. }
  1160. // =================================================线下订单导出结束=====================================
  1161. ee.addSheetByMap("线下订单信息", listMaster, headerMaster);
  1162. ee.addSheetByMap("线下订单明细信息", list, header);
  1163. ee.export(response);
  1164. return R.ok();
  1165. }
  1166. @RequestMapping("/queryOrderStatus/{orderSn}")
  1167. public R queryOrderStatus(@PathVariable("orderSn")String orderSn){
  1168. try {
  1169. // 根据订单查询是什么支付方式
  1170. OrderEntity order = orderService.queryObjectByOrderSn(orderSn);
  1171. if(order == null){
  1172. return R.error("该订单不存在");
  1173. }
  1174. String payFlag = order.getPayFlag();
  1175. if("alipay".equals(payFlag)){
  1176. AliPayMicropayApiResult aliPayMicropayApiResult = AliPayUtil.aliTradeQuery(orderSn, "");
  1177. String tradeStatus = aliPayMicropayApiResult.getTradeStatus();
  1178. if(StringUtils.isBlank(tradeStatus)){
  1179. return R.error("交易不存在");
  1180. }
  1181. return R.ok("订单号:" +orderSn + "支付方式为:支付宝支付,"+
  1182. "订单支付状态:"+tradeStatus);
  1183. }else if("weixin".equals(payFlag)){
  1184. WechatRefundApiResult wechatRefundApiResult = WechatUtil.wxOrderQuery(orderSn);
  1185. String tradeState = wechatRefundApiResult.getTrade_state();
  1186. String tradeStateDesc = wechatRefundApiResult.getTrade_state_desc();
  1187. if(StringUtils.isBlank(tradeState)){
  1188. return R.error("交易不存在");
  1189. }
  1190. return R.ok("订单号:" +orderSn + "支付方式为:微信支付,"+
  1191. "订单支付状态:"+tradeState+"。 交易详情:"+tradeStateDesc);
  1192. }else{
  1193. return R.ok();
  1194. }
  1195. } catch (Exception e) {
  1196. e.printStackTrace();
  1197. return R.error();
  1198. }
  1199. }
  1200. @RequestMapping("/queryInveResponse/{orderSn}")
  1201. public R queryInveResponse(@PathVariable("orderSn")String orderSn){
  1202. try {
  1203. // 查询订单是否存在
  1204. // OrderEntity order = orderService.queryObjectByOrderSn(orderSn);
  1205. // if(order == null){
  1206. // return R.error("该订单不存在");
  1207. // }
  1208. List<String> resultMessage = orderService.queryInveResponse(orderSn);
  1209. if(resultMessage == null || resultMessage.size() == 0){
  1210. resultMessage.add("暂无回执");
  1211. }
  1212. return R.ok().put("resultMessage",resultMessage);
  1213. } catch (Exception e) {
  1214. e.printStackTrace();
  1215. return R.error("系统异常:"+e.getMessage());
  1216. }
  1217. }
  1218. @PostMapping("/calculateOrderDiscountPrice")
  1219. public R calculateOrderDiscountPrice(@RequestBody CalculateOrderDiscountPriceVO calculateOrderDiscountPriceVo) {
  1220. try {
  1221. CalculateOrderDiscountPriceResponseVO calculateOrderDiscountPriceResponseVO = orderService.calculateOrderDiscountPrice(calculateOrderDiscountPriceVo);
  1222. return R.ok().put("data", calculateOrderDiscountPriceResponseVO);
  1223. } catch (Exception e) {
  1224. return R.error("计算出错!请联系管理员!" + e.getMessage());
  1225. }
  1226. }
  1227. /**
  1228. * System Format 导出请求
  1229. */
  1230. @RequestMapping(value = "exportSystemFormat")
  1231. public R exportSystemFormat(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) throws ParseException {
  1232. ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
  1233. params = ParamUtils.setTimeMap(params);
  1234. params.put("isOnfiilineOrder", Dict.isOnfflineOrder.item_1.getItem());
  1235. ExcelExport ee = new ExcelExport("Daily sales report");
  1236. //查询列表数据
  1237. // =================================================System Format导出开始=====================================
  1238. List<SystemFormatDto> systemFormatList = orderService.queryExportSystemFormatList(params);
  1239. String[] header = new String[]{"Receipt No.","Store Name", "Cash Register No.", "Time Stamp Details (Date & Time)", "Staff ID", "Staff Name","Pay Flag","Order Status","Order SnWx","Order SnAli",
  1240. "HS Code", "HS Code Name", "E-matou Code", "PLU", "MychemID", "Product Name (EN)","Product Name (CN)", "Barcode", "Pack Size", "Product Specification",
  1241. "Brand","EDLP","Current Price","Cost Price",/*"Prime Cost","Goods Number",*/"Deduction Rate","Unit Sold","Sales","Tax amount","Total Sales incl. Tax","Tax Rate",
  1242. "GP ¥","GP %","Product Category","Supplier Name","Transaction Type","Sale Return Type","Remark"};
  1243. // LinkedHashMap<String, Object> headerMap = initHeaderMap();
  1244. List<Entry> headerMap = initHeaderMap();
  1245. // List<Map<String, Object>> list = new LinkedList<>();
  1246. List<List<Entry>> list = new ArrayList<>();
  1247. list.add(headerMap);
  1248. if (systemFormatList != null && systemFormatList.size() > 0) {
  1249. for (SystemFormatDto systemFormat : systemFormatList) {
  1250. List<Entry> entries = new ArrayList<>();
  1251. if (Objects.nonNull(systemFormat.getTaxRate()) && Objects.nonNull(systemFormat.getTotalSalesInclTax())){
  1252. BigDecimal unitSold = new BigDecimal(systemFormat.getUnitSold());
  1253. // 设置综合税额
  1254. BigDecimal totalSalesIncTax = new BigDecimal(systemFormat.getTotalSalesInclTax());
  1255. BigDecimal taxRate = new BigDecimal(systemFormat.getTaxRate());
  1256. // GoodsEntity goodsEntity = goodsService.queryObject(systemFormat.getGoodsId());
  1257. // BigDecimal goodsTax = CalculateTax.calculateFinalTax(goodsEntity,totalSalesIncTax.divide(unitSold,2,RoundingMode.HALF_UP),goodsService).setScale(3,RoundingMode.HALF_UP);
  1258. // goodsTax = goodsTax.multiply(unitSold).setScale(2,RoundingMode.HALF_UP);
  1259. String goodsTax = systemFormat.getTaxPrice();
  1260. systemFormat.setSales(totalSalesIncTax.subtract(new BigDecimal(goodsTax)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
  1261. systemFormat.setTaxAmount(totalSalesIncTax.subtract(new BigDecimal(systemFormat.getSales())).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
  1262. // 设置实际销售额
  1263. systemFormat.setCurrentPrice(totalSalesIncTax.divide(unitSold,2,BigDecimal.ROUND_HALF_UP).setScale(2,BigDecimal.ROUND_HALF_UP).toEngineeringString());
  1264. if (Dict.orderStatus.item_401.getItem().equals(systemFormat.getOrderStatus())){
  1265. systemFormat.setUnitSold("-"+ unitSold);
  1266. systemFormat.setSales("-"+systemFormat.getSales());
  1267. systemFormat.setTaxAmount("-"+systemFormat.getTaxAmount());
  1268. systemFormat.setTotalSalesInclTax("-"+systemFormat.getTotalSalesInclTax());
  1269. }
  1270. }
  1271. if (Objects.nonNull(systemFormat.getCurrentPrice()) && Objects.nonNull(systemFormat.getEdlp())){
  1272. // 设置扣率
  1273. BigDecimal edlp = new BigDecimal(systemFormat.getEdlp());
  1274. BigDecimal currentPrice = new BigDecimal(systemFormat.getCurrentPrice());
  1275. if (!"0".equals(systemFormat.getEdlp()) && edlp.compareTo(BigDecimal.ZERO)!=0) {
  1276. systemFormat.setDeductionRate(new BigDecimal(1).subtract(currentPrice.divide(edlp, 4, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString()+"%");
  1277. }
  1278. if (Objects.nonNull(systemFormat.getCostPrice())){
  1279. // 设置GP ¥
  1280. systemFormat.setGp1(currentPrice.subtract(new BigDecimal(systemFormat.getCostPrice())).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
  1281. // 设置GP %
  1282. if (!"0".equals(systemFormat.getCurrentPrice()) && StringUtils.isNotEmpty(systemFormat.getCurrentPrice())
  1283. && currentPrice.compareTo(BigDecimal.ZERO)!=0) {
  1284. BigDecimal gp1 = new BigDecimal(systemFormat.getGp1());
  1285. systemFormat.setGp2(gp1.divide(currentPrice, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "%");
  1286. }
  1287. if (Dict.orderStatus.item_401.getItem().equals(systemFormat.getOrderStatus())){
  1288. if (!systemFormat.getGp1().contains("-")) {
  1289. systemFormat.setGp1("-" + systemFormat.getGp1());
  1290. }
  1291. if (StringUtils.isNotEmpty(systemFormat.getGp2()) && !systemFormat.getGp2().contains("-")) {
  1292. systemFormat.setGp2("-" + systemFormat.getGp2());
  1293. }
  1294. }
  1295. }
  1296. }
  1297. // 如果是退货
  1298. String orderStatus = systemFormat.getOrderStatus();
  1299. if (Dict.orderStatus.item_401.getItem().equals(orderStatus)){
  1300. systemFormat.setSaleReturnType("整单退货");
  1301. systemFormat.setTransactionType("退货");
  1302. }else{
  1303. systemFormat.setTransactionType("销售");
  1304. }
  1305. orderStatus = Dict.orderStatus.valueOf("item_"+orderStatus).getItemName();
  1306. if (Objects.nonNull(systemFormat.getPrimeCost()) && Objects.nonNull(systemFormat.getGoodsNumber())) {
  1307. String primeCost = systemFormat.getPrimeCost();
  1308. BigDecimal gp = new BigDecimal(primeCost);
  1309. primeCost = gp.setScale(2,BigDecimal.ROUND_HALF_UP).toString();
  1310. systemFormat.setPrimeCost(primeCost);
  1311. }
  1312. entries.add(new Entry("ReceiptNo",systemFormat.getReceiptNo()));
  1313. entries.add(new Entry("StoreName",systemFormat.getStoreName()));
  1314. entries.add(new Entry("CashRegisterNo",systemFormat.getCashRegisterNo()));
  1315. entries.add(new Entry("TimeStampDetails",systemFormat.getTimeStampDetails()));
  1316. entries.add(new Entry("StaffID",systemFormat.getStaffID()));
  1317. entries.add(new Entry("StaffName",systemFormat.getStaffName()));
  1318. entries.add(new Entry("PayFlag",systemFormat.getPayFlag()));
  1319. entries.add(new Entry("OrderStatus",orderStatus));
  1320. entries.add(new Entry("OrderSnWx",systemFormat.getOrderSnWx()));
  1321. entries.add(new Entry("OrderSnAli",systemFormat.getOrderSnAli()));
  1322. entries.add(new Entry("HSCode",systemFormat.getHsCode()));
  1323. entries.add(new Entry("HSCodeName",systemFormat.getHsCodeName()));
  1324. entries.add(new Entry("EmatouCode",systemFormat.getEmatouCode()));
  1325. entries.add(new Entry("PLU",systemFormat.getPlu()));
  1326. entries.add(new Entry("MychemID",systemFormat.getMychemID()));
  1327. entries.add(new Entry("ProductNameEN",systemFormat.getProductNameEN()));
  1328. entries.add(new Entry("ProductNameCN",systemFormat.getProductNameCN()));
  1329. entries.add(new Entry("Barcode",systemFormat.getBarcode()));
  1330. entries.add(new Entry("PackSize",systemFormat.getPackSize()));
  1331. entries.add(new Entry("ProductSpecification",systemFormat.getProductSpecification()));
  1332. entries.add(new Entry("Brand",systemFormat.getBrand()));
  1333. entries.add(new Entry("EDLP",systemFormat.getEdlp()));
  1334. entries.add(new Entry("CurrentPrice",systemFormat.getCurrentPrice()));
  1335. entries.add(new Entry("CostPrice",systemFormat.getCostPrice()));
  1336. // entries.add(new Entry("PrimeCost",systemFormat.getPrimeCost()));
  1337. // entries.add(new Entry("GoodsNumber",systemFormat.getGoodsNumber()));
  1338. entries.add(new Entry("DeductionRate",systemFormat.getDeductionRate()));
  1339. entries.add(new Entry("UnitSold",systemFormat.getUnitSold()));
  1340. entries.add(new Entry("Sales",systemFormat.getSales()));
  1341. entries.add(new Entry("TaxAmount",systemFormat.getTaxAmount()));
  1342. entries.add(new Entry("TotalSalesInclTax",systemFormat.getTotalSalesInclTax()));
  1343. entries.add(new Entry("TaxRate",systemFormat.getTaxRate()));
  1344. entries.add(new Entry("GP1",systemFormat.getGp1()));
  1345. entries.add(new Entry("GP2",systemFormat.getGp2()));
  1346. entries.add(new Entry("ProductCategory",systemFormat.getProductCategory()));
  1347. entries.add(new Entry("SupplierName",systemFormat.getSupplierName()));
  1348. entries.add(new Entry("TransactionType",systemFormat.getTransactionType()));
  1349. entries.add(new Entry("SaleReturnType",systemFormat.getSaleReturnType()));
  1350. entries.add(new Entry("Remark",systemFormat.getRemark()));
  1351. list.add(entries);
  1352. }
  1353. }
  1354. // =================================================System Format导出结束=====================================
  1355. ee.addSheetByList("Daily sales report", list, header);
  1356. ee.export(response);
  1357. return R.ok();
  1358. }
  1359. private ArrayList<Entry> initHeaderMap() {
  1360. // LinkedHashMap<String, Object> headerMap = new LinkedHashMap<>();
  1361. ArrayList<Entry> entries = new ArrayList<>();
  1362. entries.add(new Entry("ReceiptNo","销售单号"));
  1363. entries.add(new Entry("StoreName","门店名称"));
  1364. entries.add(new Entry("CashRegisterNo","收银台"));
  1365. entries.add(new Entry("TimeStampDetails","销售时间"));
  1366. entries.add(new Entry("StaffID","收银员"));
  1367. entries.add(new Entry("StaffName","收银员姓名"));
  1368. entries.add(new Entry("PayFlag","支付方式"));
  1369. entries.add(new Entry("OrderStatus","支付状态"));
  1370. entries.add(new Entry("OrderSnWx","微信流水号"));
  1371. entries.add(new Entry("OrderSnAli","支付宝流水号"));
  1372. entries.add(new Entry("HSCode","海关商品编码"));
  1373. entries.add(new Entry("HSCodeName","品类名称"));
  1374. entries.add(new Entry("EmatouCode","料件号"));
  1375. entries.add(new Entry("PLU","PLU"));
  1376. entries.add(new Entry("MychemID","MychemID"));
  1377. entries.add(new Entry("ProductNameEN","商品名称(英文)"));
  1378. entries.add(new Entry("ProductNameCN","商品名称(中文)"));
  1379. entries.add(new Entry("Barcode","商品主条码"));
  1380. entries.add(new Entry("PackSize","规格"));
  1381. entries.add(new Entry("ProductSpecification","单位"));
  1382. entries.add(new Entry("Brand","品牌"));
  1383. entries.add(new Entry("EDLP","日常价"));
  1384. entries.add(new Entry("CurrentPrice","实际销售价"));
  1385. entries.add(new Entry("CostPrice","进货价"));
  1386. // entries.add(new Entry("PrimeCost","成本价");
  1387. // entries.add(new Entry("GoodsNumber","可用库存数");
  1388. entries.add(new Entry("DeductionRate","扣率 (EDLP vs 实际销售价)"));
  1389. entries.add(new Entry("UnitSold","销售数量"));
  1390. entries.add(new Entry("Sales","销售额"));
  1391. entries.add(new Entry("TaxAmount","综合税额"));
  1392. entries.add(new Entry("TotalSalesInclTax","总销售额"));
  1393. entries.add(new Entry("TaxRate","综合税率"));
  1394. entries.add(new Entry("GP1","预估毛利额"));
  1395. entries.add(new Entry("GP2","预估毛利率"));
  1396. entries.add(new Entry("ProductCategory","商品类型"));
  1397. entries.add(new Entry("SupplierName","主供应商名称"));
  1398. entries.add(new Entry("TransactionType","销售类型"));
  1399. entries.add(new Entry("SaleReturnType","退货类型"));
  1400. entries.add(new Entry("Remark","备注"));
  1401. return entries;
  1402. }
  1403. /**
  1404. * 重发订单
  1405. * @param orderSn
  1406. * @return
  1407. */
  1408. @RequestMapping("/resendOrderHkMall/{orderSn}")
  1409. public R resendOrderHkMall(@PathVariable("orderSn") String orderSn){
  1410. return orderService.resendOrderHkMall(orderSn);
  1411. }
  1412. }