UserOrderController.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. package com.ruoyi.app.order;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  6. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  7. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  8. import com.ruoyi.app.order.dto.OrderCreateInput;
  9. import com.ruoyi.app.order.dto.OrderCreatItem;
  10. import com.ruoyi.app.order.dto.OrderPushBodyDto;
  11. import com.ruoyi.app.pay.LinePayRefundService;
  12. import com.ruoyi.app.utils.DateUtil;
  13. import com.ruoyi.app.utils.OperatingUtil;
  14. import com.ruoyi.app.utils.PayPush;
  15. import com.ruoyi.app.utils.event.PushEventService;
  16. import com.github.pagehelper.PageHelper;
  17. import com.ruoyi.common.annotation.Anonymous;
  18. import com.ruoyi.common.core.controller.BaseController;
  19. import com.ruoyi.common.core.domain.AjaxResult;
  20. import com.ruoyi.common.core.page.TableDataInfo;
  21. import com.ruoyi.common.exception.ServiceException;
  22. import com.ruoyi.common.utils.MessageUtils;
  23. import com.ruoyi.common.utils.StringUtils;
  24. import com.ruoyi.framework.manager.AsyncManager;
  25. import com.ruoyi.system.domain.*;
  26. import com.ruoyi.system.mapper.PosOrderPromotionMapper;
  27. import com.ruoyi.system.service.*;
  28. import com.ruoyi.system.utils.Auth;
  29. import com.ruoyi.system.utils.GetArea;
  30. import com.ruoyi.system.utils.JwtUtil;
  31. import com.ruoyi.system.utils.OrderLogHelper;
  32. import com.ruoyi.system.dto.PromotionCalcResponse;
  33. import com.ruoyi.system.domain.dto.ApplyInvoiceDto;
  34. import jakarta.validation.Valid;
  35. import org.springframework.web.bind.annotation.*;
  36. import org.springframework.beans.factory.annotation.Autowired;
  37. import org.springframework.transaction.annotation.Transactional;
  38. import java.text.SimpleDateFormat;
  39. import java.util.Date;
  40. import java.util.List;
  41. import java.util.Optional;
  42. import java.util.TimerTask;
  43. import java.util.stream.Collectors;
  44. /**
  45. * 用户订单Controller
  46. *
  47. * @author ruoyi
  48. * @date 2020-04-01
  49. */
  50. @RestController
  51. @RequestMapping("/system/userOrder")
  52. public class UserOrderController extends BaseController {
  53. @Autowired
  54. private IOrderParentService orderParentService;
  55. @Autowired
  56. private IPosOrderService posOrderService;
  57. @Autowired
  58. private IPosStoreService posStoreService;
  59. @Autowired
  60. private IInfoAddressService infoAddressService;
  61. @Autowired
  62. private IOperatingHoursService operatingHoursService;
  63. @Autowired
  64. private IUserFootprintService userFootprintService;
  65. @Autowired
  66. private IInfoUserService infoUserService;
  67. @Autowired
  68. private PushEventService pushEventService;
  69. @Autowired
  70. private OrderLogHelper orderLogHelper;
  71. @Autowired
  72. private OrderPromotionHelper orderPromotionHelper;
  73. @Autowired
  74. private PosOrderPromotionMapper posOrderPromotionMapper;
  75. @Autowired
  76. private OrderInvoiceService orderInvoiceService;
  77. @Autowired
  78. private IInfoInvoiceService infoInvoiceService;
  79. @Autowired
  80. private IPosOrderLinePaymentService linePaymentService;
  81. @Autowired
  82. private LinePayRefundService linePayRefundService;
  83. @Autowired
  84. private OrderLifecycleService orderLifecycleService;
  85. /**
  86. * 申请电子发票(订单完成后,客户主动申请:B2C 邮箱 / B2B 统编 / 载具)
  87. */
  88. @PostMapping("/applyInvoice")
  89. @Auth
  90. @Anonymous
  91. public AjaxResult applyInvoice(@RequestHeader String token, @RequestBody @Valid ApplyInvoiceDto dto) {
  92. Long userId = Long.valueOf(new JwtUtil().getusid(token));
  93. return AjaxResult.success(orderInvoiceService.applyInvoice(dto, userId));
  94. }
  95. /**
  96. * 查询订单电子发票(状态 / 发票号 / 凭证);门店不可开票时 invoiceStatus=null
  97. */
  98. @GetMapping("/getInvoice")
  99. @Auth
  100. @Anonymous
  101. public AjaxResult getInvoice(@RequestHeader String token, @RequestParam Long orderId) {
  102. Long userId = Long.valueOf(new JwtUtil().getusid(token));
  103. return AjaxResult.success(orderInvoiceService.getInvoice(orderId, userId));
  104. }
  105. /**
  106. * 捐赠机构列表(客户端选择器,仅 enabled=1,按机构名/简称/捐赠码搜索;分页)
  107. */
  108. @GetMapping("/loveOrg/list")
  109. @Auth
  110. @Anonymous
  111. public TableDataInfo loveOrgList(@RequestHeader String token,
  112. @RequestParam(defaultValue = "1") int pageNum,
  113. @RequestParam(defaultValue = "20") int pageSize,
  114. @RequestParam(required = false) String keyword) {
  115. PageHelper.startPage(pageNum, pageSize);
  116. return getDataTable(orderInvoiceService.listLoveOrg(keyword));
  117. }
  118. /**
  119. * 会员发票夹(010 Phase 11):我的发票列表,按 userId 查已开发票(不含码图)。
  120. */
  121. @GetMapping("/myInvoices")
  122. @Auth
  123. @Anonymous
  124. public TableDataInfo myInvoices(@RequestHeader String token,
  125. @RequestParam(defaultValue = "1") int pageNum,
  126. @RequestParam(defaultValue = "10") int pageSize) {
  127. Long userId = Long.valueOf(new JwtUtil().getusid(token));
  128. PageHelper.startPage(pageNum, pageSize);
  129. List<com.ruoyi.system.domain.vo.PosOrderInvoiceVo> list = orderInvoiceService.listMyInvoices(userId);
  130. return getDataTable(list);
  131. }
  132. /**
  133. * 创建订单
  134. */
  135. @PostMapping("/createOrder")
  136. @Auth
  137. @Anonymous
  138. @Transactional(rollbackFor = Exception.class)
  139. public AjaxResult createOrder(@RequestHeader String token, @RequestBody OrderCreateInput input)
  140. {
  141. JwtUtil jwtUtil = new JwtUtil();
  142. String id = jwtUtil.getusid(token);
  143. String shdz=null;
  144. if(input.getType()==0){
  145. InfoAddress usadd = infoAddressService.getById(input.getShdzId());
  146. if (usadd == null) {
  147. throw new ServiceException(MessageUtils.message("no.address.not.exist"));
  148. }
  149. shdz= JSON.toJSONString(usadd);
  150. }
  151. // === 发票意图(010 Phase 11)===
  152. // 校验:载具/捐赠/统编验真前置,不通过拦截下单(联网校验用第一个可开票门店的 ezPay 凭证)
  153. if (!StringUtils.isEmpty(input.getInvoiceChoice()) && !"PAPER".equals(input.getInvoiceChoice())) {
  154. Long invoiceStoreId = input.getItems() == null ? null : input.getItems().stream()
  155. .map(OrderCreatItem::getMdId)
  156. .filter(md -> orderInvoiceService.canInvoice(md))
  157. .findFirst().orElse(null);
  158. if (invoiceStoreId == null) {
  159. throw new ServiceException("所选门店暂不支持电子发票");
  160. }
  161. orderInvoiceService.validateCheckoutInvoiceIntent(input.getInvoiceChoice(), input.getCarrierNum(),
  162. input.getLoveCode(), input.getBuyerUbn(), input.getBuyerEmail(), invoiceStoreId);
  163. }
  164. createOrderParent(input,Long.valueOf(id),shdz);
  165. createOrderChild(input,Long.valueOf(id),Long.valueOf(id),shdz);
  166. // saveAsDefault:把载具/统编存为默认抬头(同一用户仅一条 is_default=1)
  167. if (Boolean.TRUE.equals(input.getSaveAsDefault()) && !StringUtils.isEmpty(input.getInvoiceChoice())) {
  168. saveDefaultInvoiceProfile(input, Long.valueOf(id));
  169. }
  170. OrderParent result = orderParentService.getOne(new LambdaQueryWrapper<OrderParent>().eq(OrderParent::getDdId, input.getDdId().toString()));
  171. System.out.println("创建返回信息:"+result);
  172. return super.success(result);
  173. }
  174. //创建父订单
  175. private void createOrderParent(OrderCreateInput input,Long UserId,String shdz){
  176. OrderParent orderParent = new OrderParent();
  177. orderParent.setUserId(UserId);
  178. orderParent.setOrderStatus(0L);
  179. orderParent.setTotalAmount(input.getTotalAmount());
  180. orderParent.setActualPayAmount(input.getActualPayAmount());
  181. orderParent.setPaymentMethod(input.getPaymentMethod());
  182. // orderParent.setPaymentTime(new Date());
  183. orderParent.setCreateTime(new Date());
  184. // orderParent.setUpdateTime(new Date());
  185. orderParent.setDdId(input.getDdId().toString());
  186. orderParent.setTableId(input.getTableId());
  187. orderParent.setShdzId(input.getShdzId());
  188. orderParent.setShAddress(shdz);
  189. orderParent.setType(input.getType());
  190. orderParent.setRemarks(input.getRemarks());
  191. orderParentService.save(orderParent);
  192. }
  193. //创建子订单
  194. private void createOrderChild(OrderCreateInput input,Long orderParentId,Long userId,String shdz){
  195. // 检查items是否为空
  196. if (input.getItems() == null || input.getItems().isEmpty()) {
  197. throw new ServiceException(MessageUtils.message("订单商品不能为空"));
  198. }
  199. String ddId = input.getDdId().toString();
  200. List<Long> mdIdList = input.getItems().stream().map(OrderCreatItem::getMdId).collect(Collectors.toList());
  201. // 将Long类型的门店ID转换为Integer类型用于查询(因为PosStore.getId()返回Integer)
  202. List<Integer> mdIdIntegerList = mdIdList.stream().map(Long::intValue).collect(Collectors.toList());
  203. List<PosStore> storeList = posStoreService.list(new LambdaQueryWrapper<PosStore>().in(PosStore::getId, mdIdIntegerList));
  204. LambdaQueryWrapper<OperatingHours> wrapper = new LambdaQueryWrapper<>();
  205. wrapper.in(OperatingHours::getMdId, mdIdList);
  206. List<OperatingHours> hourslist = operatingHoursService.list(wrapper);
  207. boolean isMultiStore = input.getItems().size() > 1;
  208. // 循环items,为每个item创建一条PosOrder
  209. int index = 0;
  210. for (OrderCreatItem item : input.getItems()) {
  211. // 检查门店是否开放
  212. checkStoreOpen(storeList,hourslist,item);
  213. index++;
  214. // 单店铺:子订单号与父订单一致;多店铺:子订单号追加序号
  215. String subddId = isMultiStore ? ddId + String.format("%03d", index) : ddId;
  216. PosOrder posOrder = new PosOrder();
  217. posOrder.setIsDisplay(false);
  218. handleIsDisplay(posOrder);
  219. posOrder.setShdzId(input.getShdzId());
  220. // 设置子订单的基本信息
  221. posOrder.setDdId(subddId);
  222. posOrder.setParentDdId(input.getDdId().toString()); // 设置父订单ID
  223. posOrder.setCretim(new Date());
  224. // 根据item设置订单信息
  225. posOrder.setShId(item.getShId());
  226. posOrder.setMdId(item.getMdId());
  227. posOrder.setShdzId(input.getShdzId());
  228. posOrder.setUserId(userId);
  229. posOrder.setAmount(item.getAmount());
  230. posOrder.setRemarks(item.getRemarks());
  231. posOrder.setType(item.getType());
  232. //外卖设置配送状态为
  233. if(0L==posOrder.getType()){
  234. posOrder.setDeliveryStatus(0L);
  235. }
  236. posOrder.setDelryTime(item.getDelryTime());
  237. posOrder.setFood(JSON.toJSONString(item.getFood()));
  238. if("1".equals(input.getPaymentMethod())){
  239. posOrder.setCollectPayment("1");
  240. }
  241. // 设置支付相关信息(从父订单继承)
  242. posOrder.setPayType(input.getPaymentMethod());
  243. //设置桌号(从父订单继承)
  244. posOrder.setTableId(input.getTableId());
  245. posOrder.setTableNo(input.getTableNo());
  246. posOrder.setLogo(item.getLogo());
  247. posOrder.setPosName(item.getPosName());
  248. posOrder.setJvli(item.getJvli());
  249. posOrder.setFreight(item.getFreight());
  250. posOrder.setShdzId(input.getShdzId());
  251. posOrder.setShAddress(shdz);
  252. posOrder.setFoodAmount(item.getFoodAmount());
  253. posOrder.setPickUpTime(input.getPickUpTime());
  254. posOrder.setReservePhone(input.getReservePhone());
  255. // 新状态字段初始化
  256. // 堂食订单(type=2)自动接单,跳过商家确认
  257. if (item.getType() != null && item.getType() == 2) {
  258. posOrder.setState(1L);
  259. } else {
  260. posOrder.setState(0L);
  261. }
  262. posOrder.setAfterSaleStatus(0L);
  263. posOrder.setDeliveryStatus(null);
  264. // 外送到付(payType=1):payStatus=1;其他:payStatus=0
  265. if (item.getType() != null && item.getType() == 0 && "1".equals(input.getPaymentMethod())) {
  266. posOrder.setPayStatus(1L);
  267. } else {
  268. posOrder.setPayStatus(0L);
  269. }
  270. Optional<PosStore> storeOptional = storeList.stream()
  271. .filter(x -> item.getMdId().equals(Long.valueOf(x.getId())))
  272. .findFirst();
  273. if (storeOptional.isEmpty()) {
  274. throw new ServiceException(MessageUtils.message("no.mendian.not.exist"));
  275. }
  276. PosStore store = storeOptional.get();
  277. posOrder.setLongitude(store.getLongitude());
  278. posOrder.setLatitude(store.getLatitude());
  279. //设置订单分类
  280. storeList.stream().filter(s -> Long.valueOf(s.getId()).equals(item.getMdId())).findFirst().ifPresent(st -> {
  281. posOrder.setOrderCategory(String.valueOf(st.getType()));
  282. });
  283. // 保存子订单
  284. // --- 促销:算价 + 校验 + 回填优惠字段(save之前) ---
  285. PromotionCalcResponse calc = orderPromotionHelper.calcPromotion(item, userId);
  286. orderPromotionHelper.validatePromotionAmount(calc, item.getPromoReduceAmount());
  287. orderPromotionHelper.fillPromotionFields(posOrder, calc);
  288. createFootprint(userId, item.getMdId());
  289. setPickUpNum(posOrder);
  290. posOrderService.save(posOrder);
  291. // 发票意图落 pos_order_invoice 意图行(010 Phase 11,方案B):仅开发票门店插,
  292. // issueTriggered=0 未触发;出餐 autoIssue 在该行落结果并置 issueTriggered=1
  293. if (!StringUtils.isEmpty(input.getInvoiceChoice()) && orderInvoiceService.canInvoice(item.getMdId())) {
  294. String choice = input.getInvoiceChoice();
  295. PosOrderInvoice intent = new PosOrderInvoice();
  296. intent.setOrderId(posOrder.getId());
  297. intent.setOrderNo(subddId);
  298. intent.setStoreId(item.getMdId());
  299. intent.setInvoiceChoice(choice);
  300. intent.setCarrierNum(input.getCarrierNum());
  301. intent.setBuyerUbn(input.getBuyerUbn());
  302. intent.setBuyerName(input.getBuyerName());
  303. intent.setBuyerEmail(input.getBuyerEmail());
  304. intent.setLoveCode(input.getLoveCode());
  305. if ("PHONE_BARCODE".equals(choice)) {
  306. intent.setCarrierType("0");
  307. } else if ("CITIZEN".equals(choice)) {
  308. intent.setCarrierType("1");
  309. } else if ("MEMBER".equals(choice)) {
  310. // 【决定 2026-08-05】会员载具走 PrintFlag=Y 纸本,不传 ezPay 电子载具(见 OrderInvoiceService.buildAutoIssueDto 决策备注);carrierType 留空
  311. } else {
  312. intent.setCarrierType(input.getCarrierType());
  313. }
  314. orderInvoiceService.captureInvoiceIntent(intent);
  315. }
  316. // --- 促销:写入快照 + 标记券已使用(save之后,需要posOrder.id) ---
  317. if (calc != null) {
  318. orderPromotionHelper.savePromotionSnapshots(posOrder.getId(), calc);
  319. if (calc.getCouponId() != null) {
  320. orderPromotionHelper.markCouponUsed(calc.getCouponId(), posOrder.getId(), userId);
  321. }
  322. }
  323. // 创建订单成功,添加操作日志
  324. InfoUser uUser = infoUserService.getOne(new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, userId));
  325. String uName = uUser != null ? uUser.getNickName() : "";
  326. orderLogHelper.log(subddId, 4, userId, uName, "用户" + uName + "创建订单");
  327. // 创建订单成功,给商家推送"您有新订单了"
  328. InfoUser shUser = infoUserService.getById(item.getShId());
  329. if (shUser != null && !StringUtils.isEmpty(shUser.getCid())) {
  330. PayPush push = new PayPush();
  331. String title = "no.message.push.message";
  332. String content = "no.message.push.new.order";
  333. String body = OrderPushBodyDto.getJson(subddId, String.valueOf(posOrder.getState()), 0);
  334. Long shUserId = shUser.getUserId();
  335. String cid = shUser.getCid();
  336. AsyncManager.me().execute(new TimerTask() {
  337. @Override
  338. public void run() {
  339. PayPush.shPushHandleLocal(push, pushEventService, shUserId, cid, title, content, body, "", subddId);
  340. }
  341. });
  342. }
  343. }
  344. }
  345. //保存默认发票抬头(010 Phase 11:结账勾「同意设置为默认」;同一用户仅一条 is_default=1)
  346. private void saveDefaultInvoiceProfile(OrderCreateInput input, Long userId) {
  347. String choice = input.getInvoiceChoice();
  348. if ("PAPER".equals(choice) || "LOVE_CODE".equals(choice) || "MEMBER".equals(choice)) {
  349. return; // 纸本/捐赠/会员载具不存抬头(会员载具=会员手机号,无需记忆)
  350. }
  351. InfoInvoice profile = new InfoInvoice();
  352. profile.setUserId(userId);
  353. profile.setIsDefault(1);
  354. switch (choice) {
  355. case "PHONE_BARCODE":
  356. profile.setCategory("B2C");
  357. profile.setTitleName("手机条码载具");
  358. profile.setBuyerName("手机条码载具");
  359. profile.setCarrierType("0");
  360. profile.setCarrierNum(input.getCarrierNum());
  361. break;
  362. case "CITIZEN":
  363. profile.setCategory("B2C");
  364. profile.setTitleName("自然人凭证载具");
  365. profile.setBuyerName("自然人凭证载具");
  366. profile.setCarrierType("1");
  367. profile.setCarrierNum(input.getCarrierNum());
  368. break;
  369. case "COMPANY":
  370. profile.setCategory("B2B");
  371. profile.setTitleName(input.getBuyerName());
  372. profile.setBuyerName(input.getBuyerName());
  373. profile.setBuyerUbn(input.getBuyerUbn());
  374. break;
  375. default:
  376. return;
  377. }
  378. // 先清掉该用户其它默认(同一用户仅一条为 1),再存新的
  379. InfoInvoice reset = new InfoInvoice();
  380. reset.setIsDefault(0);
  381. infoInvoiceService.update(reset, new LambdaQueryWrapper<InfoInvoice>()
  382. .eq(InfoInvoice::getUserId, userId)
  383. .eq(InfoInvoice::getIsDefault, 1));
  384. infoInvoiceService.save(profile);
  385. }
  386. //生成取餐码,根据门店id,当天取餐码从1开始累加
  387. private void setPickUpNum(PosOrder order) {
  388. if (order == null || order.getMdId() == null) {
  389. return;
  390. }
  391. try {
  392. // 获取当前日期,格式为 yyyy-MM-dd
  393. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  394. String today = dateFormat.format(new Date());
  395. // 查询当天该门店的最大取餐码
  396. LambdaQueryWrapper<PosOrder> queryWrapper = new LambdaQueryWrapper<>();
  397. queryWrapper.eq(PosOrder::getMdId, order.getMdId());
  398. queryWrapper.like(PosOrder::getCretim, today);
  399. queryWrapper.orderByDesc(PosOrder::getPickUpNum);
  400. queryWrapper.last("LIMIT 1");
  401. PosOrder lastOrder = posOrderService.getOne(queryWrapper);
  402. long nextNum = 1L;
  403. if (lastOrder != null && lastOrder.getPickUpNum() != null) {
  404. // 直接使用Long类型的取餐码
  405. nextNum = lastOrder.getPickUpNum() + 1;
  406. }
  407. // 生成新的取餐码:直接使用Long数字
  408. order.setPickUpNum(nextNum);
  409. logger.info("生成取餐码成功:门店ID={}, 取餐码={}", order.getMdId(), nextNum);
  410. } catch (Exception e) {
  411. logger.error("生成取餐码失败:门店ID={}, 错误信息={}", order.getMdId(), e.getMessage(), e);
  412. // 生成失败时使用时间戳作为备用方案
  413. Long fallbackPickUpNum = System.currentTimeMillis() % 10000;
  414. order.setPickUpNum(fallbackPickUpNum);
  415. }
  416. }
  417. //设置显示状态
  418. private void handleIsDisplay(PosOrder posOrder){
  419. if (StringUtils.isEmpty(posOrder.getDelryTime())) {
  420. posOrder.setIsDisplay(true);
  421. posOrder.setDisplayTime(new Date());
  422. }
  423. //预约单不在时间范围内不显示
  424. if (StringUtils.isNotEmpty(posOrder.getDelryTime())) {
  425. int minute = DateUtil.getAppoinmentOrderHandleTime();
  426. boolean isNear = DateUtil.isNearOrPastStartTime(posOrder.getDelryTime(), minute);
  427. if (isNear) {
  428. posOrder.setIsDisplay(true);
  429. posOrder.setDisplayTime(new Date());
  430. }
  431. }
  432. }
  433. private void createFootprint(Long uid,Long mdId){
  434. QueryWrapper<UserFootprint> Wrapper = new QueryWrapper<>();
  435. Wrapper.eq("user_id", uid);
  436. Wrapper.eq("md_id", mdId);
  437. UserFootprint foot = userFootprintService.getOne(Wrapper);
  438. DateUtil dateString = new DateUtil();
  439. if (foot == null) {
  440. UserFootprint usf = new UserFootprint();
  441. usf.setUserId(uid);
  442. usf.setMdId(mdId);
  443. usf.setCretim(dateString.GetDate());
  444. userFootprintService.saveOrUpdate(usf);
  445. } else {
  446. foot.setCretim(dateString.GetDate());
  447. userFootprintService.saveOrUpdate(foot);
  448. }
  449. }
  450. /**
  451. * 检查门店是否开放
  452. */
  453. private void checkStoreOpen( List<PosStore> storeList,List<OperatingHours> hourslist, OrderCreatItem item) {
  454. List<OperatingHours> storeHourslist = hourslist.stream().filter(x-> x.getMdId().equals(item.getMdId())).collect(Collectors.toList());
  455. PosStore store = storeList.stream()
  456. .filter(x -> Long.valueOf(x.getId()).equals(item.getMdId()))
  457. .findFirst()
  458. .orElseThrow(() -> new ServiceException(MessageUtils.message("no.mendian.not.exist")));
  459. if (storeHourslist.isEmpty()) {
  460. throw new ServiceException(store.getPosName()+MessageUtils.message("no.mendian.not.set.business.hours"));
  461. }
  462. if (store.getState() == 1) {
  463. throw new ServiceException(store.getPosName()+MessageUtils.message("no.mendian.is.closed"));
  464. }
  465. boolean isOperating = OperatingUtil.storeIsOperatingOfDay(storeHourslist);
  466. if (!isOperating) {
  467. throw new ServiceException(store.getPosName()+MessageUtils.message("no.mendian.is.closed"));
  468. }
  469. }
  470. /**
  471. * 获取父订单详情
  472. */
  473. @GetMapping("/getParentOrderDetail")
  474. @Auth
  475. @Anonymous
  476. public AjaxResult getParentOrderDetail(@RequestHeader String token, @RequestParam String ddId){
  477. OrderParent result = orderParentService.getOne(new LambdaQueryWrapper<OrderParent>().eq(OrderParent::getDdId,ddId));
  478. List<PosOrder> posOrders = posOrderService.list(new LambdaQueryWrapper<PosOrder>().eq(PosOrder::getParentDdId,ddId).orderBy(true,true,PosOrder::getCretim));
  479. result.setItems(posOrders);
  480. // 转为JSONObject以追加非实体字段(promotions)
  481. JSONObject org = JSON.parseObject(JSON.toJSONStringWithDateFormat(result, "yyyy-MM-dd HH:mm:ss"));
  482. JSONArray items = org.getJSONArray("items");
  483. if (items != null) {
  484. for (int i = 0; i < items.size(); i++) {
  485. JSONObject item = items.getJSONObject(i);
  486. Long orderId = item.getLong("id");
  487. List<PosOrderPromotion> promotions = posOrderPromotionMapper.selectByOrderId(orderId);
  488. item.put("promotions", promotions);
  489. }
  490. }
  491. return super.success(org);
  492. }
  493. /**
  494. * 计算两个经纬度之间的距离
  495. */
  496. @GetMapping("/getDistance")
  497. @Anonymous
  498. public AjaxResult getDistance(@RequestParam Double lat1, @RequestParam Double lng1,
  499. @RequestParam Double lat2, @RequestParam Double lng2) {
  500. double distance = GetArea.getDistance(lat1, lng1, lat2, lng2);
  501. return success(distance);
  502. }
  503. /**
  504. * 用户端订单列表(Tab分页)
  505. */
  506. @GetMapping("/orderList")
  507. @Auth
  508. @Anonymous
  509. public AjaxResult orderList(@RequestHeader String token,
  510. @RequestParam(defaultValue = "1") int page,
  511. @RequestParam(defaultValue = "10") int size,
  512. @RequestParam(required = false) String tab,
  513. @RequestParam(required = false) String type) {
  514. JwtUtil jwtUtil = new JwtUtil();
  515. String userId = jwtUtil.getusid(token);
  516. LambdaQueryWrapper<PosOrder> wrapper = new LambdaQueryWrapper<>();
  517. wrapper.eq(PosOrder::getUserId, Long.valueOf(userId));
  518. // 类型筛选
  519. if (type != null && !type.isEmpty()) {
  520. wrapper.eq(PosOrder::getType, Long.valueOf(type));
  521. }
  522. switch (tab) {
  523. case "unpaid":
  524. // 排除已取消(state=4)和售后中(afterSaleStatus>0)的订单
  525. wrapper.eq(PosOrder::getPayStatus, 0L).eq(PosOrder::getType, 0L).ne(PosOrder::getState, 4L).eq(PosOrder::getAfterSaleStatus, 0L);
  526. break;
  527. case "active":
  528. wrapper.in(PosOrder::getState, 0L, 1L, 2L)
  529. .eq(PosOrder::getAfterSaleStatus, 0L)
  530. .and(w -> w.eq(PosOrder::getPayStatus, 1L).or().in(PosOrder::getType, 1L, 2L));
  531. break;
  532. case "completed":
  533. wrapper.eq(PosOrder::getState, 3L).eq(PosOrder::getAfterSaleStatus, 0L);
  534. break;
  535. case "cancelled":
  536. wrapper.eq(PosOrder::getState, 4L).eq(PosOrder::getAfterSaleStatus, 0L);
  537. break;
  538. case "refund":
  539. wrapper.gt(PosOrder::getAfterSaleStatus, 0L);
  540. break;
  541. default:
  542. break;
  543. }
  544. wrapper.orderByDesc(PosOrder::getCretim);
  545. // 分页
  546. com.baomidou.mybatisplus.extension.plugins.pagination.Page<PosOrder> pageParam =
  547. new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);
  548. com.baomidou.mybatisplus.extension.plugins.pagination.Page<PosOrder> result = posOrderService.page(pageParam, wrapper);
  549. // 附加关联数据
  550. for (PosOrder order : result.getRecords()) {
  551. enrichOrderData(order);
  552. }
  553. java.util.Map<String, Object> data = new java.util.LinkedHashMap<>();
  554. data.put("records", result.getRecords());
  555. data.put("total", result.getTotal());
  556. data.put("page", page);
  557. data.put("size", size);
  558. return success(result);
  559. }
  560. private void enrichOrderData(PosOrder order) {
  561. try {
  562. if (order.getShId() != null) {
  563. InfoUser shanghu = infoUserService.getById(order.getShId());
  564. order.setPriceAll(shanghu != null ? String.valueOf(shanghu.getNickName()) : null);
  565. }
  566. } catch (Exception ignored) {}
  567. }
  568. /**
  569. * 确认取餐(自取类型订单,state=2 → state=3)
  570. */
  571. @Transactional(rollbackFor = Exception.class)
  572. @GetMapping("/confirmPickup")
  573. @Auth
  574. @Anonymous
  575. public AjaxResult confirmPickup(@RequestHeader String token, @RequestParam Long id) {
  576. JwtUtil jwtUtil = new JwtUtil();
  577. String userId = jwtUtil.getusid(token);
  578. PosOrder order = posOrderService.getOne(
  579. new LambdaQueryWrapper<PosOrder>()
  580. .eq(PosOrder::getId, id)
  581. .eq(PosOrder::getUserId, Long.valueOf(userId))
  582. );
  583. if (order == null) {
  584. return error("订单不存在");
  585. }
  586. if (order.getType() == null || order.getType() != 1) {
  587. return error("仅自取订单可确认取餐");
  588. }
  589. if (order.getState() == null || order.getState() != 2) {
  590. return error("当前订单状态不可确认取餐");
  591. }
  592. if (order.getPayStatus() == null || order.getPayStatus() != 1) {
  593. return error("订单未支付,不可确认取餐");
  594. }
  595. if (order.getAfterSaleStatus() != null && order.getAfterSaleStatus() > 0) {
  596. return error("订单存在售后处理中,不可确认取餐");
  597. }
  598. if (orderLifecycleService.isRealLineOrder(order)) {
  599. orderLifecycleService.completePaidLineOrder(order.getId());
  600. } else {
  601. order.setState(3L);
  602. posOrderService.updateById(order);
  603. }
  604. // 确认取餐成功,添加操作日志
  605. InfoUser uUser = infoUserService.getOne(new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, Long.valueOf(userId)));
  606. String uName = uUser != null ? uUser.getNickName() : "";
  607. orderLogHelper.log(String.valueOf(order.getDdId()), 4, Long.valueOf(userId), uName, "用户" + uName + "确认取餐");
  608. return success("确认取餐成功");
  609. }
  610. /**
  611. * 用户确认完成外送订单(骑手已送达后,state=2 → state=3)
  612. */
  613. @Transactional(rollbackFor = Exception.class)
  614. @GetMapping("/confirmDelivery")
  615. @Auth
  616. @Anonymous
  617. public AjaxResult confirmDelivery(@RequestHeader String token, @RequestParam Long id) {
  618. JwtUtil jwtUtil = new JwtUtil();
  619. String userId = jwtUtil.getusid(token);
  620. PosOrder order = posOrderService.getOne(
  621. new LambdaQueryWrapper<PosOrder>()
  622. .eq(PosOrder::getId, id)
  623. .eq(PosOrder::getUserId, Long.valueOf(userId))
  624. );
  625. if (order == null) {
  626. return error("订单不存在");
  627. }
  628. if (order.getState() == null || order.getState() != 2L) {
  629. return error("当前订单状态不可确认完成");
  630. }
  631. if (order.getDeliveryStatus() == null || order.getDeliveryStatus() != 3L) {
  632. return error("骑手尚未送达,不可确认完成");
  633. }
  634. if (order.getAfterSaleStatus() != null && order.getAfterSaleStatus() > 0) {
  635. return error("订单存在售后处理中,不可确认完成");
  636. }
  637. if (orderLifecycleService.isRealLineOrder(order)) {
  638. orderLifecycleService.completePaidLineOrder(order.getId());
  639. } else {
  640. PosOrder update = new PosOrder();
  641. update.setId(order.getId());
  642. update.setState(3L);
  643. posOrderService.updateById(update);
  644. }
  645. // 用户确认完成,添加操作日志
  646. InfoUser uUser = infoUserService.getOne(new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, Long.valueOf(userId)));
  647. String uName = uUser != null ? uUser.getNickName() : "";
  648. orderLogHelper.log(String.valueOf(order.getDdId()), 4, Long.valueOf(userId), uName, "用户" + uName + "确认完成订单");
  649. return success("确认完成成功");
  650. }
  651. /**
  652. * 取消订单(未接单前,state=0 → state=4)
  653. */
  654. @GetMapping("/cancelOrder")
  655. @Auth
  656. @Anonymous
  657. public AjaxResult cancelOrder(@RequestHeader String token, @RequestParam Long id) {
  658. JwtUtil jwtUtil = new JwtUtil();
  659. String userId = jwtUtil.getusid(token);
  660. PosOrder order = posOrderService.getOne(
  661. new LambdaQueryWrapper<PosOrder>()
  662. .eq(PosOrder::getId, id)
  663. .eq(PosOrder::getUserId, Long.valueOf(userId))
  664. );
  665. if (order == null) {
  666. return error("订单不存在");
  667. }
  668. if (order.getState() == null || order.getState() != 0) {
  669. return error("仅待处理状态的订单可取消");
  670. }
  671. PosOrder update = new PosOrder();
  672. update.setState(4L);
  673. boolean cancelled = posOrderService.update(update, new LambdaUpdateWrapper<PosOrder>()
  674. .eq(PosOrder::getId, order.getId())
  675. .eq(PosOrder::getState, 0L));
  676. if (!cancelled) {
  677. return error("订单状态已变化,请刷新后重试");
  678. }
  679. // 取消落库后按最新支付状态退款,避免旧订单对象覆盖退款状态或漏掉并发成功回调。
  680. PosOrder latest = posOrderService.getById(order.getId());
  681. if (latest != null && Long.valueOf(1L).equals(latest.getPayStatus())) {
  682. linePaymentService.getByDdId(String.valueOf(latest.getDdId())).stream()
  683. .filter(payment -> "PAID".equals(payment.getStatus()))
  684. .findFirst()
  685. .ifPresent(payment -> linePayRefundService
  686. .createRefundIntent(payment.getId(), "USER_CANCEL"));
  687. }
  688. // 取消订单成功,添加操作日志
  689. InfoUser uUser = infoUserService.getOne(new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, Long.valueOf(userId)));
  690. String uName = uUser != null ? uUser.getNickName() : "";
  691. orderLogHelper.log(String.valueOf(order.getDdId()), 4, Long.valueOf(userId), uName, "用户" + uName + "取消订单");
  692. return success("取消订单成功");
  693. }
  694. }