CmsOrderDonServiceImpl.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. package com.cyksj.service.mange.impl;
  2. import cn.hutool.core.date.DateField;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.lang.Assert;
  6. import cn.hutool.core.util.StrUtil;
  7. import com.alipay.api.AlipayClient;
  8. import com.alipay.api.domain.AlipayTradeRefundModel;
  9. import com.alipay.api.request.AlipayTradeRefundRequest;
  10. import com.alipay.api.response.AlipayTradeRefundResponse;
  11. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  12. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  13. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  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.*;
  18. import com.cyksj.config.WeChatConfig;
  19. import com.cyksj.config.zfb.AliPayClientFactory;
  20. import com.cyksj.dto.RedisKey;
  21. import com.cyksj.mapper.*;
  22. import com.cyksj.mapper.channel.ShopConfigMapper;
  23. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  24. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  25. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  26. import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
  27. import com.cyksj.model.entity.*;
  28. import com.cyksj.model.excel.ExcelOrderDonInfo;
  29. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  30. import com.cyksj.model.request.ChangeRelationReq;
  31. import com.cyksj.model.request.ClickOutReq;
  32. import com.cyksj.model.request.OrderRefundReq;
  33. import com.cyksj.redis.RedisService;
  34. import com.cyksj.service.coupon.CouponFontService;
  35. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  36. import com.cyksj.service.mange.CmsOrderDonService;
  37. import com.cyksj.service.mange.stock.GoodsDonStockService;
  38. import com.cyksj.service.market.MarketFrontService;
  39. import com.cyksj.service.order.OrderCommonService;
  40. import com.cyksj.service.order.UserRealOrderBenefitsService;
  41. import com.cyksj.service.relation.GroupRelationClearService;
  42. import com.cyksj.service.template.TemplateCommonService;
  43. import com.cyksj.service.user.UserBenefitsService;
  44. import com.cyksj.service.wechat.WeChatService;
  45. import lombok.RequiredArgsConstructor;
  46. import lombok.extern.slf4j.Slf4j;
  47. import org.springframework.dao.DuplicateKeyException;
  48. import org.springframework.stereotype.Service;
  49. import org.springframework.transaction.annotation.Transactional;
  50. import java.math.BigDecimal;
  51. import java.math.RoundingMode;
  52. import java.util.Date;
  53. import java.util.List;
  54. import java.util.Map;
  55. import java.util.Optional;
  56. /**
  57. * @author chan
  58. * @date 2021/10/25 下午10:14
  59. */
  60. @Service
  61. @Slf4j
  62. @RequiredArgsConstructor
  63. public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
  64. private final OrderDonTransportMapper transportMapper;
  65. private final OrderDonWaybillMapper orderDonWaybillMapper;
  66. private final GoodsSkuStockRelateMapper skuStockRelateMapper;
  67. private final GoodsDonStockService goodsDonStockService;
  68. private final TemplateCommonService templateCommonService;
  69. private final GoodsDonSkuMapper goodsDonSkuMapper;
  70. private final UserRealOrderBenefitsService userRealOrderBenefitsService;
  71. private final UserRelationKickOutRecordMapper kickOutRecordMapper;
  72. private final CmsUserMapper cmsUserMapper;
  73. private final OrderCommonService orderCommonService;
  74. private final GoodsDonMapper goodsDonMapper;
  75. private final RedisService redisService;
  76. private final UserBenefitsService userBenefitsService;
  77. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  78. private final RefundOrderDonMapper refundOrderDonMapper;
  79. private final UserDistributeMapper userDistributeMapper;
  80. private final OrderDonMapper orderDonMapper;
  81. private final MarketFrontService marketFrontService;
  82. private final EquipmentDistributeService equipmentDistributeService;
  83. private final CouponFontService couponFontService;
  84. private final WeChatService weChatService;
  85. private final WeChatConfig weChatConfig;
  86. private final ShopConfigMapper shopConfigMapper;
  87. private final GroupRelationClearService relationClearService;
  88. private final GroupsRelationMapper relationMapper;
  89. private final GroupsMapper groupsMapper;
  90. private final GoodsDonSkuMapper skuMapper;
  91. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  92. @Override
  93. public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
  94. return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
  95. }
  96. @Override
  97. public OrderDonTransport getTransport(Long orderId) {
  98. return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
  99. }
  100. @Transactional(rollbackFor = Throwable.class)
  101. @Override
  102. public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
  103. OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
  104. orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
  105. orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
  106. orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
  107. orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
  108. OrderDon orderDon = getById(orderDonWaybill.getOrderId());
  109. if(orderDonWaybill.getId() == null){
  110. try {
  111. orderDonWaybillMapper.insert(orderDonWaybill);
  112. } catch (DuplicateKeyException e) {
  113. return orderDonWaybill;
  114. }
  115. orderDon.setStatus(OrderDon.Status.transport);
  116. updateById(orderDon);
  117. //发放实物购买权益
  118. Boolean isReceivedAll = true;
  119. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  120. if (sku != null) {
  121. if (sku.getIsBenefits()) {
  122. if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
  123. try {
  124. List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
  125. //自购实物 获取权益
  126. isReceivedAll = userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), goodsDonSkus);
  127. } catch (Exception e) {
  128. }
  129. }
  130. }
  131. }
  132. final Boolean flag = isReceivedAll;
  133. //库存扣减逻辑
  134. List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId,orderDon.getSkuId()));
  135. if(!relateList.isEmpty()){
  136. relateList.forEach((relate)->{
  137. goodsDonStockService.upStockRelate(relate.getStockId(),orderDon.getId(),"transport");
  138. });
  139. }
  140. //发送微信模板消息
  141. TASK_POOL.execute(()->{
  142. try {
  143. log.info("发送发货通知至{}用户", orderDon.getUserId());
  144. templateCommonService.sendTransportMsgNotify(orderDon, reqSetLogisticsPost, flag);
  145. } catch (Exception e) {
  146. log.error("发送发货通知至{}用户失败:{}", orderDon.getUserId(), e);
  147. }
  148. });
  149. }else {
  150. if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
  151. orderDon.setStatus(OrderDon.Status.transport);
  152. updateById(orderDon);
  153. }
  154. orderDonWaybillMapper.updateById(orderDonWaybill);
  155. }
  156. return orderDonWaybill;
  157. }
  158. @Override
  159. public void kickOutRelationId(long adminId, ClickOutReq req) {
  160. Long orderId = req.getOrderId();
  161. OrderDon orderDon = getById(orderId);
  162. if (orderDon != null && !orderDon.getIsKickOut()) {
  163. try {
  164. UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
  165. kickOutRecord.setUserId(orderDon.getUserId());
  166. kickOutRecord.setRelationId(orderDon.getRelationId());
  167. kickOutRecord.setGoodsId(orderDon.getGoodsId());
  168. kickOutRecord.setSkuId(orderDon.getSkuId());
  169. kickOutRecord.setReason(req.getReason());
  170. kickOutRecord.setImg(req.getImg());
  171. kickOutRecord.setRemark(req.getRemark());
  172. kickOutRecord.setOrderId(orderDon.getId());
  173. kickOutRecord.setOrderNo(orderDon.getOrderNo());
  174. Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
  175. kickOutRecordMapper.insert(kickOutRecord);
  176. orderDon.setIsKickOut(true);
  177. updateById(orderDon);
  178. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  179. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  180. //清除车票
  181. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku.getMonths());
  182. } catch (DuplicateKeyException e) {
  183. }
  184. }
  185. }
  186. @Override
  187. @Transactional(rollbackFor = Throwable.class)
  188. public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
  189. OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
  190. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  191. GoodsDon goodsDon = goodsDonMapper.selectById(sku.getGoodsId());
  192. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  193. refundReq.setRefundType("money");
  194. }
  195. String refundType = refundReq.getRefundType();
  196. //校验订单是否符合退款
  197. checkOrderRefund(orderDon, goodsDon, sku, 2, refundReq);
  198. OrderDon.Type type = orderDon.getType();
  199. String outNo = StrUtil.EMPTY;
  200. if (type == OrderDon.Type.WeChat && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  201. outNo = wxRefund(refundReq, orderDon);
  202. }
  203. if (type == OrderDon.Type.ALI_PAY && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  204. outNo = zfbRefund(refundReq, orderDon);
  205. }
  206. orderDon.setRefundDesc(refundReq.getRefundDesc());
  207. //记录退款信息
  208. commonRefund(orderDon, goodsDon, sku, outNo, refundType);
  209. //修改订单状态
  210. orderDon.setStatus(OrderDon.Status.refund);
  211. orderDonMapper.updateById(orderDon);
  212. }
  213. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  214. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  215. return StrUtil.EMPTY;
  216. }
  217. long time = System.currentTimeMillis();
  218. //退款订单号
  219. String outRefundNo = Codec.DoDigest.custom()
  220. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  221. .setStringData(time + String.valueOf(orderDon.getId()))
  222. .toHexString();
  223. weChatService.refundWxOrder(weChatConfig.getAppid(),
  224. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  225. orderDon.getTransactionId(),
  226. outRefundNo,
  227. orderDon.getMoney(),
  228. refundReq.getRefundMoney(),
  229. weChatConfig.getDomain() + "manage/order/wx/refund/notify");
  230. //记录退款信息
  231. return outRefundNo;
  232. }
  233. @Override
  234. public void wxRefundNotify(Map<String, String> map) throws Exception {
  235. // 对退款数据 解密
  236. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  237. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  238. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  239. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  240. // 退款失败
  241. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  242. throw BusinessRuntimeException.getInstance("退款异常.");
  243. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  244. throw BusinessRuntimeException.getInstance("退款关闭.");
  245. }
  246. /* 此处处理业务逻辑 */
  247. String outRefundNo = reqInfoMap.get("out_refund_no");
  248. String transactionId = reqInfoMap.get("transaction_id");
  249. String refundFee = reqInfoMap.get("refund_fee");
  250. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  251. if (orderDon == null) {
  252. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  253. return;
  254. }
  255. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  256. }
  257. @Override
  258. @Transactional(rollbackFor = Throwable.class)
  259. public void changeRelation(ChangeRelationReq req) {
  260. Long relationId = req.getRelationId();
  261. Long groupId = req.getGroupsId();
  262. UserTicketClearedRecord.Source source = req.getSource();
  263. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  264. GroupsRelation relation = relationMapper.selectById(relationId);
  265. Assert.notNull(relation, "车票已不存在");
  266. Long userId = relation.getUserId();
  267. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  268. .eq(OrderDon::getUserId, userId)
  269. .eq(OrderDon::getRelationId, relationId)
  270. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  271. .last("limit 1"));
  272. Assert.notNull(orderDon, "订单不存在");
  273. //获取新车队
  274. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  275. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  276. .eq(GroupsTrips::getId, groupId)
  277. .ne(GroupsTrips::getId, relation.getGroupsId())
  278. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  279. .last("limit 1");
  280. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  281. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  282. if (orderDon.getGoodsId() != 18 && groups.getAvailableNum() <= 0) {
  283. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  284. }
  285. //获取新车队车位
  286. GroupsRelation newRelation;
  287. if (orderDon.getGoodsId() == 18 && groups.getAvailableNum() == 0) {
  288. //GPT车队 额外增加车位 并不让上车
  289. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, 1);
  290. } else {
  291. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  292. }
  293. newRelation.setUserId(relation.getUserId());
  294. newRelation.setStartTime(relation.getStartTime());
  295. newRelation.setExpiryTime(relation.getExpiryTime());
  296. newRelation.setCustomerService(relation.getCustomerService());
  297. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  298. newRelation.setStatus(GroupsRelation.Status.validity);
  299. }
  300. //清除原先车票
  301. relation.setNewRelationId(newRelation.getId());
  302. relationClearService.clearTicket(relation, source);
  303. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  304. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  305. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  306. orderDonList.forEach(hasPaymentOrder -> {
  307. hasPaymentOrder.setRelationId(newRelation.getId());
  308. orderDonMapper.updateById(hasPaymentOrder);
  309. });
  310. relationMapper.updateById(newRelation);
  311. return;
  312. }
  313. orderDonList.forEach((hasPaymentOrder) -> {
  314. //如果续费增加时间,如果首次则设置当前时间为初始时间
  315. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  316. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  317. Date newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  318. newRelation.setExpiryTime(newDate);
  319. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  320. relationMapper.updateById(newRelation);
  321. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  322. hasPaymentOrder.setRelationId(newRelation.getId());
  323. orderDonMapper.updateById(hasPaymentOrder);
  324. });
  325. return;
  326. }
  327. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  328. orderDonList.forEach(completeOrder->{
  329. completeOrder.setRelationId(newRelation.getId());
  330. orderDonMapper.updateById(completeOrder);
  331. });
  332. redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + newRelation.getId());
  333. relationMapper.updateById(newRelation);
  334. }
  335. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  336. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  337. return StrUtil.EMPTY;
  338. }
  339. AlipayTradeRefundResponse response;
  340. //支付宝退款
  341. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  342. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  343. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  344. //支付宝交易号
  345. model.setTradeNo(orderDon.getTransactionId());
  346. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  347. model.setQueryOptions(List.of("gmt_refund_pay"));
  348. long time = System.currentTimeMillis();
  349. //退款订单号
  350. String outRefundNo = Codec.DoDigest.custom()
  351. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  352. .setStringData(time + String.valueOf(orderDon.getId()))
  353. .toHexString();
  354. //退款请求号
  355. model.setOutRequestNo(outRefundNo);
  356. request.setBizModel(model);
  357. String shopId = orderDon.getShopId();
  358. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  359. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  360. response = alipayClient.certificateExecute(request);
  361. } else {
  362. response = alipayClient.execute(request);
  363. }
  364. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  365. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  366. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  367. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  368. return outRefundNo;
  369. }
  370. /**
  371. * 校验订单是否符合退款操作
  372. */
  373. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, Integer orderPayType, OrderRefundReq refundReq) {
  374. if (orderDon == null) {
  375. throw BusinessRuntimeException.getInstance("订单不存在");
  376. }
  377. String refundType = refundReq.getRefundType();
  378. if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  379. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  380. }
  381. if (orderDon.getType() != OrderDon.Type.BALANCE && orderDon.getType() != OrderDon.Type.WeChat && orderPayType == 1) {
  382. throw BusinessRuntimeException.getInstance("该订单不是微信支付的订单");
  383. }
  384. if (orderDon.getType() != OrderDon.Type.BALANCE && orderDon.getType() != OrderDon.Type.ALI_PAY && orderPayType == 2) {
  385. throw BusinessRuntimeException.getInstance("该订单不是支付宝支付的订单");
  386. }
  387. if (OrderDon.Status.refund == orderDon.getStatus()) {
  388. throw BusinessRuntimeException.getInstance("该订单已退款");
  389. }
  390. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  391. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  392. }
  393. if (goodsDon.getType() == 1) {
  394. //虚拟原订单是否已过期
  395. Integer months = sku.getMonths();
  396. Integer num = orderDon.getNum();
  397. DateTime now = DateTime.now();
  398. DateTime endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  399. if (now.isAfter(endTime)) {
  400. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  401. }
  402. if (orderDon.getOrderType() == 1) {
  403. //是否有其他付款订单是否过期
  404. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  405. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  406. .eq(OrderDon::getUserId, orderDon.getUserId())
  407. .ne(OrderDon::getId, orderDon.getId())
  408. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  409. .eq(OrderDon::getOrderType, 2)
  410. .orderByDesc(OrderDon::getId)
  411. .last("limit 1"));
  412. if (otherOrder != null) {
  413. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  414. }
  415. }
  416. }
  417. BigDecimal refundMoney = refundReq.getRefundMoney();
  418. BigDecimal money = orderDon.getMoney();
  419. //余额退款
  420. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  421. BigDecimal balance = orderDon.getBalance();
  422. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  423. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  424. }
  425. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  426. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  427. }
  428. orderDon.setRefundBalance(refundMoney);
  429. orderDon.setRefundMoney(BigDecimal.ZERO);
  430. } else {
  431. //退金额
  432. if (refundMoney.compareTo(money) > 0) {
  433. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  434. }
  435. orderDon.setRefundMoney(refundMoney);
  436. }
  437. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  438. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  439. }
  440. }
  441. /**
  442. * 退款后 处理关联
  443. */
  444. public void commonRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType) {
  445. TASK_POOL.execute(() -> {
  446. refundRecord(orderDon, goodsDon, sku, outNo, refundType);
  447. //退款一次
  448. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  449. try {
  450. //虚物订单退款,清出车队,车票变为已过期
  451. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku.getMonths());
  452. } catch (Exception e) {
  453. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  454. }
  455. //若存在优惠券使用,退还优惠券
  456. if (orderDon.getCouponUserId() != 0) {
  457. couponFontService.updateOrderDonCouponStatus(orderDon);
  458. }
  459. //若存在余额支付,退还余额
  460. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  461. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance());
  462. }
  463. try {
  464. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  465. if (goodsDon.getType() == 2) {
  466. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  467. //扣除用户自身实物权益
  468. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  469. }
  470. } catch (Exception e) {
  471. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  472. }
  473. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  474. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  475. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance());
  476. //退款余额时,记录
  477. userBenefitsService.recordBalanceBySource(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.clear_valid);
  478. }
  479. } else {
  480. //余额退款不需要扣除积分
  481. //分销提成积分扣除
  482. deductDsPoints(orderDon);
  483. }
  484. });
  485. }
  486. /**
  487. * 退款 分销提成积分扣除
  488. */
  489. public void deductDsPoints(OrderDon orderDon) {
  490. if (orderDon.getIsDistribute()) {
  491. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  492. if (distributeWaitingSendPoints != null) {
  493. BigDecimal money = orderDon.getMoney();
  494. BigDecimal refundMoney = orderDon.getRefundMoney();
  495. //已发送 发送中 部分 全额退款
  496. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  497. BigDecimal points = distributeWaitingSendPoints.getPoints();
  498. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  499. if (refundMoney.compareTo(money) == 0) {
  500. //待发送状态 全额退款
  501. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  502. distributeWaitingSendPoints.setRefundPoints(points);
  503. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  504. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  505. return;
  506. }
  507. Integer thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  508. if (thisGoodsRate > 0) {
  509. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  510. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  511. //剩余积分
  512. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  513. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  514. }
  515. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  516. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  517. //扣除固定推广者积分
  518. if (refundMoney.compareTo(money) == 0) {
  519. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  520. distributeWaitingSendPoints.setRefundPoints(points);
  521. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  522. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  523. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  524. return;
  525. }
  526. Integer thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  527. if (thisGoodsRate > 0) {
  528. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  529. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  530. //部分退款
  531. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  532. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  533. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  534. }
  535. }
  536. }
  537. }
  538. }
  539. /**
  540. * 记录退款信息
  541. */
  542. private void refundRecord(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outRefundNo, String refundType) {
  543. RefundOrderDon refund = new RefundOrderDon();
  544. refund.setOrderId(orderDon.getId());
  545. refund.setOutRefundNo(outRefundNo);
  546. refund.setTotalFee(orderDon.getMoney());
  547. refund.setRefundDesc(orderDon.getRefundDesc());
  548. //退款金额
  549. refund.setRefundFee(orderDon.getRefundMoney());
  550. refund.setUserId(orderDon.getUserId());
  551. refund.setGoodsId(orderDon.getGoodsId());
  552. refund.setGoodsTitle(goodsDon == null ? null : goodsDon.getTitle());
  553. refund.setSkuId(orderDon.getSkuId());
  554. refund.setSpecVal(sku == null ? null : String.format("%s%s", sku.getSpecVal(), sku.getPrice().divide(BigDecimal.valueOf(100))));
  555. refund.setRefundMethod(orderDon.getType().name());
  556. refund.setGoodsType(goodsDon == null ? 0 : goodsDon.getType());
  557. //退款方式
  558. if (StrUtil.isNotBlank(refundType) && refundType.equals(OrderDon.Type.BALANCE.getType())) {
  559. refund.setRefundMethod(refundType);
  560. refund.setRefundFee(orderDon.getRefundBalance());
  561. }
  562. refundOrderDonMapper.insert(refund);
  563. }
  564. /**
  565. * 寻找该车队空余车位
  566. */
  567. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  568. //寻找快满编车队进行占座
  569. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  570. if (relation == null) {
  571. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  572. }
  573. Long relationId = relation.getId();
  574. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  575. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  576. retryNum++;
  577. getRelationThisTrips(userId, groupsId, retryNum);
  578. }
  579. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  580. if (count == 0) {
  581. log.error("车位异常 groupId:{}", groupsId);
  582. groupsMapper.updateAvailableNum(groupsId);
  583. throw new BusinessRuntimeException("车位异常");
  584. }
  585. return relation;
  586. }
  587. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer retryNum) {
  588. //寻找快满编车队额外座位
  589. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId);
  590. if (relation == null) {
  591. relation = new GroupsRelation();
  592. relation.setStatus(GroupsRelation.Status.outside);
  593. relation.setUserId(userId);
  594. relation.setGroupsId(groupsId);
  595. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  596. relation.setNum(maxNumRelation.getNum() + 1);
  597. relationMapper.insert(relation);
  598. return relation;
  599. }
  600. Long relationId = relation.getId();
  601. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  602. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  603. retryNum++;
  604. getChatGPTOutsideRelation(userId, groupsId, retryNum);
  605. }
  606. return relation;
  607. }
  608. }