1
0

OrderController.java 78 KB

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