CmsOrderController.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. package com.cyksj.web.controller.manage;
  2. import cn.dev33.satoken.annotation.SaCheckPermission;
  3. import cn.dev33.satoken.stp.StpUtil;
  4. import cn.hutool.core.collection.CollUtil;
  5. import cn.hutool.core.date.DateTime;
  6. import cn.hutool.core.date.DateUtil;
  7. import cn.hutool.core.util.ObjectUtil;
  8. import cn.hutool.core.util.StrUtil;
  9. import com.alibaba.excel.EasyExcel;
  10. import com.alibaba.excel.support.ExcelTypeEnum;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.cyksj.common.annotation.Log;
  13. import com.cyksj.common.annotation.NoSubmit;
  14. import com.cyksj.common.constant.Constant;
  15. import com.cyksj.common.exception.BusinessRuntimeException;
  16. import com.cyksj.common.util.IoKit;
  17. import com.cyksj.common.util.Xmls;
  18. import com.cyksj.dto.Result;
  19. import com.cyksj.enums.BusinessType;
  20. import com.cyksj.enums.GatewayApiCode;
  21. import com.cyksj.enums.GatewayResponse;
  22. import com.cyksj.mapper.*;
  23. import com.cyksj.mapper.channel.ChannelPopularizeMapper;
  24. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  25. import com.cyksj.mapper.channel.UserPayEquipmentReceiveBenefitsRecordMapper;
  26. import com.cyksj.mapper.manage.RealGoodsOrderHandleMapper;
  27. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  28. import com.cyksj.mapper.manage.coupon.CouponMapper;
  29. import com.cyksj.mapper.shop.YhShopMapper;
  30. import com.cyksj.model.dto.OriSkuDto;
  31. import com.cyksj.model.dto.RenewOriOrderSkuDto;
  32. import com.cyksj.model.entity.*;
  33. import com.cyksj.model.excel.*;
  34. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  35. import com.cyksj.model.manage.views.AccountView;
  36. import com.cyksj.model.manage.views.OrderDonBackView;
  37. import com.cyksj.model.manage.views.UpgradeOrderDonBackView;
  38. import com.cyksj.model.request.*;
  39. import com.cyksj.model.views.*;
  40. import com.cyksj.service.mange.CmsOrderDonService;
  41. import com.cyksj.service.order.OrderDonCommentService;
  42. import com.cyksj.service.user.UserBindRelationService;
  43. import com.cyksj.service.user.UserService;
  44. import com.cyksj.web.util.EasyExcelUtils;
  45. import com.ejlchina.searcher.BeanSearcher;
  46. import com.ejlchina.searcher.SearchResult;
  47. import com.ejlchina.searcher.param.Operator;
  48. import com.ejlchina.searcher.util.MapBuilder;
  49. import com.ejlchina.searcher.util.MapUtils;
  50. import lombok.RequiredArgsConstructor;
  51. import lombok.extern.slf4j.Slf4j;
  52. import org.apache.commons.lang3.StringUtils;
  53. import org.springframework.dao.DuplicateKeyException;
  54. import org.springframework.validation.annotation.Validated;
  55. import org.springframework.web.bind.annotation.*;
  56. import javax.servlet.http.HttpServletRequest;
  57. import javax.servlet.http.HttpServletResponse;
  58. import java.io.IOException;
  59. import java.io.OutputStream;
  60. import java.math.BigDecimal;
  61. import java.util.*;
  62. import java.util.stream.Collectors;
  63. /**
  64. * @author chan
  65. * @date 2021/10/12 下午11:05
  66. */
  67. @Slf4j
  68. @RequestMapping("/manage/order")
  69. @RestController
  70. @RequiredArgsConstructor
  71. public class CmsOrderController {
  72. private final HttpServletRequest request;
  73. private final CmsOrderDonService cmsOrderDonService;
  74. private final UserService userService;
  75. private final BeanSearcher beanSearcher;
  76. private final RealGoodsInterestUserMapper realGoodsInterestUserMapper;
  77. private final RealGoodsOrderHandleMapper realGoodsOrderHandleMapper;
  78. private final CouponMapper couponMapper;
  79. private final OrderCommentMapper orderCommentMapper;
  80. private final OrderDonCommentService orderDonCommentService;
  81. private final GoodsDonSkuMapper skuMapper;
  82. private final ChannelPopularizeMapper channelPopularizeMapper;
  83. private final GroupsRelationMapper relationMapper;
  84. private final UserPayEquipmentReceiveBenefitsRecordMapper receiveBenefitsRecordMapper;
  85. private final UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  86. private final YhShopMapper yhShopMapper;
  87. private final CmsUserMapper cmsUserMapper;
  88. private final UserMapper userMapper;
  89. private final OrderDonMapper orderDonMapper;
  90. private final OrderDonCustomerServiceRelateMapper orderDonCustomerServiceRelateMapper;
  91. private final MidjourneyUserConversationMapper midjourneyUserConversationMapper;
  92. private final MidjourneyUserMapper midjourneyUserMapper;
  93. private final UserBindRelationService userBindRelationService;
  94. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  95. @GetMapping("/get")
  96. @SaCheckPermission("order:view")
  97. public Result<SearchResult<OrderDonBackView>> get(Long channelId, String account, String showId, Long acId, String nickname, String register, Boolean isGoogle, Boolean isSubsidy) {
  98. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  99. if (channelId != null) {
  100. List<Long> popularizeIds = channelPopularizeMapper.getPopularizeIdByChannelId(channelId);
  101. builder.field(OrderDonBackView::getPopularizeId, popularizeIds).op(Operator.InList);
  102. }
  103. if (StrUtil.isNotBlank(account)) {
  104. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  105. .eq(GroupsRelation::getAccount, account).last("limit 1"));
  106. if (relation != null) {
  107. builder.field(OrderDonBackView::getRelationId, relation.getId());
  108. } else {
  109. builder.field(OrderDonBackView::getRelationId).op(Operator.IsNull);
  110. }
  111. }
  112. if (StrUtil.isNotBlank(showId)) {
  113. builder.field(OrderDonBackView::getUserId, userService.getUserIdByShowId(showId));
  114. }
  115. String conditionSql = StrUtil.EMPTY;
  116. if (acId != null) {
  117. conditionSql += String.format(" o.user_id in (select user_id from corp_user where ac_id = %s)", acId);
  118. }
  119. if (!ObjectUtil.isAllEmpty(nickname, register, isGoogle)) {
  120. if (StrUtil.isNotEmpty(conditionSql)) {
  121. conditionSql += " and ";
  122. }
  123. conditionSql += " exists (select u.id from user u where u.id = o.user_id";
  124. if (StrUtil.isNotEmpty(nickname)) {
  125. conditionSql += String.format(" and u.nickname like '%s%%'", nickname);
  126. }
  127. if (StrUtil.isNotEmpty(register)) {
  128. if ("phone".equals(register)) {
  129. conditionSql += " and u.login_phone != ''";
  130. } else if ("email".equals(register)) {
  131. conditionSql += " and u.email != ''";
  132. } else if ("wechat".equals(register)) {
  133. conditionSql += " and u.unionid != ''";
  134. }
  135. }
  136. if (isGoogle != null && isGoogle) {
  137. conditionSql += String.format(" and u.is_google is %s", isGoogle);
  138. }
  139. conditionSql += " limit 1)";
  140. }
  141. if (isSubsidy != null) {
  142. if (StrUtil.isNotEmpty(conditionSql)) {
  143. conditionSql += " and ";
  144. }
  145. conditionSql += " exists (select 1 from order_don_subsidy_relate ocr where ocr.order_id = o.id limit 1)";
  146. }
  147. if (StrUtil.isNotBlank(conditionSql)) {
  148. builder.put("condition", conditionSql);
  149. }
  150. SearchResult<OrderDonBackView> search = beanSearcher.search(OrderDonBackView.class, builder.build());
  151. search.getDataList().forEach(data -> {
  152. if (data.getPopularizeId() != null) {
  153. Optional.ofNullable(channelPopularizeMapper.selectChannelByPid(data.getPopularizeId()))
  154. .ifPresent(channelName -> data.setChannel(channelName));
  155. }
  156. if (data.getGoodsDonType() != null && Constant.realGoodsType.contains(data.getGoodsDonType())) {
  157. RealGoodsOrderHandle realGoodsOrderHandle = realGoodsOrderHandleMapper.selectOne(Wrappers.lambdaQuery(RealGoodsOrderHandle.class).eq(RealGoodsOrderHandle::getOrderId, data.getId()).last("limit 1"));
  158. if (realGoodsOrderHandle != null) {
  159. data.setBeforeServiceName(realGoodsOrderHandle.getBeforeServiceName());
  160. data.setAfterServiceName(realGoodsOrderHandle.getAfterServiceName());
  161. }
  162. }
  163. if (data.getCouponUserId() != 0) {
  164. data.setCouponName(couponMapper.getCouponNameByCouponUserId(data.getCouponUserId()));
  165. data.setCouponMoney(data.getCouponMoney() == null ? BigDecimal.ZERO : data.getCouponMoney());
  166. }
  167. if (data.getRelationId() != 0) {
  168. Optional.ofNullable(relationMapper.getGroupRelationAccountView(data.getRelationId()))
  169. .ifPresent(e -> {
  170. data.setGtAccount(e.getTripsAccount());
  171. data.setAccount(e.getAccount());
  172. });
  173. }
  174. if (data.getIsBenefits() != null && data.getIsBenefits() && !Constant.noOrderAllStatus.contains(data.getStatus())) {
  175. //是否实物权益已发放
  176. Integer count = receiveBenefitsRecordMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  177. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, data.getId()));
  178. if (count == 0) {
  179. count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  180. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, data.getId()));
  181. }
  182. data.setIsHasBenefits(count == 0 ? true : false);
  183. }
  184. if (data.getYhsId() != 0) {
  185. Optional.ofNullable(yhShopMapper.selectById(data.getYhsId()))
  186. .ifPresent(e -> {
  187. data.setShopName(e.getName());
  188. data.setCustomId(e.getCustomId());
  189. });
  190. }
  191. User user = userMapper.selectById(data.getUserId());
  192. if (user != null) {
  193. data.setNickname(user.getNickname());
  194. data.setLoginPhone(user.getLoginPhone());
  195. data.setEmail(user.getEmail());
  196. data.setRegister(StrUtil.isNotEmpty(user.getUnionid()) ? "wechat" : StrUtil.isNotEmpty(user.getLoginPhone()) ? "phone" : "email");
  197. }
  198. if (data.getGoodsDonType() != null && data.getGoodsDonType() == 1) {
  199. //获取订单关联客服
  200. Optional.ofNullable(orderDonMapper.selectOrderRelate(data.getId())).ifPresent(e -> {
  201. data.setCmsUserId(e.getCmsUserId());
  202. data.setNickname(e.getNickname());
  203. });
  204. }
  205. });
  206. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  207. }
  208. /**
  209. * 用户退款订单列表
  210. */
  211. @GetMapping("/get/refund/list")
  212. public Result<SearchResult<RefundOrderDonView>> getRefundOrderDonView() {
  213. SearchResult<RefundOrderDonView> search = beanSearcher.search(RefundOrderDonView.class, MapUtils.flatBuilder(request.getParameterMap())
  214. .build());
  215. search.getDataList().forEach(data -> {
  216. Optional.ofNullable(userService.getById(data.getUserId()))
  217. .ifPresent(user -> data.setNickname(user.getNickname()));
  218. });
  219. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  220. }
  221. /**
  222. * 镜像规格使用详情
  223. */
  224. @GetMapping("/get/order/mj/mirror/detail/{orderId}")
  225. public Result<MidjourneyUserDetailView> getMjMirrorOrderDetail(@PathVariable Long orderId) {
  226. OrderDon orderDon = orderDonMapper.selectById(orderId);
  227. //续费订单
  228. Date startTime = null;
  229. Date expiryTime = null;
  230. if (orderDon.getOrderType() == 2) {
  231. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  232. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  233. .eq(GroupsRelation::getId, orderDon.getRelationId())
  234. .eq(GroupsRelation::getUserId, orderDon.getUserId()).last("limit 1"));
  235. if (relation == null) {
  236. return GatewayResponse.SUCCESS.newBuilder().toResult();
  237. }
  238. startTime = relation.getStartTime();
  239. startTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  240. expiryTime = relation.getExpiryTime();
  241. }
  242. MidjourneyUserDetailView midjourneyUserDetailView = midjourneyUserConversationMapper.getMjMirrorOrderDetail(orderDon.getRelationId(), startTime, expiryTime);
  243. return GatewayResponse.SUCCESS.newBuilder().toResult(midjourneyUserDetailView);
  244. }
  245. /**
  246. * 订单导出
  247. */
  248. @GetMapping("/export")
  249. @SaCheckPermission("order:export")
  250. @Log(module = "订单管理/导出订单", businessType = BusinessType.EXPORT, isSaveRequestData = true)
  251. public void exportOrders(HttpServletResponse response) {
  252. List<ExcelOrderDonData> list = beanSearcher.searchAll(ExcelOrderDonData.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  253. list.forEach(data -> {
  254. data.setMoney(data.getMoney().divide(BigDecimal.valueOf(100)));
  255. OrderDon.Type type = data.getType();
  256. data.setTypeStr(type != null ? type.getDesc() : "");
  257. OrderDon.Status status = data.getStatus();
  258. data.setStatusStr(status != null ? status.getDesc() : "");
  259. if (data.getChannelId() == null) {
  260. data.setChannel("自然流量渠道");
  261. }
  262. if (data.getGoodsDonType() != null && Constant.realGoodsType.contains(data.getGoodsDonType())) {
  263. OrderDonTransportView transportView = beanSearcher.searchFirst(OrderDonTransportView.class, MapUtils.builder().field(OrderDonTransportView::getOrderId, data.getId()).build());
  264. if (transportView != null) {
  265. data.setTransportStr(String.format("%s%s%s%s", transportView.getProvince(), transportView.getCity(), transportView.getDistrict(), transportView.getAddress()));
  266. data.setPhone(transportView.getPhone());
  267. data.setReceiver(transportView.getReceiver());
  268. data.setCodeCn(transportView.getCodeCn());
  269. data.setTrackingNumber(transportView.getTrackingNumber());
  270. }
  271. RealGoodsOrderHandle realGoodsOrderHandle = realGoodsOrderHandleMapper.selectOne(Wrappers.lambdaQuery(RealGoodsOrderHandle.class).eq(RealGoodsOrderHandle::getOrderId, data.getId()).last("limit 1"));
  272. if (realGoodsOrderHandle != null) {
  273. data.setBeforeServiceName(realGoodsOrderHandle.getBeforeServiceName());
  274. data.setAfterServiceName(realGoodsOrderHandle.getAfterServiceName());
  275. }
  276. }
  277. if (data.getCouponUserId() != 0) {
  278. data.setCouponName(couponMapper.getCouponNameByCouponUserId(data.getCouponUserId()));
  279. data.setCouponMoney(data.getCouponMoney() == null ? BigDecimal.ZERO : data.getCouponMoney().divide(BigDecimal.valueOf(100)));
  280. }
  281. });
  282. EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelOrderDonData.class, list, "订单列表", "订单列表", ExcelTypeEnum.XLSX, null);
  283. }
  284. /**
  285. * 导出实物模板 订单excel
  286. */
  287. @GetMapping("/export/realGoods")
  288. public void exportRealGoods(HttpServletResponse response) throws IOException {
  289. List<ExcelRealGoodsOrderData> list = beanSearcher.searchAll(ExcelRealGoodsOrderData.class, MapUtils.flatBuilder(request.getParameterMap())
  290. .field(ExcelOrderDonData::getGoodsDonType, Constant.realGoodsType).op(Operator.InList)
  291. .build());
  292. // AtomicInteger index = new AtomicInteger(1);
  293. list.forEach(data -> {
  294. data.setPayType("寄付现结");
  295. if (data.getGoodsDonType() == Constant.realGoodsType.get(0)) {
  296. data.setRealGoodName("路由器");
  297. } else if (data.getGoodsDonType() == Constant.realGoodsType.get(1)) {
  298. data.setRealGoodName("银河潮玩");
  299. }
  300. // data.setIndex(index.getAndIncrement());
  301. });
  302. if (CollUtil.isEmpty(list)) {
  303. throw BusinessRuntimeException.getInstance("导出数据为空");
  304. }
  305. response.setContentType("application/x-download");
  306. response.setContentType("application/vnd.ms-excel");
  307. response.setCharacterEncoding("utf-8");
  308. response.setHeader("Content-disposition",
  309. "attachment;filename=" + new String("实物订单列表".getBytes("utf-8"), "ISO-8859-1") + ExcelTypeEnum.XLS.getValue());
  310. EasyExcel.write(response.getOutputStream())
  311. .head(ExcelRealGoodsOrderData.class)
  312. //设置合并单元格策略
  313. // .registerWriteHandler(new RealGoodsOrderLineStrategy())
  314. .excelType(ExcelTypeEnum.XLS)
  315. .sheet("实物订单列表")
  316. //设置头部标题从那行开始
  317. // .relativeHeadRowIndex(2)
  318. .doWrite(list);
  319. }
  320. @PutMapping("/update/status")
  321. public Result<String> upStatus(@RequestBody OrderDon orderDon){
  322. cmsOrderDonService.update(Wrappers.lambdaUpdate(OrderDon.class).eq(OrderDon::getId,orderDon.getId()).set(OrderDon::getStatus,orderDon.getStatus()));
  323. return GatewayResponse.SUCCESS.newBuilder().toResult();
  324. }
  325. /**
  326. * 编辑自定义订阅节点
  327. */
  328. @PutMapping("/update/subNode")
  329. public Result<String> updateSubNode(@RequestBody OrderDon orderDon) {
  330. OrderDon en = cmsOrderDonService.getById(orderDon.getId());
  331. if (en != null) {
  332. en.setSubNode(orderDon.getSubNode());
  333. cmsOrderDonService.updateById(en);
  334. }
  335. return GatewayResponse.SUCCESS.newBuilder().toResult();
  336. }
  337. @GetMapping("/get/transport/{orderId}")
  338. public Result<OrderDonTransportView> getTransport(@PathVariable Long orderId){
  339. // OrderDonTransport transport = cmsOrderDonService.getTransport(orderId);
  340. OrderDonTransportView transportView = beanSearcher.searchFirst(OrderDonTransportView.class, MapUtils.builder().field(OrderDonTransportView::getOrderId, orderId).build());
  341. return GatewayResponse.SUCCESS.newBuilder().toResult(transportView);
  342. }
  343. @PostMapping("/post/setWaybill")
  344. public Result<OrderDonWaybill> setWaybill(@RequestBody ReqSetLogisticsPost reqSetLogisticsPost){
  345. OrderDonWaybill orderDonWaybill = cmsOrderDonService.setWaybill(reqSetLogisticsPost);
  346. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonWaybill);
  347. }
  348. /**
  349. * 用户购买实物商品意愿列表
  350. */
  351. @GetMapping("/get/realGooods/interest/users")
  352. @SaCheckPermission("interest:view")
  353. public Result<SearchResult> getInterestUserList(RealGoodsInterestUser.Status interestStatus, HttpServletRequest request) {
  354. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  355. SearchResult<RealGoodsInterestUserView> search;
  356. if (interestStatus == null) {
  357. builder.field(RealGoodsInterestUserView::getInterestStatus, "hasPayment").op(Operator.NotEqual);
  358. search = beanSearcher.search(RealGoodsInterestUserView.class, builder.build());
  359. } else if (interestStatus != RealGoodsInterestUser.Status.hasPayment) {
  360. builder.field(RealGoodsInterestUserView::getInterestStatus, interestStatus.name());
  361. search = beanSearcher.search(RealGoodsInterestUserView.class, builder.build());
  362. } else {
  363. search = new SearchResult<>();
  364. SearchResult<RealGoodsInterestUserHasPaymentView> search2 = beanSearcher.search(RealGoodsInterestUserHasPaymentView.class, builder.build());
  365. search.setTotalCount(search2.getTotalCount());
  366. List<RealGoodsInterestUserView> dataList = search.getDataList();
  367. dataList.addAll(search2.getDataList());
  368. }
  369. search.getDataList().forEach(data -> {
  370. Long goodsId = data.getGoodsId();
  371. OrderDon order = cmsOrderDonService.getOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, data.getUserId()).eq(OrderDon::getGoodsId, goodsId).ne(OrderDon::getId, data.getId()).gt(OrderDon::getMoney, data.getMoney()).eq(OrderDon::getStatus, "close").last("limit 1"));
  372. if (order != null) {
  373. data.setOrderId(order.getId());
  374. data.setSkuId(order.getSkuId());
  375. data.setMoney(order.getMoney());
  376. realGoodsInterestUserMapper.updateData(data.getId(), data.getSkuId(), data.getOrderCreatedTime(), data.getOrderId());
  377. }
  378. });
  379. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  380. }
  381. /**
  382. * 修改订单状态
  383. */
  384. @PutMapping("/put/status/{orderId}")
  385. public Result<String> updateOrderStatus(@PathVariable Long orderId) {
  386. OrderDon orderDon = cmsOrderDonService.getById(orderId);
  387. if (orderDon == null) {
  388. throw BusinessRuntimeException.getInstance("该订单不存在");
  389. }
  390. if (orderDon.getStatus() == OrderDon.Status.complete) {
  391. throw BusinessRuntimeException.getInstance("该订单已是已完成状态");
  392. }
  393. if (orderDon.getStatus() != OrderDon.Status.hasPayment) {
  394. throw BusinessRuntimeException.getInstance("该订单不是未支付状态");
  395. }
  396. orderDon.setStatus(OrderDon.Status.complete);
  397. cmsOrderDonService.updateById(orderDon);
  398. return GatewayResponse.SUCCESS.newBuilder().toResult("修改订单状态成功");
  399. }
  400. /**
  401. * 修改购买意愿记录
  402. */
  403. @PutMapping("/put/interest")
  404. public Result<String> updateInterest(@RequestBody @Validated UserRealGoodsInterestReq req) {
  405. RealGoodsInterestUser realGoodsInterestUser = realGoodsInterestUserMapper.selectById(req.getId());
  406. if (realGoodsInterestUser != null) {
  407. if (req.getStatus() != null) {
  408. realGoodsInterestUser.setInterestStatus(req.getStatus());
  409. }
  410. if (req.getRemark() != null) {
  411. realGoodsInterestUser.setRemark(req.getRemark());
  412. }
  413. realGoodsInterestUserMapper.updateById(realGoodsInterestUser);
  414. }
  415. return GatewayResponse.SUCCESS.newBuilder().toResult("修改成功");
  416. }
  417. /**
  418. * 导出用户意愿列表
  419. */
  420. @GetMapping("/export/interest")
  421. public void exportInterest(RealGoodsInterestUser.Status interestStatus, HttpServletRequest request, HttpServletResponse response) {
  422. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  423. List<ExcelRealGoodsUserInterestData> excelRealGoodsUserInterestData;
  424. if (interestStatus == null) {
  425. builder.field(RealGoodsInterestUserView::getInterestStatus, "hasPayment").op(Operator.NotEqual);
  426. excelRealGoodsUserInterestData = beanSearcher.searchAll(ExcelRealGoodsUserInterestData.class, builder.build());
  427. } else {
  428. List<ExcelRealGoodsUserInterestHasPaymentData> excelRealGoodsUserInterestData2 = beanSearcher.searchAll(ExcelRealGoodsUserInterestHasPaymentData.class, builder.build());
  429. excelRealGoodsUserInterestData = new ArrayList<>(excelRealGoodsUserInterestData2);
  430. }
  431. excelRealGoodsUserInterestData.forEach(data -> {
  432. Long goodsId = data.getGoodsId();
  433. OrderDon order = cmsOrderDonService.getOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, data.getUserId()).eq(OrderDon::getGoodsId, goodsId).ne(OrderDon::getId, data.getId()).gt(OrderDon::getMoney, data.getMoney()).eq(OrderDon::getStatus, "close").last("limit 1"));
  434. if (order != null) {
  435. data.setOrderId(order.getId());
  436. data.setSkuId(order.getSkuId());
  437. data.setMoney(order.getMoney());
  438. realGoodsInterestUserMapper.updateData(data.getId(), data.getSkuId(), data.getOrderCreatedTime(), data.getOrderId());
  439. }
  440. data.setMoney(data.getMoney().divide(BigDecimal.valueOf(100)));
  441. });
  442. EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelRealGoodsUserInterestHasPaymentData.class, excelRealGoodsUserInterestData, "用户意愿列表", "用户意愿列表", ExcelTypeEnum.XLSX, null);
  443. }
  444. /**
  445. * 实物订单配置售前售后客户
  446. */
  447. @PostMapping("/put/realGoods/service")
  448. @NoSubmit
  449. @Log(module = "订单管理/售前、售后客服", businessType = BusinessType.PUT, isSaveRequestData = true)
  450. public Result<String> putRealGoodsService(@RequestBody @Validated RealGoodsServiceReq request) {
  451. OrderDon orderDon = cmsOrderDonService.getById(request.getOrderId());
  452. if (orderDon == null || orderDon.getRelationId() != 0) {
  453. throw BusinessRuntimeException.getInstance("该订单不是实物订单");
  454. }
  455. Boolean isBefore = false;
  456. Boolean isAfter = false;
  457. RealGoodsOrderHandle realGoodsOrderHandle = Optional.ofNullable(realGoodsOrderHandleMapper.selectOne(Wrappers.lambdaQuery(RealGoodsOrderHandle.class).eq(RealGoodsOrderHandle::getOrderId, request.getOrderId()).last("limit 1"))).orElse(new RealGoodsOrderHandle());
  458. if (StringUtils.isNotBlank(request.getBeforeServiceName())) {
  459. realGoodsOrderHandle.setBeforeServiceName(request.getBeforeServiceName());
  460. isBefore = true;
  461. }
  462. if (StringUtils.isNotBlank(request.getAfterServiceName())) {
  463. realGoodsOrderHandle.setAfterServiceName(request.getAfterServiceName());
  464. isAfter = true;
  465. }
  466. if (realGoodsOrderHandle.getId() == null) {
  467. realGoodsOrderHandle.setOrderId(request.getOrderId());
  468. realGoodsOrderHandleMapper.insert(realGoodsOrderHandle);
  469. } else {
  470. if (realGoodsOrderHandle.getBeforeOpNum() > 2) {
  471. throw BusinessRuntimeException.getInstance("售前客服已两次修改");
  472. }
  473. if (realGoodsOrderHandle.getAfterOpNum() > 2) {
  474. throw BusinessRuntimeException.getInstance("售后客服已两次修改");
  475. }
  476. if (isBefore) {
  477. realGoodsOrderHandle.setBeforeOpNum(realGoodsOrderHandle.getBeforeOpNum() + 1);
  478. }
  479. if (isAfter) {
  480. realGoodsOrderHandle.setAfterOpNum(realGoodsOrderHandle.getAfterOpNum() + 1);
  481. }
  482. realGoodsOrderHandleMapper.updateById(realGoodsOrderHandle);
  483. }
  484. return GatewayResponse.SUCCESS.newBuilder().toResult("操作成功");
  485. }
  486. /**
  487. * 新增平台评论
  488. */
  489. @PostMapping("/post/orderComment")
  490. public Result<String> insertOrderComment(@RequestBody @Validated OrderComment orderComment) {
  491. if (StrUtil.isEmpty(orderComment.getHeadImgUrl())) {
  492. orderComment.setHeadImgUrl(Constant.DEFAULT_HEAD_IMG);
  493. }
  494. if (orderComment.getCommentTime() == null) {
  495. orderComment.setCommentTime(DateTime.now().toDateStr());
  496. }
  497. orderComment.setVerifyStatus(OrderComment.VerifyStatus.success);
  498. orderCommentMapper.insert(orderComment);
  499. return GatewayResponse.SUCCESS.newBuilder().toResult("新增成功");
  500. }
  501. /**
  502. * 编辑平台评论
  503. */
  504. @PutMapping("/put/orderComment")
  505. public Result<String> updateOrderComment(@RequestBody @Validated OrderComment orderComment) {
  506. if (orderComment.getCommentTime() == null) {
  507. orderComment.setCommentTime(DateTime.now().toDateStr());
  508. }
  509. if (orderComment.getVerifyStatus() == null) {
  510. orderComment.setVerifyStatus(OrderComment.VerifyStatus.success);
  511. }
  512. orderCommentMapper.updateById(orderComment);
  513. return GatewayResponse.SUCCESS.newBuilder().toResult("编辑成功");
  514. }
  515. /**
  516. * 删除平台评论
  517. */
  518. @DeleteMapping("/delete/orderComment/{id}")
  519. public Result<String> deleteOrderCommentById(@PathVariable Long id) {
  520. orderCommentMapper.deleteById(id);
  521. return GatewayResponse.SUCCESS.newBuilder().toResult("删除成功");
  522. }
  523. /**
  524. * 平台评论列表
  525. */
  526. @GetMapping("/get/orderComment")
  527. public Result<SearchResult<OrderCommentView>> getOrderCommentView() {
  528. SearchResult<OrderCommentView> search = beanSearcher.search(OrderCommentView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  529. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  530. }
  531. /**
  532. * 评论审核
  533. */
  534. @PutMapping("/put/orderComment/status")
  535. @NoSubmit
  536. public Result<String> updateOrderCommentStatus(@RequestBody OrderComment orderCommentReq) throws Exception {
  537. orderDonCommentService.verifyCommentStatus(orderCommentReq.getId(), orderCommentReq.getVerifyStatus());
  538. return GatewayResponse.SUCCESS.newBuilder().toResult();
  539. }
  540. /**
  541. * 配置订单平台评价列表
  542. */
  543. @PostMapping("/post/orderComment/reward/config")
  544. public Result<String> saveOrUpdateOrderCommentConfig(@RequestBody List<OrderCommentRewardConfig> configs) {
  545. orderDonCommentService.saveOrUpdateOrderCommentConfig(configs);
  546. return GatewayResponse.SUCCESS.newBuilder().toResult();
  547. }
  548. /**
  549. * 获取配置 订单平台评价
  550. */
  551. @GetMapping("/get/orderComment/reward/config")
  552. public Result<List<OrderCommentRewardConfigView>> getOrderCommentRewardConfig() {
  553. List<OrderCommentRewardConfigView> views = beanSearcher.searchAll(OrderCommentRewardConfigView.class, MapUtils.builder()
  554. .orderBy(OrderCommentRewardConfigView::getGoodsId).desc()
  555. .build());
  556. return GatewayResponse.SUCCESS.newBuilder().toResult(views);
  557. }
  558. /**
  559. * 踢出车队
  560. */
  561. @PutMapping("/kickOut")
  562. @NoSubmit
  563. public Result<String> kickOut(@RequestBody @Validated ClickOutReq req) {
  564. long adminId = StpUtil.getLoginIdAsLong();
  565. cmsOrderDonService.kickOutRelationId(adminId, req);
  566. return GatewayResponse.SUCCESS.newBuilder().toResult();
  567. }
  568. /**
  569. * 踢出车队列表
  570. */
  571. @GetMapping("/get/kickOut/list")
  572. public Result<SearchResult<UserKickOutView>> getKickOutList() {
  573. SearchResult<UserKickOutView> search = beanSearcher.search(UserKickOutView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  574. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  575. }
  576. /**
  577. * 客服修改订单来源
  578. */
  579. @PutMapping("/update/order/source")
  580. public Result<String> updateOrderSource(@RequestBody OrderDon orderDon) {
  581. Long id = orderDon.getId();
  582. String labelSource = orderDon.getLabelSource();
  583. cmsOrderDonService.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  584. .set(OrderDon::getLabelSource, labelSource)
  585. .eq(OrderDon::getId, id));
  586. realGoodsOrderHandleMapper.update(null, Wrappers.lambdaUpdate(RealGoodsOrderHandle.class)
  587. .set(RealGoodsOrderHandle::getLabelSource, labelSource)
  588. .eq(RealGoodsOrderHandle::getOrderId, id));
  589. return GatewayResponse.SUCCESS.newBuilder().toResult();
  590. }
  591. /**
  592. * 设置实物订单电视机类型
  593. */
  594. @PutMapping("/update/order/tvType")
  595. public Result<String> updateOrderTvType(@RequestBody OrderDon orderDon) {
  596. Integer tvType = orderDon.getTvType();
  597. Long id = orderDon.getId();
  598. cmsOrderDonService.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  599. .set(OrderDon::getTvType, tvType)
  600. .eq(OrderDon::getId, id));
  601. return GatewayResponse.SUCCESS.newBuilder().toResult();
  602. }
  603. /**
  604. * 订单统一退款
  605. */
  606. @PostMapping("/unified/refund")
  607. @Log(module = "订单管理/统一退款", businessType = BusinessType.PUT, isSaveRequestData = true)
  608. public Result<String> unifiedRefund(@RequestBody @Validated OrderRefundReq refundReq) throws Exception {
  609. long adminId = StpUtil.getLoginIdAsLong();
  610. CmsUser cmsUser = cmsUserMapper.selectById(adminId);
  611. if (cmsUser == null) {
  612. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  613. }
  614. refundReq.setOperator(cmsUser.getNickname());
  615. cmsOrderDonService.unifiedRefund(refundReq);
  616. return GatewayResponse.SUCCESS.newBuilder().toResult("退款成功");
  617. }
  618. /**
  619. * 微信退款回调
  620. */
  621. @PostMapping("/wx/refund/notify")
  622. public void wxRefundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
  623. String xml = IoKit.toString(request.getInputStream());
  624. log.info("=== 退款成功的回调: \n {}", xml);
  625. // 解析xml
  626. Map<String, String> map = Xmls.toMap(xml);
  627. // 退款失败
  628. if (!StrUtil.equals("SUCCESS", map.get("return_code"))) {
  629. throw BusinessRuntimeException.getInstance("退款失败.");
  630. }
  631. cmsOrderDonService.wxRefundNotify(map);
  632. String toWechatXmlResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
  633. OutputStream out = null;
  634. try {
  635. out = response.getOutputStream();
  636. IoKit.write(toWechatXmlResponse, out);
  637. } catch (Throwable e) {
  638. throw BusinessRuntimeException.getInstance(e == null ? null : e.getMessage());
  639. } finally {
  640. IoKit.close(out);
  641. }
  642. }
  643. /**
  644. * 更换用户车票
  645. */
  646. @PutMapping("/put/sameSpec/empty/relation")
  647. @Log(module = "更换用户车票", businessType = BusinessType.PUT, isSaveRequestData = true)
  648. public Result<String> changeRelation(@RequestBody @Validated ChangeRelationReq req) throws Exception {
  649. cmsOrderDonService.changeRelation(req);
  650. return GatewayResponse.SUCCESS.newBuilder().toResult();
  651. }
  652. /**
  653. * 多余车位的空账号
  654. */
  655. @GetMapping("/get/sameSpec/empty/relation")
  656. public Result<SearchResult<EmptyGroupsRelationView>> getSameSpecEmptyRelation(Long skuId, Long groupsId, Long relationId, Boolean isNormal) {
  657. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap())
  658. .field(EmptyGroupsRelationView::getStatus, GroupsTrips.Status.down.name()).op(Operator.NotEqual)
  659. .field(EmptyGroupsRelationView::getSkuId, skuId).orderBy(EmptyGroupsRelationView::getAvailableNum)
  660. .desc();
  661. GoodsDonSku sku = skuMapper.selectById(skuId);
  662. Date expiryTime = null;
  663. if (relationId != null) {
  664. GroupsRelation relation = relationMapper.selectById(relationId);
  665. if (relation != null) expiryTime = relation.getExpiryTime();
  666. }
  667. if (groupsId != null) {
  668. builder.field(EmptyGroupsRelationView::getGroupsId, groupsId).op(Operator.NotEqual);
  669. }
  670. String condition = StrUtil.EMPTY;
  671. if (isNormal != null && isNormal) {
  672. condition += String.format("gt.account_id not in (select account_id from work_order where sku_id = %s and account_id is not null)", skuId);
  673. }
  674. if (StrUtil.isNotEmpty(condition)) {
  675. condition += " and ";
  676. }
  677. Integer maxNum = sku.getNum();
  678. Integer extraNum = 5;
  679. //GPT 4人月付
  680. if (sku.getId() == 178l) {
  681. extraNum = 2;
  682. }
  683. maxNum += extraNum;
  684. condition += String.format("(available_parking_num = 0 or available_parking_num > (select count(*) from groups_relation gr where gr.groups_id = gt.id and gr.user_id != 0 and gr.num <= %s))", maxNum);
  685. if (StrUtil.isNotEmpty(condition)) {
  686. builder.put("condition", condition);
  687. }
  688. if (expiryTime != null) {
  689. builder.field(AccountView::getExpiryTime, expiryTime).op(Operator.GreaterEqual);
  690. builder.orderBy(AccountView::getExpiryTime).asc();
  691. }
  692. if (sku.getNum() == 1 || !Constant.AI_goodsIds.contains(sku.getGoodsId())) {
  693. builder.field(EmptyGroupsRelationView::getAvailableNum, 0).op(Operator.GreaterThan);
  694. }
  695. SearchResult<EmptyGroupsRelationView> search = beanSearcher.search(EmptyGroupsRelationView.class,
  696. builder.build());
  697. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  698. }
  699. /**
  700. * 订单补差价,补差价退款到余额
  701. */
  702. @PutMapping("/refund/price/differ")
  703. @Log(module = "订单管理/订单补差价", businessType = BusinessType.PUT, isSaveRequestData = true)
  704. public Result<String> refundPriceDiffer(@RequestBody OrderRefundReq orderRefundReq) throws Exception {
  705. long adminId = StpUtil.getLoginIdAsLong();
  706. CmsUser cmsUser = cmsUserMapper.selectById(adminId);
  707. if (cmsUser == null) {
  708. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  709. }
  710. orderRefundReq.setOperator(cmsUser.getNickname());
  711. cmsOrderDonService.refundPriceDiffer(orderRefundReq);
  712. return GatewayResponse.SUCCESS.newBuilder().toResult();
  713. }
  714. /**
  715. * 将余额清零 退款用户支付金额
  716. */
  717. @PutMapping("/clear/balance/refundMoney")
  718. @NoSubmit
  719. public Result<String> clearBalanceToRefundMoney(@RequestBody @Validated OrderBalanceRefundReq refundReq) throws Exception {
  720. cmsOrderDonService.clearBalanceToRefundMoney(refundReq);
  721. return GatewayResponse.SUCCESS.newBuilder().toResult();
  722. }
  723. /**
  724. * 客服退款每月数据
  725. */
  726. @GetMapping("/get/refundOrder/data")
  727. public Result<SearchResult<RefundOrderDonServiceDataView>> getRefundOrderData(String startTime, String endTime, String operator) {
  728. String time = StrUtil.EMPTY;
  729. if (StrUtil.isNotBlank(startTime)) {
  730. time += String.format(" and o.created_time >= '%s'", startTime);
  731. }
  732. if (StrUtil.isNotBlank(endTime)) {
  733. time += String.format(" and o.created_time < '%s'", endTime);
  734. }
  735. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  736. if (StrUtil.isNotBlank(time)) {
  737. builder.put("time", time);
  738. }
  739. if (StrUtil.isEmpty(operator)) {
  740. List<CmsUserVO> userVOS = beanSearcher.searchAll(CmsUserVO.class, MapUtils.builder().field(CmsUserVO::getRoleNames, "客服").op(Operator.Contain).build());
  741. List<String> collect = userVOS.stream().map(CmsUserVO::getNickname).collect(Collectors.toList());
  742. if (CollUtil.isNotEmpty(collect)) {
  743. builder.field(RefundOrderDonServiceDataView::getOperator, collect).op(Operator.InList);
  744. }
  745. }
  746. SearchResult<RefundOrderDonServiceDataView> search = beanSearcher.search(RefundOrderDonServiceDataView.class, builder.build());
  747. search.getDataList().forEach(e->{
  748. String goodsName = orderDonMapper.selectMaxRefundGoodsName(e.getOperator(), startTime, endTime);
  749. e.setGoodsName(goodsName);
  750. });
  751. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  752. }
  753. /**
  754. * 设置订单客服
  755. */
  756. @PutMapping("/set/service")
  757. public Result<String> setOrderCustomerService(@RequestBody OrderDonCustomerServiceRelate relate) {
  758. OrderDonCustomerServiceRelate orderDonCustomerServiceRelate = orderDonCustomerServiceRelateMapper.selectOne(Wrappers.lambdaQuery(OrderDonCustomerServiceRelate.class)
  759. .eq(OrderDonCustomerServiceRelate::getOrderId, relate.getOrderId()).last("limit 1"));
  760. if (orderDonCustomerServiceRelate != null) {
  761. relate.setId(orderDonCustomerServiceRelate.getId());
  762. }
  763. try {
  764. if (relate.getId() == null) {
  765. orderDonCustomerServiceRelateMapper.insert(relate);
  766. } else {
  767. orderDonCustomerServiceRelateMapper.updateById(relate);
  768. }
  769. } catch (DuplicateKeyException e) {
  770. }
  771. return GatewayResponse.SUCCESS.newBuilder().toResult();
  772. }
  773. /**
  774. * 查询套餐订单列表
  775. */
  776. @GetMapping("/upgrade/get")
  777. @SaCheckPermission("upgradeOrder:view")
  778. public Result<SearchResult<UpgradeOrderDonBackView>> getUpgradeOrder(String account, String showId, Long acId, String nickname, String register, Boolean isGoogle) {
  779. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  780. if (StrUtil.isNotBlank(account)) {
  781. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  782. .eq(GroupsRelation::getAccount, account).last("limit 1"));
  783. if (relation != null) {
  784. builder.field(OrderDonBackView::getRelationId, relation.getId());
  785. } else {
  786. builder.field(OrderDonBackView::getRelationId).op(Operator.IsNull);
  787. }
  788. }
  789. if (StrUtil.isNotBlank(showId)) {
  790. builder.field(OrderDonBackView::getUserId, userService.getUserIdByShowId(showId));
  791. }
  792. String conditionSql = StrUtil.EMPTY;
  793. if (acId != null) {
  794. conditionSql += String.format(" o.user_id in (select user_id from corp_user where ac_id = %s)", acId);
  795. }
  796. if (!ObjectUtil.isAllEmpty(nickname, register, isGoogle)) {
  797. if (StrUtil.isNotEmpty(conditionSql)) {
  798. conditionSql += " and ";
  799. }
  800. conditionSql += " exists (select u.id from user u where u.id = o.user_id";
  801. if (StrUtil.isNotEmpty(nickname)) {
  802. conditionSql += String.format(" and u.nickname like '%s%%'", nickname);
  803. }
  804. if (StrUtil.isNotEmpty(register)) {
  805. if ("phone".equals(register)) {
  806. conditionSql += " and u.login_phone != ''";
  807. } else if ("email".equals(register)) {
  808. conditionSql += " and u.email != ''";
  809. } else if ("wechat".equals(register)) {
  810. conditionSql += " and u.unionid != ''";
  811. }
  812. }
  813. if (isGoogle != null && isGoogle) {
  814. conditionSql += String.format(" and u.is_google is %s", isGoogle);
  815. }
  816. conditionSql += " limit 1)";
  817. }
  818. if (StrUtil.isNotBlank(conditionSql)) {
  819. builder.put("condition", conditionSql);
  820. }
  821. SearchResult<UpgradeOrderDonBackView> search = beanSearcher.search(UpgradeOrderDonBackView.class, builder.build());
  822. search.getDataList().forEach(data -> {
  823. User user = userMapper.selectById(data.getUserId());
  824. if (user != null) {
  825. data.setNickname(user.getNickname());
  826. data.setLoginPhone(user.getLoginPhone());
  827. data.setEmail(user.getEmail());
  828. data.setRegister(StrUtil.isNotEmpty(user.getUnionid()) ? "wechat" : StrUtil.isNotEmpty(user.getLoginPhone()) ? "phone" : "email");
  829. }
  830. });
  831. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  832. }
  833. /**
  834. * 套餐退款订单列表
  835. */
  836. @GetMapping("/get/upgrade/refund/list")
  837. public Result<SearchResult<RefundUpdradeOrderDonView>> getRefundUpgradeOrderDonView(String nickname) {
  838. List<Long> userIds = null;
  839. if (StrUtil.isNotBlank(nickname)) {
  840. userIds = userMapper.selectListByNickname(nickname);
  841. if (CollUtil.isEmpty(userIds)) {
  842. userIds.add(0l);
  843. }
  844. }
  845. MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
  846. if (CollUtil.isNotEmpty(userIds)) {
  847. builder.field(RealGoodsInterestUserView::getUserId, userIds).op(Operator.InList);
  848. }
  849. SearchResult<RefundUpdradeOrderDonView> search = beanSearcher.search(RefundUpdradeOrderDonView.class,
  850. builder.build());
  851. search.getDataList().forEach(data -> {
  852. Optional.ofNullable(userService.getById(data.getUserId()))
  853. .ifPresent(user -> data.setNickname(user.getNickname()));
  854. });
  855. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  856. }
  857. /**
  858. * 套餐订单导出
  859. */
  860. @GetMapping("/upgrade/export")
  861. @SaCheckPermission("upgradeOrder:export")
  862. @Log(module = "套餐订单管理/导出订单", businessType = BusinessType.EXPORT, isSaveRequestData = true)
  863. public void exportUpgradeOrders(HttpServletResponse response) {
  864. List<ExcelUpgradeOrderDonData> list = beanSearcher.searchAll(ExcelUpgradeOrderDonData.class, MapUtils.flatBuilder(request.getParameterMap()).build());
  865. list.forEach(data -> {
  866. data.setMoney(data.getMoney().divide(BigDecimal.valueOf(100)));
  867. UpgradeOrderDon.Type type = data.getType();
  868. data.setTypeStr(type != null ? type.getDesc() : "");
  869. UpgradeOrderDon.Status status = data.getStatus();
  870. data.setStatusStr(status != null ? status.getDesc() : "");
  871. });
  872. EasyExcelUtils.createExcelStreamMutilByEasyExcel(response, ExcelUpgradeOrderDonData.class, list, "订单列表", "订单列表", ExcelTypeEnum.XLSX, null);
  873. }
  874. /**
  875. * 套餐订单统一退款
  876. */
  877. @PostMapping("/unified/upgrade/refund")
  878. @Log(module = "套餐订单管理/统一退款", businessType = BusinessType.PUT, isSaveRequestData = true)
  879. public Result<String> unifiedUpgradeRefund(@RequestBody @Validated OrderRefundReq refundReq) throws Exception {
  880. long adminId = StpUtil.getLoginIdAsLong();
  881. CmsUser cmsUser = cmsUserMapper.selectById(adminId);
  882. if (cmsUser == null) {
  883. throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
  884. }
  885. refundReq.setOperator(cmsUser.getNickname());
  886. cmsOrderDonService.unifiedUpgradeRefund(refundReq);
  887. return GatewayResponse.SUCCESS.newBuilder().toResult("退款成功");
  888. }
  889. /**
  890. * midjourney查询订单用户账号剩余次数
  891. */
  892. @GetMapping("/get/midjourney/user")
  893. public Result<MidjourneyUserDetailView> getMidjourneyUser(Long orderId) {
  894. OrderDon orderDon = orderDonMapper.selectById(orderId);
  895. //续费订单
  896. Date startTime = null;
  897. Date expiryTime = null;
  898. if (orderDon.getOrderType() == 2) {
  899. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  900. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
  901. .eq(GroupsRelation::getId, orderDon.getRelationId())
  902. .eq(GroupsRelation::getUserId, orderDon.getUserId()).last("limit 1"));
  903. if (relation == null) {
  904. return GatewayResponse.SUCCESS.newBuilder().toResult();
  905. }
  906. startTime = relation.getStartTime();
  907. startTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  908. expiryTime = relation.getExpiryTime();
  909. }
  910. MidjourneyUser midjourneyUser = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class)
  911. .eq(MidjourneyUser::getRelationId, orderDon.getRelationId())
  912. .last("limit 1"));
  913. if (midjourneyUser == null) {
  914. return GatewayResponse.SUCCESS.newBuilder().toResult();
  915. }
  916. MidjourneyUserDetailView midjourneyUserDetailView = midjourneyUserConversationMapper.getMjMirrorOrderDetail(orderDon.getRelationId(), startTime, expiryTime);
  917. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  918. midjourneyUserDetailView.setUserId(orderDon.getUserId());
  919. midjourneyUserDetailView.setExpiryTime(midjourneyUser.getExpireTime());
  920. midjourneyUserDetailView.setMjFastNum(sku.getMjFastNum() - midjourneyUserDetailView.getUseFastNum());
  921. if (sku.getMjRelaxNum() == null) {
  922. midjourneyUserDetailView.setMjRelaxNum(null);
  923. } else {
  924. midjourneyUserDetailView.setMjRelaxNum(sku.getMjRelaxNum() - midjourneyUserDetailView.getUseRelaxNum());
  925. }
  926. return GatewayResponse.SUCCESS.newBuilder().toResult(midjourneyUserDetailView);
  927. }
  928. /**
  929. * 用户退款详情
  930. */
  931. @GetMapping("/get/user/refund/detail")
  932. public Result<OrderDonUserRefundDetailView> getUserRefundDetail(Long userId) {
  933. if (userId == null || userId == 0) {
  934. return GatewayResponse.SUCCESS.newBuilder().toResult();
  935. }
  936. List<Long> userIdList = null;
  937. try {
  938. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  939. } catch (Exception e) {
  940. }
  941. String userIds = null;
  942. if (CollUtil.isNotEmpty(userIdList)) {
  943. userIds = userIdList.toString().replaceAll("\\[", "").replaceAll("]", "");
  944. }
  945. MapBuilder builder = MapUtils.builder();
  946. if (StrUtil.isNotBlank(userIds)) {
  947. builder.put("uid", String.format(" and user_id in (%s)", userIds));
  948. } else {
  949. builder.put("uid", String.format(" and user_id = %s", userId));
  950. }
  951. OrderDonUserRefundDetailView orderDonUserRefundDetailView = beanSearcher.searchFirst(OrderDonUserRefundDetailView.class, builder.build());
  952. return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonUserRefundDetailView);
  953. }
  954. /**
  955. * 用户订单列表
  956. */
  957. @GetMapping("/get/user/orders")
  958. public Result<SearchResult<OrderDonUserRefundDetailView.OrderDonDetailView>> getUserOrdersDetail(Long userId) {
  959. if (userId == null || userId == 0) {
  960. return GatewayResponse.SUCCESS.newBuilder().toResult();
  961. }
  962. List<Long> userIdList = null;
  963. try {
  964. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  965. } catch (Exception e) {
  966. }
  967. if (userIdList == null) {
  968. userIdList = new ArrayList<>();
  969. userIdList.add(userId);
  970. }
  971. SearchResult<OrderDonUserRefundDetailView.OrderDonDetailView> search = beanSearcher.search(OrderDonUserRefundDetailView.OrderDonDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
  972. .field(OrderDonUserRefundDetailView.OrderDonDetailView::getUserId, userIdList).op(Operator.InList)
  973. .build());
  974. return GatewayResponse.SUCCESS.newBuilder().toResult(search);
  975. }
  976. /**
  977. * 续费升级订单详情
  978. */
  979. @GetMapping("/renew/orders/detail")
  980. public Result<RenewOriOrderSkuDto> getRenewOrdersDetail(Long orderId) {
  981. OrderDon orderDon = orderDonMapper.selectById(orderId);
  982. if (orderDon.getOrderType() == 2) {
  983. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  984. .eq(OrderDonRenewRecord::getOrderId, orderDon.getId())
  985. .last("limit 1"));
  986. if (orderDonRenewRecord != null) {
  987. GroupsRelation relation = relationMapper.selectById(orderDon.getRelationId());
  988. GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
  989. Date expiryTime = relation.getExpiryTime();
  990. DateTime lastExpiryTIme = DateUtil.offsetMonth(expiryTime, -sku.getMonths());
  991. RenewOriOrderSkuDto renewOriOrderSkuDto = new RenewOriOrderSkuDto();
  992. OriSkuDto oriSku = skuMapper.selectRenewOriSku(orderDonRenewRecord.getOriSkuId());
  993. renewOriOrderSkuDto.setOriSku(oriSku);
  994. renewOriOrderSkuDto.setLastExpiryTime(lastExpiryTIme);
  995. return GatewayResponse.SUCCESS.newBuilder().toResult(renewOriOrderSkuDto);
  996. }
  997. }
  998. return GatewayResponse.SUCCESS.newBuilder().toResult();
  999. }
  1000. }