OrderController.java 79 KB

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