PosOrderController.java 87 KB

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