CmsOrderController.java 50 KB

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