PosOrderController.java 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  1. package com.ruoyi.app.order;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  7. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  8. import com.baomidou.mybatisplus.core.metadata.IPage;
  9. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  10. import com.fasterxml.jackson.databind.ObjectMapper;
  11. import com.fasterxml.jackson.databind.SerializationFeature;
  12. import com.ruoyi.app.order.dto.OrderPositionInfo;
  13. import com.ruoyi.app.order.dto.OrderPushBodyDto;
  14. import com.ruoyi.app.order.dto.PositionDto;
  15. import com.ruoyi.app.order.dto.QsDto;
  16. import com.ruoyi.app.order.dto.AdminOrderActionRequest;
  17. import com.ruoyi.app.order.dto.AdminOrderStatusContext;
  18. import com.ruoyi.app.pay.LinePayService;
  19. import com.ruoyi.app.pay.LinePayRefundService;
  20. import com.ruoyi.app.order.dto.AdminOrderStatusUpdateRequest;
  21. import com.ruoyi.app.service.UserService;
  22. import com.ruoyi.app.service.WalletService;
  23. import com.ruoyi.app.user.dto.StoreOutput;
  24. import com.ruoyi.app.utils.DateUtil;
  25. import com.ruoyi.app.utils.OperatingUtil;
  26. import com.ruoyi.app.utils.PayPush;
  27. import com.ruoyi.app.utils.event.PushEventService;
  28. import com.ruoyi.common.annotation.Anonymous;
  29. import com.ruoyi.common.annotation.Log;
  30. import com.ruoyi.common.annotation.RepeatSubmit;
  31. import com.ruoyi.common.core.controller.BaseController;
  32. import com.ruoyi.common.core.domain.AjaxResult;
  33. import com.ruoyi.common.core.page.TableDataInfo;
  34. import com.ruoyi.common.enums.BusinessType;
  35. import com.ruoyi.common.exception.ServiceException;
  36. import com.ruoyi.common.utils.MessageUtils;
  37. import com.ruoyi.common.utils.StringUtils;
  38. import com.ruoyi.framework.manager.AsyncManager;
  39. import com.ruoyi.common.utils.poi.ExcelUtil;
  40. import com.ruoyi.system.domain.*;
  41. import com.ruoyi.system.domain.vo.OrderDTO;
  42. import com.ruoyi.system.domain.vo.PosOrderInvoiceVo;
  43. import com.ruoyi.system.mapper.PosFoodMapper;
  44. import com.ruoyi.system.mapper.PosOrderMapper;
  45. import com.ruoyi.system.mapper.PosOrderPromotionMapper;
  46. import com.ruoyi.system.mapper.UserBillingMapper;
  47. import com.ruoyi.system.omgpay.domain.OmgPaymentAttempt;
  48. import com.ruoyi.system.omgpay.service.IOmgPaymentAttemptService;
  49. import com.ruoyi.system.service.*;
  50. import com.ruoyi.system.utils.Auth;
  51. import com.ruoyi.system.utils.GetArea;
  52. import com.ruoyi.system.utils.JwtUtil;
  53. import com.ruoyi.system.utils.OrderLogHelper;
  54. import com.ruoyi.common.utils.SecurityUtils;
  55. import com.ruoyi.common.core.domain.entity.SysUser;
  56. import lombok.SneakyThrows;
  57. import org.redisson.api.RLock;
  58. import org.redisson.api.RedissonClient;
  59. import org.springframework.beans.BeanUtils;
  60. import org.springframework.beans.factory.annotation.Autowired;
  61. import org.springframework.context.i18n.LocaleContextHolder;
  62. import org.springframework.security.access.prepost.PreAuthorize;
  63. import org.springframework.transaction.annotation.Isolation;
  64. import org.springframework.transaction.annotation.Transactional;
  65. import org.springframework.transaction.support.TransactionSynchronization;
  66. import org.springframework.transaction.support.TransactionSynchronizationManager;
  67. import org.springframework.web.bind.annotation.*;
  68. import jakarta.servlet.http.HttpServletResponse;
  69. import jakarta.validation.Valid;
  70. import java.math.BigDecimal;
  71. import java.text.DecimalFormat;
  72. import java.util.*;
  73. import java.util.concurrent.TimeUnit;
  74. import java.util.stream.Collectors;
  75. import java.util.stream.Stream;
  76. /**
  77. * posorderController
  78. *
  79. * @author ruoyi
  80. * @date 2023-05-23
  81. */
  82. @RestController
  83. @RequestMapping("/system/order")
  84. public class PosOrderController extends BaseController {
  85. @Autowired
  86. private IPosOrderService posOrderService;
  87. @Autowired
  88. private IInfoUserService infoUserService;
  89. @Autowired
  90. private IPosStoreService posStoreService;
  91. @Autowired
  92. private IInfoAddressService infoAddressService;
  93. @Autowired
  94. private IUserFootprintService userFootprintService;
  95. @Autowired
  96. private PosOrderMapper posOrderMapper;
  97. @Autowired
  98. private IRiderPositionService riderPositionService;
  99. @Autowired
  100. private IUserBillingService userBillingService;
  101. @Autowired
  102. private UserBillingMapper userBillingMapper;
  103. @Autowired
  104. private IPosMarginService posMarginService;
  105. @Autowired
  106. private ISalesPromotionService salesPromotionService;
  107. @Autowired
  108. private IPosAppealService posAppealService;
  109. @Autowired //商品
  110. private IPosFoodService posFoodService;
  111. @Autowired //经营时间
  112. private IOperatingHoursService operatingHoursService;
  113. @Autowired
  114. private IVipUserQuanyiService userQuanyiService;
  115. @Autowired
  116. private ISysPointControlService pointControlService;
  117. @Autowired
  118. private IUserWalletService userWalletService;
  119. @Autowired
  120. private IPointsTransactionService pointsTransactionService;
  121. @Autowired
  122. private PushEventService pushEventService;
  123. @Autowired
  124. private DeliveryOrderNotificationService deliveryOrderNotificationService;
  125. @Autowired
  126. private IPosOrderRatingService posOrderRatingService;
  127. @Autowired
  128. private IFoodStatisticsService foodStatisticsService;
  129. @Autowired
  130. private IOrderParentService orderParentService;
  131. @Autowired
  132. private WalletService walletService;
  133. @Autowired
  134. private PosFoodMapper posFoodMapper;
  135. @Autowired
  136. private RedissonClient redissonClient;
  137. @Autowired
  138. private UserService userService;
  139. @Autowired
  140. private OrderService orderService;
  141. @Autowired
  142. private PosOrderShOprateController shOprateController;
  143. @Autowired
  144. private OrderLogHelper orderLogHelper;
  145. @Autowired
  146. private PosOrderPromotionMapper posOrderPromotionMapper;
  147. @Autowired
  148. private OrderInvoiceService orderInvoiceService;
  149. @Autowired
  150. private OrderLifecycleService orderLifecycleService;
  151. @Autowired
  152. private LinePayService linePayService;
  153. @Autowired
  154. private LinePayRefundService linePayRefundService;
  155. @Autowired
  156. private com.ruoyi.app.pay.LinePayOrderGuard linePayOrderGuard;
  157. @Autowired
  158. private IPosOrderLinePaymentService linePaymentService;
  159. @Autowired
  160. private IOmgPaymentAttemptService omgPaymentAttemptService;
  161. //查询用户足迹
  162. @Anonymous
  163. @Auth
  164. @GetMapping("/getuserfootlist")
  165. public AjaxResult getuserfootlist(@RequestHeader String token, @RequestParam Integer page, @RequestParam Integer size) {
  166. JwtUtil jwtUtil = new JwtUtil();
  167. String id = jwtUtil.getusid(token);
  168. IPage<UserFootprint> palist = new Page<>(page, size);
  169. QueryWrapper<UserFootprint> queryWrapper = new QueryWrapper<>();
  170. queryWrapper.select().orderByDesc("cretim");
  171. queryWrapper.eq("user_id", id);
  172. IPage<UserFootprint> list = userFootprintService.page(palist, queryWrapper);
  173. List<UserFootprint> footprints = list.getRecords();
  174. // 收集所有门店ID(Integer类型)
  175. List<Long> storeIds = footprints.stream()
  176. .map(UserFootprint::getMdId)
  177. .toList();
  178. // 使用MyBatis Plus一次性查询所有门店的商品(避免N+1查询问题)
  179. Map<Integer, List<PosFood>> foodMap = new java.util.HashMap<>();
  180. if (!storeIds.isEmpty()) {
  181. // 将Integer类型的门店ID转换为Long类型用于查询(因为mdid是Long类型)
  182. List<Long> storeIdsLong = storeIds.stream()
  183. .map(x -> x)
  184. .collect(Collectors.toList());
  185. // 使用MyBatis Plus的Mapper方法,在数据库查询时就限制每个门店只返回6条商品
  186. List<PosFood> allFoods = posFoodMapper.selectFoodsByStoreIdsWithLimit(storeIdsLong, "3", 6);
  187. // 按门店ID分组(查询结果已经限制为每个门店最多6条)
  188. foodMap = allFoods.stream()
  189. .collect(Collectors.groupingBy(food -> food.getMdid().intValue()));
  190. }
  191. // 转换为StoreOutput并设置每个门店的商品列表(每个门店最多6条)
  192. List<StoreOutput> storeOutputList = new ArrayList<>();
  193. for (UserFootprint collect : footprints) {
  194. PosStore store = posStoreService.getById(collect.getMdId());
  195. if (store != null) {
  196. StoreOutput storeOutput = new StoreOutput();
  197. // 复制PosStore的所有属性
  198. BeanUtils.copyProperties(store, storeOutput);
  199. // 从分组结果中获取该门店的商品列表(已限制为最多6条)
  200. List<PosFood> foodList = foodMap.getOrDefault(store.getId(), new ArrayList<>());
  201. storeOutput.setFoodList(foodList);
  202. storeOutputList.add(storeOutput);
  203. }
  204. }
  205. Page<StoreOutput> result = new Page<>(page, 10);
  206. result.setTotal(list.getTotal());
  207. result.setRecords(storeOutputList);
  208. return success(result);
  209. }
  210. //修改订单
  211. @Anonymous
  212. @Auth
  213. @RepeatSubmit(interval = 1000, message = "请求过于频繁")
  214. @PostMapping("/setorderuzt")
  215. @Transactional(rollbackFor = Exception.class)
  216. public AjaxResult setorderuzt(@RequestHeader String token, @RequestBody PosOrder posOrder) {
  217. JwtUtil jwtUtil = new JwtUtil();
  218. PayPush push = new PayPush();
  219. String id = jwtUtil.getusid(token);
  220. PosOrder persisted = posOrder.getId() == null ? null : posOrderService.getById(posOrder.getId());
  221. boolean actualLineOrder = persisted != null && linePaymentService != null
  222. && !linePaymentService.getByDdId(String.valueOf(persisted.getDdId())).isEmpty();
  223. if (actualLineOrder) {
  224. throw new ServiceException(lineMessage("line.pay.legacy.endpoint.disabled",
  225. "LINE Pay order must use the dedicated order operation endpoint"));
  226. }
  227. if (posOrder.getState() != null) {
  228. if (posOrder.getId() != null && posOrder.getState() != 0L) {
  229. linePayOrderGuard.requirePaidBeforeAccept(persisted);
  230. }
  231. //状态为送达,设置送达时间
  232. if (posOrder.getState() == 12) {
  233. posOrder.setSdTime(new Date());
  234. }
  235. System.out.println("修改订单状态信息:" + JSON.toJSONString(posOrder));
  236. //设置支付类型为货到付款
  237. if (!actualLineOrder && posOrder.getState() == 0
  238. && "1".equals(posOrder.getCollectPayment())) {
  239. System.out.println("进入设置paytype等于1");
  240. posOrder.setPayType("1");
  241. }
  242. //取餐时设置预计送达时间
  243. setYjsdTime(posOrder);
  244. if (posOrder.getState() == 5) {
  245. return setOrderState5(posOrder);
  246. } else if (posOrder.getState() == 2) {
  247. return setOrderState2(posOrder, id);
  248. } else if (posOrder.getState() == 3 || posOrder.getState() == 4 || posOrder.getState() == 12) {
  249. return setOrderQsState(posOrder, id, push);
  250. } else if (posOrder.getState() == 7) {
  251. return setOrderState7(posOrder);
  252. } else {
  253. boolean org = posOrderService.saveOrUpdate(posOrder);
  254. PosOrder order = posOrderService.getById(posOrder.getId());
  255. if (order.getState() == 0 && order.getCollectPayment().equals("1")) {
  256. sendHdfkMessage(order);
  257. }
  258. //作废退回积分
  259. if (posOrder.getState() == 10 && order.getPoints() != null && order.getPoints() > 0) {
  260. returnPoints(order.getUserId(), Long.valueOf(order.getDdId()), Long.valueOf(order.getPoints()));
  261. }
  262. if (org) {
  263. // 平台管理员修改订单状态,添加操作日志
  264. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  265. String adminName = adminUser != null ? adminUser.getNickName() : "";
  266. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  267. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  268. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  269. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  270. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  271. } else {
  272. return error();
  273. }
  274. }
  275. } else {
  276. return setOrderNoState(posOrder, id);
  277. }
  278. }
  279. //骑手接单、取餐、送达
  280. private AjaxResult setOrderQsState(PosOrder posOrder, String qsId, PayPush push) {
  281. String lockKey = "order:qs:lock:" + posOrder.getId();
  282. RLock lock = redissonClient.getLock(lockKey);
  283. try {
  284. var local = LocaleContextHolder.getLocale();
  285. logger.info("骑手接单local信息:" + local.getLanguage());
  286. logger.info(JSON.toJSONString(local));
  287. // 尝试获取锁
  288. if (lock.tryLock(20L, 10L, TimeUnit.SECONDS)) {
  289. boolean releaseInfinally = true;
  290. try {
  291. userService.checkUserStatus(Long.valueOf(qsId));
  292. PosOrder orst = posOrderService.getById(posOrder.getId());
  293. if (orst.getState() == 3 && posOrder.getState() == 3) {
  294. throw new ServiceException(MessageUtils.message("no.order.snatched"));
  295. }
  296. if (posOrder.getState() == 3) {
  297. QueryWrapper<PosOrder> wrapper = new QueryWrapper<>();
  298. wrapper.eq("qs_id", qsId);
  299. wrapper.in("state", 3, 4);
  300. List<PosOrder> orsts = posOrderService.list(wrapper);
  301. if (orsts.size() > 0) {
  302. throw new ServiceException(MessageUtils.message("no.exist.undelivered.order"));
  303. }
  304. }
  305. String userMessage = MessageUtils.message("no.message.push.delivery.personnel.receiving.order");
  306. if (posOrder.getState() == 4) {
  307. userMessage = MessageUtils.message("no.message.push.delivery.personnel.qspsz.order");
  308. } else if (posOrder.getState() == 12) {
  309. userMessage = MessageUtils.message("no.message.push.delivery.personnel.qsysd.order");
  310. }
  311. boolean org = posOrderService.saveOrUpdate(posOrder);
  312. if (org) {
  313. // 平台管理员修改订单状态(骑手操作),添加操作日志
  314. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  315. String adminName = adminUser != null ? adminUser.getNickName() : "";
  316. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  317. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  318. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  319. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  320. //到付订单,设置用户账单为完成
  321. if (posOrder.getState() == 3 && "1".equals(orst.getCollectPayment())) {
  322. updateUserBill(orst.getDdId(), orst.getUserId(), orst.getQsId());
  323. }
  324. InfoUser user = infoUserService.getById(orst.getUserId());
  325. InfoUser shu = infoUserService.getById(orst.getShId());
  326. String finalUserMessage = userMessage;
  327. releaseInfinally = false;
  328. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
  329. @Override
  330. public void afterCommit() {
  331. if (lock.isHeldByCurrentThread()) {
  332. lock.unlock();
  333. }
  334. // 给用户推送(骑手已接单/配送中/已送达)
  335. if (!StringUtils.isEmpty(user.getCid())) {
  336. String userTitle = "no.message.push.message";
  337. String userContent = "no.message.push.delivery.personnel.receiving.order";
  338. if (posOrder.getState() == 4) {
  339. userContent = "no.message.push.delivery.personnel.qspsz.order";
  340. } else if (posOrder.getState() == 12) {
  341. userContent = "no.message.push.delivery.personnel.qsysd.order";
  342. }
  343. final String finalUserContent = userContent;
  344. String userBody = OrderPushBodyDto.getJson(String.valueOf(orst.getDdId()), String.valueOf(posOrder.getState()));
  345. Long userUserId = user.getUserId();
  346. String userCid = user.getCid();
  347. String userCidType = "";
  348. String userDdId = String.valueOf(orst.getDdId());
  349. AsyncManager.me().execute(new TimerTask() {
  350. @Override
  351. public void run() {
  352. PayPush.userPushHandleLocal(push, pushEventService, userUserId, userCid, userTitle, finalUserContent, userBody, userCidType, userDdId);
  353. }
  354. });
  355. }
  356. // 给商家推送(骑手已接单时)
  357. if (!StringUtils.isEmpty(shu.getCid()) && posOrder.getState() == 3) {
  358. String shTitle = "no.message.push.message";
  359. String shContent = "no.message.push.delivery.personnel.receiving.order";
  360. String shBody = OrderPushBodyDto.getJson(String.valueOf(orst.getDdId()), String.valueOf(posOrder.getState()));
  361. Long shUserId = shu.getUserId();
  362. String shCid = shu.getCid();
  363. String shCidType = "";
  364. String shDdId = String.valueOf(orst.getDdId());
  365. AsyncManager.me().execute(new TimerTask() {
  366. @Override
  367. public void run() {
  368. PayPush.shPushHandleLocal(push, pushEventService, shUserId, shCid, shTitle, shContent, shBody, shCidType, shDdId);
  369. }
  370. });
  371. }
  372. }
  373. });
  374. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  375. } else {
  376. return error();
  377. }
  378. } finally {
  379. if (releaseInfinally && lock.isHeldByCurrentThread()) {
  380. lock.unlock();
  381. }
  382. }
  383. } else {
  384. throw new ServiceException(MessageUtils.message("no.system.busy.try.again"));
  385. }
  386. } catch (InterruptedException e) {
  387. Thread.currentThread().interrupt();
  388. throw new ServiceException(MessageUtils.message("no.operation.interrupted.try.again"));
  389. }
  390. }
  391. /**
  392. * 更新用户用户账单
  393. *
  394. * @param ddId
  395. * @param userId
  396. * @param qsId
  397. */
  398. private void updateUserBill(String ddId, Long userId, Long qsId) {
  399. QueryWrapper<UserBilling> queryWrapper = new QueryWrapper<>();
  400. queryWrapper.eq("dd_id", ddId);
  401. queryWrapper.eq("user_id", userId);
  402. queryWrapper.eq("type", "3");
  403. UserBilling userBill = userBillingService.getOne(queryWrapper);
  404. if (userBill != null) {
  405. userBill.setState("0");
  406. userBill.setIllustrate("Rider Payment Order");
  407. userBill.setBalancePay("1");
  408. userBill.setPaymentId(String.valueOf(qsId));
  409. userBillingService.saveOrUpdate(userBill);
  410. }
  411. }
  412. //商家接单
  413. private AjaxResult setOrderState2(PosOrder posOrder, String id) {
  414. int zsou = userBillingMapper.gettypesum(Long.valueOf(id), 1L);
  415. int zcz = userBillingMapper.gettypesum(Long.valueOf(id), 2L);
  416. int xiaof = userBillingMapper.gettypesum(Long.valueOf(id), 3L);
  417. int yure = zsou - zcz - xiaof;
  418. PosMargin posMargin = posMarginService.getById(1);
  419. InfoUser user = infoUserService.getById(id);
  420. if (user.getUserType().equals("1")) {
  421. boolean org = posOrderService.saveOrUpdate(posOrder);
  422. if (org) {
  423. PosOrder order = posOrderService.getById(posOrder.getId());
  424. // 平台管理员修改订单状态(商家接单),添加操作日志
  425. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  426. String adminName = adminUser != null ? adminUser.getNickName() : "";
  427. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  428. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  429. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  430. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  431. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  432. } else {
  433. return error();
  434. }
  435. } else {
  436. if (yure <= (int) Math.round(posMargin.getAmount())) {
  437. return error(MessageUtils.message("no.insufficient.user.security.deposit"));
  438. } else {
  439. boolean org = posOrderService.saveOrUpdate(posOrder);
  440. if (org) {
  441. PosOrder order = posOrderService.getById(posOrder.getId());
  442. // 平台管理员修改订单状态(商家接单),添加操作日志
  443. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  444. String adminName = adminUser != null ? adminUser.getNickName() : "";
  445. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  446. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  447. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  448. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  449. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  450. } else {
  451. return error();
  452. }
  453. }
  454. }
  455. }
  456. //订单完成
  457. private AjaxResult setOrderState5(PosOrder posOrder) {
  458. boolean org = posOrderService.saveOrUpdate(posOrder);
  459. if (org) {
  460. PosOrder order = posOrderService.getById(posOrder.getId());
  461. // 平台管理员修改订单状态(订单完成),添加操作日志
  462. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  463. String adminName = adminUser != null ? adminUser.getNickName() : "";
  464. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  465. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  466. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  467. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  468. QueryWrapper<UserBilling> wrapper = new QueryWrapper<>();
  469. wrapper.eq("dd_id", order.getDdId());
  470. UserBilling billing = userBillingService.getOne(wrapper);
  471. if (billing == null) {
  472. orderService.setSanghuBilling(order);
  473. orderService.setQishouBilling(order);
  474. }
  475. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  476. } else {
  477. return error();
  478. }
  479. }
  480. //同意退款
  481. private AjaxResult setOrderState7(PosOrder posOrder) {
  482. boolean org = posOrderService.saveOrUpdate(posOrder);
  483. PosOrder order = posOrderService.getById(posOrder.getId());
  484. // 平台管理员修改订单状态(同意退款),添加操作日志
  485. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  486. String adminName = adminUser != null ? adminUser.getNickName() : "";
  487. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  488. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  489. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  490. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  491. if (order.getPoints() != null && order.getPoints() > 0) {
  492. returnPoints(order.getUserId(), Long.valueOf(order.getDdId()), Long.valueOf(order.getPoints()));
  493. }
  494. if (org) {
  495. QueryWrapper<UserBilling> wrapper = new QueryWrapper<>();
  496. wrapper.eq("dd_id", posOrder.getId());
  497. List<UserBilling> billing = userBillingService.list(wrapper);
  498. if (billing.size() == 0) {
  499. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  500. } else {
  501. for (int i = 0; i < billing.size(); i++) {
  502. UserBilling user = new UserBilling();
  503. user.setId(billing.get(i).getId());
  504. user.setState("1");
  505. userBillingService.saveOrUpdate(user);
  506. }
  507. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  508. }
  509. } else {
  510. return error();
  511. }
  512. }
  513. //更改订单没传订单状态
  514. private AjaxResult setOrderNoState(PosOrder posOrder, String id) {
  515. PosOrder ordera = posOrderService.getById(posOrder.getId());
  516. //订单金额限制100万改为200万
  517. if (posOrder.getCollectPayment().equals("1") && ordera.getAmount() > 2000000) {
  518. return error(MessageUtils.message("no.cash_on_delivery_amount.exceed.limit_amount"));
  519. }
  520. QueryWrapper<PosOrder> query = new QueryWrapper<>();
  521. query.eq("user_id", id);
  522. query.eq("collect_payment", "1");
  523. query.notIn("state", 5, 10, 11);
  524. List<PosOrder> posOrders = posOrderService.list(query);
  525. //到付能存在2单未完成,第3单弹出提示;修改做判断的前提是当前订单不是为到付
  526. if (posOrders.size() >= 2 && posOrder.getCollectPayment().equals("1") && !"1".equals(ordera.getCollectPayment())) {
  527. return error(MessageUtils.message("no.exist.cash_on_delivery_order.incomplete"));
  528. }
  529. boolean org = posOrderService.saveOrUpdate(posOrder);
  530. if (org) {
  531. shOprateController.chuCan(ordera, posOrder);
  532. PosOrder order = posOrderService.getById(posOrder.getId());
  533. // 平台管理员修改订单状态(无状态变更),添加操作日志
  534. SysUser adminUser = SecurityUtils.getLoginUser().getUser();
  535. String adminName = adminUser != null ? adminUser.getNickName() : "";
  536. PosOrder beforeOrder = posOrderService.getById(posOrder.getId());
  537. String logDdId = beforeOrder != null ? String.valueOf(beforeOrder.getDdId()) : "";
  538. orderLogHelper.log(logDdId, 1, adminUser != null ? adminUser.getUserId() : null, adminName,
  539. "平台管理员" + adminName + "修改订单状态: " + (posOrder.getState() != null ? posOrder.getState() : ""));
  540. return success(MessageUtils.message("no.modify.success"), posOrder.getId());
  541. } else {
  542. return error();
  543. }
  544. }
  545. /**
  546. * 获取预计送达时间
  547. *
  548. * @param posOrder
  549. * @return
  550. */
  551. private String setYjsdTime(PosOrder posOrder) {
  552. try {
  553. if (posOrder.getState() == 4) {
  554. GetArea getArea = new GetArea();
  555. PosOrder order = posOrderService.getById(posOrder.getId());
  556. String mdlat = order.getLongitude() + "," + order.getLatitude();
  557. InfoAddress shDz = infoAddressService.getById(order.getShdzId());
  558. String shlat = shDz.getLongitude() + "," + shDz.getLatitude();
  559. double time = getArea.getMotorbikeDuration(mdlat, shlat);
  560. DateUtil dateUtil = new DateUtil();
  561. String start = dateUtil.getHourAndMinute((long) time);
  562. double endTime = time + 600; //加上10分钟
  563. String end = dateUtil.getHourAndMinute((long) endTime);
  564. posOrder.setYjsdTime(start + "-" + end);
  565. return start + "-" + end;
  566. }
  567. return "";
  568. } catch (Exception e) {
  569. logger.error("获取预计送达时间异常,id:" + posOrder.getId() + "异常信息:", e);
  570. return "";
  571. }
  572. }
  573. //修改订单
  574. @Anonymous
  575. @PostMapping("/testYjsdTime")
  576. public String testYjsdTime(@RequestBody PosOrder order) {
  577. return setYjsdTime(order);
  578. }
  579. //后台查询详情
  580. @GetMapping("/getorderhout")
  581. public AjaxResult getorderhout(@RequestParam String id) {
  582. PosOrder orlist = posOrderService.getById(id);
  583. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  584. JSONObject org = JSON.parseObject(
  585. JSON.toJSONStringWithDateFormat(orlist, "yyyy-MM-dd HH:mm:ss")
  586. );
  587. // 以下为非PosOrder字段或需要特殊处理的字段
  588. org.put("shanghu", infoUserService.getById(orlist.getShId()));
  589. org.put("store", posStoreService.getById(orlist.getMdId()));
  590. org.put("shaddress", orlist.getShAddress() == null ? infoAddressService.getById(orlist.getShdzId()) : JSONObject.parseObject(orlist.getShAddress()));
  591. org.put("user", infoUserService.getById(orlist.getUserId()));
  592. org.put("qsuser", infoUserService.getById(orlist.getQsId()));
  593. QueryWrapper<RiderPosition> query = new QueryWrapper<>();
  594. query.eq("rider_id", orlist.getQsId());
  595. org.put("RiderPosition", orlist.getQsId() == null ? null : riderPositionService.getOne(query));
  596. org.put("food", JSONArray.parseArray(orlist.getFood()));
  597. // 已支付订单附带支付商交易单号,供平台到支付商后台按单号查询交易详情
  598. org.put("payTrade", buildPayTrade(orlist));
  599. return success(org);
  600. }
  601. /**
  602. * 已支付订单的支付商交易单号信息,供平台在支付商后台按单号查询交易详情。
  603. * OMG 返回 MerchantTradeNo(支付商侧查询键)与网关 TradeNo;
  604. * LINE Pay 返回 lineOrderId 与 transactionId;其他渠道(到付等)返回 null。
  605. */
  606. private JSONObject buildPayTrade(PosOrder order) {
  607. // 已退款订单同样需要单号到支付商侧核对退款,因此仅排除未支付
  608. if (order.getPayStatus() == null || order.getPayStatus() == 0L) {
  609. return null;
  610. }
  611. JSONObject trade = new JSONObject();
  612. if (OrderLifecycleService.PAY_TYPE_OMG.equals(order.getPayType())) {
  613. OmgPaymentAttempt attempt = omgPaymentAttemptService.selectPaidByDdId(order.getDdId());
  614. if (attempt == null) {
  615. return null;
  616. }
  617. trade.put("channel", "OMG");
  618. trade.put("merchantTradeNo", attempt.getMerchantTradeNo());
  619. trade.put("gatewayTradeNo", attempt.getTradeNo());
  620. } else if (LinePayService.PAY_TYPE_LINE.equals(order.getPayType())) {
  621. PosOrderLinePayment paid = linePaymentService.getByDdId(order.getDdId()).stream()
  622. .filter(payment -> "PAID".equals(payment.getStatus()))
  623. .max(Comparator.comparing(PosOrderLinePayment::getId))
  624. .orElse(null);
  625. if (paid == null) {
  626. return null;
  627. }
  628. trade.put("channel", "LINE Pay");
  629. trade.put("lineOrderId", paid.getLineOrderId());
  630. trade.put("transactionId", paid.getTransactionId());
  631. } else {
  632. return null;
  633. }
  634. return trade;
  635. }
  636. /**
  637. * 通过订单号查询订单详情
  638. *
  639. * @param ddid
  640. * @return
  641. */
  642. //查询订单详情
  643. @Anonymous
  644. @Auth
  645. @GetMapping("/getorderxq")
  646. public AjaxResult getorderxq(@RequestParam String ddid) {
  647. QueryWrapper<PosOrder> queryWrapper = new QueryWrapper<>();
  648. queryWrapper.eq("dd_id", ddid);
  649. PosOrder orlist = posOrderService.getOne(queryWrapper);
  650. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  651. JSONObject org = JSON.parseObject(
  652. JSON.toJSONStringWithDateFormat(orlist, "yyyy-MM-dd HH:mm:ss")
  653. );
  654. // 以下为非PosOrder字段或需要特殊处理的字段
  655. org.put("shanghu", infoUserService.getById(orlist.getShId()));
  656. org.put("store", posStoreService.getById(orlist.getMdId()));
  657. org.put("shaddress", orlist.getShAddress() == null ? infoAddressService.getById(orlist.getShdzId()) : JSONObject.parseObject(orlist.getShAddress()));
  658. org.put("user", infoUserService.getById(orlist.getUserId()));
  659. InfoUser qsUser = infoUserService.getById(orlist.getQsId());
  660. setQsStar(qsUser);
  661. org.put("qsuser", orlist.getQsId() == null ? null : qsUser);
  662. QueryWrapper<RiderPosition> query = new QueryWrapper<>();
  663. query.eq("rider_id", orlist.getQsId());
  664. org.put("RiderPosition", orlist.getQsId() == null ? null : riderPositionService.getOne(query));
  665. org.put("food", JSONArray.parseArray(orlist.getFood()));
  666. Long count = posOrderRatingService.getBaseMapper().selectCount(new QueryWrapper<PosOrderRating>().eq("dd_id", ddid));
  667. org.put("isCommented", count > 0);
  668. // 查询促销快照明细
  669. List<PosOrderPromotion> promotions = posOrderPromotionMapper.selectByOrderId(orlist.getId());
  670. org.put("promotions", promotions);
  671. return success(org);
  672. }
  673. /**
  674. * 设置骑手星级
  675. *
  676. * @param infoUser
  677. */
  678. private void setQsStar(InfoUser infoUser) {
  679. if (infoUser != null) {
  680. QueryWrapper<PosOrderRating> wrapper = new QueryWrapper<>();
  681. wrapper.eq("qs_id", infoUser.getUserId()).isNotNull("qs_stars").isNotNull("qs_stars").select("ROUND(AVG(qs_stars), 1) as qs_stars");
  682. List<Map<String, Object>> map = posOrderRatingService.getBaseMapper().selectMaps(wrapper);
  683. if (!map.isEmpty() && map.get(0) != null) {
  684. Object rating = map.get(0).get("qs_stars");
  685. // 关键:显式检查null值
  686. if (rating != null) {
  687. infoUser.setStar(Double.parseDouble(rating.toString()));
  688. }
  689. } else {
  690. infoUser.setStar(4.5);
  691. }
  692. }
  693. }
  694. //查询所有的订单
  695. @Anonymous
  696. @GetMapping("/getqishouorderlist")
  697. public AjaxResult getqishouorderlist(@RequestParam Integer page, @RequestParam BigDecimal longitude, @RequestParam BigDecimal latitude, @RequestParam Integer juli, @RequestParam(defaultValue = "") String state) {
  698. JSONArray arr = new JSONArray();
  699. List<PosOrder> orlist;
  700. if (!"".equals(state)) {
  701. if (state.equals("z02")) {
  702. orlist = posOrderMapper.getz02(longitude, latitude, (page - 1) * 20, juli);
  703. } else if (state.equals("z234")) {
  704. orlist = posOrderMapper.getz234(longitude, latitude, (page - 1) * 20, juli, 2, 4);
  705. } else if (state.equals("z23")) {
  706. orlist = posOrderMapper.getz234(longitude, latitude, (page - 1) * 20, juli, 2, 3);
  707. } else if (state.equals("z34")) {
  708. orlist = posOrderMapper.getz234(longitude, latitude, (page - 1) * 20, juli, 3, 4);
  709. } else if (state.equals("z6789")) {
  710. orlist = posOrderMapper.getz234(longitude, latitude, (page - 1) * 20, juli, 6, 9);
  711. } else {
  712. orlist = posOrderMapper.getstate(longitude, latitude, (page - 1) * 20, juli, state);
  713. }
  714. } else {
  715. orlist = posOrderMapper.getqisjvli(longitude, latitude, (page - 1) * 20, juli);
  716. }
  717. // 循环外统一查询,避免N+1问题
  718. Set<Long> allUserIds = orlist.stream().flatMap(o -> Stream.of(o.getShId(), o.getUserId())).filter(Objects::nonNull).collect(Collectors.toSet());
  719. Set<Long> mdIds = orlist.stream().map(PosOrder::getMdId).filter(Objects::nonNull).collect(Collectors.toSet());
  720. Set<Long> shdzIds = orlist.stream().filter(o -> o.getShAddress() == null && o.getShdzId() != null).map(PosOrder::getShdzId).collect(Collectors.toSet());
  721. Map<Long, InfoUser> userMap = allUserIds.isEmpty() ? Collections.emptyMap() :
  722. infoUserService.listByIds(allUserIds).stream().collect(Collectors.toMap(InfoUser::getUserId, u -> u));
  723. Map<Integer, PosStore> storeMap = mdIds.isEmpty() ? Collections.emptyMap() :
  724. posStoreService.listByIds(mdIds).stream().collect(Collectors.toMap(PosStore::getId, s -> s));
  725. Map<Long, InfoAddress> addressMap = shdzIds.isEmpty() ? Collections.emptyMap() :
  726. infoAddressService.listByIds(shdzIds).stream().collect(Collectors.toMap(InfoAddress::getId, a -> a));
  727. DecimalFormat jl = new DecimalFormat("#.0");
  728. for (PosOrder order : orlist) {
  729. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  730. JSONObject org = JSON.parseObject(
  731. JSON.toJSONStringWithDateFormat(order, "yyyy-MM-dd HH:mm:ss")
  732. );
  733. // 以下为非PosOrder字段或需要特殊处理的字段
  734. org.put("shanghu", userMap.get(order.getShId()));
  735. org.put("store", storeMap.get(order.getMdId().intValue()));
  736. org.put("shaddress", order.getShAddress() == null ? addressMap.get(order.getShdzId()) : JSONObject.parseObject(order.getShAddress()));
  737. org.put("user", userMap.get(order.getUserId()));
  738. org.put("jvli", jl.format(order.getJvli()));
  739. org.put("juli", jl.format(order.getJuli()));
  740. org.put("food", JSONArray.parseArray(order.getFood()));
  741. arr.add(org);
  742. }
  743. return success(arr);
  744. }
  745. //查询骑手的订单
  746. @Anonymous
  747. @Auth
  748. @GetMapping("/getqsorderlist")
  749. public AjaxResult getqsorderlist(@RequestHeader String token, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(defaultValue = "") String state, @RequestParam(defaultValue = "0") BigDecimal longitude, @RequestParam(defaultValue = "0") BigDecimal latitude) {
  750. logger.info("骑手token:" + token);
  751. JwtUtil jwtUtil = new JwtUtil();
  752. String id = jwtUtil.getusid(token);
  753. List<PosOrder> orlist = posOrderMapper.getQsOrderList(id, longitude, latitude, (page - 1) * size, size, state);
  754. // 循环外统一查询,避免N+1问题
  755. Set<Long> allUserIds = orlist.stream().flatMap(o -> Stream.of(o.getShId(), o.getUserId(), o.getQsId())).filter(Objects::nonNull).collect(Collectors.toSet());
  756. Set<Long> mdIds = orlist.stream().map(PosOrder::getMdId).filter(Objects::nonNull).collect(Collectors.toSet());
  757. Set<Long> shdzIds = orlist.stream().filter(o -> o.getShAddress() == null && o.getShdzId() != null).map(PosOrder::getShdzId).collect(Collectors.toSet());
  758. Map<Long, InfoUser> userMap = allUserIds.isEmpty() ? Collections.emptyMap() :
  759. infoUserService.listByIds(allUserIds).stream().collect(Collectors.toMap(InfoUser::getUserId, u -> u));
  760. Map<Integer, PosStore> storeMap = mdIds.isEmpty() ? Collections.emptyMap() :
  761. posStoreService.listByIds(mdIds).stream().collect(Collectors.toMap(PosStore::getId, s -> s));
  762. Map<Long, InfoAddress> addressMap = shdzIds.isEmpty() ? Collections.emptyMap() :
  763. infoAddressService.listByIds(shdzIds).stream().collect(Collectors.toMap(InfoAddress::getId, a -> a));
  764. JSONArray arr = new JSONArray();
  765. DecimalFormat jl = new DecimalFormat("#.0");
  766. for (PosOrder order : orlist) {
  767. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  768. JSONObject org = JSON.parseObject(
  769. JSON.toJSONStringWithDateFormat(order, "yyyy-MM-dd HH:mm:ss")
  770. );
  771. // 以下为非PosOrder字段或需要特殊处理的字段
  772. org.put("shanghu", userMap.get(order.getShId()));
  773. org.put("store", storeMap.get(order.getMdId().intValue()));
  774. org.put("shaddress", order.getShAddress() == null ? addressMap.get(order.getShdzId()) : JSONObject.parseObject(order.getShAddress()));
  775. org.put("user", userMap.get(order.getUserId()));
  776. org.put("qishou", userMap.get(order.getQsId()));
  777. org.put("jvli", jl.format(order.getJvli()));
  778. org.put("qsjvli", jl.format(order.getJuli()));
  779. org.put("food", JSONArray.parseArray(order.getFood()));
  780. org.put("sqImg", org.remove("qsImg"));
  781. arr.add(org);
  782. }
  783. return success(arr);
  784. }
  785. //查询商家的订单
  786. @Anonymous
  787. @Auth
  788. @GetMapping("/getstoreorderlist")
  789. public AjaxResult getstoreorderlist(@RequestHeader String token, @RequestParam Integer page, @RequestParam Integer size, @RequestParam String mdId, @RequestParam(defaultValue = "") String state, @RequestParam(defaultValue = "") String diningStatus,@RequestParam(defaultValue = "")String type) {
  790. JwtUtil jwtUtil = new JwtUtil();
  791. String id = jwtUtil.getusid(token);
  792. IPage<PosOrder> palist = new Page<>(page, size);
  793. QueryWrapper<PosOrder> queryWrapper = new QueryWrapper<>();
  794. queryWrapper.select().orderByDesc("cretim");
  795. queryWrapper.eq("sh_id", id);
  796. System.out.println("商户id:" + id);
  797. queryWrapper.eq("md_id", mdId).eq("is_display", true);
  798. queryWrapper.eq(!StringUtils.isEmpty(type),"type",type);
  799. if (!"".equals(state)) {
  800. if (state.equals("z01")) {
  801. queryWrapper.apply(" ((state = 0 AND (collect_payment = 1 OR type = 1)) OR (state = 1))");
  802. } else if (state.equals("z234")) {
  803. queryWrapper.in("state", 2, 3, 4);
  804. } else if (state.equals("z23")) {
  805. queryWrapper.in("state", 2, 3);
  806. } else if (state.equals("z34")) {
  807. queryWrapper.in("state", 3, 4);
  808. } else if (state.equals("z678911")) {
  809. queryWrapper.in("state", 6, 7, 8, 9, 11);
  810. } else {
  811. queryWrapper.eq("state", state);
  812. }
  813. }
  814. if (!"".equals(diningStatus)) {
  815. queryWrapper.eq("dining_status", diningStatus);
  816. }
  817. IPage<PosOrder> list = posOrderService.page(palist, queryWrapper);
  818. List<PosOrder> orlist = list.getRecords();
  819. // 循环外统一查询,避免N+1问题
  820. Set<Long> allUserIds = orlist.stream().flatMap(o -> Stream.of(o.getShId(), o.getUserId())).filter(Objects::nonNull).collect(Collectors.toSet());
  821. Set<Long> mdIds = orlist.stream().map(PosOrder::getMdId).filter(Objects::nonNull).collect(Collectors.toSet());
  822. Set<Long> shdzIds = orlist.stream().filter(o -> o.getShAddress() == null && o.getShdzId() != null).map(PosOrder::getShdzId).collect(Collectors.toSet());
  823. Map<Long, InfoUser> userMap = allUserIds.isEmpty() ? Collections.emptyMap() :
  824. infoUserService.listByIds(allUserIds).stream().collect(Collectors.toMap(InfoUser::getUserId, u -> u));
  825. Map<Integer, PosStore> storeMap = mdIds.isEmpty() ? Collections.emptyMap() :
  826. posStoreService.listByIds(mdIds).stream().collect(Collectors.toMap(PosStore::getId, s -> s));
  827. Map<Long, InfoAddress> addressMap = shdzIds.isEmpty() ? Collections.emptyMap() :
  828. infoAddressService.listByIds(shdzIds).stream().collect(Collectors.toMap(InfoAddress::getId, a -> a));
  829. JSONArray arr = new JSONArray();
  830. for (PosOrder order : orlist) {
  831. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  832. JSONObject org = JSON.parseObject(
  833. JSON.toJSONStringWithDateFormat(order, "yyyy-MM-dd HH:mm:ss")
  834. );
  835. // 以下为非PosOrder字段或需要特殊处理的字段
  836. org.put("shanghu", userMap.get(order.getShId()));
  837. org.put("store", storeMap.get(order.getMdId().intValue()));
  838. org.put("shaddress", order.getShAddress() == null ? addressMap.get(order.getShdzId()) : JSONObject.parseObject(order.getShAddress()));
  839. org.put("user", userMap.get(order.getUserId()));
  840. org.put("food", JSONArray.parseArray(order.getFood()));
  841. arr.add(org);
  842. }
  843. return success(arr);
  844. }
  845. //查询用户的订单(用户端)
  846. @Anonymous
  847. @Auth
  848. @GetMapping("/getorderlist")
  849. public AjaxResult getorderlist(@RequestHeader String token, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(defaultValue = "") String state,@RequestParam(defaultValue = "")String type) {
  850. JwtUtil jwtUtil = new JwtUtil();
  851. String id = jwtUtil.getusid(token);
  852. IPage<PosOrder> palist = new Page<>(page, size);
  853. QueryWrapper<PosOrder> queryWrapper = new QueryWrapper<>();
  854. queryWrapper.select().orderByDesc("cretim");
  855. queryWrapper.eq("user_id", id);
  856. queryWrapper.eq(!StringUtils.isEmpty(type),"type",type);
  857. if (!"".equals(state)) {
  858. if (state.equals("z23412")) {
  859. queryWrapper.in("state", 2, 3, 4, 12);
  860. } else if (state.equals("z23")) {
  861. queryWrapper.in("state", 2, 3);
  862. } else if (state.equals("z34")) {
  863. queryWrapper.in("state", 3, 4);
  864. } else if (state.equals("z678911")) {
  865. queryWrapper.in("state", 6, 7, 8, 9, 11);
  866. } else {
  867. queryWrapper.eq("state", state);
  868. }
  869. }
  870. // 添加排除条件:state=0且collect_payment=0的数据
  871. queryWrapper.apply("NOT (state = 0 AND collect_payment = 0)");
  872. IPage<PosOrder> list = posOrderService.page(palist, queryWrapper);
  873. List<PosOrder> orlist = list.getRecords();
  874. List<String> parentDdIds = orlist.stream().map(PosOrder::getParentDdId).collect(Collectors.toList());
  875. List<OrderParent> orderParents = new ArrayList<>();
  876. if (!parentDdIds.isEmpty()) {
  877. orderParents = orderParentService.list(new LambdaQueryWrapper<>(OrderParent.class).in(OrderParent::getDdId, parentDdIds));
  878. }
  879. // 循环外统一查询,避免N+1问题
  880. Set<Long> allUserIds = orlist.stream().flatMap(o -> Stream.of(o.getShId(), o.getUserId())).filter(Objects::nonNull).collect(Collectors.toSet());
  881. Set<Long> mdIds = orlist.stream().map(PosOrder::getMdId).filter(Objects::nonNull).collect(Collectors.toSet());
  882. Set<Long> shdzIds = orlist.stream().filter(o -> o.getShAddress() == null && o.getShdzId() != null).map(PosOrder::getShdzId).collect(Collectors.toSet());
  883. Map<Long, InfoUser> userMap = allUserIds.isEmpty() ? Collections.emptyMap() :
  884. infoUserService.listByIds(allUserIds).stream().collect(Collectors.toMap(InfoUser::getUserId, u -> u));
  885. Map<Integer, PosStore> storeMap = mdIds.isEmpty() ? Collections.emptyMap() :
  886. posStoreService.listByIds(mdIds).stream().collect(Collectors.toMap(PosStore::getId, s -> s));
  887. Map<Long, InfoAddress> addressMap = shdzIds.isEmpty() ? Collections.emptyMap() :
  888. infoAddressService.listByIds(shdzIds).stream().collect(Collectors.toMap(InfoAddress::getId, a -> a));
  889. Map<String, OrderParent> orderParentMap = orderParents.stream().collect(Collectors.toMap(OrderParent::getDdId, p -> p));
  890. JSONArray arr = new JSONArray();
  891. for (PosOrder order : orlist) {
  892. // 自动序列化所有PosOrder字段,新增字段无需手动添加
  893. JSONObject org = JSON.parseObject(
  894. JSON.toJSONStringWithDateFormat(order, "yyyy-MM-dd HH:mm:ss")
  895. );
  896. // 以下为非PosOrder字段或需要特殊处理的字段
  897. org.put("ddId", order.getDdId() == null ? null : order.getDdId().toString());
  898. org.put("shanghu", userMap.get(order.getShId()));
  899. org.put("store", storeMap.get(order.getMdId().intValue()));
  900. org.put("shaddress", order.getShAddress() == null ? addressMap.get(order.getShdzId()) : JSONObject.parseObject(order.getShAddress()));
  901. org.put("user", userMap.get(order.getUserId()));
  902. org.put("food", JSONArray.parseArray(order.getFood()));
  903. org.put("parentRemarks", "");
  904. if (StringUtils.isNotEmpty(order.getParentDdId())) {
  905. OrderParent parent = orderParentMap.get(order.getParentDdId());
  906. if (parent != null) org.put("parentRemarks", parent.getRemarks());
  907. }
  908. arr.add(org);
  909. }
  910. return success(arr);
  911. }
  912. // @Anonymous
  913. // @GetMapping("/sssaaaa")
  914. // public AjaxResult sssaaaa(@RequestParam String aa,@RequestParam String bb){
  915. // DateUtil dateUtil = new DateUtil();
  916. // Boolean sbsj = dateUtil.isLegalTime(aa,bb);
  917. // return success(sbsj);
  918. // }
  919. //添加新订单
  920. @SneakyThrows
  921. @Anonymous
  922. @Auth
  923. @RepeatSubmit(interval = 1000, message = "请求过于频繁")
  924. @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
  925. @PostMapping("/addorder")
  926. public AjaxResult addorder(@RequestHeader String token, @RequestBody OrderDTO orderDTO) {
  927. long methodStart = System.currentTimeMillis(); // 记录方法开始时间
  928. ObjectMapper mapper = new ObjectMapper();
  929. mapper.enable(SerializationFeature.INDENT_OUTPUT);
  930. Integer xiadanjiaoyan = orderDTO.getXiadanjiaoyan();
  931. if (xiadanjiaoyan == null || !xiadanjiaoyan.equals(2)) {
  932. return error(MessageUtils.message("no.xiadanyz.message"));
  933. }
  934. System.out.println("========== 接收到的orderDTO ==========");
  935. System.out.println(mapper.writeValueAsString(orderDTO));
  936. JwtUtil jwtUtil = new JwtUtil();
  937. DateUtil dateUtil = new DateUtil();
  938. String id = jwtUtil.getusid(token);
  939. QueryWrapper<OperatingHours> wrapper = new QueryWrapper<>();
  940. wrapper.eq("md_id", orderDTO.getMdId());
  941. List<OperatingHours> hourslist = operatingHoursService.list(wrapper);
  942. PosStore store = posStoreService.getById(orderDTO.getMdId());
  943. JSONObject usdizhi = new JSONObject();
  944. if (orderDTO.getType() != null && orderDTO.getType().equals(0L)) {
  945. InfoAddress usadd = infoAddressService.getById(orderDTO.getShdzId());
  946. if (usadd == null) {
  947. return error(MessageUtils.message("no.address.not.exist"));
  948. } else {
  949. usdizhi.put("name", usadd.getName());
  950. usdizhi.put("phone", usadd.getPhone());
  951. usdizhi.put("address", usadd.getAddress());
  952. usdizhi.put("country", usadd.getCountry());
  953. usdizhi.put("province", usadd.getProvince());
  954. usdizhi.put("city", usadd.getCity());
  955. usdizhi.put("area", usadd.getArea());
  956. usdizhi.put("longitude", String.valueOf(usadd.getLongitude()));
  957. usdizhi.put("latitude", String.valueOf(usadd.getLatitude()));
  958. }
  959. }
  960. if (hourslist.size() == 0) {
  961. return error(MessageUtils.message("no.mendian.not.set.business.hours"));
  962. }
  963. if (store.getState() == 1) {
  964. return error(MessageUtils.message("no.mendian.is.closed"));
  965. }
  966. //是否在上班时间内(按星期几和是否营业过滤)
  967. boolean isOperating = OperatingUtil.storeIsOperatingOfDay(hourslist);
  968. if (!isOperating) {
  969. return error(MessageUtils.message("no.mendian.is.closed"));
  970. }
  971. //订单金额限制100万改为200万
  972. if (orderDTO.getCollectPayment().equals("1") && orderDTO.getAmount() > 2000000) {
  973. return error(MessageUtils.message("no.cash_on_delivery_amount.exceed.limit_amount"));
  974. }
  975. QueryWrapper<PosOrder> query = new QueryWrapper<>();
  976. query.eq("user_id", id);
  977. query.eq("collect_payment", "1");
  978. query.notIn("state", 5, 10, 11);
  979. List<PosOrder> posOrders = posOrderService.list(query);
  980. System.out.println("到付信息:user_id=" + id + " ,到付数量:" + posOrders.size());
  981. //到付能存在2单未完成,第3单弹出提示
  982. if (posOrders.size() >= 2 && orderDTO.getCollectPayment().equals("1")) {
  983. return error(MessageUtils.message("no.exist.cash_on_delivery_order.incomplete"));
  984. }
  985. JSONArray jsonArray = orderDTO.getFoodlist();
  986. Map<Long, Long> map = new HashMap<>();
  987. for (int i = 0; i < jsonArray.size(); i++) {
  988. Long foodid = jsonArray.getJSONObject(i).getLong("id");
  989. PosFood food = posFoodService.getById(foodid);
  990. if (food == null) {
  991. return error(jsonArray.getJSONObject(i).getString("name") + MessageUtils.message("no.goods.not.exist"));
  992. } else {
  993. if (food.getStackingUp().equals("1")) {
  994. return error(food.getName() + MessageUtils.message("no.goods.is.off.shelf"));
  995. }
  996. }
  997. Long num = jsonArray.getJSONObject(i).getLong("number");
  998. map.put(foodid, num);
  999. }
  1000. VipUserQuanyi yh = null;
  1001. VipUserQuanyi mdYh = null;
  1002. if (ObjectUtil.isNotNull(orderDTO.getYhId()) && ObjectUtil.notEqual(orderDTO.getYhId(), 0L)) {
  1003. LambdaQueryWrapper<VipUserQuanyi> yhQuery = new LambdaQueryWrapper<>();
  1004. yhQuery.eq(VipUserQuanyi::getId, orderDTO.getYhId());
  1005. yh = userQuanyiService.getOne(yhQuery);
  1006. if (yh == null) {
  1007. throw new ServiceException("no.userquanyi.not.exist");
  1008. }
  1009. if (yh.getState().equals("1")) {
  1010. throw new ServiceException("userquanyi.isUsed");
  1011. }
  1012. }
  1013. if (ObjectUtil.isNotNull(orderDTO.getMdYhId()) && ObjectUtil.notEqual(orderDTO.getMdYhId(), 0L)) {
  1014. LambdaQueryWrapper<VipUserQuanyi> mdYhquery = new LambdaQueryWrapper<>();
  1015. mdYhquery.eq(VipUserQuanyi::getId, orderDTO.getMdYhId());
  1016. mdYh = userQuanyiService.getOne(mdYhquery);
  1017. if (mdYh == null) {
  1018. throw new ServiceException("no.userquanyi.not.exist");
  1019. }
  1020. if (mdYh.getState().equals("1")) {
  1021. throw new ServiceException("userquanyi.isUsed");
  1022. }
  1023. }
  1024. SalesPromotion activity = null;
  1025. SalesPromotion mdActivity = null;
  1026. if (ObjectUtil.isNotNull(orderDTO.getActivity()) && ObjectUtil.notEqual(orderDTO.getActivity(), 0L)) {
  1027. LambdaQueryWrapper<SalesPromotion> saleQuery = new LambdaQueryWrapper<>();
  1028. saleQuery.eq(SalesPromotion::getId, orderDTO.getActivity());
  1029. activity = salesPromotionService.getOne(saleQuery);
  1030. if (activity == null) {
  1031. throw new ServiceException("no.activity.not.exist");
  1032. }
  1033. // if (yh.getState().equals("1")) {
  1034. // throw new ServiceException("userquanyi.isUsed");
  1035. // }
  1036. }
  1037. if (ObjectUtil.isNotNull(orderDTO.getMdActivity()) && ObjectUtil.notEqual(orderDTO.getMdActivity(), 0L)) {
  1038. LambdaQueryWrapper<SalesPromotion> saleQuery = new LambdaQueryWrapper<>();
  1039. saleQuery.eq(SalesPromotion::getId, orderDTO.getMdActivity());
  1040. mdActivity = salesPromotionService.getOne(saleQuery);
  1041. if (mdActivity == null) {
  1042. throw new ServiceException("no.activity.not.exist");
  1043. }
  1044. }
  1045. PosOrder posOrder = new PosOrder();
  1046. AjaxResult posOrderResult = redeePoints(orderDTO, Long.valueOf(id));
  1047. if (!posOrderResult.get("code").equals(200)) {
  1048. return posOrderResult;
  1049. } else {
  1050. posOrder.setPoints(orderDTO.getPoints());
  1051. posOrder.setPointsReduction(orderDTO.getPointsReduction());
  1052. }
  1053. posOrder.setDdId(orderDTO.getDdId());
  1054. posOrder.setShId(orderDTO.getShId());
  1055. posOrder.setMdId(orderDTO.getMdId());
  1056. posOrder.setShdzId(orderDTO.getShdzId());
  1057. posOrder.setShAddress(JSON.toJSONString(usdizhi));
  1058. posOrder.setUserId(Long.valueOf(id));
  1059. posOrder.setAmount(orderDTO.getAmount());
  1060. posOrder.setRemarks(orderDTO.getRemarks());
  1061. posOrder.setType(orderDTO.getType());
  1062. posOrder.setDelryTime(orderDTO.getDelryTime());
  1063. posOrder.setFood(jsonArray.toString());
  1064. posOrder.setState(0L);
  1065. posOrder.setJvli(orderDTO.getJvli());
  1066. posOrder.setFreight(orderDTO.getFreight());
  1067. posOrder.setLongitude(orderDTO.getLongitude());
  1068. posOrder.setLatitude(orderDTO.getLatitude());
  1069. posOrder.setDiningStatus(orderDTO.getDiningStatus());
  1070. posOrder.setQsId(orderDTO.getQsId());
  1071. posOrder.setJuli(orderDTO.getJuli());
  1072. posOrder.setPayUrl(orderDTO.getPayUrl());
  1073. posOrder.setCollectPayment(orderDTO.getCollectPayment());
  1074. posOrder.setAfterSaleStatus(0L);
  1075. posOrder.setDeliveryStatus(Long.valueOf(0L).equals(orderDTO.getType()) ? 0L : null);
  1076. posOrder.setPayStatus(Long.valueOf(0L).equals(orderDTO.getType())
  1077. && "1".equals(orderDTO.getCollectPayment()) ? 1L : 0L);
  1078. // posOrder.setCretim(dateUtil.getDatetim(orderDTO.getCretim()));
  1079. //创建时间改成后端生成
  1080. posOrder.setCretim(new Date());
  1081. if (yh != null) {
  1082. posOrder.setYhName(yh.getName());
  1083. posOrder.setYhId(orderDTO.getYhId());
  1084. posOrder.setDiscountAmount(orderDTO.getDiscountAmount());
  1085. }
  1086. if (mdYh != null) {
  1087. posOrder.setMdYhId(orderDTO.getMdYhId());
  1088. posOrder.setMdYhName(mdYh.getName());
  1089. posOrder.setMdDiscountAmount(orderDTO.getMdDiscountAmount());
  1090. }
  1091. if (mdActivity != null) {
  1092. posOrder.setMdActivity(orderDTO.getMdActivity());
  1093. posOrder.setMdSalesName(mdActivity.getSalesName());
  1094. posOrder.setMdSalesReduction(orderDTO.getMdSalesReduction());
  1095. }
  1096. if (activity != null) {
  1097. posOrder.setActivity(orderDTO.getActivity());
  1098. posOrder.setSalesName(activity.getSalesName());
  1099. posOrder.setSalesReduction(orderDTO.getSalesReduction());
  1100. }
  1101. //设置支付类型为货到付款
  1102. if ("1".equals(posOrder.getCollectPayment())) {
  1103. posOrder.setPayType("1");
  1104. }
  1105. Boolean org = posOrderService.saveOrUpdate(posOrder);
  1106. foodStatistics(map);
  1107. if (org) {
  1108. QueryWrapper<UserBilling> queryWrapper = new QueryWrapper<>();
  1109. queryWrapper.eq("user_id", id);
  1110. queryWrapper.eq("dd_id", posOrder.getDdId());
  1111. UserBilling billing = userBillingService.getOne(queryWrapper);
  1112. if (billing == null) {
  1113. UserBilling usb = new UserBilling();
  1114. usb.setUserId(Long.valueOf(id));
  1115. usb.setDdId(String.valueOf(posOrder.getDdId()));
  1116. usb.setMdId(posOrder.getMdId());
  1117. usb.setState("3");
  1118. usb.setType("3");
  1119. userBillingService.saveOrUpdate(usb);
  1120. }
  1121. QueryWrapper<UserFootprint> Wrapper = new QueryWrapper<>();
  1122. Wrapper.eq("user_id", id);
  1123. Wrapper.eq("md_id", posOrder.getMdId());
  1124. UserFootprint foot = userFootprintService.getOne(Wrapper);
  1125. DateUtil dateString = new DateUtil();
  1126. if (foot == null) {
  1127. UserFootprint usf = new UserFootprint();
  1128. usf.setUserId(Long.valueOf(id));
  1129. usf.setMdId(posOrder.getMdId());
  1130. usf.setCretim(dateString.GetDate());
  1131. userFootprintService.saveOrUpdate(usf);
  1132. } else {
  1133. foot.setCretim(dateString.GetDate());
  1134. userFootprintService.saveOrUpdate(foot);
  1135. }
  1136. QueryWrapper<PosOrder> querywra = new QueryWrapper<>();
  1137. querywra.eq("dd_id", posOrder.getDdId());
  1138. PosOrder order = posOrderService.getOne(querywra);
  1139. //货到付款、类型外卖,推送给骑手有新订单了
  1140. if (order.getCollectPayment().equals("1") && order.getType() == 0) {
  1141. sendHdfkMessage(order);
  1142. }
  1143. //存在使用优惠券的话,核销优惠券
  1144. redeemCoupons(yh, mdYh, order.getDdId());
  1145. System.out.println("========== 输出的order ==========");
  1146. System.out.println(mapper.writeValueAsString(order));
  1147. long methodEnd = System.currentTimeMillis(); // 方法结束时间
  1148. System.out.println("addorder 方法总执行耗时: " + (methodEnd - methodStart) + " ms");
  1149. return success(MessageUtils.message("no.order.submit.success"), order);
  1150. } else {
  1151. long methodEnd = System.currentTimeMillis(); // 方法结束时间
  1152. System.out.println("addorder 方法总执行耗时: " + (methodEnd - methodStart) + " ms");
  1153. return error();
  1154. }
  1155. }
  1156. //统计美食销售量
  1157. private void foodStatistics(Map<Long, Long> map) {
  1158. for (Map.Entry<Long, Long> entry : map.entrySet()) {
  1159. Long key = entry.getKey();
  1160. Long value = entry.getValue();
  1161. // 使用数据库原子UPSERT,避免并发下的竞态问题
  1162. foodStatisticsService.increaseNumber(key, value);
  1163. }
  1164. }
  1165. /**
  1166. * 货到付款发送推送
  1167. *
  1168. * @param order
  1169. */
  1170. private void sendHdfkMessage(PosOrder order) {
  1171. deliveryOrderNotificationService.notifyOrderAvailable(order);
  1172. }
  1173. //核销积分
  1174. private AjaxResult redeePoints(OrderDTO orderDTO, Long userId) {
  1175. if (ObjectUtil.isNotNull(orderDTO.getPoints()) && ObjectUtil.notEqual(orderDTO.getPoints(), 0) && ObjectUtil.isNotNull(orderDTO.getPointsReduction()) && ObjectUtil.notEqual(orderDTO.getPointsReduction(), 0)) {
  1176. SysPointControl control = pointControlService.getById(1L);
  1177. if (!control.getOrderUseEnable().equals(1L)) {
  1178. throw new ServiceException(MessageUtils.message("no.points.use.enable"));
  1179. }
  1180. LambdaQueryWrapper<UserWallet> walletQuery = new LambdaQueryWrapper<>();
  1181. walletQuery.eq(UserWallet::getUserId, userId);
  1182. walletQuery.isNull(UserWallet::getStoreId);
  1183. UserWallet userWallet = userWalletService.getOne(walletQuery);
  1184. if (ObjectUtil.isNotNull(userWallet)) {
  1185. if (userWallet.getPointsWallet().compareTo(Long.valueOf(orderDTO.getPoints())) >= 0) {
  1186. walletQuery.eq(UserWallet::getVersion, userWallet.getVersion());
  1187. userWallet.setPointsWallet(userWallet.getPointsWallet() - orderDTO.getPoints());
  1188. userWallet.setVersion(userWallet.getVersion() + 1);
  1189. boolean update = userWalletService.update(userWallet, walletQuery);
  1190. createPointTransaction(userId, Long.valueOf(orderDTO.getPoints()), userWallet.getPointsWallet(), orderDTO.getDdId().toString(), "1");
  1191. if (!update) {
  1192. throw new ServiceException(MessageUtils.message("no.points.update.fail"));
  1193. }
  1194. } else {
  1195. throw new ServiceException(MessageUtils.message("no.points.insufficient"));
  1196. }
  1197. } else {
  1198. throw new ServiceException(MessageUtils.message("no.points.not.exist"));
  1199. }
  1200. }
  1201. return success();
  1202. }
  1203. /**
  1204. * 创建积分流水
  1205. */
  1206. private void createPointTransaction(Long userid, Long pointsChange, Long currentPoints, String ddId, String type) {
  1207. PointsTransaction pointsTransaction = new PointsTransaction();
  1208. pointsTransaction.setUserId(userid);
  1209. if (type.equals("1")) {
  1210. pointsTransaction.setPointsChange("-" + pointsChange);
  1211. pointsTransaction.setType("1");
  1212. }
  1213. if (type.equals("2")) {
  1214. pointsTransaction.setPointsChange("+" + pointsChange);
  1215. pointsTransaction.setType("2");
  1216. }
  1217. pointsTransaction.setCurrentPoints(currentPoints.toString());
  1218. pointsTransaction.setDdId(ddId);
  1219. pointsTransaction.setCreateTime(new Date());
  1220. pointsTransactionService.save(pointsTransaction);
  1221. }
  1222. /**
  1223. * 核销优惠券
  1224. *
  1225. * @param orderId
  1226. */
  1227. private void redeemCoupons(VipUserQuanyi yh, VipUserQuanyi mdYh, Long orderId) {
  1228. if (ObjectUtil.isNotNull(yh)) {
  1229. yh.setState("1");
  1230. yh.setOrderId(String.valueOf(orderId));
  1231. yh.setUpdateTime(new Date());
  1232. userQuanyiService.saveOrUpdate(yh);
  1233. }
  1234. if (ObjectUtil.isNotNull(mdYh)) {
  1235. mdYh.setState("1");
  1236. mdYh.setOrderId(String.valueOf(orderId));
  1237. mdYh.setUpdateTime(new Date());
  1238. userQuanyiService.saveOrUpdate(mdYh);
  1239. }
  1240. }
  1241. /**
  1242. * 核销优惠券
  1243. *
  1244. * @param orderId
  1245. */
  1246. private void redeemCoupons(VipUserQuanyi yh, VipUserQuanyi mdYh, String orderId) {
  1247. if (ObjectUtil.isNotNull(yh)) {
  1248. yh.setState("1");
  1249. yh.setOrderId(orderId);
  1250. yh.setUpdateTime(new Date());
  1251. userQuanyiService.saveOrUpdate(yh);
  1252. }
  1253. if (ObjectUtil.isNotNull(mdYh)) {
  1254. mdYh.setState("1");
  1255. mdYh.setOrderId(orderId);
  1256. mdYh.setUpdateTime(new Date());
  1257. userQuanyiService.saveOrUpdate(mdYh);
  1258. }
  1259. }
  1260. /**
  1261. * 查询posorder列表
  1262. */
  1263. @PreAuthorize("@ss.hasPermi('system:order:list')")
  1264. @GetMapping("/list")
  1265. public TableDataInfo list(PosOrder posOrder) {
  1266. startPage();
  1267. String[] dr = posOrder.getDateRange();
  1268. if (dr != null && dr.length == 2) {
  1269. posOrder.setCretimStart(dr[0]);
  1270. posOrder.setCretimEnd(dr[1]);
  1271. }
  1272. List<PosOrder> list = posOrderService.selectPosOrderList(posOrder);
  1273. if (list != null && list.size() > 0) {
  1274. for (PosOrder od : list) {
  1275. JSONArray foodArr = JSONArray.parseArray(od.getFood());
  1276. long priceAll = 0L;
  1277. for (int i = 0; i < foodArr.size(); i++) {
  1278. JSONObject obj = foodArr.getJSONObject(i);
  1279. BigDecimal price = obj.getBigDecimal("price");
  1280. if (price == null) continue;
  1281. Integer priceDb = price.intValue();
  1282. BigDecimal otherprice = obj.getBigDecimal("otherPrice");
  1283. if (otherprice != null && otherprice.doubleValue() > 0) {
  1284. priceDb += otherprice.intValue();
  1285. }
  1286. Long num = obj.getLong("number");
  1287. if (num == null) continue;
  1288. priceAll += (priceDb * num.longValue());
  1289. }
  1290. od.setPriceAll(priceAll + "");
  1291. Long atv = od.getActivity();
  1292. if (atv != null && atv.longValue() > 0) {
  1293. SalesPromotion salesPromotion = salesPromotionService.getById(atv);
  1294. if (salesPromotion != null) {
  1295. od.setSalesName(salesPromotion.getSalesName());
  1296. // od.setSalesReduction(""+salesPromotion.getSalesReduction());
  1297. }
  1298. }
  1299. }
  1300. }
  1301. return getDataTable(list);
  1302. }
  1303. /**
  1304. * 查询sh posorder列表
  1305. */
  1306. @PreAuthorize("@ss.hasPermi('system:order:shlist1')")
  1307. @GetMapping("/shlist1")
  1308. public TableDataInfo shlist1(PosOrder posOrder) {
  1309. startPage();
  1310. String[] dr = posOrder.getDateRange();
  1311. if (dr != null && dr.length == 2) {
  1312. posOrder.setCretimStart(dr[0]);
  1313. posOrder.setCretimEnd(dr[1]);
  1314. }
  1315. List<PosOrder> list = posOrderService.selectPosOrderShList(posOrder);
  1316. if (list != null && list.size() > 0) {
  1317. for (PosOrder od : list) {
  1318. //查询用户留言
  1319. PosAppeal posAppeal = new PosAppeal();
  1320. posAppeal.setDdId(od.getDdId());
  1321. posAppeal.setUserType("0");
  1322. List<PosAppeal> aplist = posAppealService.selectPosAppealList(posAppeal);
  1323. int s = 0;
  1324. if (aplist != null) s = aplist.size();
  1325. od.setAppealCount(s + "");
  1326. }
  1327. }
  1328. return getDataTable(list);
  1329. }
  1330. /**
  1331. * 查询sh posorder列表
  1332. */
  1333. @PreAuthorize("@ss.hasPermi('system:order:shlist2')")
  1334. @GetMapping("/shlist2")
  1335. public TableDataInfo shlist2(PosOrder posOrder) {
  1336. startPage();
  1337. String[] dr = posOrder.getDateRange();
  1338. if (dr != null && dr.length == 2) {
  1339. posOrder.setCretimStart(dr[0]);
  1340. posOrder.setCretimEnd(dr[1]);
  1341. }
  1342. List<PosOrder> list = posOrderService.selectPosOrderShList(posOrder);
  1343. if (list != null && list.size() > 0) {
  1344. for (PosOrder od : list) {
  1345. //查询用户留言
  1346. PosAppeal posAppeal = new PosAppeal();
  1347. posAppeal.setDdId(od.getDdId());
  1348. posAppeal.setUserType("1");
  1349. List<PosAppeal> aplist = posAppealService.selectPosAppealList(posAppeal);
  1350. int s = 0;
  1351. if (aplist != null) s = aplist.size();
  1352. od.setAppealCount(s + "");
  1353. }
  1354. }
  1355. return getDataTable(list);
  1356. }
  1357. /**
  1358. * 查询sh posorder列表
  1359. */
  1360. @PreAuthorize("@ss.hasPermi('system:order:shlist3')")
  1361. @GetMapping("/shlist3")
  1362. public TableDataInfo shlist3(PosOrder posOrder) {
  1363. startPage();
  1364. String[] dr = posOrder.getDateRange();
  1365. if (dr != null && dr.length == 2) {
  1366. posOrder.setCretimStart(dr[0]);
  1367. posOrder.setCretimEnd(dr[1]);
  1368. }
  1369. List<PosOrder> list = posOrderService.selectPosOrderShList(posOrder);
  1370. if (list != null && list.size() > 0) {
  1371. for (PosOrder od : list) {
  1372. //查询用户留言
  1373. PosAppeal posAppeal = new PosAppeal();
  1374. posAppeal.setDdId(od.getDdId());
  1375. posAppeal.setUserType("2");
  1376. List<PosAppeal> aplist = posAppealService.selectPosAppealList(posAppeal);
  1377. int s = 0;
  1378. if (aplist != null) s = aplist.size();
  1379. od.setAppealCount(s + "");
  1380. }
  1381. }
  1382. return getDataTable(list);
  1383. }
  1384. /**
  1385. * 导出posorder列表
  1386. */
  1387. @PreAuthorize("@ss.hasPermi('system:order:export')")
  1388. @Log(title = "posorder", businessType = BusinessType.EXPORT)
  1389. @PostMapping("/export")
  1390. public void export(HttpServletResponse response, PosOrder posOrder) {
  1391. List<PosOrder> list = posOrderService.selectPosOrderList(posOrder);
  1392. if (list != null && list.size() > 0) {
  1393. for (PosOrder od : list) {
  1394. JSONArray foodArr = JSONArray.parseArray(od.getFood());
  1395. long priceAll = 0L;
  1396. for (int i = 0; i < foodArr.size(); i++) {
  1397. JSONObject obj = foodArr.getJSONObject(i);
  1398. BigDecimal price = obj.getBigDecimal("price");
  1399. if (price == null) continue;
  1400. Integer priceDb = price.intValue();
  1401. //商品规格价格
  1402. BigDecimal otherprice = obj.getBigDecimal("otherPrice");
  1403. if (otherprice != null && otherprice.doubleValue() > 0) {
  1404. priceDb += otherprice.intValue();
  1405. }
  1406. Long num = obj.getLong("number");
  1407. if (num == null) continue;
  1408. priceAll += (priceDb * num.longValue());
  1409. }
  1410. od.setPriceAll(priceAll + "");
  1411. Long atv = od.getActivity();
  1412. if (atv != null && atv.longValue() > 0) {
  1413. SalesPromotion salesPromotion = salesPromotionService.getById(atv);
  1414. if (salesPromotion != null) {
  1415. od.setSalesName(salesPromotion.getSalesName());
  1416. // od.setSalesReduction(""+salesPromotion.getSalesReduction());
  1417. }
  1418. }
  1419. }
  1420. }
  1421. ExcelUtil<PosOrder> util = new ExcelUtil<PosOrder>(PosOrder.class);
  1422. util.exportExcel(response, list, MessageUtils.message("no.export.excel.posorder"));
  1423. }
  1424. /**
  1425. * 获取posorder详细信息
  1426. */
  1427. @PreAuthorize("@ss.hasPermi('system:order:query')")
  1428. @GetMapping(value = "/{id}")
  1429. public AjaxResult getInfo(@PathVariable("id") Long id) {
  1430. return success(posOrderService.selectPosOrderById(id));
  1431. }
  1432. @PreAuthorize("@ss.hasPermi('system:order:edit')")
  1433. @GetMapping("/{id}/status-context")
  1434. public AjaxResult getStatusContext(@PathVariable Long id) {
  1435. return success(orderLifecycleService.getStatusContext(id));
  1436. }
  1437. @PreAuthorize("@ss.hasPermi('system:order:linePaymentReconcile')")
  1438. @RepeatSubmit(interval = 2000, message = "查询过于频繁")
  1439. @PostMapping("/{id}/line-payment/reconcile")
  1440. public AjaxResult adminReconcileLinePayment(@PathVariable Long id) {
  1441. AdminOrderStatusContext context = orderLifecycleService.getStatusContext(id);
  1442. if (context.getLinePaymentId() == null) {
  1443. throw new ServiceException("LINE Pay 流水不存在");
  1444. }
  1445. String status = linePayService.reconcilePayment(context.getLinePaymentId(), "ADMIN");
  1446. Map<String, Object> data = new LinkedHashMap<>();
  1447. data.put("status", status);
  1448. data.put("context", orderLifecycleService.getStatusContext(id));
  1449. return success("LINE Pay 状态查询完成", data);
  1450. }
  1451. @PreAuthorize("@ss.hasPermi('system:order:lineRefund')")
  1452. @RepeatSubmit(interval = 2000, message = "请求过于频繁")
  1453. @PostMapping("/{id}/line-refund")
  1454. public AjaxResult adminRefundLinePayment(@PathVariable Long id) {
  1455. Long paymentId = orderLifecycleService.reserveLineRefund(id, "ADMIN");
  1456. String status = linePayRefundService.requestFullRefund(paymentId, "ADMIN");
  1457. Map<String, Object> data = new LinkedHashMap<>();
  1458. data.put("status", status);
  1459. data.put("context", orderLifecycleService.getStatusContext(id));
  1460. return success("LINE Pay 退款处理完成", data);
  1461. }
  1462. private String lineMessage(String key, String fallback) {
  1463. try {
  1464. return MessageUtils.message(key);
  1465. } catch (RuntimeException ignored) {
  1466. return fallback;
  1467. }
  1468. }
  1469. @PreAuthorize("@ss.hasPermi('system:order:edit')")
  1470. @RepeatSubmit(interval = 1000, message = "请求过于频繁")
  1471. @PutMapping("/{id}/status")
  1472. public AjaxResult adminUpdateStatus(@PathVariable Long id,
  1473. @Valid @RequestBody AdminOrderStatusUpdateRequest request) {
  1474. SysUser operator = currentAdmin();
  1475. return success("修改成功", orderLifecycleService.updateStatus(id, request,
  1476. operator == null ? null : operator.getUserId(), operatorName(operator)));
  1477. }
  1478. @PreAuthorize("@ss.hasPermi('system:order:edit')")
  1479. @RepeatSubmit(interval = 1000, message = "请求过于频繁")
  1480. @PostMapping("/{id}/offline-payment/confirm")
  1481. public AjaxResult adminConfirmOfflinePayment(@PathVariable Long id,
  1482. @Valid @RequestBody AdminOrderActionRequest request) {
  1483. SysUser operator = currentAdmin();
  1484. return success("已确认线下收款", orderLifecycleService.confirmOfflinePayment(id, request,
  1485. operator == null ? null : operator.getUserId(), operatorName(operator)));
  1486. }
  1487. @PreAuthorize("@ss.hasPermi('system:order:edit')")
  1488. @RepeatSubmit(interval = 1000, message = "请求过于频繁")
  1489. @PostMapping("/{id}/offline-refund/confirm")
  1490. public AjaxResult adminConfirmOfflineRefund(@PathVariable Long id,
  1491. @Valid @RequestBody AdminOrderActionRequest request) {
  1492. SysUser operator = currentAdmin();
  1493. return success("已确认线下退款", orderLifecycleService.confirmOfflineRefund(id, request,
  1494. operator == null ? null : operator.getUserId(), operatorName(operator)));
  1495. }
  1496. /**
  1497. * 新增posorder
  1498. */
  1499. @PreAuthorize("@ss.hasPermi('system:order:add')")
  1500. @Log(title = "posorder", businessType = BusinessType.INSERT)
  1501. @PostMapping
  1502. public AjaxResult add(@RequestBody PosOrder posOrder) {
  1503. return toAjax(posOrderService.insertPosOrder(posOrder));
  1504. }
  1505. /**
  1506. * 修改posorder
  1507. */
  1508. @Transactional(rollbackFor = Exception.class)
  1509. @PreAuthorize("@ss.hasPermi('system:order:edit')")
  1510. @Log(title = "posorder", businessType = BusinessType.UPDATE)
  1511. @PutMapping
  1512. public AjaxResult edit(@RequestBody PosOrder posOrder) {
  1513. if (posOrder == null || posOrder.getId() == null) {
  1514. return error("订单ID不能为空");
  1515. }
  1516. if (posOrder.getState() != null || posOrder.getDeliveryStatus() != null
  1517. || posOrder.getPayStatus() != null || posOrder.getAfterSaleStatus() != null
  1518. || posOrder.getSdTime() != null) {
  1519. return error("订单状态请使用状态专用操作");
  1520. }
  1521. return toAjax(posOrderService.updatePosOrder(posOrder));
  1522. }
  1523. private SysUser currentAdmin() {
  1524. return SecurityUtils.getLoginUser() == null ? null : SecurityUtils.getLoginUser().getUser();
  1525. }
  1526. private String operatorName(SysUser operator) {
  1527. return operator == null || operator.getNickName() == null ? "" : operator.getNickName();
  1528. }
  1529. /**
  1530. * 订单取消、退款成功返回积分
  1531. *
  1532. * @param userId
  1533. * @param ddId
  1534. * @param points
  1535. */
  1536. public void returnPoints(Long userId, Long ddId, Long points) {
  1537. LambdaQueryWrapper<UserWallet> walletQuery = new LambdaQueryWrapper<>();
  1538. walletQuery.eq(UserWallet::getUserId, userId);
  1539. walletQuery.isNull(UserWallet::getStoreId);
  1540. UserWallet userWallet = userWalletService.getOne(walletQuery);
  1541. PointsTransaction transaction = pointsTransactionService.getOne(new LambdaQueryWrapper<PointsTransaction>().eq(PointsTransaction::getDdId, ddId.toString()).eq(PointsTransaction::getType, "2"));
  1542. //该订单不存在退回的积分记录
  1543. if (ObjectUtil.isNotNull(userWallet) && transaction == null) {
  1544. walletQuery.eq(UserWallet::getVersion, userWallet.getVersion());
  1545. userWallet.setPointsWallet(userWallet.getPointsWallet() + points);
  1546. userWallet.setVersion(userWallet.getVersion() + 1);
  1547. boolean update = userWalletService.update(userWallet, walletQuery);
  1548. createPointTransaction(userId, Long.valueOf(points), userWallet.getPointsWallet(), ddId.toString(), "2");
  1549. if (!update) {
  1550. throw new ServiceException(MessageUtils.message("no.points.update.fail"));
  1551. }
  1552. } else {
  1553. throw new ServiceException(MessageUtils.message("no.points.insufficient"));
  1554. }
  1555. }
  1556. /**
  1557. * 删除posorder
  1558. */
  1559. @PreAuthorize("@ss.hasPermi('system:order:remove')")
  1560. @Log(title = "posorder", businessType = BusinessType.DELETE)
  1561. @DeleteMapping("/{ids}")
  1562. public AjaxResult remove(@PathVariable Long[] ids) {
  1563. return toAjax(posOrderService.deletePosOrderByIds(ids));
  1564. }
  1565. /**
  1566. * 测试推送消息
  1567. *
  1568. * @param cid
  1569. * @return
  1570. */
  1571. @Anonymous
  1572. @RequestMapping(value = "/testPushMessage", method = {RequestMethod.GET})
  1573. public AjaxResult testPushMessage(String cid, String title, String content, String body) {
  1574. PayPush push = new PayPush();
  1575. push.qspush(cid, title, content, body);
  1576. return AjaxResult.success();
  1577. }
  1578. /**
  1579. * 获取配送中的订单位置信息
  1580. */
  1581. @Anonymous
  1582. @Auth
  1583. @GetMapping("/getPsOrdersPosition")
  1584. public AjaxResult getPsOrdersPosition(@RequestHeader String token) {
  1585. JwtUtil jwtUtil = new JwtUtil();
  1586. String id = jwtUtil.getusid(token);
  1587. List<OrderPositionInfo> result = new ArrayList<>();
  1588. QueryWrapper<PosOrder> wrapper = new QueryWrapper<>();
  1589. wrapper.eq("user_id", id).apply("(pay_type!=1 and (state = 1 or state = 2 or state = 3 or state = 4) or (pay_type=1 and (state = 0 or state = 1 or state = 2 or state = 3 or state = 4)))").orderByDesc("cretim");
  1590. List<PosOrder> list = posOrderService.list(wrapper);
  1591. if (!list.isEmpty()) {
  1592. List<Long> qsIds = list.stream().map(PosOrder::getQsId).collect(Collectors.toList());
  1593. List<InfoUser> users = new ArrayList<>();
  1594. if (!qsIds.isEmpty()) {
  1595. LambdaQueryWrapper<InfoUser> userWrapper = new LambdaQueryWrapper<>();
  1596. userWrapper.in(InfoUser::getUserId, qsIds);
  1597. users = infoUserService.list(userWrapper);
  1598. }
  1599. List<Long> mdIds = list.stream().map(PosOrder::getMdId).collect(Collectors.toList());
  1600. LambdaQueryWrapper<PosStore> mdWrapper = new LambdaQueryWrapper<PosStore>().in(PosStore::getId, mdIds);
  1601. List<PosStore> stores = posStoreService.list(mdWrapper);
  1602. List<RiderPosition> riderPositions = new ArrayList<>();
  1603. if (!qsIds.isEmpty()) {
  1604. riderPositions = riderPositionService.list(new LambdaQueryWrapper<RiderPosition>().in(RiderPosition::getRiderId, qsIds));
  1605. }
  1606. for (PosOrder posOrder : list) {
  1607. OrderPositionInfo orderPositionInfo = new OrderPositionInfo();
  1608. orderPositionInfo.setDdId(posOrder.getDdId());
  1609. orderPositionInfo.setOrderState(posOrder.getState());
  1610. orderPositionInfo.setDelryTime(posOrder.getDelryTime());
  1611. orderPositionInfo.setYjsdTime(posOrder.getYjsdTime());
  1612. orderPositionInfo.setDiningStatus(posOrder.getDiningStatus());
  1613. orderPositionInfo.setPayType(posOrder.getPayType());
  1614. if (posOrder.getQsId() != null) {
  1615. QsDto qsDto = new QsDto();
  1616. users.stream().filter(infoUser -> infoUser.getUserId().equals(posOrder.getQsId())).findFirst().ifPresent(user -> {
  1617. qsDto.setUserName(user.getUserName());
  1618. qsDto.setNickName(user.getNickName());
  1619. });
  1620. qsDto.setDelryTime(posOrder.getDelryTime());
  1621. orderPositionInfo.setQsInfo(qsDto);
  1622. PositionDto qsPosition = new PositionDto();
  1623. riderPositions.stream().filter(riderPosition -> riderPosition.getRiderId().equals(posOrder.getQsId())).findFirst().ifPresent(rPosition -> {
  1624. qsPosition.setLat(rPosition.getLatitude().toString());
  1625. qsPosition.setLng(rPosition.getLongitude().toString());
  1626. });
  1627. orderPositionInfo.setQsPosition(qsPosition);
  1628. }
  1629. PositionDto mdPosition = new PositionDto();
  1630. stores.stream().filter(posStore -> posStore.getId().equals(Integer.valueOf(posOrder.getMdId().toString()))).findFirst().ifPresent(p -> {
  1631. mdPosition.setLat(p.getLatitude().toString());
  1632. mdPosition.setLng(p.getLongitude().toString());
  1633. });
  1634. orderPositionInfo.setMdPosition(mdPosition);
  1635. Map map = JSON.parseObject(posOrder.getShAddress(), Map.class);
  1636. PositionDto userPosition = new PositionDto();
  1637. userPosition.setLat(map.get("latitude").toString());
  1638. userPosition.setLng(map.get("longitude").toString());
  1639. orderPositionInfo.setUserPosition(userPosition);
  1640. result.add(orderPositionInfo);
  1641. }
  1642. }
  1643. return AjaxResult.success(result);
  1644. }
  1645. }